Debian Codegraph @

contrib/mod_sql_postgres.c

raw symbols SCIP
1 /*
2 * ProFTPD: mod_sql_postgres -- Support for connecting to Postgres databases.
3 * Copyright (c) 2001 Andrew Houghton
4 * Copyright (c) 2004-2022 TJ Saunders
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
19 *
20 * As a special exemption, Andrew Houghton and other respective copyright
21 * holders give permission to link this program with OpenSSL, and distribute
22 * the resulting executable, without including the source code for OpenSSL in
23 * the source distribution.
24 *
25 * $Libraries: -lm -lpq$
26 */
27
28 /* Internal define used for debug and logging. All backends are encouraged
29 * to use the same format.
30 */
31 #define MOD_SQL_POSTGRES_VERSION "mod_sql_postgres/4.0.4"
32
33 #define _POSTGRES_PORT "5432"
34
35 #include "conf.h"
36 #include "../contrib/mod_sql.h"
37
38 #include <libpq-fe.h>
39 #if defined(HAVE_POSTGRES_PQGETSSL) && defined(PR_USE_OPENSSL)
40 # include <openssl/ssl.h>
41
42 /* Define if you have the LibreSSL library. */
43 # if defined(LIBRESSL_VERSION_NUMBER)
44 # define HAVE_LIBRESSL 1
45 # endif
46 #endif /* HAVE_POSTGRES_PQGETSSL and PR_USE_OPENSSL */
47
48 /* For the pg_encoding_to_char() function, used for NLS support, we need
49 * to include the <mb/pg_wchar.h> file. It's OK; the function has been
50 * declared in that file for a while, according to:
51 *
52 * http://archives.postgresql.org/pgsql-bugs/2006-07/msg00125.php
53 *
54 * But it's a pain to quell all of the compiler warnings about redefined
55 * this, undefined that. The linker finds the symbol without issue, so
56 * punt on including <mb/pg_wchar.h> file. Instead, we'll copy the
57 * function declaration here.
58 */
59 #ifdef PR_USE_NLS
60 extern const char *pg_encoding_to_char(int encoding);
61
62 /* And this is the mod_sql_postgres-specific function mapping iconv
63 * locales to Postgres encodings.
64 */
65 static const char *get_postgres_encoding(const char *encoding);
66 #endif
67
68 static const char *trace_channel = "sql.postgres";
69
70 /*
71 * timer-handling code adds the need for a couple of forward declarations
72 */
73 MODRET cmd_close(cmd_rec *cmd);
74 module sql_postgres_module;
75
76 /*
77 * db_conn_struct: an internal struct to hold connection information. This
78 * connection information is backend-specific; the members here reflect
79 * the information Postgres needs for connections.
80 */
81 struct db_conn_struct {
82
83 /* Postgres-specific members */
84 const char *host;
85 const char *user;
86 const char *pass;
87 const char *db;
88 const char *port;
89
90 /* For configuring the SSL/TLS session to the Postgres server. */
91 const char *ssl_cert_file;
92 const char *ssl_key_file;
93 const char *ssl_ca_file;
94
95 const char *connect_string;
96
97 PGconn *postgres;
98 PGresult *result;
99 };
100
101 typedef struct db_conn_struct db_conn_t;
102
103 /* This struct is a wrapper for whatever backend data is needed to access
104 * the database, and supports named connections, connection counting, and
105 * timer handling.
106 */
107 struct conn_entry_struct {
108 const char *name;
109 void *data;
110
111 /* Iimer handling */
112 int timer;
113 int ttl;
114
115 /* Connection handling */
116 unsigned int connections;
117 };
118
119 typedef struct conn_entry_struct conn_entry_t;
120
121 #define DEF_CONN_POOL_SIZE 10
122
123 static pool *conn_pool = NULL;
124 static array_header *conn_cache = NULL;
125
126 /* sql_get_connection: walks the connection cache looking for the named
127 * connection. Returns NULL if unsuccessful, a pointer to the conn_entry_t
128 * if successful.
129 */
130 static conn_entry_t *sql_get_connection(const char *conn_name) {
131 register unsigned int i;
132
133 if (conn_name == NULL) {
134 errno = EINVAL;
135 return NULL;
136 }
137
138 for (i = 0; i < conn_cache->nelts; i++) {
139 conn_entry_t *entry;
140
141 entry = ((conn_entry_t **) conn_cache->elts)[i];
142 if (strcmp(conn_name, entry->name) == 0) {
143 return entry;
144 }
145 }
146
147 errno = ENOENT;
148 return NULL;
149 }
150
151 /* sql_add_connection: internal helper function to maintain a cache of
152 * connections. Since we expect the number of named connections to be small,
153 * simply use an array header to hold them. We don't allow duplicate
154 * connection names.
155 *
156 * Returns: NULL if the insertion was unsuccessful, a pointer to the
157 * conn_entry_t that was created if successful.
158 */
159 static void *sql_add_connection(pool *p, const char *name, db_conn_t *conn) {
160 conn_entry_t *entry = NULL;
161
162 if (p == NULL ||
163 name == NULL ||
164 conn == NULL) {
165 errno = EINVAL;
166 return NULL;
167 }
168
169 if (sql_get_connection(name) != NULL) {
170 errno = EEXIST;
171 return NULL;
172 }
173
174 entry = (conn_entry_t *) pcalloc(p, sizeof(conn_entry_t));
175 entry->name = pstrdup(p, name);
176 entry->data = conn;
177
178 *((conn_entry_t **) push_array(conn_cache)) = entry;
179 return entry;
180 }
181
182 /* sql_check_cmd: tests to make sure the cmd_rec is valid and is properly
183 * filled in. If not, it's grounds for the daemon to shutdown.
184 */
185 static void sql_check_cmd(cmd_rec *cmd, char *msg) {
186 if (cmd == NULL ||
187 cmd->tmp_pool == NULL) {
188 pr_log_pri(PR_LOG_ERR, MOD_SQL_POSTGRES_VERSION
189 ": '%s' was passed an invalid cmd_rec (internal bug); shutting down",
190 msg);
191 sql_log(DEBUG_WARN, "'%s' was passed an invalid cmd_rec (internal bug); "
192 "shutting down", msg);
193 pr_session_end(0);
194 }
195
196 return;
197 }
198
199 /*
200 * sql_timer_cb: when a timer goes off, this is the function that gets called.
201 * This function makes assumptions about the db_conn_t members.
202 */
203 static int sql_timer_cb(CALLBACK_FRAME) {
204 register unsigned int i;
205
206 for (i = 0; i < conn_cache->nelts; i++) {
207 conn_entry_t *entry = NULL;
208
209 entry = ((conn_entry_t **) conn_cache->elts)[i];
210 if ((unsigned long) entry->timer == p2) {
211 cmd_rec *cmd = NULL;
212
213 sql_log(DEBUG_INFO, "timer expired for connection '%s'", entry->name);
214 cmd = sql_make_cmd(conn_pool, 2, entry->name, "1");
215 cmd_close(cmd);
216 SQL_FREE_CMD(cmd);
217 entry->timer = 0;
218 }
219 }
220
221 return 0;
222 }
223
224 /* build_error: constructs a modret_t filled with error information;
225 * mod_sql_postgres calls this function and returns the resulting modret_t
226 * whenever a call to the database results in an error.
227 */
228 static modret_t *build_error(cmd_rec *cmd, db_conn_t *conn) {
229 if (conn == NULL) {
230 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
231 }
232
233 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
234 pstrdup(cmd->pool, PQerrorMessage(conn->postgres)));
235 }
236
237 /* build_data: both cmd_select and cmd_procedure potentially
238 * return data to mod_sql; this function builds a modret to return
239 * that data. This is Postgres specific; other backends may choose
240 * to do things differently.
241 */
242 static modret_t *build_data(cmd_rec *cmd, db_conn_t *conn) {
243 PGresult *result = NULL;
244 sql_data_t *sd = NULL;
245 char **data = NULL;
246 int idx = 0;
247 unsigned long row;
248
249 if (conn == NULL) {
250 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
251 }
252
253 result = conn->result;
254
255 sd = (sql_data_t *) pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
256 sd->rnum = (unsigned long) PQntuples(result);
257 sd->fnum = (unsigned long) PQnfields(result);
258
259 data = (char **) pcalloc(cmd->tmp_pool, sizeof(char *) *
260 ((sd->rnum * sd->fnum) + 1));
261
262 for (row = 0; row < sd->rnum; row++) {
263 unsigned long field;
264
265 for (field = 0; field < sd->fnum; field++) {
266 data[idx++] = pstrdup(cmd->tmp_pool, PQgetvalue(result, row, field));
267 }
268 }
269 data[idx] = NULL;
270
271 sd->data = data;
272
273 return mod_create_data(cmd, (void *) sd);
274 }
275
276 #ifdef PR_USE_NLS
277 static const char *get_postgres_encoding(const char *encoding) {
278
279 /* XXX Hack to deal with Postgres' incredibly broken behavior when
280 * handling the 'ASCII' encoding. Specifically, Postgres chokes on
281 * 'ASCII', and instead insists on calling it 'SQL_ASCII' (which, of
282 * course, is not even close to being a valid encoding name according
283 * to libiconv.)
284 *
285 * Treat 'ANSI_X3.4-1968' (another common name/alias for ASCII) the
286 * same; rename it to 'SQL_ASCII' for Postgres' benefit. And same for
287 * 'US-ASCII'.
288 */
289 if (strcasecmp(encoding, "ANSI_X3.4-1968") == 0 ||
290 strcasecmp(encoding, "ASCII") == 0 ||
291 strcasecmp(encoding, "US-ASCII") == 0) {
292 return "SQL_ASCII";
293 }
294
295 /* And other commonly used charsets for which Postgres has their own names. */
296
297 if (strcasecmp(encoding, "CP1251") == 0 ||
298 strcasecmp(encoding, "WINDOWS-1251") == 0) {
299 return "WIN1251";
300 }
301
302 if (strcasecmp(encoding, "KOI-8") == 0 ||
303 strcasecmp(encoding, "KOI8-R") == 0 ||
304 strcasecmp(encoding, "KOI8") == 0 ||
305 strcasecmp(encoding, "KOI8R") == 0) {
306 return "KOI";
307 }
308
309 if (strcasecmp(encoding, "CP866") == 0) {
310 return "WIN866";
311 }
312
313 if (strcasecmp(encoding, "ISO-8859-1") == 0) {
314 return "LATIN1";
315 }
316
317 if (strcasecmp(encoding, "ISO-8859-15") == 0) {
318 return "LATIN9";
319 }
320
321 if (strcasecmp(encoding, "EUC-CN") == 0 ||
322 strcasecmp(encoding, "EUCCN") == 0) {
323 return "EUC_CN";
324 }
325
326 if (strcasecmp(encoding, "EUC-JP") == 0 ||
327 strcasecmp(encoding, "EUCJP") == 0) {
328 return "EUC_JP";
329 }
330
331 if (strcasecmp(encoding, "EUC-KR") == 0 ||
332 strcasecmp(encoding, "EUCKR") == 0) {
333 return "EUC_KR";
334 }
335
336 if (strcasecmp(encoding, "EUC-TW") == 0 ||
337 strcasecmp(encoding, "EUCTW") == 0) {
338 return "EUC_TW";
339 }
340
341 if (strcasecmp(encoding, "SHIFT-JIS") == 0 ||
342 strcasecmp(encoding, "SHIFT_JIS") == 0) {
343 return "SJIS";
344 }
345
346 if (strcasecmp(encoding, "UTF8") == 0 ||
347 strcasecmp(encoding, "UTF-8") == 0 ||
348 strcasecmp(encoding, "UTF8-MAC") == 0) {
349 return "UTF8";
350 }
351
352 return encoding;
353 }
354 #endif
355
356 /*
357 * cmd_open: attempts to open a named connection to the database.
358 *
359 * Inputs:
360 * cmd->argv[0]: connection name
361 *
362 * Returns:
363 * either a properly filled error modret_t if a connection could not be
364 * opened, or a simple non-error modret_t.
365 *
366 * Notes:
367 * mod_sql depends on these semantics -- a backend should not open
368 * a connection unless mod_sql requests it, nor close one unless
369 * mod_sql requests it. Connection counting is *REQUIRED* for complete
370 * compatibility; a connection should not be closed unless the count
371 * reaches 0, and ideally will not need to be re-opened for counts > 1.
372 */
373 MODRET cmd_open(cmd_rec *cmd) {
374 conn_entry_t *entry = NULL;
375 db_conn_t *conn = NULL;
376 const char *server_version = NULL;
377 #if defined(PR_USE_NLS)
378 const char *encoding = NULL;
379 #endif /* PR_USE_NLS */
380
381 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_open");
382
383 sql_check_cmd(cmd, "cmd_open");
384
385 if (cmd->argc < 1) {
386 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
387 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
388 }
389
390 entry = sql_get_connection(cmd->argv[0]);
391 if (entry == NULL) {
392 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
393 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
394 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
395 }
396
397 conn = (db_conn_t *) entry->data;
398
399 /* if we're already open (connections > 0) increment connections
400 * reset our timer if we have one, and return HANDLED
401 */
402 if (entry->connections > 0) {
403 if (PQstatus(conn->postgres) == CONNECTION_OK) {
404 entry->connections++;
405
406 if (entry->timer) {
407 pr_timer_reset(entry->timer, &sql_postgres_module);
408 }
409
410 sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name,
411 entry->connections);
412 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
413 return PR_HANDLED(cmd);
414
415 } else {
416 char *reason;
417 size_t reason_len;
418
419 /* Unless we've been told not to reconnect, try to reconnect now.
420 * We only try once; if it fails, we return an error.
421 */
422 if (!(pr_sql_opts & SQL_OPT_NO_RECONNECT)) {
423 PQreset(conn->postgres);
424
425 if (PQstatus(conn->postgres) == CONNECTION_OK) {
426 entry->connections++;
427
428 if (entry->timer) {
429 pr_timer_reset(entry->timer, &sql_postgres_module);
430 }
431
432 sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name,
433 entry->connections);
434 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
435 return PR_HANDLED(cmd);
436 }
437 }
438
439 reason = PQerrorMessage(conn->postgres);
440 reason_len = strlen(reason);
441
442 /* Postgres might give us an empty string as the reason; not helpful. */
443 if (reason_len == 0) {
444 reason = "(unknown)";
445 reason_len = strlen(reason);
446 }
447
448 /* The error message returned by Postgres is usually appended with
449 * a newline. Let's prettify it by removing the newline. Note
450 * that yes, we are overwriting the pointer given to us by Postgres,
451 * but it's OK. The Postgres docs say that we're not supposed to
452 * free the memory associated with the returned string anyway.
453 */
454 reason = pstrdup(session.pool, reason);
455
456 if (reason[reason_len-1] == '\n') {
457 reason[reason_len-1] = '\0';
458 }
459
460 sql_log(DEBUG_INFO, "lost connection to database: %s", reason);
461
462 entry->connections = 0;
463 if (entry->timer) {
464 pr_timer_remove(entry->timer, &sql_postgres_module);
465 entry->timer = 0;
466 }
467
468 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
469 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
470 "lost connection to database");
471 }
472 }
473
474 /* make sure we have a new conn struct */
475 conn->postgres = PQconnectdb(conn->connect_string);
476 if (PQstatus(conn->postgres) == CONNECTION_BAD) {
477 modret_t *mr = NULL;
478
479 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
480 mr = build_error(cmd, conn);
481
482 /* Since we failed to connect here, avoid a memory leak by freeing up the
483 * postgres conn struct.
484 */
485 PQfinish(conn->postgres);
486 conn->postgres = NULL;
487
488 return mr;
489 }
490
491 #if defined(PG_VERSION_STR)
492 sql_log(DEBUG_FUNC, "Postgres client: %s", PG_VERSION_STR);
493 #endif
494
495 server_version = PQparameterStatus(conn->postgres, "server_version");
496 if (server_version != NULL) {
497 sql_log(DEBUG_FUNC, "Postgres server version: %s", server_version);
498 }
499
500 #if defined(PR_USE_NLS)
501 encoding = pr_encode_get_encoding();
502 if (encoding != NULL) {
503 encoding = get_postgres_encoding(pr_encode_get_encoding());
504
505 } else {
506 pr_trace_msg(trace_channel, 3, "no encoding found (%s), using 'UTF8'",
507 strerror(errno));
508
509 encoding = "UTF8";
510 }
511
512 /* Configure the connection for the current local character set. */
513 if (PQsetClientEncoding(conn->postgres, encoding) < 0) {
514 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
515 return build_error(cmd, conn);
516 }
517
518 sql_log(DEBUG_FUNC, "Postgres connection character set now '%s' "
519 "(from '%s')", pg_encoding_to_char(PQclientEncoding(conn->postgres)),
520 encoding);
521 #endif /* !PR_USE_NLS */
522
523 #if defined(HAVE_POSTGRES_PQGETSSL)
524 if (PQgetssl(conn->postgres) != NULL) {
525 # if defined(PR_USE_OPENSSL)
526 SSL *ssl;
527
528 ssl = PQgetssl(conn->postgres);
529 sql_log(DEBUG_FUNC, "%s", "Postgres SSL connection: true");
530 sql_log(DEBUG_FUNC, "%s", "Postgres SSL cipher: %s",
531 SSL_get_cipher_name(ssl));
532 # else
533 sql_log(DEBUG_FUNC, "%s", "Postgres SSL connection: true");
534 # endif /* PR_USE_OPENSSL */
535 } else {
536 sql_log(DEBUG_FUNC, "%s", "Postgres SSL connection: false");
537 }
538 #endif /* HAVE_POSTGRES_PQGETSSL */
539
540 /* bump connections */
541 entry->connections++;
542
543 if (pr_sql_conn_policy == SQL_CONN_POLICY_PERSESSION) {
544 /* If the connection policy is PERSESSION... */
545 if (entry->connections == 1) {
546 /* ...and we are actually opening the first connection to the database;
547 * we want to make sure this connection stays open, after this first use
548 * (as per Bug#3290). To do this, we re-bump the connection count.
549 */
550 entry->connections++;
551 }
552
553 } else if (entry->ttl > 0) {
554 /* Set up our timer if necessary */
555
556 entry->timer = pr_timer_add(entry->ttl, -1, &sql_postgres_module,
557 sql_timer_cb, "postgres connection ttl");
558 sql_log(DEBUG_INFO, "connection '%s' - %d second timer started",
559 entry->name, entry->ttl);
560
561 /* Timed connections get re-bumped so they don't go away when cmd_close
562 * is called.
563 */
564 entry->connections++;
565 }
566
567 /* return HANDLED */
568 sql_log(DEBUG_INFO, "connection '%s' opened", entry->name);
569 sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name,
570 entry->connections);
571 pr_event_generate("mod_sql.db.connection-opened", &sql_postgres_module);
572
573 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
574 return PR_HANDLED(cmd);
575 }
576
577 /*
578 * cmd_close: attempts to close the named connection.
579 *
580 * Inputs:
581 * cmd->argv[0]: connection name
582 * Optional:
583 * cmd->argv[1]: close immediately
584 *
585 * Returns:
586 * either a properly filled error modret_t if a connection could not be
587 * closed, or a simple non-error modret_t. For the case of mod_sql_postgres,
588 * there are no error codes returned by the close call; other backends
589 * may be able to return a useful error message.
590 *
591 * Notes:
592 * mod_sql depends on these semantics -- a backend should not open
593 * a connection unless mod_sql requests it, nor close one unless
594 * mod_sql requests it. Connection counting is *REQUIRED* for complete
595 * compatibility; a connection should not be closed unless the count
596 * reaches 0, and should not need to be re-opened for counts > 1.
597 *
598 * If argv[1] exists and is not NULL, the connection should be immediately
599 * closed and the connection count should be reset to 0.
600 */
601 MODRET cmd_close(cmd_rec *cmd) {
602 conn_entry_t *entry = NULL;
603 db_conn_t *conn = NULL;
604
605 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_close");
606
607 sql_check_cmd(cmd, "cmd_close");
608
609 if (cmd->argc < 1 ||
610 cmd->argc > 2) {
611 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_close");
612 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
613 }
614
615 entry = sql_get_connection(cmd->argv[0]);
616 if (entry == NULL) {
617 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_close");
618 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
619 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
620 }
621
622 conn = (db_conn_t *) entry->data;
623
624 /* if we're closed already (connections == 0) return HANDLED */
625 if (entry->connections == 0) {
626 sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name,
627 entry->connections);
628
629 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_close");
630 return PR_HANDLED(cmd);
631 }
632
633 /* decrement connections. If our count is 0 or we received a second arg
634 * close the connection, explicitly set the counter to 0, and remove any
635 * timers.
636 */
637 if (((--entry->connections) == 0) || ((cmd->argc == 2) && (cmd->argv[1]))) {
638 if (conn->postgres != NULL) {
639 PQfinish(conn->postgres);
640 conn->postgres = NULL;
641 }
642 entry->connections = 0;
643
644 if (entry->timer) {
645 pr_timer_remove(entry->timer, &sql_postgres_module);
646 entry->timer = 0;
647 sql_log(DEBUG_INFO, "connection '%s' - timer stopped", entry->name);
648 }
649
650 sql_log(DEBUG_INFO, "connection '%s' closed", entry->name);
651 pr_event_generate("mod_sql.db.connection-closed", &sql_postgres_module);
652 }
653
654 sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name,
655 entry->connections);
656 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_close");
657
658 return PR_HANDLED(cmd);
659 }
660
661 /* cmd_defineconnection: takes all information about a database
662 * connection and stores it for later use.
663 *
664 * Inputs:
665 * cmd->argv[0]: connection name
666 * cmd->argv[1]: username portion of the SQLConnectInfo directive
667 * cmd->argv[2]: password portion of the SQLConnectInfo directive
668 * cmd->argv[3]: info portion of the SQLConnectInfo directive
669 *
670 * Optional:
671 * cmd->argv[4]: time-to-live in seconds
672 * cmd->argv[5]: SSL client cert file
673 * cmd->argv[6]: SSL client key file
674 * cmd->argv[7]: SSL CA file
675 * cmd->argv[8]: SSL CA directory
676 * cmd->argv[9]: SSL ciphers
677 *
678 * Returns:
679 * either a properly filled error modret_t if the connection could not
680 * defined, or a simple non-error modret_t.
681 *
682 * Notes:
683 * time-to-live is the length of time to allow a connection to remain unused;
684 * once that amount of time has passed, a connection should be closed and
685 * it's connection count should be reduced to 0. If ttl is 0, or ttl is not
686 * a number or ttl is negative, the connection will be assumed to have no
687 * associated timer.
688 */
689 MODRET cmd_defineconnection(cmd_rec *cmd) {
690 char *have_host = NULL, *have_port = NULL, *info = NULL, *name = NULL;
691 const char *db = NULL, *host = NULL, *port = NULL, *connect_string = NULL;
692 const char *ssl_cert_file = NULL, *ssl_key_file = NULL, *ssl_ca_file = NULL;
693 const char *ssl_ciphers = NULL;
694 conn_entry_t *entry = NULL;
695 db_conn_t *conn = NULL;
696
697 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_defineconnection");
698
699 sql_check_cmd(cmd, "cmd_defineconnection");
700
701 if (cmd->argc < 4 ||
702 cmd->argc > 10 ||
703 !cmd->argv[0]) {
704 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_defineconnection");
705 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
706 }
707
708 if (conn_pool == NULL) {
709 pr_log_pri(PR_LOG_WARNING, "WARNING: the mod_sql_postgres module has not "
710 "been properly initialized. Please make sure your --with-modules "
711 "configure option lists mod_sql *before* mod_sql_postgres, and "
712 "recompile.");
713
714 sql_log(DEBUG_FUNC, "%s", "The mod_sql_postgres module has not been "
715 "properly initialized. Please make sure your --with-modules configure "
716 "option lists mod_sql *before* mod_sql_postgres, and recompile.");
717 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_defineconnection");
718
719 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "uninitialized module");
720 }
721
722 conn = (db_conn_t *) pcalloc(conn_pool, sizeof(db_conn_t));
723 name = pstrdup(conn_pool, cmd->argv[0]);
724 conn->user = pstrdup(conn_pool, cmd->argv[1]);
725 conn->pass = pstrdup(conn_pool, cmd->argv[2]);
726
727 info = cmd->argv[3];
728
729 db = pstrdup(cmd->tmp_pool, info);
730
731 have_host = strchr(db, '@');
732 have_port = strchr(db, ':');
733
734 /* If have_port, parse it, otherwise default it.
735 * If have_port, set it to '\0'
736 *
737 * If have_host, parse it, otherwise default it.
738 * If have_host, set it to '\0'
739 */
740
741 if (have_port != NULL) {
742 port = have_port + 1;
743 *have_port = '\0';
744
745 } else {
746 port = _POSTGRES_PORT;
747 }
748
749 if (have_host) {
750 host = have_host + 1;
751 *have_host = '\0';
752
753 } else {
754 host = "localhost";
755 }
756
757 /* SSL parameters, if configured. */
758 if (cmd->argc >= 6) {
759 ssl_cert_file = cmd->argv[5];
760 }
761
762 if (cmd->argc >= 7) {
763 ssl_key_file = cmd->argv[6];
764 }
765
766 if (cmd->argc >= 8) {
767 ssl_ca_file = cmd->argv[7];
768 }
769
770 /* Ignore the ssl_ca_dir parameter, for now. */
771 if (cmd->argc >= 10) {
772 ssl_ciphers = cmd->argv[9];
773 }
774
775 conn->host = pstrdup(conn_pool, host);
776 conn->db = pstrdup(conn_pool, db);
777 conn->port = pstrdup(conn_pool, port);
778 conn->ssl_cert_file = pstrdup(conn_pool, ssl_cert_file);
779 conn->ssl_key_file = pstrdup(conn_pool, ssl_key_file);
780 conn->ssl_ca_file = pstrdup(conn_pool, ssl_ca_file);
781
782 /* Set up the connect string the way postgres likes it */
783 connect_string = pstrcat(cmd->tmp_pool, "host='", conn->host, "' port='",
784 conn->port,"' dbname='", conn->db, "' user='", conn->user,"' password='",
785 conn->pass, "'", NULL);
786
787 /* XXX Should we set the sslmode keyword to "prefer" explicitly, or
788 * "require", when SSL parameters have been set?
789 */
790
791 if (ssl_ciphers != NULL ||
792 ssl_cert_file != NULL ||
793 ssl_key_file != NULL ||
794 ssl_ca_file != NULL) {
795 connect_string = pstrcat(cmd->tmp_pool, connect_string,
796 " sslmode='prefer'", NULL);
797 }
798
799 if (conn->ssl_cert_file != NULL) {
800 connect_string = pstrcat(cmd->tmp_pool, connect_string, " sslcert='",
801 conn->ssl_cert_file, "'", NULL);
802 }
803
804 if (conn->ssl_key_file != NULL) {
805 connect_string = pstrcat(cmd->tmp_pool, connect_string, " sslkey='",
806 conn->ssl_key_file, "'", NULL);
807 }
808
809 if (conn->ssl_ca_file != NULL) {
810 connect_string = pstrcat(cmd->tmp_pool, connect_string, " sslrootcert='",
811 conn->ssl_ca_file, "'", NULL);
812 }
813
814 pr_trace_msg(trace_channel, 17, "using connect string '%s'", connect_string);
815 conn->connect_string = pstrdup(conn_pool, connect_string);
816
817 /* insert the new conn_info into the connection hash */
818 entry = sql_add_connection(conn_pool, name, (void *) conn);
819 if (entry == NULL &&
820 errno == EEXIST) {
821 /* Log only connections named other than "default", for debugging
822 * misconfigurations with multiple different SQLNamedConnectInfo
823 * directives using the same name.
824 */
825 if (strcmp(name, "default") != 0) {
826 sql_log(DEBUG_FUNC, "named connection '%s' already exists", name);
827 }
828
829 entry = sql_get_connection(name);
830 }
831
832 if (entry == NULL) {
833 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_defineconnection");
834 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
835 "error adding named connection");
836 }
837
838 if (cmd->argc >= 5) {
839 entry->ttl = (int) strtol(cmd->argv[4], (char **) NULL, 10);
840 if (entry->ttl >= 1) {
841 pr_sql_conn_policy = SQL_CONN_POLICY_TIMER;
842
843 } else {
844 entry->ttl = 0;
845 }
846 }
847
848 entry->timer = 0;
849 entry->connections = 0;
850
851 sql_log(DEBUG_INFO, " name: '%s'", entry->name);
852 sql_log(DEBUG_INFO, " user: '%s'", conn->user);
853 sql_log(DEBUG_INFO, " host: '%s'", conn->host);
854 sql_log(DEBUG_INFO, " db: '%s'", conn->db);
855 sql_log(DEBUG_INFO, " port: '%s'", conn->port);
856 sql_log(DEBUG_INFO, " ttl: '%d'", entry->ttl);
857
858 if (conn->ssl_cert_file != NULL) {
859 sql_log(DEBUG_INFO, " ssl: client cert = '%s'", conn->ssl_cert_file);
860 }
861
862 if (conn->ssl_key_file != NULL) {
863 sql_log(DEBUG_INFO, " ssl: client key = '%s'", conn->ssl_key_file);
864 }
865
866 if (conn->ssl_ca_file != NULL) {
867 sql_log(DEBUG_INFO, " ssl: CA file = '%s'", conn->ssl_ca_file);
868 }
869
870 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_defineconnection");
871 return PR_HANDLED(cmd);
872 }
873
874 /*
875 * cmd_exit: closes all open connections.
876 *
877 * Inputs:
878 * None
879 *
880 * Returns:
881 * A simple non-error modret_t.
882 */
883 static modret_t *cmd_exit(cmd_rec *cmd) {
884 register unsigned int i = 0;
885
886 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_exit");
887
888 for (i = 0; i < conn_cache->nelts; i++) {
889 conn_entry_t *entry;
890
891 entry = ((conn_entry_t **) conn_cache->elts)[i];
892 if (entry->connections > 0) {
893 cmd_rec *close_cmd;
894
895 close_cmd = sql_make_cmd(conn_pool, 2, entry->name, "1");
896 cmd_close(close_cmd);
897 destroy_pool(close_cmd->pool);
898 }
899 }
900
901 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_exit");
902
903 return PR_HANDLED(cmd);
904 }
905
906 /*
907 * cmd_select: executes a SELECT query. properly constructing the query
908 * based on the inputs. See mod_sql.h for the definition of the _sql_data
909 * structure which is used to return the result data.
910 *
911 * cmd_select takes either exactly two inputs, or more than two. If only
912 * two inputs are given, the second is a monolithic query string. See
913 * the examples below.
914 *
915 * Inputs:
916 * cmd->argv[0]: connection name
917 * cmd->argv[1]: table
918 * cmd->argv[2]: select string
919 * Optional:
920 * cmd->argv[3]: where clause
921 * cmd->argv[4]: requested number of return rows (LIMIT)
922 *
923 * etc. : other options, such as "GROUP BY", "ORDER BY",
924 * and "DISTINCT" will start at cmd->arg[5]. All
925 * backends MUST support 'DISTINCT', the other
926 * arguments are optional (but encouraged).
927 *
928 * Returns:
929 * either a properly filled error modret_t if the select failed, or a
930 * modret_t with the result data filled in.
931 *
932 * Example:
933 * These are example queries that would be executed for Postgres; other
934 * backends will have different SQL syntax.
935 *
936 * argv[] = "default","user","userid, count", "userid='aah'","2"
937 * query = "SELECT userid, count FROM user WHERE userid='aah' LIMIT 2"
938 *
939 * argv[] = "default","usr1, usr2","usr1.foo, usr2.bar"
940 * query = "SELECT usr1.foo, usr2.bar FROM usr1, usr2"
941 *
942 * argv[] = "default","usr1","foo",,,"DISTINCT"
943 * query = "SELECT DISTINCT foo FROM usr1"
944 *
945 * argv[] = "default","bar FROM usr1 WHERE tmp=1 ORDER BY bar"
946 * query = "SELECT bar FROM usr1 WHERE tmp=1 ORDER BY bar"
947 *
948 * Notes:
949 * certain selects could return huge amounts of data. do whatever is
950 * possible to minimize the amount of data copying here.
951 */
952 MODRET cmd_select(cmd_rec *cmd) {
953 conn_entry_t *entry = NULL;
954 db_conn_t *conn = NULL;
955 modret_t *cmr = NULL;
956 modret_t *dmr = NULL;
957 char *query = NULL;
958 cmd_rec *close_cmd;
959
960 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_select");
961
962 sql_check_cmd(cmd, "cmd_select");
963
964 if (cmd->argc < 2) {
965 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_select");
966 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
967 }
968
969 entry = sql_get_connection(cmd->argv[0]);
970 if (entry == NULL) {
971 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_select");
972 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
973 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
974 }
975
976 conn = (db_conn_t *) entry->data;
977
978 cmr = cmd_open(cmd);
979 if (MODRET_ERROR(cmr)) {
980 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_select");
981 return cmr;
982 }
983
984 /* construct the query string */
985 if (cmd->argc == 2) {
986 query = pstrcat(cmd->tmp_pool, "SELECT ", cmd->argv[1], NULL);
987
988 } else {
989 query = pstrcat(cmd->tmp_pool, cmd->argv[2], " FROM ", cmd->argv[1], NULL);
990 if (cmd->argc > 3 &&
991 cmd->argv[3]) {
992 query = pstrcat(cmd->tmp_pool, query, " WHERE ", cmd->argv[3], NULL);
993 }
994
995 if (cmd->argc > 4 &&
996 cmd->argv[4]) {
997 query = pstrcat(cmd->tmp_pool, query, " LIMIT ", cmd->argv[4], NULL);
998 }
999
1000 if (cmd->argc > 5) {
1001 register unsigned int i;
1002
1003 /* Handle the optional arguments -- they're rare, so in this case
1004 * we'll play with the already constructed query string, but in
1005 * general we should probably take optional arguments into account
1006 * and put the query string together later once we know what they are.
1007 */
1008
1009 for (i = 5; i < cmd->argc; i++) {
1010 if (cmd->argv[i] != NULL &&
1011 strcasecmp("DISTINCT", cmd->argv[i]) == 0) {
1012 query = pstrcat(cmd->tmp_pool, "DISTINCT ", query, NULL);
1013 }
1014 }
1015 }
1016
1017 query = pstrcat(cmd->tmp_pool, "SELECT ", query, NULL);
1018 }
1019
1020 /* log the query string */
1021 sql_log(DEBUG_INFO, "query \"%s\"", query);
1022
1023 /* perform the query. if it doesn't work, log the error, close the
1024 * connection then return the error from the query processing.
1025 */
1026 if (!(conn->result = PQexec(conn->postgres, query)) ||
1027 (PQresultStatus(conn->result) != PGRES_TUPLES_OK)) {
1028 dmr = build_error(cmd, conn);
1029
1030 if (conn->result != NULL) {
1031 PQclear(conn->result);
1032 }
1033
1034 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1035 cmd_close(close_cmd);
1036 SQL_FREE_CMD(close_cmd);
1037
1038 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_select");
1039 return dmr;
1040 }
1041
1042 /* get the data. if it doesn't work, log the error, close the
1043 * connection then return the error from the data processing.
1044 */
1045 dmr = build_data(cmd, conn);
1046
1047 PQclear(conn->result);
1048
1049 if (MODRET_ERROR(dmr)) {
1050 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_select");
1051
1052 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1053 cmd_close(close_cmd);
1054 SQL_FREE_CMD(close_cmd);
1055
1056 return dmr;
1057 }
1058
1059 /* close the connection, return the data. */
1060 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1061 cmd_close(close_cmd);
1062 SQL_FREE_CMD(close_cmd);
1063
1064 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_select");
1065 return dmr;
1066 }
1067
1068 /*
1069 * cmd_insert: executes an INSERT query, properly constructing the query
1070 * based on the inputs.
1071 *
1072 * cmd_insert takes either exactly two inputs, or exactly four. If only
1073 * two inputs are given, the second is a monolithic query string. See
1074 * the examples below.
1075 *
1076 * Inputs:
1077 * cmd->argv[0]: connection name
1078 * cmd->argv[1]: table
1079 * cmd->argv[2]: field string
1080 * cmd->argv[3]: value string
1081 *
1082 * Returns:
1083 * either a properly filled error modret_t if the insert failed, or a
1084 * simple non-error modret_t.
1085 *
1086 * Example:
1087 * These are example queries that would be executed for Postgres; other
1088 * backends will have different SQL syntax.
1089 *
1090 * argv[] = "default","log","userid, date, count", "'aah', now(), 2"
1091 * query = "INSERT INTO log (userid, date, count) VALUES ('aah', now(), 2)"
1092 *
1093 * argv[] = "default"," INTO foo VALUES ('do','re','mi','fa')"
1094 * query = "INSERT INTO foo VALUES ('do','re','mi','fa')"
1095 *
1096 * Notes:
1097 * none
1098 */
1099 MODRET cmd_insert(cmd_rec *cmd) {
1100 conn_entry_t *entry = NULL;
1101 db_conn_t *conn = NULL;
1102 modret_t *cmr = NULL;
1103 modret_t *dmr = NULL;
1104 char *query = NULL;
1105 cmd_rec *close_cmd;
1106
1107 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_insert");
1108
1109 sql_check_cmd(cmd, "cmd_insert");
1110
1111 if (cmd->argc != 2 &&
1112 cmd->argc != 4) {
1113 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_insert");
1114 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
1115 }
1116
1117 entry = sql_get_connection(cmd->argv[0]);
1118 if (entry == NULL) {
1119 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_insert");
1120 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
1121 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
1122 }
1123
1124 conn = (db_conn_t *) entry->data;
1125
1126 cmr = cmd_open(cmd);
1127 if (MODRET_ERROR(cmr)) {
1128 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_insert");
1129 return cmr;
1130 }
1131
1132 /* construct the query string */
1133 if (cmd->argc == 2) {
1134 query = pstrcat(cmd->tmp_pool, "INSERT ", cmd->argv[1], NULL);
1135
1136 } else {
1137 query = pstrcat(cmd->tmp_pool, "INSERT INTO ", cmd->argv[1], " (",
1138 cmd->argv[2], ") VALUES (", cmd->argv[3], ")", NULL);
1139 }
1140
1141 sql_log(DEBUG_INFO, "query \"%s\"", query);
1142
1143 /* perform the query. if it doesn't work, log the error, close the
1144 * connection then return the error from the query processing.
1145 */
1146 if (!(conn->result = PQexec(conn->postgres, query)) ||
1147 (PQresultStatus(conn->result) != PGRES_COMMAND_OK)) {
1148 dmr = build_error(cmd, conn);
1149
1150 if (conn->result != NULL) {
1151 PQclear(conn->result);
1152 }
1153
1154 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1155 cmd_close(close_cmd);
1156 SQL_FREE_CMD(close_cmd);
1157
1158 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_insert");
1159 return dmr;
1160 }
1161
1162 PQclear(conn->result);
1163
1164 /* close the connection and return HANDLED. */
1165 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1166 cmd_close(close_cmd);
1167 SQL_FREE_CMD(close_cmd);
1168
1169 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_insert");
1170 return PR_HANDLED(cmd);
1171 }
1172
1173 /*
1174 * cmd_update: executes an UPDATE query, properly constructing the query
1175 * based on the inputs.
1176 *
1177 * cmd_update takes either exactly two, three, or four inputs. If only
1178 * two inputs are given, the second is a monolithic query string. See
1179 * the examples below.
1180 *
1181 * Inputs:
1182 * cmd->argv[0]: connection name
1183 * cmd->argv[1]: table
1184 * cmd->argv[2]: update string
1185 * Optional:
1186 * cmd->argv[3]: where string
1187 *
1188 * Returns:
1189 * either a properly filled error modret_t if the update failed, or a
1190 * simple non-error modret_t.
1191 *
1192 * Example:
1193 * These are example queries that would be executed for Postgres; other
1194 * backends will have different SQL syntax.
1195 *
1196 * argv[] = "default","user","count=count+1", "userid='joesmith'"
1197 * query = "UPDATE user SET count=count+1 WHERE userid='joesmith'"
1198 *
1199 * Notes:
1200 * argv[3] is optional -- it may be NULL, or it may not exist at all.
1201 * make sure this is handled correctly.
1202 */
1203 MODRET cmd_update(cmd_rec *cmd) {
1204 conn_entry_t *entry = NULL;
1205 db_conn_t *conn = NULL;
1206 modret_t *cmr = NULL;
1207 modret_t *dmr = NULL;
1208 char *query = NULL;
1209 cmd_rec *close_cmd;
1210
1211 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_update");
1212
1213 sql_check_cmd(cmd, "cmd_update");
1214
1215 if (cmd->argc < 2 ||
1216 cmd->argc > 4) {
1217 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_update");
1218 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
1219 }
1220
1221 entry = sql_get_connection(cmd->argv[0]);
1222 if (entry == NULL) {
1223 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_update");
1224 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
1225 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
1226 }
1227
1228 conn = (db_conn_t *) entry->data;
1229
1230 cmr = cmd_open(cmd);
1231 if (MODRET_ERROR(cmr)) {
1232 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_update");
1233 return cmr;
1234 }
1235
1236 if (cmd->argc == 2) {
1237 query = pstrcat(cmd->tmp_pool, "UPDATE ", cmd->argv[1], NULL);
1238
1239 } else {
1240 query = pstrcat(cmd->tmp_pool, "UPDATE ", cmd->argv[1], " SET ",
1241 cmd->argv[2], NULL);
1242 if (cmd->argc > 3 &&
1243 cmd->argv[3]) {
1244 query = pstrcat(cmd->tmp_pool, query, " WHERE ", cmd->argv[3], NULL);
1245 }
1246 }
1247
1248 sql_log(DEBUG_INFO, "query \"%s\"", query);
1249
1250 /* perform the query. if it doesn't work, log the error, close the
1251 * connection then return the error from the query processing.
1252 */
1253 if (!(conn->result = PQexec(conn->postgres, query)) ||
1254 (PQresultStatus(conn->result) != PGRES_COMMAND_OK)) {
1255 dmr = build_error(cmd, conn);
1256
1257 if (conn->result != NULL) {
1258 PQclear(conn->result);
1259 }
1260
1261 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1262 cmd_close(close_cmd);
1263 SQL_FREE_CMD(close_cmd);
1264
1265 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_update");
1266 return dmr;
1267 }
1268
1269 PQclear(conn->result);
1270
1271 /* close the connection, return HANDLED. */
1272 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1273 cmd_close(close_cmd);
1274 SQL_FREE_CMD(close_cmd);
1275
1276 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_update");
1277 return PR_HANDLED(cmd);
1278 }
1279
1280 /*
1281 * cmd_procedure: executes a stored procedure.
1282 *
1283 * Inputs:
1284 * cmd->argv[0]: connection name
1285 * cmd->argv[1]: procedure name
1286 * cmd->argv[2]: procedure string
1287 *
1288 * Returns:
1289 * either a properly filled error modret_t if the procedure failed in
1290 * some way, or a modret_t with the result data. If a procedure
1291 * returns data, it should be returned in the same way as cmd_select.
1292 *
1293 * Notes:
1294 * not every backend will support stored procedures. Backends which do
1295 * not support stored procedures should return an error with a descriptive
1296 * error message (something like 'backend does not support procedures').
1297 */
1298 MODRET cmd_procedure(cmd_rec *cmd) {
1299 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_procedure");
1300
1301 sql_check_cmd(cmd, "cmd_procedure");
1302
1303 if (cmd->argc != 3) {
1304 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_procedure");
1305 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
1306 }
1307
1308 /* PostgreSQL supports procedures, but the backend doesn't. */
1309
1310 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_procedure");
1311
1312 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
1313 "backend does not support procedures");
1314 }
1315
1316 /*
1317 * cmd_query: executes a freeform query string, with no syntax checking.
1318 *
1319 * cmd_query takes exactly two inputs, the connection and the query string.
1320 *
1321 * Inputs:
1322 * cmd->argv[0]: connection name
1323 * cmd->argv[1]: query string
1324 *
1325 * Returns:
1326 * depending on the query type, returns a modret_t with data, a non-error
1327 * modret_t, or a properly filled error modret_t if the query failed.
1328 *
1329 * Example:
1330 * None. The query should be passed directly to the backend database.
1331 *
1332 * Notes:
1333 * None.
1334 */
1335 MODRET cmd_query(cmd_rec *cmd) {
1336 conn_entry_t *entry = NULL;
1337 db_conn_t *conn = NULL;
1338 modret_t *cmr = NULL;
1339 modret_t *dmr = NULL;
1340 char *query = NULL;
1341 cmd_rec *close_cmd;
1342
1343 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_query");
1344
1345 sql_check_cmd(cmd, "cmd_query");
1346
1347 if (cmd->argc != 2) {
1348 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_query");
1349 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
1350 }
1351
1352 entry = sql_get_connection(cmd->argv[0]);
1353 if (entry == NULL) {
1354 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_query");
1355 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
1356 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
1357 }
1358
1359 conn = (db_conn_t *) entry->data;
1360
1361 cmr = cmd_open(cmd);
1362 if (MODRET_ERROR(cmr)) {
1363 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_query");
1364 return cmr;
1365 }
1366
1367 query = pstrcat(cmd->tmp_pool, cmd->argv[1], NULL);
1368
1369 sql_log(DEBUG_INFO, "query \"%s\"", query);
1370
1371 /* perform the query. if it doesn't work, log the error, close the
1372 * connection then return the error from the query processing.
1373 */
1374 if (!(conn->result = PQexec(conn->postgres, query)) ||
1375 ((PQresultStatus(conn->result) != PGRES_TUPLES_OK) &&
1376 (PQresultStatus(conn->result) != PGRES_COMMAND_OK))) {
1377 dmr = build_error(cmd, conn);
1378
1379 if (conn->result != NULL) {
1380 PQclear(conn->result);
1381 }
1382
1383 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1384 cmd_close(close_cmd);
1385 SQL_FREE_CMD(close_cmd);
1386
1387 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_select");
1388 return dmr;
1389 }
1390
1391 /* get data if necessary. if it doesn't work, log the error, close the
1392 * connection then return the error from the data processing.
1393 */
1394
1395 if (PQresultStatus(conn->result) == PGRES_TUPLES_OK) {
1396 dmr = build_data(cmd, conn);
1397
1398 PQclear(conn->result);
1399
1400 if (MODRET_ERROR(dmr)) {
1401 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_query");
1402 }
1403
1404 } else {
1405 dmr = PR_HANDLED(cmd);
1406 }
1407
1408 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1409 cmd_close(close_cmd);
1410 SQL_FREE_CMD(close_cmd);
1411
1412 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_query");
1413 return dmr;
1414 }
1415
1416 /*
1417 * cmd_escapestring: certain strings sent to a database should be properly
1418 * escaped -- for instance, quotes need to be escaped to insure that
1419 * a query string is properly formatted. cmd_escapestring does whatever
1420 * is necessary to escape the special characters in a string.
1421 *
1422 * Inputs:
1423 * cmd->argv[0]: connection name
1424 * cmd->argv[1]: string to escape
1425 *
1426 * Returns:
1427 * this command CANNOT fail. The return string is null-terminated and
1428 * stored in the data field of the modret_t structure.
1429 *
1430 * Notes:
1431 * Different languages may escape different characters in different ways.
1432 * A backend should handle this correctly, where possible. If there is
1433 * no client library function to do the string conversion, it is strongly
1434 * recommended that the backend module writer do whatever is necessry (read
1435 * the database documentation and figure it out) to do the conversion
1436 * themselves in this function.
1437 *
1438 * A backend MUST supply a working escapestring implementation. Simply
1439 * copying the data from argv[0] into the data field of the modret allows
1440 * for possible SQL injection attacks when this backend is used.
1441 */
1442 MODRET cmd_escapestring(cmd_rec *cmd) {
1443 conn_entry_t *entry = NULL;
1444 db_conn_t *conn = NULL;
1445 modret_t *cmr = NULL;
1446 char *unescaped = NULL;
1447 char *escaped = NULL;
1448 cmd_rec *close_cmd;
1449 size_t unescaped_len = 0;
1450 #ifdef HAVE_POSTGRES_PQESCAPESTRINGCONN
1451 int pgerr = 0;
1452 #endif
1453
1454 sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_escapestring");
1455
1456 sql_check_cmd(cmd, "cmd_escapestring");
1457
1458 if (cmd->argc != 2) {
1459 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
1460 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request");
1461 }
1462
1463 entry = sql_get_connection(cmd->argv[0]);
1464 if (entry == NULL) {
1465 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
1466 return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
1467 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
1468 }
1469
1470 conn = (db_conn_t *) entry->data;
1471
1472 /* Make sure the connection is open. */
1473 cmr = cmd_open(cmd);
1474 if (MODRET_ERROR(cmr)) {
1475 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
1476 return cmr;
1477 }
1478
1479 unescaped = cmd->argv[1];
1480 unescaped_len = strlen(unescaped);
1481 escaped = (char *) pcalloc(cmd->tmp_pool, sizeof(char) *
1482 (unescaped_len * 2) + 1);
1483
1484 #ifdef HAVE_POSTGRES_PQESCAPESTRINGCONN
1485 PQescapeStringConn(conn->postgres, escaped, unescaped, unescaped_len, &pgerr);
1486 if (pgerr != 0) {
1487 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
1488 return build_error(cmd, conn);
1489 }
1490 #else
1491 PQescapeString(escaped, unescaped, unescaped_len);
1492 #endif
1493
1494 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1495 cmd_close(close_cmd);
1496 SQL_FREE_CMD(close_cmd);
1497
1498 sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_escapestring");
1499 return mod_create_data(cmd, (void *) escaped);
1500 }
1501
1502 /*
1503 * cmd_identify: returns API information and an identification string for
1504 * the backend handler. mod_sql will call this at initialization and
1505 * display the identification string. The API version information is
1506 * used by mod_sql to identify available command handlers.
1507 *
1508 * Inputs:
1509 * None. The cmd->tmp_pool can be used to construct the return data, but
1510 * do not depend on any other portion of the cmd_rec to be useful in any way.
1511 *
1512 * Returns:
1513 * A sql_data_t of *exactly* this form:
1514 * sql_data_t->rnum = 1;
1515 * sql_data_t->fnum = 2;
1516 * sql_data_t->data[0] = "identification string"
1517 * sql_data_t->data[0] = "API version"
1518 *
1519 * Notes:
1520 * See mod_sql.h for currently accepted APIs.
1521 */
1522 MODRET cmd_identify(cmd_rec *cmd) {
1523 sql_data_t *sd = NULL;
1524
1525 sql_check_cmd(cmd, "cmd_identify");
1526
1527 sd = (sql_data_t *) pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
1528 sd->data = (char **) pcalloc(cmd->tmp_pool, sizeof(char *) * 2);
1529
1530 sd->rnum = 1;
1531 sd->fnum = 2;
1532
1533 sd->data[0] = MOD_SQL_POSTGRES_VERSION;
1534 sd->data[1] = MOD_SQL_API_V1;
1535
1536 return mod_create_data(cmd, (void *) sd);
1537 }
1538
1539 MODRET cmd_prepare(cmd_rec *cmd) {
1540 if (cmd->argc != 1) {
1541 return PR_ERROR(cmd);
1542 }
1543
1544 conn_pool = (pool *) cmd->argv[0];
1545
1546 if (conn_cache == NULL) {
1547 conn_cache = make_array((pool *) cmd->argv[0], DEF_CONN_POOL_SIZE,
1548 sizeof(conn_entry_t *));
1549 }
1550
1551 return mod_create_data(cmd, NULL);
1552 }
1553
1554 MODRET cmd_cleanup(cmd_rec *cmd) {
1555 destroy_pool(conn_pool);
1556 conn_pool = NULL;
1557 conn_cache = NULL;
1558
1559 return mod_create_data(cmd, NULL);
1560 }
1561
1562 /* SQL cmdtable: mod_sql requires each backend module to define a cmdtable
1563 * with this exact name. ALL these functions must be defined; mod_sql checks
1564 * that they all exist on startup and ProFTPD will refuse to start if they
1565 * aren't defined.
1566 */
1567 static cmdtable sql_postgres_cmdtable[] = {
1568 { CMD, "sql_cleanup", G_NONE, cmd_cleanup, FALSE, FALSE },
1569 { CMD, "sql_close", G_NONE, cmd_close, FALSE, FALSE },
1570 { CMD, "sql_defineconnection", G_NONE, cmd_defineconnection, FALSE, FALSE },
1571 { CMD, "sql_escapestring", G_NONE, cmd_escapestring, FALSE, FALSE },
1572 { CMD, "sql_exit", G_NONE, cmd_exit, FALSE, FALSE },
1573 { CMD, "sql_identify", G_NONE, cmd_identify, FALSE, FALSE },
1574 { CMD, "sql_insert", G_NONE, cmd_insert, FALSE, FALSE },
1575 { CMD, "sql_open", G_NONE, cmd_open, FALSE, FALSE },
1576 { CMD, "sql_prepare", G_NONE, cmd_prepare, FALSE, FALSE },
1577 { CMD, "sql_procedure", G_NONE, cmd_procedure, FALSE, FALSE },
1578 { CMD, "sql_query", G_NONE, cmd_query, FALSE, FALSE },
1579 { CMD, "sql_select", G_NONE, cmd_select, FALSE, FALSE },
1580 { CMD, "sql_update", G_NONE, cmd_update, FALSE, FALSE },
1581
1582 { 0, NULL }
1583 };
1584
1585 /* Event handlers
1586 */
1587
1588 static void sql_postgres_mod_load_ev(const void *event_data,
1589 void *user_data) {
1590
1591 if (strcmp("mod_sql_postgres.c", (const char *) event_data) == 0) {
1592 /* Register ourselves with mod_sql. */
1593 if (sql_register_backend("postgres", sql_postgres_cmdtable) < 0) {
1594 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_POSTGRES_VERSION
1595 ": notice: error registering backend: %s", strerror(errno));
1596 pr_session_end(0);
1597 }
1598 }
1599 }
1600
1601 static void sql_postgres_mod_unload_ev(const void *event_data,
1602 void *user_data) {
1603
1604 if (strcmp("mod_sql_postgres.c", (const char *) event_data) == 0) {
1605 /* Unegister ourselves with mod_sql. */
1606 if (sql_unregister_backend("postgres") < 0) {
1607 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_POSTGRES_VERSION
1608 ": notice: error unregistering backend: %s", strerror(errno));
1609 pr_session_end(0);
1610 }
1611
1612 /* Unregister ourselves from all events. */
1613 pr_event_unregister(&sql_postgres_module, NULL, NULL);
1614 }
1615 }
1616
1617 /* Initialization routines
1618 */
1619
1620 static void sql_postgres_ssl_init(void) {
1621 #ifdef HAVE_POSTGRES_PQINITOPENSSL
1622 int init_ssl = TRUE, init_crypto = TRUE;
1623
1624 /* If any of the OpenSSL-using modules are loaded, tell Postgres to NOT
1625 * initialize OpenSSL itself. Note that there are nuances to this; some
1626 * of the other modules may only use the crypto libs.
1627 */
1628 if (pr_module_exists("mod_auth_otp.c") == TRUE ||
1629 pr_module_exists("mod_digest.c") == TRUE ||
1630 pr_module_exists("mod_sftp.c") == TRUE ||
1631 pr_module_exists("mod_sql_passwd.c") == TRUE) {
1632 init_crypto = FALSE;
1633 }
1634
1635 if (pr_module_exists("mod_tls.c") == TRUE) {
1636 init_ssl = FALSE;
1637 init_crypto = FALSE;
1638 }
1639
1640 # if defined(HAVE_LIBRESSL)
1641 /* However, if we are using LibreSSL, then the above modules will NOT be
1642 * properly initializing OpenSSL. Thus Postgres should do such
1643 * initializations itself.
1644 */
1645 init_ssl = init_crypto = TRUE;
1646 # endif
1647
1648 pr_trace_msg(trace_channel, 18,
1649 "telling Postgres about OpenSSL initialization: ssl = %s, crypto = %s",
1650 init_ssl ? "yes" : "no", init_crypto ? "yes" : "no");
1651 PQinitOpenSSL(init_ssl, init_crypto);
1652 #endif /* HAVE_POSTGRES_PQINITOPENSSL */
1653 }
1654
1655 static int sql_postgres_init(void) {
1656 /* Register listeners for the load and unload events. */
1657 pr_event_register(&sql_postgres_module, "core.module-load",
1658 sql_postgres_mod_load_ev, NULL);
1659 pr_event_register(&sql_postgres_module, "core.module-unload",
1660 sql_postgres_mod_unload_ev, NULL);
1661
1662 sql_postgres_ssl_init();
1663 return 0;
1664 }
1665
1666 static int sql_postgres_sess_init(void) {
1667 if (conn_pool != NULL) {
1668 destroy_pool(conn_pool);
1669 conn_cache = NULL;
1670 }
1671
1672 conn_pool = make_sub_pool(session.pool);
1673 pr_pool_tag(conn_pool, "Postgres connection pool");
1674
1675 if (conn_cache == NULL) {
1676 conn_cache = make_array(conn_pool, DEF_CONN_POOL_SIZE,
1677 sizeof(conn_entry_t *));
1678 }
1679
1680 return 0;
1681 }
1682
1683 /*
1684 * sql_postgres_module: The standard module struct for all ProFTPD modules.
1685 * We use the pre-fork handler to initialize the conn_cache array header.
1686 * Other backend modules may not need any init functions, or may need
1687 * to extend the init functions to initialize other internal variables.
1688 */
1689 module sql_postgres_module = {
1690 /* Always NULL */
1691 NULL, NULL,
1692
1693 /* Module API version */
1694 0x20,
1695
1696 /* Module name */
1697 "sql_postgres",
1698
1699 /* Module configuration directive handlers */
1700 NULL,
1701
1702 /* Module command handlers */
1703 NULL,
1704
1705 /* Module authentication handlers */
1706 NULL,
1707
1708 /* Module initialization */
1709 sql_postgres_init,
1710
1711 /* Session initialization */
1712 sql_postgres_sess_init,
1713
1714 /* Module version */
1715 MOD_SQL_POSTGRES_VERSION
1716 };