The FreeRADIUS server  $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
rlm_sql_sqlite.c
Go to the documentation of this file.
1 /*
2  * This program is is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or (at
5  * your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16 
17 /**
18  * $Id: 3b5f663a6a4ed2ef31d270091af385da3a30a770 $
19  * @file rlm_sql_sqlite.c
20  * @brief SQLite driver.
21  *
22  * @copyright 2013 Network RADIUS SAS (legal@networkradius.com)
23  * @copyright 2007 Apple Inc.
24  */
25 RCSID("$Id: 3b5f663a6a4ed2ef31d270091af385da3a30a770 $")
26 
27 #define LOG_PREFIX "sql - sqlite"
28 #include <freeradius-devel/server/base.h>
29 #include <freeradius-devel/util/debug.h>
30 
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 
34 #include <sqlite3.h>
35 
36 #include "rlm_sql.h"
37 #include "config.h"
38 
39 #define BOOTSTRAP_MAX (1048576 * 10)
40 
41 /*
42  * Allow us to use versions < 3.6.0 beta0
43  */
44 #ifndef SQLITE_OPEN_NOMUTEX
45 # define SQLITE_OPEN_NOMUTEX 0
46 #endif
47 
48 #ifndef HAVE_SQLITE3_INT64
49 typedef sqlite_int64 sqlite3_int64;
50 #endif
51 
52 typedef struct {
53  sqlite3 *db;
54  sqlite3_stmt *statement;
55  int col_count;
57 
58 typedef struct {
59  char const *filename;
60  bool bootstrap;
62 
63 static const conf_parser_t driver_config[] = {
66 };
67 
68 /** Convert an sqlite status code to an sql_rcode_t
69  *
70  * @param status to convert.
71  * @return
72  * - RLM_SQL_OK - If no errors found.
73  * - RLM_SQL_ERROR - If a known, non-fatal, error occurred.
74  * - RLM_SQL_ALT_QUERY - If a constraints violation occurred.
75  * - RLM_SQL_RECONNECT - Anything else, we assume the connection can no longer be used.
76  */
77 static sql_rcode_t sql_error_to_rcode(int status)
78 {
79  /*
80  * Lowest byte is error category, other byte may contain
81  * the extended error, depending on version.
82  */
83  switch (status & 0xff) {
84  /*
85  * Not errors
86  */
87  case SQLITE_OK:
88  case SQLITE_DONE:
89  case SQLITE_ROW:
90  return RLM_SQL_OK;
91  /*
92  * User/transient errors
93  */
94  case SQLITE_ERROR: /* SQL error or missing database */
95  case SQLITE_FULL:
96  case SQLITE_MISMATCH:
97  case SQLITE_BUSY: /* Can be caused by database locking */
98  return RLM_SQL_ERROR;
99 
100  /*
101  * Constraints violations
102  */
103  case SQLITE_CONSTRAINT:
104  return RLM_SQL_ALT_QUERY;
105 
106  /*
107  * Errors with the handle, that probably require reinitialisation
108  */
109  default:
110  return RLM_SQL_RECONNECT;
111  }
112 }
113 
114 /** Determine if an error occurred, and what type of error it was
115  *
116  * @param db handle to extract error from (may be NULL).
117  * @param status to check (if unused, set to SQLITE_OK).
118  * @return
119  * - RLM_SQL_OK - If no errors found.
120  * - RLM_SQL_ERROR - If a known, non-fatal, error occurred.
121  * - RLM_SQL_ALT_QUERY - If a constraints violation occurred.
122  * - RLM_SQL_RECONNECT - Anything else. We assume the connection can no longer be used.
123  */
124 static sql_rcode_t sql_check_error(sqlite3 *db, int status)
125 {
126  int hstatus = SQLITE_OK;
127 
128  if (db) {
129  hstatus = sqlite3_errcode(db);
130  switch (hstatus & 0xff) {
131  case SQLITE_OK:
132  case SQLITE_DONE:
133  case SQLITE_ROW:
134  hstatus = SQLITE_OK;
135  break;
136 
137  default:
138  break;
139  }
140  }
141 
142  switch (status & 0xff) {
143  case SQLITE_OK:
144  case SQLITE_DONE:
145  case SQLITE_ROW:
146  status = SQLITE_OK;
147  break;
148 
149  default:
150  break;
151  }
152 
153  if (status != SQLITE_OK) return sql_error_to_rcode(status);
154  if (hstatus != SQLITE_OK) return sql_error_to_rcode(status);
155 
156  return RLM_SQL_OK;
157 }
158 
159 /** Print an error to the global debug log
160  *
161  * If status does not indicate success, write an error to the global error log.
162  *
163  * @note The error code will be appended to the fmt string in the format ": code 0x<hex> (<int>)[: <string>]".
164  *
165  * @param db handle to extract error from (may be NULL).
166  * @param status to check (if unused, set to SQLITE_OK).
167  * @param fmt to prepend.
168  * @param ... arguments to fmt.
169  */
170 static void sql_print_error(sqlite3 *db, int status, char const *fmt, ...)
171  CC_HINT(format (printf, 3, 4)) CC_HINT(nonnull (3));
172 static void sql_print_error(sqlite3 *db, int status, char const *fmt, ...)
173 {
174  va_list ap;
175  char *p;
176  int hstatus = SQLITE_OK;
177 
178  if (db) {
179  hstatus = sqlite3_errcode(db);
180  switch (hstatus & 0xff) {
181  case SQLITE_OK:
182  case SQLITE_DONE:
183  case SQLITE_ROW:
184  hstatus = SQLITE_OK;
185  break;
186 
187  default:
188  break;
189  }
190  }
191 
192  switch (status & 0xff) {
193  case SQLITE_OK:
194  case SQLITE_DONE:
195  case SQLITE_ROW:
196  status = SQLITE_OK;
197  break;
198 
199  default:
200  break;
201  }
202 
203  /*
204  * No errors!
205  */
206  if ((hstatus == SQLITE_OK) && (status == SQLITE_OK)) return;
207 
208  /*
209  * At least one error...
210  */
211  va_start(ap, fmt);
212  MEM(p = talloc_vasprintf(NULL, fmt, ap));
213  va_end(ap);
214 
215  /*
216  * Disagreement between handle, and function return code,
217  * print them both.
218  */
219  if ((status != SQLITE_OK) && (status != hstatus)) {
220 #ifdef HAVE_SQLITE3_ERRSTR
221  ERROR("%s: Code 0x%04x (%i): %s", p, status, status, sqlite3_errstr(status));
222 #else
223  ERROR("%s: Code 0x%04x (%i)", p, status, status);
224 #endif
225  }
226 
227  if (hstatus != SQLITE_OK) ERROR("%s: Code 0x%04x (%i): %s",
228  p, hstatus, hstatus, sqlite3_errmsg(db));
229 }
230 
231 #ifdef HAVE_SQLITE3_OPEN_V2
232 static int sql_loadfile(TALLOC_CTX *ctx, sqlite3 *db, char const *filename)
233 {
234  ssize_t len;
235  int statement_len, statement_cnt = 0;
236  char *buffer;
237  char const *p;
238  int cl;
239  FILE *f;
240  struct stat finfo;
241 
242  int status;
243  sqlite3_stmt *statement;
244  char const *z_tail;
245 
246  INFO("Executing SQL statements from file \"%s\"", filename);
247 
248  f = fopen(filename, "r");
249  if (!f) {
250  ERROR("Failed opening SQL file \"%s\": %s", filename,
251  fr_syserror(errno));
252 
253  return -1;
254  }
255 
256  if (fstat(fileno(f), &finfo) < 0) {
257  ERROR("Failed stating SQL file \"%s\": %s", filename,
258  fr_syserror(errno));
259 
260  fclose(f);
261 
262  return -1;
263  }
264 
265  if (finfo.st_size > BOOTSTRAP_MAX) {
266  too_big:
267  ERROR("Size of SQL (%zu) file exceeds limit (%uk)",
268  (size_t) finfo.st_size / 1024, BOOTSTRAP_MAX / 1024);
269 
270  fclose(f);
271 
272  return -1;
273  }
274 
275  MEM(buffer = talloc_array(ctx, char, finfo.st_size + 1));
276  len = fread(buffer, sizeof(char), finfo.st_size, f);
277  if (len > finfo.st_size) {
279  goto too_big;
280  }
281 
282  if (!len) {
283  if (ferror(f)) {
284  ERROR("Error reading SQL file: %s", fr_syserror(errno));
285 
286  fclose(f);
288 
289  return -1;
290  }
291 
292  DEBUG("Ignoring empty SQL file");
293 
294  fclose(f);
296 
297  return 0;
298  }
299 
300  buffer[len] = '\0';
301  fclose(f);
302 
303  /*
304  * Check if input data is UTF-8. Allow CR/LF \t, too.
305  */
306  for (p = buffer; p < (buffer + len); p += cl) {
307  if (*p < ' ') {
308  if ((*p != 0x0a) && (*p != 0x0d) && (*p != '\t')) break;
309  cl = 1;
310  } else {
311  cl = fr_utf8_char((uint8_t const *) p, -1);
312  if (!cl) break;
313  }
314  }
315 
316  if ((p - buffer) != len) {
317  ERROR("Bootstrap file contains non-UTF8 char at offset %zu", p - buffer);
319  return -1;
320  }
321 
322  p = buffer;
323  while (*p) {
324  statement_len = len - (p - buffer);
325 #ifdef HAVE_SQLITE3_PREPARE_V2
326  status = sqlite3_prepare_v2(db, p, statement_len, &statement, &z_tail);
327 #else
328  status = sqlite3_prepare(db, p, statement_len, &statement, &z_tail);
329 #endif
330 
331  if (sql_check_error(db, status) != RLM_SQL_OK) {
332  sql_print_error(db, status, "Failed preparing statement %i", statement_cnt);
334  return -1;
335  }
336 
337  /*
338  * No SQL statement was found
339  */
340  if (!statement) break;
341 
342  status = sqlite3_step(statement);
343  if (sql_check_error(db, status) != RLM_SQL_OK) {
344  sql_print_error(db, status, "Failed executing statement %i", statement_cnt);
345  sqlite3_finalize(statement);
347  return -1;
348  }
349 
350  status = sqlite3_finalize(statement);
351  if (sql_check_error(db, status) != RLM_SQL_OK) {
352  sql_print_error(db, status, "Failed finalizing statement %i", statement_cnt);
354  return -1;
355  }
356 
357  statement_cnt++;
358  p = z_tail;
359  }
360 
362  return 0;
363 }
364 #endif
365 
367 {
368  int status = 0;
369 
370  DEBUG2("Socket destructor called, closing socket");
371 
372  if (conn->db) {
373  status = sqlite3_close(conn->db);
374  if (status != SQLITE_OK) WARN("Got SQLite error when closing socket: %s",
375  sqlite3_errmsg(conn->db));
376  }
377 
378  return 0;
379 }
380 
381 static void _sql_greatest(sqlite3_context *ctx, int num_values, sqlite3_value **values)
382 {
383  int i;
384  sqlite3_int64 value, max = 0;
385 
386  for (i = 0; i < num_values; i++) {
387  value = sqlite3_value_int64(values[i]);
388  if (value > max) {
389  max = value;
390  }
391  }
392 
393  sqlite3_result_int64(ctx, max);
394 }
395 
398 {
399  rlm_sql_sqlite_conn_t *conn;
400  rlm_sql_sqlite_t *inst = talloc_get_type_abort(handle->inst->driver_submodule->dl_inst->data, rlm_sql_sqlite_t);
401 
402  int status;
403 
404  MEM(conn = handle->conn = talloc_zero(handle, rlm_sql_sqlite_conn_t));
405  talloc_set_destructor(conn, _sql_socket_destructor);
406 
407  INFO("Opening SQLite database \"%s\"", inst->filename);
408 #ifdef HAVE_SQLITE3_OPEN_V2
409  status = sqlite3_open_v2(inst->filename, &(conn->db), SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, NULL);
410 #else
411  status = sqlite3_open(inst->filename, &(conn->db));
412 #endif
413 
414  if (!conn->db || (sql_check_error(conn->db, status) != RLM_SQL_OK)) {
415  sql_print_error(conn->db, status, "Error opening SQLite database \"%s\"", inst->filename);
416 #ifdef HAVE_SQLITE3_OPEN_V2
417  if (!inst->bootstrap) {
418  INFO("Use the sqlite driver 'bootstrap' option to automatically create the database file");
419  }
420 #endif
421  return RLM_SQL_ERROR;
422  }
423  status = sqlite3_busy_timeout(conn->db, fr_time_delta_to_sec(config->query_timeout));
424  if (sql_check_error(conn->db, status) != RLM_SQL_OK) {
425  sql_print_error(conn->db, status, "Error setting busy timeout");
426  return RLM_SQL_ERROR;
427  }
428 
429  /*
430  * Enable extended return codes for extra debugging info.
431  */
432 #ifdef HAVE_SQLITE3_EXTENDED_RESULT_CODES
433  status = sqlite3_extended_result_codes(conn->db, 1);
434  if (sql_check_error(conn->db, status) != RLM_SQL_OK) {
435  sql_print_error(conn->db, status, "Error enabling extended result codes");
436  return RLM_SQL_ERROR;
437  }
438 #endif
439 
440 #ifdef HAVE_SQLITE3_CREATE_FUNCTION_V2
441  status = sqlite3_create_function_v2(conn->db, "GREATEST", -1, SQLITE_ANY, NULL,
442  _sql_greatest, NULL, NULL, NULL);
443 #else
444  status = sqlite3_create_function(conn->db, "GREATEST", -1, SQLITE_ANY, NULL,
445  _sql_greatest, NULL, NULL);
446 #endif
447  if (sql_check_error(conn->db, status) != RLM_SQL_OK) {
448  sql_print_error(conn->db, status, "Failed registering 'GREATEST' sql function");
449  return RLM_SQL_ERROR;
450  }
451 
452  return RLM_SQL_OK;
453 }
454 
455 static sql_rcode_t sql_select_query(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config, char const *query)
456 {
457  rlm_sql_sqlite_conn_t *conn = handle->conn;
458  char const *z_tail;
459  int status;
460 
461 #ifdef HAVE_SQLITE3_PREPARE_V2
462  status = sqlite3_prepare_v2(conn->db, query, strlen(query), &conn->statement, &z_tail);
463 #else
464  status = sqlite3_prepare(conn->db, query, strlen(query), &conn->statement, &z_tail);
465 #endif
466 
467  conn->col_count = 0;
468 
469  return sql_check_error(conn->db, status);
470 }
471 
472 
473 static sql_rcode_t sql_query(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config, char const *query)
474 {
475 
476  sql_rcode_t rcode;
477  rlm_sql_sqlite_conn_t *conn = handle->conn;
478  char const *z_tail;
479  int status;
480 
481 #ifdef HAVE_SQLITE3_PREPARE_V2
482  status = sqlite3_prepare_v2(conn->db, query, strlen(query), &conn->statement, &z_tail);
483 #else
484  status = sqlite3_prepare(conn->db, query, strlen(query), &conn->statement, &z_tail);
485 #endif
486  rcode = sql_check_error(conn->db, status);
487  if (rcode != RLM_SQL_OK) return rcode;
488 
489  status = sqlite3_step(conn->statement);
490  return sql_check_error(conn->db, status);
491 }
492 
494 {
495  rlm_sql_sqlite_conn_t *conn = handle->conn;
496 
497  if (conn->statement) return sqlite3_column_count(conn->statement);
498 
499  return 0;
500 }
501 
502 static sql_rcode_t sql_fields(char const **out[], rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config)
503 {
504  rlm_sql_sqlite_conn_t *conn = handle->conn;
505 
506  int fields, i;
507  char const **names;
508 
509  fields = sqlite3_column_count(conn->statement);
510  if (fields <= 0) return RLM_SQL_ERROR;
511 
512  MEM(names = talloc_array(handle, char const *, fields));
513 
514  for (i = 0; i < fields; i++) names[i] = sqlite3_column_name(conn->statement, i);
515  *out = names;
516 
517  return RLM_SQL_OK;
518 }
519 
521 {
522  int status;
523  rlm_sql_sqlite_conn_t *conn = handle->conn;
524 
525  int i = 0;
526 
527  char **row;
528 
529  *out = NULL;
530 
531  TALLOC_FREE(handle->row);
532 
533  /*
534  * Executes the SQLite query and iterates over the results
535  */
536  status = sqlite3_step(conn->statement);
537 
538  /*
539  * Error getting next row
540  */
541  if (sql_check_error(conn->db, status) != RLM_SQL_OK) return RLM_SQL_ERROR;
542 
543  /*
544  * No more rows to process (we're done)
545  */
546  if (status == SQLITE_DONE) return RLM_SQL_NO_MORE_ROWS;
547 
548  /*
549  * We only need to do this once per result set, because
550  * the number of columns won't change.
551  */
552  if (conn->col_count == 0) {
553  conn->col_count = sql_num_fields(handle, config);
554  if (conn->col_count == 0) return RLM_SQL_ERROR;
555  }
556 
557  /*
558  * Free the previous result (also gets called on finish_query)
559  */
560  MEM(row = handle->row = talloc_zero_array(handle->conn, char *, conn->col_count + 1));
561 
562  for (i = 0; i < conn->col_count; i++) {
563  switch (sqlite3_column_type(conn->statement, i)) {
564  case SQLITE_INTEGER:
565  MEM(row[i] = talloc_typed_asprintf(row, "%d", sqlite3_column_int(conn->statement, i)));
566  break;
567 
568  case SQLITE_FLOAT:
569  MEM(row[i] = talloc_typed_asprintf(row, "%f", sqlite3_column_double(conn->statement, i)));
570  break;
571 
572  case SQLITE_TEXT:
573  {
574  char const *p;
575  p = (char const *) sqlite3_column_text(conn->statement, i);
576 
577  if (p) MEM(row[i] = talloc_typed_strdup(row, p));
578  }
579  break;
580 
581  case SQLITE_BLOB:
582  {
583  uint8_t const *p;
584  size_t len;
585 
586  p = sqlite3_column_blob(conn->statement, i);
587  if (p) {
588  len = sqlite3_column_bytes(conn->statement, i);
589 
590  MEM(row[i] = talloc_zero_array(row, char, len + 1));
591  memcpy(row[i], p, len);
592  }
593  }
594  break;
595 
596  default:
597  break;
598  }
599  }
600 
601  *out = row;
602 
603  return RLM_SQL_OK;
604 }
605 
607 {
608  rlm_sql_sqlite_conn_t *conn = handle->conn;
609 
610  if (conn->statement) {
611  TALLOC_FREE(handle->row);
612 
613  (void) sqlite3_finalize(conn->statement);
614  conn->statement = NULL;
615  conn->col_count = 0;
616  }
617 
618  /*
619  * There's no point in checking the code returned by finalize
620  * as it'll have already been encountered elsewhere in the code.
621  *
622  * It's just the last error that occurred processing the
623  * statement.
624  */
625  return RLM_SQL_OK;
626 }
627 
628 /** Retrieves any errors associated with the connection handle
629  *
630  * @note Caller will free any memory allocated in ctx.
631  *
632  * @param ctx to allocate temporary error buffers in.
633  * @param out Array of sql_log_entrys to fill.
634  * @param outlen Length of out array.
635  * @param handle rlm_sql connection handle.
636  * @param config rlm_sql config.
637  * @return number of errors written to the #sql_log_entry_t array.
638  */
639 static size_t sql_error(UNUSED TALLOC_CTX *ctx, sql_log_entry_t out[], NDEBUG_UNUSED size_t outlen,
641 {
642  rlm_sql_sqlite_conn_t *conn = handle->conn;
643  char const *error;
644 
645  fr_assert(outlen > 0);
646 
647  error = sqlite3_errmsg(conn->db);
648  if (!error) return 0;
649 
650  out[0].type = L_ERR;
651  out[0].msg = error;
652 
653  return 1;
654 }
655 
657 {
658  return sql_free_result(handle, config);
659 }
660 
663 {
664  rlm_sql_sqlite_conn_t *conn = handle->conn;
665 
666  if (conn->db) return sqlite3_changes(conn->db);
667 
668  return -1;
669 }
670 
671 static int mod_bootstrap(module_inst_ctx_t const *mctx)
672 {
673  rlm_sql_t const *parent = talloc_get_type_abort(mctx->inst->parent->data, rlm_sql_t);
674  rlm_sql_config_t const *config = &parent->config;
675  rlm_sql_sqlite_t *inst = talloc_get_type_abort(mctx->inst->data, rlm_sql_sqlite_t);
676  bool exists;
677  struct stat buf;
678  int fd;
679  char const *r;
680 
681  if (!inst->filename) {
682  MEM(inst->filename = talloc_typed_asprintf(inst, "%s/%s",
683  main_config->raddb_dir, config->sql_db));
684  }
685 
686  /*
687  * mod_bootstrap() will try to create the database if it doesn't exist, up to and
688  * including creating the directory it should live in, in which case we get to call
689  * fr_dirfd() again. Hence failing this first fr_dirfd() just means the database isn't there.
690  */
691  if (fr_dirfd(&fd, &r, inst->filename) < 0) {
692  exists = false;
693  } else if (fstatat(fd, r, &buf, 0) == 0) {
694  exists = true;
695  } else if (errno == ENOENT) {
696  exists = false;
697  } else {
698  ERROR("Database exists, but couldn't be opened: %s", fr_syserror(errno));
699  close(fd);
700  return -1;
701  }
702 
703  if (cf_pair_find(mctx->inst->conf, "bootstrap")) {
704  inst->bootstrap = true;
705  }
706 
707  if (inst->bootstrap && !exists) {
708 #ifdef HAVE_SQLITE3_OPEN_V2
709  int status;
710  int ret;
711  char const *p;
712  char *buff;
713  sqlite3 *db = NULL;
714  CONF_PAIR *cp;
715 
716  INFO("Database \"%s\" doesn't exist, creating it and loading schema", inst->filename);
717 
718  p = strrchr(inst->filename, '/');
719  if (p) {
720  size_t len = (p - inst->filename) + 1;
721 
722  buff = talloc_array(mctx->inst->conf, char, len);
723  strlcpy(buff, inst->filename, len);
724  } else {
725  MEM(buff = talloc_typed_strdup(mctx->inst->conf, inst->filename));
726  }
727 
728  ret = fr_mkdir(NULL, buff, -1, 0700, NULL, NULL);
729  talloc_free(buff);
730  if (ret < 0) {
731  PERROR("Failed creating directory for SQLite database");
732 
733  return -1;
734  }
735  (void) fr_dirfd(&fd, &r, inst->filename);
736 
737  status = sqlite3_open_v2(inst->filename, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
738  if (!db) {
739 # ifdef HAVE_SQLITE3_ERRSTR
740  ERROR("Failed creating opening/creating SQLite database: %s",
741  sqlite3_errstr(status));
742 # else
743  ERROR("Failed creating opening/creating SQLite database, got code (%i)",
744  status);
745 # endif
746 
747  goto unlink;
748  }
749 
750  if (sql_check_error(db, status) != RLM_SQL_OK) {
751  (void) sqlite3_close(db);
752 
753  goto unlink;
754  }
755 
756  /*
757  * Execute multiple bootstrap SQL files in order
758  */
759  for (cp = cf_pair_find(mctx->inst->conf, "bootstrap");
760  cp;
761  cp = cf_pair_find_next(mctx->inst->conf, cp, "bootstrap")) {
762  p = cf_pair_value(cp);
763  if (!p) continue;
764 
765  ret = sql_loadfile(mctx->inst->conf, db, p);
766  if (ret < 0) goto unlink;
767  }
768 
769  status = sqlite3_close(db);
770  if (status != SQLITE_OK) {
771  /*
772  * Safer to use sqlite3_errstr here, just in case the handle is in a weird state
773  */
774 # ifdef HAVE_SQLITE3_ERRSTR
775  ERROR("Error closing SQLite handle: %s", sqlite3_errstr(status));
776 # else
777  ERROR("Error closing SQLite handle, got code (%i)", status);
778 # endif
779  goto unlink;
780  }
781 
782  if (ret < 0) {
783  unlink:
784  if ((unlinkat(fd, r, 0) < 0) && (errno != ENOENT)) {
785  ERROR("Error removing partially initialised database: %s",
786  fr_syserror(errno));
787  }
788  close(fd);
789  return -1;
790  }
791 #else
792  WARN("sqlite3_open_v2() not available, cannot bootstrap database. "
793  "Upgrade to SQLite >= 3.5.1 if you need this functionality");
794 #endif
795  }
796 
797  close(fd);
798  return 0;
799 }
800 
801 static int mod_load(void)
802 {
803  if (sqlite3_libversion_number() != SQLITE_VERSION_NUMBER) {
804  WARN("libsqlite version changed since the server was built");
805  WARN("linked: %s built: %s", sqlite3_libversion(), SQLITE_VERSION);
806  }
807  INFO("libsqlite version: %s", sqlite3_libversion());
808 
809  return 0;
810 }
811 
812 /* Exported to rlm_sql */
815  .common = {
816  .name = "sql_sqlite",
817  .magic = MODULE_MAGIC_INIT,
818  .inst_size = sizeof(rlm_sql_sqlite_t),
820  .onload = mod_load,
821  .bootstrap = mod_bootstrap
822  },
824  .number = 4,
825  .sql_socket_init = sql_socket_init,
826  .sql_query = sql_query,
827  .sql_select_query = sql_select_query,
828  .sql_num_fields = sql_num_fields,
829  .sql_affected_rows = sql_affected_rows,
830  .sql_fetch_row = sql_fetch_row,
831  .sql_fields = sql_fields,
832  .sql_free_result = sql_free_result,
833  .sql_error = sql_error,
834  .sql_finish_query = sql_finish_query,
835  .sql_finish_select_query = sql_finish_query
836 };
static int const char char buffer[256]
Definition: acutest.h:574
va_end(args)
static int const char * fmt
Definition: acutest.h:573
va_start(args, fmt)
#define RCSID(id)
Definition: build.h:444
#define NDEBUG_UNUSED
Definition: build.h:324
#define UNUSED
Definition: build.h:313
#define CONF_PARSER_TERMINATOR
Definition: cf_parse.h:626
#define FR_CONF_OFFSET_FLAGS(_name, _flags, _struct, _field)
conf_parser_t which parses a single CONF_PAIR, writing the result to a field in a struct
Definition: cf_parse.h:256
@ CONF_FLAG_REQUIRED
Error out if no matching CONF_PAIR is found, and no dflt value is set.
Definition: cf_parse.h:406
@ CONF_FLAG_FILE_OUTPUT
File matching value must exist, and must be writable.
Definition: cf_parse.h:414
Defines a CONF_PAIR to C data type mapping.
Definition: cf_parse.h:563
Configuration AVP similar to a fr_pair_t.
Definition: cf_priv.h:70
CONF_PAIR * cf_pair_find(CONF_SECTION const *cs, char const *attr)
Search for a CONF_PAIR with a specific name.
Definition: cf_util.c:1356
char const * cf_pair_value(CONF_PAIR const *pair)
Return the value of a CONF_PAIR.
Definition: cf_util.c:1511
CONF_PAIR * cf_pair_find_next(CONF_SECTION const *cs, CONF_PAIR const *prev, char const *attr)
Find a pair with a name matching attr, after specified pair.
Definition: cf_util.c:1370
#define ERROR(fmt,...)
Definition: dhcpclient.c:41
#define DEBUG(fmt,...)
Definition: dhcpclient.c:39
static fr_time_delta_t timeout
Definition: dhcpclient.c:54
Test enumeration values.
Definition: dict_test.h:92
void *_CONST data
Module instance's parsed configuration.
Definition: dl_module.h:165
#define MODULE_MAGIC_INIT
Stop people using different module/library/server versions together.
Definition: dl_module.h:65
CONF_SECTION *_CONST conf
Module's instance configuration.
Definition: dl_module.h:166
dl_module_inst_t const *_CONST parent
Parent module's instance (if any).
Definition: dl_module.h:167
ssize_t fr_mkdir(int *fd_out, char const *path, ssize_t len, mode_t mode, fr_mkdir_func_t func, void *uctx)
Create directories that are missing in the specified path.
Definition: file.c:200
int fr_dirfd(int *dirfd, char const **filename, char const *pathname)
From a pathname, return fd and filename needed for *at() functions.
Definition: file.c:393
#define PERROR(_fmt,...)
Definition: log.h:228
talloc_free(reap)
@ L_ERR
Error message.
Definition: log.h:56
main_config_t const * main_config
Main server configuration.
Definition: main_config.c:69
char const * raddb_dir
Path to raddb directory.
Definition: main_config.h:78
long int ssize_t
Definition: merged_model.c:24
unsigned char uint8_t
Definition: merged_model.c:30
dl_module_inst_t const * inst
Dynamic loader API handle for the module.
Definition: module_ctx.h:52
Temporary structure to hold arguments for instantiation calls.
Definition: module_ctx.h:51
size_t fr_utf8_char(uint8_t const *str, ssize_t inlen)
Checks for utf-8, taken from http://www.w3.org/International/questions/qa-forms-utf-8.
Definition: print.c:39
static const conf_parser_t config[]
Definition: base.c:188
#define DEBUG2(fmt,...)
Definition: radclient.h:43
#define WARN(fmt,...)
Definition: radclient.h:47
#define INFO(fmt,...)
Definition: radict.c:54
Prototypes and functions for the SQL module.
rlm_sql_t const * inst
The rlm_sql instance this connection belongs to.
Definition: rlm_sql.h:103
void * conn
Database specific connection handle.
Definition: rlm_sql.h:101
sql_rcode_t
Action to take at end of an SQL query.
Definition: rlm_sql.h:42
@ RLM_SQL_ALT_QUERY
Key constraint violation, use an alternative query.
Definition: rlm_sql.h:47
@ RLM_SQL_RECONNECT
Stale connection, should reconnect.
Definition: rlm_sql.h:46
@ RLM_SQL_ERROR
General connection/server error.
Definition: rlm_sql.h:44
@ RLM_SQL_OK
Success.
Definition: rlm_sql.h:45
@ RLM_SQL_NO_MORE_ROWS
No more rows available.
Definition: rlm_sql.h:48
#define RLM_SQL_RCODE_FLAGS_ALT_QUERY
Can distinguish between other errors and those.
Definition: rlm_sql.h:116
char ** rlm_sql_row_t
Definition: rlm_sql.h:57
rlm_sql_row_t row
Row data from the last query.
Definition: rlm_sql.h:102
Definition: rlm_sql.h:59
sqlite_int64 sqlite3_int64
static int mod_load(void)
static sql_rcode_t sql_fetch_row(rlm_sql_row_t *out, rlm_sql_handle_t *handle, rlm_sql_config_t const *config)
static void sql_print_error(sqlite3 *db, int status, char const *fmt,...))
Print an error to the global debug log.
rlm_sql_driver_t rlm_sql_sqlite
static sql_rcode_t sql_finish_query(rlm_sql_handle_t *handle, rlm_sql_config_t const *config)
static sql_rcode_t sql_select_query(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config, char const *query)
char const * filename
static int mod_bootstrap(module_inst_ctx_t const *mctx)
static sql_rcode_t sql_free_result(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config)
sqlite3_stmt * statement
static const conf_parser_t driver_config[]
static sql_rcode_t sql_error_to_rcode(int status)
Convert an sqlite status code to an sql_rcode_t.
#define SQLITE_OPEN_NOMUTEX
#define BOOTSTRAP_MAX
static sql_rcode_t sql_query(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config, char const *query)
static int sql_affected_rows(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config)
static int _sql_socket_destructor(rlm_sql_sqlite_conn_t *conn)
static int sql_num_fields(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config)
static sql_rcode_t sql_check_error(sqlite3 *db, int status)
Determine if an error occurred, and what type of error it was.
static void _sql_greatest(sqlite3_context *ctx, int num_values, sqlite3_value **values)
static sql_rcode_t sql_socket_init(rlm_sql_handle_t *handle, rlm_sql_config_t const *config, UNUSED fr_time_delta_t timeout)
static sql_rcode_t sql_fields(char const **out[], rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config)
static size_t sql_error(UNUSED TALLOC_CTX *ctx, sql_log_entry_t out[], NDEBUG_UNUSED size_t outlen, rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t const *config)
Retrieves any errors associated with the connection handle.
dl_module_inst_t * dl_inst
Structure containing the module's instance data, configuration, and dl handle.
Definition: module.h:183
static char buff[sizeof("18446744073709551615")+3]
Definition: size_tests.c:41
fr_assert(0)
MEM(pair_append_request(&vp, attr_eap_aka_sim_identity) >=0)
eap_aka_sim_process_conf_t * inst
size_t strlcpy(char *dst, char const *src, size_t siz)
Definition: strlcpy.c:34
module_t common
Common fields for all loadable modules.
Definition: rlm_sql.h:148
module_instance_t * driver_submodule
Driver's submodule.
Definition: rlm_sql.h:185
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition: syserror.c:243
char * talloc_typed_strdup(TALLOC_CTX *ctx, char const *p)
Call talloc_strdup, setting the type on the new chunk correctly.
Definition: talloc.c:333
char * talloc_typed_asprintf(TALLOC_CTX *ctx, char const *fmt,...)
Call talloc vasprintf, setting the type on the new chunk correctly.
Definition: talloc.c:380
static const char * names[8]
Definition: time.c:617
static int64_t fr_time_delta_to_sec(fr_time_delta_t delta)
Definition: time.h:645
A time delta, a difference in time measured in nanoseconds.
Definition: time.h:80
close(uq->fd)
static fr_slen_t parent
Definition: pair.h:844
int nonnull(2, 5))
int format(printf, 5, 0))
static size_t char ** out
Definition: value.h:984