blob: df52f9bd6b985cf9b0e7a642c824337af49830bd [file] [log] [blame]
Harald Weltee72cf552016-04-28 07:18:49 +02001/* (C) 2015 by Harald Welte <laforge@gnumonks.org>
2 *
3 * All Rights Reserved
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20#include <osmocom/core/utils.h>
21
Max00b37152017-02-20 11:09:27 +010022#include <stdbool.h>
Harald Weltee72cf552016-04-28 07:18:49 +020023#include <sqlite3.h>
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +020024#include <string.h>
Harald Weltee72cf552016-04-28 07:18:49 +020025
26#include "logging.h"
27#include "db.h"
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +020028#include "db_bootstrap.h"
Harald Weltee72cf552016-04-28 07:18:49 +020029
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +010030#define CURRENT_SCHEMA_VERSION 0
31
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020032#define SEL_COLUMNS \
33 "id," \
34 "imsi," \
35 "msisdn," \
36 "vlr_number," \
37 "sgsn_number," \
38 "sgsn_address," \
39 "periodic_lu_tmr," \
40 "periodic_rau_tau_tmr," \
41 "nam_cs," \
42 "nam_ps," \
43 "lmsi," \
44 "ms_purged_cs," \
45 "ms_purged_ps"
46
Harald Weltee72cf552016-04-28 07:18:49 +020047static const char *stmt_sql[] = {
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020048 [DB_STMT_SEL_BY_IMSI] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE imsi = ?",
49 [DB_STMT_SEL_BY_MSISDN] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE msisdn = ?",
50 [DB_STMT_SEL_BY_ID] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE id = ?",
Neels Hofmeyrdd783052017-10-09 17:36:08 +020051 [DB_STMT_UPD_VLR_BY_ID] = "UPDATE subscriber SET vlr_number = $number WHERE id = $subscriber_id",
52 [DB_STMT_UPD_SGSN_BY_ID] = "UPDATE subscriber SET sgsn_number = $number WHERE id = $subscriber_id",
Neels Hofmeyr0cac0a02017-10-09 17:47:21 +020053 [DB_STMT_AUC_BY_IMSI] =
54 "SELECT id, algo_id_2g, ki, algo_id_3g, k, op, opc, sqn, ind_bitlen"
55 " FROM subscriber"
56 " LEFT JOIN auc_2g ON auc_2g.subscriber_id = subscriber.id"
57 " LEFT JOIN auc_3g ON auc_3g.subscriber_id = subscriber.id"
Neels Hofmeyrc5122f22017-10-09 23:12:57 +020058 " WHERE imsi = $imsi",
Neels Hofmeyr1cbdb702017-10-09 23:03:57 +020059 [DB_STMT_AUC_UPD_SQN] = "UPDATE auc_3g SET sqn = $sqn WHERE subscriber_id = $subscriber_id",
Neels Hofmeyre50121e2017-10-09 17:48:51 +020060 [DB_STMT_UPD_PURGE_CS_BY_IMSI] = "UPDATE subscriber SET ms_purged_cs = $val WHERE imsi = $imsi",
61 [DB_STMT_UPD_PURGE_PS_BY_IMSI] = "UPDATE subscriber SET ms_purged_ps = $val WHERE imsi = $imsi",
Neels Hofmeyre8ccd502017-10-06 04:10:06 +020062 [DB_STMT_UPD_NAM_CS_BY_IMSI] = "UPDATE subscriber SET nam_cs = $val WHERE imsi = $imsi",
63 [DB_STMT_UPD_NAM_PS_BY_IMSI] = "UPDATE subscriber SET nam_ps = $val WHERE imsi = $imsi",
Neels Hofmeyrf7c3e6e2017-10-09 17:55:16 +020064 [DB_STMT_SUBSCR_CREATE] = "INSERT INTO subscriber (imsi) VALUES ($imsi)",
65 [DB_STMT_DEL_BY_ID] = "DELETE FROM subscriber WHERE id = $subscriber_id",
66 [DB_STMT_SET_MSISDN_BY_IMSI] = "UPDATE subscriber SET msisdn = $msisdn WHERE imsi = $imsi",
Neels Hofmeyra820ea12018-12-02 19:46:46 +010067 [DB_STMT_DELETE_MSISDN_BY_IMSI] = "UPDATE subscriber SET msisdn = NULL WHERE imsi = $imsi",
Neels Hofmeyr1332a172017-10-10 02:25:00 +020068 [DB_STMT_AUC_2G_INSERT] =
69 "INSERT INTO auc_2g (subscriber_id, algo_id_2g, ki)"
70 " VALUES($subscriber_id, $algo_id_2g, $ki)",
71 [DB_STMT_AUC_2G_DELETE] = "DELETE FROM auc_2g WHERE subscriber_id = $subscriber_id",
72 [DB_STMT_AUC_3G_INSERT] =
73 "INSERT INTO auc_3g (subscriber_id, algo_id_3g, k, op, opc, ind_bitlen)"
74 " VALUES($subscriber_id, $algo_id_3g, $k, $op, $opc, $ind_bitlen)",
75 [DB_STMT_AUC_3G_DELETE] = "DELETE FROM auc_3g WHERE subscriber_id = $subscriber_id",
Harald Weltee72cf552016-04-28 07:18:49 +020076};
77
78static void sql3_error_log_cb(void *arg, int err_code, const char *msg)
79{
80 LOGP(DDB, LOGL_ERROR, "(%d) %s\n", err_code, msg);
81}
82
83static void sql3_sql_log_cb(void *arg, sqlite3 *s3, const char *stmt, int type)
84{
85 switch (type) {
86 case 0:
87 LOGP(DDB, LOGL_DEBUG, "Opened database\n");
88 break;
89 case 1:
Max58d4a842017-02-20 11:06:12 +010090 LOGP(DDB, LOGL_DEBUG, "%s\n", stmt);
Harald Weltee72cf552016-04-28 07:18:49 +020091 break;
92 case 2:
93 LOGP(DDB, LOGL_DEBUG, "Closed database\n");
94 break;
95 default:
96 LOGP(DDB, LOGL_DEBUG, "Unknown %d\n", type);
97 break;
98 }
99}
100
Max00b37152017-02-20 11:09:27 +0100101/* remove bindings and reset statement to be re-executed */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200102void db_remove_reset(sqlite3_stmt *stmt)
Max00b37152017-02-20 11:09:27 +0100103{
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200104 sqlite3_clear_bindings(stmt);
Neels Hofmeyr4f3841c2017-11-07 13:24:44 +0100105 /* sqlite3_reset() just repeats an error code already evaluated during sqlite3_step(). */
106 /* coverity[CHECKED_RETURN] */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200107 sqlite3_reset(stmt);
Max00b37152017-02-20 11:09:27 +0100108}
109
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200110/** bind text arg and do proper cleanup in case of failure. If param_name is
111 * NULL, bind to the first parameter (useful for SQL statements that have only
112 * one parameter). */
113bool db_bind_text(sqlite3_stmt *stmt, const char *param_name, const char *text)
Max00b37152017-02-20 11:09:27 +0100114{
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200115 int rc;
116 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
117 if (idx < 1) {
118 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
119 param_name);
120 return false;
121 }
122 rc = sqlite3_bind_text(stmt, idx, text, -1, SQLITE_STATIC);
Max00b37152017-02-20 11:09:27 +0100123 if (rc != SQLITE_OK) {
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200124 LOGP(DDB, LOGL_ERROR, "Error binding text to SQL parameter %s: %d\n",
125 param_name ? param_name : "#1", rc);
Max00b37152017-02-20 11:09:27 +0100126 db_remove_reset(stmt);
127 return false;
128 }
Max00b37152017-02-20 11:09:27 +0100129 return true;
130}
131
Neels Hofmeyr28da26e2017-10-06 03:44:57 +0200132/** bind int arg and do proper cleanup in case of failure. If param_name is
133 * NULL, bind to the first parameter (useful for SQL statements that have only
134 * one parameter). */
135bool db_bind_int(sqlite3_stmt *stmt, const char *param_name, int nr)
136{
137 int rc;
138 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
139 if (idx < 1) {
140 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
141 param_name);
142 return false;
143 }
144 rc = sqlite3_bind_int(stmt, idx, nr);
145 if (rc != SQLITE_OK) {
146 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
147 param_name ? param_name : "#1", rc);
148 db_remove_reset(stmt);
149 return false;
150 }
151 return true;
152}
153
154/** bind int64 arg and do proper cleanup in case of failure. If param_name is
155 * NULL, bind to the first parameter (useful for SQL statements that have only
156 * one parameter). */
157bool db_bind_int64(sqlite3_stmt *stmt, const char *param_name, int64_t nr)
158{
159 int rc;
160 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
161 if (idx < 1) {
162 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
163 param_name);
164 return false;
165 }
166 rc = sqlite3_bind_int64(stmt, idx, nr);
167 if (rc != SQLITE_OK) {
168 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
169 param_name ? param_name : "#1", rc);
170 db_remove_reset(stmt);
171 return false;
172 }
173 return true;
174}
175
Harald Weltee72cf552016-04-28 07:18:49 +0200176void db_close(struct db_context *dbc)
177{
178 unsigned int i;
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700179 int rc;
Harald Weltee72cf552016-04-28 07:18:49 +0200180
181 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
182 /* it is ok to call finalize on NULL */
183 sqlite3_finalize(dbc->stmt[i]);
184 }
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700185
186 /* Ask sqlite3 to close DB */
187 rc = sqlite3_close(dbc->db);
188 if (rc != SQLITE_OK) { /* Make sure it's actually closed! */
189 LOGP(DDB, LOGL_ERROR, "Couldn't close database: (rc=%d) %s\n",
190 rc, sqlite3_errmsg(dbc->db));
191 }
192
Harald Weltee72cf552016-04-28 07:18:49 +0200193 talloc_free(dbc);
194}
195
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200196static int db_bootstrap(struct db_context *dbc)
197{
198 int i;
199 for (i = 0; i < ARRAY_SIZE(stmt_bootstrap_sql); i++) {
200 int rc;
201 sqlite3_stmt *stmt;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100202 rc = sqlite3_prepare_v2(dbc->db, stmt_bootstrap_sql[i], -1, &stmt, NULL);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200203 if (rc != SQLITE_OK) {
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100204 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_bootstrap_sql[i]);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700205 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200206 }
207
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200208 rc = sqlite3_step(stmt);
209 db_remove_reset(stmt);
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700210 sqlite3_finalize(stmt);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200211 if (rc != SQLITE_DONE) {
212 LOGP(DDB, LOGL_ERROR, "Cannot bootstrap database: SQL error: (%d) %s,"
213 " during stmt '%s'",
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100214 rc, sqlite3_errmsg(dbc->db), stmt_bootstrap_sql[i]);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700215 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200216 }
217 }
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700218 return SQLITE_OK;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200219}
220
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100221/* https://www.sqlite.org/fileformat2.html#storage_of_the_sql_database_schema */
222static bool db_table_exists(struct db_context *dbc, const char *table_name)
223{
224 const char *table_exists_sql = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
225 sqlite3_stmt *stmt;
226 int rc;
227
228 rc = sqlite3_prepare_v2(dbc->db, table_exists_sql, -1, &stmt, NULL);
229 if (rc != SQLITE_OK) {
230 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", table_exists_sql);
231 return false;
232 }
233
234 if (!db_bind_text(stmt, NULL, table_name))
235 return false;
236
237 rc = sqlite3_step(stmt);
238 db_remove_reset(stmt);
239 sqlite3_finalize(stmt);
240 return (rc == SQLITE_ROW);
241}
242
243/* Indicate whether the database is initialized with tables for schema version 0.
244 * We only check for the 'subscriber' table here because Neels said so. */
245static bool db_is_bootstrapped_v0(struct db_context *dbc)
246{
247 if (!db_table_exists(dbc, "subscriber")) {
248 LOGP(DDB, LOGL_DEBUG, "Table 'subscriber' not found in database '%s'\n", dbc->fname);
249 return false;
250 }
251
252 return true;
253}
254
255static int db_get_user_version(struct db_context *dbc)
256{
257 const char *user_version_sql = "PRAGMA user_version";
258 sqlite3_stmt *stmt;
259 int version, rc;
260
261 rc = sqlite3_prepare_v2(dbc->db, user_version_sql, -1, &stmt, NULL);
262 if (rc != SQLITE_OK) {
263 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", user_version_sql);
264 return -1;
265 }
266 rc = sqlite3_step(stmt);
267 if (rc == SQLITE_ROW) {
268 version = sqlite3_column_int(stmt, 0);
269 } else {
270 LOGP(DDB, LOGL_ERROR, "SQL statement '%s' failed: %d\n", user_version_sql, rc);
271 version = -1;
272 }
273
274 db_remove_reset(stmt);
275 sqlite3_finalize(stmt);
276 return version;
277}
278
279struct db_context *db_open(void *ctx, const char *fname, bool enable_sqlite_logging, bool allow_upgrade)
Harald Weltee72cf552016-04-28 07:18:49 +0200280{
281 struct db_context *dbc = talloc_zero(ctx, struct db_context);
282 unsigned int i;
283 int rc;
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200284 bool has_sqlite_config_sqllog = false;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100285 int version;
Harald Weltee72cf552016-04-28 07:18:49 +0200286
Neels Hofmeyr7f9491f2017-01-30 13:30:47 +0100287 LOGP(DDB, LOGL_NOTICE, "using database: %s\n", fname);
Harald Weltee72cf552016-04-28 07:18:49 +0200288 LOGP(DDB, LOGL_INFO, "Compiled against SQLite3 lib version %s\n", SQLITE_VERSION);
289 LOGP(DDB, LOGL_INFO, "Running with SQLite3 lib version %s\n", sqlite3_libversion());
290
291 dbc->fname = talloc_strdup(dbc, fname);
292
293 for (i = 0; i < 0xfffff; i++) {
294 const char *o = sqlite3_compileoption_get(i);
295 if (!o)
296 break;
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200297 LOGP(DDB, LOGL_DEBUG, "SQLite3 compiled with '%s'\n", o);
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200298 if (!strcmp(o, "ENABLE_SQLLOG"))
299 has_sqlite_config_sqllog = true;
Harald Weltee72cf552016-04-28 07:18:49 +0200300 }
301
Neels Hofmeyrd3814b92017-11-21 12:28:07 +0100302 if (enable_sqlite_logging) {
303 rc = sqlite3_config(SQLITE_CONFIG_LOG, sql3_error_log_cb, NULL);
304 if (rc != SQLITE_OK)
305 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 error log callback\n");
306 }
Harald Weltee72cf552016-04-28 07:18:49 +0200307
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200308 if (has_sqlite_config_sqllog) {
309 rc = sqlite3_config(SQLITE_CONFIG_SQLLOG, sql3_sql_log_cb, NULL);
310 if (rc != SQLITE_OK)
311 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 SQL log callback\n");
312 } else
313 LOGP(DDB, LOGL_DEBUG, "Not setting SQL log callback:"
314 " SQLite3 compiled without support for it\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200315
316 rc = sqlite3_open(dbc->fname, &dbc->db);
317 if (rc != SQLITE_OK) {
318 LOGP(DDB, LOGL_ERROR, "Unable to open DB; rc = %d\n", rc);
319 talloc_free(dbc);
320 return NULL;
321 }
322
323 /* enable extended result codes */
324 rc = sqlite3_extended_result_codes(dbc->db, 1);
325 if (rc != SQLITE_OK)
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200326 LOGP(DDB, LOGL_ERROR, "Unable to enable SQLite3 extended result codes\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200327
Harald Welteabd1a542016-05-03 18:50:41 +0200328 char *err_msg;
329 rc = sqlite3_exec(dbc->db, "PRAGMA journal_mode=WAL; PRAGMA synchonous = NORMAL;", 0, 0, &err_msg);
330 if (rc != SQLITE_OK)
331 LOGP(DDB, LOGL_ERROR, "Unable to set Write-Ahead Logging: %s\n",
332 err_msg);
333
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100334 version = db_get_user_version(dbc);
335 if (version < 0) {
336 LOGP(DDB, LOGL_ERROR, "Unable to read user version number from database '%s'\n", dbc->fname);
337 goto out_free;
338 }
339
340 /* An empty database will always report version zero. */
341 if (version == 0 && !db_is_bootstrapped_v0(dbc)) {
342 LOGP(DDB, LOGL_NOTICE, "Missing database tables detected; Bootstrapping database '%s'\n", dbc->fname);
343 rc = db_bootstrap(dbc);
344 if (rc != SQLITE_OK) {
345 LOGP(DDB, LOGL_ERROR, "Failed to bootstrap DB: (rc=%d) %s\n",
346 rc, sqlite3_errmsg(dbc->db));
347 goto out_free;
348 }
349 }
350
351 LOGP(DDB, LOGL_NOTICE, "Database '%s' has HLR DB schema version %d\n", dbc->fname, version);
352
353 if (version < CURRENT_SCHEMA_VERSION && allow_upgrade) {
354 /* Future version upgrades will happen here. */
355 }
356
357 if (version != CURRENT_SCHEMA_VERSION) {
358 if (version < CURRENT_SCHEMA_VERSION) {
359 LOGP(DDB, LOGL_NOTICE, "HLR DB schema version %d is outdated\n", version);
360 if (!allow_upgrade) {
361 LOGP(DDB, LOGL_ERROR, "Not upgrading HLR database to schema version %d; "
362 "use the --db-upgrade option to allow HLR database upgrades\n",
363 CURRENT_SCHEMA_VERSION);
364 }
365 } else
366 LOGP(DDB, LOGL_ERROR, "HLR DB schema version %d is unknown\n", version);
367
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700368 goto out_free;
369 }
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200370
Harald Weltee72cf552016-04-28 07:18:49 +0200371 /* prepare all SQL statements */
372 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
373 rc = sqlite3_prepare_v2(dbc->db, stmt_sql[i], -1,
374 &dbc->stmt[i], NULL);
375 if (rc != SQLITE_OK) {
376 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_sql[i]);
377 goto out_free;
378 }
379 }
380
381 return dbc;
382out_free:
383 db_close(dbc);
384 return NULL;
385}