example-libevent-ssl.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <signal.h>
  5. #include <hiredis.h>
  6. #include <hiredis_ssl.h>
  7. #include <async.h>
  8. #include <adapters/libevent.h>
  9. void getCallback(redisAsyncContext *c, void *r, void *privdata) {
  10. redisReply *reply = r;
  11. if (reply == NULL) return;
  12. printf("argv[%s]: %s\n", (char*)privdata, reply->str);
  13. /* Disconnect after receiving the reply to GET */
  14. redisAsyncDisconnect(c);
  15. }
  16. void connectCallback(const redisAsyncContext *c, int status) {
  17. if (status != REDIS_OK) {
  18. printf("Error: %s\n", c->errstr);
  19. return;
  20. }
  21. printf("Connected...\n");
  22. }
  23. void disconnectCallback(const redisAsyncContext *c, int status) {
  24. if (status != REDIS_OK) {
  25. printf("Error: %s\n", c->errstr);
  26. return;
  27. }
  28. printf("Disconnected...\n");
  29. }
  30. int main (int argc, char **argv) {
  31. #ifndef _WIN32
  32. signal(SIGPIPE, SIG_IGN);
  33. #endif
  34. struct event_base *base = event_base_new();
  35. if (argc < 5) {
  36. fprintf(stderr,
  37. "Usage: %s <key> <host> <port> <cert> <certKey> [ca]\n", argv[0]);
  38. exit(1);
  39. }
  40. const char *value = argv[1];
  41. size_t nvalue = strlen(value);
  42. const char *hostname = argv[2];
  43. int port = atoi(argv[3]);
  44. const char *cert = argv[4];
  45. const char *certKey = argv[5];
  46. const char *caCert = argc > 5 ? argv[6] : NULL;
  47. redisSSLContext *ssl;
  48. redisSSLContextError ssl_error;
  49. redisInitOpenSSL();
  50. ssl = redisCreateSSLContext(caCert, NULL,
  51. cert, certKey, NULL, &ssl_error);
  52. if (!ssl) {
  53. printf("Error: %s\n", redisSSLContextGetError(ssl_error));
  54. return 1;
  55. }
  56. redisAsyncContext *c = redisAsyncConnect(hostname, port);
  57. if (c->err) {
  58. /* Let *c leak for now... */
  59. printf("Error: %s\n", c->errstr);
  60. return 1;
  61. }
  62. if (redisInitiateSSLWithContext(&c->c, ssl) != REDIS_OK) {
  63. printf("SSL Error!\n");
  64. exit(1);
  65. }
  66. redisLibeventAttach(c,base);
  67. redisAsyncSetConnectCallback(c,connectCallback);
  68. redisAsyncSetDisconnectCallback(c,disconnectCallback);
  69. redisAsyncCommand(c, NULL, NULL, "SET key %b", value, nvalue);
  70. redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
  71. event_base_dispatch(base);
  72. redisFreeSSLContext(ssl);
  73. return 0;
  74. }