Debian Codegraph @

contrib/mod_sql.c

raw symbols SCIP
1 /*
2 * ProFTPD: mod_sql -- SQL frontend
3 * Copyright (c) 1998-1999 Johnie Ingram.
4 * Copyright (c) 2001 Andrew Houghton.
5 * Copyright (c) 2004-2026 TJ Saunders
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
20 *
21 * As a special exemption, Andrew Houghton and other respective copyright
22 * holders give permission to link this program with OpenSSL, and distribute
23 * the resulting executable, without including the source code for OpenSSL in
24 * the source distribution.
25 */
26
27 #include "conf.h"
28 #include "privs.h"
29 #include "mod_sql.h"
30 #include "jot.h"
31
32 #define MOD_SQL_VERSION "mod_sql/4.5"
33
34 #if defined(HAVE_CRYPT_H) && !defined(AIX4) && !defined(AIX5)
35 # include <crypt.h>
36 #endif
37
38 #if defined(HAVE_OPENSSL) || defined(PR_USE_OPENSSL)
39 # include <openssl/evp.h>
40 #endif
41
42 /* Define if you have the LibreSSL library. */
43 #if defined(LIBRESSL_VERSION_NUMBER)
44 # define HAVE_LIBRESSL 1
45 #endif
46
47 /* default information for tables and fields */
48 #define MOD_SQL_DEF_USERTABLE "users"
49 #define MOD_SQL_DEF_USERNAMEFIELD "userid"
50 #define MOD_SQL_DEF_USERUIDFIELD "uid"
51 #define MOD_SQL_DEF_USERGIDFIELD "gid"
52 #define MOD_SQL_DEF_USERPASSWORDFIELD "passwd"
53 #define MOD_SQL_DEF_USERSHELLFIELD "shell"
54 #define MOD_SQL_DEF_USERHOMEDIRFIELD "homedir"
55
56 #define MOD_SQL_DEF_GROUPTABLE "groups"
57 #define MOD_SQL_DEF_GROUPNAMEFIELD "groupname"
58 #define MOD_SQL_DEF_GROUPGIDFIELD "gid"
59 #define MOD_SQL_DEF_GROUPMEMBERSFIELD "members"
60
61 /* default minimum ID / default UID / default GID info.
62 * UIDs and GIDs less than MOD_SQL_MIN_USER_UID and MOD_SQL_MIN_USER_GID,
63 * respectively, get automatically mapped to the defaults, below. These can
64 * be overridden using directives
65 */
66 #define MOD_SQL_MIN_USER_UID 999
67 #define MOD_SQL_MIN_USER_GID 999
68 #define MOD_SQL_DEF_UID 65533
69 #define MOD_SQL_DEF_GID 65533
70
71 #define MOD_SQL_BUFSIZE 32
72
73 /* Named Query defines */
74 #define SQL_SELECT_C "SELECT"
75 #define SQL_INSERT_C "INSERT"
76 #define SQL_UPDATE_C "UPDATE"
77 #define SQL_FREEFORM_C "FREEFORM"
78
79 /* SQLEngine flags */
80 #define SQL_ENGINE_FL_AUTH 0x001
81 #define SQL_ENGINE_FL_LOG 0x002
82
83 /* SQLLog flags */
84 #define SQL_LOG_FL_IGNORE_ERRORS 0x001
85
86 /* authmask defines */
87 #define SQL_AUTH_USERS (1<<0)
88 #define SQL_AUTH_GROUPS (1<<1)
89 #define SQL_AUTH_USERSET (1<<4)
90 #define SQL_AUTH_GROUPSET (1<<5)
91 #define SQL_FAST_USERSET (1<<6)
92 #define SQL_FAST_GROUPSET (1<<7)
93
94 #define SQL_GROUPS (cmap.authmask & SQL_AUTH_GROUPS)
95 #define SQL_USERS (cmap.authmask & SQL_AUTH_USERS)
96 #define SQL_GROUPSET (cmap.authmask & SQL_AUTH_GROUPSET)
97 #define SQL_USERSET (cmap.authmask & SQL_AUTH_USERSET)
98 #define SQL_FASTGROUPS (cmap.authmask & SQL_FAST_GROUPSET)
99 #define SQL_FASTUSERS (cmap.authmask & SQL_FAST_USERSET)
100
101 /*
102 * externs, function signatures.. whatever necessary to make
103 * the compiler happy..
104 */
105
106 module sql_module;
107
108 unsigned long pr_sql_opts = 0UL;
109 unsigned int pr_sql_conn_policy = 0;
110
111 /* For tracking the size of deleted files. */
112 static off_t sql_dele_filesz = 0;
113
114 static int sql_keepalive_timer_id = -1;
115 static const char *sql_keepalive_stmt = NULL;
116
117 /* It is best if this value is larger than the PR_TUNABLE_BUFFER_SIZE value.
118 * PR_TUNABLE_BUFFER_SIZE controls how much network data from a client at
119 * a time we might read; by keeping the statement buffer size larger, we reduce
120 * the chance of handling data from the network which exceeds the statement
121 * buffer length.
122 */
123 #define SQL_MAX_STMT_LEN 4096
124
125 static int sql_sess_init(void);
126
127 static char *sql_prepare_where(int, cmd_rec *, int, ...);
128 #define SQL_PREPARE_WHERE_FL_NO_TAGS 0x00001
129
130 static int resolve_numeric_val(cmd_rec *cmd, const char *val);
131
132 static modret_t *process_named_query(cmd_rec *cmd, char *name, int flags);
133 static const char *get_named_conn_backend(const char *name);
134 static char *get_query_named_conn(config_rec *c);
135 static void set_named_conn_backend(const char *name);
136
137 MODRET sql_auth_getgrent(cmd_rec *cmd);
138 MODRET sql_auth_setgrent(cmd_rec *cmd);
139 MODRET sql_lookup(cmd_rec *cmd);
140
141 static cmdtable *sql_set_backend(const char *name);
142
143 static pool *sql_pool = NULL;
144 static const char *trace_channel = "sql";
145
146 /*
147 * cache typedefs
148 */
149
150 #define CACHE_SIZE 13
151
152 typedef struct cache_entry {
153 struct cache_entry *list_next;
154 struct cache_entry *bucket_next;
155 void *data;
156 } cache_entry_t;
157
158 /* This struct holds invariant information for the current session */
159
160 static struct {
161 /* Info valid after getpwnam(). */
162 char *authuser; /* current authorized user */
163 struct passwd *authpasswd; /* and their passwd struct */
164
165 /* Generic status information. */
166 int engine; /* is mod_sql on? */
167 int authmask; /* authentication mask.
168 * see set_sqlauthenticate for info */
169 /* User table and field information. */
170 char *usrtable; /* user info table name */
171 char *usrfield; /* user name field */
172 char *pwdfield; /* user password field */
173 char *uidfield; /* user UID field */
174 char *gidfield; /* user GID field */
175 char *homedirfield; /* user homedir field */
176 char *shellfield; /* user login shell field */
177 char *userwhere; /* user where clause */
178
179 char *usercustom; /* custom users query (by name) */
180 char *usercustombyid; /* custom users query (by UID) */
181 char *usercustomuserset; /* custom query to get 'userset' users */
182 char *usercustomusersetfast; /* custom query to get 'usersetfast' users */
183
184 /* Group table and field information. */
185 char *grptable; /* group info table name */
186 char *grpfield; /* group name field */
187 char *grpgidfield; /* group GID field */
188 char *grpmembersfield; /* group members field */
189 char *groupwhere; /* group where clause */
190
191 char *groupcustombyname; /* custom group query (by name) */
192 char *groupcustombyid; /* custom group query (by GID) */
193 char *groupcustommembers; /* custom group query (user members only) */
194 char *groupcustomgroupset; /* custom query to get 'groupset' groups */
195 char *groupcustomgroupsetfast;/* custom query to get 'groupsetfast' groups */
196
197 /* Other information. */
198 array_header *auth_list; /* auth handler list */
199 char *defaulthomedir; /* default homedir if no field specified */
200
201 uid_t minid; /* users UID must be this or greater */
202 uid_t minuseruid; /* users UID must be this or greater */
203 gid_t minusergid; /* users UID must be this or greater */
204 uid_t defaultuid; /* default UID if none in database */
205 gid_t defaultgid; /* default GID if none in database */
206
207 cache_entry_t *curr_group; /* next group in group array for getgrent */
208 cache_entry_t *curr_passwd; /* next passwd in passwd array for getpwent */
209 int group_cache_filled;
210 int passwd_cache_filled;
211
212 /* Cache negative, as well as positive, lookups */
213 unsigned char negative_cache;
214
215 /* mod_ratio data -- someday this needs to be removed from mod_sql. */
216 char *sql_fstor; /* fstor int(11) NOT NULL DEFAULT '0', */
217 char *sql_fretr; /* fretr int(11) NOT NULL DEFAULT '0', */
218 char *sql_bstor; /* bstor int(11) NOT NULL DEFAULT '0', */
219 char *sql_bretr; /* bretr int(11) NOT NULL DEFAULT '0', */
220
221 char *sql_frate; /* frate int(11) NOT NULL DEFAULT '5', */
222 char *sql_fcred; /* fcred int(2) NOT NULL DEFAULT '15', */
223 char *sql_brate; /* brate int(11) NOT NULL DEFAULT '5', */
224 char *sql_bcred; /* bcred int(2) NOT NULL DEFAULT '150000', */
225
226 /* Precomputed strings. */
227 char *usrfields;
228 char *grpfields;
229 } cmap;
230
231 /* For handling the SQLBackend directive */
232 struct sql_backend {
233 struct sql_backend *next, *prev;
234 const char *backend;
235 cmdtable *cmdtab;
236 };
237
238 static struct sql_backend *sql_backends = NULL;
239 static unsigned int sql_nbackends = 0;
240 static cmdtable *sql_cmdtable = NULL, *sql_default_cmdtable = NULL;
241
242 /* For handling the SQLNamedConnectInfo directives */
243 struct sql_named_conn {
244 struct sql_named_conn *next, *prev;
245 const char *conn_name;
246 unsigned int conn_policy;
247 const char *backend;
248 };
249
250 static struct sql_named_conn *sql_named_conns = NULL;
251
252 #define MOD_SQL_DEF_CONN_NAME "default"
253
254 /* Look up the backend to use for the named connection. */
255 static const char *get_named_conn_backend(const char *conn_name) {
256 if (conn_name == NULL) {
257 errno = EINVAL;
258 return NULL;
259 }
260
261 /* Make sure that "default" is handled as a reserved connection name. */
262 if (strcmp(conn_name, MOD_SQL_DEF_CONN_NAME) == 0) {
263 errno = EACCES;
264 return NULL;
265 }
266
267 if (sql_named_conns != NULL) {
268 struct sql_named_conn *snc;
269
270 for (snc = sql_named_conns; snc; snc = snc->next) {
271 pr_trace_msg(trace_channel, 17,
272 "comparing requested named connection '%s' with '%s'", conn_name,
273 snc->conn_name);
274
275 if (strcmp(snc->conn_name, conn_name) == 0) {
276 return snc->backend;
277 }
278 }
279
280 pr_trace_msg(trace_channel, 17,
281 "unable to find named connection '%s': no such named connection found",
282 conn_name);
283
284 } else {
285 pr_trace_msg(trace_channel, 17,
286 "unable to find named connection '%s': no named connections registered",
287 conn_name);
288 }
289
290 errno = ENOENT;
291 return NULL;
292 }
293
294 static char *get_query_named_conn(config_rec *c) {
295 char *conn_name = MOD_SQL_DEF_CONN_NAME;
296
297 if (strcasecmp(c->argv[0], SQL_SELECT_C) == 0 ||
298 strcasecmp(c->argv[0], SQL_FREEFORM_C) == 0) {
299 conn_name = c->argv[2];
300
301 } else if (strcasecmp(c->argv[0], SQL_INSERT_C) == 0 ||
302 strcasecmp(c->argv[0], SQL_UPDATE_C) == 0) {
303 conn_name = c->argv[3];
304 }
305
306 return conn_name;
307 }
308
309 static void set_named_conn_backend(const char *conn_name) {
310 const char *backend;
311
312 if (conn_name == NULL) {
313 /* The caller is requesting that we request the backend to the default. */
314 sql_cmdtable = sql_default_cmdtable;
315 return;
316 }
317
318 if (strcmp(conn_name, MOD_SQL_DEF_CONN_NAME) == 0) {
319 sql_cmdtable = sql_default_cmdtable;
320 return;
321 }
322
323 backend = get_named_conn_backend(conn_name);
324 if (backend == NULL) {
325 sql_log(DEBUG_INFO, MOD_SQL_VERSION
326 ": named connection '%s' does not exist, defaulting to '%s'",
327 conn_name, MOD_SQL_DEF_CONN_NAME);
328 sql_cmdtable = sql_default_cmdtable;
329 return;
330 }
331
332 if (sql_set_backend(backend) == NULL) {
333 sql_log(DEBUG_INFO, "unable to load SQL backend '%s': %s", backend,
334 strerror(errno));
335
336 } else {
337 sql_log(DEBUG_INFO, "using named connection '%s', backend '%s' for query",
338 conn_name, backend);
339 }
340 }
341
342 /*
343 * cache functions
344 */
345
346 typedef unsigned int (* val_func)(const void *);
347 typedef int (* cmp_func)(const void *, const void *);
348
349 typedef struct {
350 /* memory pool for this object */
351 pool *pool;
352
353 /* cache buckets */
354 cache_entry_t *buckets[ CACHE_SIZE ];
355
356 /* cache functions */
357 val_func hash_val;
358 cmp_func cmp;
359
360 /* list pointers */
361 cache_entry_t *head;
362
363 /* list size */
364 unsigned int nelts;
365 } cache_t;
366
367 static cache_t *group_name_cache = NULL;
368 static cache_t *group_gid_cache = NULL;
369 static cache_t *passwd_name_cache = NULL;
370 static cache_t *passwd_uid_cache = NULL;
371
372 static cache_t *make_cache(pool *p, val_func hash_val, cmp_func cmp) {
373 cache_t *res;
374
375 if (p == NULL ||
376 hash_val == NULL ||
377 cmp == NULL)
378 return NULL;
379
380 res = (cache_t *) pcalloc(p, sizeof(cache_t));
381
382 res->pool = p;
383 res->hash_val = hash_val;
384 res->cmp = cmp;
385
386 res->head = NULL;
387
388 res->nelts = 0;
389
390 return res;
391 }
392
393 static cache_entry_t *cache_addentry(cache_t *cache, void *data) {
394 cache_entry_t *entry;
395 int hashval;
396
397 if (cache == NULL ||
398 data == NULL)
399 return NULL;
400
401 /* create the entry */
402 entry = (cache_entry_t *) pcalloc(cache->pool, sizeof(cache_entry_t));
403 entry->data = data;
404
405 /* deal with the list */
406
407 if (cache->head == NULL) {
408 cache->head = entry;
409
410 } else {
411 entry->list_next = cache->head;
412 cache->head = entry;
413 }
414
415 /* deal with the buckets */
416 hashval = cache->hash_val(data) % CACHE_SIZE;
417 if (cache->buckets[hashval] == NULL) {
418 cache->buckets[hashval] = entry;
419
420 } else {
421 entry->bucket_next = cache->buckets[hashval];
422 cache->buckets[hashval] = entry;
423 }
424
425 cache->nelts++;
426 return entry;
427 }
428
429 static void *cache_findvalue(cache_t *cache, void *data) {
430 cache_entry_t *entry;
431 int hashval;
432
433 if (cache == NULL ||
434 data == NULL) {
435 errno = EINVAL;
436 return NULL;
437 }
438
439 hashval = cache->hash_val(data) % CACHE_SIZE;
440
441 entry = cache->buckets[hashval];
442 while (entry != NULL) {
443 pr_signals_handle();
444
445 if (cache->cmp(data, entry->data)) {
446 break;
447 }
448
449 entry = entry->bucket_next;
450 }
451
452 return (entry == NULL ? NULL : entry->data);
453 }
454
455 cmd_rec *sql_make_cmd(pool *p, int argc, ...) {
456 register int i = 0;
457 pool *newpool = NULL;
458 cmd_rec *cmd = NULL;
459 va_list args;
460
461 if (argc < 0) {
462 errno = EINVAL;
463 return NULL;
464 }
465
466 newpool = make_sub_pool(p);
467 cmd = pcalloc(newpool, sizeof(cmd_rec));
468 cmd->argc = argc;
469 cmd->stash_index = -1;
470 cmd->pool = newpool;
471
472 cmd->argv = pcalloc(newpool, sizeof(void *) * (argc + 1));
473 cmd->tmp_pool = newpool;
474 cmd->server = main_server;
475
476 va_start(args, argc);
477
478 for (i = 0; i < argc; i++) {
479 cmd->argv[i] = (void *) va_arg(args, char *);
480 }
481 va_end(args);
482
483 cmd->argv[argc] = NULL;
484 return cmd;
485 }
486
487 static int check_response(modret_t *mr, int flags) {
488 if (!MODRET_ISERROR(mr)) {
489 return 0;
490 }
491
492 sql_log(DEBUG_WARN, "%s", "unrecoverable backend error");
493 sql_log(DEBUG_WARN, "error: '%s'", mr->mr_numeric);
494 sql_log(DEBUG_WARN, "message: '%s'", mr->mr_message);
495
496 pr_log_pri(PR_LOG_ERR, MOD_SQL_VERSION
497 ": unrecoverable backend error: (%s) %s", mr->mr_numeric, mr->mr_message);
498 pr_log_pri(PR_LOG_ERR, MOD_SQL_VERSION
499 ": check the SQLLogFile for more details");
500
501 pr_event_generate("mod_sql.db.error", mr->mr_message);
502
503 if (!(flags & SQL_LOG_FL_IGNORE_ERRORS) &&
504 !(pr_sql_opts & SQL_OPT_NO_DISCONNECT_ON_ERROR)) {
505 pr_session_disconnect(&sql_module, PR_SESS_DISCONNECT_BY_APPLICATION,
506 "Database error");
507 }
508
509 if (flags & SQL_LOG_FL_IGNORE_ERRORS) {
510 sql_log(DEBUG_FUNC, "SQLLog IGNORE_ERRORS in effect, not exiting");
511
512 } else {
513 sql_log(DEBUG_FUNC, "SQLOption noDisconnectOnError in effect, not exiting");
514 }
515
516 return -1;
517 }
518
519 static modret_t *sql_dispatch(cmd_rec *cmd, char *cmdname) {
520 modret_t *mr = NULL;
521 register unsigned int i = 0;
522
523 pr_trace_msg(trace_channel, 19, "dispatching SQL command '%s'", cmdname);
524
525 for (i = 0; sql_cmdtable[i].command; i++) {
526 if (strcmp(cmdname, sql_cmdtable[i].command) == 0) {
527 pr_signals_block();
528 mr = sql_cmdtable[i].handler(cmd);
529 pr_signals_unblock();
530 return mr;
531 }
532 }
533
534 sql_log(DEBUG_WARN, "unknown backend handler '%s'", cmdname);
535 return PR_ERROR(cmd);
536 }
537
538 static struct sql_backend *sql_get_backend(const char *backend) {
539 struct sql_backend *sb;
540
541 if (sql_backends == NULL) {
542 pr_trace_msg(trace_channel, 17,
543 "unable to find '%s' backend: no backends registered", backend);
544 return NULL;
545 }
546
547 for (sb = sql_backends; sb; sb = sb->next) {
548 pr_trace_msg(trace_channel, 17,
549 "comparing requested backend '%s' with '%s'", backend, sb->backend);
550
551 if (strcasecmp(sb->backend, backend) == 0) {
552 return sb;
553 }
554 }
555
556 pr_trace_msg(trace_channel, 17,
557 "unable to find '%s' backend: no such backend found", backend);
558 errno = ENOENT;
559 return NULL;
560 }
561
562 /* This function is used by mod_sql backends, to register their
563 * individual backend command tables with the main mod_sql module.
564 */
565 int sql_register_backend(const char *backend, cmdtable *cmdtab) {
566 struct sql_backend *sb;
567
568 if (backend == NULL ||
569 cmdtab == NULL) {
570 errno = EINVAL;
571 return -1;
572 }
573
574 if (sql_pool == NULL) {
575 sql_pool = make_sub_pool(permanent_pool);
576 pr_pool_tag(sql_pool, MOD_SQL_VERSION);
577 }
578
579 /* Check to see if this backend has already been registered. */
580 sb = sql_get_backend(backend);
581 if (sb != NULL) {
582 errno = EEXIST;
583 return -1;
584 }
585
586 sb = pcalloc(sql_pool, sizeof(struct sql_backend));
587 sb->backend = backend;
588 sb->cmdtab = cmdtab;
589
590 if (sql_backends != NULL) {
591 sql_backends->prev = sb;
592 sb->next = sql_backends;
593 }
594
595 sql_backends = sb;
596 sql_nbackends++;
597 pr_trace_msg(trace_channel, 8, "registered '%s' backend", backend);
598
599 return 0;
600 }
601
602 /* Used by mod_sql backends to unregister their backend command tables
603 * from the main mod_sql module.
604 */
605 int sql_unregister_backend(const char *backend) {
606 struct sql_backend *sb;
607
608 if (backend == NULL) {
609 errno = EINVAL;
610 return -1;
611 }
612
613 /* Check to see if this backend has been registered. */
614 sb = sql_get_backend(backend);
615 if (sb == NULL) {
616 errno = ENOENT;
617 return -1;
618 }
619
620 #if !defined(PR_SHARED_MODULE)
621 /* If there is only one registered backend, it cannot be removed.
622 */
623 if (sql_nbackends == 1) {
624 errno = EPERM;
625 return -1;
626 }
627
628 /* Be sure to handle the case where this is the currently active backend. */
629 if (sql_cmdtable &&
630 sb->cmdtab == sql_cmdtable) {
631 errno = EACCES;
632 return -1;
633 }
634 #endif
635
636 /* Remove this backend from the linked list. */
637 if (sb->prev != NULL) {
638 sb->prev->next = sb->next;
639
640 } else {
641 /* This backend is the start of the sql_backends list (prev is NULL),
642 * so we need to update the list head pointer as well.
643 */
644 sql_backends = sb->next;
645 }
646
647 if (sb->next != NULL) {
648 sb->next->prev = sb->prev;
649 }
650
651 sb->prev = sb->next = NULL;
652
653 sql_nbackends--;
654
655 /* NOTE: a counter should be kept of the number of unregistrations,
656 * as the memory for a registration is not freed on unregistration.
657 */
658
659 return 0;
660 }
661
662 /* Determine which backend to use.
663 *
664 * If there is only one registered backend to use, the decision is easy.
665 *
666 * If there are more than one backends, default to using the first
667 * entry in the linked list (last backend module registered). Check
668 * for a given backend name argument, if any, to see if that backend
669 * is available.
670 */
671 static cmdtable *sql_set_backend(const char *backend) {
672 if (sql_nbackends == 0 ||
673 sql_backends == NULL) {
674 pr_log_debug(DEBUG0, MOD_SQL_VERSION ": no SQL backends registered");
675 sql_log(DEBUG_INFO, "%s", "no SQL backends registered");
676 errno = ENOENT;
677 return NULL;
678 }
679
680 if (sql_nbackends == 1) {
681 pr_log_debug(DEBUG8, MOD_SQL_VERSION ": defaulting to '%s' backend",
682 sql_backends->backend);
683 sql_log(DEBUG_INFO, "defaulting to '%s' backend", sql_backends->backend);
684 sql_cmdtable = sql_backends->cmdtab;
685
686 } else if (sql_nbackends > 1) {
687 if (backend != NULL) {
688 struct sql_backend *b;
689
690 for (b = sql_backends; b; b = b->next) {
691 if (strcasecmp(b->backend, backend) == 0) {
692 sql_log(DEBUG_INFO, "using SQLBackend '%s'", backend);
693 sql_cmdtable = b->cmdtab;
694 break;
695 }
696 }
697
698 /* If no match is found, default to using the last entry in the list. */
699 if (sql_cmdtable == NULL) {
700 b = sql_backends;
701 while (b->next != NULL) {
702 pr_signals_handle();
703 b = b->next;
704 }
705
706 sql_log(DEBUG_INFO,
707 "SQLBackend '%s' not found, defaulting to '%s' backend",
708 backend, b->backend);
709 sql_cmdtable = b->cmdtab;
710 }
711
712 } else {
713 /* Default to using the last entry in the list. */
714 struct sql_backend *b = sql_backends;
715
716 while (b->next != NULL) {
717 pr_signals_handle();
718 b = b->next;
719 }
720
721 sql_log(DEBUG_INFO, "defaulting to '%s' backend",
722 b->backend);
723 sql_cmdtable = b->cmdtab;
724 }
725 }
726
727 return sql_cmdtable;
728 }
729
730 /* Text resolvers. */
731
732 struct sql_resolved {
733 char *ptr, *buf;
734 size_t bufsz, buflen;
735
736 /* Used for escaping the resolved values per the database rules. */
737 const char *conn_name;
738 int conn_flags;
739 };
740
741 static int is_escaped_text(const char *text, size_t text_len) {
742 register unsigned int i;
743
744 if (text[0] != '\'') {
745 return FALSE;
746 }
747
748 if (text[text_len-1] != '\'') {
749 return FALSE;
750 }
751
752 for (i = 1; i < text_len-1; i++) {
753 if (text[i] == '\'') {
754 return FALSE;
755 }
756 }
757
758 return TRUE;
759 }
760
761 static int sql_resolved_append_text(pool *p, struct sql_resolved *resolved,
762 const char *text, size_t text_len, int already_escaped) {
763 char *new_text = NULL;
764 size_t new_textlen = 0;
765
766 if (text == NULL ||
767 text_len == 0) {
768 return 0;
769 }
770
771 new_text = (char *) text;
772 new_textlen = text_len;
773
774 if (already_escaped == FALSE) {
775 /* For backward compatibility (see Issue #1149), we indulge in a little
776 * heuristic here, and only escape the text if it hasn't already been
777 * escaped. How to properly tell? If the first and last characters of
778 * the given text are `'`, AND there are no other occurrences of that
779 * character in the text, assume it has already been quoted.
780 *
781 * Per Issue #2052, we refine this to use this heuristic only if we do
782 * not already know that the text has been escaped. Some callers may
783 * have already escaped the provided text for us.
784 */
785 if (is_escaped_text(text, text_len) == FALSE) {
786 modret_t *mr;
787
788 mr = sql_dispatch(sql_make_cmd(p, 2, resolved->conn_name, text),
789 "sql_escapestring");
790 if (check_response(mr, resolved->conn_flags) < 0) {
791 errno = EIO;
792 return -1;
793 }
794
795 new_text = (char *) mr->data;
796 new_textlen = strlen(new_text);
797
798 } else {
799 pr_trace_msg(trace_channel, 17,
800 "text '%s' is already escaped, skipping escaping it again", text);
801 }
802 }
803
804 if (new_textlen > resolved->buflen) {
805 new_textlen = resolved->buflen;
806 }
807
808 pr_trace_msg(trace_channel, 19, "appending text '%.*s' (%lu) to buffer",
809 (int) new_textlen, new_text, (unsigned long) new_textlen);
810 memcpy(resolved->buf, new_text, new_textlen);
811 resolved->buf += new_textlen;
812 resolved->buflen -= new_textlen;
813
814 return 0;
815 }
816
817 static int sql_resolve_on_meta(pool *p, pr_jot_ctx_t *jot_ctx,
818 unsigned char logfmt_id, const char *jot_hint, const void *val) {
819 int res = 0, already_escaped = FALSE;
820 struct sql_resolved *resolved;
821
822 resolved = jot_ctx->log;
823 if (resolved->buflen > 0) {
824 const char *text = NULL;
825 size_t text_len = 0;
826 char buf[1024];
827
828 switch (logfmt_id) {
829 case LOGFMT_META_MICROSECS: {
830 unsigned long num;
831
832 num = *((double *) val);
833 text_len = pr_snprintf(buf, sizeof(buf)-1, "%06lu", num);
834 buf[text_len] = '\0';
835 text = buf;
836 break;
837 }
838
839 case LOGFMT_META_MILLISECS: {
840 unsigned long num;
841
842 num = *((double *) val);
843 text_len = pr_snprintf(buf, sizeof(buf)-1, "%03lu", num);
844 buf[text_len] = '\0';
845 text = buf;
846 break;
847 }
848
849 case LOGFMT_META_LOCAL_PORT:
850 case LOGFMT_META_REMOTE_PORT:
851 case LOGFMT_META_RESPONSE_CODE:
852 case LOGFMT_META_XFER_PORT: {
853 int num;
854
855 num = (int) *((double *) val);
856 text_len = pr_snprintf(buf, sizeof(buf)-1, "%d", num);
857 buf[text_len] = '\0';
858 text = buf;
859 break;
860 }
861
862 case LOGFMT_META_UID: {
863 uid_t uid;
864
865 uid = *((double *) val);
866 text = pr_uid2str(p, uid);
867 break;
868 }
869
870 case LOGFMT_META_GID: {
871 gid_t gid;
872
873 gid = *((double *) val);
874 text = pr_gid2str(p, gid);
875 break;
876 }
877
878 case LOGFMT_META_BYTES_SENT:
879 case LOGFMT_META_FILE_OFFSET:
880 case LOGFMT_META_FILE_SIZE:
881 case LOGFMT_META_RAW_BYTES_IN:
882 case LOGFMT_META_RAW_BYTES_OUT:
883 case LOGFMT_META_RESPONSE_MS:
884 case LOGFMT_META_XFER_MS: {
885 off_t num;
886
887 num = *((double *) val);
888 text_len = pr_snprintf(buf, sizeof(buf)-1, "%" PR_LU, (pr_off_t) num);
889 buf[text_len] = '\0';
890 text = buf;
891 break;
892 }
893
894 case LOGFMT_META_EPOCH:
895 case LOGFMT_META_PID: {
896 unsigned long num;
897
898 num = *((double *) val);
899 text_len = pr_snprintf(buf, sizeof(buf)-1, "%lu", num);
900 buf[text_len] = '\0';
901 text = buf;
902 break;
903 }
904
905 case LOGFMT_META_FILE_MODIFIED: {
906 int truth;
907
908 truth = *((int *) val);
909 text = truth ? "true" : "false";
910 break;
911 }
912
913 case LOGFMT_META_SECONDS: {
914 float num;
915
916 num = *((double *) val);
917 text_len = pr_snprintf(buf, sizeof(buf)-1, "%0.3f", num);
918 buf[text_len] = '\0';
919 text = buf;
920 break;
921 }
922
923 /* Jot uses gmtime; for backward compatibility, we need to use
924 * localtime.
925 */
926 case LOGFMT_META_TIME: {
927 const char *time_fmt = "%Y-%m-%d %H:%M:%S %z";
928 struct tm *tm;
929 time_t now;
930
931 now = time(NULL);
932 tm = pr_localtime(p, &now);
933
934 if (jot_hint != NULL) {
935 time_fmt = jot_hint;
936 }
937
938 text_len = strftime(buf, sizeof(buf)-1, time_fmt, tm);
939 buf[text_len] = '\0';
940 text = buf;
941 break;
942 }
943
944 case LOGFMT_META_CUSTOM: {
945 register unsigned int i;
946 const char *val_text;
947 size_t val_textlen;
948 cmd_rec *cmd;
949 int is_hook_sql_cmd = FALSE, is_numeric_tag = TRUE;
950
951 cmd = (cmd_rec *) jot_ctx->user_data;
952 val_text = (const char *) val;
953 val_textlen = strlen(val_text);
954
955 for (i = 0; i < val_textlen-1; i++) {
956 if (!PR_ISDIGIT(val_text[i])) {
957 is_numeric_tag = FALSE;
958 break;
959 }
960 }
961
962 /* Numeric tags are reserved ONLY for use by internally-generated
963 * "sql_lookup" or "sql_change" cmd_recs, which have at least 2
964 * parameters. Hence why we add 2 to the retrieved index value later.
965 *
966 * Skip such processing for any other commd. (Why only these two
967 * internally-generated commands? Those are the ones registered as
968 * HOOKs, and are only used by other modules.)
969 */
970 if (is_numeric_tag == TRUE) {
971 if (strcasecmp(cmd->argv[0], "sql_change") == 0) {
972 is_hook_sql_cmd = TRUE;
973
974 } else if (strcasecmp(cmd->argv[0], "sql_lookup") == 0) {
975 is_hook_sql_cmd = TRUE;
976 }
977
978 if (is_hook_sql_cmd == FALSE) {
979 sql_log(DEBUG_FUNC,
980 "ignoring non-internal SQL command '%s' for resolving numeric "
981 "reference '%s' in query", (char *) cmd->argv[0], val_text);
982 }
983 }
984
985 if (is_numeric_tag == TRUE &&
986 is_hook_sql_cmd == TRUE) {
987 int idx;
988
989 idx = resolve_numeric_val(cmd, val_text);
990 if (idx < 0) {
991 sql_log(DEBUG_FUNC, "out-of-bounds numeric reference '%s' in query",
992 val_text);
993 errno = EIO;
994 return -1;
995 }
996
997 text = cmd->argv[idx+2];
998 }
999
1000 break;
1001 }
1002
1003 /* Per Issue #2052, the following variable values can all be supplied
1004 * remotely by the client. As such, they should be escaped preemptively.
1005 */
1006 case LOGFMT_META_ANON_PASS:
1007 case LOGFMT_META_BASENAME:
1008 case LOGFMT_META_CMD_PARAMS:
1009 case LOGFMT_META_COMMAND:
1010 case LOGFMT_META_DIR_NAME:
1011 case LOGFMT_META_DIR_PATH:
1012 case LOGFMT_META_ENV_VAR:
1013 case LOGFMT_META_FILENAME:
1014 case LOGFMT_META_IDENT_USER:
1015 case LOGFMT_META_METHOD:
1016 case LOGFMT_META_NOTE_VAR:
1017 case LOGFMT_META_ORIGINAL_USER:
1018 case LOGFMT_META_RESPONSE_STR:
1019 case LOGFMT_META_REMOTE_HOST:
1020 case LOGFMT_META_RENAME_FROM:
1021 case LOGFMT_META_USER:
1022 case LOGFMT_META_XFER_PATH: {
1023 modret_t *mr;
1024
1025 mr = sql_dispatch(sql_make_cmd(p, 2, resolved->conn_name,
1026 (const char *) val), "sql_escapestring");
1027 if (check_response(mr, resolved->conn_flags) < 0) {
1028 errno = EIO;
1029 return -1;
1030 }
1031
1032 text = (char *) mr->data;
1033 text_len = strlen(text);
1034 already_escaped = TRUE;
1035 break;
1036 }
1037
1038 case LOGFMT_META_CLASS:
1039 case LOGFMT_META_EOS_REASON:
1040 case LOGFMT_META_GROUP:
1041 case LOGFMT_META_ISO8601:
1042 case LOGFMT_META_LOCAL_FQDN:
1043 case LOGFMT_META_LOCAL_IP:
1044 case LOGFMT_META_LOCAL_NAME:
1045 case LOGFMT_META_PROTOCOL:
1046 case LOGFMT_META_REMOTE_IP:
1047 case LOGFMT_META_VERSION:
1048 case LOGFMT_META_VHOST_IP:
1049 case LOGFMT_META_XFER_FAILURE:
1050 case LOGFMT_META_XFER_SPEED:
1051 case LOGFMT_META_XFER_STATUS:
1052 case LOGFMT_META_XFER_TYPE:
1053 default:
1054 text = val;
1055 break;
1056 }
1057
1058 if (text != NULL &&
1059 text_len == 0) {
1060 text_len = strlen(text);
1061 }
1062
1063 res = sql_resolved_append_text(p, resolved, text, text_len,
1064 already_escaped);
1065 }
1066
1067 return res;
1068 }
1069
1070 static int sql_resolve_on_default(pool *p, pr_jot_ctx_t *jot_ctx,
1071 unsigned char logfmt_id) {
1072 int res = 0;
1073 struct sql_resolved *resolved;
1074
1075 resolved = jot_ctx->log;
1076 if (resolved->buflen > 0) {
1077 const char *text = NULL;
1078 size_t text_len = 0;
1079
1080 switch (logfmt_id) {
1081 case LOGFMT_META_ANON_PASS:
1082 case LOGFMT_META_IDENT_USER:
1083 text = "UNKNOWN";
1084 text_len = strlen(text);
1085 break;
1086
1087 case LOGFMT_META_BYTES_SENT:
1088 case LOGFMT_META_SECONDS:
1089 text = "0.0";
1090 text_len = strlen(text);
1091 break;
1092
1093 case LOGFMT_META_BASENAME:
1094 case LOGFMT_META_CLASS:
1095 case LOGFMT_META_FILENAME:
1096 case LOGFMT_META_FILE_OFFSET:
1097 case LOGFMT_META_FILE_SIZE:
1098 case LOGFMT_META_GROUP:
1099 case LOGFMT_META_ORIGINAL_USER:
1100 case LOGFMT_META_RENAME_FROM:
1101 case LOGFMT_META_RESPONSE_CODE:
1102 case LOGFMT_META_RESPONSE_MS:
1103 case LOGFMT_META_RESPONSE_STR:
1104 case LOGFMT_META_USER:
1105 case LOGFMT_META_XFER_FAILURE:
1106 case LOGFMT_META_XFER_MS:
1107 case LOGFMT_META_XFER_PATH:
1108 case LOGFMT_META_XFER_STATUS:
1109 case LOGFMT_META_XFER_TYPE:
1110 text = "-";
1111 text_len = 1;
1112 break;
1113
1114 /* These explicitly do NOT have default values. */
1115 case LOGFMT_META_CMD_PARAMS:
1116 case LOGFMT_META_COMMAND:
1117 case LOGFMT_META_DIR_NAME:
1118 case LOGFMT_META_DIR_PATH:
1119 case LOGFMT_META_ENV_VAR:
1120 case LOGFMT_META_EOS_REASON:
1121 case LOGFMT_META_NOTE_VAR:
1122 case LOGFMT_META_METHOD:
1123 default:
1124 break;
1125 }
1126
1127 res = sql_resolved_append_text(p, resolved, text, text_len, FALSE);
1128 }
1129
1130 return res;
1131 }
1132
1133 static int sql_resolve_on_other(pool *p, pr_jot_ctx_t *jot_ctx,
1134 unsigned char *text, size_t text_len) {
1135 struct sql_resolved *resolved;
1136
1137 resolved = jot_ctx->log;
1138 if (resolved->buflen > 0) {
1139 if (text_len > resolved->buflen) {
1140 text_len = resolved->buflen;
1141 }
1142
1143 pr_trace_msg(trace_channel, 19, "appending text '%.*s' (%lu) to buffer",
1144 (int) text_len, text, (unsigned long) text_len);
1145 memcpy(resolved->buf, text, text_len);
1146 resolved->buf += text_len;
1147 resolved->buflen -= text_len;
1148 }
1149
1150 return 0;
1151 }
1152
1153 /* Default SQL password handlers (a.k.a. "AuthTypes") provided by mod_sql. */
1154
1155 static modret_t *sql_auth_crypt(cmd_rec *cmd, const char *plaintext,
1156 const char *ciphertext) {
1157 char *res = NULL;
1158
1159 if (*ciphertext == '\0') {
1160 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1161 }
1162
1163 res = (char *) crypt(plaintext, ciphertext);
1164 if (res == NULL) {
1165 sql_log(DEBUG_WARN, "error using crypt(3): %s", strerror(errno));
1166 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1167 }
1168
1169 if (strcmp(res, ciphertext) == 0) {
1170 return PR_HANDLED(cmd);
1171 }
1172
1173 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1174 }
1175
1176 static modret_t *sql_auth_plaintext(cmd_rec *cmd, const char *plaintext,
1177 const char *ciphertext) {
1178
1179 if (*ciphertext == '\0') {
1180 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1181 }
1182
1183 if (strcmp(plaintext, ciphertext) == 0) {
1184 return PR_HANDLED(cmd);
1185 }
1186
1187 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1188 }
1189
1190 static modret_t *sql_auth_empty(cmd_rec *cmd, const char *plaintext,
1191 const char *ciphertext) {
1192
1193 if (strcmp(ciphertext, "") == 0) {
1194 return PR_HANDLED(cmd);
1195 }
1196
1197 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1198 }
1199
1200 #if defined(HAVE_OPENSSL) || defined(PR_USE_OPENSSL)
1201 static modret_t *sql_auth_openssl(cmd_rec *cmd, const char *plaintext,
1202 const char *ciphertext) {
1203
1204 /* The ciphertext argument is a combined digest name and hashed value, of
1205 * the form "{digest}hash".
1206 */
1207
1208 EVP_MD_CTX *md_ctx;
1209 const EVP_MD *md;
1210
1211 /* According to RATS, the output buffer (buf) for EVP_EncodeBlock() needs to
1212 * be 4/3 the size of the input buffer (mdval). Let's make it easy, and
1213 * use an output buffer that's twice the size of the input buffer.
1214 */
1215 unsigned char buf[EVP_MAX_MD_SIZE*2], mdval[EVP_MAX_MD_SIZE];
1216 unsigned int mdlen;
1217
1218 char *digestname; /* ptr to name of the digest function */
1219 char *hashvalue; /* ptr to hashed value we're comparing to */
1220 char *copytext; /* temporary copy of the ciphertext string */
1221
1222 if (ciphertext[0] != '{') {
1223 sql_log(DEBUG_WARN, "%s", "no digest found in password hash");
1224 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1225 }
1226
1227 /* We need a copy of the ciphertext. */
1228 copytext = pstrdup(cmd->tmp_pool, ciphertext);
1229
1230 digestname = copytext + 1;
1231
1232 hashvalue = (char *) strchr(copytext, '}');
1233 if (hashvalue == NULL) {
1234 sql_log(DEBUG_WARN, "%s", "no terminating '}' for digest");
1235 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1236 }
1237
1238 *hashvalue = '\0';
1239 hashvalue++;
1240
1241 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
1242 defined(HAVE_LIBRESSL)
1243 OpenSSL_add_all_digests();
1244 #endif /* OpenSSL-1.1.0 and later */
1245
1246 md = EVP_get_digestbyname(digestname);
1247 if (md == NULL) {
1248 sql_log(DEBUG_WARN, "no such digest '%s' supported", digestname);
1249 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1250 }
1251
1252 md_ctx = EVP_MD_CTX_create();
1253 EVP_DigestInit(md_ctx, md);
1254 EVP_DigestUpdate(md_ctx, plaintext, strlen(plaintext));
1255 EVP_DigestFinal(md_ctx, mdval, &mdlen);
1256 EVP_MD_CTX_destroy(md_ctx);
1257
1258 memset(buf, '\0', sizeof(buf));
1259 EVP_EncodeBlock(buf, mdval, (int) mdlen);
1260
1261 if (strcmp((char *) buf, hashvalue) == 0) {
1262 return PR_HANDLED(cmd);
1263 }
1264
1265 return PR_ERROR_INT(cmd, PR_AUTH_BADPWD);
1266 }
1267 #endif
1268
1269 struct sql_authtype_handler {
1270 struct sql_authtype_handler *next, *prev;
1271 pool *pool;
1272 const char *name;
1273 modret_t *(*cb)(cmd_rec *, const char *, const char *);
1274 };
1275
1276 static struct sql_authtype_handler *sql_auth_list = NULL;
1277
1278 static struct sql_authtype_handler *sql_get_authtype(const char *name) {
1279 if (sql_auth_list) {
1280 struct sql_authtype_handler *sah;
1281
1282 for (sah = sql_auth_list; sah; sah = sah->next) {
1283 if (strcasecmp(sah->name, name) == 0) {
1284 return sah;
1285 }
1286 }
1287 }
1288
1289 errno = ENOENT;
1290 return NULL;
1291 }
1292
1293 int sql_register_authtype(const char *name,
1294 modret_t *(*cb)(cmd_rec *, const char *, const char *)) {
1295 struct sql_authtype_handler *sah;
1296 pool *p;
1297
1298 if (name == NULL ||
1299 cb == NULL) {
1300 errno = EINVAL;
1301 return -1;
1302 }
1303
1304 /* Check for duplicates. */
1305 sah = sql_get_authtype(name);
1306 if (sah != NULL) {
1307 errno = EEXIST;
1308 return -1;
1309 }
1310
1311 if (sql_pool == NULL) {
1312 sql_pool = make_sub_pool(permanent_pool);
1313 pr_pool_tag(sql_pool, MOD_SQL_VERSION);
1314 }
1315
1316 p = pr_pool_create_sz(sql_pool, 128);
1317 sah = pcalloc(p, sizeof(struct sql_authtype_handler));
1318 sah->pool = p;
1319 sah->name = pstrdup(sah->pool, name);
1320 sah->cb = cb;
1321
1322 if (sql_auth_list) {
1323 sql_auth_list->prev = sah;
1324 sah->next = sql_auth_list;
1325 }
1326
1327 sql_auth_list = sah;
1328 return 0;
1329 }
1330
1331 int sql_unregister_authtype(const char *name) {
1332
1333 if (name == NULL) {
1334 errno = EINVAL;
1335 return -1;
1336 }
1337
1338 if (sql_auth_list) {
1339 struct sql_authtype_handler *sah;
1340
1341 for (sah = sql_auth_list; sah; sah = sah->next) {
1342 if (strcasecmp(sah->name, name) == 0) {
1343 if (sah->prev) {
1344 sah->prev->next = sah->next;
1345
1346 } else {
1347 /* This backend is the start of the list, so update the list
1348 * head pointer as well.
1349 */
1350 sql_auth_list = sah->next;
1351 }
1352
1353 if (sah->next) {
1354 sah->next->prev = sah->prev;
1355 }
1356
1357 destroy_pool(sah->pool);
1358 return 0;
1359 }
1360 }
1361 }
1362
1363 errno = ENOENT;
1364 return -1;
1365 }
1366
1367 /*****************************************************************
1368 *
1369 * INTERNAL HELPER FUNCTIONS
1370 *
1371 *****************************************************************/
1372
1373 /* find who core thinks is the user, and return a (backend-escaped)
1374 * version of that name */
1375 static char *_sql_realuser(cmd_rec *cmd) {
1376 modret_t *mr = NULL;
1377 const char *user = NULL;
1378
1379 /* this is the userid given by the user */
1380 user = pr_table_get(session.notes, "mod_auth.orig-user", NULL);
1381
1382 /* Do we need to check for useralias? see mod_time.c, get_user_cmd_times(). */
1383 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
1384 user), "sql_escapestring");
1385 if (check_response(mr, 0) < 0) {
1386 return NULL;
1387 }
1388
1389 return mr ? (char *) mr->data : NULL;
1390 }
1391
1392 static int sql_define_conn(pool *p, const char *conn_name, const char *user,
1393 const char *passwd, const char *info, const char *ttl,
1394 const char *ssl_cert_file, const char *ssl_key_file,
1395 const char *ssl_ca_file, const char *ssl_ca_dir, const char *ssl_ciphers) {
1396 cmd_rec *cmd = NULL;
1397 modret_t *mr = NULL;
1398
1399 /* For backward compatibility of sub-modules' 'defineconn' handler, only
1400 * provide the SSL-related parameters if they are present.
1401 */
1402 if (ssl_cert_file != NULL ||
1403 ssl_key_file != NULL ||
1404 ssl_ca_file != NULL ||
1405 ssl_ca_dir != NULL ||
1406 ssl_ciphers != NULL) {
1407 cmd = sql_make_cmd(p, 10, conn_name, user, passwd, info, ttl, ssl_cert_file,
1408 ssl_key_file, ssl_ca_file, ssl_ca_dir, ssl_ciphers);
1409
1410 } else {
1411 cmd = sql_make_cmd(p, 5, conn_name, user, passwd, info, ttl);
1412 }
1413
1414 mr = sql_dispatch(cmd, "sql_defineconnection");
1415 if (check_response(mr, 0) < 0) {
1416 return -1;
1417 }
1418
1419 SQL_FREE_CMD(cmd);
1420
1421 if (pr_sql_conn_policy == SQL_CONN_POLICY_PERCONN) {
1422 /* Open a database connection now, so that we have a database connection
1423 * for the lifetime of the client's connection to the server.
1424 */
1425 cmd = sql_make_cmd(p, 1, conn_name);
1426 mr = sql_dispatch(cmd, "sql_open");
1427 if (check_response(mr, 0) < 0) {
1428 return -1;
1429 }
1430
1431 SQL_FREE_CMD(cmd);
1432 }
1433
1434 return 0;
1435 }
1436
1437 static char *sql_prepare_where(int flags, cmd_rec *cmd, int cnt, ...) {
1438 int i, flag, nclauses = 0, res;
1439 char *buf = "", *where_clause;
1440 unsigned char *logfmt = NULL;
1441 size_t len = 0;
1442 va_list dummy;
1443 pool *tmp_pool;
1444 pr_jot_ctx_t *jot_ctx;
1445 pr_jot_parsed_t *jot_parsed;
1446 struct sql_resolved *resolved;
1447
1448 flag = 0;
1449 va_start(dummy, cnt);
1450 for (i = 0; i < cnt; i++) {
1451 char *clause = va_arg(dummy, char *);
1452 if (clause != NULL &&
1453 *clause != '\0') {
1454 nclauses++;
1455
1456 if (flag++) {
1457 buf = pstrcat(cmd->tmp_pool, buf, " AND ", NULL);
1458 }
1459 buf = pstrcat(cmd->tmp_pool, buf, "(", clause, ")", NULL);
1460 }
1461 }
1462 va_end(dummy);
1463
1464 if (nclauses == 0) {
1465 return NULL;
1466 }
1467
1468 if (flags & SQL_PREPARE_WHERE_FL_NO_TAGS) {
1469 /* Return the provided buffer as is; no processing needed. */
1470 return buf;
1471 }
1472
1473 /* In this function, we want to parse AND resolve the text in the same
1474 * step, IGNORING custom tags. The resolved text is what we return.
1475 */
1476
1477 tmp_pool = make_sub_pool(cmd->tmp_pool);
1478
1479 /* Allocate one byte more for the terminating NUL. */
1480 logfmt = pcalloc(tmp_pool, SQL_MAX_STMT_LEN + 1);
1481
1482 jot_ctx = pcalloc(tmp_pool, sizeof(pr_jot_ctx_t));
1483 jot_parsed = pcalloc(tmp_pool, sizeof(pr_jot_parsed_t));
1484 jot_parsed->bufsz = jot_parsed->buflen = SQL_MAX_STMT_LEN;
1485 jot_parsed->ptr = jot_parsed->buf = logfmt;
1486
1487 jot_ctx->log = jot_parsed;
1488
1489 /* Process variables in WHERE clauses, except any "%{num}" references. */
1490 res = pr_jot_parse_logfmt(tmp_pool, buf, jot_ctx, pr_jot_parse_on_meta,
1491 pr_jot_parse_on_unknown, pr_jot_parse_on_other, 0);
1492 if (res < 0) {
1493 sql_log(DEBUG_FUNC, "error parsing WHERE clause '%s': %s", buf,
1494 strerror(errno));
1495 destroy_pool(tmp_pool);
1496 return NULL;
1497 }
1498
1499 len = jot_parsed->bufsz - jot_parsed->buflen;
1500 logfmt[len] = '\0';
1501
1502 /* Allocate one byte more for the terminating NUL. */
1503 where_clause = pcalloc(cmd->tmp_pool, SQL_MAX_STMT_LEN + 1);
1504
1505 resolved = pcalloc(tmp_pool, sizeof(struct sql_resolved));
1506 resolved->bufsz = resolved->buflen = SQL_MAX_STMT_LEN;
1507 resolved->ptr = resolved->buf = where_clause;
1508 resolved->conn_name = MOD_SQL_DEF_CONN_NAME;
1509
1510 jot_ctx->log = resolved;
1511 jot_ctx->user_data = cmd;
1512
1513 res = pr_jot_resolve_logfmt(tmp_pool, cmd, NULL, logfmt, jot_ctx,
1514 sql_resolve_on_meta, sql_resolve_on_default, sql_resolve_on_other);
1515 if (res < 0) {
1516 sql_log(DEBUG_FUNC, "error resolving WHERE clause '%s': %s", buf,
1517 strerror(errno));
1518 destroy_pool(tmp_pool);
1519 return NULL;
1520 }
1521
1522 len = resolved->bufsz - resolved->buflen;
1523 where_clause[len] = '\0';
1524
1525 destroy_pool(tmp_pool);
1526
1527 pr_trace_msg(trace_channel, 19, "prepared WHERE clause '%s' as '%s'",
1528 buf, where_clause);
1529 return where_clause;
1530 }
1531
1532 static int _sql_strcmp(const char *s1, const char *s2) {
1533 if ((s1 == NULL) || (s2 == NULL)) {
1534 return 1;
1535 }
1536
1537 return strcmp(s1, s2);
1538 }
1539
1540 static unsigned int _group_gid(const void *val) {
1541 if (val == NULL) {
1542 return 0;
1543 }
1544
1545 return ((struct group *) val)->gr_gid;
1546 }
1547
1548 static unsigned int _group_name(const void *val) {
1549 register unsigned int i;
1550 size_t namelen;
1551 char *name;
1552 unsigned int nameval = 0;
1553
1554 if (val == NULL) {
1555 return 0;
1556 }
1557
1558 name = ((struct group *) val)->gr_name;
1559 if (name == NULL) {
1560 return 0;
1561 }
1562
1563 namelen = strlen(name);
1564 for (i = 0; i < namelen; i++) {
1565 nameval += name[i];
1566 }
1567
1568 return nameval;
1569 }
1570
1571 static int _groupcmp(const void *val1, const void *val2) {
1572 if ((val1 == NULL) || (val2 == NULL)) {
1573 return 0;
1574 }
1575
1576 /* either the groupnames match or the GIDs match */
1577 if (_sql_strcmp(((struct group *) val1)->gr_name,
1578 ((struct group *) val2)->gr_name) == 0) {
1579 return 1;
1580 }
1581
1582 if (((struct group *) val1)->gr_gid == ((struct group *) val2)->gr_gid) {
1583 return 1;
1584 }
1585
1586 return 0;
1587 }
1588
1589 static unsigned int _passwd_uid(const void *val) {
1590 if (val == NULL) {
1591 return 0;
1592 }
1593
1594 return ((struct passwd *) val)->pw_uid;
1595 }
1596
1597 static unsigned int _passwd_name(const void *val) {
1598 register unsigned int i;
1599 char *name;
1600 size_t namelen;
1601 unsigned int nameval = 0;
1602
1603 if (val == NULL) {
1604 return 0;
1605 }
1606
1607 name = ((struct passwd *) val)->pw_name;
1608 if (name == NULL) {
1609 return 0;
1610 }
1611
1612 namelen = strlen(name);
1613 for (i = 0; i < namelen; i++) {
1614 nameval += name[i];
1615 }
1616
1617 return nameval;
1618 }
1619
1620 static int _passwdcmp(const void *val1, const void *val2) {
1621 if ((val1 == NULL) || (val2 == NULL)) {
1622 return 0;
1623 }
1624
1625 /* either the usernames match or the UIDs match */
1626 if (_sql_strcmp(((struct passwd *) val1)->pw_name,
1627 ((struct passwd *) val2)->pw_name) == 0) {
1628 return 1;
1629 }
1630
1631 if (((struct passwd *) val1)->pw_uid == ((struct passwd *) val2)->pw_uid) {
1632 return 1;
1633 }
1634
1635 return 0;
1636 }
1637
1638 static void show_group(pool *p, struct group *g) {
1639 char *members = "";
1640
1641 if (g == NULL) {
1642 sql_log(DEBUG_INFO, "%s", "NULL group to show_group()");
1643 return;
1644 }
1645
1646 if (g->gr_mem != NULL) {
1647 char **member;
1648
1649 member = g->gr_mem;
1650
1651 while (*member != NULL) {
1652 pr_signals_handle();
1653
1654 members = pstrcat(p, members, *members ? ", " : "", *member, NULL);
1655 member++;
1656 }
1657 }
1658
1659 sql_log(DEBUG_INFO, "+ grp.gr_name : %s", g->gr_name);
1660 sql_log(DEBUG_INFO, "+ grp.gr_gid : %s", pr_gid2str(NULL, g->gr_gid));
1661 sql_log(DEBUG_INFO, "+ grp.gr_mem : %s", members);
1662
1663 return;
1664 }
1665
1666 static void show_passwd(struct passwd *p) {
1667 if (p == NULL) {
1668 sql_log(DEBUG_INFO, "%s", "NULL passwd to show_passwd()");
1669 return;
1670 }
1671
1672 sql_log(DEBUG_INFO, "+ pwd.pw_name : %s", p->pw_name);
1673 sql_log(DEBUG_INFO, "+ pwd.pw_uid : %s", pr_uid2str(NULL, p->pw_uid));
1674 sql_log(DEBUG_INFO, "+ pwd.pw_gid : %s", pr_gid2str(NULL, p->pw_gid));
1675 sql_log(DEBUG_INFO, "+ pwd.pw_dir : %s", p->pw_dir ?
1676 p->pw_dir : "(null)");
1677 sql_log(DEBUG_INFO, "+ pwd.pw_shell : %s", p->pw_shell ?
1678 p->pw_shell : "(null)");
1679
1680 return;
1681 }
1682
1683 /* _sql_addpasswd: creates a passwd and adds it to the passwd struct
1684 * cache if it doesn't already exist. Returns the created passwd
1685 * struct, or the pre-existing struct if there was one.
1686 *
1687 * DOES NOT CHECK ARGUMENTS. CALLING FUNCTIONS NEED TO MAKE SURE
1688 * THEY PASS VALID DATA
1689 */
1690 static struct passwd *_sql_addpasswd(cmd_rec *cmd, char *username,
1691 char *password, uid_t uid, gid_t gid, char *shell, char *dir) {
1692 struct passwd *cached = NULL;
1693 struct passwd *pwd = NULL;
1694
1695 pwd = pcalloc(cmd->tmp_pool, sizeof(struct passwd));
1696 pwd->pw_uid = uid;
1697 pwd->pw_name = username;
1698
1699 /* check to make sure the entry doesn't exist in the cache */
1700 cached = (struct passwd *) cache_findvalue(passwd_name_cache, pwd);
1701 if (cached != NULL) {
1702 pwd = cached;
1703 sql_log(DEBUG_INFO, "cache hit for user '%s'", pwd->pw_name);
1704
1705 } else {
1706 pwd = pcalloc(sql_pool, sizeof(struct passwd));
1707
1708 if (username != NULL) {
1709 pwd->pw_name = pstrdup(sql_pool, username);
1710 }
1711
1712 if (password != NULL) {
1713 pwd->pw_passwd = pstrdup(sql_pool, password);
1714 }
1715
1716 pwd->pw_uid = uid;
1717 pwd->pw_gid = gid;
1718
1719 if (shell != NULL) {
1720 pwd->pw_shell = pstrdup(sql_pool, shell);
1721
1722 if (pr_table_add(session.notes, "shell", pwd->pw_shell, 0) < 0) {
1723 int xerrno = errno;
1724
1725 if (xerrno != EEXIST) {
1726 pr_trace_msg(trace_channel, 8,
1727 "error setting 'shell' session note: %s", strerror(xerrno));
1728 }
1729 }
1730 }
1731
1732 if (dir) {
1733 pwd->pw_dir = pstrdup(sql_pool, dir);
1734
1735 if (pr_table_add(session.notes, "home", pwd->pw_dir, 0) < 0) {
1736 int xerrno = errno;
1737
1738 if (xerrno != EEXIST) {
1739 pr_trace_msg(trace_channel, 8,
1740 "error setting 'home' session note: %s", strerror(xerrno));
1741 }
1742 }
1743 }
1744
1745 cache_addentry(passwd_name_cache, pwd);
1746 cache_addentry(passwd_uid_cache, pwd);
1747
1748 sql_log(DEBUG_INFO, "cache miss for user '%s'", pwd->pw_name);
1749 sql_log(DEBUG_INFO, "user '%s' cached", pwd->pw_name);
1750 show_passwd(pwd);
1751 }
1752
1753 return pwd;
1754 }
1755
1756 static int sql_getuserprimarykey(cmd_rec *cmd, const char *username) {
1757 sql_data_t *sd = NULL;
1758 modret_t *mr = NULL;
1759 char *key_field = NULL, *key_value = NULL, *ptr = NULL;
1760 config_rec *c;
1761 const void *v = NULL;
1762
1763 v = pr_table_get(session.notes, "sql.user-primary-key", NULL);
1764 if (v != NULL) {
1765 /* Already have UserPrimaryKey. */
1766 return 0;
1767 }
1768
1769 c = find_config(main_server->conf, CONF_PARAM, "SQLUserPrimaryKey", FALSE);
1770 if (c == NULL) {
1771 return 0;
1772 }
1773
1774 key_field = c->argv[0];
1775 if (strncmp(key_field, "custom:/", 8) == 0) {
1776 config_rec *custom_c = NULL;
1777 char *named_query;
1778
1779 ptr = key_field + 8;
1780 named_query = pstrcat(cmd->tmp_pool, "SQLNamedQuery_", ptr, NULL);
1781
1782 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
1783 if (custom_c == NULL) {
1784 sql_log(DEBUG_INFO, "error: unable to resolve custom "
1785 "SQLNamedQuery name '%s'", (char *) ptr);
1786 ptr = NULL;
1787 }
1788 }
1789
1790 if (ptr == NULL) {
1791 char *where;
1792
1793 where = pstrcat(cmd->tmp_pool, cmap.usrfield, " = '", username, "'", NULL);
1794
1795 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 5, MOD_SQL_DEF_CONN_NAME,
1796 cmap.usrtable, key_field, where, "1"), "sql_select");
1797 if (check_response(mr, 0) < 0) {
1798 return -1;
1799 }
1800
1801 if (MODRET_HASDATA(mr)) {
1802 sd = (sql_data_t *) mr->data;
1803 }
1804
1805 } else {
1806 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 3, MOD_SQL_DEF_CONN_NAME, ptr,
1807 username));
1808 if (check_response(mr, 0) < 0) {
1809 return -1;
1810 }
1811
1812 if (MODRET_HASDATA(mr)) {
1813 array_header *ah = (array_header *) mr->data;
1814 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
1815
1816 /* Assume the query only returned 1 row. */
1817 sd->fnum = ah->nelts;
1818
1819 sql_log(DEBUG_INFO,
1820 "custom SQLUserPrimaryKey query '%s' returned %lu columns for "
1821 "user '%s'", ptr, sd->fnum, username);
1822 if (sd->fnum) {
1823 sd->rnum = 1;
1824 sd->data = (char **) ah->elts;
1825
1826 } else {
1827 sd->rnum = 0;
1828 sd->data = NULL;
1829 }
1830 }
1831 }
1832
1833 /* If we have no data...*/
1834 if (sd == NULL ||
1835 sd->rnum == 0) {
1836 errno = ENOENT;
1837 return -1;
1838 }
1839
1840 key_value = sd->data[0];
1841 if (pr_table_add(session.notes, "sql.user-primary-key",
1842 pstrdup(session.pool, key_value), 0) < 0) {
1843 sql_log(DEBUG_INFO,
1844 "error stashing 'sql.user-primary-key' note for value '%s': %s",
1845 key_value, strerror(errno));
1846 }
1847
1848 return 0;
1849 }
1850
1851 static int sql_getgroupprimarykey(cmd_rec *cmd, const char *groupname) {
1852 sql_data_t *sd = NULL;
1853 modret_t *mr = NULL;
1854 char *key_field = NULL, *key_value = NULL, *ptr = NULL;
1855 config_rec *c;
1856 const void *v = NULL;
1857
1858 v = pr_table_get(session.notes, "sql.group-primary-key", NULL);
1859 if (v != NULL) {
1860 /* Already have GroupPrimaryKey. */
1861 return 0;
1862 }
1863
1864 c = find_config(main_server->conf, CONF_PARAM, "SQLGroupPrimaryKey", FALSE);
1865 if (c == NULL) {
1866 return 0;
1867 }
1868
1869 key_field = c->argv[0];
1870 if (strncmp(key_field, "custom:/", 8) == 0) {
1871 config_rec *custom_c = NULL;
1872 char *named_query;
1873
1874 ptr = key_field + 8;
1875 named_query = pstrcat(cmd->tmp_pool, "SQLNamedQuery_", ptr, NULL);
1876
1877 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
1878 if (custom_c == NULL) {
1879 sql_log(DEBUG_INFO, "error: unable to resolve custom "
1880 "SQLNamedQuery name '%s'", (char *) ptr);
1881 ptr = NULL;
1882 }
1883 }
1884
1885 if (ptr == NULL) {
1886 char *where;
1887
1888 where = pstrcat(cmd->tmp_pool, cmap.grpfield, " = '", groupname, "'", NULL);
1889
1890 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 5, MOD_SQL_DEF_CONN_NAME,
1891 cmap.grptable, key_field, where, "1"), "sql_select");
1892 if (check_response(mr, 0) < 0) {
1893 return -1;
1894 }
1895
1896 if (MODRET_HASDATA(mr)) {
1897 sd = (sql_data_t *) mr->data;
1898 }
1899
1900 } else {
1901 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 3, MOD_SQL_DEF_CONN_NAME, ptr,
1902 groupname));
1903 if (check_response(mr, 0) < 0) {
1904 return -1;
1905 }
1906
1907 if (MODRET_HASDATA(mr)) {
1908 array_header *ah = (array_header *) mr->data;
1909 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
1910
1911 /* Assume the query only returned 1 row. */
1912 sd->fnum = ah->nelts;
1913
1914 sql_log(DEBUG_INFO,
1915 "custom SQLGroupPrimaryKey query '%s' returned %lu columns for "
1916 "group '%s'", ptr, sd->fnum, groupname);
1917 if (sd->fnum) {
1918 sd->rnum = 1;
1919 sd->data = (char **) ah->elts;
1920
1921 } else {
1922 sd->rnum = 0;
1923 sd->data = NULL;
1924 }
1925 }
1926 }
1927
1928 /* If we have no data...*/
1929 if (sd == NULL ||
1930 sd->rnum == 0) {
1931 errno = ENOENT;
1932 return -1;
1933 }
1934
1935 key_value = sd->data[0];
1936 if (pr_table_add(session.notes, "sql.group-primary-key",
1937 pstrdup(session.pool, key_value), 0) < 0) {
1938 sql_log(DEBUG_INFO,
1939 "error stashing 'sql.group-primary-key' note for value '%s': %s",
1940 key_value, strerror(errno));
1941 }
1942
1943 return 0;
1944 }
1945
1946 static struct passwd *sql_getpasswd(cmd_rec *cmd, struct passwd *p) {
1947 sql_data_t *sd = NULL;
1948 modret_t *mr = NULL;
1949 struct passwd *pwd = NULL;
1950 char *usrwhere, *where;
1951 char *realname = NULL;
1952 int i = 0;
1953
1954 char *username = NULL;
1955 char *password = NULL;
1956 char *shell = NULL;
1957 char *dir = NULL;
1958 uid_t uid = 0;
1959 gid_t gid = 0;
1960
1961 if (p == NULL) {
1962 sql_log(DEBUG_WARN, "%s", "sql_getpasswd called with NULL passwd struct");
1963 sql_log(DEBUG_WARN, "%s", "THIS SHOULD NEVER HAPPEN");
1964 return NULL;
1965 }
1966
1967 /* Check to see if the passwd already exists in one of the passwd caches.
1968 * Give preference to name-based lookups, as opposed to UID-based lookups.
1969 */
1970 if (p->pw_name != NULL) {
1971 pwd = (struct passwd *) cache_findvalue(passwd_name_cache, p);
1972
1973 } else {
1974 pwd = (struct passwd *) cache_findvalue(passwd_uid_cache, p);
1975 }
1976
1977 if (pwd != NULL) {
1978 sql_log(DEBUG_AUTH, "cache hit for user '%s'", pwd->pw_name);
1979
1980 /* Check for negatively cached passwds, which will have NULL
1981 * passwd/home/shell.
1982 */
1983 if (pwd->pw_passwd == NULL &&
1984 pwd->pw_shell == NULL &&
1985 pwd->pw_dir == NULL) {
1986 sql_log(DEBUG_AUTH, "negative cache entry for user '%s'", pwd->pw_name);
1987 return NULL;
1988 }
1989
1990 return pwd;
1991 }
1992
1993 if (p->pw_name != NULL) {
1994 realname = p->pw_name;
1995
1996 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
1997 realname), "sql_escapestring");
1998 if (check_response(mr, 0) < 0) {
1999 return NULL;
2000 }
2001
2002 username = (char *) mr->data;
2003 usrwhere = pstrcat(cmd->tmp_pool, cmap.usrfield, "='", username, "'", NULL);
2004
2005 sql_log(DEBUG_WARN, "cache miss for user '%s'", realname);
2006
2007 if (!cmap.usercustom) {
2008 /* The following nested function calls may look a little strange, but
2009 * it is deliberate. We want to handle any tags/variables within the
2010 * cmap.userwhere string (i.e. the SQLUserWhereClause directive, if
2011 * configured), but we do NOT want to handle any tags/variables in
2012 * the usrwhere variable (a string we concatenated ourselves). The
2013 * usrwhere variable contains the user name, and we need to handle that
2014 * string as-is, lest we corrupt/change the user name.
2015 */
2016
2017 where = sql_prepare_where(SQL_PREPARE_WHERE_FL_NO_TAGS, cmd, 2, usrwhere,
2018 sql_prepare_where(0, cmd, 1, cmap.userwhere, NULL), NULL);
2019
2020 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 5, MOD_SQL_DEF_CONN_NAME,
2021 cmap.usrtable, cmap.usrfields, where, "1"), "sql_select");
2022 if (check_response(mr, 0) < 0) {
2023 return NULL;
2024 }
2025
2026 if (MODRET_HASDATA(mr)) {
2027 sd = (sql_data_t *) mr->data;
2028 }
2029
2030 } else {
2031 /* The username has been escaped according to the backend database' rules
2032 * at this point.
2033 */
2034 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 3, MOD_SQL_DEF_CONN_NAME,
2035 cmap.usercustom, username ? username : "NULL"));
2036
2037 if (check_response(mr, 0) < 0) {
2038 return NULL;
2039 }
2040
2041 if (MODRET_HASDATA(mr)) {
2042 array_header *ah = (array_header *) mr->data;
2043 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
2044
2045 /* Assume the query only returned 1 row. */
2046 sd->fnum = ah->nelts;
2047
2048 sql_log(DEBUG_INFO,
2049 "custom SQLUserInfo query '%s' returned %lu columns for user '%s'",
2050 cmap.usercustom, sd->fnum, realname);
2051 if (sd->fnum) {
2052 sd->rnum = 1;
2053 sd->data = (char **) ah->elts;
2054
2055 } else {
2056 sd->rnum = 0;
2057 sd->data = NULL;
2058 }
2059 }
2060 }
2061
2062 } else {
2063 /* Assume we have a UID */
2064 const char *uidstr;
2065
2066 uidstr = pr_uid2str(cmd->tmp_pool, p->pw_uid);
2067 sql_log(DEBUG_WARN, "cache miss for UID '%s'", uidstr);
2068
2069 if (!cmap.usercustombyid) {
2070 if (cmap.uidfield) {
2071 usrwhere = pstrcat(cmd->tmp_pool, cmap.uidfield, " = ", uidstr, NULL);
2072
2073 where = sql_prepare_where(SQL_PREPARE_WHERE_FL_NO_TAGS, cmd, 2,
2074 usrwhere, sql_prepare_where(0, cmd, 1, cmap.userwhere, NULL), NULL);
2075
2076 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 5,
2077 MOD_SQL_DEF_CONN_NAME, cmap.usrtable, cmap.usrfields, where, "1"),
2078 "sql_select");
2079 if (check_response(mr, 0) < 0) {
2080 return NULL;
2081 }
2082
2083 if (MODRET_HASDATA(mr)) {
2084 sd = (sql_data_t *) mr->data;
2085 }
2086
2087 } else {
2088 sql_log(DEBUG_WARN, "no user UID field configured, declining to "
2089 "lookup UID '%s'", uidstr);
2090
2091 /* If no UID field has been configured, return now and let other
2092 * modules possibly have a chance at resolving this UID to a name.
2093 */
2094 return NULL;
2095 }
2096
2097 } else {
2098 array_header *ah = NULL;
2099
2100 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 3, MOD_SQL_DEF_CONN_NAME,
2101 cmap.usercustombyid, uidstr));
2102 if (check_response(mr, 0) < 0) {
2103 return NULL;
2104 }
2105
2106 ah = mr->data;
2107
2108 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
2109
2110 /* Assume the query only return 1 row. */
2111 sd->fnum = ah->nelts;
2112 if (sd->fnum) {
2113 sd->rnum = 1;
2114 sd->data = (char **) ah->elts;
2115
2116 } else {
2117 sd->rnum = 0;
2118 sd->data = NULL;
2119 }
2120 }
2121 }
2122
2123 /* if we have no data.. */
2124 if (sd == NULL ||
2125 sd->rnum == 0) {
2126 if (!cmap.negative_cache) {
2127 return NULL;
2128
2129 } else {
2130 /* If doing caching of negative lookups, cache this failed lookup.
2131 * Use the default UID and GID.
2132 */
2133 return _sql_addpasswd(cmd, username, NULL, p->pw_uid, p->pw_gid,
2134 NULL, NULL);
2135 }
2136 }
2137
2138 i = 0;
2139
2140 username = sd->data[i++];
2141 password = sd->data[i++];
2142
2143 uid = cmap.defaultuid;
2144 if (cmap.uidfield) {
2145 if (sd->data[i]) {
2146 if (pr_str2uid(sd->data[i++], &uid) < 0) {
2147 uid = cmap.defaultuid;
2148 }
2149
2150 } else {
2151 i++;
2152 }
2153 }
2154
2155 gid = cmap.defaultgid;
2156 if (cmap.gidfield) {
2157 if (sd->data[i]) {
2158 if (pr_str2gid(sd->data[i++], &gid) < 0) {
2159 gid = cmap.defaultgid;
2160 }
2161
2162 } else {
2163 i++;
2164 }
2165 }
2166
2167 dir = cmap.defaulthomedir;
2168 if (sd->data[i]) {
2169 if (strcmp(sd->data[i], "") == 0 ||
2170 strcmp(sd->data[i], "NULL") == 0) {
2171
2172 /* Leave dir pointing to the SQLDefaultHomedir, if any. */
2173 i++;
2174
2175 } else {
2176 dir = sd->data[i++];
2177 }
2178 }
2179
2180 if (cmap.shellfield) {
2181 if (sd->fnum-1 < (unsigned long) i ||
2182 !sd->data[i]) {
2183
2184 /* Make sure that, if configured, the shell value is valid, and scream
2185 * if it is not.
2186 */
2187 sql_log(DEBUG_WARN, "NULL shell column value");
2188 shell = NULL;
2189
2190 } else {
2191 shell = sd->data[i];
2192 }
2193
2194 } else {
2195 shell = NULL;
2196 }
2197
2198 if (uid < cmap.minuseruid) {
2199 sql_log(DEBUG_INFO, "user UID %s below SQLMinUserUID %s, using "
2200 "SQLDefaultUID %s", pr_uid2str(cmd->tmp_pool, uid),
2201 pr_uid2str(cmd->tmp_pool, cmap.minuseruid),
2202 pr_uid2str(cmd->tmp_pool, cmap.defaultuid));
2203 uid = cmap.defaultuid;
2204 }
2205
2206 if (gid < cmap.minusergid) {
2207 sql_log(DEBUG_INFO, "user GID %s below SQLMinUserGID %s, using "
2208 "SQLDefaultGID %s", pr_gid2str(cmd->tmp_pool, gid),
2209 pr_gid2str(cmd->tmp_pool, cmap.minusergid),
2210 pr_gid2str(cmd->tmp_pool, cmap.defaultgid));
2211 gid = cmap.defaultgid;
2212 }
2213
2214 return _sql_addpasswd(cmd, username, password, uid, gid, shell, dir);
2215 }
2216
2217 /* _sql_addgroup: creates a group and adds it to the group struct
2218 * cache if it doesn't already exist. Returns the created group
2219 * struct, or the pre-existing struct if there was one.
2220 *
2221 * DOES NOT CHECK ARGUMENTS. CALLING FUNCTIONS NEED TO MAKE SURE
2222 * THEY PASS VALID DATA
2223 */
2224 static struct group *_sql_addgroup(cmd_rec *cmd, char *groupname, gid_t gid,
2225 array_header *ah) {
2226 struct group *cached = NULL;
2227 struct group *grp = NULL;
2228
2229 grp = pcalloc(cmd->tmp_pool, sizeof(struct group));
2230 grp->gr_gid = gid;
2231 grp->gr_name = groupname;
2232
2233 /* check to make sure the entry doesn't exist in the cache */
2234 if ((cached = (struct group *) cache_findvalue(group_name_cache, grp)) != NULL) {
2235 grp = cached;
2236 sql_log(DEBUG_INFO, "cache hit for group '%s'", grp->gr_name);
2237
2238 } else {
2239 grp = pcalloc(sql_pool, sizeof(struct group));
2240
2241 if (groupname) {
2242 grp->gr_name = pstrdup(sql_pool, groupname);
2243
2244 if (pr_table_add(session.notes, "primary-group", grp->gr_name, 0) < 0) {
2245 int xerrno = errno;
2246
2247 if (xerrno != EEXIST) {
2248 pr_trace_msg(trace_channel, 8,
2249 "error setting 'primary-group' session note: %s", strerror(xerrno));
2250 }
2251 }
2252 }
2253
2254 grp->gr_gid = gid;
2255
2256 if (ah) {
2257 register unsigned int i;
2258
2259 /* finish filling in the group */
2260 grp->gr_mem = (char **) pcalloc(sql_pool,
2261 sizeof(char *) * (ah->nelts + 1));
2262
2263 for (i = 0; i < ah->nelts; i++) {
2264 grp->gr_mem[i] = pstrdup(sql_pool, ((char **) ah->elts)[i]);
2265 }
2266
2267 grp->gr_mem[i] = NULL;
2268 }
2269
2270 cache_addentry(group_name_cache, grp);
2271 cache_addentry(group_gid_cache, grp);
2272
2273 sql_log(DEBUG_INFO, "cache miss for group '%s'", grp->gr_name);
2274 sql_log(DEBUG_INFO, "group '%s' cached", grp->gr_name);
2275 show_group(cmd->tmp_pool, grp);
2276 }
2277
2278 return grp;
2279 }
2280
2281 static struct group *sql_getgroup(cmd_rec *cmd, struct group *g) {
2282 struct group *grp = NULL;
2283 modret_t *mr = NULL;
2284 int cnt = 0;
2285 sql_data_t *sd = NULL;
2286 char *groupname = NULL;
2287 char **rows = NULL;
2288 int numrows = 0;
2289 array_header *ah = NULL;
2290 char *members = NULL;
2291 char *member = NULL;
2292 char *grpwhere;
2293 char *where;
2294 char *iterator;
2295
2296 gid_t gid = 0;
2297
2298 if (g == NULL) {
2299 sql_log(DEBUG_WARN, "%s", "sql_getgroup called with NULL group struct");
2300 sql_log(DEBUG_WARN, "%s", "THIS SHOULD NEVER HAPPEN");
2301 return NULL;
2302 }
2303
2304 /* check to see if the group already exists in one of the group caches */
2305 if (((grp = (struct group *) cache_findvalue(group_name_cache, g)) != NULL) ||
2306 ((grp = (struct group *) cache_findvalue(group_gid_cache, g)) != NULL)) {
2307 sql_log(DEBUG_AUTH, "cache hit for group '%s'", grp->gr_name);
2308
2309 /* Check for negatively cached groups, which will have NULL gr_mem. */
2310 if (grp->gr_mem == NULL) {
2311 sql_log(DEBUG_AUTH, "negative cache entry for group '%s'", grp->gr_name);
2312 return NULL;
2313 }
2314
2315 return grp;
2316 }
2317
2318 if (g->gr_name != NULL) {
2319 char *realname;
2320
2321 realname = g->gr_name;
2322
2323 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
2324 realname), "sql_escapestring");
2325 if (check_response(mr, 0) < 0) {
2326 return NULL;
2327 }
2328
2329 groupname = (char *) mr->data;
2330 sql_log(DEBUG_WARN, "cache miss for group '%s'", groupname);
2331
2332 } else {
2333 const char *gidstr = NULL;
2334
2335 /* Get groupname from GID */
2336 gidstr = pr_gid2str(NULL, g->gr_gid);
2337
2338 sql_log(DEBUG_WARN, "cache miss for GID '%s'", gidstr);
2339
2340 if (!cmap.groupcustombyid) {
2341 if (cmap.grpgidfield) {
2342 grpwhere = pstrcat(cmd->tmp_pool, cmap.grpgidfield, " = ", gidstr,
2343 NULL);
2344
2345 } else {
2346 sql_log(DEBUG_WARN, "no group GID field configured, declining to "
2347 "lookup GID '%s'", gidstr);
2348
2349 /* If no GID field has been configured, return now and let other
2350 * modules possibly have a chance at resolving this GID to a name.
2351 */
2352 return NULL;
2353 }
2354
2355 where = sql_prepare_where(SQL_PREPARE_WHERE_FL_NO_TAGS, cmd, 2, grpwhere,
2356 sql_prepare_where(0, cmd, 1, cmap.groupwhere, NULL), NULL);
2357
2358 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 5, MOD_SQL_DEF_CONN_NAME,
2359 cmap.grptable, cmap.grpfield, where, "1"), "sql_select");
2360 if (check_response(mr, 0) < 0) {
2361 return NULL;
2362 }
2363
2364 sd = (sql_data_t *) mr->data;
2365
2366 } else {
2367 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 3, MOD_SQL_DEF_CONN_NAME,
2368 cmap.groupcustombyid, gidstr));
2369 if (check_response(mr, 0) < 0) {
2370 return NULL;
2371 }
2372
2373 ah = mr->data;
2374
2375 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
2376
2377 /* Assume the query only return 1 row. */
2378 sd->fnum = ah->nelts;
2379 if (sd->fnum) {
2380 sd->rnum = 1;
2381 sd->data = (char **) ah->elts;
2382
2383 } else {
2384 sd->rnum = 0;
2385 sd->data = NULL;
2386 }
2387 }
2388
2389 /* If we have no data.. */
2390 if (sd->rnum == 0)
2391 return NULL;
2392
2393 groupname = sd->data[0];
2394 }
2395
2396 /* The groupname has been escaped according to the backend database' rules
2397 * at this point.
2398 */
2399
2400 if (!cmap.groupcustombyname) {
2401 grpwhere = pstrcat(cmd->tmp_pool, cmap.grpfield, " = '", groupname, "'",
2402 NULL);
2403
2404 where = sql_prepare_where(SQL_PREPARE_WHERE_FL_NO_TAGS, cmd, 2, grpwhere,
2405 sql_prepare_where(0, cmd, 1, cmap.groupwhere, NULL), NULL);
2406
2407 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 4, MOD_SQL_DEF_CONN_NAME,
2408 cmap.grptable, cmap.grpfields, where), "sql_select");
2409 if (check_response(mr, 0) < 0) {
2410 return NULL;
2411 }
2412
2413 sd = (sql_data_t *) mr->data;
2414
2415 } else {
2416 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 3, MOD_SQL_DEF_CONN_NAME,
2417 cmap.groupcustombyname, groupname ? groupname : "NULL"));
2418 if (check_response(mr, 0) < 0) {
2419 return NULL;
2420 }
2421
2422 ah = mr->data;
2423 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
2424
2425 /* Assume the query only returned 1 row. */
2426 sd->fnum = ah->nelts;
2427
2428 if (sd->fnum) {
2429 sd->rnum = 1;
2430 sd->data = (char **) ah->elts;
2431
2432 } else {
2433 sd->rnum = 0;
2434 sd->data = NULL;
2435 }
2436 }
2437
2438 /* if we have no data.. */
2439 if (sd->rnum == 0) {
2440 if (!cmap.negative_cache) {
2441 return NULL;
2442
2443 } else {
2444
2445 /* If doing caching of negative lookups, cache this failed lookup. */
2446 return _sql_addgroup(cmd, groupname, g->gr_gid, NULL);
2447 }
2448 }
2449
2450 rows = sd->data;
2451 numrows = sd->rnum;
2452
2453 gid = (gid_t) strtoul(rows[1], NULL, 10);
2454
2455 /* Painful.. we need to walk through the returned rows and fill in our
2456 * members. Every third element in a row is a member field, and every
2457 * member field can have multiple members.
2458 */
2459
2460 ah = make_array(cmd->tmp_pool, 10, sizeof(char *));
2461
2462 for (cnt = 0; cnt < numrows; cnt++) {
2463 members = rows[(cnt * 3) + 2];
2464 iterator = members;
2465
2466 pr_signals_handle();
2467
2468 /* If the row is null, continue.. */
2469 if (members == NULL) {
2470 continue;
2471 }
2472
2473 /* For each member in the list, toss 'em into the array. no
2474 * need to copy the string -- _sql_addgroup will do it for us
2475 */
2476 for (member = strsep(&iterator, ","); member;
2477 member = strsep(&iterator, ",")) {
2478 if (*member == '\0') {
2479 continue;
2480 }
2481
2482 *((char **) push_array(ah)) = member;
2483 }
2484 }
2485
2486 return _sql_addgroup(cmd, groupname, gid, ah);
2487 }
2488
2489 static void _setstats(cmd_rec *cmd, int fstor, int fretr, int bstor,
2490 int bretr) {
2491 /*
2492 * if anyone has a better way of doing this, let me know..
2493 */
2494 char query[256] = { '\0' };
2495 char *usrwhere, *where;
2496 modret_t *mr = NULL;
2497
2498 pr_snprintf(query, sizeof(query),
2499 "%s = %s + %i, %s = %s + %i, %s = %s + %i, %s = %s + %i",
2500 cmap.sql_fstor, cmap.sql_fstor, fstor,
2501 cmap.sql_fretr, cmap.sql_fretr, fretr,
2502 cmap.sql_bstor, cmap.sql_bstor, bstor,
2503 cmap.sql_bretr, cmap.sql_bretr, bretr);
2504
2505 usrwhere = pstrcat(cmd->tmp_pool, cmap.usrfield, " = '", _sql_realuser(cmd),
2506 "'", NULL);
2507
2508 where = sql_prepare_where(SQL_PREPARE_WHERE_FL_NO_TAGS, cmd, 2, usrwhere,
2509 sql_prepare_where(0, cmd, 1, cmap.userwhere, NULL), NULL);
2510
2511 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 4, MOD_SQL_DEF_CONN_NAME,
2512 cmap.usrtable, query, where), "sql_update");
2513 (void) check_response(mr, 0);
2514 }
2515
2516 static int sql_getgroups(cmd_rec *cmd) {
2517 struct passwd *pw = NULL, lpw;
2518 struct group *grp, lgr;
2519 char *grpwhere = NULL, *where = NULL;
2520 sql_data_t *sd = NULL;
2521 modret_t *mr = NULL;
2522 array_header *gids = NULL, *groups = NULL;
2523 char *name = cmd->argv[0], *username = NULL;
2524 int argc, numrows = 0, res = -1;
2525 register int i = 0;
2526
2527 /* Check for NULL values */
2528 if (cmd->argv[1]) {
2529 gids = (array_header *) cmd->argv[1];
2530 }
2531
2532 if (cmd->argv[2]) {
2533 groups = (array_header *) cmd->argv[2];
2534 }
2535
2536 lpw.pw_uid = -1;
2537 lpw.pw_gid = -1;
2538 lpw.pw_name = name;
2539
2540 /* Now that we have the pointers for the lists, tweak the argc field
2541 * before passing this cmd_rec on, lest we try to resolve some variable
2542 * like %r which will assume that all of the cmd_rec args are strings, as
2543 * from the client.
2544 */
2545 argc = cmd->argc;
2546 cmd->argc = 1;
2547
2548 /* Retrieve the necessary info */
2549 if (!name ||
2550 !(pw = sql_getpasswd(cmd, &lpw))) {
2551 cmd->argc = argc;
2552 return -1;
2553 }
2554
2555 /* Populate the first group ID and name */
2556 if (gids) {
2557 *((gid_t *) push_array(gids)) = pw->pw_gid;
2558 }
2559
2560 lgr.gr_gid = pw->pw_gid;
2561 lgr.gr_name = NULL;
2562
2563 if (groups &&
2564 (grp = sql_getgroup(cmd, &lgr)) != NULL) {
2565 *((char **) push_array(groups)) = pstrdup(permanent_pool, grp->gr_name);
2566 }
2567
2568 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
2569 name), "sql_escapestring");
2570 if (check_response(mr, 0) < 0) {
2571 cmd->argc = argc;
2572 return -1;
2573 }
2574
2575 username = (char *) mr->data;
2576
2577 if (!cmap.groupcustommembers) {
2578 if (!(pr_sql_opts & SQL_OPT_USE_NORMALIZED_GROUP_SCHEMA)) {
2579
2580 /* Use a SELECT with a LIKE clause:
2581 *
2582 * SELECT groupname,gid,members FROM groups
2583 * WHERE members LIKE '%,<user>,%' OR LIKE '<user>,%' OR LIKE '%,<user>';
2584 */
2585
2586 grpwhere = pstrcat(cmd->tmp_pool,
2587 cmap.grpmembersfield, " = '", username, "' OR ",
2588 cmap.grpmembersfield, " LIKE '", username, ",%' OR ",
2589 cmap.grpmembersfield, " LIKE '%,", username, "' OR ",
2590 cmap.grpmembersfield, " LIKE '%,", username, ",%'", NULL);
2591
2592 } else {
2593 /* Use a single SELECT:
2594 *
2595 * SELECT groupname,gid,members FROM groups WHERE members = <user>';
2596 */
2597 grpwhere = pstrcat(cmd->tmp_pool,
2598 cmap.grpmembersfield, " = '", username, "'", NULL);
2599 }
2600
2601 where = sql_prepare_where(SQL_PREPARE_WHERE_FL_NO_TAGS, cmd, 2, grpwhere,
2602 sql_prepare_where(0, cmd, 1, cmap.groupwhere, NULL), NULL);
2603
2604 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 4, MOD_SQL_DEF_CONN_NAME,
2605 cmap.grptable, cmap.grpfields, where), "sql_select");
2606 if (check_response(mr, 0) < 0) {
2607 cmd->argc = argc;
2608 return -1;
2609 }
2610
2611 sd = (sql_data_t *) mr->data;
2612
2613 } else {
2614 array_header *ah;
2615
2616 /* The username has been escaped according to the backend database' rules
2617 * at this point.
2618 */
2619 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 3, MOD_SQL_DEF_CONN_NAME,
2620 cmap.groupcustommembers, username));
2621 if (check_response(mr, 0) < 0) {
2622 cmd->argc = argc;
2623 return -1;
2624 }
2625
2626 ah = mr->data;
2627 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
2628
2629 /* Assume the query returned N rows, 3 columns per row. */
2630 if (ah->nelts % 3 == 0) {
2631 sd->fnum = 3;
2632 sd->rnum = ah->nelts / 3;
2633
2634 if (sd->rnum > 0) {
2635 sd->data = (char **) ah->elts;
2636 }
2637
2638 } else {
2639 sql_log(DEBUG_INFO, "wrong number of columns (%d) returned by custom SQLGroupInfo members query, ignoring results", ah->nelts % 3);
2640 sd->rnum = 0;
2641 sd->data = NULL;
2642 }
2643 }
2644
2645 /* If we have no data... */
2646 if (sd->rnum == 0) {
2647 cmd->argc = argc;
2648 return -1;
2649 }
2650
2651 numrows = sd->rnum;
2652
2653 for (i = 0; i < numrows; i++) {
2654 gid_t gid;
2655 char *groupname = sd->data[(i * 3)];
2656 char *memberstr = sd->data[(i * 3) + 2], *member = NULL;
2657 array_header *members = make_array(cmd->tmp_pool, 2, sizeof(char *));
2658
2659 if (pr_str2gid(sd->data[(i * 3) +1], &gid) < 0) {
2660 gid = (gid_t) -1;
2661 }
2662
2663 *((gid_t *) push_array(gids)) = gid;
2664 *((char **) push_array(groups)) = pstrdup(permanent_pool, groupname);
2665
2666 /* For each member in the list, toss 'em into the array. no
2667 * need to copy the string -- _sql_addgroup will do it for us
2668 */
2669 for (member = strsep(&memberstr, ","); member;
2670 member = strsep(&memberstr, ",")) {
2671 if (*member == '\0') {
2672 continue;
2673 }
2674
2675 *((char **) push_array(members)) = member;
2676 }
2677
2678 /* Add this group data to the group cache. */
2679 _sql_addgroup(cmd, groupname, gid, members);
2680 }
2681
2682 if (gids &&
2683 gids->nelts > 0) {
2684 res = gids->nelts;
2685
2686 } else if (groups &&
2687 groups->nelts) {
2688 res = groups->nelts;
2689 }
2690
2691 cmd->argc = argc;
2692 return res;
2693 }
2694
2695 /* Command handlers
2696 */
2697
2698 MODRET sql_pre_dele(cmd_rec *cmd) {
2699 char *path;
2700
2701 if (cmap.engine == 0) {
2702 return PR_DECLINED(cmd);
2703 }
2704
2705 sql_dele_filesz = 0;
2706
2707 path = dir_canonical_path(cmd->tmp_pool,
2708 pr_fs_decode_path(cmd->tmp_pool, cmd->arg));
2709 if (path) {
2710 struct stat st;
2711
2712 /* Briefly cache the size of the file being deleted, so that it can be
2713 * logged properly using %b.
2714 */
2715 pr_fs_clear_cache2(path);
2716 if (pr_fsio_stat(path, &st) < 0) {
2717 sql_log(DEBUG_INFO, "%s: unable to stat '%s': %s", (char *) cmd->argv[0],
2718 path, strerror(errno));
2719
2720 } else {
2721 sql_dele_filesz = st.st_size;
2722 }
2723 }
2724
2725 return PR_DECLINED(cmd);
2726 }
2727
2728 MODRET sql_pre_pass(cmd_rec *cmd) {
2729 config_rec *c = NULL;
2730 const char *user = NULL;
2731
2732 if (cmap.engine == 0) {
2733 return PR_DECLINED(cmd);
2734 }
2735
2736 sql_log(DEBUG_FUNC, "%s", ">>> sql_pre_pass");
2737
2738 user = pr_table_get(session.notes, "mod_auth.orig-user", NULL);
2739 if (user != NULL) {
2740 config_rec *anon_config;
2741
2742 /* Use the looked-up user name to determine whether this is to be
2743 * an anonymous session.
2744 */
2745 anon_config = pr_auth_get_anon_config(cmd->pool, &user, NULL, NULL);
2746
2747 c = find_config(anon_config ? anon_config->subset : main_server->conf,
2748 CONF_PARAM, "SQLEngine", FALSE);
2749 if (c != NULL) {
2750 cmap.engine = *((int *) c->argv[0]);
2751 }
2752
2753 } else {
2754 /* Just assume the vhost config. */
2755 c = find_config(main_server->conf, CONF_PARAM, "SQLEngine", FALSE);
2756 if (c != NULL) {
2757 cmap.engine = *((int *) c->argv[0]);
2758 }
2759 }
2760
2761 sql_log(DEBUG_FUNC, "%s", "<<< sql_pre_pass");
2762 return PR_DECLINED(cmd);
2763 }
2764
2765 MODRET sql_post_pass(cmd_rec *cmd) {
2766 int res;
2767
2768 if (cmap.engine == 0) {
2769 return PR_DECLINED(cmd);
2770 }
2771
2772 res = sql_getuserprimarykey(cmd, session.user);
2773 if (res < 0) {
2774 pr_trace_msg(trace_channel, 9,
2775 "error getting primary lookup key for user '%s': %s", session.user,
2776 strerror(errno));
2777 }
2778
2779 res = sql_getgroupprimarykey(cmd, session.group);
2780 if (res < 0) {
2781 pr_trace_msg(trace_channel, 9,
2782 "error getting primary lookup key for group '%s': %s", session.group,
2783 strerror(errno));
2784 }
2785
2786 return PR_DECLINED(cmd);
2787 }
2788
2789 MODRET sql_post_stor(cmd_rec *cmd) {
2790 if (cmap.engine == 0) {
2791 return PR_DECLINED(cmd);
2792 }
2793
2794 sql_log(DEBUG_FUNC, "%s", ">>> sql_post_stor");
2795
2796 if (cmap.sql_fstor)
2797 _setstats(cmd, 1, 0, session.xfer.total_bytes, 0);
2798
2799 sql_log(DEBUG_FUNC, "%s", "<<< sql_post_stor");
2800 return PR_DECLINED(cmd);
2801 }
2802
2803 MODRET sql_post_retr(cmd_rec *cmd) {
2804 if (cmap.engine == 0) {
2805 return PR_DECLINED(cmd);
2806 }
2807
2808 sql_log(DEBUG_FUNC, "%s", ">>> sql_post_retr");
2809
2810 if (cmap.sql_fretr)
2811 _setstats(cmd, 0, 1, 0, session.xfer.total_bytes);
2812
2813 sql_log(DEBUG_FUNC, "%s", "<<< sql_post_retr");
2814 return PR_DECLINED(cmd);
2815 }
2816
2817 static int resolve_numeric_val(cmd_rec *cmd, const char *val) {
2818 int idx = -1;
2819 unsigned int n;
2820 char *ptr = NULL;
2821
2822 idx = strtol(val, &ptr, 10);
2823 if (*ptr != '\0') {
2824 return -1;
2825 }
2826
2827 if (idx < 0) {
2828 return -1;
2829 }
2830
2831 /* Internally-generated "sql_change" or "sql_lookup" commands have at least
2832 * two parameters: the command name, and the name of the SQLNamedQuery
2833 * being processed. They MAY have more parameters, or not.
2834 */
2835 n = idx + 2;
2836 if (n > cmd->argc) {
2837 return -1;
2838 }
2839
2840 return idx;
2841 }
2842
2843 static char *named_query_type(cmd_rec *cmd, char *name) {
2844 config_rec *c = NULL;
2845 char *query = NULL;
2846
2847 query = pstrcat(cmd->tmp_pool, "SQLNamedQuery_", name, NULL);
2848 c = find_config(main_server->conf, CONF_PARAM, query, FALSE);
2849 if (c != NULL) {
2850 return c->argv[0];
2851 }
2852
2853 sql_log(DEBUG_FUNC, "no '%s' SQLNamedQuery found", name);
2854 errno = ENOENT;
2855 return NULL;
2856 }
2857
2858 static modret_t *process_named_query(cmd_rec *cmd, char *name, int flags) {
2859 config_rec *c;
2860 char *conn_name, *query = NULL;
2861 char stmt[SQL_MAX_STMT_LEN+1];
2862 size_t stmt_len;
2863 modret_t *mr = NULL;
2864 int res;
2865 pool *tmp_pool;
2866 pr_jot_ctx_t *jot_ctx;
2867 struct sql_resolved *resolved;
2868
2869 sql_log(DEBUG_FUNC, ">>> process_named_query '%s'", name);
2870
2871 /* Check for a query by that name. */
2872 query = pstrcat(cmd->tmp_pool, "SQLNamedQuery_", name, NULL);
2873
2874 c = find_config(main_server->conf, CONF_PARAM, query, FALSE);
2875 if (c == NULL) {
2876 mr = PR_ERROR(cmd);
2877 sql_log(DEBUG_FUNC, "<<< process_named_query '%s'", name);
2878 return mr;
2879 }
2880
2881 conn_name = get_query_named_conn(c);
2882 set_named_conn_backend(conn_name);
2883
2884 tmp_pool = make_sub_pool(cmd->tmp_pool);
2885 jot_ctx = pcalloc(tmp_pool, sizeof(pr_jot_ctx_t));
2886 resolved = pcalloc(tmp_pool, sizeof(struct sql_resolved));
2887 resolved->bufsz = resolved->buflen = sizeof(stmt)-1;
2888 resolved->ptr = resolved->buf = stmt;
2889 resolved->conn_name = conn_name;
2890 resolved->conn_flags = flags;
2891
2892 jot_ctx->log = resolved;
2893 jot_ctx->user_data = cmd;
2894
2895 res = pr_jot_resolve_logfmt(tmp_pool, cmd, NULL, c->argv[1], jot_ctx,
2896 sql_resolve_on_meta, sql_resolve_on_default, sql_resolve_on_other);
2897 if (res < 0) {
2898 int xerrno = errno;
2899
2900 destroy_pool(tmp_pool);
2901 set_named_conn_backend(NULL);
2902
2903 if (xerrno == EIO) {
2904 return PR_ERROR_MSG(cmd, MOD_SQL_VERSION, "database error");
2905 }
2906
2907 return PR_ERROR_MSG(cmd, MOD_SQL_VERSION,
2908 "malformed reference %{?} in query");
2909 }
2910
2911 stmt_len = resolved->bufsz - resolved->buflen;
2912 stmt[stmt_len] = '\0';
2913
2914 /* Construct our return data based on the type of query */
2915 if (strcasecmp(c->argv[0], SQL_UPDATE_C) == 0) {
2916 query = pstrcat(cmd->tmp_pool, c->argv[2], " SET ", stmt, NULL);
2917 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, conn_name, query),
2918 "sql_update");
2919
2920 } else if (strcasecmp(c->argv[0], SQL_INSERT_C) == 0) {
2921 query = pstrcat(cmd->tmp_pool, "INTO ", c->argv[2], " VALUES (",
2922 stmt, ")", NULL);
2923 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, conn_name, query),
2924 "sql_insert");
2925
2926 } else if (strcasecmp(c->argv[0], SQL_FREEFORM_C) == 0) {
2927 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, conn_name, stmt),
2928 "sql_query");
2929
2930 } else if (strcasecmp(c->argv[0], SQL_SELECT_C) == 0) {
2931 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, conn_name, stmt),
2932 "sql_select");
2933
2934 if (MODRET_ISHANDLED(mr) &&
2935 MODRET_HASDATA(mr) &&
2936 pr_trace_get_level(trace_channel) >= 9) {
2937 register unsigned long i, idx;
2938 sql_data_t *sd;
2939
2940 sd = mr->data;
2941
2942 pr_trace_msg(trace_channel, 9, "SQLNamedQuery %s results:", name);
2943 pr_trace_msg(trace_channel, 9, " row count: %lu", sd->rnum);
2944 pr_trace_msg(trace_channel, 9, " col count: %lu", sd->fnum);
2945
2946 for (i = 0, idx = 0; i < sd->rnum; i++) {
2947 register unsigned long j;
2948
2949 pr_trace_msg(trace_channel, 9, " row #%lu:", i+1);
2950 for (j = 0; j < sd->fnum; j++) {
2951 pr_trace_msg(trace_channel, 9, " col #%lu: '%s'", j+1,
2952 sd->data[idx++]);
2953 }
2954 }
2955 }
2956
2957 } else {
2958 mr = PR_ERROR_MSG(cmd, MOD_SQL_VERSION, "unknown NamedQuery type");
2959 }
2960
2961 set_named_conn_backend(NULL);
2962 destroy_pool(tmp_pool);
2963
2964 sql_log(DEBUG_FUNC, "<<< process_named_query '%s'", name);
2965 return mr;
2966 }
2967
2968 MODRET process_sqllog(cmd_rec *cmd, config_rec *c, const char *label,
2969 int flags) {
2970 char *query_name = NULL, *query_type = NULL;
2971 modret_t *mr = NULL;
2972
2973 query_name = c->argv[0];
2974
2975 sql_log(DEBUG_FUNC, ">>> %s (%s)", label, c->name);
2976
2977 query_type = named_query_type(cmd, query_name);
2978 if (query_type != NULL) {
2979 if (strcasecmp(query_type, SQL_UPDATE_C) == 0 ||
2980 strcasecmp(query_type, SQL_FREEFORM_C) == 0 ||
2981 strcasecmp(query_type, SQL_INSERT_C) == 0) {
2982 mr = process_named_query(cmd, query_name, flags);
2983 if (check_response(mr, flags) < 0) {
2984 return mr;
2985 }
2986
2987 } else {
2988 sql_log(DEBUG_WARN, "named query '%s' is not an INSERT, UPDATE, or "
2989 "FREEFORM query", query_name);
2990 }
2991
2992 } else {
2993 sql_log(DEBUG_WARN, "named query '%s' cannot be found", query_name);
2994 }
2995
2996 sql_log(DEBUG_FUNC, "<<< %s (%s)", label, c->name);
2997 return mr;
2998 }
2999
3000 static int eventlog_master(const char *event_name) {
3001 char *name = NULL;
3002 cmd_rec *cmd = NULL;
3003 config_rec *c = NULL;
3004 modret_t *mr = NULL;
3005
3006 if (!(cmap.engine & SQL_ENGINE_FL_LOG)) {
3007 return 0;
3008 }
3009
3010 /* Need to create fake cmd_rec for dispatching, since we need
3011 * cmd->pool, cmd->tmp_pool. The cmd_rec MUST have
3012 * fake/unknown name (i.e. cmd->argv[0], cmd->cmd_id), so that it does
3013 * not run afoul of other logging variables.
3014 */
3015 cmd = sql_make_cmd(session.pool, 1, "EVENT");
3016 name = pstrcat(cmd->tmp_pool, "SQLLog_Event_", event_name, NULL);
3017
3018 c = find_config(main_server->conf, CONF_PARAM, name, FALSE);
3019 while (c != NULL) {
3020 int flags = 0;
3021
3022 pr_signals_handle();
3023
3024 if (c->argc == 3 &&
3025 strncmp(c->argv[2], "ignore", 7) == 0) {
3026 flags |= SQL_LOG_FL_IGNORE_ERRORS;
3027 }
3028
3029 pr_trace_msg(trace_channel, 12,
3030 "executing SQLNamedQuery '%s' for event '%s'", (char *) c->argv[0],
3031 event_name);
3032 mr = process_sqllog(cmd, c, "eventlog_master", flags);
3033 if (mr != NULL &&
3034 MODRET_ISERROR(mr)) {
3035 SQL_FREE_CMD(cmd);
3036 return -1;
3037 }
3038
3039 c = find_config_next(c, c->next, CONF_PARAM, name, FALSE);
3040 }
3041
3042 SQL_FREE_CMD(cmd);
3043 return 0;
3044 }
3045
3046 MODRET log_master(cmd_rec *cmd) {
3047 char *name = NULL;
3048 config_rec *c = NULL;
3049 modret_t *mr = NULL;
3050
3051 if (!(cmap.engine & SQL_ENGINE_FL_LOG)) {
3052 return PR_DECLINED(cmd);
3053 }
3054
3055 /* Ignore EXIT commands (as from mod_log) here; we handle them differently
3056 * in the 'core.exit' event lister.
3057 */
3058 if (pr_cmd_strcmp(cmd, "EXIT") == 0) {
3059 return PR_DECLINED(cmd);
3060 }
3061
3062 /* handle explicit queries */
3063 name = pstrcat(cmd->tmp_pool, "SQLLog_", cmd->argv[0], NULL);
3064
3065 c = find_config(main_server->conf, CONF_PARAM, name, FALSE);
3066 while (c != NULL) {
3067 int flags = 0;
3068
3069 pr_signals_handle();
3070
3071 if (c->argc == 2 &&
3072 strncmp(c->argv[1], "ignore", 7) == 0) {
3073 flags |= SQL_LOG_FL_IGNORE_ERRORS;
3074 }
3075
3076 mr = process_sqllog(cmd, c, "log_master", flags);
3077 if (mr != NULL &&
3078 MODRET_ISERROR(mr)) {
3079
3080 /* We always return DECLINED if we're in the LOG_CMD/LOG_CMD_ERR phase,
3081 * regardless of the SQLLog processing outcome (Bug#3633).
3082 */
3083 if (session.curr_phase == LOG_CMD ||
3084 session.curr_phase == LOG_CMD_ERR) {
3085 return PR_DECLINED(cmd);
3086 }
3087
3088 return mr;
3089 }
3090
3091 c = find_config_next(c, c->next, CONF_PARAM, name, FALSE);
3092 }
3093
3094 /* handle implicit queries */
3095 name = pstrcat(cmd->tmp_pool, "SQLLog_*", NULL);
3096
3097 c = find_config(main_server->conf, CONF_PARAM, name, FALSE);
3098 while (c != NULL) {
3099 int flags = 0;
3100
3101 pr_signals_handle();
3102
3103 if (c->argc == 2 &&
3104 strncmp(c->argv[1], "ignore", 7) == 0) {
3105 flags |= SQL_LOG_FL_IGNORE_ERRORS;
3106 }
3107
3108 mr = process_sqllog(cmd, c, "log_master", flags);
3109 if (mr != NULL &&
3110 MODRET_ISERROR(mr)) {
3111
3112 /* We always return DECLINED if we're in the LOG_CMD/LOG_CMD_ERR phase,
3113 * regardless of the SQLLog processing outcome (Bug#3633).
3114 */
3115 if (session.curr_phase == LOG_CMD ||
3116 session.curr_phase == LOG_CMD_ERR) {
3117 return PR_DECLINED(cmd);
3118 }
3119
3120 return mr;
3121 }
3122
3123 c = find_config_next(c, c->next, CONF_PARAM, name, FALSE);
3124 }
3125
3126 return PR_DECLINED(cmd);
3127 }
3128
3129 MODRET err_master(cmd_rec *cmd) {
3130 char *name = NULL;
3131 config_rec *c = NULL;
3132 modret_t *mr = NULL;
3133
3134 if (!(cmap.engine & SQL_ENGINE_FL_LOG)) {
3135 return PR_DECLINED(cmd);
3136 }
3137
3138 /* handle explicit errors */
3139 name = pstrcat(cmd->tmp_pool, "SQLLog_ERR_", cmd->argv[0], NULL);
3140
3141 c = find_config(main_server->conf, CONF_PARAM, name, FALSE);
3142 while (c != NULL) {
3143 int flags = 0;
3144
3145 pr_signals_handle();
3146
3147 if (c->argc == 2 &&
3148 strncmp(c->argv[1], "ignore", 7) == 0) {
3149 flags |= SQL_LOG_FL_IGNORE_ERRORS;
3150 }
3151
3152 mr = process_sqllog(cmd, c, "err_master", flags);
3153 if (mr != NULL &&
3154 MODRET_ISERROR(mr)) {
3155
3156 /* We always return DECLINED if we're in the LOG_CMD/LOG_CMD_ERR phase,
3157 * regardless of the SQLLog processing outcome (Bug#3633).
3158 */
3159 if (session.curr_phase == LOG_CMD ||
3160 session.curr_phase == LOG_CMD_ERR) {
3161 return PR_DECLINED(cmd);
3162 }
3163
3164 return mr;
3165 }
3166
3167 c = find_config_next(c, c->next, CONF_PARAM, name, FALSE);
3168 }
3169
3170 /* handle implicit errors */
3171 name = pstrcat(cmd->tmp_pool, "SQLLog_ERR_*", NULL);
3172
3173 c = find_config(main_server->conf, CONF_PARAM, name, FALSE);
3174 while (c != NULL) {
3175 int flags = 0;
3176
3177 pr_signals_handle();
3178
3179 if (c->argc == 2 &&
3180 strncmp(c->argv[1], "ignore", 7) == 0) {
3181 flags |= SQL_LOG_FL_IGNORE_ERRORS;
3182 }
3183
3184 mr = process_sqllog(cmd, c, "err_master", flags);
3185 if (mr != NULL &&
3186 MODRET_ISERROR(mr)) {
3187
3188 /* We always return DECLINED if we're in the LOG_CMD/LOG_CMD_ERR phase,
3189 * regardless of the SQLLog processing outcome (Bug#3633).
3190 */
3191 if (session.curr_phase == LOG_CMD ||
3192 session.curr_phase == LOG_CMD_ERR) {
3193 return PR_DECLINED(cmd);
3194 }
3195
3196 return mr;
3197 }
3198
3199 c = find_config_next(c, c->next, CONF_PARAM, name, FALSE);
3200 }
3201
3202 return PR_DECLINED(cmd);
3203 }
3204
3205 static int showinfo_on_meta(pool *p, pr_jot_ctx_t *jot_ctx,
3206 unsigned char logfmt_id, const char *jot_hint, const void *val) {
3207 int res = 0;
3208 struct sql_resolved *resolved;
3209 cmd_rec *cmd;
3210
3211 resolved = jot_ctx->log;
3212 cmd = (cmd_rec *) jot_ctx->user_data;
3213
3214 if (resolved->buflen > 0) {
3215 /* Note: we can cheat, and reuse the sql_resolve_on_meta() function for
3216 * almost all of this.
3217 */
3218 if (logfmt_id == LOGFMT_META_CUSTOM) {
3219 const char *text;
3220 size_t text_len = 0;
3221 char *query_name, *query_type;
3222 modret_t *mr = NULL;
3223 sql_data_t *sd = NULL;
3224
3225 /* If this is not a SELECT query, skip it. */
3226 query_name = (char *) val;
3227 query_type = named_query_type(cmd, query_name);
3228 if (query_type == NULL ||
3229 (strcasecmp(query_type, SQL_SELECT_C) != 0 &&
3230 strcasecmp(query_type, SQL_FREEFORM_C) != 0)) {
3231 return 0;
3232 }
3233
3234 mr = process_named_query(cmd, query_name, 0);
3235 if (check_response(mr, 0) < 0) {
3236 errno = EPERM;
3237 return -1;
3238 }
3239
3240 sd = mr->data;
3241 if (sd->rnum == 0 ||
3242 sd->data[0] == NULL) {
3243 /* No data returned. */
3244 errno = ENOENT;
3245 return -1;
3246 }
3247
3248 text = sd->data[0];
3249
3250 /* Treat the text "null" the same as a real null, and ignore it. */
3251 if (strcasecmp(text, "null") == 0) {
3252 errno = ENOENT;
3253 return -1;
3254 }
3255
3256 text_len = strlen(text);
3257 res = sql_resolved_append_text(p, resolved, text, text_len, FALSE);
3258
3259 } else {
3260 res = sql_resolve_on_meta(p, jot_ctx, logfmt_id, jot_hint, val);
3261 }
3262 }
3263
3264 return res;
3265 }
3266
3267 static char *get_showinfo_query_text(cmd_rec *cmd, unsigned char *logfmt,
3268 const char *conn_name, size_t *text_len) {
3269 char results[SQL_MAX_STMT_LEN+1], *text = NULL;
3270 size_t results_len = 0;
3271 int res;
3272 pool *tmp_pool;
3273 pr_jot_ctx_t *jot_ctx;
3274 struct sql_resolved *resolved;
3275
3276 tmp_pool = make_sub_pool(cmd->tmp_pool);
3277 jot_ctx = pcalloc(tmp_pool, sizeof(pr_jot_ctx_t));
3278 resolved = pcalloc(tmp_pool, sizeof(struct sql_resolved));
3279 resolved->bufsz = resolved->buflen = sizeof(results)-1;
3280 resolved->ptr = resolved->buf = results;
3281 resolved->conn_name = conn_name;
3282
3283 jot_ctx->log = resolved;
3284 jot_ctx->user_data = cmd;
3285
3286 res = pr_jot_resolve_logfmt(tmp_pool, cmd, NULL, logfmt, jot_ctx,
3287 showinfo_on_meta, sql_resolve_on_default, sql_resolve_on_other);
3288 if (res < 0) {
3289 if (errno == EIO) {
3290 return NULL;
3291 }
3292
3293 /* For any other reason, the resolver terminated early; we do not
3294 * want to use anything that may be in the buffer.
3295 */
3296 results_len = 0;
3297
3298 } else {
3299 results_len = resolved->bufsz - resolved->buflen;
3300 }
3301
3302 results[results_len] = '\0';
3303 text = pstrndup(cmd->tmp_pool, results, results_len);
3304 *text_len = results_len;
3305
3306 destroy_pool(tmp_pool);
3307 return text;
3308 }
3309
3310 MODRET info_master(cmd_rec *cmd) {
3311 char *name = NULL;
3312 config_rec *c = NULL;
3313 char *resp_code = NULL;
3314
3315 if (!(cmap.engine & SQL_ENGINE_FL_LOG)) {
3316 return PR_DECLINED(cmd);
3317 }
3318
3319 /* process explicit handlers */
3320 name = pstrcat(cmd->tmp_pool, "SQLShowInfo_", cmd->argv[0], NULL);
3321
3322 c = find_config(main_server->conf, CONF_PARAM, name, FALSE);
3323 while (c != NULL) {
3324 char *conn_name, *text = NULL;
3325 size_t text_len = 0;
3326
3327 pr_signals_handle();
3328
3329 sql_log(DEBUG_FUNC, ">>> info_master (%s)", name);
3330
3331 /* We now have at least one config_rec. Take the output string from
3332 * each, and process it: resolve tags, and when we find a named query,
3333 * run it and get info from it.
3334 */
3335
3336 conn_name = get_query_named_conn(c);
3337 set_named_conn_backend(conn_name);
3338
3339 text = get_showinfo_query_text(cmd, c->argv[1], conn_name, &text_len);
3340 set_named_conn_backend(NULL);
3341
3342 /* Add the response, if we have one. */
3343 if (text != NULL &&
3344 text_len > 0) {
3345 /* We keep track of the response code used, as we will need it when
3346 * flushing the added lines out to the client.
3347 */
3348 resp_code = c->argv[0];
3349 pr_response_add(resp_code, "%s", text);
3350 }
3351
3352 sql_log(DEBUG_FUNC, "<<< info_master (%s)", name);
3353
3354 c = find_config_next(c, c->next, CONF_PARAM, name, FALSE);
3355 }
3356
3357 /* process implicit handlers */
3358 name = pstrdup(cmd->tmp_pool, "SQLShowInfo_*");
3359
3360 c = find_config(main_server->conf, CONF_PARAM, name, FALSE);
3361 while (c != NULL) {
3362 char *conn_name, *text = NULL;
3363 size_t text_len = 0;
3364
3365 pr_signals_handle();
3366
3367 sql_log(DEBUG_FUNC, ">>> info_master (%s)", name);
3368
3369 conn_name = get_query_named_conn(c);
3370 set_named_conn_backend(conn_name);
3371
3372 text = get_showinfo_query_text(cmd, c->argv[1], conn_name, &text_len);
3373 set_named_conn_backend(NULL);
3374
3375 /* Add the response, if we have one. */
3376 if (text != NULL &&
3377 text_len > 0) {
3378 /* We keep track of the response code used, as we will need it when
3379 * flushing the added lines out to the client.
3380 */
3381 resp_code = c->argv[0];
3382 pr_response_add(resp_code, "%s", text);
3383 }
3384
3385 sql_log(DEBUG_FUNC, "<<< info_master (%s)", name);
3386
3387 c = find_config_next(c, c->next, CONF_PARAM, name, FALSE);
3388 }
3389
3390 return PR_DECLINED(cmd);
3391 }
3392
3393 MODRET errinfo_master(cmd_rec *cmd) {
3394 char *name = NULL;
3395 config_rec *c = NULL;
3396 char *resp_code = NULL;
3397
3398 if (!(cmap.engine & SQL_ENGINE_FL_LOG)) {
3399 return PR_DECLINED(cmd);
3400 }
3401
3402 /* process explicit handlers */
3403 name = pstrcat(cmd->tmp_pool, "SQLShowInfo_ERR_", cmd->argv[0], NULL);
3404
3405 c = find_config(main_server->conf, CONF_PARAM, name, FALSE);
3406 while (c != NULL) {
3407 char *conn_name, *text = NULL;
3408 size_t text_len = 0;
3409
3410 pr_signals_handle();
3411
3412 sql_log(DEBUG_FUNC, ">>> errinfo_master (%s)", name);
3413
3414 /* We now have at least one config_rec. Take the output string from
3415 * each, and process it: resolve tags, and when we find a named query,
3416 * run it and get info from it.
3417 */
3418
3419 conn_name = get_query_named_conn(c);
3420 set_named_conn_backend(conn_name);
3421
3422 pr_trace_msg(trace_channel, 15, "processing SQLShowInfo ERR_%s",
3423 (char *) cmd->argv[0]);
3424 text = get_showinfo_query_text(cmd, c->argv[1], conn_name, &text_len);
3425 set_named_conn_backend(NULL);
3426
3427 /* Add the response, if we have one. */
3428 if (text != NULL &&
3429 text_len > 0) {
3430 /* We keep track of the response code used, as we will need it when
3431 * flushing the added lines out to the client.
3432 */
3433 resp_code = c->argv[0];
3434
3435 if (*resp_code == '4' ||
3436 *resp_code == '5') {
3437 pr_trace_msg(trace_channel, 15,
3438 "adding error response code %s, msg '%.*s' for SQLShowInfo ERR_%s",
3439 resp_code, (int) text_len, text, (char *) cmd->argv[0]);
3440
3441 pr_response_add_err(resp_code, "%.*s", (int) text_len, text);
3442
3443 } else {
3444 pr_trace_msg(trace_channel, 15,
3445 "adding response code %s, msg '%.*s' for SQLShowInfo ERR_%s",
3446 resp_code, (int) text_len, text, (char *) cmd->argv[0]);
3447
3448 pr_response_add(resp_code, "%.*s", (int) text_len, text);
3449 }
3450 }
3451
3452 sql_log(DEBUG_FUNC, "<<< errinfo_master (%s)", name);
3453
3454 c = find_config_next(c, c->next, CONF_PARAM, name, FALSE);
3455 }
3456
3457 /* process implicit handlers */
3458 name = pstrcat(cmd->tmp_pool, "SQLShowInfo_ERR_*", NULL);
3459
3460 c = find_config(main_server->conf, CONF_PARAM, name, FALSE);
3461 while (c != NULL) {
3462 char *conn_name, *text = NULL;
3463 size_t text_len = 0;
3464
3465 pr_signals_handle();
3466
3467 sql_log(DEBUG_FUNC, ">>> errinfo_master (%s)", name);
3468
3469 conn_name = get_query_named_conn(c);
3470 set_named_conn_backend(conn_name);
3471
3472 text = get_showinfo_query_text(cmd, c->argv[1], conn_name, &text_len);
3473 set_named_conn_backend(NULL);
3474
3475 /* Add the response, if we have one. */
3476 if (text != NULL &&
3477 text_len > 0) {
3478 /* We keep track of the response code used, as we will need it when
3479 * flushing the added lines out to the client.
3480 */
3481 resp_code = c->argv[0];
3482
3483 if (*resp_code == '4' ||
3484 *resp_code == '5') {
3485 pr_trace_msg(trace_channel, 15,
3486 "adding error response code %s, msg '%.*s' for SQLShowInfo ERR_*",
3487 resp_code, (int) text_len, text);
3488
3489 pr_response_add_err(resp_code, "%.*s", (int) text_len, text);
3490
3491 } else {
3492 pr_trace_msg(trace_channel, 15,
3493 "adding response code %s, msg '%.*s' for SQLShowInfo ERR_*",
3494 resp_code, (int) text_len, text);
3495
3496 pr_response_add(resp_code, "%.*s", (int) text_len, text);
3497 }
3498 }
3499
3500 sql_log(DEBUG_FUNC, "<<< errinfo_master (%s)", name);
3501
3502 c = find_config_next(c, c->next, CONF_PARAM, name, FALSE);
3503 }
3504
3505 return PR_DECLINED(cmd);
3506 }
3507
3508 MODRET sql_cleanup(cmd_rec *cmd) {
3509 modret_t *res;
3510
3511 sql_log(DEBUG_FUNC, "%s", ">>> sql_cleanup");
3512
3513 res = sql_dispatch(cmd, "sql_cleanup");
3514 if (check_response(res, 0) < 0) {
3515 sql_log(DEBUG_FUNC, "%s", "<<< sql_cleanup");
3516 return res;
3517 }
3518
3519 sql_log(DEBUG_FUNC, "%s", "<<< sql_cleanup");
3520 return res;
3521 }
3522
3523 MODRET sql_closeconn(cmd_rec *cmd) {
3524 modret_t *res;
3525
3526 sql_log(DEBUG_FUNC, "%s", ">>> sql_closeconn");
3527 res = sql_dispatch(cmd, "sql_close");
3528 sql_log(DEBUG_FUNC, "%s", "<<< sql_closeconn");
3529
3530 return res;
3531 }
3532
3533 MODRET sql_defineconn(cmd_rec *cmd) {
3534 modret_t *res;
3535
3536 sql_log(DEBUG_FUNC, "%s", ">>> sql_defineconn");
3537 res = sql_dispatch(cmd, "sql_defineconnection");
3538 sql_log(DEBUG_FUNC, "%s", "<<< sql_defineconn");
3539
3540 return res;
3541 }
3542
3543 MODRET sql_load_backend(cmd_rec *cmd) {
3544 modret_t *res;
3545
3546 sql_log(DEBUG_FUNC, "%s", ">>> sql_load_backend");
3547
3548 if (cmd->argc == 1) {
3549 sql_set_backend(cmd->argv[0]);
3550
3551 } else {
3552 sql_set_backend(NULL);
3553 }
3554
3555 res = mod_create_data(cmd, NULL);
3556
3557 sql_log(DEBUG_FUNC, "%s", "<<< sql_load_backend");
3558 return res;
3559 }
3560
3561 MODRET sql_openconn(cmd_rec *cmd) {
3562 modret_t *res;
3563
3564 sql_log(DEBUG_FUNC, "%s", ">>> sql_openconn");
3565 res = sql_dispatch(cmd, "sql_open");
3566 sql_log(DEBUG_FUNC, "%s", "<<< sql_openconn");
3567
3568 return res;
3569 }
3570
3571 MODRET sql_prepare(cmd_rec *cmd) {
3572 modret_t *res;
3573
3574 sql_log(DEBUG_FUNC, "%s", ">>> sql_prepare");
3575 res = sql_dispatch(cmd, "sql_prepare");
3576 sql_log(DEBUG_FUNC, "%s", "<<< sql_prepare");
3577
3578 return res;
3579 }
3580
3581 MODRET sql_select(cmd_rec *cmd) {
3582 modret_t *res;
3583
3584 sql_log(DEBUG_FUNC, "%s", ">>> sql_select");
3585 res = sql_dispatch(cmd, "sql_select");
3586 sql_log(DEBUG_FUNC, "%s", "<<< sql_select");
3587
3588 return res;
3589 }
3590
3591 /* sql_lookup: used by third-party modules to get data via a SQL query.
3592 * Third party module must pass a legitimate cmd_rec (including tmp_pool),
3593 * and the cmd_rec must have only one argument: the name of a SQLNamedQuery.
3594 *
3595 * Returns:
3596 *
3597 * DECLINED if mod_sql isn't on
3598 * ERROR if named query doesn't exist
3599 *
3600 * SHUTS DOWN if query caused an error
3601 *
3602 * otherwise:
3603 *
3604 * array_header * in the data slot with the returned data. It is up to the
3605 * calling function to know how many pieces of data to expect, and how to
3606 * parse them.
3607 */
3608 MODRET sql_lookup(cmd_rec *cmd) {
3609 char *type = NULL;
3610 modret_t *mr = NULL;
3611 sql_data_t *sd = NULL;
3612 array_header *ah = NULL;
3613
3614 if (cmap.engine == 0) {
3615 return PR_DECLINED(cmd);
3616 }
3617
3618 if (cmd->argc < 1) {
3619 return PR_ERROR(cmd);
3620 }
3621
3622 sql_log(DEBUG_FUNC, "%s", ">>> sql_lookup");
3623
3624 type = named_query_type(cmd, cmd->argv[1]);
3625 if (type && (strcasecmp(type, SQL_SELECT_C) == 0 ||
3626 strcasecmp(type, SQL_FREEFORM_C) == 0)) {
3627 mr = process_named_query(cmd, cmd->argv[1], 0);
3628
3629 if (mr != NULL &&
3630 !MODRET_ISERROR(mr)) {
3631 register unsigned int i;
3632
3633 sd = (sql_data_t *) mr->data;
3634
3635 ah = make_array(session.pool, (sd->rnum * sd->fnum) , sizeof(char *));
3636
3637 /* The right way to do this is to preserve the abstraction of the array
3638 * header so things don't blow up when it gets freed.
3639 */
3640 for (i = 0; i < (sd->rnum * sd->fnum); i++) {
3641 *((char **) push_array(ah)) = sd->data[i];
3642 }
3643
3644 mr = mod_create_data(cmd, (void *) ah);
3645
3646 } else {
3647 /* We have an error. Log it and die. */
3648 if (check_response(mr, 0) < 0) {
3649 sql_log(DEBUG_FUNC, "%s", "<<< sql_lookup");
3650 return mr;
3651 }
3652 }
3653
3654 } else {
3655 mr = PR_ERROR(cmd);
3656 }
3657
3658 sql_log(DEBUG_FUNC, "%s", "<<< sql_lookup");
3659 return mr;
3660 }
3661
3662 MODRET sql_change(cmd_rec *cmd) {
3663 char *type = NULL;
3664 modret_t *mr = NULL;
3665
3666 if (cmap.engine == 0) {
3667 return PR_DECLINED(cmd);
3668 }
3669
3670 if (cmd->argc < 1) {
3671 return PR_ERROR(cmd);
3672 }
3673
3674 sql_log(DEBUG_FUNC, "%s", ">>> sql_change");
3675
3676 type = named_query_type(cmd, cmd->argv[1]);
3677 if (type && ((!strcasecmp(type, SQL_INSERT_C)) ||
3678 (!strcasecmp(type, SQL_UPDATE_C)) ||
3679 (!strcasecmp(type, SQL_FREEFORM_C)))) {
3680 /* fixup the cmd_rec */
3681
3682 mr = process_named_query(cmd, cmd->argv[1], 0);
3683 if (check_response(mr, 0) < 0) {
3684 sql_log(DEBUG_FUNC, "%s", "<<< sql_change");
3685 return mr;
3686 }
3687
3688 } else {
3689 mr = PR_ERROR(cmd);
3690 }
3691
3692 sql_log(DEBUG_FUNC, "%s", "<<< sql_change");
3693 return mr;
3694 }
3695
3696 MODRET sql_escapestr(cmd_rec *cmd) {
3697 modret_t *mr;
3698
3699 sql_log(DEBUG_FUNC, "%s", ">>> sql_escapestr");
3700
3701 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
3702 cmd->argv[0]), "sql_escapestring");
3703 if (check_response(mr, 0) < 0) {
3704 sql_log(DEBUG_FUNC, "%s", "<<< sql_escapestr");
3705 return mr;
3706 }
3707
3708 sql_log(DEBUG_FUNC, "%s", "<<< sql_escapestr");
3709 return mr;
3710 }
3711
3712 /* SQLKeepAlive timer callback. */
3713 static int sql_keepalive_cb(CALLBACK_FRAME) {
3714 pool *tmp_pool;
3715 cmd_rec *cmd;
3716
3717 tmp_pool = make_sub_pool(session.pool);
3718 pr_pool_tag(tmp_pool, "SQL keepalive pool");
3719 cmd = sql_make_cmd(tmp_pool, 2, MOD_SQL_DEF_CONN_NAME, sql_keepalive_stmt);
3720 (void) sql_dispatch(cmd, "sql_query");
3721
3722 return 1;
3723 }
3724
3725 /* Auth Handlers.
3726 */
3727
3728 MODRET sql_auth_setpwent(cmd_rec *cmd) {
3729 sql_data_t *sd = NULL;
3730 modret_t *mr = NULL;
3731 char *where = NULL;
3732 int i = 0;
3733 unsigned long cnt = 0;
3734
3735 char *username = NULL;
3736 char *password = NULL;
3737 char *shell = NULL;
3738 char *dir = NULL;
3739 uid_t uid = 0;
3740 gid_t gid = 0;
3741
3742 struct passwd lpw;
3743
3744 if (!SQL_USERSET ||
3745 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
3746 return PR_DECLINED(cmd);
3747 }
3748
3749 sql_log(DEBUG_FUNC, "%s", ">>> cmd_setpwent");
3750
3751 /* if we've already filled the passwd cache, just reset the curr_passwd */
3752 if (cmap.passwd_cache_filled) {
3753 cmap.curr_passwd = passwd_name_cache->head;
3754 sql_log(DEBUG_FUNC, "%s", "<<< cmd_setpwent");
3755 return PR_DECLINED(cmd);
3756 }
3757
3758 /* single select or not? */
3759 if (SQL_FASTUSERS) {
3760 /* retrieve our list of users */
3761
3762 if (!cmap.usercustomusersetfast) {
3763 where = sql_prepare_where(0, cmd, 1, cmap.userwhere, NULL);
3764
3765 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 4, MOD_SQL_DEF_CONN_NAME,
3766 cmap.usrtable, cmap.usrfields, where), "sql_select");
3767 if (check_response(mr, 0) < 0) {
3768 return mr;
3769 }
3770
3771 sd = (sql_data_t *) mr->data;
3772
3773 } else {
3774 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
3775 cmap.usercustomusersetfast));
3776 if (check_response(mr, 0) < 0) {
3777 return mr;
3778 }
3779
3780 if (MODRET_HASDATA(mr)) {
3781 array_header *ah = (array_header *) mr->data;
3782 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
3783
3784 /* Assume the query returned 6 columns per row. */
3785 sd->fnum = 6;
3786 sd->rnum = ah->nelts / 6;
3787 sd->data = (char **) ah->elts;
3788
3789 } else {
3790 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
3791 sd->rnum = 0;
3792 }
3793 }
3794
3795 /* Walk through the array, adding users to the cache */
3796 if (sd != NULL) {
3797 for (i = 0, cnt = 0; cnt < sd->rnum; cnt++) {
3798 username = sd->data[i++];
3799
3800 /* if the username is NULL, skip it */
3801 if (username == NULL)
3802 continue;
3803
3804 password = sd->data[i++];
3805
3806 uid = cmap.defaultuid;
3807 if (cmap.uidfield) {
3808 if (sd->data[i]) {
3809 if (pr_str2uid(sd->data[i++], &uid) < 0) {
3810 uid = cmap.defaultuid;
3811 }
3812
3813 } else {
3814 i++;
3815 }
3816 }
3817
3818 gid = cmap.defaultgid;
3819 if (cmap.gidfield) {
3820 if (sd->data[i]) {
3821 if (pr_str2gid(sd->data[i++], &gid) < 0) {
3822 gid = cmap.defaultgid;
3823 }
3824
3825 } else {
3826 i++;
3827 }
3828 }
3829
3830 dir = cmap.defaulthomedir;
3831 if (sd->data[i]) {
3832 if (strncmp(sd->data[i], "", 2) == 0 ||
3833 strncmp(sd->data[i], "NULL", 5) == 0) {
3834 /* Leave dir pointing to the SQLDefaultHomedir, if any. */
3835 i++;
3836
3837 } else {
3838 dir = sd->data[i++];
3839 }
3840 }
3841
3842 if (cmap.shellfield) {
3843 shell = sd->data[i++];
3844
3845 } else {
3846 shell = "";
3847 }
3848
3849 if (uid < cmap.minuseruid) {
3850 sql_log(DEBUG_INFO, "user UID %s below SQLMinUserUID %s, using "
3851 "SQLDefaultUID %s", pr_uid2str(cmd->tmp_pool, uid),
3852 pr_uid2str(cmd->tmp_pool, cmap.minuseruid),
3853 pr_uid2str(cmd->tmp_pool, cmap.defaultuid));
3854 uid = cmap.defaultuid;
3855 }
3856
3857 if (gid < cmap.minusergid) {
3858 sql_log(DEBUG_INFO, "user GID %s below SQLMinUserGID %s, using "
3859 "SQLDefaultGID %s", pr_gid2str(cmd->tmp_pool, gid),
3860 pr_gid2str(cmd->tmp_pool, cmap.minusergid),
3861 pr_gid2str(cmd->tmp_pool, cmap.defaultgid));
3862 gid = cmap.defaultgid;
3863 }
3864
3865 _sql_addpasswd(cmd, username, password, uid, gid, shell, dir);
3866 }
3867 }
3868
3869 } else {
3870 /* Retrieve our list of users */
3871
3872 if (!cmap.usercustomuserset) {
3873 where = sql_prepare_where(0, cmd, 1, cmap.userwhere, NULL);
3874
3875 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 4, MOD_SQL_DEF_CONN_NAME,
3876 cmap.usrtable, cmap.usrfield, where), "sql_select");
3877 if (check_response(mr, 0) < 0) {
3878 return mr;
3879 }
3880
3881 sd = (sql_data_t *) mr->data;
3882
3883 } else {
3884 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
3885 cmap.usercustomuserset));
3886 if (check_response(mr, 0) < 0) {
3887 return mr;
3888 }
3889
3890 if (MODRET_HASDATA(mr)) {
3891 array_header *ah = (array_header *) mr->data;
3892 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
3893
3894 /* Assume the query only returned 1 column per row. */
3895 sd->fnum = 1;
3896 sd->rnum = ah->nelts;
3897 sd->data = (char **) ah->elts;
3898 }
3899 }
3900
3901 if (sd != NULL) {
3902 for (cnt = 0; cnt < sd->rnum; cnt++) {
3903 username = sd->data[cnt];
3904
3905 /* if the username is NULL for whatever reason, skip it */
3906 if (username == NULL) {
3907 continue;
3908 }
3909
3910 /* otherwise, add it to the cache */
3911 lpw.pw_uid = -1;
3912 lpw.pw_gid = -1;
3913 lpw.pw_name = username;
3914 sql_getpasswd(cmd, &lpw);
3915 }
3916 }
3917 }
3918
3919 cmap.passwd_cache_filled = 1;
3920 cmap.curr_passwd = passwd_name_cache->head;
3921
3922 sql_log(DEBUG_FUNC, "%s", "<<< cmd_setpwent");
3923 return PR_DECLINED(cmd);
3924 }
3925
3926 MODRET sql_auth_getpwent(cmd_rec *cmd) {
3927 struct passwd *pw;
3928 modret_t *mr;
3929
3930 if (!SQL_USERSET ||
3931 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
3932 return PR_DECLINED(cmd);
3933 }
3934
3935 sql_log(DEBUG_FUNC, "%s", ">>> cmd_getpwent");
3936
3937 /* make sure our passwd cache is complete */
3938 if (!cmap.passwd_cache_filled) {
3939 mr = sql_auth_setpwent(cmd);
3940 if (mr->data == NULL) {
3941 /* something didn't work in the setpwent call */
3942 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getpwent");
3943 return PR_DECLINED(cmd);
3944 }
3945 }
3946
3947 if (cmap.curr_passwd != NULL) {
3948 pw = (struct passwd *) cmap.curr_passwd->data;
3949 cmap.curr_passwd = cmap.curr_passwd->list_next;
3950
3951 } else {
3952 pw = NULL;
3953 }
3954
3955 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getpwent");
3956
3957 if (pw == NULL ||
3958 pw->pw_uid == (uid_t) -1)
3959 return PR_DECLINED(cmd);
3960
3961 return mod_create_data(cmd, (void *) pw);
3962 }
3963
3964 MODRET sql_auth_endpwent(cmd_rec *cmd) {
3965 if (!SQL_USERSET ||
3966 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
3967 return PR_DECLINED(cmd);
3968 }
3969
3970 sql_log(DEBUG_FUNC, "%s", ">>> cmd_endpwent");
3971
3972 cmap.curr_passwd = NULL;
3973
3974 sql_log(DEBUG_FUNC, "%s", "<<< cmd_endpwent");
3975 return PR_DECLINED(cmd);
3976 }
3977
3978 MODRET sql_auth_setgrent(cmd_rec *cmd) {
3979 modret_t *mr = NULL;
3980 sql_data_t *sd = NULL;
3981 unsigned long cnt = 0;
3982 struct group lgr;
3983 gid_t gid;
3984 char *groupname = NULL;
3985 char *grp_mem = NULL;
3986 char *where = NULL;
3987 array_header *ah =NULL;
3988 char *iterator = NULL;
3989 char *member = NULL;
3990
3991 if (!SQL_GROUPSET ||
3992 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
3993 return PR_DECLINED(cmd);
3994 }
3995
3996 sql_log(DEBUG_FUNC, "%s", ">>> cmd_setgrent");
3997
3998 /* if we've already filled the passwd group, just reset curr_group */
3999 if (cmap.group_cache_filled) {
4000 cmap.curr_group = group_name_cache->head;
4001 sql_log(DEBUG_FUNC, "%s", "<<< cmd_setgrent");
4002 return PR_DECLINED(cmd);
4003 }
4004
4005 if (SQL_FASTGROUPS) {
4006 /* retrieve our list of groups */
4007
4008 if (!cmap.groupcustomgroupsetfast) {
4009 where = sql_prepare_where(0, cmd, 1, cmap.groupwhere, NULL);
4010
4011 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 5, MOD_SQL_DEF_CONN_NAME,
4012 cmap.grptable, cmap.grpfields, where, "1"), "sql_select");
4013 if (check_response(mr, 0) < 0) {
4014 return mr;
4015 }
4016
4017 sd = (sql_data_t *) mr->data;
4018
4019 } else {
4020 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
4021 cmap.groupcustomgroupsetfast));
4022 if (check_response(mr, 0) < 0) {
4023 return mr;
4024 }
4025
4026 if (MODRET_HASDATA(mr)) {
4027 ah = mr->data;
4028 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
4029
4030 /* Assume the query returned 3 columns per row. */
4031 sd->fnum = 3;
4032 sd->rnum = ah->nelts / 3;
4033 sd->data = (char **) ah->elts;
4034
4035 } else {
4036 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
4037 sd->rnum = 0;
4038 }
4039 }
4040
4041 /* for each group, fill our array header and call _sql_addgroup */
4042
4043 for (cnt = 0; cnt < sd->rnum; cnt ++) {
4044 /* if the groupname is NULL for whatever reason, skip the row */
4045 groupname = sd->data[cnt * 3];
4046 if (groupname == NULL) {
4047 continue;
4048 }
4049
4050 gid = (gid_t) atol(sd->data[(cnt * 3) + 1]);
4051 grp_mem = sd->data[(cnt * 3) + 2];
4052
4053 ah = make_array(cmd->tmp_pool, 10, sizeof(char *));
4054 iterator = grp_mem;
4055
4056 for (member = strsep(&iterator, " ,"); member; member = strsep(&iterator, " ,")) {
4057 if (*member == '\0') {
4058 continue;
4059 }
4060
4061 *((char **) push_array(ah)) = member;
4062 }
4063
4064 _sql_addgroup(cmd, groupname, gid, ah);
4065 }
4066
4067 } else {
4068 /* Retrieve our list of groups. */
4069
4070 if (!cmap.groupcustomgroupset) {
4071 where = sql_prepare_where(0, cmd, 1, cmap.groupwhere, NULL);
4072
4073 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 6, MOD_SQL_DEF_CONN_NAME,
4074 cmap.grptable, cmap.grpfield, where, NULL, "DISTINCT"), "sql_select");
4075 if (check_response(mr, 0) < 0) {
4076 return mr;
4077 }
4078
4079 sd = (sql_data_t *) mr->data;
4080
4081 } else {
4082 mr = sql_lookup(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
4083 cmap.groupcustomgroupset));
4084 if (check_response(mr, 0) < 0) {
4085 return mr;
4086 }
4087
4088 if (MODRET_HASDATA(mr)) {
4089 ah = mr->data;
4090 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
4091
4092 /* Assume the query only returned 1 column per row. */
4093 sd->fnum = 1;
4094 sd->rnum = ah->nelts;
4095 sd->data = (char **) ah->elts;
4096
4097 } else {
4098 sd = pcalloc(cmd->tmp_pool, sizeof(sql_data_t));
4099 sd->rnum = 0;
4100 }
4101 }
4102
4103 for (cnt = 0; cnt < sd->rnum; cnt++) {
4104 groupname = sd->data[cnt];
4105
4106 /* if the groupname is NULL for whatever reason, skip it */
4107 if (groupname == NULL) {
4108 continue;
4109 }
4110
4111 /* otherwise, add it to the cache */
4112 lgr.gr_gid = -1;
4113 lgr.gr_name = groupname;
4114
4115 sql_getgroup(cmd, &lgr);
4116 }
4117 }
4118
4119 cmap.group_cache_filled = 1;
4120 cmap.curr_group = group_name_cache->head;
4121
4122 sql_log(DEBUG_FUNC, "%s", "<<< cmd_setgrent");
4123 return PR_DECLINED(cmd);
4124 }
4125
4126 MODRET sql_auth_getgrent(cmd_rec *cmd) {
4127 struct group *gr;
4128 modret_t *mr;
4129
4130 if (!SQL_GROUPSET ||
4131 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4132 return PR_DECLINED(cmd);
4133 }
4134
4135 sql_log(DEBUG_FUNC, "%s", ">>> cmd_getgrent");
4136
4137 /* make sure our group cache is complete */
4138 if (!cmap.group_cache_filled) {
4139 mr = sql_auth_setgrent(cmd);
4140 if (mr->data == NULL) {
4141 /* something didn't work in the setgrent call */
4142 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getgrent");
4143 return PR_DECLINED(cmd);
4144 }
4145 }
4146
4147 if (cmap.curr_group != NULL) {
4148 gr = (struct group *) cmap.curr_group->data;
4149 cmap.curr_group = cmap.curr_group->list_next;
4150
4151 } else {
4152 gr = NULL;
4153 }
4154
4155 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getgrent");
4156
4157 if (gr == NULL ||
4158 gr->gr_gid == (gid_t) -1) {
4159 return PR_DECLINED(cmd);
4160 }
4161
4162 return mod_create_data(cmd, (void *) gr);
4163 }
4164
4165 MODRET sql_auth_endgrent(cmd_rec *cmd) {
4166 if (!SQL_GROUPSET ||
4167 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4168 return PR_DECLINED(cmd);
4169 }
4170
4171 sql_log(DEBUG_FUNC, "%s", ">>> cmd_endgrent");
4172
4173 cmap.curr_group = NULL;
4174
4175 sql_log(DEBUG_FUNC, "%s", "<<< cmd_endgrent");
4176 return PR_DECLINED(cmd);
4177 }
4178
4179 MODRET sql_auth_getpwnam(cmd_rec *cmd) {
4180 struct passwd *pw;
4181 struct passwd lpw;
4182
4183 if (!SQL_USERS ||
4184 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4185 return PR_DECLINED(cmd);
4186 }
4187
4188 sql_log(DEBUG_FUNC, "%s", ">>> cmd_getpwnam");
4189
4190 lpw.pw_uid = -1;
4191 lpw.pw_gid = -1;
4192 lpw.pw_name = cmd->argv[0];
4193 pw = sql_getpasswd(cmd, &lpw);
4194
4195 if (pw == NULL ||
4196 pw->pw_uid == (uid_t) -1) {
4197 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getpwnam");
4198 return PR_DECLINED(cmd);
4199 }
4200
4201 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getpwnam");
4202 return mod_create_data(cmd, pw);
4203 }
4204
4205 MODRET sql_auth_getpwuid(cmd_rec *cmd) {
4206 struct passwd *pw;
4207 struct passwd lpw;
4208
4209 if (!SQL_USERS ||
4210 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4211 return PR_DECLINED(cmd);
4212 }
4213
4214 sql_log(DEBUG_FUNC, "%s", ">>> cmd_getpwuid");
4215
4216 lpw.pw_uid = *((uid_t *) cmd->argv[0]);
4217 lpw.pw_name = NULL;
4218 pw = sql_getpasswd(cmd, &lpw);
4219
4220 if (pw == NULL ||
4221 pw->pw_uid == (uid_t) -1) {
4222 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getpwuid");
4223 return PR_DECLINED(cmd);
4224 }
4225
4226 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getpwuid");
4227 return mod_create_data(cmd, pw);
4228 }
4229
4230 MODRET sql_auth_getgrnam(cmd_rec *cmd) {
4231 struct group *gr;
4232 struct group lgr;
4233
4234 if (!SQL_GROUPS ||
4235 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4236 return PR_DECLINED(cmd);
4237 }
4238
4239 sql_log(DEBUG_FUNC, "%s", ">>> cmd_getgrnam");
4240
4241 lgr.gr_gid = -1;
4242 lgr.gr_name = cmd->argv[0];
4243 gr = sql_getgroup(cmd, &lgr);
4244
4245 if (gr == NULL ||
4246 gr->gr_gid == (gid_t) -1) {
4247 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getgrnam");
4248 return PR_DECLINED(cmd);
4249 }
4250
4251 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getgrnam");
4252 return mod_create_data(cmd, gr);
4253 }
4254
4255 MODRET sql_auth_getgrgid(cmd_rec *cmd) {
4256 struct group *gr;
4257 struct group lgr;
4258
4259 if (!SQL_GROUPS ||
4260 !(cmap.engine & SQL_ENGINE_FL_AUTH))
4261 return PR_DECLINED(cmd);
4262
4263 sql_log(DEBUG_FUNC, "%s", ">>> cmd_getgrgid");
4264
4265 lgr.gr_gid = *((gid_t *) cmd->argv[0]);
4266 lgr.gr_name = NULL;
4267 gr = sql_getgroup(cmd, &lgr);
4268
4269 if (gr == NULL ||
4270 gr->gr_gid == (gid_t) -1) {
4271 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getgrgid");
4272 return PR_DECLINED(cmd);
4273 }
4274
4275 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getgrgid");
4276 return mod_create_data(cmd, gr);
4277 }
4278
4279 MODRET sql_auth_authenticate(cmd_rec *cmd) {
4280 char *user = NULL;
4281 struct passwd lpw, *pw;
4282 modret_t *mr = NULL;
4283
4284 if (!SQL_USERS ||
4285 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4286 return PR_DECLINED(cmd);
4287 }
4288
4289 sql_log(DEBUG_FUNC, "%s", ">>> cmd_auth");
4290
4291 user = cmd->argv[0];
4292
4293 /* escape our username */
4294 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 2, MOD_SQL_DEF_CONN_NAME,
4295 user), "sql_escapestring");
4296 if (check_response(mr, 0) < 0) {
4297 return mr;
4298 }
4299
4300 user = (char *) mr->data;
4301
4302 lpw.pw_uid = -1;
4303 lpw.pw_gid = -1;
4304 lpw.pw_name = cmd->argv[0];
4305
4306 if ((pw = sql_getpasswd(cmd, &lpw)) &&
4307 !pr_auth_check(cmd->tmp_pool, pw->pw_passwd, cmd->argv[0],
4308 cmd->argv[1])) {
4309 sql_log(DEBUG_FUNC, "%s", "<<< cmd_auth");
4310 session.auth_mech = "mod_sql.c";
4311 return PR_HANDLED(cmd);
4312 }
4313
4314 sql_log(DEBUG_FUNC, "%s", "<<< cmd_auth");
4315 return PR_DECLINED(cmd);
4316 }
4317
4318 MODRET sql_auth_check(cmd_rec *cmd) {
4319 /* Should we bother to see if the hashed password is what we have in the
4320 * database? or do we simply assume it is, and ignore the fact that we're
4321 * being passed the username, too?
4322 */
4323 array_header *ah = cmap.auth_list;
4324 int success = FALSE;
4325 modret_t *mr = NULL;
4326
4327 if (!SQL_USERS ||
4328 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4329 return PR_DECLINED(cmd);
4330 }
4331
4332 sql_log(DEBUG_FUNC, "%s", ">>> cmd_check");
4333
4334 if (cmd->argv[0] == NULL) {
4335 sql_log(DEBUG_AUTH, "%s", "NULL hashed password");
4336
4337 } else if (cmd->argv[1] == NULL) {
4338 sql_log(DEBUG_AUTH, "%s", "NULL user name");
4339
4340 } else if (cmd->argv[2] == NULL) {
4341 sql_log(DEBUG_AUTH, "%s", "NULL clear password");
4342
4343 } else {
4344 register unsigned int i;
4345 char *ciphertext = cmd->argv[0];
4346 char *plaintext = cmd->argv[2];
4347
4348 if (ah == NULL) {
4349 sql_log(DEBUG_AUTH, "%s", "warning: no SQLAuthTypes configured");
4350 }
4351
4352 for (i = 0; ah && i < ah->nelts; i++) {
4353 struct sql_authtype_handler *sah;
4354
4355 sah = ((struct sql_authtype_handler **) ah->elts)[i];
4356 sql_log(DEBUG_AUTH, "checking password using SQLAuthType '%s'",
4357 sah->name);
4358
4359 mr = (sah->cb)(cmd, plaintext, ciphertext);
4360 if (!MODRET_ISERROR(mr)) {
4361 sql_log(DEBUG_AUTH, "'%s' SQLAuthType handler reports success",
4362 sah->name);
4363 success = 1;
4364 break;
4365
4366 } else {
4367 if (MODRET_HASMSG(mr)) {
4368 const char *err_msg;
4369
4370 err_msg = MODRET_ERRMSG(mr);
4371 sql_log(DEBUG_AUTH, "'%s' SQLAuthType handler reports failure: %s",
4372 sah->name, err_msg);
4373
4374 } else {
4375 sql_log(DEBUG_AUTH, "'%s' SQLAuthType handler reports failure",
4376 sah->name);
4377 }
4378 }
4379 }
4380 }
4381
4382 if (success) {
4383 struct passwd lpw;
4384
4385 /* This and the associated hack in sql_uid2name() are to support
4386 * UID reuse in the database -- people (for whatever reason) are
4387 * reusing UIDs/GIDs multiple times, and the displayed owner in a
4388 * LIST or NLST needs to match the current user if possible. This
4389 * depends on the fact that if we get success, the user exists in the
4390 * database (is this always true?).
4391 */
4392
4393 lpw.pw_uid = -1;
4394 lpw.pw_gid = -1;
4395 lpw.pw_name = cmd->argv[1];
4396 cmap.authpasswd = sql_getpasswd(cmd, &lpw);
4397
4398 session.auth_mech = "mod_sql.c";
4399 sql_log(DEBUG_FUNC, "%s", "<<< cmd_check");
4400 return PR_HANDLED(cmd);
4401 }
4402
4403 sql_log(DEBUG_FUNC, "%s", "<<< cmd_check");
4404 return PR_DECLINED(cmd);
4405 }
4406
4407 MODRET sql_auth_uid2name(cmd_rec *cmd) {
4408 char *uid_name = NULL;
4409 struct passwd *pw;
4410 struct passwd lpw;
4411
4412 if (!SQL_USERS ||
4413 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4414 return PR_DECLINED(cmd);
4415 }
4416
4417 sql_log(DEBUG_FUNC, "%s", ">>> cmd_uid2name");
4418
4419 lpw.pw_uid = *((uid_t *) cmd->argv[0]);
4420 lpw.pw_name = NULL;
4421
4422 /* check to see if we're looking up the current user */
4423 if (cmap.authpasswd &&
4424 lpw.pw_uid == cmap.authpasswd->pw_uid) {
4425 sql_log(DEBUG_INFO, "%s", "matched current user");
4426 pw = cmap.authpasswd;
4427
4428 } else {
4429 pw = sql_getpasswd(cmd, &lpw);
4430 }
4431
4432 sql_log(DEBUG_FUNC, "%s", "<<< cmd_uid2name");
4433
4434 if (pw == NULL) {
4435 return PR_DECLINED(cmd);
4436 }
4437
4438 /* In the case of a lookup of a negatively cached UID, the pw_name
4439 * member will be NULL, which causes an undesired handling by
4440 * the core code. Handle this case separately.
4441 */
4442 if (pw->pw_name) {
4443 uid_name = pw->pw_name;
4444
4445 } else {
4446 const char *uidstr = NULL;
4447
4448 uidstr = pr_uid2str(cmd->pool, *((uid_t *) cmd->argv[0]));
4449 uid_name = (char *) uidstr;
4450 }
4451
4452 return mod_create_data(cmd, uid_name);
4453 }
4454
4455 MODRET sql_auth_gid2name(cmd_rec *cmd) {
4456 char *gid_name = NULL;
4457 struct group *gr;
4458 struct group lgr;
4459
4460 if (!SQL_GROUPS ||
4461 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4462 return PR_DECLINED(cmd);
4463 }
4464
4465 sql_log(DEBUG_FUNC, "%s", ">>> cmd_gid2name");
4466
4467 lgr.gr_gid = *((gid_t *) cmd->argv[0]);
4468 lgr.gr_name = NULL;
4469 gr = sql_getgroup(cmd, &lgr);
4470
4471 sql_log(DEBUG_FUNC, "%s", "<<< cmd_gid2name");
4472
4473 if (gr == NULL) {
4474 return PR_DECLINED(cmd);
4475 }
4476
4477 /* In the case of a lookup of a negatively cached GID, the gr_name
4478 * member will be NULL, which causes an undesired handling by
4479 * the core code. Handle this case separately.
4480 */
4481 if (gr->gr_name) {
4482 gid_name = gr->gr_name;
4483
4484 } else {
4485 const char *gidstr = NULL;
4486
4487 gidstr = pr_gid2str(cmd->pool, *((gid_t *) cmd->argv[0]));
4488 gid_name = (char *) gidstr;
4489 }
4490
4491 return mod_create_data(cmd, gid_name);
4492 }
4493
4494 MODRET sql_auth_name2uid(cmd_rec *cmd) {
4495 struct passwd *pw;
4496 struct passwd lpw;
4497
4498 if (!SQL_USERS ||
4499 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4500 return PR_DECLINED(cmd);
4501 }
4502
4503 sql_log(DEBUG_FUNC, "%s", ">>> cmd_name2uid");
4504
4505 lpw.pw_uid = -1;
4506 lpw.pw_gid = -1;
4507 lpw.pw_name = cmd->argv[0];
4508
4509 /* check to see if we're looking up the current user */
4510 if (cmap.authpasswd &&
4511 strcmp(lpw.pw_name, cmap.authpasswd->pw_name) == 0) {
4512 sql_log(DEBUG_INFO, "%s", "matched current user");
4513 pw = cmap.authpasswd;
4514
4515 } else {
4516 pw = sql_getpasswd(cmd, &lpw);
4517 }
4518
4519 if (pw == NULL ||
4520 pw->pw_uid == (uid_t) -1) {
4521 sql_log(DEBUG_FUNC, "%s", "<<< cmd_name2uid");
4522 return PR_DECLINED(cmd);
4523 }
4524
4525 sql_log(DEBUG_FUNC, "%s", "<<< cmd_name2uid");
4526 return mod_create_data(cmd, (void *) &pw->pw_uid);
4527 }
4528
4529 MODRET sql_auth_name2gid(cmd_rec *cmd) {
4530 struct group *gr;
4531 struct group lgr;
4532
4533 if (!SQL_GROUPS ||
4534 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4535 return PR_DECLINED(cmd);
4536 }
4537
4538 sql_log(DEBUG_FUNC, "%s", ">>> cmd_name2gid");
4539
4540 lgr.gr_gid = -1;
4541 lgr.gr_name = cmd->argv[0];
4542 gr = sql_getgroup(cmd, &lgr);
4543
4544 if (gr == NULL ||
4545 gr->gr_gid == (gid_t) -1) {
4546 sql_log(DEBUG_FUNC, "%s", "<<< cmd_name2gid");
4547 return PR_DECLINED(cmd);
4548 }
4549
4550 sql_log(DEBUG_FUNC, "%s", "<<< cmd_name2gid");
4551 return mod_create_data(cmd, (void *) &gr->gr_gid);
4552 }
4553
4554 MODRET sql_auth_getgroups(cmd_rec *cmd) {
4555 int res;
4556 void *val;
4557
4558 if (!SQL_GROUPS ||
4559 !(cmap.engine & SQL_ENGINE_FL_AUTH)) {
4560 return PR_DECLINED(cmd);
4561 }
4562
4563 sql_log(DEBUG_FUNC, "%s", ">>> cmd_getgroups");
4564
4565 res = sql_getgroups(cmd);
4566 if (res < 0) {
4567 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getgroups");
4568 return PR_DECLINED(cmd);
4569 }
4570
4571 val = palloc(cmd->tmp_pool, sizeof(int));
4572 *((int *) val) = res;
4573
4574 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getgroups");
4575 return mod_create_data(cmd, val);
4576 }
4577
4578 /* XXX mod_ratio hacks. */
4579
4580 MODRET sql_getstats(cmd_rec *cmd) {
4581 modret_t *mr;
4582 char *query;
4583 sql_data_t *sd;
4584 char *usrwhere, *where;
4585
4586 sql_log(DEBUG_FUNC, "%s", ">>> cmd_getstats");
4587
4588 if (!cmap.sql_fstor) {
4589 return PR_DECLINED(cmd);
4590 }
4591
4592 usrwhere = pstrcat(cmd->tmp_pool, cmap.usrfield, " = '", _sql_realuser(cmd),
4593 "'", NULL);
4594
4595 where = sql_prepare_where(SQL_PREPARE_WHERE_FL_NO_TAGS, cmd, 2, usrwhere,
4596 sql_prepare_where(0, cmd, 1, cmap.userwhere, NULL), NULL);
4597
4598 query = pstrcat(cmd->tmp_pool, cmap.sql_fstor, ", ",
4599 cmap.sql_fretr, ", ", cmap.sql_bstor, ", ", cmap.sql_bretr, NULL);
4600
4601 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 4, MOD_SQL_DEF_CONN_NAME,
4602 cmap.usrtable, query, where), "sql_select");
4603 if (check_response(mr, 0) < 0) {
4604 return mr;
4605 }
4606
4607 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getstats");
4608
4609 sd = mr->data;
4610
4611 if (sd->rnum == 0) {
4612 return PR_ERROR(cmd);
4613 }
4614
4615 return mod_create_data(cmd, sd->data);
4616 }
4617
4618 MODRET sql_getratio(cmd_rec *cmd) {
4619 modret_t *mr;
4620 char *query;
4621 sql_data_t *sd;
4622 char *usrwhere, *where;
4623
4624 if (!cmap.sql_frate) {
4625 return PR_DECLINED(cmd);
4626 }
4627
4628 sql_log(DEBUG_FUNC, "%s", ">>> cmd_getratio");
4629
4630 usrwhere = pstrcat(cmd->tmp_pool, cmap.usrfield, " = '", _sql_realuser(cmd),
4631 "'", NULL);
4632
4633 where = sql_prepare_where(SQL_PREPARE_WHERE_FL_NO_TAGS, cmd, 2, usrwhere,
4634 sql_prepare_where(0, cmd, 1, cmap.userwhere, NULL), NULL);
4635
4636 query = pstrcat(cmd->tmp_pool, cmap.sql_frate, ", ", cmap.sql_fcred, ", ",
4637 cmap.sql_brate, ", ", cmap.sql_bcred, NULL);
4638
4639 mr = sql_dispatch(sql_make_cmd(cmd->tmp_pool, 4, MOD_SQL_DEF_CONN_NAME,
4640 cmap.usrtable, query, where), "sql_select");
4641 if (check_response(mr, 0) < 0)
4642 return mr;
4643
4644 sql_log(DEBUG_FUNC, "%s", "<<< cmd_getratio");
4645
4646 sd = mr->data;
4647
4648 if (sd->rnum == 0) {
4649 return PR_ERROR(cmd);
4650 }
4651
4652 return mod_create_data(cmd, sd->data);
4653 }
4654
4655 /*****************************************************************
4656 *
4657 * CONFIGURATION DIRECTIVE HANDLERS
4658 *
4659 *****************************************************************/
4660
4661 MODRET set_sqlratiostats(cmd_rec *cmd) {
4662 int b;
4663
4664 CHECK_CONF(cmd, CONF_ROOT | CONF_GLOBAL);
4665
4666 switch (cmd->argc - 1) {
4667 default:
4668 CONF_ERROR(cmd, "requires a Boolean or 4 field names: "
4669 "fstor fretr bstor bretr");
4670 break;
4671
4672 case 1: {
4673 b = get_boolean(cmd, 1);
4674 if (b == -1) {
4675 CONF_ERROR(cmd, "requires a Boolean or 4 field names: "
4676 "fstor fretr bstor bretr");
4677 }
4678
4679 if (b == TRUE) {
4680 add_config_param_str("SQLRatioStats", 4, "fstor", "fretr", "bstor",
4681 "bretr");
4682 }
4683 break;
4684 }
4685
4686 case 4:
4687 add_config_param_str("SQLRatioStats", 4,
4688 (void *) cmd->argv[1], (void *) cmd->argv[2],
4689 (void *) cmd->argv[3], (void *) cmd->argv[4]);
4690 break;
4691 }
4692
4693 return PR_HANDLED(cmd);
4694 }
4695
4696 MODRET set_sqlnegativecache(cmd_rec *cmd) {
4697 int negative_cache = -1;
4698 config_rec *c = NULL;
4699
4700 CHECK_ARGS(cmd, 1);
4701 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
4702
4703 negative_cache = get_boolean(cmd, 1);
4704 if (negative_cache == -1) {
4705 CONF_ERROR(cmd, "expected a Boolean parameter");
4706 }
4707
4708 c = add_config_param(cmd->argv[0], 1, NULL);
4709 c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
4710 *((unsigned char *) c->argv[0]) = negative_cache;
4711
4712 return PR_HANDLED(cmd);
4713 }
4714
4715 /* usage: SQLOptions opt1 [opt2 ...] */
4716 MODRET set_sqloptions(cmd_rec *cmd) {
4717 config_rec *c;
4718 unsigned long opts = 0UL;
4719 register unsigned int i;
4720
4721 if (cmd->argc-1 == 0) {
4722 CONF_ERROR(cmd, "wrong number of parameters");
4723 }
4724
4725 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
4726
4727 c = add_config_param(cmd->argv[0], 1, NULL);
4728
4729 for (i = 1; i < cmd->argc; i++) {
4730 if (strcasecmp(cmd->argv[i], "NoDisconnectOnError") == 0) {
4731 opts |= SQL_OPT_NO_DISCONNECT_ON_ERROR;
4732
4733 } else if (strcasecmp(cmd->argv[i], "UseNormalizedGroupSchema") == 0) {
4734 opts |= SQL_OPT_USE_NORMALIZED_GROUP_SCHEMA;
4735
4736 } else if (strcasecmp(cmd->argv[i], "NoReconnect") == 0) {
4737 opts |= SQL_OPT_NO_RECONNECT;
4738
4739 } else if (strcasecmp(cmd->argv[i], "IgnoreConfigFile") == 0) {
4740 opts |= SQL_OPT_IGNORE_CONFIG_FILE;
4741
4742 } else {
4743 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown SQLOption '",
4744 cmd->argv[i], "'", NULL));
4745 }
4746 }
4747
4748 c->argv[0] = pcalloc(c->pool, sizeof(unsigned long));
4749 *((unsigned long *) c->argv[0]) = opts;
4750
4751 if (pr_module_exists("mod_ifsession.c")) {
4752 /* These are needed in case this directive is used with mod_ifsession
4753 * configuration.
4754 */
4755 c->flags |= CF_MULTI;
4756 }
4757
4758 return PR_HANDLED(cmd);
4759 }
4760
4761 MODRET set_sqlratios(cmd_rec *cmd) {
4762 int b;
4763
4764 CHECK_CONF(cmd, CONF_ROOT | CONF_GLOBAL);
4765
4766 switch (cmd->argc - 1) {
4767 default:
4768 CONF_ERROR(cmd, "requires a Boolean or 4 field names: "
4769 "frate fcred brate bcred");
4770 break;
4771
4772 case 1: {
4773 b = get_boolean(cmd, 1);
4774 if (b == -1) {
4775 CONF_ERROR(cmd, "requires a Boolean or 4 field names: "
4776 "frate fcred brate bcred");
4777 }
4778
4779 if (b == TRUE) {
4780 add_config_param_str("SQLRatios", 4, "frate", "fcred", "brate",
4781 "bcred");
4782 }
4783 break;
4784 }
4785
4786 case 4:
4787 add_config_param_str("SQLRatios", 4,
4788 (void *) cmd->argv[1], (void *) cmd->argv[2],
4789 (void *) cmd->argv[3], (void *) cmd->argv[4]);
4790 break;
4791 }
4792
4793 return PR_HANDLED(cmd);
4794 }
4795
4796 MODRET add_virtualstr(char *name, cmd_rec *cmd) {
4797 CHECK_ARGS(cmd, 1);
4798 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
4799
4800 add_config_param_str(name, 1, (void *) cmd->argv[1]);
4801 return PR_HANDLED(cmd);
4802 }
4803
4804 /* usage: SQLUserInfo table(s) usernamefield passwdfield UID GID homedir
4805 * shell | custom:/<sql-named-query>[/<sql-named-query>[/<sql-named-query>[/<sql-named-query>]]]
4806 */
4807 MODRET set_sqluserinfo(cmd_rec *cmd) {
4808
4809 if (cmd->argc-1 != 1 &&
4810 cmd->argc-1 != 7) {
4811 CONF_ERROR(cmd, "missing parameters");
4812 }
4813
4814 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
4815
4816 if (cmd->argc-1 == 1) {
4817 char *user = NULL, *userbyid = NULL, *userset = NULL, *usersetfast = NULL;
4818 char *param, *ptr = NULL;
4819
4820 /* If only one parameter is used, it must be of the "custom:/" form. */
4821 param = cmd->argv[1];
4822 if (strncmp("custom:/", param, 8) != 0) {
4823 CONF_ERROR(cmd, "badly formatted parameter");
4824 }
4825
4826 ptr = strchr(param + 8, '/');
4827 if (ptr == NULL) {
4828 add_config_param_str("SQLCustomUserInfoByName", 1, param + 8);
4829 return PR_HANDLED(cmd);
4830 }
4831
4832 *ptr = '\0';
4833 user = param + 8;
4834 userbyid = ptr + 1;
4835
4836 add_config_param_str("SQLCustomUserInfoByName", 1, user);
4837
4838 ptr = strchr(userbyid, '/');
4839 if (ptr == NULL) {
4840 add_config_param_str("SQLCustomUserInfoByID", 1, userbyid);
4841 return PR_HANDLED(cmd);
4842 }
4843
4844 *ptr = '\0';
4845 userset = ptr + 1;
4846
4847 add_config_param_str("SQLCustomUserInfoByID", 1, userbyid);
4848
4849 ptr = strchr(userset, '/');
4850 if (ptr == NULL) {
4851 add_config_param_str("SQLCustomUserInfoAllNames", 1, userset);
4852 return PR_HANDLED(cmd);
4853 }
4854
4855 *ptr = '\0';
4856 usersetfast = ptr + 1;
4857
4858 add_config_param_str("SQLCustomUserInfoAllNames", 1, userset);
4859 add_config_param_str("SQLCustomUserInfoAllUsers", 1, usersetfast);
4860 return PR_HANDLED(cmd);
4861 }
4862
4863 /* required to exist - not even going to check them. */
4864 add_config_param_str("SQLUserTable", 1, (void *) cmd->argv[1]);
4865 add_config_param_str("SQLUsernameField", 1, (void *) cmd->argv[2]);
4866 add_config_param_str("SQLPasswordField", 1, (void *) cmd->argv[3]);
4867
4868 /* These could be "NULL" */
4869 if (strncasecmp("null", cmd->argv[4], 5) != 0)
4870 add_config_param_str("SQLUidField", 1, (void *) cmd->argv[4]);
4871
4872 if (strncasecmp("null", cmd->argv[5], 5) != 0)
4873 add_config_param_str("SQLGidField", 1, (void *) cmd->argv[5]);
4874
4875 if (strncasecmp("null", cmd->argv[6], 5) != 0)
4876 add_config_param_str("SQLHomedirField", 1, (void *) cmd->argv[6]);
4877
4878 if (strncasecmp("null", cmd->argv[7], 5) != 0)
4879 add_config_param_str("SQLShellField", 1, (void *) cmd->argv[7]);
4880
4881 return PR_HANDLED(cmd);
4882 }
4883
4884 /* usage: SQLUserPrimaryKey column-name */
4885 MODRET set_sqluserprimarykey(cmd_rec *cmd) {
4886 return add_virtualstr(cmd->argv[0], cmd);
4887 }
4888
4889 MODRET set_sqluserwhereclause(cmd_rec *cmd) {
4890 return add_virtualstr(cmd->argv[0], cmd);
4891 }
4892
4893 /* usage: SQLGroupInfo table(s) groupnamefield gidfield membersfield */
4894 /* usage: SQLGroupInfo table(s) groupnamefield gidfield membersfield |
4895 * custom:/<sql-named-query>/<sql-named-query>/sql-named-query[/<sql-named-query[/<sql-named-query>]]
4896 */
4897 MODRET set_sqlgroupinfo(cmd_rec *cmd) {
4898
4899 if (cmd->argc-1 != 1 &&
4900 cmd->argc-1 != 4) {
4901 CONF_ERROR(cmd, "missing parameters");
4902 }
4903
4904 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
4905
4906 if (cmd->argc-1 == 1) {
4907 char *groupbyname = NULL, *groupbyid = NULL, *groupmembers = NULL,
4908 *groupset = NULL, *groupsetfast = NULL;
4909 char *param, *ptr = NULL;
4910
4911 /* If only one parameter is used, it must be of the "custom:/" form. */
4912 param = cmd->argv[1];
4913 if (strncmp("custom:/", param, 8) != 0) {
4914 CONF_ERROR(cmd, "badly formatted parameter");
4915 }
4916
4917 ptr = strchr(param + 8, '/');
4918 if (ptr == NULL) {
4919 CONF_ERROR(cmd, "badly formatted parameter");
4920 }
4921
4922 *ptr = '\0';
4923 groupbyname = param + 8;
4924 groupbyid = ptr + 1;
4925
4926 add_config_param_str("SQLCustomGroupInfoByName", 1, groupbyname);
4927
4928 ptr = strchr(groupbyid, '/');
4929 if (ptr == NULL) {
4930 CONF_ERROR(cmd, "badly formatted parameter");
4931 }
4932
4933 *ptr = '\0';
4934 groupmembers = ptr + 1;
4935
4936 add_config_param_str("SQLCustomGroupInfoByID", 1, groupbyid);
4937
4938 ptr = strchr(groupmembers, '/');
4939 if (ptr == NULL) {
4940 add_config_param_str("SQLCustomGroupInfoMembers", 1, groupmembers);
4941 return PR_HANDLED(cmd);
4942 }
4943
4944 *ptr = '\0';
4945 groupset = ptr + 1;
4946
4947 add_config_param_str("SQLCustomGroupInfoMembers", 1, groupmembers);
4948
4949 ptr = strchr(groupset, '/');
4950 if (ptr == NULL) {
4951 add_config_param_str("SQLCustomGroupInfoAllNames", 1, groupset);
4952 return PR_HANDLED(cmd);
4953 }
4954
4955 *ptr = '\0';
4956 groupsetfast = ptr + 1;
4957
4958 add_config_param_str("SQLCustomGroupInfoAllNames", 1, groupset);
4959 add_config_param_str("SQLCustomGroupInfoAllGroups", 1, groupsetfast);
4960 return PR_HANDLED(cmd);
4961 }
4962
4963 /* required to exist - not even going to check them. */
4964 add_config_param_str("SQLGroupTable", 1, cmd->argv[1]);
4965 add_config_param_str("SQLGroupnameField", 1, cmd->argv[2]);
4966 add_config_param_str("SQLGroupGIDField", 1, cmd->argv[3]);
4967 add_config_param_str("SQLGroupMembersField", 1, cmd->argv[4]);
4968
4969 return PR_HANDLED(cmd);
4970 }
4971
4972 /* usage: SQLGroupPrimaryKey column-name */
4973 MODRET set_sqlgroupprimarykey(cmd_rec *cmd) {
4974 return add_virtualstr(cmd->argv[0], cmd);
4975 }
4976
4977 MODRET set_sqlgroupwhereclause(cmd_rec *cmd) {
4978 return add_virtualstr(cmd->argv[0], cmd);
4979 }
4980
4981 MODRET set_sqldefaulthomedir(cmd_rec *cmd) {
4982 return add_virtualstr("SQLDefaultHomedir", cmd);
4983 }
4984
4985 /* usage: SQLKeepAlive interval [select-stmt] */
4986 MODRET set_sqlkeepalive(cmd_rec *cmd) {
4987 config_rec *c;
4988 int interval;
4989 const char *stmt;
4990
4991 if (cmd->argc != 2 &&
4992 cmd->argc != 3) {
4993 CONF_ERROR(cmd, "wrong number of parameters");
4994 }
4995
4996 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
4997
4998 interval = atoi(cmd->argv[1]);
4999 if (interval < 0) {
5000 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "interval '", (char *) cmd->argv[1],
5001 "' must be equal to or greater than zero", NULL));
5002 }
5003
5004 /* Default SQL query to use: `SELECT 1` */
5005 stmt = "SELECT 1";
5006 if (cmd->argc == 3) {
5007 stmt = cmd->argv[2];
5008 }
5009
5010 c = add_config_param(cmd->argv[0], 2, NULL, NULL);
5011 c->argv[0] = pcalloc(c->pool, sizeof(int));
5012 *((int *) c->argv[0]) = interval;
5013 c->argv[1] = pstrdup(c->pool, stmt);
5014
5015 return PR_HANDLED(cmd);
5016 }
5017
5018 /* usage: SQLLog cmdlist query-name ["IGNORE_ERRORS"] */
5019 MODRET set_sqllog(cmd_rec *cmd) {
5020 config_rec *c;
5021 char *name, *namep;
5022 char *cmds;
5023 char *iterator;
5024
5025 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5026
5027 if (cmd->argc < 3 ||
5028 cmd->argc > 4) {
5029 CONF_ERROR(cmd, "expected cmdlist query-name [IGNORE_ERRORS]");
5030 }
5031
5032 /* For each element in the command list, add a 'SQLLog_CMD' config_rec..
5033 * this is an optimization that speeds up logging and also simplifies the
5034 * logging code, since there's no need to run through and parse a bunch
5035 * of potenitally unused SQLLog statements each time any command is run.
5036 */
5037
5038 cmds = cmd->argv[1];
5039 iterator = cmds;
5040
5041 for (name = strsep(&iterator, ", "); name; name = strsep(&iterator, ", ")) {
5042 if (*name == '\0') {
5043 continue;
5044 }
5045
5046 for (namep = name; *namep != '\0'; namep++) {
5047 *namep = toupper(*namep);
5048 }
5049
5050 name = pstrcat(cmd->tmp_pool, "SQLLog_", name, NULL);
5051 if (cmd->argc == 4 &&
5052 strcasecmp(cmd->argv[3], "IGNORE_ERRORS") == 0) {
5053 c = add_config_param_str(name, 2, cmd->argv[2], "ignore");
5054
5055 } else {
5056 c = add_config_param_str(name, 1, cmd->argv[2]);
5057 }
5058
5059 if (pr_module_exists("mod_ifsession.c")) {
5060 /* If the mod_ifsession module is in use, then we need to set the
5061 * CF_MULTI flag, so that SQLLog directives that appear in
5062 * mod_ifsession's <IfClass>/<IfGroup>/<IfUser> sections work
5063 * properly.
5064 */
5065 c->flags |= CF_MULTI;
5066 }
5067 }
5068
5069 return PR_HANDLED(cmd);
5070 }
5071
5072 /* usage: SQLLogFile path */
5073 MODRET set_sqllogfile(cmd_rec *cmd) {
5074 CHECK_ARGS(cmd, 1);
5075 CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
5076
5077 add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
5078 return PR_HANDLED(cmd);
5079 }
5080
5081 /* usage: SQLLogOnEvent event query-name ["IGNORE_ERRORS"] */
5082 MODRET set_sqllogonevent(cmd_rec *cmd) {
5083 config_rec *c;
5084 char *event_name, *config_name;
5085
5086 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5087
5088 if (cmd->argc < 3 ||
5089 cmd->argc > 4) {
5090 CONF_ERROR(cmd, "expected event query-name [IGNORE_ERRORS]");
5091 }
5092
5093 /* Provide convenience aliases, falling back to "raw" event name. */
5094 if (strcasecmp(cmd->argv[1], "MaxClientsPerClass") == 0) {
5095 event_name = "mod_auth.max-clients-per-class";
5096
5097 } else if (strcasecmp(cmd->argv[1], "MaxClientsPerHost") == 0) {
5098 event_name = "mod_auth.max-clients-per-host";
5099
5100 } else if (strcasecmp(cmd->argv[1], "MaxClientsPerUser") == 0) {
5101 event_name = "mod_auth.max-clients-per-user";
5102
5103 } else if (strcasecmp(cmd->argv[1], "MaxCommandRate") == 0) {
5104 event_name = "core.max-command-rate";
5105
5106 } else if (strcasecmp(cmd->argv[1], "MaxConnectionsPerHost") == 0) {
5107 event_name = "mod_auth.max-connections-per-host";
5108
5109 } else if (strcasecmp(cmd->argv[1], "MaxHostsPerUser") == 0) {
5110 event_name = "mod_auth.max-hosts-per-user";
5111
5112 } else if (strcasecmp(cmd->argv[1], "MaxLoginAttempts") == 0) {
5113 event_name = "mod_auth.max-login-attempts";
5114
5115 } else if (strcasecmp(cmd->argv[1], "RootLogin") == 0) {
5116 event_name = "mod_auth.root-login";
5117
5118 } else if (strcasecmp(cmd->argv[1], "TimeoutIdle") == 0) {
5119 event_name = "core.timeout-idle";
5120
5121 } else if (strcasecmp(cmd->argv[1], "TimeoutLogin") == 0) {
5122 event_name = "core.timeout-login";
5123
5124 } else if (strcasecmp(cmd->argv[1], "TimeoutNoTransfer") == 0) {
5125 event_name = "core.timeout-no-transfer";
5126
5127 } else if (strcasecmp(cmd->argv[1], "TimeoutStalled") == 0) {
5128 event_name = "core.timeout-stalled";
5129
5130 } else if (strcasecmp(cmd->argv[1], "UserBanned") == 0) {
5131 event_name = "mod_ban.ban-user";
5132
5133 } else if (strcasecmp(cmd->argv[1], "HostBanned") == 0) {
5134 event_name = "mod_ban.ban-host";
5135
5136 } else if (strcasecmp(cmd->argv[1], "ClassBanned") == 0) {
5137 event_name = "mod_ban.ban-class";
5138
5139 } else {
5140 event_name = cmd->argv[1];
5141 }
5142
5143 /* Add a 'SQLLog_Event_<event>' config_rec. This is an optimization that
5144 * speeds up logging and also simplifies the logging code.
5145 */
5146 config_name = pstrcat(cmd->tmp_pool, "SQLLog_Event_", event_name, NULL);
5147 if (cmd->argc == 4 &&
5148 strcasecmp(cmd->argv[3], "IGNORE_ERRORS") == 0) {
5149 c = add_config_param_str(config_name, 3, cmd->argv[2], event_name,
5150 "ignore");
5151
5152 } else {
5153 c = add_config_param_str(config_name, 2, cmd->argv[2], event_name);
5154 }
5155
5156 if (pr_module_exists("mod_ifsession.c")) {
5157 /* If the mod_ifsession module is in use, then we need to set the
5158 * CF_MULTI flag, so that SQLLogOnEvent directives that appear in
5159 * mod_ifsession's <IfClass>/<IfGroup>/<IfUser> sections work
5160 * properly.
5161 */
5162 c->flags |= CF_MULTI;
5163 }
5164
5165 /* In addition, we also need to set a SQLLogOnEvent config_rec, for
5166 * lookup in sess_init(), so that we know to which events to subscribe.
5167 */
5168 add_config_param_str(cmd->argv[0], 1, event_name);
5169
5170 return PR_HANDLED(cmd);
5171 }
5172
5173 /* usage: SQLNamedConnectInfo name backend info [user [pass [ttl]]]
5174 * [ssl-cert:<path>] [ssl-key:<path>] [ssl-ca:/path] [ssl-ciphers:str]
5175 */
5176 MODRET set_sqlnamedconnectinfo(cmd_rec *cmd) {
5177 register unsigned int i;
5178 int argc = 0;
5179 char *conn_name = NULL;
5180 char *backend = NULL;
5181 char **argv = NULL, *info = NULL, *user = "", *pass = "", *ttl = NULL;
5182 char *ssl_cert_file = NULL, *ssl_key_file = NULL, *ssl_ca_file = NULL;
5183 char *ssl_ca_dir = NULL, *ssl_ciphers = NULL;
5184 struct sql_backend *sb;
5185 array_header *params;
5186
5187 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5188
5189 if (cmd->argc-1 < 3 ||
5190 cmd->argc-1 > 10) {
5191 CONF_ERROR(cmd, "requires 3 to 10 parameters; check the mod_sql docs");
5192 }
5193
5194 /* First, deal with any required parameters. */
5195 conn_name = cmd->argv[1];
5196
5197 backend = cmd->argv[2];
5198 sb = sql_get_backend(backend);
5199 if (sb == NULL) {
5200 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": SQLBackend '", backend,
5201 "' not supported", NULL));
5202 }
5203
5204 /* Next, search for/process any optional named parameters. */
5205 params = make_array(cmd->tmp_pool, 0, sizeof(char *));
5206
5207 for (i = 3; i < cmd->argc; i++) {
5208 if (strncmp(cmd->argv[i], "ssl-cert:", 9) == 0) {
5209 char *path;
5210
5211 path = cmd->argv[i];
5212
5213 /* Advance past the "ssl-cert:" prefix. */
5214 path += 9;
5215
5216 /* Check the file exists! */
5217 if (file_exists2(cmd->tmp_pool, path) == TRUE) {
5218 ssl_cert_file = path;
5219
5220 } else {
5221 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_VERSION
5222 ": %s: SSL certificate '%s': %s", (char *) cmd->argv[0], path,
5223 strerror(ENOENT));
5224 }
5225
5226 } else if (strncmp(cmd->argv[i], "ssl-key:", 8) == 0) {
5227 char *path;
5228
5229 path = cmd->argv[i];
5230
5231 /* Advance past the "ssl-key:" prefix. */
5232 path += 8;
5233
5234 /* Check the file exists! */
5235 if (file_exists2(cmd->tmp_pool, path) == TRUE) {
5236 ssl_key_file = path;
5237
5238 } else {
5239 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_VERSION
5240 ": %s: SSL certificate key '%s': %s", (char *) cmd->argv[0], path,
5241 strerror(ENOENT));
5242 }
5243
5244 } else if (strncmp(cmd->argv[i], "ssl-ca:", 7) == 0) {
5245 char *path;
5246
5247 path = cmd->argv[i];
5248
5249 /* Advance past the "ssl-ca:" prefix. */
5250 path += 7;
5251
5252 /* Check the file exists! */
5253 if (file_exists2(cmd->tmp_pool, path) == TRUE) {
5254 ssl_ca_file = path;
5255
5256 } else if (dir_exists2(cmd->tmp_pool, path) == TRUE) {
5257 ssl_ca_dir = path;
5258
5259 } else {
5260 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_VERSION
5261 ": %s: SSL CA '%s': %s", (char *) cmd->argv[0], path,
5262 strerror(ENOENT));
5263 }
5264
5265 } else if (strncmp(cmd->argv[i], "ssl-ciphers:", 12) == 0) {
5266 char *ciphers;
5267
5268 ciphers = cmd->argv[i];
5269
5270 /* Advance past the "ssl-ciphers:" prefix. */
5271 ciphers += 12;
5272
5273 ssl_ciphers = ciphers;
5274
5275 } else {
5276 *((char **) push_array(params)) = cmd->argv[i];
5277 }
5278 }
5279
5280 /* Last, handle any optional positional parameters. */
5281
5282 argc = params->nelts;
5283 argv = params->elts;
5284
5285 if (argc >= 1) {
5286 info = argv[0];
5287 }
5288
5289 if (argc >= 2) {
5290 user = argv[1];
5291 }
5292
5293 if (argc >= 3) {
5294 pass = argv[2];
5295 }
5296
5297 /* Note: The only connection policy which is honored for NamedConnInfos
5298 * is the TTL policy, i.e. for setting a timer on this connect. Other
5299 * policies are only honored if set on the default connection via
5300 * SQLConnectInfo.
5301 */
5302
5303 if (argc >= 4) {
5304 ttl = argv[3];
5305
5306 } else {
5307 ttl = "0";
5308 }
5309
5310 (void) add_config_param_str(cmd->argv[0], 11, conn_name, backend, info, user,
5311 pass, ttl, ssl_cert_file, ssl_key_file, ssl_ca_file, ssl_ca_dir,
5312 ssl_ciphers);
5313 return PR_HANDLED(cmd);
5314 }
5315
5316 /* Parse the provided SQL statement for any LogFormat variables; the output
5317 * as a parsed buffer which will be resolved at runtime.
5318 */
5319 static int parse_named_query(pool *p, const char *stmt_text,
5320 unsigned char *stmt_buf, size_t stmt_bufsz, size_t *stmt_buflen,
5321 int flags) {
5322 int res;
5323 pool *tmp_pool;
5324 pr_jot_ctx_t *jot_ctx;
5325 pr_jot_parsed_t *jot_parsed;
5326
5327 tmp_pool = make_sub_pool(p);
5328 jot_ctx = pcalloc(tmp_pool, sizeof(pr_jot_ctx_t));
5329 jot_parsed = pcalloc(tmp_pool, sizeof(pr_jot_parsed_t));
5330 jot_parsed->bufsz = jot_parsed->buflen = stmt_bufsz;
5331 jot_parsed->ptr = jot_parsed->buf = stmt_buf;
5332
5333 jot_ctx->log = jot_parsed;
5334
5335 res = pr_jot_parse_logfmt(tmp_pool, stmt_text, jot_ctx, pr_jot_parse_on_meta,
5336 pr_jot_parse_on_unknown, pr_jot_parse_on_other, flags);
5337 if (res < 0) {
5338 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_VERSION
5339 ": error parsing SQLNamedQuery '%s': %s", stmt_text, strerror(errno));
5340 }
5341
5342 *stmt_buflen = jot_parsed->bufsz - jot_parsed->buflen;
5343 stmt_buf[*stmt_buflen] = '\0';
5344
5345 destroy_pool(tmp_pool);
5346 return res;
5347 }
5348
5349 /* usage: SQLNamedQuery name type query-string [table-name] [conn-name] */
5350 MODRET set_sqlnamedquery(cmd_rec *cmd) {
5351 int res;
5352 config_rec *c = NULL;
5353 char *name = NULL;
5354 unsigned char stmt_buf[4096];
5355 size_t stmt_buflen;
5356
5357 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5358
5359 if (cmd->argc < 4) {
5360 CONF_ERROR(cmd, "requires at least 3 parameters");
5361 }
5362
5363 res = parse_named_query(cmd->tmp_pool, cmd->argv[3], stmt_buf,
5364 sizeof(stmt_buf)-1, &stmt_buflen, PR_JOT_LOGFMT_PARSE_FL_UNKNOWN_AS_CUSTOM);
5365 if (res < 0) {
5366 CONF_ERROR(cmd, "syntax error in query");
5367 }
5368
5369 name = pstrcat(cmd->tmp_pool, "SQLNamedQuery_", cmd->argv[1], NULL);
5370
5371 if (strcasecmp(cmd->argv[2], "SELECT") == 0) {
5372 char *conn_name;
5373
5374 conn_name = MOD_SQL_DEF_CONN_NAME;
5375 if (cmd->argc == 5) {
5376 conn_name = cmd->argv[4];
5377 }
5378
5379 c = add_config_param_str(name, 3, SQL_SELECT_C, stmt_buf, conn_name);
5380
5381 } else if (strcasecmp(cmd->argv[2], "FREEFORM") == 0) {
5382 char *conn_name;
5383
5384 conn_name = MOD_SQL_DEF_CONN_NAME;
5385 if (cmd->argc == 5) {
5386 conn_name = cmd->argv[4];
5387 }
5388
5389 c = add_config_param_str(name, 3, SQL_FREEFORM_C, stmt_buf, conn_name);
5390
5391 } else if (strcasecmp(cmd->argv[2], "INSERT") == 0) {
5392 char *conn_name;
5393
5394 if (cmd->argc < 5) {
5395 CONF_ERROR(cmd, "expected 'INSERT' query-string table-name");
5396 }
5397
5398 conn_name = MOD_SQL_DEF_CONN_NAME;
5399 if (cmd->argc == 6) {
5400 conn_name = cmd->argv[5];
5401 }
5402
5403 c = add_config_param_str(name, 4, SQL_INSERT_C, stmt_buf, cmd->argv[4],
5404 conn_name);
5405
5406 } else if (strcasecmp(cmd->argv[2], "UPDATE") == 0) {
5407 char *conn_name;
5408
5409 if (cmd->argc < 5) {
5410 CONF_ERROR(cmd, "expected 'UPDATE' query-string table-name");
5411 }
5412
5413 conn_name = MOD_SQL_DEF_CONN_NAME;
5414 if (cmd->argc == 6) {
5415 conn_name = cmd->argv[5];
5416 }
5417
5418 c = add_config_param_str(name, 4, SQL_UPDATE_C, stmt_buf, cmd->argv[4],
5419 conn_name);
5420
5421 } else {
5422 CONF_ERROR(cmd, "type must be SELECT, INSERT, UPDATE, or FREEFORM");
5423 }
5424
5425 if (c != NULL) {
5426 c->flags |= CF_MULTI;
5427 }
5428
5429 return PR_HANDLED(cmd);
5430 }
5431
5432 /* usage: SQLShowInfo cmdlist numeric format-string */
5433 MODRET set_sqlshowinfo(cmd_rec *cmd) {
5434 int res;
5435 config_rec *c = NULL;
5436 char *cmds = NULL, *iterator = NULL, *name = NULL;
5437 unsigned char stmt_buf[4096];
5438 size_t stmt_buflen;
5439
5440 CHECK_ARGS(cmd, 3);
5441 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5442
5443 res = parse_named_query(cmd->tmp_pool, cmd->argv[3], stmt_buf,
5444 sizeof(stmt_buf)-1, &stmt_buflen, PR_JOT_LOGFMT_PARSE_FL_UNKNOWN_AS_CUSTOM);
5445 if (res < 0) {
5446 CONF_ERROR(cmd, "syntax error in query");
5447 }
5448
5449 cmds = pstrdup(cmd->tmp_pool, cmd->argv[1]);
5450 iterator = cmds;
5451
5452 for (name = strsep(&iterator, ", "); name; name = strsep(&iterator, ", ")) {
5453 char *ptr = NULL;
5454
5455 if (*name == '\0') {
5456 continue;
5457 }
5458
5459 for (ptr = name; *ptr != '\0'; ptr++) {
5460 *ptr = toupper(*ptr);
5461 }
5462
5463 name = pstrcat(cmd->tmp_pool, "SQLShowInfo_", name, NULL);
5464
5465 c = add_config_param_str(name, 2, cmd->argv[2], stmt_buf);
5466
5467 if (pr_module_exists("mod_ifsession.c")) {
5468 /* If the mod_ifsession module is in use, then we need to set the
5469 * CF_MULTI flag, so that SQLShowInfo directives that appear in
5470 * mod_ifsession's <IfClass>/<IfGroup>/<IfUser> sections work
5471 * properly.
5472 */
5473 c->flags |= CF_MULTI;
5474 }
5475 }
5476
5477 return PR_HANDLED(cmd);
5478 }
5479
5480 MODRET set_sqlauthenticate(cmd_rec *cmd) {
5481 config_rec *c = NULL;
5482 char *arg = NULL;
5483 int authmask = 0;
5484 unsigned long cnt = 0;
5485 int groupset_flag, userset_flag, groups_flag, users_flag;
5486
5487 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5488
5489 if (cmd->argc < 2 ||
5490 cmd->argc > 5) {
5491 CONF_ERROR(cmd, "requires 1 to 4 parameters; check the mod_sql docs");
5492 }
5493
5494 groupset_flag = userset_flag = groups_flag = users_flag = FALSE;
5495
5496 /* We're setting our authmask here -- we have a bunch of checks needed to
5497 * make sure users aren't trying to screw around with us.
5498 */
5499
5500 if (cmd->argc == 2 &&
5501 strcasecmp(cmd->argv[1], "on") == 0) {
5502 authmask = SQL_AUTH_GROUPSET|SQL_AUTH_USERSET|SQL_AUTH_USERS|
5503 SQL_AUTH_GROUPS;
5504
5505 } else if (!((cmd->argc == 2) && !strcasecmp(cmd->argv[1], "off"))) {
5506 for (cnt = 1; cnt < cmd->argc; cnt++) {
5507 arg = cmd->argv[cnt];
5508
5509 if (strncasecmp("groupset", arg, 8) == 0) {
5510 if (groupset_flag) {
5511 CONF_ERROR(cmd, "groupset already set");
5512 }
5513
5514 if (strcasecmp("groupsetfast", arg) == 0) {
5515 authmask |= SQL_FAST_GROUPSET;
5516
5517 } else if (strlen(arg) > 8) {
5518 CONF_ERROR(cmd, "unknown argument");
5519 }
5520
5521 authmask |= SQL_AUTH_GROUPSET;
5522 groupset_flag = TRUE;
5523
5524 } else if (strncasecmp("userset", arg, 7) == 0) {
5525 if (userset_flag) {
5526 CONF_ERROR(cmd, "userset already set");
5527 }
5528
5529 if (strcasecmp("usersetfast", arg) == 0) {
5530 authmask |= SQL_FAST_USERSET;
5531
5532 } else if (strlen(arg) > 7) {
5533 CONF_ERROR(cmd, "unknown argument");
5534 }
5535
5536 authmask |= SQL_AUTH_USERSET;
5537 userset_flag = TRUE;
5538
5539 } else if (strncasecmp("groups", arg, 6) == 0) {
5540 if (groups_flag) {
5541 CONF_ERROR(cmd, "groups already set");
5542 }
5543
5544 if (strcasecmp("groups*", arg) == 0) {
5545 pr_log_debug(DEBUG1,
5546 "%s: use of '*' in SQLAuthenticate has been deprecated. "
5547 "Use AuthOrder for setting authoritativeness",
5548 (char *) cmd->argv[0]);
5549
5550 } else if (strlen(arg) > 6) {
5551 CONF_ERROR(cmd, "unknown argument");
5552 }
5553
5554 authmask |= SQL_AUTH_GROUPS;
5555 groups_flag = TRUE;
5556
5557 } else if (strncasecmp("users", arg, 5) == 0) {
5558 if (users_flag) {
5559 CONF_ERROR(cmd, "users already set");
5560 }
5561
5562 if (strcasecmp("users*", arg) == 0) {
5563 pr_log_debug(DEBUG1,
5564 "%s: use of '*' in SQLAuthenticate has been deprecated. "
5565 "Use AuthOrder for setting authoritativeness",
5566 (char *) cmd->argv[0]);
5567
5568 } else if (strlen(arg) > 5) {
5569 CONF_ERROR(cmd, "unknown argument");
5570 }
5571
5572 authmask |= SQL_AUTH_USERS;
5573 users_flag = TRUE;
5574
5575 } else {
5576 CONF_ERROR(cmd, "unknown argument");
5577 }
5578 }
5579 }
5580
5581 /* Finally, fixup if we've received groupset with no groups,
5582 * or userset with no users
5583 */
5584 if ((groupset_flag && !groups_flag) ||
5585 (userset_flag && !users_flag)) {
5586 CONF_ERROR(cmd, "groupset and userset have no meaning without "
5587 "a corresponding groups or users argument.");
5588 }
5589
5590 c = add_config_param(cmd->argv[0], 1, NULL);
5591 c->argv[0] = pcalloc(c->pool, sizeof(int));
5592 *((int *) c->argv[0]) = authmask;
5593
5594 return PR_HANDLED(cmd);
5595 }
5596
5597 /* logging stuff */
5598
5599 static char *sql_logfile = NULL;
5600 static int sql_logfd = -1;
5601
5602 static int sql_closelog(void) {
5603
5604 /* sanity check */
5605 if (sql_logfd >= 0) {
5606 (void) close(sql_logfd);
5607 }
5608
5609 sql_logfd = -1;
5610 sql_logfile = NULL;
5611
5612 return 0;
5613 }
5614
5615 int sql_log(int level, const char *fmt, ...) {
5616 va_list msg;
5617 int res;
5618
5619 /* sanity check */
5620 if (!sql_logfile)
5621 return 0;
5622
5623 va_start(msg, fmt);
5624 res = pr_log_vwritefile(sql_logfd, MOD_SQL_VERSION, fmt, msg);
5625 va_end(msg);
5626
5627 return res;
5628 }
5629
5630 static int sql_openlog(void) {
5631 int res = 0, xerrno = 0;
5632
5633 /* Sanity checks */
5634 sql_logfile = get_param_ptr(main_server->conf, "SQLLogFile", FALSE);
5635 if (sql_logfile == NULL)
5636 return 0;
5637
5638 if (strcasecmp(sql_logfile, "none") == 0) {
5639 sql_logfile = NULL;
5640 return 0;
5641 }
5642
5643 pr_signals_block();
5644 PRIVS_ROOT
5645 res = pr_log_openfile(sql_logfile, &sql_logfd, PR_LOG_SYSTEM_MODE);
5646 xerrno = errno;
5647 PRIVS_RELINQUISH
5648 pr_signals_unblock();
5649
5650 errno = xerrno;
5651 return res;
5652 }
5653
5654 /* usage: SQLConnectInfo info [user [pass [policy]]]
5655 * [ssl-cert:<path>] [ssl-key:<path>] [ssl-ca:/path] [ssl-ciphers:str]
5656 */
5657 MODRET set_sqlconnectinfo(cmd_rec *cmd) {
5658 register unsigned int i;
5659 int argc = 0;
5660 char **argv = NULL, *info = NULL, *user = "", *pass = "", *ttl = NULL;
5661 char *ssl_cert_file = NULL, *ssl_key_file = NULL, *ssl_ca_file = NULL;
5662 char *ssl_ca_dir = NULL, *ssl_ciphers = NULL;
5663 array_header *params;
5664
5665 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5666
5667 if (cmd->argc < 2 ||
5668 cmd->argc > 9) {
5669 CONF_ERROR(cmd, "requires 1 to 8 parameters; check the mod_sql docs");
5670 }
5671
5672 /* First, deal with any required parameters. */
5673 info = cmd->argv[1];
5674
5675 /* Next, search for/process any optional named parameters. */
5676 params = make_array(cmd->tmp_pool, 0, sizeof(char *));
5677
5678 for (i = 2; i < cmd->argc; i++) {
5679 if (strncmp(cmd->argv[i], "ssl-cert:", 9) == 0) {
5680 char *path;
5681
5682 path = cmd->argv[i];
5683
5684 /* Advance past the "ssl-cert:" prefix. */
5685 path += 9;
5686
5687 /* Check the file exists! */
5688 if (file_exists2(cmd->tmp_pool, path) == TRUE) {
5689 ssl_cert_file = path;
5690
5691 } else {
5692 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_VERSION
5693 ": %s: SSL certificate '%s': %s", (char *) cmd->argv[0], path,
5694 strerror(ENOENT));
5695 }
5696
5697 } else if (strncmp(cmd->argv[i], "ssl-key:", 8) == 0) {
5698 char *path;
5699
5700 path = cmd->argv[i];
5701
5702 /* Advance past the "ssl-key:" prefix. */
5703 path += 8;
5704
5705 /* Check the file exists! */
5706 if (file_exists2(cmd->tmp_pool, path) == TRUE) {
5707 ssl_key_file = path;
5708
5709 } else {
5710 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_VERSION
5711 ": %s: SSL certificate key '%s': %s", (char *) cmd->argv[0], path,
5712 strerror(ENOENT));
5713 }
5714
5715 } else if (strncmp(cmd->argv[i], "ssl-ca:", 7) == 0) {
5716 char *path;
5717
5718 path = cmd->argv[i];
5719
5720 /* Advance past the "ssl-ca:" prefix. */
5721 path += 7;
5722
5723 /* Check the file exists! */
5724 if (file_exists2(cmd->tmp_pool, path) == TRUE) {
5725 ssl_ca_file = path;
5726
5727 } else if (dir_exists2(cmd->tmp_pool, path) == TRUE) {
5728 ssl_ca_dir = path;
5729
5730 } else {
5731 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_VERSION
5732 ": %s: SSL CA '%s': %s", (char *) cmd->argv[0], path,
5733 strerror(ENOENT));
5734 }
5735
5736 } else if (strncmp(cmd->argv[i], "ssl-ciphers:", 12) == 0) {
5737 char *ciphers;
5738
5739 ciphers = cmd->argv[i];
5740
5741 /* Advance past the "ssl-ciphers:" prefix. */
5742 ciphers += 12;
5743
5744 ssl_ciphers = ciphers;
5745
5746 } else {
5747 *((char **) push_array(params)) = cmd->argv[i];
5748 }
5749 }
5750
5751 /* Last, handle any optional positional parameters. */
5752
5753 argc = params->nelts;
5754 argv = params->elts;
5755
5756 if (argc >= 1) {
5757 user = argv[0];
5758 }
5759
5760 if (argc >= 2) {
5761 pass = argv[1];
5762 }
5763
5764 if (argc >= 3) {
5765 ttl = argv[2];
5766
5767 } else {
5768 ttl = "0";
5769 }
5770
5771 (void) add_config_param_str(cmd->argv[0], 9, info, user, pass, ttl,
5772 ssl_cert_file, ssl_key_file, ssl_ca_file, ssl_ca_dir, ssl_ciphers);
5773 return PR_HANDLED(cmd);
5774 }
5775
5776 /* usage: SQLEngine on|off|auth|log */
5777 MODRET set_sqlengine(cmd_rec *cmd) {
5778 config_rec *c;
5779 int engine = -1;
5780
5781 CHECK_ARGS(cmd, 1);
5782 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL|CONF_ANON);
5783
5784 engine = get_boolean(cmd, 1);
5785 if (engine == -1) {
5786 /* The parameter is not a boolean; check for "auth" or "log". */
5787 if (strcasecmp(cmd->argv[1], "auth") == 0) {
5788 engine = SQL_ENGINE_FL_AUTH;
5789
5790 } else if (strcasecmp(cmd->argv[1], "log") == 0) {
5791 engine = SQL_ENGINE_FL_LOG;
5792
5793 } else {
5794 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown SQLEngine parameter '",
5795 cmd->argv[1], "'", NULL));
5796 }
5797
5798 } else {
5799 if (engine == 1) {
5800 /* Convert an "on" into a auth|log combination. */
5801 engine = SQL_ENGINE_FL_AUTH|SQL_ENGINE_FL_LOG;
5802 }
5803 }
5804
5805 c = add_config_param(cmd->argv[0], 1, NULL);
5806 c->argv[0] = pcalloc(c->pool, sizeof(int));
5807 *((int *) c->argv[0]) = engine;
5808 c->flags |= CF_MERGEDOWN;
5809
5810 return PR_HANDLED(cmd);
5811 }
5812
5813 MODRET set_sqlauthtypes(cmd_rec *cmd) {
5814 array_header *auth_list;
5815 register unsigned int i;
5816
5817 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5818
5819 /* Need *at least* one handler. */
5820 if (cmd->argc < 2) {
5821 CONF_ERROR(cmd, "expected at least one SQLAuthType");
5822 }
5823
5824 auth_list = make_array(permanent_pool, cmd->argc-1,
5825 sizeof(struct sql_authtype_handler *));
5826
5827 /* Walk through our cmd->argv. */
5828 for (i = 1; i < cmd->argc; i++) {
5829 struct sql_authtype_handler *sah;
5830
5831 sah = sql_get_authtype(cmd->argv[i]);
5832 if (sah == NULL) {
5833 sql_log(DEBUG_WARN, "unknown SQLAuthType '%s'", (char *) cmd->argv[i]);
5834 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown SQLAuthType '",
5835 cmd->argv[i], "'", NULL));
5836 }
5837
5838 if (strcasecmp(sah->name, "Plaintext") == 0) {
5839 pr_log_pri(PR_LOG_WARNING, MOD_SQL_VERSION
5840 ": WARNING: Use of Plaintext SQLAuthType is insecure, as it allows "
5841 "storage of passwords IN THE CLEAR in your database tables!");
5842 }
5843
5844 *((struct sql_authtype_handler **) push_array(auth_list)) = sah;
5845 }
5846
5847 (void) add_config_param(cmd->argv[0], 1, auth_list);
5848 return PR_HANDLED(cmd);
5849 }
5850
5851 /* usage: SQLBackend name */
5852 MODRET set_sqlbackend(cmd_rec *cmd) {
5853 CHECK_ARGS(cmd, 1);
5854 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5855
5856 add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
5857 return PR_HANDLED(cmd);
5858 }
5859
5860 MODRET set_sqlminid(cmd_rec *cmd) {
5861 config_rec *c;
5862 uid_t uid;
5863 gid_t gid;
5864
5865 CHECK_ARGS(cmd, 1);
5866 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5867
5868 if (pr_str2uid(cmd->argv[1], &uid) < 0) {
5869 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "invalid UID value '",
5870 cmd->argv[1], "'", NULL));
5871 }
5872
5873 if (pr_str2gid(cmd->argv[1], &gid) < 0) {
5874 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "invalid GID value '",
5875 cmd->argv[1], "'", NULL));
5876 }
5877
5878 c = add_config_param(cmd->argv[0], 2, NULL, NULL);
5879 c->argv[0] = pcalloc(c->pool, sizeof(uid_t));
5880 *((uid_t *) c->argv[0]) = uid;
5881 c->argv[1] = pcalloc(c->pool, sizeof(gid_t));
5882 *((gid_t *) c->argv[1]) = gid;
5883
5884 return PR_HANDLED(cmd);
5885 }
5886
5887 MODRET set_sqlminuseruid(cmd_rec *cmd) {
5888 config_rec *c = NULL;
5889 uid_t uid;
5890
5891 CHECK_ARGS(cmd, 1);
5892 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5893
5894 if (pr_str2uid(cmd->argv[1], &uid) < 0) {
5895 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "invalid UID value '",
5896 cmd->argv[1], "'", NULL));
5897 }
5898
5899 c = add_config_param(cmd->argv[0], 1, NULL);
5900 c->argv[0] = pcalloc(c->pool, sizeof(uid_t));
5901 *((uid_t *) c->argv[0]) = uid;
5902
5903 return PR_HANDLED(cmd);
5904 }
5905
5906 MODRET set_sqlminusergid(cmd_rec *cmd) {
5907 config_rec *c = NULL;
5908 gid_t gid;
5909
5910 CHECK_ARGS(cmd, 1);
5911 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5912
5913 if (pr_str2gid(cmd->argv[1], &gid) < 0) {
5914 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "invalid GID value '",
5915 cmd->argv[1], "'", NULL));
5916 }
5917
5918 c = add_config_param(cmd->argv[0], 1, NULL);
5919 c->argv[0] = pcalloc(c->pool, sizeof(gid_t));
5920 *((gid_t *) c->argv[0]) = gid;
5921
5922 return PR_HANDLED(cmd);
5923 }
5924
5925 MODRET set_sqldefaultuid(cmd_rec *cmd) {
5926 config_rec *c;
5927 uid_t uid;
5928
5929 CHECK_ARGS(cmd, 1);
5930 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5931
5932 if (pr_str2uid(cmd->argv[1], &uid) < 0) {
5933 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "invalid UID value '",
5934 cmd->argv[1], "'", NULL));
5935 }
5936
5937 c = add_config_param(cmd->argv[0], 1, NULL);
5938 c->argv[0] = pcalloc(c->pool, sizeof(uid_t));
5939 *((uid_t *) c->argv[0]) = uid;
5940
5941 return PR_HANDLED(cmd);
5942 }
5943
5944 MODRET set_sqldefaultgid(cmd_rec *cmd) {
5945 config_rec *c;
5946 gid_t gid;
5947
5948 CHECK_ARGS(cmd, 1);
5949 CHECK_CONF(cmd, CONF_ROOT|CONF_GLOBAL|CONF_VIRTUAL);
5950
5951 if (pr_str2gid(cmd->argv[1], &gid) < 0) {
5952 CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "invalid GID value '",
5953 cmd->argv[1], "'", NULL));
5954 }
5955
5956 c = add_config_param(cmd->argv[0], 1, NULL);
5957 c->argv[0] = pcalloc(c->pool, sizeof(gid_t));
5958 *((gid_t *) c->argv[0]) = gid;
5959
5960 return PR_HANDLED(cmd);
5961 }
5962
5963 /* Event handlers
5964 */
5965
5966 static void sql_chroot_ev(const void *event_data, void *user_data) {
5967 /* Loop through our list of named connections, making sure that any
5968 * with a connection policy of PERSESSION are opened.
5969 */
5970 if (sql_named_conns != NULL) {
5971 pool *tmp_pool;
5972 struct sql_named_conn *snc;
5973
5974 cmdtable *curr_cmdtable = NULL;
5975
5976 /* Stash a pointer to the cmdtable of the current backend module, to
5977 * be restored afterward (Issue #1659).
5978 */
5979 curr_cmdtable = sql_cmdtable;
5980
5981 tmp_pool = make_sub_pool(session.pool);
5982
5983 for (snc = sql_named_conns; snc; snc = snc->next) {
5984 pr_signals_handle();
5985
5986 sql_log(DEBUG_FUNC,
5987 "ensuring presence of SQLNamedConnectInfo '%s' for SQLBackend '%s'",
5988 snc->conn_name, snc->backend);
5989 if (snc->conn_policy == SQL_CONN_POLICY_PERSESSION) {
5990 cmd_rec *cmd;
5991 modret_t *mr;
5992
5993 sql_set_backend(snc->backend);
5994 cmd = sql_make_cmd(tmp_pool, 1, snc->conn_name);
5995 mr = sql_dispatch(cmd, "sql_open");
5996 (void) check_response(mr, 0);
5997 SQL_FREE_CMD(cmd);
5998 }
5999 }
6000
6001 destroy_pool(tmp_pool);
6002
6003 /* Restore the previous cmdtable (Issue #1659). */
6004 sql_cmdtable = curr_cmdtable;
6005 }
6006 }
6007
6008 static void sql_exit_ev(const void *event_data, void *user_data) {
6009 config_rec *c;
6010 cmd_rec *cmd;
6011 modret_t *mr;
6012 struct sql_backend *sb;
6013
6014 if (cmap.engine == 0) {
6015 return;
6016 }
6017
6018 /* handle EXIT queries */
6019 c = find_config(main_server->conf, CONF_PARAM, "SQLLog_EXIT", FALSE);
6020 while (c != NULL) {
6021 pr_signals_handle();
6022
6023 /* Since we're exiting the process here (or soon, anyway), we can
6024 * get away with using the config_rec's pool.
6025 */
6026 cmd = sql_make_cmd(c->pool, 1, "EXIT");
6027
6028 /* Ignore errors; we're exiting anyway. */
6029 (void) process_sqllog(cmd, c, "exit_listener", SQL_LOG_FL_IGNORE_ERRORS);
6030
6031 c = find_config_next(c, c->next, CONF_PARAM, "SQLLog_EXIT", FALSE);
6032 }
6033
6034 for (sb = sql_backends; sb != NULL; sb = sb->next) {
6035 cmdtable *curr_cmdtable = NULL;
6036
6037 pr_signals_handle();
6038
6039 /* Stash a pointer to the cmdtable of the current backend module, to
6040 * be restored afterward (Issue #1697).
6041 */
6042 curr_cmdtable = sql_cmdtable;
6043
6044 sql_cmdtable = sb->cmdtab;
6045 cmd = sql_make_cmd(session.pool, 0);
6046 mr = sql_dispatch(cmd, "sql_exit");
6047 (void) check_response(mr, SQL_LOG_FL_IGNORE_ERRORS);
6048
6049 /* Restore the previous cmdtable (Issue #1659). */
6050 sql_cmdtable = curr_cmdtable;
6051 }
6052
6053 sql_closelog();
6054 }
6055
6056 #if defined(PR_SHARED_MODULE)
6057 static void sql_mod_unload_ev(const void *event_data, void *user_data) {
6058 if (strcmp("mod_sql.c", (const char *) event_data) != 0) {
6059 return;
6060 }
6061
6062 destroy_pool(sql_pool);
6063 sql_pool = NULL;
6064 sql_backends = NULL;
6065 sql_auth_list = NULL;
6066
6067 pr_event_unregister(&sql_module, NULL, NULL);
6068
6069 pr_timer_remove(-1, &sql_module);
6070 sql_keepalive_timer_id = -1;
6071 sql_keepalive_stmt = NULL;
6072
6073 (void) sql_unregister_authtype("Crypt");
6074 (void) sql_unregister_authtype("Empty");
6075 (void) sql_unregister_authtype("Plaintext");
6076
6077 #if defined(HAVE_OPENSSL) || defined(PR_USE_OPENSSL)
6078 (void) sql_unregister_authtype("OpenSSL");
6079 #endif /* HAVE_OPENSSL */
6080
6081 close(sql_logfd);
6082 sql_logfd = -1;
6083 sql_logfile = NULL;
6084 }
6085
6086 #else
6087
6088 static void sql_preparse_ev(const void *event_data, void *user_data) {
6089 /* If no backends have been registered, croak. */
6090 if (sql_nbackends == 0) {
6091 pr_log_pri(PR_LOG_NOTICE, MOD_SQL_VERSION
6092 ": notice: no backend modules have been registered");
6093 exit(1);
6094 }
6095 }
6096 #endif /* PR_SHARED_MODULE */
6097
6098 static void sql_eventlog_ev(const void *event_data, void *user_data) {
6099 const char *event_name;
6100 int res;
6101
6102 event_name = user_data;
6103 res = eventlog_master(event_name);
6104 if (res < 0) {
6105 sql_log(DEBUG_FUNC, "SQLLogOnEvent '%s' query failed", event_name);
6106 }
6107 }
6108
6109 static void sql_sess_reinit_ev(const void *event_data, void *user_data) {
6110 config_rec *c;
6111 int res;
6112
6113 /* A HOST command changed the main_server pointer; reinitialize ourselves. */
6114
6115 pr_event_unregister(&sql_module, "core.chroot", sql_chroot_ev);
6116 pr_event_unregister(&sql_module, "core.exit", sql_exit_ev);
6117 pr_event_unregister(&sql_module, "core.session-reinit", sql_sess_reinit_ev);
6118
6119 pr_timer_remove(-1, &sql_module);
6120 sql_keepalive_timer_id = -1;
6121 sql_keepalive_stmt = NULL;
6122
6123 c = find_config(session.prev_server->conf, CONF_PARAM, "SQLLogOnEvent",
6124 FALSE);
6125 while (c != NULL) {
6126 char *event_name;
6127
6128 pr_signals_handle();
6129
6130 event_name = c->argv[0];
6131
6132 pr_event_unregister(&sql_module, event_name, sql_eventlog_ev);
6133 c = find_config_next(c, c->next, CONF_PARAM, "SQLLogOnEvent", FALSE);
6134 }
6135
6136 pr_sql_opts = 0UL;
6137 pr_sql_conn_policy = 0;
6138
6139 if (sql_logfd >= 0) {
6140 (void) close(sql_logfd);
6141 sql_logfd = -1;
6142 sql_logfile = NULL;
6143 }
6144
6145 memset(&cmap, 0, sizeof(cmap));
6146 sql_cmdtable = NULL;
6147 sql_default_cmdtable = NULL;
6148
6149 res = sql_sess_init();
6150 if (res < 0) {
6151 pr_session_disconnect(&sql_module, PR_SESS_DISCONNECT_SESSION_INIT_FAILED,
6152 NULL);
6153 }
6154 }
6155
6156 /* Initialization routines
6157 */
6158
6159 static int sql_init(void) {
6160 #if defined(PR_SHARED_MODULE)
6161 pr_event_register(&sql_module, "core.module-unload", sql_mod_unload_ev, NULL);
6162 #else
6163 pr_event_register(&sql_module, "core.preparse", sql_preparse_ev, NULL);
6164 #endif /* PR_SHARED_MODULE */
6165
6166 /* Register our built-in auth handlers. */
6167 (void) sql_register_authtype("Crypt", sql_auth_crypt);
6168 (void) sql_register_authtype("Empty", sql_auth_empty);
6169 (void) sql_register_authtype("Plaintext", sql_auth_plaintext);
6170
6171 #if defined(HAVE_OPENSSL) || defined(PR_USE_OPENSSL)
6172 (void) sql_register_authtype("OpenSSL", sql_auth_openssl);
6173 #endif /* HAVE_OPENSSL */
6174
6175 return 0;
6176 }
6177
6178 static int sql_sess_init(void) {
6179 char *authstr = NULL;
6180 config_rec *c = NULL;
6181 void *default_backend = NULL, *ptr = NULL;
6182 unsigned char *negative_cache = NULL;
6183 cmd_rec *cmd = NULL;
6184 modret_t *mr = NULL;
6185 sql_data_t *sd = NULL;
6186 int engine = 0, res = 0;
6187 char *fieldset = NULL;
6188 pool *tmp_pool = NULL;
6189
6190 pr_event_register(&sql_module, "core.session-reinit", sql_sess_reinit_ev,
6191 NULL);
6192
6193 /* Build a temporary pool */
6194 tmp_pool = make_sub_pool(session.pool);
6195
6196 /* Open any configured SQLLogFile */
6197 res = sql_openlog();
6198 if (res < 0) {
6199 if (res == -1) {
6200 pr_log_pri(PR_LOG_NOTICE, "notice: unable to open SQLLogFile: %s",
6201 strerror(errno));
6202
6203 } else if (res == PR_LOG_WRITABLE_DIR) {
6204 pr_log_pri(PR_LOG_WARNING, "notice: unable to open SQLLogFile: "
6205 "parent directory is world-writable");
6206
6207 } else if (res == PR_LOG_SYMLINK) {
6208 pr_log_pri(PR_LOG_WARNING, "notice: unable to open SQLLogFile: "
6209 "cannot log to a symbolic link");
6210 }
6211 }
6212
6213 default_backend = get_param_ptr(main_server->conf, "SQLBackend", FALSE);
6214 sql_default_cmdtable = sql_set_backend(default_backend);
6215 if (sql_default_cmdtable == NULL) {
6216 if (default_backend != NULL) {
6217 sql_log(DEBUG_INFO, "unable to load '%s' SQL backend: %s",
6218 (char *) default_backend, strerror(errno));
6219
6220 } else {
6221 sql_log(DEBUG_INFO, "unable to load SQL backend: %s", strerror(errno));
6222 }
6223
6224 destroy_pool(tmp_pool);
6225 return -1;
6226 }
6227
6228 if (default_backend != NULL) {
6229 pr_trace_msg(trace_channel, 9, "loaded '%s' SQL backend",
6230 (char *) default_backend);
6231 }
6232
6233 /* Construct our internal cache structure for this session. */
6234 memset(&cmap, 0, sizeof(cmap));
6235
6236 c = find_config(main_server->conf, CONF_PARAM, "SQLEngine", FALSE);
6237 if (c != NULL) {
6238 cmap.engine = engine = *((int *) c->argv[0]);
6239
6240 } else {
6241 cmap.engine = engine = (SQL_ENGINE_FL_AUTH|SQL_ENGINE_FL_LOG);
6242 }
6243
6244 if (cmap.engine == 0) {
6245 destroy_pool(tmp_pool);
6246 return 0;
6247 }
6248
6249 /* Get our backend info and toss it up */
6250 cmd = sql_make_cmd(tmp_pool, 1, "foo");
6251 mr = sql_dispatch(cmd, "sql_identify");
6252 if (check_response(mr, 0) < 0) {
6253 destroy_pool(tmp_pool);
6254 return -1;
6255 }
6256
6257 sd = (sql_data_t *) mr->data;
6258
6259 sql_log(DEBUG_INFO, "backend module '%s'", sd->data[0]);
6260 sql_log(DEBUG_INFO, "backend api '%s'", sd->data[1]);
6261
6262 SQL_FREE_CMD(cmd);
6263
6264 sql_log(DEBUG_FUNC, "%s", ">>> sql_sess_init");
6265
6266 if (sql_pool == NULL) {
6267 sql_pool = make_sub_pool(session.pool);
6268 pr_pool_tag(sql_pool, MOD_SQL_VERSION);
6269 }
6270
6271 group_name_cache = make_cache(sql_pool, _group_name, _groupcmp);
6272 passwd_name_cache = make_cache(sql_pool, _passwd_name, _passwdcmp);
6273 group_gid_cache = make_cache(sql_pool, _group_gid, _groupcmp);
6274 passwd_uid_cache = make_cache(sql_pool, _passwd_uid, _passwdcmp);
6275
6276 cmap.group_cache_filled = 0;
6277 cmap.passwd_cache_filled = 0;
6278
6279 cmap.curr_group = NULL;
6280 cmap.curr_passwd = NULL;
6281
6282 ptr = get_param_ptr(main_server->conf, "SQLAuthenticate", FALSE);
6283 if (ptr != NULL) {
6284 cmap.authmask = *((int *) ptr);
6285
6286 } else {
6287 cmap.authmask = SQL_AUTH_GROUPS|SQL_AUTH_USERS|SQL_AUTH_GROUPSET|
6288 SQL_AUTH_USERSET;
6289 }
6290
6291 negative_cache = get_param_ptr(main_server->conf, "SQLNegativeCache",
6292 FALSE);
6293 cmap.negative_cache = negative_cache ? *negative_cache : FALSE;
6294
6295 cmap.defaulthomedir = get_param_ptr(main_server->conf, "SQLDefaultHomedir",
6296 FALSE);
6297
6298 pr_sql_opts = 0UL;
6299 c = find_config(main_server->conf, CONF_PARAM, "SQLOptions", FALSE);
6300 while (c != NULL) {
6301 unsigned long opts;
6302
6303 pr_signals_handle();
6304
6305 opts = *((unsigned long *) c->argv[0]);
6306 pr_sql_opts |= opts;
6307
6308 c = find_config_next(c, c->next, CONF_PARAM, "SQLOptions", FALSE);
6309 }
6310
6311 ptr = get_param_ptr(main_server->conf, "SQLUserTable", FALSE);
6312
6313 /* if we have no SQLUserTable, SQLUserInfo was not used -- default all */
6314
6315 if (ptr == NULL) {
6316 cmap.usrtable = MOD_SQL_DEF_USERTABLE;
6317 cmap.usrfield = MOD_SQL_DEF_USERNAMEFIELD;
6318 cmap.pwdfield = MOD_SQL_DEF_USERPASSWORDFIELD;
6319 cmap.uidfield = MOD_SQL_DEF_USERUIDFIELD;
6320 cmap.gidfield = MOD_SQL_DEF_USERGIDFIELD;
6321 cmap.homedirfield = MOD_SQL_DEF_USERHOMEDIRFIELD;
6322 cmap.shellfield = MOD_SQL_DEF_USERSHELLFIELD;
6323
6324 /* It's possible that custom UserInfo queries were configured. Check for
6325 * them.
6326 */
6327 ptr = get_param_ptr(main_server->conf, "SQLCustomUserInfoByName", FALSE);
6328 if (ptr != NULL) {
6329 config_rec *custom_c = NULL;
6330 char *named_query = pstrcat(tmp_pool, "SQLNamedQuery_", ptr, NULL);
6331
6332 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
6333 if (custom_c == NULL) {
6334 sql_log(DEBUG_INFO, "error: unable to resolve custom "
6335 "SQLNamedQuery name '%s'", (char *) ptr);
6336
6337 } else {
6338 cmap.usercustom = ptr;
6339 }
6340 }
6341
6342 ptr = get_param_ptr(main_server->conf, "SQLCustomUserInfoByID", FALSE);
6343 if (ptr != NULL) {
6344 config_rec *custom_c = NULL;
6345 char *named_query = pstrcat(tmp_pool, "SQLNamedQuery_", ptr, NULL);
6346
6347 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
6348 if (custom_c == NULL) {
6349 sql_log(DEBUG_INFO, "error: unable to resolve custom "
6350 "SQLNamedQuery name '%s'", (char *) ptr);
6351
6352 } else {
6353 cmap.usercustombyid = ptr;
6354 }
6355 }
6356
6357 ptr = get_param_ptr(main_server->conf, "SQLCustomUserInfoAllNames", FALSE);
6358 if (ptr) {
6359 config_rec *custom_c = NULL;
6360 char *named_query = pstrcat(tmp_pool, "SQLNamedQuery_", ptr, NULL);
6361
6362 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
6363 if (custom_c == NULL) {
6364 sql_log(DEBUG_INFO, "error: unable to resolve custom "
6365 "SQLNamedQuery name '%s'", (char *) ptr);
6366
6367 } else {
6368 cmap.usercustomuserset = ptr;
6369 }
6370 }
6371
6372 ptr = get_param_ptr(main_server->conf, "SQLCustomUserInfoAllUsers", FALSE);
6373 if (ptr != NULL) {
6374 config_rec *custom_c = NULL;
6375 char *named_query = pstrcat(tmp_pool, "SQLNamedQuery_", ptr, NULL);
6376
6377 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
6378 if (custom_c == NULL) {
6379 sql_log(DEBUG_INFO, "error: unable to resolve custom "
6380 "SQLNamedQuery name '%s'", (char *) ptr);
6381
6382 } else {
6383 cmap.usercustomusersetfast = ptr;
6384 }
6385 }
6386
6387 if (cmap.usercustomuserset &&
6388 cmap.usercustomusersetfast &&
6389 strcmp(cmap.usercustomuserset, cmap.usercustomusersetfast) == 0) {
6390 sql_log(DEBUG_INFO, "warning: 'userset' and 'usersetfast' custom "
6391 "SQLUserInfo SQLNamedQuery are the same query ('%s'), probable "
6392 "misconfiguration", cmap.usercustomuserset);
6393 }
6394
6395 } else {
6396 cmap.usrtable = ptr;
6397 cmap.usrfield = get_param_ptr(main_server->conf, "SQLUsernameField", FALSE);
6398 cmap.pwdfield = get_param_ptr(main_server->conf, "SQLPasswordField", FALSE);
6399 cmap.uidfield = get_param_ptr(main_server->conf, "SQLUidField", FALSE);
6400 cmap.gidfield = get_param_ptr(main_server->conf, "SQLGidField", FALSE);
6401 cmap.homedirfield = get_param_ptr(main_server->conf, "SQLHomedirField",
6402 FALSE);
6403 cmap.shellfield = get_param_ptr(main_server->conf, "SQLShellField", FALSE);
6404 }
6405
6406 /* Build the userfieldset */
6407 fieldset = pstrcat(tmp_pool, cmap.usrfield, ", ", cmap.pwdfield, NULL);
6408
6409 if (cmap.uidfield)
6410 fieldset = pstrcat(tmp_pool, fieldset, ", ", cmap.uidfield, NULL);
6411
6412 if (cmap.gidfield)
6413 fieldset = pstrcat(tmp_pool, fieldset, ", ", cmap.gidfield, NULL);
6414
6415 if (cmap.homedirfield)
6416 fieldset = pstrcat(tmp_pool, fieldset, ", ", cmap.homedirfield, NULL);
6417
6418 if (cmap.shellfield)
6419 fieldset = pstrcat(tmp_pool, fieldset, ", ", cmap.shellfield, NULL);
6420
6421 cmap.usrfields = pstrdup(sql_pool, fieldset);
6422
6423 ptr = get_param_ptr(main_server->conf, "SQLGroupTable", FALSE);
6424
6425 /* If we have no ptr, SQLGroupInfo was not used - default all */
6426 if (ptr == NULL) {
6427 cmap.grptable = MOD_SQL_DEF_GROUPTABLE;
6428 cmap.grpfield = MOD_SQL_DEF_GROUPNAMEFIELD;
6429 cmap.grpgidfield = MOD_SQL_DEF_GROUPGIDFIELD;
6430 cmap.grpmembersfield = MOD_SQL_DEF_GROUPMEMBERSFIELD;
6431
6432 /* Check for any configured custom SQLGroupInfo queries. */
6433
6434 ptr = get_param_ptr(main_server->conf, "SQLCustomGroupInfoByID", FALSE);
6435 if (ptr != NULL) {
6436 config_rec *custom_c = NULL;
6437 char *named_query = pstrcat(tmp_pool, "SQLNamedQuery_", ptr, NULL);
6438
6439 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
6440 if (custom_c == NULL) {
6441 sql_log(DEBUG_INFO, "error: unable to resolve custom "
6442 "SQLNamedQuery name '%s'", (char *) ptr);
6443
6444 } else {
6445 cmap.groupcustombyid = ptr;
6446 cmap.grpgidfield = NULL;
6447 }
6448 }
6449
6450 ptr = get_param_ptr(main_server->conf, "SQLCustomGroupInfoByName", FALSE);
6451 if (ptr != NULL) {
6452 config_rec *custom_c = NULL;
6453 char *named_query = pstrcat(tmp_pool, "SQLNamedQuery_", ptr, NULL);
6454
6455 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
6456 if (custom_c == NULL) {
6457 sql_log(DEBUG_INFO, "error: unable to resolve custom "
6458 "SQLNamedQuery name '%s'", (char *) ptr);
6459
6460 } else {
6461 cmap.groupcustombyname = ptr;
6462 }
6463 }
6464
6465 ptr = get_param_ptr(main_server->conf, "SQLCustomGroupInfoMembers", FALSE);
6466 if (ptr != NULL) {
6467 config_rec *custom_c = NULL;
6468 char *named_query = pstrcat(tmp_pool, "SQLNamedQuery_", ptr, NULL);
6469
6470 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
6471 if (custom_c == NULL) {
6472 sql_log(DEBUG_INFO, "error: unable to resolve custom "
6473 "SQLNamedQuery name '%s'", (char *) ptr);
6474
6475 } else {
6476 cmap.groupcustommembers = ptr;
6477 }
6478 }
6479
6480 ptr = get_param_ptr(main_server->conf, "SQLCustomGroupInfoAllNames", FALSE);
6481 if (ptr != NULL) {
6482 config_rec *custom_c = NULL;
6483 char *named_query = pstrcat(tmp_pool, "SQLNamedQuery_", ptr, NULL);
6484
6485 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
6486 if (custom_c == NULL) {
6487 sql_log(DEBUG_INFO, "error: unable to resolve custom "
6488 "SQLNamedQuery name '%s'", (char *) ptr);
6489
6490 } else {
6491 cmap.groupcustomgroupset = ptr;
6492 }
6493 }
6494
6495 ptr = get_param_ptr(main_server->conf, "SQLCustomGroupInfoAllGroups",
6496 FALSE);
6497 if (ptr != NULL) {
6498 config_rec *custom_c = NULL;
6499 char *named_query = pstrcat(tmp_pool, "SQLNamedQuery_", ptr, NULL);
6500
6501 custom_c = find_config(main_server->conf, CONF_PARAM, named_query, FALSE);
6502 if (custom_c == NULL) {
6503 sql_log(DEBUG_INFO, "error: unable to resolve custom "
6504 "SQLNamedQuery name '%s'", (char *) ptr);
6505
6506 } else {
6507 cmap.groupcustomgroupsetfast = ptr;
6508 }
6509 }
6510
6511 } else {
6512 cmap.grptable = get_param_ptr(main_server->conf, "SQLGroupTable", FALSE);
6513 cmap.grpfield = get_param_ptr(main_server->conf, "SQLGroupnameField",
6514 FALSE);
6515 cmap.grpgidfield = get_param_ptr(main_server->conf, "SQLGroupGIDField",
6516 FALSE);
6517 cmap.grpmembersfield = get_param_ptr(main_server->conf,
6518 "SQLGroupMembersField", FALSE);
6519 }
6520
6521 /* Build the groupfieldset */
6522 fieldset = pstrcat(tmp_pool, cmap.grpfield, ", ", cmap.grpgidfield, ", ",
6523 cmap.grpmembersfield, NULL);
6524 cmap.grpfields = pstrdup(sql_pool, fieldset);
6525
6526 ptr = get_param_ptr(main_server->conf, "SQLUserWhereClause", FALSE);
6527 cmap.userwhere = ptr ? pstrcat(sql_pool, "(", ptr, ")", NULL) : NULL;
6528
6529 ptr = get_param_ptr(main_server->conf, "SQLGroupWhereClause", FALSE);
6530 cmap.groupwhere = ptr ? pstrcat(sql_pool, "(", ptr, ")", NULL) : NULL;
6531
6532 ptr = get_param_ptr(main_server->conf, "SQLAuthTypes", FALSE);
6533 cmap.auth_list = ptr;
6534
6535 if (cmap.auth_list == NULL &&
6536 cmap.authmask != 0 &&
6537 (engine > 0 && engine != SQL_ENGINE_FL_LOG)) {
6538 sql_log(DEBUG_INFO, "%s", "error: no SQLAuthTypes configured");
6539 }
6540
6541 c = find_config(main_server->conf, CONF_PARAM, "SQLMinID", FALSE);
6542 if (c != NULL) {
6543 cmap.minuseruid = *((uid_t *) c->argv[0]);
6544 cmap.minusergid = *((gid_t *) c->argv[1]);
6545
6546 } else {
6547 ptr = get_param_ptr(main_server->conf, "SQLMinUserUID", FALSE);
6548 cmap.minuseruid = ptr ? *((uid_t *) ptr) : MOD_SQL_MIN_USER_UID;
6549
6550 ptr = get_param_ptr(main_server->conf, "SQLMinUserGID", FALSE);
6551 cmap.minusergid = ptr ? *((gid_t *) ptr) : MOD_SQL_MIN_USER_GID;
6552 }
6553
6554 ptr = get_param_ptr(main_server->conf, "SQLDefaultUID", FALSE);
6555 cmap.defaultuid = ptr ? *((uid_t *) ptr) : MOD_SQL_DEF_UID;
6556
6557 ptr = get_param_ptr(main_server->conf, "SQLDefaultGID", FALSE);
6558 cmap.defaultgid = ptr ? *((gid_t *) ptr) : MOD_SQL_DEF_GID;
6559
6560 c = find_config(main_server->conf, CONF_PARAM, "SQLRatioStats", FALSE);
6561 if (c) {
6562 cmap.sql_fstor = c->argv[0];
6563 cmap.sql_fretr = c->argv[1];
6564 cmap.sql_bstor = c->argv[2];
6565 cmap.sql_bretr = c->argv[3];
6566 }
6567
6568 c = find_config(main_server->conf, CONF_PARAM, "SQLRatios", FALSE);
6569 if (c) {
6570 if (!cmap.sql_fstor) {
6571 pr_log_pri(PR_LOG_WARNING,
6572 MOD_SQL_VERSION ": warning: SQLRatios directive ineffective "
6573 "without SQLRatioStats on");
6574 sql_log(DEBUG_WARN, "%s", "warning: SQLRatios directive ineffective "
6575 "without SQLRatioStats on");
6576 }
6577
6578 cmap.sql_frate = c->argv[0];
6579 cmap.sql_fcred = c->argv[1];
6580 cmap.sql_brate = c->argv[2];
6581 cmap.sql_bcred = c->argv[3];
6582 }
6583
6584 if (!cmap.homedirfield &&
6585 !cmap.defaulthomedir) {
6586 cmap.authmask ^= SQL_AUTH_USERS;
6587
6588 pr_log_pri(PR_LOG_WARNING, MOD_SQL_VERSION
6589 ": warning: no homedir field and no default specified. "
6590 "User authentication is OFF");
6591 sql_log(DEBUG_WARN, "%s",
6592 "warning: no homedir field and no default specified. "
6593 "User authentication is OFF");
6594 }
6595
6596 c = find_config(main_server->conf, CONF_PARAM, "SQLConnectInfo", FALSE);
6597 if (c == NULL) {
6598 cmap.authmask = 0;
6599 cmap.engine = 0;
6600 cmap.sql_fstor = NULL;
6601 cmap.sql_frate = NULL;
6602 sql_log(DEBUG_WARN, "%s",
6603 "warning: no SQLConnectInfo specified. mod_sql is OFF");
6604
6605 } else {
6606 unsigned int default_conn_policy;
6607
6608 pr_sql_conn_policy = SQL_CONN_POLICY_PERSESSION;
6609
6610 if (strcasecmp(c->argv[3], "perconn") == 0 ||
6611 strcasecmp(c->argv[3], "perconnection") == 0) {
6612 pr_sql_conn_policy = SQL_CONN_POLICY_PERCONN;
6613
6614 } else if (strcasecmp(c->argv[3], "percall") == 0) {
6615 pr_sql_conn_policy = SQL_CONN_POLICY_PERCALL;
6616 }
6617
6618 if (sql_define_conn(tmp_pool, MOD_SQL_DEF_CONN_NAME, c->argv[1], c->argv[2],
6619 c->argv[0], c->argv[3], c->argv[4], c->argv[5], c->argv[6], c->argv[7],
6620 c->argv[8]) < 0) {
6621 return -1;
6622 }
6623
6624 /* Since sql_define_conn() can change the policy (depending on the
6625 * backend's handling of the connection parameters, we record the
6626 * default connection policy here.
6627 */
6628 default_conn_policy = pr_sql_conn_policy;
6629
6630 sql_log(DEBUG_INFO, "%s", "connection 'default' successfully established");
6631
6632 c = find_config(main_server->conf, CONF_PARAM, "SQLNamedConnectInfo",
6633 FALSE);
6634 while (c != NULL) {
6635 struct sql_named_conn *snc;
6636 const char *conn_name;
6637
6638 pr_signals_handle();
6639
6640 conn_name = c->argv[0];
6641
6642 /* Avoid duplicated connection names. */
6643 if (get_named_conn_backend(conn_name) == NULL) {
6644 pr_sql_conn_policy = SQL_CONN_POLICY_PERSESSION;
6645
6646 if (strncasecmp(c->argv[5], "perconn", 8) == 0 ||
6647 strncasecmp(c->argv[5], "perconnection", 14) == 0) {
6648 pr_sql_conn_policy = SQL_CONN_POLICY_PERCONN;
6649
6650 } else if (strncasecmp(c->argv[5], "percall", 8) == 0) {
6651 pr_sql_conn_policy = SQL_CONN_POLICY_PERCALL;
6652 }
6653
6654 /* Make sure we set the correct backend driver here, so that we
6655 * dispatch to the correct module's command table when defining the
6656 * connection.
6657 */
6658 sql_set_backend(c->argv[1]);
6659
6660 if (sql_define_conn(tmp_pool, c->argv[0], c->argv[3], c->argv[4],
6661 c->argv[2], c->argv[5], c->argv[6], c->argv[7], c->argv[8],
6662 c->argv[9], c->argv[10]) < 0) {
6663 /* Restore the default connection policy. */
6664 pr_sql_conn_policy = default_conn_policy;
6665
6666 destroy_pool(tmp_pool);
6667 return -1;
6668 }
6669
6670 /* Add the mapping of the connection name to the backend to the
6671 * lookup list.
6672 */
6673 snc = pcalloc(sql_pool, sizeof(struct sql_named_conn));
6674 snc->conn_name = conn_name;
6675 snc->conn_policy = pr_sql_conn_policy;
6676 snc->backend = c->argv[1];
6677
6678 if (sql_named_conns != NULL) {
6679 sql_named_conns->prev = snc;
6680 snc->next = sql_named_conns;
6681 }
6682
6683 sql_named_conns = snc;
6684
6685 /* Restore the default connection policy. */
6686 pr_sql_conn_policy = default_conn_policy;
6687
6688 sql_log(DEBUG_INFO, "connection '%s' successfully established",
6689 conn_name );
6690
6691 } else {
6692 sql_log(DEBUG_INFO, MOD_SQL_VERSION
6693 ": unable to open SQLNamedConnectInfo '%s': another connection "
6694 "with that name already exists", conn_name);
6695 }
6696
6697 c = find_config_next(c, c->next, CONF_PARAM, "SQLNamedConnectInfo",
6698 FALSE);
6699 }
6700 }
6701
6702 /* Make sure we use the default SQLBackend here, after processing any
6703 * SQLNamedConnectInfos.
6704 */
6705 if (default_backend != NULL) {
6706 sql_set_backend(default_backend);
6707 }
6708
6709 c = find_config(main_server->conf, CONF_PARAM, "SQLLogOnEvent", FALSE);
6710 while (c != NULL) {
6711 char *event_name;
6712
6713 pr_signals_handle();
6714
6715 event_name = c->argv[0];
6716
6717 pr_event_register(&sql_module, event_name, sql_eventlog_ev, event_name);
6718 c = find_config_next(c, c->next, CONF_PARAM, "SQLLogOnEvent", FALSE);
6719 }
6720
6721 if (cmap.engine == 0) {
6722 sql_log(DEBUG_INFO, "mod_sql engine : off");
6723
6724 } else if (cmap.engine == (SQL_ENGINE_FL_AUTH|SQL_ENGINE_FL_LOG)) {
6725 sql_log(DEBUG_INFO, "mod_sql engine : on");
6726
6727 } else if (cmap.engine == SQL_ENGINE_FL_AUTH) {
6728 sql_log(DEBUG_INFO, "mod_sql engine : auth");
6729
6730 } else if (cmap.engine == SQL_ENGINE_FL_LOG) {
6731 sql_log(DEBUG_INFO, "mod_sql engine : log");
6732 }
6733
6734 sql_log(DEBUG_INFO, "negative_cache : %s", cmap.negative_cache ? "on" : "off");
6735
6736 authstr = "";
6737
6738 if (SQL_USERS)
6739 authstr = pstrcat(tmp_pool, authstr, "users ", NULL);
6740
6741 if (SQL_GROUPS)
6742 authstr = pstrcat(tmp_pool, authstr, "groups ", NULL);
6743
6744 if (SQL_USERSET) {
6745 if (SQL_FASTUSERS) {
6746 authstr = pstrcat(tmp_pool, authstr, "userset(fast) ", NULL);
6747
6748 } else {
6749 authstr = pstrcat(tmp_pool, authstr, "userset ", NULL);
6750 }
6751 }
6752
6753 if (SQL_GROUPSET) {
6754 if (SQL_FASTGROUPS) {
6755 authstr = pstrcat(tmp_pool, authstr, "groupset(fast)", NULL);
6756
6757 } else {
6758 authstr = pstrcat(tmp_pool, authstr, "groupset", NULL);
6759 }
6760 }
6761
6762 sql_log(DEBUG_INFO, "authenticate : %s",
6763 (!authstr || *authstr=='\0') ? "off" : authstr);
6764
6765 if (SQL_USERS ||
6766 cmap.sql_fstor ||
6767 cmap.sql_frate) {
6768 sql_log(DEBUG_INFO, "usertable : %s", cmap.usrtable);
6769 sql_log(DEBUG_INFO, "userid field : %s", cmap.usrfield);
6770 }
6771
6772 if (SQL_USERS) {
6773 sql_log(DEBUG_INFO, "password field : %s", cmap.pwdfield);
6774
6775 sql_log(DEBUG_INFO, "UID field : %s",
6776 (cmap.uidfield ? cmap.uidfield : "NULL"));
6777
6778 sql_log(DEBUG_INFO, "GID field : %s",
6779 (cmap.gidfield ? cmap.gidfield : "NULL"));
6780
6781 if (cmap.homedirfield)
6782 sql_log(DEBUG_INFO, "homedir field : %s", cmap.homedirfield);
6783
6784 if (cmap.defaulthomedir)
6785 sql_log(DEBUG_INFO, "homedir(default) : '%s'", cmap.defaulthomedir);
6786
6787 sql_log(DEBUG_INFO, "shell field : %s",
6788 (cmap.shellfield ? cmap.shellfield : "NULL"));
6789 }
6790
6791 if (SQL_GROUPS) {
6792 sql_log(DEBUG_INFO, "group table : %s", cmap.grptable);
6793 sql_log(DEBUG_INFO, "groupname field : %s", cmap.grpfield);
6794 sql_log(DEBUG_INFO, "grp GID field : %s", cmap.grpgidfield);
6795 sql_log(DEBUG_INFO, "grp members field : %s", cmap.grpmembersfield);
6796 }
6797
6798 if (SQL_USERS) {
6799 sql_log(DEBUG_INFO, "SQLMinUserUID : %u", cmap.minuseruid);
6800 sql_log(DEBUG_INFO, "SQLMinUserGID : %u", cmap.minusergid);
6801 }
6802
6803 sql_log(DEBUG_INFO, "SQLDefaultUID : %u", cmap.defaultuid);
6804 sql_log(DEBUG_INFO, "SQLDefaultGID : %u", cmap.defaultgid);
6805
6806 if (cmap.sql_fstor) {
6807 sql_log(DEBUG_INFO, "sql_fstor : %s", cmap.sql_fstor);
6808 sql_log(DEBUG_INFO, "sql_fretr : %s", cmap.sql_fretr);
6809 sql_log(DEBUG_INFO, "sql_bstor : %s", cmap.sql_bstor);
6810 sql_log(DEBUG_INFO, "sql_bretr : %s", cmap.sql_bretr);
6811 }
6812
6813 if (cmap.sql_frate) {
6814 sql_log(DEBUG_INFO, "sql_frate : %s", cmap.sql_frate);
6815 sql_log(DEBUG_INFO, "sql_fcred : %s", cmap.sql_fcred);
6816 sql_log(DEBUG_INFO, "sql_brate : %s", cmap.sql_brate);
6817 sql_log(DEBUG_INFO, "sql_bcred : %s", cmap.sql_bcred);
6818 }
6819
6820 sql_log(DEBUG_FUNC, "%s", "<<< sql_sess_init");
6821
6822 destroy_pool(tmp_pool);
6823
6824 pr_event_register(&sql_module, "core.chroot", sql_chroot_ev, NULL);
6825 pr_event_register(&sql_module, "core.exit", sql_exit_ev, NULL);
6826
6827 c = find_config(main_server->conf, CONF_PARAM, "SQLKeepAlive", FALSE);
6828 if (c != NULL) {
6829 int interval;
6830
6831 interval = *((int *) c->argv[0]);
6832
6833 sql_keepalive_stmt = c->argv[1];
6834 sql_keepalive_timer_id = pr_timer_add(interval, -1, &sql_module,
6835 sql_keepalive_cb, "SQL keepalive");
6836 sql_log(DEBUG_INFO, "scheduling SQLKeepAlive (using '%s') every %d %s",
6837 sql_keepalive_stmt, interval, interval != 1 ? "secs" : "sec");
6838 }
6839
6840 return 0;
6841 }
6842
6843 /*****************************************************************
6844 *
6845 * HANDLER TABLES
6846 *
6847 *****************************************************************/
6848
6849 static conftable sql_conftab[] = {
6850 { "SQLAuthenticate", set_sqlauthenticate, NULL },
6851 { "SQLAuthTypes", set_sqlauthtypes, NULL },
6852 { "SQLBackend", set_sqlbackend, NULL },
6853 { "SQLConnectInfo", set_sqlconnectinfo, NULL },
6854 { "SQLDefaultGID", set_sqldefaultgid, NULL },
6855 { "SQLDefaultHomedir", set_sqldefaulthomedir, NULL },
6856 { "SQLDefaultUID", set_sqldefaultuid, NULL },
6857 { "SQLEngine", set_sqlengine, NULL },
6858 { "SQLGroupInfo", set_sqlgroupinfo, NULL },
6859 { "SQLGroupPrimaryKey", set_sqlgroupprimarykey, NULL },
6860 { "SQLGroupWhereClause", set_sqlgroupwhereclause, NULL },
6861 { "SQLKeepAlive", set_sqlkeepalive, NULL },
6862 { "SQLLog", set_sqllog, NULL },
6863 { "SQLLogFile", set_sqllogfile, NULL },
6864 { "SQLLogOnEvent", set_sqllogonevent, NULL },
6865 { "SQLMinID", set_sqlminid, NULL },
6866 { "SQLMinUserGID", set_sqlminusergid, NULL },
6867 { "SQLMinUserUID", set_sqlminuseruid, NULL },
6868 { "SQLNamedConnectInfo", set_sqlnamedconnectinfo, NULL },
6869 { "SQLNamedQuery", set_sqlnamedquery, NULL },
6870 { "SQLNegativeCache", set_sqlnegativecache, NULL },
6871 { "SQLOptions", set_sqloptions, NULL },
6872 { "SQLShowInfo", set_sqlshowinfo, NULL },
6873 { "SQLUserInfo", set_sqluserinfo, NULL },
6874 { "SQLUserPrimaryKey", set_sqluserprimarykey, NULL },
6875 { "SQLUserWhereClause", set_sqluserwhereclause, NULL },
6876
6877 { "SQLRatios", set_sqlratios, NULL },
6878 { "SQLRatioStats", set_sqlratiostats, NULL },
6879
6880 { NULL, NULL, NULL }
6881 };
6882
6883 static cmdtable sql_cmdtab[] = {
6884 { PRE_CMD, C_PASS, G_NONE, sql_pre_pass, FALSE, FALSE },
6885 { POST_CMD, C_PASS, G_NONE, sql_post_pass, FALSE, FALSE },
6886 { PRE_CMD, C_DELE, G_NONE, sql_pre_dele, FALSE, FALSE },
6887 { POST_CMD, C_RETR, G_NONE, sql_post_retr, FALSE, FALSE },
6888 { POST_CMD, C_STOR, G_NONE, sql_post_stor, FALSE, FALSE },
6889 { POST_CMD, C_ANY, G_NONE, info_master, FALSE, FALSE },
6890 { POST_CMD_ERR, C_ANY, G_NONE, errinfo_master, FALSE, FALSE },
6891 { LOG_CMD, C_ANY, G_NONE, log_master, FALSE, FALSE },
6892 { LOG_CMD_ERR, C_ANY, G_NONE, err_master, FALSE, FALSE },
6893
6894 /* Module hooks */
6895 { HOOK, "sql_change", G_NONE, sql_change, FALSE, FALSE },
6896 { HOOK, "sql_cleanup", G_NONE, sql_cleanup, FALSE, FALSE },
6897 { HOOK, "sql_close_conn", G_NONE, sql_closeconn, FALSE, FALSE },
6898 { HOOK, "sql_define_conn", G_NONE, sql_defineconn, FALSE, FALSE },
6899 { HOOK, "sql_escapestr", G_NONE, sql_escapestr, FALSE, FALSE },
6900 { HOOK, "sql_load_backend", G_NONE, sql_load_backend,FALSE, FALSE },
6901 { HOOK, "sql_lookup", G_NONE, sql_lookup, FALSE, FALSE },
6902 { HOOK, "sql_open_conn", G_NONE, sql_openconn, FALSE, FALSE },
6903 { HOOK, "sql_prepare", G_NONE, sql_prepare, FALSE, FALSE },
6904 { HOOK, "sql_select", G_NONE, sql_select, FALSE, FALSE },
6905
6906 { 0, NULL }
6907 };
6908
6909 static authtable sql_authtab[] = {
6910 { 0, "setpwent", sql_auth_setpwent },
6911 { 0, "getpwent", sql_auth_getpwent },
6912 { 0, "endpwent", sql_auth_endpwent },
6913 { 0, "setgrent", sql_auth_setgrent },
6914 { 0, "getgrent", sql_auth_getgrent },
6915 { 0, "endgrent", sql_auth_endgrent },
6916 { 0, "getpwnam", sql_auth_getpwnam },
6917 { 0, "getpwuid", sql_auth_getpwuid },
6918 { 0, "getgrnam", sql_auth_getgrnam },
6919 { 0, "getgrgid", sql_auth_getgrgid },
6920 { 0, "auth", sql_auth_authenticate },
6921 { 0, "check", sql_auth_check },
6922 { 0, "uid2name", sql_auth_uid2name },
6923 { 0, "gid2name", sql_auth_gid2name },
6924 { 0, "name2uid", sql_auth_name2uid },
6925 { 0, "name2gid", sql_auth_name2gid },
6926 { 0, "getgroups", sql_auth_getgroups },
6927
6928 /* Note: these should be HOOKs, and in the cmdtab. */
6929 { 0, "getstats", sql_getstats },
6930 { 0, "getratio", sql_getratio },
6931
6932 { 0, NULL, NULL }
6933 };
6934
6935 module sql_module = {
6936
6937 /* Always NULL */
6938 NULL, NULL,
6939
6940 /* Module API version */
6941 0x20,
6942
6943 /* Module name */
6944 "sql",
6945
6946 /* Module configuration directive table */
6947 sql_conftab,
6948
6949 /* Module command handler table */
6950 sql_cmdtab,
6951
6952 /* Module auth handler table */
6953 sql_authtab,
6954
6955 /* Module initialization */
6956 sql_init,
6957
6958 /* Session initialization */
6959 sql_sess_init,
6960
6961 /* Module version */
6962 MOD_SQL_VERSION
6963 };