1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
12 #include "lf_functions.h"
14 #include <hiredis/hiredis.h>
17 # define nele(arr) (sizeof(arr) / sizeof(*arr))
20 /* Structure and anchor for caching connections. */
21 typedef struct redis_connection
{
22 struct redis_connection
*next
;
27 static redis_connection
*redis_connections
= NULL
;
31 redis_open(uschar
*filename
, uschar
**errmsg
)
42 /* XXX: Not sure how often this is called!
43 Guess its called after every lookup which probably would mean to just
44 not use the _tidy() function at all and leave with exim exiting to
47 while ((cn
= redis_connections
))
49 redis_connections
= cn
->next
;
50 DEBUG(D_lookup
) debug_printf("close REDIS connection: %s\n", cn
->server
);
51 redisFree(cn
->handle
);
56 /* This function is called from the find entry point to do the search for a
60 query the query string
61 server the server string
62 resultptr where to store the result
63 errmsg where to point an error message
64 defer_break TRUE if no more servers are to be tried after DEFER
65 do_cache set false if data is changed
67 The server string is of the form "host/dbnumber/password". The host can be
68 host:port. This string is in a nextinlist temporary buffer, so can be
71 Returns: OK, FAIL, or DEFER
75 perform_redis_search(const uschar
*command
, uschar
*server
, uschar
**resultptr
,
76 uschar
**errmsg
, BOOL
*defer_break
, uint
*do_cache
)
78 redisContext
*redis_handle
= NULL
; /* Keep compilers happy */
79 redisReply
*redis_reply
= NULL
;
80 redisReply
*entry
= NULL
;
81 redisReply
*tentry
= NULL
;
85 gstring
* result
= NULL
;
86 uschar
*server_copy
= NULL
;
89 /* Disaggregate the parameters from the server argument.
90 The order is host:port(socket)
91 We can write to the string, since it is in a nextinlist temporary buffer.
92 This copy is also used for debugging output. */
94 memset(sdata
, 0, sizeof(sdata
)) /* Set all to NULL */;
95 for (i
= 2; i
> 0; i
--)
97 uschar
*pp
= Ustrrchr(server
, '/');
101 *errmsg
= string_sprintf("incomplete Redis server data: %s",
102 i
== 2 ? server
: server_copy
);
108 if (i
== 2) server_copy
= string_copy(server
); /* sans password */
110 sdata
[0] = server
; /* What's left at the start */
112 /* If the database or password is an empty string, set it NULL */
113 if (sdata
[1][0] == 0) sdata
[1] = NULL
;
114 if (sdata
[2][0] == 0) sdata
[2] = NULL
;
116 /* See if we have a cached connection to the server */
118 for (cn
= redis_connections
; cn
; cn
= cn
->next
)
119 if (Ustrcmp(cn
->server
, server_copy
) == 0)
121 redis_handle
= cn
->handle
;
128 uschar
*socket
= NULL
;
130 /* int redis_err = REDIS_OK; */
132 if ((p
= Ustrchr(sdata
[0], '(')))
136 while (*p
!= 0 && *p
!= ')') p
++;
140 if ((p
= Ustrchr(sdata
[0], ':')))
146 port
= Uatoi("6379");
148 if (Ustrchr(server
, '/'))
150 *errmsg
= string_sprintf("unexpected slash in Redis server hostname: %s",
157 debug_printf("REDIS new connection: host=%s port=%d socket=%s database=%s\n",
158 sdata
[0], port
, socket
, sdata
[1]);
160 /* Get store for a new handle, initialize it, and connect to the server */
161 /* XXX: Use timeouts ? */
163 socket
? redisConnectUnix(CCS socket
) : redisConnect(CCS server
, port
);
166 *errmsg
= string_sprintf("REDIS connection failed");
167 *defer_break
= FALSE
;
171 /* Add the connection to the cache */
172 cn
= store_get(sizeof(redis_connection
));
173 cn
->server
= server_copy
;
174 cn
->handle
= redis_handle
;
175 cn
->next
= redis_connections
;
176 redis_connections
= cn
;
181 debug_printf("REDIS using cached connection for %s\n", server_copy
);
184 /* Authenticate if there is a password */
186 if (!(redis_reply
= redisCommand(redis_handle
, "AUTH %s", sdata
[2])))
188 *errmsg
= string_sprintf("REDIS Authentication failed: %s\n", redis_handle
->errstr
);
189 *defer_break
= FALSE
;
193 /* Select the database if there is a dbnumber passed */
196 if (!(redis_reply
= redisCommand(redis_handle
, "SELECT %s", sdata
[1])))
198 *errmsg
= string_sprintf("REDIS: Selecting database=%s failed: %s\n", sdata
[1], redis_handle
->errstr
);
199 *defer_break
= FALSE
;
202 DEBUG(D_lookup
) debug_printf("REDIS: Selecting database=%s\n", sdata
[1]);
205 /* split string on whitespace into argv */
209 const uschar
* s
= command
;
213 while (isspace(*s
)) s
++;
215 for (i
= 0; *s
&& i
< nele(argv
); i
++)
219 for (g
= NULL
; (c
= *s
) && !isspace(c
); s
++)
220 if (c
!= '\\' || *++s
) /* backslash protects next char */
221 g
= string_catn(g
, s
, 1);
222 argv
[i
] = string_from_gstring(g
);
224 DEBUG(D_lookup
) debug_printf("REDIS: argv[%d] '%s'\n", i
, argv
[i
]);
225 while (isspace(*s
)) s
++;
228 /* Run the command. We use the argv form rather than plain as that parses
229 into args by whitespace yet has no escaping mechanism. */
231 redis_reply
= redisCommandArgv(redis_handle
, i
, (const char **) argv
, NULL
);
234 *errmsg
= string_sprintf("REDIS: query failed: %s\n", redis_handle
->errstr
);
235 *defer_break
= FALSE
;
240 switch (redis_reply
->type
)
242 case REDIS_REPLY_ERROR
:
243 *errmsg
= string_sprintf("REDIS: lookup result failed: %s\n", redis_reply
->str
);
245 /* trap MOVED cluster responses and follow them */
246 if (Ustrncmp(redis_reply
->str
, "MOVED", 5) == 0)
249 debug_printf("REDIS: cluster redirect %s\n", redis_reply
->str
);
251 This is cheating, we simply set defer_break = FALSE to move on to
252 the next server in the redis_servers list */
253 *defer_break
= FALSE
;
262 case REDIS_REPLY_NIL
:
264 debug_printf("REDIS: query was not one that returned any data\n");
265 result
= string_catn(result
, US
"", 1);
270 case REDIS_REPLY_INTEGER
:
271 result
= string_cat(result
, redis_reply
->integer
!= 0 ? US
"true" : US
"false");
274 case REDIS_REPLY_STRING
:
275 case REDIS_REPLY_STATUS
:
276 result
= string_catn(result
, US redis_reply
->str
, redis_reply
->len
);
279 case REDIS_REPLY_ARRAY
:
281 /* NOTE: For now support 1 nested array result. If needed a limitless
282 result can be parsed */
284 for (i
= 0; i
< redis_reply
->elements
; i
++)
286 entry
= redis_reply
->element
[i
];
289 result
= string_catn(result
, US
"\n", 1);
293 case REDIS_REPLY_INTEGER
:
294 result
= string_fmt_append(result
, "%d", entry
->integer
);
296 case REDIS_REPLY_STRING
:
297 result
= string_catn(result
, US entry
->str
, entry
->len
);
299 case REDIS_REPLY_ARRAY
:
300 for (j
= 0; j
< entry
->elements
; j
++)
302 tentry
= entry
->element
[j
];
305 result
= string_catn(result
, US
"\n", 1);
307 switch (tentry
->type
)
309 case REDIS_REPLY_INTEGER
:
310 result
= string_fmt_append(result
, "%d", tentry
->integer
);
312 case REDIS_REPLY_STRING
:
313 result
= string_catn(result
, US tentry
->str
, tentry
->len
);
315 case REDIS_REPLY_ARRAY
:
317 debug_printf("REDIS: result has nesting of arrays which"
318 " is not supported. Ignoring!\n");
321 DEBUG(D_lookup
) debug_printf(
322 "REDIS: result has unsupported type. Ignoring!\n");
328 DEBUG(D_lookup
) debug_printf("REDIS: query returned unsupported type\n");
337 store_reset(result
->s
+ result
->ptr
+ 1);
341 *errmsg
= US
"REDIS: no data found";
346 /* Free store for any result that was got; don't close the connection,
349 if (redis_reply
) freeReplyObject(redis_reply
);
351 /* Non-NULL result indicates a successful result */
355 *resultptr
= string_from_gstring(result
);
360 DEBUG(D_lookup
) debug_printf("%s\n", *errmsg
);
361 /* NOTE: Required to close connection since it needs to be reopened */
362 return yield
; /* FAIL or DEFER */
368 /*************************************************
370 *************************************************/
372 * See local README for interface description. The handle and filename
373 * arguments are not used. The code to loop through a list of servers while the
374 * query is deferred with a retryable error is now in a separate function that is
375 * shared with other noSQL lookups.
379 redis_find(void *handle
__attribute__((unused
)),
380 uschar
*filename
__attribute__((unused
)),
381 const uschar
*command
, int length
, uschar
**result
, uschar
**errmsg
,
384 return lf_sqlperform(US
"Redis", US
"redis_servers", redis_servers
, command
,
385 result
, errmsg
, do_cache
, perform_redis_search
);
390 /*************************************************
391 * Quote entry point *
392 *************************************************/
394 /* Prefix any whitespace, or backslash, with a backslash.
395 This is not a Redis thing but instead to let the argv splitting
396 we do to split on whitespace, yet provide means for getting
397 whitespace into an argument.
400 s the string to be quoted
401 opt additional option text or NULL if none
403 Returns: the processed string or NULL for a bad option
407 redis_quote(uschar
*s
, uschar
*opt
)
414 if (opt
) return NULL
; /* No options recognized */
416 while ((c
= *t
++) != 0)
417 if (isspace(c
) || c
== '\\') count
++;
419 if (count
== 0) return s
;
420 t
= quoted
= store_get(Ustrlen(s
) + count
+ 1);
422 while ((c
= *s
++) != 0)
424 if (isspace(c
) || c
== '\\') *t
++ = '\\';
433 /*************************************************
434 * Version reporting entry point *
435 *************************************************/
436 #include "../version.h"
439 redis_version_report(FILE *f
)
441 fprintf(f
, "Library version: REDIS: Compile: %d [%d]\n",
442 HIREDIS_MAJOR
, HIREDIS_MINOR
);
444 fprintf(f
, " Exim version %s\n", EXIM_VERSION_STR
);
450 /* These are the lookup_info blocks for this driver */
451 static lookup_info redis_lookup_info
= {
452 US
"redis", /* lookup name */
453 lookup_querystyle
, /* query-style lookup */
454 redis_open
, /* open function */
455 NULL
, /* no check function */
456 redis_find
, /* find function */
457 NULL
, /* no close function */
458 redis_tidy
, /* tidy function */
459 redis_quote
, /* quoting function */
460 redis_version_report
/* version reporting */
464 # define redis_lookup_module_info _lookup_module_info
465 #endif /* DYNLOOKUP */
467 static lookup_info
*_lookup_list
[] = { &redis_lookup_info
};
468 lookup_module_info redis_lookup_module_info
= { LOOKUP_MODULE_INFO_MAGIC
, _lookup_list
, 1 };
470 #endif /* LOOKUP_REDIS */
471 /* End of lookups/redis.c */