FR-AD-003 - Pass correct statement length into sqlite3_prepare[_v2]
[freeradius.git] / src / modules / rlm_sql / drivers / rlm_sql_sqlite / rlm_sql_sqlite.c
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$
19  * @file rlm_sql_sqlite.c
20  * @brief SQLite driver.
21  *
22  * @copyright 2013 Network RADIUS SARL <info@networkradius.com>
23  * @copyright 2007 Apple Inc.
24  */
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/rad_assert.h>
29
30 #include <fcntl.h>
31 #include <sys/stat.h>
32
33 #include <sqlite3.h>
34
35 #include "rlm_sql.h"
36 #include "config.h"
37
38 #define BOOTSTRAP_MAX (1048576 * 10)
39
40 /*
41  *      Allow us to use versions < 3.6.0 beta0
42  */
43 #ifndef SQLITE_OPEN_NOMUTEX
44 #  define SQLITE_OPEN_NOMUTEX 0
45 #endif
46
47 #ifndef HAVE_SQLITE3_INT64
48 typedef sqlite_int64 sqlite3_int64;
49 #endif
50
51 typedef struct rlm_sql_sqlite_conn {
52         sqlite3 *db;
53         sqlite3_stmt *statement;
54         int col_count;
55 } rlm_sql_sqlite_conn_t;
56
57 typedef struct rlm_sql_sqlite_config {
58         char const      *filename;
59         uint32_t        busy_timeout;
60 } rlm_sql_sqlite_config_t;
61
62 static const CONF_PARSER driver_config[] = {
63         { "filename", FR_CONF_OFFSET(PW_TYPE_FILE_OUTPUT | PW_TYPE_REQUIRED, rlm_sql_sqlite_config_t, filename), NULL },
64         { "busy_timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, rlm_sql_sqlite_config_t, busy_timeout), "200" },
65         CONF_PARSER_TERMINATOR
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                 return RLM_SQL_ERROR;
98
99         /*
100          *      Constraints violations
101          */
102         case SQLITE_CONSTRAINT:
103                 return RLM_SQL_ALT_QUERY;
104
105         /*
106          *      Errors with the handle, that probably require reinitialisation
107          */
108         default:
109                 return RLM_SQL_RECONNECT;
110         }
111 }
112
113 /** Determine if an error occurred, and what type of error it was
114  *
115  * @param db handle to extract error from (may be NULL).
116  * @param status to check (if unused, set to SQLITE_OK).
117  * @return
118  *      - RLM_SQL_OK - If no errors found.
119  *      - RLM_SQL_ERROR - If a known, non-fatal, error occurred.
120  *      - RLM_SQL_ALT_QUERY - If a constraints violation occurred.
121  *      - RLM_SQL_RECONNECT - Anything else. We assume the connection can no longer be used.
122  */
123 static sql_rcode_t sql_check_error(sqlite3 *db, int status)
124 {
125         int hstatus = SQLITE_OK;
126
127         if (db) {
128                 hstatus = sqlite3_errcode(db);
129                 switch (hstatus & 0xff) {
130                 case SQLITE_OK:
131                 case SQLITE_DONE:
132                 case SQLITE_ROW:
133                         hstatus = SQLITE_OK;
134                         break;
135
136                 default:
137                         break;
138                 }
139         }
140
141         switch (status & 0xff) {
142         case SQLITE_OK:
143         case SQLITE_DONE:
144         case SQLITE_ROW:
145                 status = SQLITE_OK;
146                 break;
147
148         default:
149                 break;
150         }
151
152         if (status != SQLITE_OK) return sql_error_to_rcode(status);
153         if (hstatus != SQLITE_OK) return sql_error_to_rcode(status);
154
155         return RLM_SQL_OK;
156 }
157
158 /** Print an error to the global debug log
159  *
160  * If status does not indicate success, write an error to the global error log.
161  *
162  * @note The error code will be appended to the fmt string in the format ": code 0x<hex> (<int>)[: <string>]".
163  *
164  * @param db handle to extract error from (may be NULL).
165  * @param status to check (if unused, set to SQLITE_OK).
166  * @param fmt to preprend.
167  * @param ... arguments to fmt.
168  */
169 static void sql_print_error(sqlite3 *db, int status, char const *fmt, ...)
170         CC_HINT(format (printf, 3, 4)) CC_HINT(nonnull (3));
171 static void sql_print_error(sqlite3 *db, int status, char const *fmt, ...)
172 {
173         va_list ap;
174         char *p;
175         int hstatus = SQLITE_OK;
176
177         if (db) {
178                 hstatus = sqlite3_errcode(db);
179                 switch (hstatus & 0xff) {
180                 case SQLITE_OK:
181                 case SQLITE_DONE:
182                 case SQLITE_ROW:
183                         hstatus = SQLITE_OK;
184                         break;
185
186                 default:
187                         break;
188                 }
189         }
190
191         switch (status & 0xff) {
192         case SQLITE_OK:
193         case SQLITE_DONE:
194         case SQLITE_ROW:
195                 status = SQLITE_OK;
196                 break;
197
198         default:
199                 break;
200         }
201
202         /*
203          *      No errors!
204          */
205         if ((hstatus == SQLITE_OK) && (status == SQLITE_OK)) return;
206
207         /*
208          *      At least one error...
209          */
210         va_start(ap, fmt);
211         MEM(p = talloc_vasprintf(NULL, fmt, ap));
212         va_end(ap);
213
214         /*
215          *      Disagreement between handle, and function return code,
216          *      print them both.
217          */
218         if ((status != SQLITE_OK) && (status != hstatus)) {
219 #ifdef HAVE_SQLITE3_ERRSTR
220                 ERROR("rlm_sql_sqlite: %s: Code 0x%04x (%i): %s", p, status, status, sqlite3_errstr(status));
221 #else
222                 ERROR("rlm_sql_sqlite: %s: Code 0x%04x (%i)", p, status, status);
223 #endif
224         }
225
226         if (hstatus != SQLITE_OK) ERROR("rlm_sql_sqlite: %s: Code 0x%04x (%i): %s",
227                                         p, hstatus, hstatus, sqlite3_errmsg(db));
228 }
229
230 #ifdef HAVE_SQLITE3_OPEN_V2
231 static int sql_loadfile(TALLOC_CTX *ctx, sqlite3 *db, char const *filename)
232 {
233         ssize_t         len;
234         int             statement_cnt = 0;
235         char            *buffer;
236         char            *p, *q;
237         int             cl;
238         FILE            *f;
239         struct stat     finfo;
240
241         int status;
242         sqlite3_stmt *statement;
243         char const *z_tail;
244
245         INFO("rlm_sql_sqlite: Executing SQL statements from file \"%s\"", filename);
246
247         f = fopen(filename, "r");
248         if (!f) {
249                 ERROR("rlm_sql_sqlite: Failed opening SQL file \"%s\": %s", filename,
250                        fr_syserror(errno));
251
252                 return -1;
253         }
254
255         if (fstat(fileno(f), &finfo) < 0) {
256                 ERROR("rlm_sql_sqlite: Failed stating SQL file \"%s\": %s", filename,
257                        fr_syserror(errno));
258
259                 fclose(f);
260
261                 return -1;
262         }
263
264         if (finfo.st_size > BOOTSTRAP_MAX) {
265                 too_big:
266                 ERROR("rlm_sql_sqlite: Size of SQL (%zu) file exceeds limit (%uk)",
267                        (size_t) finfo.st_size / 1024, BOOTSTRAP_MAX / 1024);
268
269                 fclose(f);
270
271                 return -1;
272         }
273
274         MEM(buffer = talloc_array(ctx, char, finfo.st_size + 1));
275         len = fread(buffer, sizeof(char), finfo.st_size + 1, f);
276         if (len > finfo.st_size) {
277                 talloc_free(buffer);
278                 goto too_big;
279         }
280
281         if (!len) {
282                 if (ferror(f)) {
283                         ERROR("rlm_sql_sqlite: Error reading SQL file: %s", fr_syserror(errno));
284
285                         fclose(f);
286                         talloc_free(buffer);
287
288                         return -1;
289                 }
290
291                 DEBUG("rlm_sql_sqlite: Ignoring empty SQL file");
292
293                 fclose(f);
294                 talloc_free(buffer);
295
296                 return 0;
297         }
298
299         buffer[len] = '\0';
300         fclose(f);
301
302         /*
303          *      Check if input data is UTF-8.  Allow CR/LF \t, too.
304          */
305         for (p = buffer; p < (buffer + len); p += cl) {
306                 if (*p < ' ') {
307                         if ((*p != 0x0a) && (*p != 0x0d) && (*p != '\t')) break;
308                         cl = 1;
309                 } else {
310                         cl = fr_utf8_char((uint8_t *) p, -1);
311                         if (!cl) break;
312                 }
313         }
314
315         if ((p - buffer) != len) {
316                 ERROR("rlm_sql_sqlite: Bootstrap file contains non-UTF8 char at offset %zu", p - buffer);
317                 talloc_free(buffer);
318                 return -1;
319         }
320
321         /*
322          *      Statement delimiter is ;\n
323          */
324         p = buffer;
325         while ((q = strchr(p, ';'))) {
326                 if ((q[1] != '\n') && (q[1] != '\0')) {
327                         p = q + 1;
328                         statement_cnt++;
329                         continue;
330                 }
331
332 #ifdef HAVE_SQLITE3_PREPARE_V2
333                 status = sqlite3_prepare_v2(db, p, q - p, &statement, &z_tail);
334 #else
335                 status = sqlite3_prepare(db, p, q - p, &statement, &z_tail);
336 #endif
337
338                 if (sql_check_error(db, status) != RLM_SQL_OK) {
339                         sql_print_error(db, status, "Failed preparing statement %i", statement_cnt);
340                         talloc_free(buffer);
341                         return -1;
342                 }
343
344                 status = sqlite3_step(statement);
345                 if (sql_check_error(db, status) != RLM_SQL_OK) {
346                         sql_print_error(db, status, "Failed executing statement %i", statement_cnt);
347                         sqlite3_finalize(statement);
348                         talloc_free(buffer);
349                         return -1;
350                 }
351
352                 status = sqlite3_finalize(statement);
353                 if (sql_check_error(db, status) != RLM_SQL_OK) {
354                         sql_print_error(db, status, "Failed finalizing statement %i", statement_cnt);
355                         talloc_free(buffer);
356                         return -1;
357                 }
358
359                 statement_cnt++;
360                 p = q + 1;
361         }
362
363         talloc_free(buffer);
364         return 0;
365 }
366 #endif
367
368 static int mod_instantiate(CONF_SECTION *conf, rlm_sql_config_t *config)
369 {
370         static bool version_done;
371
372         bool exists;
373         rlm_sql_sqlite_config_t *driver;
374         struct stat buf;
375
376         if (!version_done) {
377                 version_done = true;
378
379                 if (sqlite3_libversion_number() != SQLITE_VERSION_NUMBER) {
380                         WARN("rlm_sql_sqlite: libsqlite version changed since the server was built");
381                         WARN("rlm_sql_sqlite: linked: %s built: %s", sqlite3_libversion(), SQLITE_VERSION);
382                 }
383                 INFO("rlm_sql_sqlite: libsqlite version: %s", sqlite3_libversion());
384         }
385
386         MEM(driver = config->driver = talloc_zero(config, rlm_sql_sqlite_config_t));
387         if (cf_section_parse(conf, driver, driver_config) < 0) {
388                 return -1;
389         }
390         if (!driver->filename) {
391                 MEM(driver->filename = talloc_typed_asprintf(driver, "%s/%s", get_radius_dir(), config->sql_db));
392         }
393
394         if (stat(driver->filename, &buf) == 0) {
395                 exists = true;
396         } else if (errno == ENOENT) {
397                 exists = false;
398         } else {
399                 ERROR("rlm_sql_sqlite: Database exists, but couldn't be opened: %s", fr_syserror(errno));
400                 return -1;
401         }
402
403         if (cf_pair_find(conf, "bootstrap") && !exists) {
404 #  ifdef HAVE_SQLITE3_OPEN_V2
405                 int             status;
406                 int             ret;
407                 char const      *p;
408                 char            *buff;
409                 sqlite3         *db = NULL;
410                 CONF_PAIR       *cp;
411
412                 INFO("rlm_sql_sqlite: Database doesn't exist, creating it and loading schema");
413
414                 p = strrchr(driver->filename, '/');
415                 if (p) {
416                         size_t len = (p - driver->filename) + 1;
417
418                         buff = talloc_array(conf, char, len);
419                         strlcpy(buff, driver->filename, len);
420                 } else {
421                         MEM(buff = talloc_typed_strdup(conf, driver->filename));
422                 }
423
424                 ret = rad_mkdir(buff, 0700, -1, -1);
425                 talloc_free(buff);
426                 if (ret < 0) {
427                         ERROR("rlm_sql_sqlite: Failed creating directory for SQLite database: %s", fr_syserror(errno));
428
429                         return -1;
430                 };
431
432                 status = sqlite3_open_v2(driver->filename, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
433                 if (!db) {
434 #    ifdef HAVE_SQLITE3_ERRSTR
435                         ERROR("rlm_sql_sqlite: Failed creating opening/creating SQLite database: %s",
436                               sqlite3_errstr(status));
437 #    else
438                         ERROR("rlm_sql_sqlite: Failed creating opening/creating SQLite database, got code (%i)",
439                               status);
440 #    endif
441
442                         goto unlink;
443                 }
444
445                 if (sql_check_error(db, status) != RLM_SQL_OK) {
446                         (void) sqlite3_close(db);
447
448                         goto unlink;
449                 }
450
451                 /*
452                  *      Execute multiple bootstrap SQL files in order
453                  */
454                 for (cp = cf_pair_find(conf, "bootstrap");
455                      cp;
456                      cp = cf_pair_find_next(conf, cp, "bootstrap")) {
457                         p = cf_pair_value(cp);
458                         if (!p) continue;
459
460                         ret = sql_loadfile(conf, db, p);
461                         if (ret < 0) goto unlink;
462                 }
463
464                 status = sqlite3_close(db);
465                 if (status != SQLITE_OK) {
466                 /*
467                  *      Safer to use sqlite3_errstr here, just in case the handle is in a weird state
468                  */
469 #  ifdef HAVE_SQLITE3_ERRSTR
470                         ERROR("rlm_sql_sqlite: Error closing SQLite handle: %s", sqlite3_errstr(status));
471 #  else
472                         ERROR("rlm_sql_sqlite: Error closing SQLite handle, got code (%i)", status);
473 #  endif
474
475                         goto unlink;
476                 }
477
478                 if (ret < 0) {
479                 unlink:
480                         if ((unlink(driver->filename) < 0) && (errno != ENOENT)) {
481                                 ERROR("rlm_sql_sqlite: Error removing partially initialised database: %s",
482                                       fr_syserror(errno));
483                         }
484                         return -1;
485                 }
486 #else
487                 WARN("rlm_sql_sqlite: sqlite3_open_v2() not available, cannot bootstrap database. "
488                        "Upgrade to SQLite >= 3.5.1 if you need this functionality");
489 #endif
490         }
491
492         return 0;
493 }
494
495 static int _sql_socket_destructor(rlm_sql_sqlite_conn_t *conn)
496 {
497         int status = 0;
498
499         DEBUG2("rlm_sql_sqlite: Socket destructor called, closing socket");
500
501         if (conn->db) {
502                 status = sqlite3_close(conn->db);
503                 if (status != SQLITE_OK) WARN("rlm_sql_sqlite: Got SQLite error code (%u) when closing socket", status);
504         }
505
506         return 0;
507 }
508
509 static void _sql_greatest(sqlite3_context *ctx, int num_values, sqlite3_value **values)
510 {
511         int i;
512         sqlite3_int64 value, max = 0;
513
514         for (i = 0; i < num_values; i++) {
515                 value = sqlite3_value_int64(values[i]);
516                 if (value > max) {
517                         max = value;
518                 }
519         }
520
521         sqlite3_result_int64(ctx, max);
522 }
523
524 static sql_rcode_t sql_socket_init(rlm_sql_handle_t *handle, rlm_sql_config_t *config)
525 {
526         rlm_sql_sqlite_conn_t *conn;
527         rlm_sql_sqlite_config_t *driver = config->driver;
528
529         int status;
530
531         MEM(conn = handle->conn = talloc_zero(handle, rlm_sql_sqlite_conn_t));
532         talloc_set_destructor(conn, _sql_socket_destructor);
533
534         INFO("rlm_sql_sqlite: Opening SQLite database \"%s\"", driver->filename);
535 #ifdef HAVE_SQLITE3_OPEN_V2
536         status = sqlite3_open_v2(driver->filename, &(conn->db), SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, NULL);
537 #else
538         status = sqlite3_open(driver->filename, &(conn->db));
539 #endif
540
541         if (!conn->db || (sql_check_error(conn->db, status) != RLM_SQL_OK)) {
542                 sql_print_error(conn->db, status, "Error opening SQLite database \"%s\"", driver->filename);
543                 return RLM_SQL_ERROR;
544         }
545         status = sqlite3_busy_timeout(conn->db, driver->busy_timeout);
546         if (sql_check_error(conn->db, status) != RLM_SQL_OK) {
547                 sql_print_error(conn->db, status, "Error setting busy timeout");
548                 return RLM_SQL_ERROR;
549         }
550
551         /*
552          *      Enable extended return codes for extra debugging info.
553          */
554 #ifdef HAVE_SQLITE3_EXTENDED_RESULT_CODES
555         status = sqlite3_extended_result_codes(conn->db, 1);
556         if (sql_check_error(conn->db, status) != RLM_SQL_OK) {
557                 sql_print_error(conn->db, status, "Error enabling extended result codes");
558                 return RLM_SQL_ERROR;
559         }
560 #endif
561
562 #ifdef HAVE_SQLITE3_CREATE_FUNCTION_V2
563         status = sqlite3_create_function_v2(conn->db, "GREATEST", -1, SQLITE_ANY, NULL,
564                                             _sql_greatest, NULL, NULL, NULL);
565 #else
566         status = sqlite3_create_function(conn->db, "GREATEST", -1, SQLITE_ANY, NULL,
567                                          _sql_greatest, NULL, NULL);
568 #endif
569         if (sql_check_error(conn->db, status) != RLM_SQL_OK) {
570                 sql_print_error(conn->db, status, "Failed registering 'GREATEST' sql function");
571                 return RLM_SQL_ERROR;
572         }
573
574         return RLM_SQL_OK;
575 }
576
577 static sql_rcode_t sql_select_query(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config, char const *query)
578 {
579         rlm_sql_sqlite_conn_t   *conn = handle->conn;
580         char const              *z_tail;
581         int                     status;
582
583 #ifdef HAVE_SQLITE3_PREPARE_V2
584         status = sqlite3_prepare_v2(conn->db, query, strlen(query), &conn->statement, &z_tail);
585 #else
586         status = sqlite3_prepare(conn->db, query, strlen(query), &conn->statement, &z_tail);
587 #endif
588
589         conn->col_count = 0;
590
591         return sql_check_error(conn->db, status);
592 }
593
594
595 static sql_rcode_t sql_query(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config, char const *query)
596 {
597
598         sql_rcode_t             rcode;
599         rlm_sql_sqlite_conn_t   *conn = handle->conn;
600         char const              *z_tail;
601         int                     status;
602
603 #ifdef HAVE_SQLITE3_PREPARE_V2
604         status = sqlite3_prepare_v2(conn->db, query, strlen(query), &conn->statement, &z_tail);
605 #else
606         status = sqlite3_prepare(conn->db, query, strlen(query), &conn->statement, &z_tail);
607 #endif
608         rcode = sql_check_error(conn->db, status);
609         if (rcode != RLM_SQL_OK) return rcode;
610
611         status = sqlite3_step(conn->statement);
612         return sql_check_error(conn->db, status);
613 }
614
615 static int sql_num_fields(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config)
616 {
617         rlm_sql_sqlite_conn_t *conn = handle->conn;
618
619         if (conn->statement) {
620                 return sqlite3_column_count(conn->statement);
621         }
622
623         return 0;
624 }
625
626 static int sql_num_rows(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config)
627 {
628         rlm_sql_sqlite_conn_t *conn = handle->conn;
629
630         if (conn->statement) {
631                 return sqlite3_data_count(conn->statement);
632         }
633
634         return 0;
635 }
636
637 static sql_rcode_t sql_fields(char const **out[], rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config)
638 {
639         rlm_sql_sqlite_conn_t *conn = handle->conn;
640
641         int             fields, i;
642         char const      **names;
643
644         fields = sqlite3_column_count(conn->statement);
645         if (fields <= 0) return RLM_SQL_ERROR;
646
647         MEM(names = talloc_zero_array(handle, char const *, fields + 1));
648
649         for (i = 0; i < fields; i++) names[i] = sqlite3_column_name(conn->statement, i);
650         *out = names;
651
652         return RLM_SQL_OK;
653 }
654
655 static sql_rcode_t sql_fetch_row(rlm_sql_handle_t *handle, rlm_sql_config_t *config)
656 {
657         int status;
658         rlm_sql_sqlite_conn_t *conn = handle->conn;
659
660         int i = 0;
661
662         char **row;
663
664         TALLOC_FREE(handle->row);
665
666         /*
667          *      Executes the SQLite query and interates over the results
668          */
669         status = sqlite3_step(conn->statement);
670
671         /*
672          *      Error getting next row
673          */
674         if (sql_check_error(conn->db, status) != RLM_SQL_OK) return RLM_SQL_ERROR;
675
676         /*
677          *      No more rows to process (were done)
678          */
679         if (status == SQLITE_DONE) return RLM_SQL_NO_MORE_ROWS;
680
681         /*
682          *      We only need to do this once per result set, because
683          *      the number of columns won't change.
684          */
685         if (conn->col_count == 0) {
686                 conn->col_count = sql_num_fields(handle, config);
687                 if (conn->col_count == 0) return RLM_SQL_ERROR;
688         }
689
690         MEM(row = handle->row = talloc_zero_array(handle->conn, char *, conn->col_count + 1));
691
692         for (i = 0; i < conn->col_count; i++) {
693                 switch (sqlite3_column_type(conn->statement, i)) {
694                 case SQLITE_INTEGER:
695                         MEM(row[i] = talloc_typed_asprintf(row, "%d", sqlite3_column_int(conn->statement, i)));
696                         break;
697
698                 case SQLITE_FLOAT:
699                         MEM(row[i] = talloc_typed_asprintf(row, "%f", sqlite3_column_double(conn->statement, i)));
700                         break;
701
702                 case SQLITE_TEXT:
703                 {
704                         char const *p;
705                         p = (char const *) sqlite3_column_text(conn->statement, i);
706
707                         if (p) MEM(row[i] = talloc_typed_strdup(row, p));
708                 }
709                         break;
710
711                 case SQLITE_BLOB:
712                 {
713                         uint8_t const *p;
714                         size_t len;
715
716                         p = sqlite3_column_blob(conn->statement, i);
717                         if (p) {
718                                 len = sqlite3_column_bytes(conn->statement, i);
719
720                                 MEM(row[i] = talloc_zero_array(row, char, len + 1));
721                                 memcpy(row[i], p, len);
722                         }
723                 }
724                         break;
725
726                 default:
727                         break;
728                 }
729         }
730
731         return RLM_SQL_OK;
732 }
733
734 static sql_rcode_t sql_free_result(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config)
735 {
736         rlm_sql_sqlite_conn_t *conn = handle->conn;
737
738         if (conn->statement) {
739                 TALLOC_FREE(handle->row);
740
741                 (void) sqlite3_finalize(conn->statement);
742                 conn->statement = NULL;
743                 conn->col_count = 0;
744         }
745
746         /*
747          *      There's no point in checking the code returned by finalize
748          *      as it'll have already been encountered elsewhere in the code.
749          *
750          *      It's just the last error that occurred processing the
751          *      statement.
752          */
753         return RLM_SQL_OK;
754 }
755
756 /** Retrieves any errors associated with the connection handle
757  *
758  * @note Caller will free any memory allocated in ctx.
759  *
760  * @param ctx to allocate temporary error buffers in.
761  * @param out Array of sql_log_entrys to fill.
762  * @param outlen Length of out array.
763  * @param handle rlm_sql connection handle.
764  * @param config rlm_sql config.
765  * @return number of errors written to the sql_log_entry array.
766  */
767 static size_t sql_error(UNUSED TALLOC_CTX *ctx, sql_log_entry_t out[], size_t outlen,
768                         rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config)
769 {
770         rlm_sql_sqlite_conn_t *conn = handle->conn;
771         char const *error;
772
773         rad_assert(outlen > 0);
774
775         error = sqlite3_errmsg(conn->db);
776         if (!error) return 0;
777
778         out[0].type = L_ERR;
779         out[0].msg = error;
780
781         return 1;
782 }
783
784 static sql_rcode_t sql_finish_query(rlm_sql_handle_t *handle, rlm_sql_config_t *config)
785 {
786         return sql_free_result(handle, config);
787 }
788
789 static int sql_affected_rows(rlm_sql_handle_t *handle,
790                              UNUSED rlm_sql_config_t *config)
791 {
792         rlm_sql_sqlite_conn_t *conn = handle->conn;
793
794         if (conn->db) return sqlite3_changes(conn->db);
795
796         return -1;
797 }
798
799
800 /* Exported to rlm_sql */
801 extern rlm_sql_module_t rlm_sql_sqlite;
802 rlm_sql_module_t rlm_sql_sqlite = {
803         .name                           = "rlm_sql_sqlite",
804         .flags                          = RLM_SQL_RCODE_FLAGS_ALT_QUERY,
805         .mod_instantiate                = mod_instantiate,
806         .sql_socket_init                = sql_socket_init,
807         .sql_query                      = sql_query,
808         .sql_select_query               = sql_select_query,
809         .sql_num_fields                 = sql_num_fields,
810         .sql_num_rows                   = sql_num_rows,
811         .sql_affected_rows              = sql_affected_rows,
812         .sql_fetch_row                  = sql_fetch_row,
813         .sql_fields                     = sql_fields,
814         .sql_free_result                = sql_free_result,
815         .sql_error                      = sql_error,
816         .sql_finish_query               = sql_finish_query,
817         .sql_finish_select_query        = sql_finish_query
818 };