String handling: refactor the expanding-string routines and users to use a descriptor...
[exim.git] / src / src / lookups / mysql.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2015 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* Thanks to Paul Kelly for contributing the original code for these
9 functions. */
10
11
12 #include "../exim.h"
13 #include "lf_functions.h"
14
15 #include <mysql.h>       /* The system header */
16 #include <mysql_version.h>
17
18
19 /* Structure and anchor for caching connections. */
20
21 typedef struct mysql_connection {
22   struct mysql_connection *next;
23   uschar  *server;
24   MYSQL *handle;
25 } mysql_connection;
26
27 static mysql_connection *mysql_connections = NULL;
28
29
30
31 /*************************************************
32 *              Open entry point                  *
33 *************************************************/
34
35 /* See local README for interface description. */
36
37 static void *
38 mysql_open(uschar *filename, uschar **errmsg)
39 {
40 return (void *)(1);    /* Just return something non-null */
41 }
42
43
44
45 /*************************************************
46 *               Tidy entry point                 *
47 *************************************************/
48
49 /* See local README for interface description. */
50
51 static void
52 mysql_tidy(void)
53 {
54 mysql_connection *cn;
55 while ((cn = mysql_connections) != NULL)
56   {
57   mysql_connections = cn->next;
58   DEBUG(D_lookup) debug_printf("close MYSQL connection: %s\n", cn->server);
59   mysql_close(cn->handle);
60   }
61 }
62
63
64
65 /*************************************************
66 *        Internal search function                *
67 *************************************************/
68
69 /* This function is called from the find entry point to do the search for a
70 single server.
71
72 Arguments:
73   query        the query string
74   server       the server string
75   resultptr    where to store the result
76   errmsg       where to point an error message
77   defer_break  TRUE if no more servers are to be tried after DEFER
78   do_cache     set zero if data is changed
79
80 The server string is of the form "host/dbname/user/password". The host can be
81 host:port. This string is in a nextinlist temporary buffer, so can be
82 overwritten.
83
84 Returns:       OK, FAIL, or DEFER
85 */
86
87 static int
88 perform_mysql_search(const uschar *query, uschar *server, uschar **resultptr,
89   uschar **errmsg, BOOL *defer_break, uint *do_cache)
90 {
91 MYSQL *mysql_handle = NULL;        /* Keep compilers happy */
92 MYSQL_RES *mysql_result = NULL;
93 MYSQL_ROW mysql_row_data;
94 MYSQL_FIELD *fields;
95
96 int i;
97 int yield = DEFER;
98 unsigned int num_fields;
99 gstring * result = NULL;
100 mysql_connection *cn;
101 uschar *server_copy = NULL;
102 uschar *sdata[4];
103
104 /* Disaggregate the parameters from the server argument. The order is host,
105 database, user, password. We can write to the string, since it is in a
106 nextinlist temporary buffer. The copy of the string that is used for caching
107 has the password removed. This copy is also used for debugging output. */
108
109 for (i = 3; i > 0; i--)
110   {
111   uschar *pp = Ustrrchr(server, '/');
112   if (pp == NULL)
113     {
114     *errmsg = string_sprintf("incomplete MySQL server data: %s",
115       (i == 3)? server : server_copy);
116     *defer_break = TRUE;
117     return DEFER;
118     }
119   *pp++ = 0;
120   sdata[i] = pp;
121   if (i == 3) server_copy = string_copy(server);  /* sans password */
122   }
123 sdata[0] = server;   /* What's left at the start */
124
125 /* See if we have a cached connection to the server */
126
127 for (cn = mysql_connections; cn; cn = cn->next)
128   if (Ustrcmp(cn->server, server_copy) == 0)
129     {
130     mysql_handle = cn->handle;
131     break;
132     }
133
134 /* If no cached connection, we must set one up. Mysql allows for a host name
135 and port to be specified. It also allows the name of a Unix socket to be used.
136 Unfortunately, this contains slashes, but its use is expected to be rare, so
137 the rather cumbersome syntax shouldn't inconvenience too many people. We use
138 this:  host:port(socket)[group]  where all the parts are optional.
139 The "group" parameter specifies an option group from a MySQL option file. */
140
141 if (!cn)
142   {
143   uschar *p;
144   uschar *socket = NULL;
145   int port = 0;
146   uschar *group = US"exim";
147
148   if ((p = Ustrchr(sdata[0], '[')))
149     {
150     *p++ = 0;
151     group = p;
152     while (*p && *p != ']') p++;
153     *p = 0;
154     }
155
156   if ((p = Ustrchr(sdata[0], '(')))
157     {
158     *p++ = 0;
159     socket = p;
160     while (*p && *p != ')') p++;
161     *p = 0;
162     }
163
164   if ((p = Ustrchr(sdata[0], ':')))
165     {
166     *p++ = 0;
167     port = Uatoi(p);
168     }
169
170   if (Ustrchr(sdata[0], '/'))
171     {
172     *errmsg = string_sprintf("unexpected slash in MySQL server hostname: %s",
173       sdata[0]);
174     *defer_break = TRUE;
175     return DEFER;
176     }
177
178   /* If the database is the empty string, set it NULL - the query must then
179   define it. */
180
181   if (sdata[1][0] == 0) sdata[1] = NULL;
182
183   DEBUG(D_lookup)
184     debug_printf("MYSQL new connection: host=%s port=%d socket=%s "
185       "database=%s user=%s\n", sdata[0], port, socket, sdata[1], sdata[2]);
186
187   /* Get store for a new handle, initialize it, and connect to the server */
188
189   mysql_handle = store_get(sizeof(MYSQL));
190   mysql_init(mysql_handle);
191   mysql_options(mysql_handle, MYSQL_READ_DEFAULT_GROUP, CS group);
192   if (mysql_real_connect(mysql_handle,
193       /*  host        user         passwd     database */
194       CS sdata[0], CS sdata[2], CS sdata[3], CS sdata[1],
195       port, CS socket, CLIENT_MULTI_RESULTS) == NULL)
196     {
197     *errmsg = string_sprintf("MYSQL connection failed: %s",
198       mysql_error(mysql_handle));
199     *defer_break = FALSE;
200     goto MYSQL_EXIT;
201     }
202
203   /* Add the connection to the cache */
204
205   cn = store_get(sizeof(mysql_connection));
206   cn->server = server_copy;
207   cn->handle = mysql_handle;
208   cn->next = mysql_connections;
209   mysql_connections = cn;
210   }
211
212 /* Else use a previously cached connection */
213
214 else
215   {
216   DEBUG(D_lookup)
217     debug_printf("MYSQL using cached connection for %s\n", server_copy);
218   }
219
220 /* Run the query */
221
222 if (mysql_query(mysql_handle, CS query) != 0)
223   {
224   *errmsg = string_sprintf("MYSQL: query failed: %s\n",
225     mysql_error(mysql_handle));
226   *defer_break = FALSE;
227   goto MYSQL_EXIT;
228   }
229
230 /* Pick up the result. If the query was not of the type that returns data,
231 namely INSERT, UPDATE, or DELETE, an error occurs here. However, this situation
232 can be detected by calling mysql_field_count(). If its result is zero, no data
233 was expected (this is all explained clearly in the MySQL manual). In this case,
234 we return the number of rows affected by the command. In this event, we do NOT
235 want to cache the result; also the whole cache for the handle must be cleaned
236 up. Setting do_cache zero requests this. */
237
238 if ((mysql_result = mysql_use_result(mysql_handle)) == NULL)
239   {
240   if ( mysql_field_count(mysql_handle) == 0 )
241     {
242     DEBUG(D_lookup) debug_printf("MYSQL: query was not one that returns data\n");
243     result = string_cat(result,
244                string_sprintf("%d", mysql_affected_rows(mysql_handle)));
245     *do_cache = 0;
246     goto MYSQL_EXIT;
247     }
248   *errmsg = string_sprintf("MYSQL: lookup result failed: %s\n",
249     mysql_error(mysql_handle));
250   *defer_break = FALSE;
251   goto MYSQL_EXIT;
252   }
253
254 /* Find the number of fields returned. If this is one, we don't add field
255 names to the data. Otherwise we do. */
256
257 num_fields = mysql_num_fields(mysql_result);
258
259 /* Get the fields and construct the result string. If there is more than one
260 row, we insert '\n' between them. */
261
262 fields = mysql_fetch_fields(mysql_result);
263
264 while ((mysql_row_data = mysql_fetch_row(mysql_result)))
265   {
266   unsigned long *lengths = mysql_fetch_lengths(mysql_result);
267
268   if (result)
269     result = string_catn(result, US"\n", 1);
270
271   if (num_fields == 1)
272     {
273     if (mysql_row_data[0] != NULL)    /* NULL value yields nothing */
274       {
275       result = string_catn(result, US mysql_row_data[0],
276         lengths[0]);
277       (void) string_from_gstring(result);
278       }
279     }
280
281   else for (i = 0; i < num_fields; i++)
282     result = lf_quote(US fields[i].name, US mysql_row_data[i], lengths[i], result);
283   }
284
285 /* more results? -1 = no, >0 = error, 0 = yes (keep looping)
286    This is needed because of the CLIENT_MULTI_RESULTS on mysql_real_connect(),
287    we don't expect any more results. */
288
289 while((i = mysql_next_result(mysql_handle)) >= 0) {
290    if(i == 0) {   /* Just ignore more results */
291      DEBUG(D_lookup) debug_printf("MYSQL: got unexpected more results\n");
292      continue;
293    }
294
295    *errmsg = string_sprintf("MYSQL: lookup result error when checking for more results: %s\n",
296        mysql_error(mysql_handle));
297    goto MYSQL_EXIT;
298 }
299
300 /* If result is NULL then no data has been found and so we return FAIL.
301 Otherwise, we must terminate the string which has been built; string_cat()
302 always leaves enough room for a terminating zero. */
303
304 if (!result)
305   {
306   yield = FAIL;
307   *errmsg = US"MYSQL: no data found";
308   }
309 else
310   {
311   (void) string_from_gstring(result);
312   store_reset(result->s + result->ptr + 1);
313   }
314
315 /* Get here by goto from various error checks and from the case where no data
316 was read (e.g. an update query). */
317
318 MYSQL_EXIT:
319
320 /* Free mysal store for any result that was got; don't close the connection, as
321 it is cached. */
322
323 if (mysql_result) mysql_free_result(mysql_result);
324
325 /* Non-NULL result indicates a successful result */
326
327 if (result)
328   {
329   *resultptr = result->s;
330   return OK;
331   }
332 else
333   {
334   DEBUG(D_lookup) debug_printf("%s\n", *errmsg);
335   return yield;      /* FAIL or DEFER */
336   }
337 }
338
339
340
341
342 /*************************************************
343 *               Find entry point                 *
344 *************************************************/
345
346 /* See local README for interface description. The handle and filename
347 arguments are not used. The code to loop through a list of servers while the
348 query is deferred with a retryable error is now in a separate function that is
349 shared with other SQL lookups. */
350
351 static int
352 mysql_find(void *handle, uschar *filename, const uschar *query, int length,
353   uschar **result, uschar **errmsg, uint *do_cache)
354 {
355 return lf_sqlperform(US"MySQL", US"mysql_servers", mysql_servers, query,
356   result, errmsg, do_cache, perform_mysql_search);
357 }
358
359
360
361 /*************************************************
362 *               Quote entry point                *
363 *************************************************/
364
365 /* The only characters that need to be quoted (with backslash) are newline,
366 tab, carriage return, backspace, backslash itself, and the quote characters.
367 Percent, and underscore and not escaped. They are only special in contexts
368 where they can be wild cards, and this isn't usually the case for data inserted
369 from messages, since that isn't likely to be treated as a pattern of any kind.
370 Sadly, MySQL doesn't seem to behave like other programs. If you use something
371 like "where id="ab\%cd" it does not treat the string as "ab%cd". So you really
372 can't quote "on spec".
373
374 Arguments:
375   s          the string to be quoted
376   opt        additional option text or NULL if none
377
378 Returns:     the processed string or NULL for a bad option
379 */
380
381 static uschar *
382 mysql_quote(uschar *s, uschar *opt)
383 {
384 register int c;
385 int count = 0;
386 uschar *t = s;
387 uschar *quoted;
388
389 if (opt != NULL) return NULL;     /* No options recognized */
390
391 while ((c = *t++) != 0)
392   if (Ustrchr("\n\t\r\b\'\"\\", c) != NULL) count++;
393
394 if (count == 0) return s;
395 t = quoted = store_get(Ustrlen(s) + count + 1);
396
397 while ((c = *s++) != 0)
398   {
399   if (Ustrchr("\n\t\r\b\'\"\\", c) != NULL)
400     {
401     *t++ = '\\';
402     switch(c)
403       {
404       case '\n': *t++ = 'n';
405       break;
406       case '\t': *t++ = 't';
407       break;
408       case '\r': *t++ = 'r';
409       break;
410       case '\b': *t++ = 'b';
411       break;
412       default:   *t++ = c;
413       break;
414       }
415     }
416   else *t++ = c;
417   }
418
419 *t = 0;
420 return quoted;
421 }
422
423
424 /*************************************************
425 *         Version reporting entry point          *
426 *************************************************/
427
428 /* See local README for interface description. */
429
430 #include "../version.h"
431
432 void
433 mysql_version_report(FILE *f)
434 {
435 fprintf(f, "Library version: MySQL: Compile: %s [%s]\n"
436            "                        Runtime: %s\n",
437         MYSQL_SERVER_VERSION, MYSQL_COMPILATION_COMMENT,
438         mysql_get_client_info());
439 #ifdef DYNLOOKUP
440 fprintf(f, "                        Exim version %s\n", EXIM_VERSION_STR);
441 #endif
442 }
443
444 /* These are the lookup_info blocks for this driver */
445
446 static lookup_info mysql_lookup_info = {
447   US"mysql",                     /* lookup name */
448   lookup_querystyle,             /* query-style lookup */
449   mysql_open,                    /* open function */
450   NULL,                          /* no check function */
451   mysql_find,                    /* find function */
452   NULL,                          /* no close function */
453   mysql_tidy,                    /* tidy function */
454   mysql_quote,                   /* quoting function */
455   mysql_version_report           /* version reporting */
456 };
457
458 #ifdef DYNLOOKUP
459 #define mysql_lookup_module_info _lookup_module_info
460 #endif
461
462 static lookup_info *_lookup_list[] = { &mysql_lookup_info };
463 lookup_module_info mysql_lookup_module_info = { LOOKUP_MODULE_INFO_MAGIC, _lookup_list, 1 };
464
465 /* End of lookups/mysql.c */