Copyright updates:
[exim.git] / src / src / lookups / pgsql.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2022 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9 /* Thanks to Petr Cech for contributing the original code for these
10 functions. Thanks to Joachim Wieland for the initial patch for the Unix domain
11 socket extension. */
12
13 #include "../exim.h"
14 #include "lf_functions.h"
15
16 #include <libpq-fe.h>       /* The system header */
17
18 /* Structure and anchor for caching connections. */
19
20 typedef struct pgsql_connection {
21   struct pgsql_connection *next;
22   uschar *server;
23   PGconn *handle;
24 } pgsql_connection;
25
26 static pgsql_connection *pgsql_connections = NULL;
27
28
29
30 /*************************************************
31 *              Open entry point                  *
32 *************************************************/
33
34 /* See local README for interface description. */
35
36 static void *
37 pgsql_open(const uschar * filename, uschar ** errmsg)
38 {
39 return (void *)(1);    /* Just return something non-null */
40 }
41
42
43
44 /*************************************************
45 *               Tidy entry point                 *
46 *************************************************/
47
48 /* See local README for interface description. */
49
50 static void
51 pgsql_tidy(void)
52 {
53 pgsql_connection *cn;
54 while ((cn = pgsql_connections) != NULL)
55   {
56   pgsql_connections = cn->next;
57   DEBUG(D_lookup) debug_printf_indent("close PGSQL connection: %s\n", cn->server);
58   PQfinish(cn->handle);
59   }
60 }
61
62
63 /*************************************************
64 *       Notice processor function for pgsql      *
65 *************************************************/
66
67 /* This function is passed to pgsql below, and called for any PostgreSQL
68 "notices". By default they are written to stderr, which is undesirable.
69
70 Arguments:
71   arg        an opaque user cookie (not used)
72   message    the notice
73
74 Returns:     nothing
75 */
76
77 static void
78 notice_processor(void *arg, const char *message)
79 {
80 arg = arg;   /* Keep compiler happy */
81 DEBUG(D_lookup) debug_printf_indent("PGSQL: %s\n", message);
82 }
83
84
85
86 /*************************************************
87 *        Internal search function                *
88 *************************************************/
89
90 /* This function is called from the find entry point to do the search for a
91 single server. The server string is of the form "server/dbname/user/password".
92
93 PostgreSQL supports connections through Unix domain sockets. This is usually
94 faster and costs less cpu time than a TCP/IP connection. However it can only be
95 used if the mail server runs on the same machine as the database server. A
96 configuration line for PostgreSQL via Unix domain sockets looks like this:
97
98 hide pgsql_servers = (/tmp/.s.PGSQL.5432)/db/user/password[:<nextserver>]
99
100 We enclose the path name in parentheses so that its slashes aren't visually
101 confused with the delimiters for the other pgsql_server settings.
102
103 For TCP/IP connections, the server is a host name and optional port (with a
104 colon separator).
105
106 NOTE:
107  1) All three '/' must be present.
108  2) If host is omitted the local unix socket is used.
109
110 Arguments:
111   query        the query string
112   server       the server string; this is in dynamic memory and can be updated
113   resultptr    where to store the result
114   errmsg       where to point an error message
115   defer_break  set TRUE if no more servers are to be tried after DEFER
116   do_cache     set FALSE if data is changed
117   opts         options list
118
119 Returns:       OK, FAIL, or DEFER
120 */
121
122 static int
123 perform_pgsql_search(const uschar *query, uschar *server, uschar **resultptr,
124   uschar **errmsg, BOOL *defer_break, uint *do_cache, const uschar * opts)
125 {
126 PGconn *pg_conn = NULL;
127 PGresult *pg_result = NULL;
128
129 gstring * result = NULL;
130 int yield = DEFER;
131 unsigned int num_fields, num_tuples;
132 pgsql_connection *cn;
133 rmark reset_point = store_mark();
134 uschar *server_copy = NULL;
135 uschar *sdata[3];
136
137 /* Disaggregate the parameters from the server argument. The order is host or
138 path, database, user, password. We can write to the string, since it is in a
139 nextinlist temporary buffer. The copy of the string that is used for caching
140 has the password removed. This copy is also used for debugging output. */
141
142 for (int i = 2; i >= 0; i--)
143   {
144   uschar *pp = Ustrrchr(server, '/');
145   if (!pp)
146     {
147     *errmsg = string_sprintf("incomplete pgSQL server data: %s",
148       (i == 2)? server : server_copy);
149     *defer_break = TRUE;
150     return DEFER;
151     }
152   *pp++ = 0;
153   sdata[i] = pp;
154   if (i == 2) server_copy = string_copy(server);  /* sans password */
155   }
156
157 /* The total server string has now been truncated so that what is left at the
158 start is the identification of the server (host or path). See if we have a
159 cached connection to the server. */
160
161 for (cn = pgsql_connections; cn; cn = cn->next)
162   if (Ustrcmp(cn->server, server_copy) == 0)
163     {
164     pg_conn = cn->handle;
165     break;
166     }
167
168 /* If there is no cached connection, we must set one up. */
169
170 if (!cn)
171   {
172   uschar *port = US"";
173
174   /* For a Unix domain socket connection, the path is in parentheses */
175
176   if (*server == '(')
177     {
178     uschar *last_slash, *last_dot, *p;
179
180     p = ++server;
181     while (*p && *p != ')') p++;
182     *p = 0;
183
184     last_slash = Ustrrchr(server, '/');
185     last_dot = Ustrrchr(server, '.');
186
187     DEBUG(D_lookup) debug_printf_indent("PGSQL new connection: socket=%s "
188       "database=%s user=%s\n", server, sdata[0], sdata[1]);
189
190     /* A valid socket name looks like this: /var/run/postgresql/.s.PGSQL.5432
191     We have to call PQsetdbLogin with '/var/run/postgresql' as the hostname
192     argument and put '5432' into the port variable. */
193
194     if (!last_slash || !last_dot)
195       {
196       *errmsg = string_sprintf("PGSQL invalid filename for socket: %s", server);
197       *defer_break = TRUE;
198       return DEFER;
199       }
200
201     /* Terminate the path name and set up the port: we'll have something like
202     server = "/var/run/postgresql" and port = "5432". */
203
204     *last_slash = 0;
205     port = last_dot + 1;
206     }
207
208   /* Host connection; sort out the port */
209
210   else
211     {
212     uschar *p;
213     if ((p = Ustrchr(server, ':')))
214       {
215       *p++ = 0;
216       port = p;
217       }
218
219     if (Ustrchr(server, '/'))
220       {
221       *errmsg = string_sprintf("unexpected slash in pgSQL server hostname: %s",
222         server);
223       *defer_break = TRUE;
224       return DEFER;
225       }
226
227     DEBUG(D_lookup) debug_printf_indent("PGSQL new connection: host=%s port=%s "
228       "database=%s user=%s\n", server, port, sdata[0], sdata[1]);
229     }
230
231   /* If the database is the empty string, set it NULL - the query must then
232   define it. */
233
234   if (sdata[0][0] == 0) sdata[0] = NULL;
235
236   /* Get store for a new handle, initialize it, and connect to the server */
237
238   pg_conn=PQsetdbLogin(
239     /*  host      port  options tty   database       user       passwd */
240     CS server, CS port,  NULL, NULL, CS sdata[0], CS sdata[1], CS sdata[2]);
241
242   if(PQstatus(pg_conn) == CONNECTION_BAD)
243     {
244     reset_point = store_reset(reset_point);
245     *errmsg = string_sprintf("PGSQL connection failed: %s",
246       PQerrorMessage(pg_conn));
247     PQfinish(pg_conn);
248     goto PGSQL_EXIT;
249     }
250
251   /* Set the client encoding to SQL_ASCII, which means that the server will
252   not try to interpret the query as being in any fancy encoding such as UTF-8
253   or other multibyte code that might cause problems with escaping. */
254
255   PQsetClientEncoding(pg_conn, "SQL_ASCII");
256
257   /* Set the notice processor to prevent notices from being written to stderr
258   (which is what the default does). Our function (above) just produces debug
259   output. */
260
261   PQsetNoticeProcessor(pg_conn, notice_processor, NULL);
262
263   /* Add the connection to the cache */
264
265   cn = store_get(sizeof(pgsql_connection), GET_UNTAINTED);
266   cn->server = server_copy;
267   cn->handle = pg_conn;
268   cn->next = pgsql_connections;
269   pgsql_connections = cn;
270   }
271
272 /* Else use a previously cached connection */
273
274 else
275   {
276   DEBUG(D_lookup) debug_printf_indent("PGSQL using cached connection for %s\n",
277     server_copy);
278   }
279
280 /* Run the query */
281
282 pg_result = PQexec(pg_conn, CS query);
283 switch(PQresultStatus(pg_result))
284   {
285   case PGRES_EMPTY_QUERY:
286   case PGRES_COMMAND_OK:
287     /* The command was successful but did not return any data since it was
288     not SELECT but either an INSERT, UPDATE or DELETE statement. Tell the
289     high level code to not cache this query, and clean the current cache for
290     this handle by setting *do_cache zero. */
291
292     result = string_cat(result, US PQcmdTuples(pg_result));
293     *do_cache = 0;
294     DEBUG(D_lookup) debug_printf_indent("PGSQL: command does not return any data "
295       "but was successful. Rows affected: %s\n", string_from_gstring(result));
296     break;
297
298   case PGRES_TUPLES_OK:
299     break;
300
301   default:
302     /* This was the original code:
303     *errmsg = string_sprintf("PGSQL: query failed: %s\n",
304                              PQresultErrorMessage(pg_result));
305     This was suggested by a user:
306     */
307
308     *errmsg = string_sprintf("PGSQL: query failed: %s (%s) (%s)\n",
309                            PQresultErrorMessage(pg_result),
310                            PQresStatus(PQresultStatus(pg_result)), query);
311     goto PGSQL_EXIT;
312   }
313
314 /* Result is in pg_result. Find the number of fields returned. If this is one,
315 we don't add field names to the data. Otherwise we do. If the query did not
316 return anything we skip the for loop; this also applies to the case
317 PGRES_COMMAND_OK. */
318
319 num_fields = PQnfields(pg_result);
320 num_tuples = PQntuples(pg_result);
321
322 /* Get the fields and construct the result string. If there is more than one
323 row, we insert '\n' between them. */
324
325 for (int i = 0; i < num_tuples; i++)
326   {
327   if (result)
328     result = string_catn(result, US"\n", 1);
329
330   if (num_fields == 1)
331     result = string_catn(result,
332         US PQgetvalue(pg_result, i, 0), PQgetlength(pg_result, i, 0));
333   else
334     for (int j = 0; j < num_fields; j++)
335       {
336       uschar *tmp = US PQgetvalue(pg_result, i, j);
337       result = lf_quote(US PQfname(pg_result, j), tmp, Ustrlen(tmp), result);
338       }
339   if (!result) result = string_get(1);
340   }
341
342 /* If result is NULL then no data has been found and so we return FAIL. */
343
344 if (!result)
345   {
346   yield = FAIL;
347   *errmsg = US"PGSQL: no data found";
348   }
349
350 /* Get here by goto from various error checks. */
351
352 PGSQL_EXIT:
353
354 /* Free store for any result that was got; don't close the connection, as
355 it is cached. */
356
357 if (pg_result) PQclear(pg_result);
358
359 /* Non-NULL result indicates a successful result */
360
361 if (result)
362   {
363   gstring_release_unused(result);
364   *resultptr = string_from_gstring(result);
365   return OK;
366   }
367 else
368   {
369   DEBUG(D_lookup) debug_printf_indent("%s\n", *errmsg);
370   return yield;      /* FAIL or DEFER */
371   }
372 }
373
374
375
376
377 /*************************************************
378 *               Find entry point                 *
379 *************************************************/
380
381 /* See local README for interface description. The handle and filename
382 arguments are not used. The code to loop through a list of servers while the
383 query is deferred with a retryable error is now in a separate function that is
384 shared with other SQL lookups. */
385
386 static int
387 pgsql_find(void * handle, const uschar * filename, const uschar * query,
388   int length, uschar ** result, uschar ** errmsg, uint * do_cache,
389   const uschar * opts)
390 {
391 return lf_sqlperform(US"PostgreSQL", US"pgsql_servers", pgsql_servers, query,
392   result, errmsg, do_cache, opts, perform_pgsql_search);
393 }
394
395
396
397 /*************************************************
398 *               Quote entry point                *
399 *************************************************/
400
401 /* The characters that always need to be quoted (with backslash) are newline,
402 tab, carriage return, backspace, backslash itself, and the quote characters.
403
404 The original code quoted single quotes as \' which is documented as valid in
405 the O'Reilly book "Practical PostgreSQL" (first edition) as an alternative to
406 the SQL standard '' way of representing a single quote as data. However, in
407 June 2006 there was some security issue with using \' and so this has been
408 changed.
409
410 [Note: There is a function called PQescapeStringConn() that quotes strings.
411 This cannot be used because it needs a PGconn argument (the connection handle).
412 Why, I don't know. Seems odd for just string escaping...]
413
414 Arguments:
415   s          the string to be quoted
416   opt        additional option text or NULL if none
417   idx        lookup type index
418
419 Returns:     the processed string or NULL for a bad option
420 */
421
422 static uschar *
423 pgsql_quote(uschar * s, uschar * opt, unsigned idx)
424 {
425 int count = 0, c;
426 uschar * t = s, * quoted;
427
428 if (opt) return NULL;     /* No options recognized */
429
430 while ((c = *t++))
431   if (Ustrchr("\n\t\r\b\'\"\\", c) != NULL) count++;
432
433 t = quoted = store_get_quoted(Ustrlen(s) + count + 1, s, idx);
434
435 while ((c = *s++))
436   {
437   if (c == '\'')
438     {
439     *t++ = '\'';
440     *t++ = '\'';
441     }
442   else if (Ustrchr("\n\t\r\b\"\\", c) != NULL)
443     {
444     *t++ = '\\';
445     switch(c)
446       {
447       case '\n': *t++ = 'n'; break;
448       case '\t': *t++ = 't'; break;
449       case '\r': *t++ = 'r'; break;
450       case '\b': *t++ = 'b'; break;
451       default:   *t++ = c;   break;
452       }
453     }
454   else *t++ = c;
455   }
456
457 *t = 0;
458 return quoted;
459 }
460
461
462 /*************************************************
463 *         Version reporting entry point          *
464 *************************************************/
465
466 /* See local README for interface description. */
467
468 #include "../version.h"
469
470 gstring *
471 pgsql_version_report(gstring * g)
472 {
473 #ifdef DYNLOOKUP
474 g = string_fmt_append(g, "Library version: PostgreSQL: Exim version %s\n", EXIM_VERSION_STR);
475 #endif
476
477 /* Version reporting: there appears to be no available information about
478 the client library in libpq-fe.h; once you have a connection object, you
479 can access the server version and the chosen protocol version, but those
480 aren't really what we want.  It might make sense to debug_printf those
481 when the connection is established though? */
482
483 return g;
484 }
485
486
487 static lookup_info _lookup_info = {
488   .name = US"pgsql",                    /* lookup name */
489   .type = lookup_querystyle,            /* query-style lookup */
490   .open = pgsql_open,                   /* open function */
491   .check = NULL,                        /* no check function */
492   .find = pgsql_find,                   /* find function */
493   .close = NULL,                        /* no close function */
494   .tidy = pgsql_tidy,                   /* tidy function */
495   .quote = pgsql_quote,                 /* quoting function */
496   .version_report = pgsql_version_report           /* version reporting */
497 };
498
499 #ifdef DYNLOOKUP
500 #define pgsql_lookup_module_info _lookup_module_info
501 #endif
502
503 static lookup_info *_lookup_list[] = { &_lookup_info };
504 lookup_module_info pgsql_lookup_module_info = { LOOKUP_MODULE_INFO_MAGIC, _lookup_list, 1 };
505
506 /* End of lookups/pgsql.c */