example-libevent-ssl.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. signal(SIGPIPE, SIG_IGN);
  32. struct event_base *base = event_base_new();
  33. if (argc < 5) {
  34. fprintf(stderr,
  35. "Usage: %s <key> <host> <port> <cert> <certKey> [ca]\n", argv[0]);
  36. exit(1);
  37. }
  38. const char *value = argv[1];
  39. size_t nvalue = strlen(value);
  40. const char *hostname = argv[2];
  41. int port = atoi(argv[3]);
  42. const char *cert = argv[4];
  43. const char *certKey = argv[5];
  44. const char *caCert = argc > 5 ? argv[6] : NULL;
  45. redisAsyncContext *c = redisAsyncConnect(hostname, port);
  46. if (c->err) {
  47. /* Let *c leak for now... */
  48. printf("Error: %s\n", c->errstr);
  49. return 1;
  50. }
  51. if (redisSecureConnection(&c->c, caCert, cert, certKey, "sni") != REDIS_OK) {
  52. printf("SSL Error!\n");
  53. exit(1);
  54. }
  55. redisLibeventAttach(c,base);
  56. redisAsyncSetConnectCallback(c,connectCallback);
  57. redisAsyncSetDisconnectCallback(c,disconnectCallback);
  58. redisAsyncCommand(c, NULL, NULL, "SET key %b", value, nvalue);
  59. redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
  60. event_base_dispatch(base);
  61. return 0;
  62. }