amqp_ssl_connect.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2007 - 2021, Alan Antonuk and the rabbitmq-c contributors.
  2. // SPDX-License-Identifier: mit
  3. #include <stdint.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <rabbitmq-c/amqp.h>
  8. #include <rabbitmq-c/ssl_socket.h>
  9. #include <assert.h>
  10. #ifdef _WIN32
  11. #ifndef WIN32_LEAN_AND_MEAN
  12. #define WIN32_LEAN_AND_MEAN
  13. #endif
  14. #include <Winsock2.h>
  15. #else
  16. #include <sys/time.h>
  17. #endif
  18. #include "utils.h"
  19. int main(int argc, char const *const *argv) {
  20. char const *hostname;
  21. int port;
  22. int timeout;
  23. amqp_socket_t *socket;
  24. amqp_connection_state_t conn;
  25. struct timeval tval;
  26. struct timeval *tv;
  27. if (argc < 3) {
  28. fprintf(stderr,
  29. "Usage: amqp_ssl_connect host port timeout_sec "
  30. "[cacert.pem [engine engine_ID] [verifypeer] [verifyhostname] "
  31. "[key.pem cert.pem]]\n");
  32. return 1;
  33. }
  34. hostname = argv[1];
  35. port = atoi(argv[2]);
  36. timeout = atoi(argv[3]);
  37. if (timeout > 0) {
  38. tv = &tval;
  39. tv->tv_sec = timeout;
  40. tv->tv_usec = 0;
  41. } else {
  42. tv = NULL;
  43. }
  44. conn = amqp_new_connection();
  45. socket = amqp_ssl_socket_new(conn);
  46. if (!socket) {
  47. die("creating SSL/TLS socket");
  48. }
  49. amqp_ssl_socket_set_verify_peer(socket, 0);
  50. amqp_ssl_socket_set_verify_hostname(socket, 0);
  51. if (argc > 5) {
  52. int nextarg = 5;
  53. die_on_error(amqp_ssl_socket_set_cacert(socket, argv[4]),
  54. "setting CA certificate");
  55. if (argc > nextarg && !strcmp("engine", argv[nextarg])) {
  56. amqp_set_ssl_engine(argv[++nextarg]);
  57. nextarg++;
  58. }
  59. if (argc > nextarg && !strcmp("verifypeer", argv[nextarg])) {
  60. amqp_ssl_socket_set_verify_peer(socket, 1);
  61. nextarg++;
  62. }
  63. if (argc > nextarg && !strcmp("verifyhostname", argv[nextarg])) {
  64. amqp_ssl_socket_set_verify_hostname(socket, 1);
  65. nextarg++;
  66. }
  67. if (argc > nextarg + 1) {
  68. die_on_error(
  69. amqp_ssl_socket_set_key(socket, argv[nextarg + 1], argv[nextarg]),
  70. "setting client key");
  71. }
  72. }
  73. die_on_error(amqp_socket_open_noblock(socket, hostname, port, tv),
  74. "opening SSL/TLS connection");
  75. die_on_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,
  76. "guest", "guest"),
  77. "Logging in");
  78. die_on_amqp_error(amqp_connection_close(conn, AMQP_REPLY_SUCCESS),
  79. "Closing connection");
  80. die_on_error(amqp_destroy_connection(conn), "Ending connection");
  81. die_on_error(amqp_uninitialize_ssl_library(), "Uninitializing SSL library");
  82. printf("Done\n");
  83. return 0;
  84. }