1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2015 */
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
;
87 uschar
*result
= NULL
;
88 uschar
*server_copy
= NULL
;
92 /* Disaggregate the parameters from the server argument.
93 The order is host:port(socket)
94 We can write to the string, since it is in a nextinlist temporary buffer.
95 This copy is also used for debugging output. */
97 memset(sdata
, 0, sizeof(sdata
)) /* Set all to NULL */;
98 for (i
= 2; i
> 0; i
--)
100 uschar
*pp
= Ustrrchr(server
, '/');
104 *errmsg
= string_sprintf("incomplete Redis server data: %s",
105 i
== 2 ? server
: server_copy
);
111 if (i
== 2) server_copy
= string_copy(server
); /* sans password */
113 sdata
[0] = server
; /* What's left at the start */
115 /* If the database or password is an empty string, set it NULL */
116 if (sdata
[1][0] == 0) sdata
[1] = NULL
;
117 if (sdata
[2][0] == 0) sdata
[2] = NULL
;
119 /* See if we have a cached connection to the server */
121 for (cn
= redis_connections
; cn
; cn
= cn
->next
)
122 if (Ustrcmp(cn
->server
, server_copy
) == 0)
124 redis_handle
= cn
->handle
;
131 uschar
*socket
= NULL
;
133 /* int redis_err = REDIS_OK; */
135 if ((p
= Ustrchr(sdata
[0], '(')))
139 while (*p
!= 0 && *p
!= ')') p
++;
143 if ((p
= Ustrchr(sdata
[0], ':')))
149 port
= Uatoi("6379");
151 if (Ustrchr(server
, '/'))
153 *errmsg
= string_sprintf("unexpected slash in Redis server hostname: %s",
160 debug_printf("REDIS new connection: host=%s port=%d socket=%s database=%s\n",
161 sdata
[0], port
, socket
, sdata
[1]);
163 /* Get store for a new handle, initialize it, and connect to the server */
164 /* XXX: Use timeouts ? */
166 socket
? redisConnectUnix(CCS socket
) : redisConnect(CCS server
, port
);
169 *errmsg
= string_sprintf("REDIS connection failed");
170 *defer_break
= FALSE
;
174 /* Add the connection to the cache */
175 cn
= store_get(sizeof(redis_connection
));
176 cn
->server
= server_copy
;
177 cn
->handle
= redis_handle
;
178 cn
->next
= redis_connections
;
179 redis_connections
= cn
;
184 debug_printf("REDIS using cached connection for %s\n", server_copy
);
187 /* Authenticate if there is a password */
189 if (!(redis_reply
= redisCommand(redis_handle
, "AUTH %s", sdata
[2])))
191 *errmsg
= string_sprintf("REDIS Authentication failed: %s\n", redis_handle
->errstr
);
192 *defer_break
= FALSE
;
196 /* Select the database if there is a dbnumber passed */
199 if (!(redis_reply
= redisCommand(redis_handle
, "SELECT %s", sdata
[1])))
201 *errmsg
= string_sprintf("REDIS: Selecting database=%s failed: %s\n", sdata
[1], redis_handle
->errstr
);
202 *defer_break
= FALSE
;
205 DEBUG(D_lookup
) debug_printf("REDIS: Selecting database=%s\n", sdata
[1]);
208 /* split string on whitespace into argv */
212 const uschar
* s
= command
;
216 while (isspace(*s
)) s
++;
218 for (i
= 0; *s
&& i
< nele(argv
); i
++)
220 for (argv
[i
] = NULL
, siz
= ptr
= 0; (c
= *s
) && !isspace(c
); s
++)
221 if (c
!= '\\' || *++s
) /* backslash protects next char */
222 argv
[i
] = string_catn(argv
[i
], &siz
, &ptr
, s
, 1);
223 *(argv
[i
]+ptr
) = '\0';
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
);
244 *defer_break
= FALSE
;
249 case REDIS_REPLY_NIL
:
251 debug_printf("REDIS: query was not one that returned any data\n");
252 result
= string_sprintf("");
257 case REDIS_REPLY_INTEGER
:
258 ttmp
= (redis_reply
->integer
!= 0) ? US
"true" : US
"false";
259 result
= string_cat(result
, &ssize
, &offset
, US ttmp
);
262 case REDIS_REPLY_STRING
:
263 case REDIS_REPLY_STATUS
:
264 result
= string_catn(result
, &ssize
, &offset
,
265 US redis_reply
->str
, redis_reply
->len
);
268 case REDIS_REPLY_ARRAY
:
270 /* NOTE: For now support 1 nested array result. If needed a limitless
271 result can be parsed */
273 for (i
= 0; i
< redis_reply
->elements
; i
++)
275 entry
= redis_reply
->element
[i
];
278 result
= string_catn(result
, &ssize
, &offset
, US
"\n", 1);
282 case REDIS_REPLY_INTEGER
:
283 tmp
= string_sprintf("%d", entry
->integer
);
284 result
= string_cat(result
, &ssize
, &offset
, US tmp
);
286 case REDIS_REPLY_STRING
:
287 result
= string_catn(result
, &ssize
, &offset
,
288 US entry
->str
, entry
->len
);
290 case REDIS_REPLY_ARRAY
:
291 for (j
= 0; j
< entry
->elements
; j
++)
293 tentry
= entry
->element
[j
];
296 result
= string_catn(result
, &ssize
, &offset
, US
"\n", 1);
298 switch (tentry
->type
)
300 case REDIS_REPLY_INTEGER
:
301 ttmp
= string_sprintf("%d", tentry
->integer
);
302 result
= string_cat(result
, &ssize
, &offset
, US ttmp
);
304 case REDIS_REPLY_STRING
:
305 result
= string_catn(result
, &ssize
, &offset
,
306 US tentry
->str
, tentry
->len
);
308 case REDIS_REPLY_ARRAY
:
310 debug_printf("REDIS: result has nesting of arrays which"
311 " is not supported. Ignoring!\n");
314 DEBUG(D_lookup
) debug_printf(
315 "REDIS: result has unsupported type. Ignoring!\n");
321 DEBUG(D_lookup
) debug_printf("REDIS: query returned unsupported type\n");
332 store_reset(result
+ offset
+ 1);
337 *errmsg
= US
"REDIS: no data found";
342 /* Free store for any result that was got; don't close the connection,
345 if (redis_reply
) freeReplyObject(redis_reply
);
347 /* Non-NULL result indicates a sucessful result */
356 DEBUG(D_lookup
) debug_printf("%s\n", *errmsg
);
357 /* NOTE: Required to close connection since it needs to be reopened */
358 return yield
; /* FAIL or DEFER */
364 /*************************************************
366 *************************************************/
368 * See local README for interface description. The handle and filename
369 * arguments are not used. The code to loop through a list of servers while the
370 * query is deferred with a retryable error is now in a separate function that is
371 * shared with other noSQL lookups.
375 redis_find(void *handle
__attribute__((unused
)),
376 uschar
*filename
__attribute__((unused
)),
377 const uschar
*command
, int length
, uschar
**result
, uschar
**errmsg
,
380 return lf_sqlperform(US
"Redis", US
"redis_servers", redis_servers
, command
,
381 result
, errmsg
, do_cache
, perform_redis_search
);
386 /*************************************************
387 * Quote entry point *
388 *************************************************/
390 /* Prefix any whitespace, or backslash, with a backslash.
391 This is not a Redis thing but instead to let the argv splitting
392 we do to split on whitespace, yet provide means for getting
393 whitespace into an argument.
396 s the string to be quoted
397 opt additional option text or NULL if none
399 Returns: the processed string or NULL for a bad option
403 redis_quote(uschar
*s
, uschar
*opt
)
410 if (opt
) return NULL
; /* No options recognized */
412 while ((c
= *t
++) != 0)
413 if (isspace(c
) || c
== '\\') count
++;
415 if (count
== 0) return s
;
416 t
= quoted
= store_get(Ustrlen(s
) + count
+ 1);
418 while ((c
= *s
++) != 0)
420 if (isspace(c
) || c
== '\\') *t
++ = '\\';
429 /*************************************************
430 * Version reporting entry point *
431 *************************************************/
432 #include "../version.h"
435 redis_version_report(FILE *f
)
437 fprintf(f
, "Library version: REDIS: Compile: %d [%d]\n",
438 HIREDIS_MAJOR
, HIREDIS_MINOR
);
440 fprintf(f
, " Exim version %s\n", EXIM_VERSION_STR
);
446 /* These are the lookup_info blocks for this driver */
447 static lookup_info redis_lookup_info
= {
448 US
"redis", /* lookup name */
449 lookup_querystyle
, /* query-style lookup */
450 redis_open
, /* open function */
451 NULL
, /* no check function */
452 redis_find
, /* find function */
453 NULL
, /* no close function */
454 redis_tidy
, /* tidy function */
455 redis_quote
, /* quoting function */
456 redis_version_report
/* version reporting */
460 # define redis_lookup_module_info _lookup_module_info
461 #endif /* DYNLOOKUP */
463 static lookup_info
*_lookup_list
[] = { &redis_lookup_info
};
464 lookup_module_info redis_lookup_module_info
= { LOOKUP_MODULE_INFO_MAGIC
, _lookup_list
, 1 };
466 #endif /* LOOKUP_REDIS */
467 /* End of lookups/redis.c */