blob: 4fd2654c86257059458f9ae797ffaa2da0862d03 [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
Neels Hofmeyr2f758032019-11-20 00:37:07 +010026#include <osmocom/hlr/logging.h>
27#include <osmocom/hlr/db.h>
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +020028#include "db_bootstrap.h"
Harald Weltee72cf552016-04-28 07:18:49 +020029
Stefan Sperling638ba8c2018-12-04 15:07:29 +010030/* This constant is currently duplicated in sql/hlr.sql and must be kept in sync! */
Neels Hofmeyr04c23752019-11-25 03:59:50 +010031#define CURRENT_SCHEMA_VERSION 5
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +010032
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020033#define SEL_COLUMNS \
34 "id," \
35 "imsi," \
36 "msisdn," \
Oliver Smith81db3892019-01-09 12:03:51 +010037 "imei," \
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020038 "vlr_number," \
39 "sgsn_number," \
40 "sgsn_address," \
41 "periodic_lu_tmr," \
42 "periodic_rau_tau_tmr," \
43 "nam_cs," \
44 "nam_ps," \
45 "lmsi," \
46 "ms_purged_cs," \
Stefan Sperling638ba8c2018-12-04 15:07:29 +010047 "ms_purged_ps," \
Neels Hofmeyr07e16022019-11-20 02:36:35 +010048 "last_lu_seen," \
Neels Hofmeyr04c23752019-11-25 03:59:50 +010049 "last_lu_seen_ps," \
50 "vlr_via_proxy," \
51 "sgsn_via_proxy"
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020052
Harald Weltee72cf552016-04-28 07:18:49 +020053static const char *stmt_sql[] = {
Keith89fda302021-01-19 07:01:33 +010054 [DB_STMT_SEL_ALL] = "SELECT " SEL_COLUMNS " FROM subscriber;",
55 [DB_STMT_SEL_ALL_ORDER_LAST_SEEN] = "SELECT " SEL_COLUMNS " FROM subscriber "
56 "WHERE last_lu_seen IS NOT NULL ORDER BY last_lu_seen;",
57 [DB_STMT_SEL_FILTER_MSISDN] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE msisdn LIKE $search ORDER BY msisdn",
58 [DB_STMT_SEL_FILTER_IMSI] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE imsi LIKE $search ORDER BY imsi",
Keithca8e6ef2021-05-07 05:59:21 +020059 [DB_STMT_SEL_FILTER_IMEI] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE imei LIKE $search ORDER BY imei",
Keith89fda302021-01-19 07:01:33 +010060 [DB_STMT_SEL_FILTER_CS] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE nam_cs = $search ORDER BY last_lu_seen",
61 [DB_STMT_SEL_FILTER_PS] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE nam_ps = $search ORDER BY last_lu_seen",
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020062 [DB_STMT_SEL_BY_IMSI] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE imsi = ?",
63 [DB_STMT_SEL_BY_MSISDN] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE msisdn = ?",
64 [DB_STMT_SEL_BY_ID] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE id = ?",
Oliver Smith81db3892019-01-09 12:03:51 +010065 [DB_STMT_SEL_BY_IMEI] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE imei = ?",
Neels Hofmeyr04c23752019-11-25 03:59:50 +010066 [DB_STMT_UPD_VLR_BY_ID] = "UPDATE subscriber SET vlr_number = $number, vlr_via_proxy = $proxy WHERE id = $subscriber_id",
67 [DB_STMT_UPD_SGSN_BY_ID] = "UPDATE subscriber SET sgsn_number = $number, sgsn_via_proxy = $proxy WHERE id = $subscriber_id",
Oliver Smith81db3892019-01-09 12:03:51 +010068 [DB_STMT_UPD_IMEI_BY_IMSI] = "UPDATE subscriber SET imei = $imei WHERE imsi = $imsi",
Neels Hofmeyr0cac0a02017-10-09 17:47:21 +020069 [DB_STMT_AUC_BY_IMSI] =
70 "SELECT id, algo_id_2g, ki, algo_id_3g, k, op, opc, sqn, ind_bitlen"
71 " FROM subscriber"
72 " LEFT JOIN auc_2g ON auc_2g.subscriber_id = subscriber.id"
73 " LEFT JOIN auc_3g ON auc_3g.subscriber_id = subscriber.id"
Neels Hofmeyrc5122f22017-10-09 23:12:57 +020074 " WHERE imsi = $imsi",
Neels Hofmeyr1cbdb702017-10-09 23:03:57 +020075 [DB_STMT_AUC_UPD_SQN] = "UPDATE auc_3g SET sqn = $sqn WHERE subscriber_id = $subscriber_id",
Neels Hofmeyre50121e2017-10-09 17:48:51 +020076 [DB_STMT_UPD_PURGE_CS_BY_IMSI] = "UPDATE subscriber SET ms_purged_cs = $val WHERE imsi = $imsi",
77 [DB_STMT_UPD_PURGE_PS_BY_IMSI] = "UPDATE subscriber SET ms_purged_ps = $val WHERE imsi = $imsi",
Neels Hofmeyre8ccd502017-10-06 04:10:06 +020078 [DB_STMT_UPD_NAM_CS_BY_IMSI] = "UPDATE subscriber SET nam_cs = $val WHERE imsi = $imsi",
79 [DB_STMT_UPD_NAM_PS_BY_IMSI] = "UPDATE subscriber SET nam_ps = $val WHERE imsi = $imsi",
Oliver Smithcd2af5e2019-03-06 13:17:39 +010080 [DB_STMT_SUBSCR_CREATE] = "INSERT INTO subscriber (imsi, nam_cs, nam_ps) VALUES ($imsi, $nam_cs, $nam_ps)",
Neels Hofmeyrf7c3e6e2017-10-09 17:55:16 +020081 [DB_STMT_DEL_BY_ID] = "DELETE FROM subscriber WHERE id = $subscriber_id",
82 [DB_STMT_SET_MSISDN_BY_IMSI] = "UPDATE subscriber SET msisdn = $msisdn WHERE imsi = $imsi",
Neels Hofmeyra820ea12018-12-02 19:46:46 +010083 [DB_STMT_DELETE_MSISDN_BY_IMSI] = "UPDATE subscriber SET msisdn = NULL WHERE imsi = $imsi",
Neels Hofmeyr1332a172017-10-10 02:25:00 +020084 [DB_STMT_AUC_2G_INSERT] =
85 "INSERT INTO auc_2g (subscriber_id, algo_id_2g, ki)"
86 " VALUES($subscriber_id, $algo_id_2g, $ki)",
87 [DB_STMT_AUC_2G_DELETE] = "DELETE FROM auc_2g WHERE subscriber_id = $subscriber_id",
88 [DB_STMT_AUC_3G_INSERT] =
89 "INSERT INTO auc_3g (subscriber_id, algo_id_3g, k, op, opc, ind_bitlen)"
90 " VALUES($subscriber_id, $algo_id_3g, $k, $op, $opc, $ind_bitlen)",
91 [DB_STMT_AUC_3G_DELETE] = "DELETE FROM auc_3g WHERE subscriber_id = $subscriber_id",
Stefan Sperling638ba8c2018-12-04 15:07:29 +010092 [DB_STMT_SET_LAST_LU_SEEN] = "UPDATE subscriber SET last_lu_seen = datetime($val, 'unixepoch') WHERE id = $subscriber_id",
Neels Hofmeyr07e16022019-11-20 02:36:35 +010093 [DB_STMT_SET_LAST_LU_SEEN_PS] = "UPDATE subscriber SET last_lu_seen_ps = datetime($val, 'unixepoch') WHERE id = $subscriber_id",
Oliver Smith6b73fd92019-03-06 13:49:05 +010094 [DB_STMT_EXISTS_BY_IMSI] = "SELECT 1 FROM subscriber WHERE imsi = $imsi",
Vadim Yanitskiyc13599d2019-03-30 17:03:42 +070095 [DB_STMT_EXISTS_BY_MSISDN] = "SELECT 1 FROM subscriber WHERE msisdn = $msisdn",
Harald Weltee72cf552016-04-28 07:18:49 +020096};
97
98static void sql3_error_log_cb(void *arg, int err_code, const char *msg)
99{
100 LOGP(DDB, LOGL_ERROR, "(%d) %s\n", err_code, msg);
101}
102
103static void sql3_sql_log_cb(void *arg, sqlite3 *s3, const char *stmt, int type)
104{
105 switch (type) {
106 case 0:
107 LOGP(DDB, LOGL_DEBUG, "Opened database\n");
108 break;
109 case 1:
Max58d4a842017-02-20 11:06:12 +0100110 LOGP(DDB, LOGL_DEBUG, "%s\n", stmt);
Harald Weltee72cf552016-04-28 07:18:49 +0200111 break;
112 case 2:
113 LOGP(DDB, LOGL_DEBUG, "Closed database\n");
114 break;
115 default:
116 LOGP(DDB, LOGL_DEBUG, "Unknown %d\n", type);
117 break;
118 }
119}
120
Max00b37152017-02-20 11:09:27 +0100121/* remove bindings and reset statement to be re-executed */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200122void db_remove_reset(sqlite3_stmt *stmt)
Max00b37152017-02-20 11:09:27 +0100123{
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200124 sqlite3_clear_bindings(stmt);
Neels Hofmeyr4f3841c2017-11-07 13:24:44 +0100125 /* sqlite3_reset() just repeats an error code already evaluated during sqlite3_step(). */
126 /* coverity[CHECKED_RETURN] */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200127 sqlite3_reset(stmt);
Max00b37152017-02-20 11:09:27 +0100128}
129
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200130/** bind text arg and do proper cleanup in case of failure. If param_name is
131 * NULL, bind to the first parameter (useful for SQL statements that have only
132 * one parameter). */
133bool db_bind_text(sqlite3_stmt *stmt, const char *param_name, const char *text)
Max00b37152017-02-20 11:09:27 +0100134{
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200135 int rc;
136 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
137 if (idx < 1) {
138 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
139 param_name);
140 return false;
141 }
142 rc = sqlite3_bind_text(stmt, idx, text, -1, SQLITE_STATIC);
Max00b37152017-02-20 11:09:27 +0100143 if (rc != SQLITE_OK) {
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200144 LOGP(DDB, LOGL_ERROR, "Error binding text to SQL parameter %s: %d\n",
145 param_name ? param_name : "#1", rc);
Max00b37152017-02-20 11:09:27 +0100146 db_remove_reset(stmt);
147 return false;
148 }
Max00b37152017-02-20 11:09:27 +0100149 return true;
150}
151
Neels Hofmeyr28da26e2017-10-06 03:44:57 +0200152/** bind int arg and do proper cleanup in case of failure. If param_name is
153 * NULL, bind to the first parameter (useful for SQL statements that have only
154 * one parameter). */
155bool db_bind_int(sqlite3_stmt *stmt, const char *param_name, int nr)
156{
157 int rc;
158 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
159 if (idx < 1) {
160 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
161 param_name);
162 return false;
163 }
164 rc = sqlite3_bind_int(stmt, idx, nr);
165 if (rc != SQLITE_OK) {
166 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
167 param_name ? param_name : "#1", rc);
168 db_remove_reset(stmt);
169 return false;
170 }
171 return true;
172}
173
174/** bind int64 arg and do proper cleanup in case of failure. If param_name is
175 * NULL, bind to the first parameter (useful for SQL statements that have only
176 * one parameter). */
177bool db_bind_int64(sqlite3_stmt *stmt, const char *param_name, int64_t nr)
178{
179 int rc;
180 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
181 if (idx < 1) {
182 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
183 param_name);
184 return false;
185 }
186 rc = sqlite3_bind_int64(stmt, idx, nr);
187 if (rc != SQLITE_OK) {
188 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
189 param_name ? param_name : "#1", rc);
190 db_remove_reset(stmt);
191 return false;
192 }
193 return true;
194}
195
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100196bool db_bind_null(sqlite3_stmt *stmt, const char *param_name)
197{
198 int rc;
199 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
200 if (idx < 1) {
201 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
202 param_name);
203 return false;
204 }
205 rc = sqlite3_bind_null(stmt, idx);
206 if (rc != SQLITE_OK) {
207 LOGP(DDB, LOGL_ERROR, "Error binding NULL to SQL parameter %s: %d\n",
208 param_name ? param_name : "#1", rc);
209 db_remove_reset(stmt);
210 return false;
211 }
212 return true;
213}
214
Harald Weltee72cf552016-04-28 07:18:49 +0200215void db_close(struct db_context *dbc)
216{
217 unsigned int i;
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700218 int rc;
Harald Weltee72cf552016-04-28 07:18:49 +0200219
220 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
221 /* it is ok to call finalize on NULL */
222 sqlite3_finalize(dbc->stmt[i]);
223 }
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700224
225 /* Ask sqlite3 to close DB */
226 rc = sqlite3_close(dbc->db);
227 if (rc != SQLITE_OK) { /* Make sure it's actually closed! */
228 LOGP(DDB, LOGL_ERROR, "Couldn't close database: (rc=%d) %s\n",
229 rc, sqlite3_errmsg(dbc->db));
230 }
231
Harald Weltee72cf552016-04-28 07:18:49 +0200232 talloc_free(dbc);
233}
234
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100235static int db_run_statements(struct db_context *dbc, const char **statements, size_t statements_count)
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200236{
Pau Espin Pedrol608e2e42021-07-15 13:33:07 +0200237 int rc = 0;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200238 int i;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100239 for (i = 0; i < statements_count; i++) {
240 const char *stmt_str = statements[i];
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200241 sqlite3_stmt *stmt;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100242
243 rc = sqlite3_prepare_v2(dbc->db, stmt_str, -1, &stmt, NULL);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200244 if (rc != SQLITE_OK) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100245 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_str);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700246 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200247 }
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200248 rc = sqlite3_step(stmt);
249 db_remove_reset(stmt);
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700250 sqlite3_finalize(stmt);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200251 if (rc != SQLITE_DONE) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100252 LOGP(DDB, LOGL_ERROR, "SQL error: (%d) %s, during stmt '%s'",
253 rc, sqlite3_errmsg(dbc->db), stmt_str);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700254 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200255 }
256 }
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100257 return rc;
258}
259
260static int db_bootstrap(struct db_context *dbc)
261{
262 int rc = db_run_statements(dbc, stmt_bootstrap_sql, ARRAY_SIZE(stmt_bootstrap_sql));
263 if (rc != SQLITE_DONE) {
264 LOGP(DDB, LOGL_ERROR, "Cannot bootstrap database\n");
265 return rc;
266 }
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700267 return SQLITE_OK;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200268}
269
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100270/* https://www.sqlite.org/fileformat2.html#storage_of_the_sql_database_schema */
271static bool db_table_exists(struct db_context *dbc, const char *table_name)
272{
273 const char *table_exists_sql = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
274 sqlite3_stmt *stmt;
275 int rc;
276
277 rc = sqlite3_prepare_v2(dbc->db, table_exists_sql, -1, &stmt, NULL);
278 if (rc != SQLITE_OK) {
279 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", table_exists_sql);
280 return false;
281 }
282
283 if (!db_bind_text(stmt, NULL, table_name))
284 return false;
285
286 rc = sqlite3_step(stmt);
287 db_remove_reset(stmt);
288 sqlite3_finalize(stmt);
289 return (rc == SQLITE_ROW);
290}
291
292/* Indicate whether the database is initialized with tables for schema version 0.
293 * We only check for the 'subscriber' table here because Neels said so. */
294static bool db_is_bootstrapped_v0(struct db_context *dbc)
295{
296 if (!db_table_exists(dbc, "subscriber")) {
297 LOGP(DDB, LOGL_DEBUG, "Table 'subscriber' not found in database '%s'\n", dbc->fname);
298 return false;
299 }
300
301 return true;
302}
303
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100304static int
305db_upgrade_v1(struct db_context *dbc)
306{
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100307 int rc;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100308 const char *statements[] = {
309 "ALTER TABLE subscriber ADD COLUMN last_lu_seen TIMESTAMP default NULL",
310 "PRAGMA user_version = 1",
311 };
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100312
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100313 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100314 if (rc != SQLITE_DONE) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100315 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 1\n");
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100316 return rc;
317 }
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100318 return rc;
319}
320
Oliver Smith81db3892019-01-09 12:03:51 +0100321static int db_upgrade_v2(struct db_context *dbc)
322{
Oliver Smith81db3892019-01-09 12:03:51 +0100323 int rc;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100324 const char *statements[] = {
325 "ALTER TABLE subscriber ADD COLUMN imei VARCHAR(14)",
326 "PRAGMA user_version = 2",
327 };
Oliver Smith81db3892019-01-09 12:03:51 +0100328
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100329 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
Oliver Smith81db3892019-01-09 12:03:51 +0100330 if (rc != SQLITE_DONE) {
Neels Hofmeyrf5459de2019-10-31 01:29:59 +0100331 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 2\n");
Oliver Smith81db3892019-01-09 12:03:51 +0100332 return rc;
333 }
Oliver Smith81db3892019-01-09 12:03:51 +0100334 return rc;
335}
336
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100337static int db_upgrade_v3(struct db_context *dbc)
338{
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100339 int rc;
340
341 /* A newer SQLite version would allow simply 'ATLER TABLE subscriber RENAME COLUMN hlr_number TO msc_number'.
342 * This is a really expensive workaround for that in order to cover earlier SQLite versions as well:
343 * Create a new table with the new column name and copy the data over (https://www.sqlite.org/faq.html#q11).
344 */
345#define SUBSCR_V3_CREATE \
346"(\n" \
347"-- OsmoHLR's DB scheme is modelled roughly after TS 23.008 version 13.3.0\n" \
348" id INTEGER PRIMARY KEY,\n" \
349" -- Chapter 2.1.1.1\n" \
350" imsi VARCHAR(15) UNIQUE NOT NULL,\n" \
351" -- Chapter 2.1.2\n" \
352" msisdn VARCHAR(15) UNIQUE,\n" \
353" -- Chapter 2.2.3: Most recent / current IMEISV\n" \
354" imeisv VARCHAR,\n" \
355" -- Chapter 2.1.9: Most recent / current IMEI\n" \
356" imei VARCHAR(14),\n" \
357" -- Chapter 2.4.5\n" \
358" vlr_number VARCHAR(15),\n" \
359" -- Chapter 2.4.6\n" \
360" msc_number VARCHAR(15),\n" \
361" -- Chapter 2.4.8.1\n" \
362" sgsn_number VARCHAR(15),\n" \
363" -- Chapter 2.13.10\n" \
364" sgsn_address VARCHAR,\n" \
365" -- Chapter 2.4.8.2\n" \
366" ggsn_number VARCHAR(15),\n" \
367" -- Chapter 2.4.9.2\n" \
368" gmlc_number VARCHAR(15),\n" \
369" -- Chapter 2.4.23\n" \
370" smsc_number VARCHAR(15),\n" \
371" -- Chapter 2.4.24\n" \
372" periodic_lu_tmr INTEGER,\n" \
373" -- Chapter 2.13.115\n" \
374" periodic_rau_tau_tmr INTEGER,\n" \
375" -- Chapter 2.1.1.2: network access mode\n" \
376" nam_cs BOOLEAN NOT NULL DEFAULT 1,\n" \
377" nam_ps BOOLEAN NOT NULL DEFAULT 1,\n" \
378" -- Chapter 2.1.8\n" \
379" lmsi INTEGER,\n" \
380 \
381" -- The below purged flags might not even be stored non-volatile,\n" \
382" -- refer to TS 23.012 Chapter 3.6.1.4\n" \
383" -- Chapter 2.7.5\n" \
384" ms_purged_cs BOOLEAN NOT NULL DEFAULT 0,\n" \
385" -- Chapter 2.7.6\n" \
386" ms_purged_ps BOOLEAN NOT NULL DEFAULT 0,\n" \
387 \
388" -- Timestamp of last location update seen from subscriber\n" \
389" -- The value is a string which encodes a UTC timestamp in granularity of seconds.\n" \
390" last_lu_seen TIMESTAMP default NULL\n" \
391")\n"
392
393#define SUBSCR_V2_COLUMN_NAMES \
394 "id," \
395 "imsi," \
396 "msisdn," \
397 "imeisv," \
398 "imei," \
399 "vlr_number," \
400 "hlr_number," \
401 "sgsn_number," \
402 "sgsn_address," \
403 "ggsn_number," \
404 "gmlc_number," \
405 "smsc_number," \
406 "periodic_lu_tmr," \
407 "periodic_rau_tau_tmr," \
408 "nam_cs," \
409 "nam_ps," \
410 "lmsi," \
411 "ms_purged_cs," \
412 "ms_purged_ps," \
413 "last_lu_seen"
414
415#define SUBSCR_V3_COLUMN_NAMES \
416 "id," \
417 "imsi," \
418 "msisdn," \
419 "imeisv," \
420 "imei," \
421 "vlr_number," \
422 "msc_number," \
423 "sgsn_number," \
424 "sgsn_address," \
425 "ggsn_number," \
426 "gmlc_number," \
427 "smsc_number," \
428 "periodic_lu_tmr," \
429 "periodic_rau_tau_tmr," \
430 "nam_cs," \
431 "nam_ps," \
432 "lmsi," \
433 "ms_purged_cs," \
434 "ms_purged_ps," \
435 "last_lu_seen"
436
437 const char *statements[] = {
438 "BEGIN TRANSACTION",
439 "CREATE TEMPORARY TABLE subscriber_backup" SUBSCR_V3_CREATE,
440 "INSERT INTO subscriber_backup SELECT " SUBSCR_V2_COLUMN_NAMES " FROM subscriber",
441 "DROP TABLE subscriber",
442 "CREATE TABLE subscriber" SUBSCR_V3_CREATE,
443 "INSERT INTO subscriber SELECT " SUBSCR_V3_COLUMN_NAMES " FROM subscriber_backup",
444 "DROP TABLE subscriber_backup",
445 "COMMIT",
446 "PRAGMA user_version = 3",
447 };
448
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100449 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
450 if (rc != SQLITE_DONE) {
451 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 3\n");
452 return rc;
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100453 }
454 return rc;
455}
456
Neels Hofmeyr07e16022019-11-20 02:36:35 +0100457static int db_upgrade_v4(struct db_context *dbc)
458{
459 int rc;
460 const char *statements[] = {
461 "ALTER TABLE subscriber ADD COLUMN last_lu_seen_ps TIMESTAMP default NULL",
462 "PRAGMA user_version = 4",
463 };
464
465 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
466 if (rc != SQLITE_DONE) {
467 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 4\n");
468 return rc;
469 }
470 return rc;
471}
472
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100473static int db_upgrade_v5(struct db_context *dbc)
474{
475 int rc;
476 const char *statements[] = {
477 "ALTER TABLE subscriber ADD COLUMN vlr_via_proxy VARCHAR",
478 "ALTER TABLE subscriber ADD COLUMN sgsn_via_proxy VARCHAR",
479 "PRAGMA user_version = 5",
480 };
481
482 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
483 if (rc != SQLITE_DONE) {
484 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 5\n");
485 return rc;
486 }
487 return rc;
488}
489
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100490typedef int (*db_upgrade_func_t)(struct db_context *dbc);
491static db_upgrade_func_t db_upgrade_path[] = {
492 db_upgrade_v1,
493 db_upgrade_v2,
494 db_upgrade_v3,
Neels Hofmeyr07e16022019-11-20 02:36:35 +0100495 db_upgrade_v4,
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100496 db_upgrade_v5,
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100497};
498
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100499static int db_get_user_version(struct db_context *dbc)
500{
501 const char *user_version_sql = "PRAGMA user_version";
502 sqlite3_stmt *stmt;
503 int version, rc;
504
505 rc = sqlite3_prepare_v2(dbc->db, user_version_sql, -1, &stmt, NULL);
506 if (rc != SQLITE_OK) {
507 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", user_version_sql);
508 return -1;
509 }
510 rc = sqlite3_step(stmt);
511 if (rc == SQLITE_ROW) {
512 version = sqlite3_column_int(stmt, 0);
513 } else {
514 LOGP(DDB, LOGL_ERROR, "SQL statement '%s' failed: %d\n", user_version_sql, rc);
515 version = -1;
516 }
517
518 db_remove_reset(stmt);
519 sqlite3_finalize(stmt);
520 return version;
521}
522
523struct db_context *db_open(void *ctx, const char *fname, bool enable_sqlite_logging, bool allow_upgrade)
Harald Weltee72cf552016-04-28 07:18:49 +0200524{
525 struct db_context *dbc = talloc_zero(ctx, struct db_context);
526 unsigned int i;
527 int rc;
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200528 bool has_sqlite_config_sqllog = false;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100529 int version;
Harald Weltee72cf552016-04-28 07:18:49 +0200530
Neels Hofmeyr7f9491f2017-01-30 13:30:47 +0100531 LOGP(DDB, LOGL_NOTICE, "using database: %s\n", fname);
Harald Weltee72cf552016-04-28 07:18:49 +0200532 LOGP(DDB, LOGL_INFO, "Compiled against SQLite3 lib version %s\n", SQLITE_VERSION);
533 LOGP(DDB, LOGL_INFO, "Running with SQLite3 lib version %s\n", sqlite3_libversion());
534
Vadim Yanitskiyfbd736e2018-07-31 22:40:30 +0700535#ifdef SQLITE_USE_TALLOC
536 /* Configure SQLite3 to use talloc memory allocator */
537 rc = db_sqlite3_use_talloc(ctx);
538 if (rc == SQLITE_OK) {
539 LOGP(DDB, LOGL_NOTICE, "SQLite3 is configured to use talloc\n");
540 } else {
541 LOGP(DDB, LOGL_ERROR, "Failed to configure SQLite3 "
542 "to use talloc, using default memory allocator\n");
543 }
544#endif
545
Harald Weltee72cf552016-04-28 07:18:49 +0200546 dbc->fname = talloc_strdup(dbc, fname);
547
548 for (i = 0; i < 0xfffff; i++) {
549 const char *o = sqlite3_compileoption_get(i);
550 if (!o)
551 break;
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200552 LOGP(DDB, LOGL_DEBUG, "SQLite3 compiled with '%s'\n", o);
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200553 if (!strcmp(o, "ENABLE_SQLLOG"))
554 has_sqlite_config_sqllog = true;
Harald Weltee72cf552016-04-28 07:18:49 +0200555 }
556
Neels Hofmeyrd3814b92017-11-21 12:28:07 +0100557 if (enable_sqlite_logging) {
558 rc = sqlite3_config(SQLITE_CONFIG_LOG, sql3_error_log_cb, NULL);
559 if (rc != SQLITE_OK)
560 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 error log callback\n");
561 }
Harald Weltee72cf552016-04-28 07:18:49 +0200562
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200563 if (has_sqlite_config_sqllog) {
564 rc = sqlite3_config(SQLITE_CONFIG_SQLLOG, sql3_sql_log_cb, NULL);
565 if (rc != SQLITE_OK)
566 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 SQL log callback\n");
567 } else
568 LOGP(DDB, LOGL_DEBUG, "Not setting SQL log callback:"
569 " SQLite3 compiled without support for it\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200570
571 rc = sqlite3_open(dbc->fname, &dbc->db);
572 if (rc != SQLITE_OK) {
573 LOGP(DDB, LOGL_ERROR, "Unable to open DB; rc = %d\n", rc);
574 talloc_free(dbc);
575 return NULL;
576 }
577
578 /* enable extended result codes */
579 rc = sqlite3_extended_result_codes(dbc->db, 1);
580 if (rc != SQLITE_OK)
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200581 LOGP(DDB, LOGL_ERROR, "Unable to enable SQLite3 extended result codes\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200582
Harald Welteabd1a542016-05-03 18:50:41 +0200583 char *err_msg;
584 rc = sqlite3_exec(dbc->db, "PRAGMA journal_mode=WAL; PRAGMA synchonous = NORMAL;", 0, 0, &err_msg);
Vadim Yanitskiy15ad7be2020-02-09 05:32:46 +0700585 if (rc != SQLITE_OK) {
Harald Welteabd1a542016-05-03 18:50:41 +0200586 LOGP(DDB, LOGL_ERROR, "Unable to set Write-Ahead Logging: %s\n",
587 err_msg);
Vadim Yanitskiy15ad7be2020-02-09 05:32:46 +0700588 sqlite3_free(err_msg);
589 }
Harald Welteabd1a542016-05-03 18:50:41 +0200590
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100591 version = db_get_user_version(dbc);
592 if (version < 0) {
593 LOGP(DDB, LOGL_ERROR, "Unable to read user version number from database '%s'\n", dbc->fname);
594 goto out_free;
595 }
596
597 /* An empty database will always report version zero. */
598 if (version == 0 && !db_is_bootstrapped_v0(dbc)) {
599 LOGP(DDB, LOGL_NOTICE, "Missing database tables detected; Bootstrapping database '%s'\n", dbc->fname);
600 rc = db_bootstrap(dbc);
601 if (rc != SQLITE_OK) {
602 LOGP(DDB, LOGL_ERROR, "Failed to bootstrap DB: (rc=%d) %s\n",
603 rc, sqlite3_errmsg(dbc->db));
604 goto out_free;
605 }
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100606 version = CURRENT_SCHEMA_VERSION;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100607 }
608
609 LOGP(DDB, LOGL_NOTICE, "Database '%s' has HLR DB schema version %d\n", dbc->fname, version);
610
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100611 for (; allow_upgrade && (version < ARRAY_SIZE(db_upgrade_path)); version++) {
612 db_upgrade_func_t upgrade_func = db_upgrade_path[version];
613 rc = upgrade_func(dbc);
614 if (rc != SQLITE_DONE) {
615 LOGP(DDB, LOGL_ERROR, "Failed to upgrade HLR DB schema to version %d: (rc=%d) %s\n",
616 version+1, rc, sqlite3_errmsg(dbc->db));
617 goto out_free;
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100618 }
619 LOGP(DDB, LOGL_NOTICE, "Database '%s' has been upgraded to HLR DB schema version %d\n",
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100620 dbc->fname, version+1);
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100621 }
622
623 if (version != CURRENT_SCHEMA_VERSION) {
624 if (version < CURRENT_SCHEMA_VERSION) {
625 LOGP(DDB, LOGL_NOTICE, "HLR DB schema version %d is outdated\n", version);
626 if (!allow_upgrade) {
627 LOGP(DDB, LOGL_ERROR, "Not upgrading HLR database to schema version %d; "
628 "use the --db-upgrade option to allow HLR database upgrades\n",
629 CURRENT_SCHEMA_VERSION);
630 }
631 } else
632 LOGP(DDB, LOGL_ERROR, "HLR DB schema version %d is unknown\n", version);
633
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700634 goto out_free;
635 }
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200636
Harald Weltee72cf552016-04-28 07:18:49 +0200637 /* prepare all SQL statements */
638 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
639 rc = sqlite3_prepare_v2(dbc->db, stmt_sql[i], -1,
640 &dbc->stmt[i], NULL);
641 if (rc != SQLITE_OK) {
642 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_sql[i]);
643 goto out_free;
644 }
645 }
646
647 return dbc;
648out_free:
649 db_close(dbc);
650 return NULL;
651}