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