Debian Codegraph @

contrib/mod_sql_mysql.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 * ProFTPD: mod_sql_mysql -- Support for connecting to MySQL databases.
3 * Copyright (c) 2001 Andrew Houghton
4 * Copyright (c) 2004-2025 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 * -----DO NOT EDIT-----
26 * $Libraries: -lm -lmysqlclient -lz$
27 */
28
29 /* INTRO:
30 *
31 * mod_sql_mysql is the reference backend module for mod_sql. As such,
32 * it's very, very over-commented.
33 *
34 * COPYRIGHT NOTICE:
35 *
36 * The section of the copyright notice above that refers to OpenSSL *must*
37 * be present in every backend module. Without that exemption the backend
38 * module cannot legally be compiled into ProFTPD, even if the backend
39 * module makes no use of OpenSSL.
40 *
41 * FUNCTIONS IN THIS CODE:
42 *
43 * Backend modules are only called into via the functions listed in
44 * sql_cmdtable (see the end of this file). All other functions are
45 * internal.
46 *
47 * For stylistic reasons, it's requested that backend authors maintain the
48 * following conventions:
49 * 1) when returning data in a modret_t, use the standard ProFTPD macros
50 * whenever possible (ERR_MSG, HANDLED, etc.)
51 * 2) although 'static modret_t *' and 'MODRET' are equivalent, please
52 * use MODRET only for those functions listed in sql_cmdtable.
53 *
54 * NAMED CONNECTIONS:
55 *
56 * Backend modules need to handle named connections. A named connection
57 * is the complete specification of how to access a database coupled with
58 * a unique (to the session) descriptive name. Every call mod_sql makes
59 * into a backend is directed at a particular named connection.
60 * mod_sql_mysql includes a set of simplistic cache functions to keep an
61 * internal map of names to connections -- other backends should feel free
62 * to handle this however they want.
63 *
64 * OPEN/CLOSE SEMANTICS & CONNECTION COUNTING:
65 *
66 * Administrators using mod_sql decide on one of three connection policies:
67 * 1) open a connection to the database and hold it open for the life of
68 * the client process
69 * 2) open a connection to the database and hold it open for the life of
70 * each call
71 * 3) open a connection to the database and hold it open until a specified
72 * period of time has elapsed with no activity
73 *
74 * mod_sql enforces this choice by requiring that backends:
75 * 1) wrap each call in an open/close bracket (so if a connection isn't
76 * currently open, it will be opened for the call and closed afterwards)
77 * 2) properly do connection counting to ensure that a connection is not
78 * re-opened unnecessarily, and not closed too early.
79 *
80 * In simple terms: if an administrator chooses the "one connection for the
81 * life of the process" policy, mod_sql will send an initial cmd_open call
82 * for that connection at the start of the client session, and a final
83 * cmd_close call when the session ends. If an administrator chooses the
84 * "per-call" connection policy, the initial cmd_open and final cmd_close
85 * calls will not be made. If an administrator chooses the "timeout"
86 * connection policy, connections may be closed at any time and may need
87 * to be reopened for any call.
88 *
89 * CONNECTION TIMERS
90 *
91 * Backends are required to handle connection timers; when a connection is
92 * defined via cmd_defineconnection, a time value (in seconds) will be sent
93 * with the definition. Given the complexity of the semantics, it's
94 * recommended that backend authors simply copy the timer handling code from
95 * this module. Timer handling code exists in nearly every function in this
96 * module; read the code for more information.
97 *
98 * ERROR HANDLING AND LOGGING:
99 *
100 * Proper error handling is required of backend modules -- the modret_t
101 * structure passed back to mod_sql should have the error fields correctly
102 * filled. mod_sql handles backend errors by logging them then closing the
103 * connection and the session. Therefore, it's not necessary for backends
104 * to log errors which will be passed back to mod_sql, but they should log
105 * any errors or useful information which will not be returned in the
106 * modret_t. If an error is transient -- if there's any way for the backend
107 * module to handle an error intelligently -- it should do so. mod_sql
108 * will always handle backend errors by ending the client session.
109 *
110 * Good debug logging is encouraged -- major functions (the functions that
111 * mod_sql calls directly) should be wrapped in 'entering' and 'exiting'
112 * DEBUG_FUNC level output, the text of SQL queries should be visible with
113 * DEBUG_INFO level output, and any errors should be visible with DEBUG_WARN
114 * level output.
115 *
116 * Check the code if this makes no sense.
117 *
118 * COMMENTS / QUESTIONS:
119 *
120 * Backend module writers are encouraged to read through all comments in this
121 * file. If anything is unclear, please contact the author.
122 */
123
124 /* Internal define used for debug and logging. All backends are encouraged
125 * to use the same format.
126 */
127 #define MOD_SQL_MYSQL_VERSION "mod_sql_mysql/4.0.9"
128
129 #define _MYSQL_PORT "3306"
130
131 #include "conf.h"
132 #include "../contrib/mod_sql.h"
133
134 #include <mysql.h>
135 #include <stdbool.h>
136
137 /* The my_make_scrambled_password{,_323} functions are not part of the public
138 * MySQL API and are not declared in any of the MySQL header files. But the
139 * use of these functions are required for implementing the "Backend"
140 * SQLAuthType for MySQL. Thus these functions are declared here (Bug#3908).
141 */
142 #if defined(HAVE_MYSQL_MY_MAKE_SCRAMBLED_PASSWORD)
143 void my_make_scrambled_password(char *to, const char *from, size_t fromlen);
144 #endif
145
146 #if defined(HAVE_MYSQL_MY_MAKE_SCRAMBLED_PASSWORD_323)
147 void my_make_scrambled_password_323(char *to, const char *from, size_t fromlen);
148 #endif
149
150 /* Timer-handling code adds the need for a couple of forward declarations. */
151 MODRET cmd_close(cmd_rec *cmd);
152 module sql_mysql_module;
153
154 /*
155 * db_conn_struct: an internal struct to hold connection information. This
156 * connection information is backend-specific; the members here reflect
157 * the information MySQL needs for connections.
158 *
159 * Other backends are expected to make whatever changes are necessary.
160 */
161 struct db_conn_struct {
162
163 /* MySQL-specific members */
164 const char *host;
165 const char *user;
166 const char *pass;
167 const char *db;
168 const char *port;
169 const char *unix_sock;
170
171 /* For configuring the SSL/TLS session to the MySQL server. */
172 const char *ssl_cert_file;
173 const char *ssl_key_file;
174 const char *ssl_ca_file;
175 const char *ssl_ca_dir;
176 const char *ssl_ciphers;
177
178 MYSQL *mysql;
179 };
180
181 typedef struct db_conn_struct db_conn_t;
182
183 /*
184 * This struct is a wrapper for whatever backend data is needed to access
185 * the database, and supports named connections, connection counting, and
186 * timer handling. In most cases it should be enough for backend authors
187 * to change db_conn_t and leave this struct alone.
188 */
189
190 struct conn_entry_struct {
191 const char *name;
192 void *data;
193
194 /* Timer handling */
195 int timer;
196 int ttl;
197
198 /* Connection handling */
199 unsigned int connections;
200 };
201
202 typedef struct conn_entry_struct conn_entry_t;
203
204 #define DEF_CONN_POOL_SIZE 10
205
206 static pool *conn_pool = NULL;
207 static array_header *conn_cache = NULL;
208
209 static const char *trace_channel = "sql.mysql";
210
211 /* sql_get_connection: walks the connection cache looking for the named
212 * connection. Returns NULL if unsuccessful, a pointer to the conn_entry_t
213 * if successful.
214 */
215 static conn_entry_t *sql_get_connection(const char *conn_name) {
216 register unsigned int i;
217
218 if (conn_name == NULL) {
219 errno = EINVAL;
220 return NULL;
221 }
222
223 /* walk the array looking for our entry */
224 for (i = 0; i < conn_cache->nelts; i++) {
225 conn_entry_t *entry;
226
227 entry = ((conn_entry_t **) conn_cache->elts)[i];
228 if (strcmp(conn_name, entry->name) == 0) {
229 return entry;
230 }
231 }
232
233 errno = ENOENT;
234 return NULL;
235 }
236
237 /* sql_add_connection: internal helper function to maintain a cache of
238 * connections. Since we expect the number of named connections to be small,
239 * simply use an array header to hold them. We don't allow duplicate
240 * connection names.
241 *
242 * Returns: NULL if the insertion was unsuccessful, a pointer to the
243 * conn_entry_t that was created if successful.
244 */
245 static void *sql_add_connection(pool *p, const char *name, db_conn_t *conn) {
246 conn_entry_t *entry = NULL;
247
248 if (name == NULL ||
249 conn == NULL ||
250 p == NULL) {
251 errno = EINVAL;
252 return NULL;
253 }
254
255 if (sql_get_connection(name) != NULL) {
256 errno = EEXIST;
257 return NULL;
258 }
259
260 entry = (conn_entry_t *) pcalloc(p, sizeof(conn_entry_t));
261 entry->name = pstrdup(p, name);
262 entry->data = conn;
263
264 *((conn_entry_t **) push_array(conn_cache)) = entry;
265 return entry;
266 }
267
268 /* sql_check_cmd: tests to make sure the cmd_rec is valid and is properly
269 * filled in. If not, it's grounds for the daemon to shutdown.
270 */
271 static void sql_check_cmd(cmd_rec *cmd, char *msg) {
272 if (cmd == NULL ||
273 cmd->tmp_pool == NULL) {
274 pr_log_pri(PR_LOG_ERR, MOD_SQL_MYSQL_VERSION
275 ": '%s' was passed an invalid cmd_rec (internal bug); shutting down",
276 msg);
277 sql_log(DEBUG_WARN, "'%s' was passed an invalid cmd_rec (internal bug); "
278 "shutting down", msg);
279 pr_session_end(0);
280 }
281
282 return;
283 }
284
285 /* sql_timer_cb: when a timer goes off, this is the function that gets called.
286 * This function makes assumptions about the db_conn_t members.
287 */
288 static int sql_timer_cb(CALLBACK_FRAME) {
289 register unsigned int i;
290
291 for (i = 0; i < conn_cache->nelts; i++) {
292 conn_entry_t *entry = NULL;
293
294 entry = ((conn_entry_t **) conn_cache->elts)[i];
295 if ((unsigned long) entry->timer == p2) {
296 cmd_rec *cmd = NULL;
297
298 sql_log(DEBUG_INFO, "timer expired for connection '%s'", entry->name);
299 cmd = sql_make_cmd(conn_pool, 2, entry->name, "1");
300 cmd_close(cmd);
301 SQL_FREE_CMD(cmd);
302 entry->timer = 0;
303 }
304 }
305
306 return 0;
307 }
308
309 /* build_error: constructs a modret_t filled with error information;
310 * mod_sql_mysql calls this function and returns the resulting mod_ret_t
311 * whenever a call to the database results in an error. Other backends
312 * may want to use a different method to return error information.
313 */
314 static modret_t *build_error(cmd_rec *cmd, db_conn_t *conn) {
315 char num[20] = {'\0'};
316
317 if (conn == NULL) {
318 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
319 }
320
321 pr_snprintf(num, 20, "%u", mysql_errno(conn->mysql));
322 return PR_ERROR_MSG(cmd, pstrdup(cmd->pool, num),
323 pstrdup(cmd->pool, (char *) mysql_error(conn->mysql)));
324 }
325
326 /* build_data: both cmd_select and cmd_procedure potentially
327 * return data to mod_sql; this function builds a modret to return
328 * that data. This is MySQL specific; other backends may choose
329 * to do things differently.
330 */
331 static modret_t *build_data(cmd_rec *cmd, db_conn_t *conn) {
332 modret_t *mr = NULL;
333 MYSQL *mysql = NULL;
334 MYSQL_RES *result = NULL;
335 MYSQL_ROW row;
336 sql_data_t *sd = NULL;
337 char **data = NULL;
338 unsigned long cnt = 0;
339 unsigned long i = 0;
340
341 if (conn == NULL) {
342 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
343 }
344
345 mysql = conn->mysql;
346
347 /* Would much rather use mysql_use_result here but without knowing
348 * the number of rows returned we can't presize the data[] array.
349 */
350
351 result = mysql_store_result(mysql);
352 if (!result) {
353 return build_error(cmd, conn);
354 }
355
356 sd = (sql_data_t *) pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
357 sd->rnum = (unsigned long) mysql_num_rows(result);
358 sd->fnum = (unsigned long) mysql_num_fields(result);
359 cnt = sd->rnum * sd->fnum;
360
361 data = (char **) pcalloc(cmd->tmp_pool, sizeof(char *) * (cnt + 1));
362
363 while ((row = mysql_fetch_row(result))) {
364 for (cnt = 0; cnt < sd->fnum; cnt++) {
365 data[i++] = pstrdup(cmd->tmp_pool, row[cnt]);
366 }
367 }
368
369 /* At this point either we finished correctly or an error occurred in the
370 * fetch. Do the right thing.
371 */
372 if (mysql_errno(mysql) != 0) {
373 mr = build_error(cmd, conn);
374 mysql_free_result(result);
375 return mr;
376 }
377
378 mysql_free_result(result);
379 data[i] = NULL;
380 sd->data = data;
381
382 #ifdef CLIENT_MULTI_RESULTS
383 /* We might be dealing with multiple result sets here, as when a stored
384 * procedure was called which produced more results than we expect.
385 *
386 * We only want the first result set, so simply iterate through and free
387 * up any remaining result sets.
388 */
389 while (mysql_next_result(mysql) == 0) {
390 pr_signals_handle();
391 result = mysql_store_result(mysql);
392 mysql_free_result(result);
393 }
394 #endif
395
396 return mod_create_data(cmd, (void *) sd);
397 }
398
399 /*
400 * cmd_open: attempts to open a named connection to the database.
401 *
402 * Inputs:
403 * cmd->argv[0]: connection name
404 *
405 * Returns:
406 * either a properly filled error modret_t if a connection could not be
407 * opened, or a simple non-error modret_t.
408 *
409 * Notes:
410 * mod_sql depends on these semantics -- a backend should not open
411 * a connection unless mod_sql requests it, nor close one unless
412 * mod_sql requests it. Connection counting is *REQUIRED* for complete
413 * compatibility; a connection should not be closed unless the count
414 * reaches 0, and ideally will not need to be re-opened for counts > 1.
415 */
416 MODRET cmd_open(cmd_rec *cmd) {
417 conn_entry_t *entry = NULL;
418 db_conn_t *conn = NULL;
419 unsigned long client_flags = CLIENT_INTERACTIVE;
420 #if defined(PR_USE_NLS)
421 const char *encoding = NULL;
422 #endif /* PR_USE_NLS */
423 #if defined(HAVE_MYSQL_MYSQL_GET_SSL_CIPHER)
424 const char *ssl_cipher = NULL;
425 #endif
426
427 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_open");
428
429 sql_check_cmd(cmd, "cmd_open");
430
431 if (cmd->argc < 1) {
432 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_open");
433 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
434 }
435
436 entry = sql_get_connection(cmd->argv[0]);
437 if (entry == NULL) {
438 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_open");
439 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
440 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
441 }
442
443 conn = (db_conn_t *) entry->data;
444
445 /* If we're already open (connections > 0), AND our connection to MySQL
446 * is still alive, increment the connection counter, reset our timer (if
447 * we have one), and return HANDLED.
448 */
449 if (entry->connections > 0) {
450 if (mysql_ping(conn->mysql) == 0) {
451 entry->connections++;
452
453 if (entry->timer) {
454 pr_timer_reset(entry->timer, &sql_mysql_module);
455 }
456
457 sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name,
458 entry->connections);
459 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_open");
460 return PR_HANDLED(cmd);
461
462 } else {
463 sql_log(DEBUG_INFO, "lost connection to database: %s",
464 mysql_error(conn->mysql));
465
466 entry->connections = 0;
467 if (entry->timer) {
468 pr_timer_remove(entry->timer, &sql_mysql_module);
469 entry->timer = 0;
470 }
471
472 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_open");
473 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
474 "lost connection to database");
475 }
476 }
477
478 /* Make sure we have a new conn struct */
479 conn->mysql = mysql_init(NULL);
480 if (conn->mysql == NULL) {
481 pr_log_pri(PR_LOG_ALERT, MOD_SQL_MYSQL_VERSION
482 ": failed to allocate memory for MYSQL structure; shutting down");
483 sql_log(DEBUG_WARN, "%s", "failed to allocate memory for MYSQL structure; "
484 "shutting down");
485 pr_session_end(0);
486 }
487
488 if (!(pr_sql_opts & SQL_OPT_IGNORE_CONFIG_FILE)) {
489 /* Make sure the MySQL config files are read in. This will read in
490 * options from group "client" in the MySQL .cnf files.
491 */
492 mysql_options(conn->mysql, MYSQL_READ_DEFAULT_GROUP, "client");
493 }
494
495 #if MYSQL_VERSION_ID >= 50013 && \
496 MYSQL_VERSION_ID < 80034
497 /* The MYSQL_OPT_RECONNECT option appeared in MySQL 5.0.13, according to
498 *
499 * http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
500 *
501 * And in MySQL 8.0.34, it was deprecated.
502 */
503 if (!(pr_sql_opts & SQL_OPT_NO_RECONNECT)) {
504 #if MYSQL_VERSION_ID >= 80000
505 char reconnect = true;
506 #else
507 char reconnect = TRUE;
508 #endif
509 mysql_options(conn->mysql, MYSQL_OPT_RECONNECT, &reconnect);
510 }
511 #endif
512
513 #ifdef CLIENT_MULTI_RESULTS
514 /* Enable mod_sql_mysql to deal with multiple result sets which may be
515 * returned from calling stored procedures.
516 */
517 client_flags |= CLIENT_MULTI_RESULTS;
518 #endif
519
520 #if MYSQL_VERSION_ID >= 80035
521 /* Per the MySQL docs, the `mysql_ssl_set` function was deprecated in
522 * MySQL 8.0.35, to be replaced by equivalent options for `mysql_options`.
523 */
524 if (conn->ssl_ca_file != NULL) {
525 mysql_options(conn->mysql, MYSQL_OPT_SSL_CA, conn->ssl_ca_file);
526 }
527
528 if (conn->ssl_ca_dir != NULL) {
529 mysql_options(conn->mysql, MYSQL_OPT_SSL_CAPATH, conn->ssl_ca_dir);
530 }
531
532 if (conn->ssl_cert_file != NULL) {
533 mysql_options(conn->mysql, MYSQL_OPT_SSL_CERT, conn->ssl_cert_file);
534 }
535
536 if (conn->ssl_ciphers != NULL) {
537 mysql_options(conn->mysql, MYSQL_OPT_SSL_CIPHER, conn->ssl_ciphers);
538 }
539
540 if (conn->ssl_key_file != NULL) {
541 mysql_options(conn->mysql, MYSQL_OPT_SSL_KEY, conn->ssl_key_file);
542 }
543
544 #elif defined(HAVE_MYSQL_MYSQL_SSL_SET)
545 /* Per the MySQL docs, this function always returns success. Errors are
546 * reported when we actually attempt to connect.
547 *
548 * Note: There are some other TLS-related options, in newer versions of
549 * MySQL, which might be interest (although they require the use of the
550 * mysql_options() function, not mysql_ssl_set()):
551 *
552 * MYSQL_OPT_SSL_ENFORCE (boolean, defaults to 'false')
553 * MYSQL_OPT_SSL_VERIFY_SERVER_CERT (boolean, defaults to 'false')
554 * MYSQL_OPT_TLS_VERSION (char *, for configuring the protocol versions)
555 */
556 (void) mysql_ssl_set(conn->mysql, conn->ssl_key_file, conn->ssl_cert_file,
557 conn->ssl_ca_file, conn->ssl_ca_dir, conn->ssl_ciphers);
558 #endif
559
560 if (!mysql_real_connect(conn->mysql, conn->host, conn->user, conn->pass,
561 conn->db, (int) strtol(conn->port, (char **) NULL, 10),
562 conn->unix_sock, client_flags)) {
563 modret_t *mr = NULL;
564
565 /* If it didn't work, return an error. */
566 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_open");
567 mr = build_error(cmd, conn);
568
569 /* Since we failed to connect here, avoid a memory leak by freeing up the
570 * mysql conn struct.
571 */
572 mysql_close(conn->mysql);
573 conn->mysql = NULL;
574
575 return mr;
576 }
577
578 sql_log(DEBUG_FUNC, "MySQL version ID: %d", MYSQL_VERSION_ID);
579 sql_log(DEBUG_FUNC, "MySQL client version: %s", mysql_get_client_info());
580 sql_log(DEBUG_FUNC, "MySQL server version: %s",
581 mysql_get_server_info(conn->mysql));
582
583 # if MYSQL_VERSION_ID >= 50703 && defined(HAVE_MYSQL_GET_OPTION)
584 /* Log the configured authentication plugin, if any. For example, it
585 * might be set in the my.cnf file using:
586 *
587 * [client]
588 * default-auth = mysql_native_password
589 *
590 * Note: the mysql_get_option() function appeared in MySQL 5.7.3, as per:
591 *
592 * https://dev.mysql.com/doc/refman/5.7/en/mysql-get-option.html
593 *
594 * The MYSQL_DEFAULT_AUTH value is an enum, not a #define, so we cannot
595 * use a simple #ifdef here.
596 */
597 {
598 const char *auth_plugin = NULL;
599
600 if (mysql_get_option(conn->mysql, MYSQL_DEFAULT_AUTH, &auth_plugin) == 0) {
601 /* There may not have been a default auth plugin explicitly configured,
602 * and the MySQL internals themselves may not set one. So it is not
603 * surprising if the pointer remains null.
604 */
605 if (auth_plugin != NULL) {
606 sql_log(DEBUG_FUNC, "MySQL client default authentication plugin: %s",
607 auth_plugin);
608 }
609 }
610 }
611 #endif /* MySQL 5.7.3 and later */
612
613 #if defined(HAVE_MYSQL_MYSQL_GET_SSL_CIPHER)
614 ssl_cipher = mysql_get_ssl_cipher(conn->mysql);
615 /* XXX Should we fail the connection here, if we expect an SSL session to
616 * have been successfully completed/required?
617 */
618 if (ssl_cipher != NULL) {
619 sql_log(DEBUG_FUNC, "%s", "MySQL SSL connection: true");
620 sql_log(DEBUG_FUNC, "MySQL SSL cipher: %s", ssl_cipher);
621
622 } else {
623 sql_log(DEBUG_FUNC, "%s", "MySQL SSL connection: false");
624 }
625 #endif
626
627 #if defined(PR_USE_NLS)
628 encoding = pr_encode_get_encoding();
629 if (encoding == NULL) {
630 pr_trace_msg(trace_channel, 3, "no encoding found (%s), using 'UTF-8'",
631 strerror(errno));
632
633 encoding = "UTF-8";
634 }
635
636 # if MYSQL_VERSION_ID >= 50007
637 /* Configure the connection for the current local character set.
638 *
639 * Note: the mysql_set_character_set() function appeared in MySQL 5.0.7,
640 * as per:
641 *
642 * http://dev.mysql.com/doc/refman/5.0/en/mysql-set-character-set.html
643 *
644 * Yes, even though the variable names say "charset", we (and MySQL,
645 * though their documentation says otherwise) actually mean "encoding".
646 */
647
648 if (strcasecmp(encoding, "UTF-8") == 0) {
649 # if MYSQL_VERSION_ID >= 50503
650 /* MySQL prefers the name "utf8mb4", not "UTF-8" */
651 encoding = pstrdup(cmd->tmp_pool, "utf8mb4");
652 # else
653 /* MySQL prefers the name "utf8", not "UTF-8" */
654 encoding = pstrdup(cmd->tmp_pool, "utf8");
655 # endif /* MySQL before 5.5.3 */
656 }
657
658 if (mysql_set_character_set(conn->mysql, encoding) != 0) {
659 /* Failing to set the character set should NOT be a fatal error.
660 * There are situations where, due to client/server mismatch, the
661 * requested character set may not be available. Thus for now,
662 * we simply log the failure.
663 *
664 * A future improvement might be to implement fallback behavior,
665 * trying to set "older" character sets as needed.
666 */
667 sql_log(DEBUG_FUNC, MOD_SQL_MYSQL_VERSION
668 ": failed to set character set '%s': %s (%u)", encoding,
669 mysql_error(conn->mysql), mysql_errno(conn->mysql));
670 }
671
672 sql_log(DEBUG_FUNC, "MySQL connection character set now '%s' (from '%s')",
673 mysql_character_set_name(conn->mysql), encoding);
674
675 # else
676 /* No mysql_set_character_set() API available. But
677 * mysql_character_set_name() has been around for a while; we can use it
678 * to at least see whether there might be a character set discrepancy.
679 */
680 const char *local_charset = pr_encode_get_encoding();
681 const char *mysql_charset = mysql_character_set_name(conn->mysql);
682
683 if (strcasecmp(mysql_charset, "utf8") == 0) {
684 mysql_charset = pstrdup(cmd->tmp_pool, "UTF-8");
685 }
686
687 if (local_charset != NULL &&
688 mysql_charset != NULL &&
689 strcasecmp(local_charset, mysql_charset) != 0) {
690 pr_log_pri(PR_LOG_ERR, MOD_SQL_MYSQL_VERSION
691 ": local character set '%s' does not match MySQL character set '%s', "
692 "SQL injection possible, shutting down", local_charset, mysql_charset);
693 sql_log(DEBUG_WARN, "local character set '%s' does not match MySQL "
694 "character set '%s', SQL injection possible, shutting down",
695 local_charset, mysql_charset);
696 pr_session_end(0);
697 }
698 # endif /* older MySQL */
699 #endif /* !PR_USE_NLS */
700
701 /* bump connections */
702 entry->connections++;
703
704 if (pr_sql_conn_policy == SQL_CONN_POLICY_PERSESSION) {
705 /* If the connection policy is PERSESSION... */
706 if (entry->connections == 1) {
707 /* ...and we are actually opening the first connection to the database;
708 * we want to make sure this connection stays open, after this first use
709 * (as per Bug#3290). To do this, we re-bump the connection count.
710 */
711 entry->connections++;
712 }
713
714 } else if (entry->ttl > 0) {
715 /* Set up our timer if necessary */
716
717 entry->timer = pr_timer_add(entry->ttl, -1, &sql_mysql_module,
718 sql_timer_cb, "mysql connection ttl");
719 sql_log(DEBUG_INFO, "connection '%s' - %d second timer started",
720 entry->name, entry->ttl);
721
722 /* timed connections get re-bumped so they don't go away when cmd_close
723 * is called.
724 */
725 entry->connections++;
726 }
727
728 /* return HANDLED */
729 sql_log(DEBUG_INFO, "connection '%s' opened", entry->name);
730 sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name,
731 entry->connections);
732 pr_event_generate("mod_sql.db.connection-opened", &sql_mysql_module);
733
734 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_open");
735 return PR_HANDLED(cmd);
736 }
737
738 /*
739 * cmd_close: attempts to close the named connection.
740 *
741 * Inputs:
742 * cmd->argv[0]: connection name
743 * Optional:
744 * cmd->argv[1]: close immediately
745 *
746 * Returns:
747 * either a properly filled error modret_t if a connection could not be
748 * closed, or a simple non-error modret_t. For the case of mod_sql_mysql,
749 * there are no error codes returned by the close call; other backends
750 * may be able to return a useful error message.
751 *
752 * Notes:
753 * mod_sql depends on these semantics -- a backend should not open
754 * a connection unless mod_sql requests it, nor close one unless
755 * mod_sql requests it. Connection counting is *REQUIRED* for complete
756 * compatibility; a connection should not be closed unless the count
757 * reaches 0, and should not need to be re-opened for counts > 1.
758 *
759 * If argv[1] exists and is not NULL, the connection should be immediately
760 * closed and the connection count should be reset to 0.
761 */
762 MODRET cmd_close(cmd_rec *cmd) {
763 conn_entry_t *entry = NULL;
764 db_conn_t *conn = NULL;
765
766 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_close");
767
768 sql_check_cmd(cmd, "cmd_close");
769
770 if ((cmd->argc < 1) || (cmd->argc > 2)) {
771 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_close");
772 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
773 }
774
775 entry = sql_get_connection(cmd->argv[0]);
776 if (entry == NULL) {
777 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_close");
778 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
779 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
780 }
781
782 conn = (db_conn_t *) entry->data;
783
784 /* if we're closed already (connections == 0) return HANDLED */
785 if (entry->connections == 0) {
786 sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name,
787 entry->connections);
788
789 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_close");
790 return PR_HANDLED(cmd);
791 }
792
793 /* decrement connections. If our count is 0 or we received a second arg
794 * close the connection, explicitly set the counter to 0, and remove any
795 * timers.
796 */
797 if (((--entry->connections) == 0) || ((cmd->argc == 2) && (cmd->argv[1]))) {
798 if (conn->mysql != NULL) {
799 mysql_close(conn->mysql);
800 conn->mysql = NULL;
801 }
802 entry->connections = 0;
803
804 if (entry->timer) {
805 pr_timer_remove(entry->timer, &sql_mysql_module);
806 entry->timer = 0;
807 sql_log(DEBUG_INFO, "connection '%s' - timer stopped", entry->name);
808 }
809
810 sql_log(DEBUG_INFO, "connection '%s' closed", entry->name);
811 pr_event_generate("mod_sql.db.connection-closed", &sql_mysql_module);
812 }
813
814 sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name,
815 entry->connections);
816 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_close");
817
818 return PR_HANDLED(cmd);
819 }
820
821 /* cmd_defineconnection: takes all information about a database
822 * connection and stores it for later use.
823 *
824 * Inputs:
825 * cmd->argv[0]: connection name
826 * cmd->argv[1]: username portion of the SQLConnectInfo directive
827 * cmd->argv[2]: password portion of the SQLConnectInfo directive
828 * cmd->argv[3]: info portion of the SQLConnectInfo directive
829 *
830 * Optional:
831 * cmd->argv[4]: time-to-live in seconds
832 * cmd->argv[5]: SSL client cert file
833 * cmd->argv[6]: SSL client key file
834 * cmd->argv[7]: SSL CA file
835 * cmd->argv[8]: SSL CA directory
836 * cmd->argv[9]: SSL ciphers
837 *
838 * Returns:
839 * either a properly filled error modret_t if the connection could not
840 * defined, or a simple non-error modret_t.
841 *
842 * Notes:
843 * time-to-live is the length of time to allow a connection to remain unused;
844 * once that amount of time has passed, a connection should be closed and
845 * it's connection count should be reduced to 0. If ttl is 0, or ttl is not
846 * a number or ttl is negative, the connection will be assumed to have no
847 * associated timer.
848 */
849 MODRET cmd_defineconnection(cmd_rec *cmd) {
850 char *have_host = NULL, *have_port = NULL, *info = NULL, *name = NULL;
851 const char *db = NULL, *host = NULL, *port = NULL;
852 const char *ssl_cert_file = NULL, *ssl_key_file = NULL, *ssl_ca_file = NULL;
853 const char *ssl_ca_dir = NULL, *ssl_ciphers = NULL;
854 conn_entry_t *entry = NULL;
855 db_conn_t *conn = NULL;
856
857 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_defineconnection");
858
859 sql_check_cmd(cmd, "cmd_defineconnection");
860
861 if (cmd->argc < 4 ||
862 cmd->argc > 10 ||
863 !cmd->argv[0]) {
864 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_defineconnection");
865 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
866 }
867
868 if (conn_pool == NULL) {
869 pr_log_pri(PR_LOG_WARNING, "WARNING: the mod_sql_mysql module has not been "
870 "properly initialized. Please make sure your --with-modules configure "
871 "option lists mod_sql *before* mod_sql_mysql, and recompile.");
872
873 sql_log(DEBUG_FUNC, "%s", "The mod_sql_mysql module has not been properly "
874 "initialized. Please make sure your --with-modules configure option "
875 "lists mod_sql *before* mod_sql_mysql, and recompile.");
876 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_defineconnection");
877
878 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "uninitialized module");
879 }
880
881 conn = (db_conn_t *) pcalloc(conn_pool, sizeof(db_conn_t));
882
883 name = pstrdup(conn_pool, cmd->argv[0]);
884 conn->user = pstrdup(conn_pool, cmd->argv[1]);
885 conn->pass = pstrdup(conn_pool, cmd->argv[2]);
886
887 info = cmd->argv[3];
888
889 db = pstrdup(cmd->tmp_pool, info);
890
891 have_host = strchr(db, '@');
892 have_port = strchr(db, ':');
893
894 /* If have_port, parse it, otherwise default it.
895 * If have_port, set it to '\0'.
896 *
897 * If have_host, parse it, otherwise default it.
898 * If have_host, set it to '\0'.
899 */
900
901 if (have_port != NULL) {
902 port = have_port + 1;
903 *have_port = '\0';
904
905 } else {
906 port = _MYSQL_PORT;
907 }
908
909 if (have_host != NULL) {
910 host = have_host + 1;
911 *have_host = '\0';
912
913 } else {
914 host = "localhost";
915 }
916
917 /* Hack to support ability to configure path to Unix domain socket
918 * for MySQL: if the host string starts with a '/', assume it's
919 * a path to the Unix domain socket to use.
920 */
921 if (*host == '/') {
922 conn->unix_sock = pstrdup(conn_pool, host);
923
924 } else {
925 conn->host = pstrdup(conn_pool, host);
926 }
927
928 conn->db = pstrdup(conn_pool, db);
929 conn->port = pstrdup(conn_pool, port);
930
931 /* SSL parameters, if configured. */
932 if (cmd->argc >= 6) {
933 ssl_cert_file = cmd->argv[5];
934 if (ssl_cert_file != NULL) {
935 conn->ssl_cert_file = pstrdup(conn_pool, ssl_cert_file);
936 }
937 }
938
939 if (cmd->argc >= 7) {
940 ssl_key_file = cmd->argv[6];
941 if (ssl_key_file != NULL) {
942 conn->ssl_key_file = pstrdup(conn_pool, ssl_key_file);
943 }
944 }
945
946 if (cmd->argc >= 8) {
947 ssl_ca_file = cmd->argv[7];
948 if (ssl_ca_file != NULL) {
949 conn->ssl_ca_file = pstrdup(conn_pool, ssl_ca_file);
950 }
951 }
952
953 if (cmd->argc >= 9) {
954 ssl_ca_dir = cmd->argv[8];
955 if (ssl_ca_dir != NULL) {
956 conn->ssl_ca_dir = pstrdup(conn_pool, ssl_ca_dir);
957 }
958 }
959
960 if (cmd->argc >= 10) {
961 ssl_ciphers = cmd->argv[9];
962 if (ssl_ciphers != NULL) {
963 conn->ssl_ciphers = pstrdup(conn_pool, ssl_ciphers);
964 }
965 }
966
967 entry = sql_add_connection(conn_pool, name, (void *) conn);
968 if (entry == NULL &&
969 errno == EEXIST) {
970 /* Log only connections named other than "default", for debugging
971 * misconfigurations with multiple different SQLNamedConnectInfo
972 * directives using the same name.
973 */
974 if (strcmp(name, "default") != 0) {
975 sql_log(DEBUG_FUNC, "named connection '%s' already exists", name);
976 }
977
978 entry = sql_get_connection(name);
979 }
980
981 if (entry == NULL) {
982 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_defineconnection");
983 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
984 "error adding named connection");
985 }
986
987 if (cmd->argc >= 5) {
988 entry->ttl = (int) strtol(cmd->argv[4], (char **) NULL, 10);
989 if (entry->ttl >= 1) {
990 pr_sql_conn_policy = SQL_CONN_POLICY_TIMER;
991
992 } else {
993 entry->ttl = 0;
994 }
995 }
996
997 entry->timer = 0;
998 entry->connections = 0;
999
1000 sql_log(DEBUG_INFO, " name: '%s'", entry->name);
1001 sql_log(DEBUG_INFO, " user: '%s'", conn->user);
1002
1003 if (conn->host != NULL) {
1004 sql_log(DEBUG_INFO, " host: '%s'", conn->host);
1005
1006 } else if (conn->unix_sock != NULL) {
1007 sql_log(DEBUG_INFO, "socket: '%s'", conn->unix_sock);
1008 }
1009
1010 sql_log(DEBUG_INFO, " db: '%s'", conn->db);
1011 sql_log(DEBUG_INFO, " port: '%s'", conn->port);
1012 sql_log(DEBUG_INFO, " ttl: '%d'", entry->ttl);
1013
1014 if (conn->ssl_cert_file != NULL) {
1015 sql_log(DEBUG_INFO, " ssl: client cert = '%s'", conn->ssl_cert_file);
1016 }
1017
1018 if (conn->ssl_key_file != NULL) {
1019 sql_log(DEBUG_INFO, " ssl: client key = '%s'", conn->ssl_key_file);
1020 }
1021
1022 if (conn->ssl_ca_file != NULL) {
1023 sql_log(DEBUG_INFO, " ssl: CA file = '%s'", conn->ssl_ca_file);
1024 }
1025
1026 if (conn->ssl_ca_dir != NULL) {
1027 sql_log(DEBUG_INFO, " ssl: CA dir = '%s'", conn->ssl_ca_dir);
1028 }
1029
1030 if (conn->ssl_ciphers != NULL) {
1031 sql_log(DEBUG_INFO, " ssl: ciphers = '%s'", conn->ssl_ciphers);
1032 }
1033
1034 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_defineconnection");
1035 return PR_HANDLED(cmd);
1036 }
1037
1038 /*
1039 * cmd_exit: closes all open connections.
1040 *
1041 * Inputs:
1042 * None
1043 *
1044 * Returns:
1045 * A simple non-error modret_t.
1046 */
1047 static modret_t *cmd_exit(cmd_rec *cmd) {
1048 register unsigned int i = 0;
1049
1050 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_exit");
1051
1052 for (i = 0; i < conn_cache->nelts; i++) {
1053 conn_entry_t *entry;
1054
1055 entry = ((conn_entry_t **) conn_cache->elts)[i];
1056 if (entry->connections > 0) {
1057 cmd_rec *close_cmd;
1058
1059 close_cmd = sql_make_cmd(conn_pool, 2, entry->name, "1");
1060 cmd_close(close_cmd);
1061 destroy_pool(close_cmd->pool);
1062 }
1063 }
1064
1065 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_exit");
1066 return PR_HANDLED(cmd);
1067 }
1068
1069 /*
1070 * cmd_select: executes a SELECT query. properly constructing the query
1071 * based on the inputs. See mod_sql.h for the definition of the _sql_data
1072 * structure which is used to return the result data.
1073 *
1074 * cmd_select takes either exactly two inputs, or more than two. If only
1075 * two inputs are given, the second is a monolithic query string. See
1076 * the examples below.
1077 *
1078 * Inputs:
1079 * cmd->argv[0]: connection name
1080 * cmd->argv[1]: table
1081 * cmd->argv[2]: select string
1082 * Optional:
1083 * cmd->argv[3]: where clause
1084 * cmd->argv[4]: requested number of return rows (LIMIT)
1085 *
1086 * etc. : other options, such as "GROUP BY", "ORDER BY",
1087 * and "DISTINCT" will start at cmd->arg[5]. All
1088 * backends MUST support 'DISTINCT', the other
1089 * arguments are optional (but encouraged).
1090 *
1091 * Returns:
1092 * either a properly filled error modret_t if the select failed, or a
1093 * modret_t with the result data filled in.
1094 *
1095 * Example:
1096 * These are example queries that would be executed for MySQL; other
1097 * backends will have different SQL syntax.
1098 *
1099 * argv[] = "default","user","userid, count", "userid='aah'","2"
1100 * query = "SELECT userid, count FROM user WHERE userid='aah' LIMIT 2"
1101 *
1102 * argv[] = "default","usr1, usr2","usr1.foo, usr2.bar"
1103 * query = "SELECT usr1.foo, usr2.bar FROM usr1, usr2"
1104 *
1105 * argv[] = "default","usr1","foo",,,"DISTINCT"
1106 * query = "SELECT DISTINCT foo FROM usr1"
1107 *
1108 * argv[] = "default","bar FROM usr1 WHERE tmp=1 ORDER BY bar"
1109 * query = "SELECT bar FROM usr1 WHERE tmp=1 ORDER BY bar"
1110 *
1111 * Notes:
1112 * certain selects could return huge amounts of data. do whatever is
1113 * possible to minimize the amount of data copying here.
1114 */
1115 MODRET cmd_select(cmd_rec *cmd) {
1116 conn_entry_t *entry = NULL;
1117 db_conn_t *conn = NULL;
1118 modret_t *cmr = NULL;
1119 modret_t *dmr = NULL;
1120 char *query = NULL;
1121 cmd_rec *close_cmd;
1122
1123 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_select");
1124
1125 sql_check_cmd(cmd, "cmd_select");
1126
1127 if (cmd->argc < 2) {
1128 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_select");
1129 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
1130 }
1131
1132 entry = sql_get_connection(cmd->argv[0]);
1133 if (entry == NULL) {
1134 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_select");
1135 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
1136 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
1137 }
1138
1139 conn = (db_conn_t *) entry->data;
1140
1141 cmr = cmd_open(cmd);
1142 if (MODRET_ERROR(cmr)) {
1143 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_select");
1144 return cmr;
1145 }
1146
1147 /* construct the query string */
1148 if (cmd->argc == 2) {
1149 query = pstrcat(cmd->tmp_pool, "SELECT ", cmd->argv[1], NULL);
1150
1151 } else {
1152 /* Make sure to properly quote the table name, as it might be a reserved
1153 * keyword; see Issue #1212.
1154 */
1155 query = pstrcat(cmd->tmp_pool, cmd->argv[2], " FROM `", cmd->argv[1], "`",
1156 NULL);
1157
1158 if (cmd->argc > 3 &&
1159 cmd->argv[3]) {
1160 query = pstrcat(cmd->tmp_pool, query, " WHERE ", cmd->argv[3], NULL);
1161 }
1162
1163 if (cmd->argc > 4 &&
1164 cmd->argv[4]) {
1165 query = pstrcat(cmd->tmp_pool, query, " LIMIT ", cmd->argv[4], NULL);
1166 }
1167
1168 if (cmd->argc > 5) {
1169 register unsigned int i;
1170
1171 /* Handle the optional arguments -- they're rare, so in this case
1172 * we'll play with the already constructed query string, but in
1173 * general we should probably take optional arguments into account
1174 * and put the query string together later once we know what they are.
1175 */
1176 for (i = 5; i < cmd->argc; i++) {
1177 if (cmd->argv[i] != NULL &&
1178 strcasecmp("DISTINCT", cmd->argv[i]) == 0) {
1179 query = pstrcat(cmd->tmp_pool, "DISTINCT ", query, NULL);
1180 }
1181 }
1182 }
1183
1184 query = pstrcat(cmd->tmp_pool, "SELECT ", query, NULL);
1185 }
1186
1187 /* Log the query string */
1188 sql_log(DEBUG_INFO, "query \"%s\"", query);
1189
1190 /* Perform the query. if it doesn't work, log the error, close the
1191 * connection then return the error from the query processing.
1192 */
1193 if (mysql_real_query(conn->mysql, query, strlen(query)) != 0) {
1194 dmr = build_error(cmd, conn);
1195
1196 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1197 cmd_close(close_cmd);
1198 SQL_FREE_CMD(close_cmd);
1199
1200 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_select");
1201 return dmr;
1202 }
1203
1204 /* Get the data. if it doesn't work, log the error, close the
1205 * connection then return the error from the data processing.
1206 */
1207 dmr = build_data(cmd, conn);
1208 if (MODRET_ERROR(dmr)) {
1209 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_select");
1210
1211 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1212 cmd_close(close_cmd);
1213 SQL_FREE_CMD(close_cmd);
1214
1215 return dmr;
1216 }
1217
1218 /* close the connection, return the data. */
1219 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1220 cmd_close(close_cmd);
1221 SQL_FREE_CMD(close_cmd);
1222
1223 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_select");
1224 return dmr;
1225 }
1226
1227 /*
1228 * cmd_insert: executes an INSERT query, properly constructing the query
1229 * based on the inputs.
1230 *
1231 * cmd_insert takes either exactly two inputs, or exactly four. If only
1232 * two inputs are given, the second is a monolithic query string. See
1233 * the examples below.
1234 *
1235 * Inputs:
1236 * cmd->argv[0]: connection name
1237 * cmd->argv[1]: table
1238 * cmd->argv[2]: field string
1239 * cmd->argv[3]: value string
1240 *
1241 * Returns:
1242 * either a properly filled error modret_t if the insert failed, or a
1243 * simple non-error modret_t.
1244 *
1245 * Example:
1246 * These are example queries that would be executed for MySQL; other
1247 * backends will have different SQL syntax.
1248 *
1249 * argv[] = "default","log","userid, date, count", "'aah', now(), 2"
1250 * query = "INSERT INTO log (userid, date, count) VALUES ('aah', now(), 2)"
1251 *
1252 * argv[] = "default"," INTO foo VALUES ('do','re','mi','fa')"
1253 * query = "INSERT INTO foo VALUES ('do','re','mi','fa')"
1254 *
1255 * Notes:
1256 * none
1257 */
1258 MODRET cmd_insert(cmd_rec *cmd) {
1259 conn_entry_t *entry = NULL;
1260 db_conn_t *conn = NULL;
1261 modret_t *cmr = NULL;
1262 modret_t *dmr = NULL;
1263 char *query = NULL;
1264 cmd_rec *close_cmd;
1265
1266 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_insert");
1267
1268 sql_check_cmd(cmd, "cmd_insert");
1269
1270 if ((cmd->argc != 2) && (cmd->argc != 4)) {
1271 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_insert");
1272 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
1273 }
1274
1275 entry = sql_get_connection(cmd->argv[0]);
1276 if (entry == NULL) {
1277 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_insert");
1278 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
1279 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
1280 }
1281
1282 conn = (db_conn_t *) entry->data;
1283
1284 cmr = cmd_open(cmd);
1285 if (MODRET_ERROR(cmr)) {
1286 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_insert");
1287 return cmr;
1288 }
1289
1290 /* construct the query string */
1291 if (cmd->argc == 2) {
1292 query = pstrcat(cmd->tmp_pool, "INSERT ", cmd->argv[1], NULL);
1293
1294 } else {
1295 /* Make sure to properly quote the table name, as it might be a reserved
1296 * keyword; see Issue #1212.
1297 */
1298 query = pstrcat(cmd->tmp_pool, "INSERT INTO `", cmd->argv[1], "` (",
1299 cmd->argv[2], ") VALUES (", cmd->argv[3], ")", NULL);
1300 }
1301
1302 sql_log(DEBUG_INFO, "query \"%s\"", query);
1303
1304 /* perform the query. if it doesn't work, log the error, close the
1305 * connection (and log any errors there, too) then return the error
1306 * from the query processing.
1307 */
1308 if (mysql_real_query(conn->mysql, query, strlen(query)) != 0) {
1309 dmr = build_error(cmd, conn);
1310
1311 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1312 cmd_close(close_cmd);
1313 SQL_FREE_CMD(close_cmd);
1314
1315 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_insert");
1316 return dmr;
1317 }
1318
1319 /* close the connection and return HANDLED. */
1320 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1321 cmd_close(close_cmd);
1322 SQL_FREE_CMD(close_cmd);
1323
1324 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_insert");
1325 return PR_HANDLED(cmd);
1326 }
1327
1328 /*
1329 * cmd_update: executes an UPDATE query, properly constructing the query
1330 * based on the inputs.
1331 *
1332 * cmd_update takes either exactly two, three, or four inputs. If only
1333 * two inputs are given, the second is a monolithic query string. See
1334 * the examples below.
1335 *
1336 * Inputs:
1337 * cmd->argv[0]: connection name
1338 * cmd->argv[1]: table
1339 * cmd->argv[2]: update string
1340 * Optional:
1341 * cmd->argv[3]: where string
1342 *
1343 * Returns:
1344 * either a properly filled error modret_t if the update failed, or a
1345 * simple non-error modret_t.
1346 *
1347 * Example:
1348 * These are example queries that would be executed for MySQL; other
1349 * backends will have different SQL syntax.
1350 *
1351 * argv[] = "default","user","count=count+1", "userid='joesmith'"
1352 * query = "UPDATE user SET count=count+1 WHERE userid='joesmith'"
1353 *
1354 * Notes:
1355 * argv[3] is optional -- it may be NULL, or it may not exist at all.
1356 * make sure this is handled correctly.
1357 */
1358 MODRET cmd_update(cmd_rec *cmd) {
1359 conn_entry_t *entry = NULL;
1360 db_conn_t *conn = NULL;
1361 modret_t *cmr = NULL;
1362 modret_t *dmr = NULL;
1363 char *query = NULL;
1364 cmd_rec *close_cmd;
1365
1366 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_update");
1367
1368 sql_check_cmd(cmd, "cmd_update");
1369
1370 if ((cmd->argc < 2) || (cmd->argc > 4)) {
1371 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_update");
1372 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
1373 }
1374
1375 entry = sql_get_connection(cmd->argv[0]);
1376 if (entry == NULL) {
1377 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_update");
1378 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
1379 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
1380 }
1381
1382 conn = (db_conn_t *) entry->data;
1383
1384 cmr = cmd_open(cmd);
1385 if (MODRET_ERROR(cmr)) {
1386 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_update");
1387 return cmr;
1388 }
1389
1390 if (cmd->argc == 2) {
1391 query = pstrcat(cmd->tmp_pool, "UPDATE ", cmd->argv[1], NULL);
1392
1393 } else {
1394 /* Make sure to properly quote the table name, as it might be a reserved
1395 * keyword; see Issue #1212.
1396 */
1397 query = pstrcat(cmd->tmp_pool, "UPDATE `", cmd->argv[1], "` SET ",
1398 cmd->argv[2], NULL);
1399 if (cmd->argc > 3 &&
1400 cmd->argv[3]) {
1401 query = pstrcat(cmd->tmp_pool, query, " WHERE ", cmd->argv[3], NULL);
1402 }
1403 }
1404
1405 /* Log the query string */
1406 sql_log(DEBUG_INFO, "query \"%s\"", query);
1407
1408 /* Perform the query. if it doesn't work close the connection, then
1409 * return the error from the query processing.
1410 */
1411 if (mysql_real_query(conn->mysql, query, strlen(query)) != 0) {
1412 dmr = build_error(cmd, conn);
1413
1414 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1415 cmd_close(close_cmd);
1416 SQL_FREE_CMD(close_cmd);
1417
1418 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_update");
1419 return dmr;
1420 }
1421
1422 /* Close the connection, return HANDLED. */
1423 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1424 cmd_close(close_cmd);
1425 SQL_FREE_CMD(close_cmd);
1426
1427 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_update");
1428 return PR_HANDLED(cmd);
1429 }
1430
1431 /*
1432 * cmd_procedure: executes a stored procedure.
1433 *
1434 * Inputs:
1435 * cmd->argv[0]: connection name
1436 * cmd->argv[1]: procedure name
1437 * cmd->argv[2]: procedure string
1438 *
1439 * Returns:
1440 * either a properly filled error modret_t if the procedure failed in
1441 * some way, or a modret_t with the result data. If a procedure
1442 * returns data, it should be returned in the same way as cmd_select.
1443 *
1444 * Notes:
1445 * not every backend will support stored procedures. Backends which do
1446 * not support stored procedures should return an error with a descriptive
1447 * error message (something like 'backend does not support procedures').
1448 */
1449 MODRET cmd_procedure(cmd_rec *cmd) {
1450 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_procedure");
1451
1452 sql_check_cmd(cmd, "cmd_procedure");
1453
1454 if (cmd->argc != 3) {
1455 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_procedure");
1456 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
1457 }
1458
1459 /* MySQL does not support procedures. Nothing to do. */
1460
1461 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_procedure");
1462
1463 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
1464 "backend does not support procedures");
1465 }
1466
1467 /*
1468 * cmd_query: executes a freeform query string, with no syntax checking.
1469 *
1470 * cmd_query takes exactly two inputs, the connection and the query string.
1471 *
1472 * Inputs:
1473 * cmd->argv[0]: connection name
1474 * cmd->argv[1]: query string
1475 *
1476 * Returns:
1477 * depending on the query type, returns a modret_t with data, a non-error
1478 * modret_t, or a properly filled error modret_t if the query failed.
1479 *
1480 * Example:
1481 * None. The query should be passed directly to the backend database.
1482 *
1483 * Notes:
1484 * None.
1485 */
1486 MODRET cmd_query(cmd_rec *cmd) {
1487 conn_entry_t *entry = NULL;
1488 db_conn_t *conn = NULL;
1489 modret_t *cmr = NULL;
1490 modret_t *dmr = NULL;
1491 char *query = NULL;
1492 cmd_rec *close_cmd;
1493
1494 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_query");
1495
1496 sql_check_cmd(cmd, "cmd_query");
1497
1498 if (cmd->argc != 2) {
1499 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_query");
1500 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
1501 }
1502
1503 entry = sql_get_connection(cmd->argv[0]);
1504 if (entry == NULL) {
1505 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_query");
1506 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
1507 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
1508 }
1509
1510 conn = (db_conn_t *) entry->data;
1511
1512 cmr = cmd_open(cmd);
1513 if (MODRET_ERROR(cmr)) {
1514 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_query");
1515 return cmr;
1516 }
1517
1518 query = pstrcat(cmd->tmp_pool, cmd->argv[1], NULL);
1519
1520 /* Log the query string */
1521 sql_log(DEBUG_INFO, "query \"%s\"", query);
1522
1523 /* Perform the query. if it doesn't work close the connection, then
1524 * return the error from the query processing.
1525 */
1526 if (mysql_real_query(conn->mysql, query, strlen(query)) != 0) {
1527 dmr = build_error(cmd, conn);
1528
1529 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1530 cmd_close(close_cmd);
1531 SQL_FREE_CMD(close_cmd);
1532
1533 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_query");
1534 return dmr;
1535 }
1536
1537 /* Get data if necessary. if it doesn't work, log the error, close the
1538 * connection then return the error from the data processing.
1539 */
1540
1541 if (mysql_field_count(conn->mysql) > 0) {
1542 dmr = build_data(cmd, conn);
1543 if (MODRET_ERROR(dmr)) {
1544 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_query");
1545 }
1546
1547 } else {
1548 dmr = PR_HANDLED(cmd);
1549 }
1550
1551 /* close the connection, return the data. */
1552 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1553 cmd_close(close_cmd);
1554 SQL_FREE_CMD(close_cmd);
1555
1556 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_query");
1557 return dmr;
1558 }
1559
1560 /*
1561 * cmd_escapestring: certain strings sent to a database should be properly
1562 * escaped -- for instance, quotes need to be escaped to insure that
1563 * a query string is properly formatted. cmd_escapestring does whatever
1564 * is necessary to escape the special characters in a string.
1565 *
1566 * Inputs:
1567 * cmd->argv[0]: connection name
1568 * cmd->argv[1]: string to escape
1569 *
1570 * Returns:
1571 * this command CANNOT fail. The return string is null-terminated and
1572 * stored in the data field of the modret_t structure.
1573 *
1574 * Notes:
1575 * Different languages may escape different characters in different ways.
1576 * A backend should handle this correctly, where possible. If there is
1577 * no client library function to do the string conversion, it is strongly
1578 * recommended that the backend module writer do whatever is necessry (read
1579 * the database documentation and figure it out) to do the conversion
1580 * themselves in this function.
1581 *
1582 * A backend MUST supply a working escapestring implementation. Simply
1583 * copying the data from argv[0] into the data field of the modret allows
1584 * for possible SQL injection attacks when this backend is used.
1585 */
1586 MODRET cmd_escapestring(cmd_rec * cmd) {
1587 conn_entry_t *entry = NULL;
1588 db_conn_t *conn = NULL;
1589 modret_t *cmr = NULL;
1590 char *unescaped = NULL;
1591 char *escaped = NULL;
1592 cmd_rec *close_cmd;
1593
1594 sql_log(DEBUG_FUNC, "%s", "entering \tmysql cmd_escapestring");
1595
1596 sql_check_cmd(cmd, "cmd_escapestring");
1597
1598 if (cmd->argc != 2) {
1599 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_escapestring");
1600 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION, "badly formed request");
1601 }
1602
1603 entry = sql_get_connection(cmd->argv[0]);
1604 if (entry == NULL) {
1605 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_escapestring");
1606 return PR_ERROR_MSG(cmd, MOD_SQL_MYSQL_VERSION,
1607 pstrcat(cmd->tmp_pool, "unknown named connection: ", cmd->argv[0], NULL));
1608 }
1609
1610 conn = (db_conn_t *) entry->data;
1611
1612 /* Make sure the connection is open. */
1613 cmr = cmd_open(cmd);
1614 if (MODRET_ERROR(cmr)) {
1615 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_escapestring");
1616 return cmr;
1617 }
1618
1619 unescaped = cmd->argv[1];
1620 escaped = (char *) pcalloc(cmd->tmp_pool, sizeof(char) *
1621 (strlen(unescaped) * 2) + 1);
1622
1623 /* Note: the mysql_real_escape_string() function appeared in the C API
1624 * as of MySQL 3.23.14; this macro allows functioning with older mysql
1625 * installations.
1626 */
1627 #if MYSQL_VERSION_ID >= 32314
1628 mysql_real_escape_string(conn->mysql, escaped, unescaped, strlen(unescaped));
1629 #else
1630 mysql_escape_string(escaped, unescaped, strlen(unescaped));
1631 #endif
1632
1633 close_cmd = sql_make_cmd(cmd->tmp_pool, 1, entry->name);
1634 cmd_close(close_cmd);
1635 SQL_FREE_CMD(close_cmd);
1636
1637 sql_log(DEBUG_FUNC, "%s", "exiting \tmysql cmd_escapestring");
1638 return mod_create_data(cmd, (void *) escaped);
1639 }
1640
1641 /* Per the MySQL docs for the PASSWORD function, MySQL pre-4.1 passwords
1642 * are always 16 bytes; MySQL 4.1 passwords are 41 bytes AND start with '*'.
1643 * See:
1644 * http://dev.mysql.com/doc/refman/5.7/en/encryption-functions.html#function_password
1645 */
1646
1647 #define MYSQL_PASSWD_FMT_UNKNOWN -1
1648 #define MYSQL_PASSWD_FMT_PRE41 1
1649 #define MYSQL_PASSWD_FMT_41 2
1650 #define MYSQL_PASSWD_FMT_SHA256 3
1651
1652 static int get_mysql_passwd_fmt(const char *txt, size_t txt_len) {
1653 if (txt_len == 16) {
1654 return MYSQL_PASSWD_FMT_PRE41;
1655 }
1656
1657 if (txt_len == 41 &&
1658 txt[0] == '*') {
1659 return MYSQL_PASSWD_FMT_41;
1660 }
1661
1662 if (txt_len > 3 &&
1663 txt[0] == '$' &&
1664 txt[1] == '5' &&
1665 txt[2] == '$') {
1666 return MYSQL_PASSWD_FMT_SHA256;
1667 }
1668
1669 return MYSQL_PASSWD_FMT_UNKNOWN;
1670 }
1671
1672 static int match_mysql_passwds(const char *hashed, size_t hashed_len,
1673 const char *scrambled, size_t scrambled_len, const char *scramble_func) {
1674 int hashed_fmt = 0, scrambled_fmt = 0, matched = FALSE;
1675
1676 if (pr_trace_get_level(trace_channel) >= 7) {
1677 const char *hashed_fmt_name, *scrambled_fmt_name;
1678
1679 hashed_fmt = get_mysql_passwd_fmt(hashed, hashed_len);
1680 scrambled_fmt = get_mysql_passwd_fmt(scrambled, scrambled_len);
1681
1682 switch (hashed_fmt) {
1683 case MYSQL_PASSWD_FMT_PRE41:
1684 hashed_fmt_name = "pre-4.1";
1685 break;
1686
1687 case MYSQL_PASSWD_FMT_41:
1688 hashed_fmt_name = "4.1";
1689 break;
1690
1691 case MYSQL_PASSWD_FMT_SHA256:
1692 hashed_fmt_name = "SHA256";
1693 break;
1694
1695 default:
1696 hashed_fmt_name = "unknown";
1697 break;
1698 }
1699
1700 switch (scrambled_fmt) {
1701 case MYSQL_PASSWD_FMT_PRE41:
1702 scrambled_fmt_name = "pre-4.1";
1703 break;
1704
1705 case MYSQL_PASSWD_FMT_41:
1706 scrambled_fmt_name = "4.1";
1707 break;
1708
1709 case MYSQL_PASSWD_FMT_SHA256:
1710 scrambled_fmt_name = "SHA256";
1711 break;
1712
1713 default:
1714 scrambled_fmt_name = "unknown";
1715 break;
1716 }
1717
1718 pr_trace_msg(trace_channel, 7,
1719 "SQLAuthType Backend: database password format = %s, "
1720 "client library password format = %s (using %s())", hashed_fmt_name,
1721 scrambled_fmt_name, scramble_func);
1722 }
1723
1724 /* Note here that if the scrambled value has a different length than our
1725 * expected hash, it might be a completely different format (i.e. not the
1726 * 4.1 or whatever format provided by the db). Log if this the case!
1727 *
1728 * Consider that using PASSWORD() on the server might make a 4.1 format
1729 * value, but the client lib might make a SHA256 format value. Or
1730 * vice versa.
1731 */
1732 if (scrambled_len == hashed_len) {
1733 matched = (strncmp(scrambled, hashed, hashed_len) == 0);
1734 }
1735
1736 if (matched == FALSE) {
1737 if (hashed_fmt == 0) {
1738 hashed_fmt = get_mysql_passwd_fmt(hashed, hashed_len);
1739 }
1740
1741 if (scrambled_fmt == 0) {
1742 scrambled_fmt = get_mysql_passwd_fmt(scrambled, scrambled_len);
1743 }
1744
1745 if (hashed_fmt != scrambled_fmt) {
1746 if (scrambled_fmt == MYSQL_PASSWD_FMT_SHA256) {
1747 sql_log(DEBUG_FUNC, "MySQL client library used MySQL SHA256 password format, and Backend SQLAuthType cannot succeed; consider using MD5/SHA1/SHA256 SQLAuthType using mod_sql_passwd");
1748 switch (hashed_fmt) {
1749 case MYSQL_PASSWD_FMT_PRE41:
1750 sql_log(DEBUG_FUNC, "MySQL server used MySQL pre-4.1 password format for PASSWORD() value");
1751 break;
1752
1753 case MYSQL_PASSWD_FMT_41:
1754 sql_log(DEBUG_FUNC, "MySQL server used MySQL 4.1 password format for PASSWORD() value");
1755 break;
1756
1757 default:
1758 pr_trace_msg(trace_channel, 19,
1759 "unknown MySQL PASSWORD() format used on server");
1760 break;
1761 }
1762 }
1763 }
1764
1765 pr_trace_msg(trace_channel, 9,
1766 "expected '%.*s' (%lu), got '%.*s' (%lu) using MySQL %s()",
1767 (int) hashed_len, hashed, (unsigned long) hashed_len,
1768 (int) scrambled_len, scrambled, (unsigned long) scrambled_len,
1769 scramble_func);
1770 }
1771
1772 return matched;
1773 }
1774
1775 static modret_t *sql_mysql_password(cmd_rec *cmd, const char *plaintext,
1776 const char *ciphertext) {
1777 char scrambled[256] = {'\0'};
1778 size_t plaintext_len = 0, ciphertext_len = 0, scrambled_len = 0;
1779 int success = 0;
1780
1781 plaintext_len = strlen(plaintext);
1782 ciphertext_len = strlen(ciphertext);
1783
1784 /* Checking order (damn MySQL API changes):
1785 *
1786 * my_make_scrambled_password (if available)
1787 * my_make_scrambled_password_323 (if available)
1788 * make_scrambled_password (if available)
1789 * make_scrammbed_password_323 (if available)
1790 */
1791
1792 #if defined(HAVE_MYSQL_MY_MAKE_SCRAMBLED_PASSWORD)
1793 if (success == FALSE) {
1794 memset(scrambled, '\0', sizeof(scrambled));
1795
1796 my_make_scrambled_password(scrambled, plaintext, plaintext_len);
1797 scrambled_len = strlen(scrambled);
1798
1799 success = match_mysql_passwds(ciphertext, ciphertext_len, scrambled,
1800 scrambled_len, "my_make_scrambled_password");
1801 }
1802 #endif /* HAVE_MYSQL_MY_MAKE_SCRAMBLED_PASSWORD */
1803
1804 #if defined(HAVE_MYSQL_MY_MAKE_SCRAMBLED_PASSWORD_323)
1805 if (success == FALSE) {
1806 memset(scrambled, '\0', sizeof(scrambled));
1807
1808 sql_log(DEBUG_FUNC, "%s",
1809 "checking again using deprecated legacy MySQL password algorithm (my_make_scrambled_password_323 function)");
1810 sql_log(DEBUG_FUNC, "%s",
1811 "warning: support for this legacy MySQ-3.xL password algorithm will be dropped from MySQL in the future");
1812
1813 my_make_scrambled_password_323(scrambled, plaintext, plaintext_len);
1814 scrambled_len = strlen(scrambled);
1815
1816 success = match_mysql_passwds(ciphertext, ciphertext_len, scrambled,
1817 scrambled_len, "my_make_scrambled_password_323");
1818 }
1819 #endif /* HAVE_MYSQL_MY_MAKE_SCRAMBLED_PASSWORD_323 */
1820
1821 #if defined(HAVE_MYSQL_MAKE_SCRAMBLED_PASSWORD)
1822 if (success == FALSE) {
1823 memset(scrambled, '\0', sizeof(scrambled));
1824
1825 # if MYSQL_VERSION_ID >= 40100 && MYSQL_VERSION_ID < 40101
1826 make_scrambled_password(scrambled, plaintext, 1, NULL);
1827 # else
1828 make_scrambled_password(scrambled, plaintext);
1829 # endif
1830 scrambled_len = strlen(scrambled);
1831
1832 success = match_mysql_passwds(ciphertext, ciphertext_len, scrambled,
1833 scrambled_len, "make_scrambled_password");
1834 }
1835 #endif /* HAVE_MYSQL_MAKE_SCRAMBLED_PASSWORD */
1836
1837 #if defined(HAVE_MYSQL_MAKE_SCRAMBLED_PASSWORD_323)
1838 if (success == FALSE) {
1839 memset(scrambled, '\0', sizeof(scrambled));
1840
1841 sql_log(DEBUG_FUNC, "%s",
1842 "checking again using deprecated legacy MySQL password algorithm (make_scrambled_password_323 function)");
1843 sql_log(DEBUG_FUNC, "%s",
1844 "warning: support for this legacy MySQ-3.xL password algorithm will be dropped from MySQL in the future");
1845
1846 make_scrambled_password_323(scrambled, plaintext);
1847 scrambled_len = strlen(scrambled);
1848
1849 success = match_mysql_passwds(ciphertext, ciphertext_len, scrambled,
1850 scrambled_len, "make_scrambled_password_323");
1851 }
1852 #endif /* HAVE_MYSQL_MAKE_SCRAMBLED_PASSWORD_323 */
1853
1854 if (success == FALSE) {
1855 sql_log(DEBUG_FUNC, "%s", "password mismatch");
1856 }
1857
1858 return success ? PR_HANDLED(cmd) : PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1859 }
1860
1861 /*
1862 * cmd_identify: returns API information and an identification string for
1863 * the backend handler. mod_sql will call this at initialization and
1864 * display the identification string. The API version information is
1865 * used by mod_sql to identify available command handlers.
1866 *
1867 * Inputs:
1868 * None. The cmd->tmp_pool can be used to construct the return data, but
1869 * do not depend on any other portion of the cmd_rec to be useful in any way.
1870 *
1871 * Returns:
1872 * A sql_data_t of *exactly* this form:
1873 * sql_data_t->rnum = 1;
1874 * sql_data_t->fnum = 2;
1875 * sql_data_t->data[0] = "identification string"
1876 * sql_data_t->data[0] = "API version"
1877 *
1878 * Notes:
1879 * See mod_sql.h for currently accepted APIs.
1880 */
1881 MODRET cmd_identify(cmd_rec * cmd) {
1882 sql_data_t *sd = NULL;
1883
1884 sql_check_cmd(cmd, "cmd_identify");
1885
1886 sd = (sql_data_t *) pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
1887 sd->data = (char **) pcalloc(cmd->tmp_pool, sizeof(char *) * 2);
1888
1889 sd->rnum = 1;
1890 sd->fnum = 2;
1891
1892 sd->data[0] = MOD_SQL_MYSQL_VERSION;
1893 sd->data[1] = MOD_SQL_API_V1;
1894
1895 return mod_create_data(cmd, (void *) sd);
1896 }
1897
1898 /*
1899 * cmd_prepare: prepares this mod_sql_mysql module for running.
1900 *
1901 * Inputs:
1902 * cmd->argv[0]: A pool to be used for any necessary preparations.
1903 *
1904 * Returns:
1905 * Success.
1906 */
1907 MODRET cmd_prepare(cmd_rec *cmd) {
1908 if (cmd->argc != 1) {
1909 return PR_ERROR(cmd);
1910 }
1911
1912 conn_pool = (pool *) cmd->argv[0];
1913
1914 if (conn_cache == NULL) {
1915 conn_cache = make_array(conn_pool, DEF_CONN_POOL_SIZE,
1916 sizeof(conn_entry_t *));
1917 }
1918
1919 return mod_create_data(cmd, NULL);
1920 }
1921
1922 /*
1923 * cmd_cleanup: cleans up any initialisations made during module preparations
1924 * (see cmd_prepre).
1925 *
1926 * Inputs:
1927 * None.
1928 *
1929 * Returns:
1930 * Success.
1931 */
1932 MODRET cmd_cleanup(cmd_rec *cmd) {
1933 destroy_pool(conn_pool);
1934 conn_pool = NULL;
1935 conn_cache = NULL;
1936
1937 return mod_create_data(cmd, NULL);
1938 }
1939
1940 /* SQL cmdtable: mod_sql requires each backend module to define a cmdtable
1941 * with this exact name. ALL these functions must be defined; mod_sql checks
1942 * that they all exist on startup and ProFTPD will refuse to start if they
1943 * aren't defined.
1944 */
1945 static cmdtable sql_mysql_cmdtable[] = {
1946 { CMD, "sql_close", G_NONE, cmd_close, FALSE, FALSE },
1947 { CMD, "sql_cleanup", G_NONE, cmd_cleanup, FALSE, FALSE },
1948 { CMD, "sql_defineconnection", G_NONE, cmd_defineconnection, FALSE, FALSE },
1949 { CMD, "sql_escapestring", G_NONE, cmd_escapestring, FALSE, FALSE },
1950 { CMD, "sql_exit", G_NONE, cmd_exit, FALSE, FALSE },
1951 { CMD, "sql_identify", G_NONE, cmd_identify, FALSE, FALSE },
1952 { CMD, "sql_insert", G_NONE, cmd_insert, FALSE, FALSE },
1953 { CMD, "sql_open", G_NONE, cmd_open, FALSE, FALSE },
1954 { CMD, "sql_prepare", G_NONE, cmd_prepare, FALSE, FALSE },
1955 { CMD, "sql_procedure", G_NONE, cmd_procedure, FALSE, FALSE },
1956 { CMD, "sql_query", G_NONE, cmd_query, FALSE, FALSE },
1957 { CMD, "sql_select", G_NONE, cmd_select, FALSE, FALSE },
1958 { CMD, "sql_update", G_NONE, cmd_update, FALSE, FALSE },
1959
1960 { 0, NULL }
1961 };
1962
1963 /* Configuration handlers
1964 */
1965
1966 MODRET set_sqlauthtypes(cmd_rec *cmd) {
1967 #if MYSQL_VERSION_ID >= 50600 && \
1968 !defined(HAVE_MYSQL_MAKE_SCRAMBLED_PASSWORD) && \
1969 !defined(HAVE_MYSQL_MAKE_SCRAMBLED_PASSWORD_323) && \
1970 !defined(HAVE_MYSQL_MY_MAKE_SCRAMBLED_PASSWORD_323)
1971 register unsigned int i;
1972
1973 /* If we are using MySQL 5.6.x or later, AND we only have the
1974 * my_make_scrambled_password() MySQL function available, AND the Backend
1975 * SQLAuthType is used, then we must fail the directive; see Bug#4281.
1976 */
1977
1978 for (i = 1; i < cmd->argc; i++) {
1979 const char *auth_type;
1980
1981 auth_type = cmd->argv[i];
1982 if (strcasecmp(auth_type, "Backend") == 0) {
1983 pr_log_pri(PR_LOG_NOTICE, "%s: WARNING: MySQL client library uses MySQL SHA256 password format, and Backend SQLAuthType cannot succeed; consider using MD5/SHA1/SHA256 SQLAuthType using mod_sql_passwd", (char *) cmd->argv[0]);
1984 break;
1985 }
1986 }
1987 #endif
1988
1989 return PR_DECLINED(cmd);
1990 }
1991
1992 /* Event handlers
1993 */
1994
1995 static void sql_mysql_mod_load_ev(const void *event_data, void *user_data) {
1996
1997 if (strcmp("mod_sql_mysql.c", (const char *) event_data) == 0) {
1998 /* Register ourselves with mod_sql. */
1999 if (sql_register_backend("mysql", sql_mysql_cmdtable) < 0) {
2000 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_MYSQL_VERSION
2001 ": notice: error registering backend: %s", strerror(errno));
2002 pr_session_end(0);
2003 }
2004 }
2005 }
2006
2007 static void sql_mysql_mod_unload_ev(const void *event_data, void *user_data) {
2008 if (strcmp("mod_sql_mysql.c", (const char *) event_data) == 0) {
2009 /* Unregister ourselves from all events. */
2010 pr_event_unregister(&sql_mysql_module, NULL, NULL);
2011
2012 /* Unegister ourselves with mod_sql. */
2013 (void) sql_unregister_authtype("Backend");
2014
2015 if (sql_unregister_backend("mysql") < 0) {
2016 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_MYSQL_VERSION
2017 ": notice: error unregistering backend: %s", strerror(errno));
2018 pr_session_end(0);
2019 }
2020 }
2021 }
2022
2023 /* Initialization routines
2024 */
2025
2026 static int sql_mysql_init(void) {
2027
2028 /* Register listeners for the load and unload events. */
2029 pr_event_register(&sql_mysql_module, "core.module-load",
2030 sql_mysql_mod_load_ev, NULL);
2031 pr_event_register(&sql_mysql_module, "core.module-unload",
2032 sql_mysql_mod_unload_ev, NULL);
2033
2034 /* Register our auth handler. */
2035 (void) sql_register_authtype("Backend", sql_mysql_password);
2036 return 0;
2037 }
2038
2039 static int sql_mysql_sess_init(void) {
2040 if (conn_pool != NULL) {
2041 destroy_pool(conn_pool);
2042 conn_cache = NULL;
2043 }
2044
2045 conn_pool = make_sub_pool(session.pool);
2046 pr_pool_tag(conn_pool, "MySQL connection pool");
2047
2048 if (conn_cache == NULL) {
2049 conn_cache = make_array(conn_pool, DEF_CONN_POOL_SIZE,
2050 sizeof(conn_entry_t *));
2051 }
2052
2053 return 0;
2054 }
2055
2056 static conftable sql_mysql_conftab[] = {
2057 { "SQLAuthTypes", set_sqlauthtypes, NULL },
2058
2059 { NULL, NULL, NULL }
2060 };
2061
2062 /* sql_mysql_module: The standard module struct for all ProFTPD modules.
2063 * We use the pre-fork handler to initialize the conn_cache array header.
2064 * Other backend modules may not need any init functions, or may need
2065 * to extend the init functions to initialize other internal variables.
2066 */
2067 module sql_mysql_module = {
2068 /* Always NULL */
2069 NULL, NULL,
2070
2071 /* Module API version */
2072 0x20,
2073
2074 /* Module name */
2075 "sql_mysql",
2076
2077 /* Module configuration directive handlers */
2078 sql_mysql_conftab,
2079
2080 /* Module command handlers */
2081 NULL,
2082
2083 /* Module authentication handlers */
2084 NULL,
2085
2086 /* Module initialization */
2087 sql_mysql_init,
2088
2089 /* Session initialization */
2090 sql_mysql_sess_init,
2091
2092 /* Module version */
2093 MOD_SQL_MYSQL_VERSION
2094 };