blob: 7b8a415895a5f73d20ad7667ab871270d093f353 [file] [log] [blame]
Harald Welte626f5eb2023-05-30 18:28:15 +02001/* (C) 2015-2023 by Harald Welte <laforge@gnumonks.org>
Harald Weltee72cf552016-04-28 07:18:49 +02002 *
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! */
Harald Welte626f5eb2023-05-30 18:28:15 +020031#define CURRENT_SCHEMA_VERSION 7
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",
Neels Hofmeyr3f9d1972019-12-12 04:04:53 +010096 [DB_STMT_IND_ADD] = "INSERT INTO ind (vlr) VALUES ($vlr)",
97 [DB_STMT_IND_SELECT] = "SELECT ind FROM ind WHERE vlr = $vlr",
98 [DB_STMT_IND_DEL] = "DELETE FROM ind WHERE vlr = $vlr",
Harald Weltee72cf552016-04-28 07:18:49 +020099};
100
101static void sql3_error_log_cb(void *arg, int err_code, const char *msg)
102{
103 LOGP(DDB, LOGL_ERROR, "(%d) %s\n", err_code, msg);
104}
105
106static void sql3_sql_log_cb(void *arg, sqlite3 *s3, const char *stmt, int type)
107{
108 switch (type) {
109 case 0:
110 LOGP(DDB, LOGL_DEBUG, "Opened database\n");
111 break;
112 case 1:
Max58d4a842017-02-20 11:06:12 +0100113 LOGP(DDB, LOGL_DEBUG, "%s\n", stmt);
Harald Weltee72cf552016-04-28 07:18:49 +0200114 break;
115 case 2:
116 LOGP(DDB, LOGL_DEBUG, "Closed database\n");
117 break;
118 default:
119 LOGP(DDB, LOGL_DEBUG, "Unknown %d\n", type);
120 break;
121 }
122}
123
Max00b37152017-02-20 11:09:27 +0100124/* remove bindings and reset statement to be re-executed */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200125void db_remove_reset(sqlite3_stmt *stmt)
Max00b37152017-02-20 11:09:27 +0100126{
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200127 sqlite3_clear_bindings(stmt);
Neels Hofmeyr4f3841c2017-11-07 13:24:44 +0100128 /* sqlite3_reset() just repeats an error code already evaluated during sqlite3_step(). */
129 /* coverity[CHECKED_RETURN] */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200130 sqlite3_reset(stmt);
Max00b37152017-02-20 11:09:27 +0100131}
132
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200133/** bind text arg and do proper cleanup in case of failure. If param_name is
134 * NULL, bind to the first parameter (useful for SQL statements that have only
135 * one parameter). */
136bool db_bind_text(sqlite3_stmt *stmt, const char *param_name, const char *text)
Max00b37152017-02-20 11:09:27 +0100137{
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200138 int rc;
139 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
140 if (idx < 1) {
141 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
142 param_name);
143 return false;
144 }
145 rc = sqlite3_bind_text(stmt, idx, text, -1, SQLITE_STATIC);
Max00b37152017-02-20 11:09:27 +0100146 if (rc != SQLITE_OK) {
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200147 LOGP(DDB, LOGL_ERROR, "Error binding text to SQL parameter %s: %d\n",
148 param_name ? param_name : "#1", rc);
Max00b37152017-02-20 11:09:27 +0100149 db_remove_reset(stmt);
150 return false;
151 }
Max00b37152017-02-20 11:09:27 +0100152 return true;
153}
154
Neels Hofmeyr28da26e2017-10-06 03:44:57 +0200155/** bind int arg and do proper cleanup in case of failure. If param_name is
156 * NULL, bind to the first parameter (useful for SQL statements that have only
157 * one parameter). */
158bool db_bind_int(sqlite3_stmt *stmt, const char *param_name, int nr)
159{
160 int rc;
161 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
162 if (idx < 1) {
163 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
164 param_name);
165 return false;
166 }
167 rc = sqlite3_bind_int(stmt, idx, nr);
168 if (rc != SQLITE_OK) {
169 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
170 param_name ? param_name : "#1", rc);
171 db_remove_reset(stmt);
172 return false;
173 }
174 return true;
175}
176
177/** bind int64 arg and do proper cleanup in case of failure. If param_name is
178 * NULL, bind to the first parameter (useful for SQL statements that have only
179 * one parameter). */
180bool db_bind_int64(sqlite3_stmt *stmt, const char *param_name, int64_t nr)
181{
182 int rc;
183 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
184 if (idx < 1) {
185 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
186 param_name);
187 return false;
188 }
189 rc = sqlite3_bind_int64(stmt, idx, nr);
190 if (rc != SQLITE_OK) {
191 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
192 param_name ? param_name : "#1", rc);
193 db_remove_reset(stmt);
194 return false;
195 }
196 return true;
197}
198
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100199bool db_bind_null(sqlite3_stmt *stmt, const char *param_name)
200{
201 int rc;
202 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
203 if (idx < 1) {
204 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
205 param_name);
206 return false;
207 }
208 rc = sqlite3_bind_null(stmt, idx);
209 if (rc != SQLITE_OK) {
210 LOGP(DDB, LOGL_ERROR, "Error binding NULL to SQL parameter %s: %d\n",
211 param_name ? param_name : "#1", rc);
212 db_remove_reset(stmt);
213 return false;
214 }
215 return true;
216}
217
Harald Weltee72cf552016-04-28 07:18:49 +0200218void db_close(struct db_context *dbc)
219{
220 unsigned int i;
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700221 int rc;
Harald Weltee72cf552016-04-28 07:18:49 +0200222
223 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
224 /* it is ok to call finalize on NULL */
225 sqlite3_finalize(dbc->stmt[i]);
226 }
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700227
228 /* Ask sqlite3 to close DB */
229 rc = sqlite3_close(dbc->db);
230 if (rc != SQLITE_OK) { /* Make sure it's actually closed! */
231 LOGP(DDB, LOGL_ERROR, "Couldn't close database: (rc=%d) %s\n",
232 rc, sqlite3_errmsg(dbc->db));
233 }
234
Harald Weltee72cf552016-04-28 07:18:49 +0200235 talloc_free(dbc);
236}
237
Harald Weltef4159bd2023-06-04 10:48:04 +0200238static int db_run_statements(struct db_context *dbc, const char * const *statements, size_t statements_count)
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200239{
Pau Espin Pedrol608e2e42021-07-15 13:33:07 +0200240 int rc = 0;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200241 int i;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100242 for (i = 0; i < statements_count; i++) {
243 const char *stmt_str = statements[i];
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200244 sqlite3_stmt *stmt;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100245
246 rc = sqlite3_prepare_v2(dbc->db, stmt_str, -1, &stmt, NULL);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200247 if (rc != SQLITE_OK) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100248 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_str);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700249 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200250 }
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200251 rc = sqlite3_step(stmt);
252 db_remove_reset(stmt);
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700253 sqlite3_finalize(stmt);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200254 if (rc != SQLITE_DONE) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100255 LOGP(DDB, LOGL_ERROR, "SQL error: (%d) %s, during stmt '%s'",
256 rc, sqlite3_errmsg(dbc->db), stmt_str);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700257 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200258 }
259 }
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100260 return rc;
261}
262
263static int db_bootstrap(struct db_context *dbc)
264{
265 int rc = db_run_statements(dbc, stmt_bootstrap_sql, ARRAY_SIZE(stmt_bootstrap_sql));
266 if (rc != SQLITE_DONE) {
267 LOGP(DDB, LOGL_ERROR, "Cannot bootstrap database\n");
268 return rc;
269 }
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700270 return SQLITE_OK;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200271}
272
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100273/* https://www.sqlite.org/fileformat2.html#storage_of_the_sql_database_schema */
274static bool db_table_exists(struct db_context *dbc, const char *table_name)
275{
276 const char *table_exists_sql = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
277 sqlite3_stmt *stmt;
278 int rc;
279
280 rc = sqlite3_prepare_v2(dbc->db, table_exists_sql, -1, &stmt, NULL);
281 if (rc != SQLITE_OK) {
282 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", table_exists_sql);
283 return false;
284 }
285
286 if (!db_bind_text(stmt, NULL, table_name))
287 return false;
288
289 rc = sqlite3_step(stmt);
290 db_remove_reset(stmt);
291 sqlite3_finalize(stmt);
292 return (rc == SQLITE_ROW);
293}
294
295/* Indicate whether the database is initialized with tables for schema version 0.
296 * We only check for the 'subscriber' table here because Neels said so. */
297static bool db_is_bootstrapped_v0(struct db_context *dbc)
298{
299 if (!db_table_exists(dbc, "subscriber")) {
300 LOGP(DDB, LOGL_DEBUG, "Table 'subscriber' not found in database '%s'\n", dbc->fname);
301 return false;
302 }
303
304 return true;
305}
306
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100307static int
308db_upgrade_v1(struct db_context *dbc)
309{
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100310 int rc;
Harald Weltef4159bd2023-06-04 10:48:04 +0200311 const char * const statements[] = {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100312 "ALTER TABLE subscriber ADD COLUMN last_lu_seen TIMESTAMP default NULL",
313 "PRAGMA user_version = 1",
314 };
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100315
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100316 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100317 if (rc != SQLITE_DONE) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100318 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 1\n");
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100319 return rc;
320 }
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100321 return rc;
322}
323
Oliver Smith81db3892019-01-09 12:03:51 +0100324static int db_upgrade_v2(struct db_context *dbc)
325{
Oliver Smith81db3892019-01-09 12:03:51 +0100326 int rc;
Harald Weltef4159bd2023-06-04 10:48:04 +0200327 const char * const statements[] = {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100328 "ALTER TABLE subscriber ADD COLUMN imei VARCHAR(14)",
329 "PRAGMA user_version = 2",
330 };
Oliver Smith81db3892019-01-09 12:03:51 +0100331
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100332 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
Oliver Smith81db3892019-01-09 12:03:51 +0100333 if (rc != SQLITE_DONE) {
Neels Hofmeyrf5459de2019-10-31 01:29:59 +0100334 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 2\n");
Oliver Smith81db3892019-01-09 12:03:51 +0100335 return rc;
336 }
Oliver Smith81db3892019-01-09 12:03:51 +0100337 return rc;
338}
339
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100340static int db_upgrade_v3(struct db_context *dbc)
341{
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100342 int rc;
343
344 /* A newer SQLite version would allow simply 'ATLER TABLE subscriber RENAME COLUMN hlr_number TO msc_number'.
345 * This is a really expensive workaround for that in order to cover earlier SQLite versions as well:
346 * Create a new table with the new column name and copy the data over (https://www.sqlite.org/faq.html#q11).
347 */
348#define SUBSCR_V3_CREATE \
349"(\n" \
350"-- OsmoHLR's DB scheme is modelled roughly after TS 23.008 version 13.3.0\n" \
351" id INTEGER PRIMARY KEY,\n" \
352" -- Chapter 2.1.1.1\n" \
353" imsi VARCHAR(15) UNIQUE NOT NULL,\n" \
354" -- Chapter 2.1.2\n" \
355" msisdn VARCHAR(15) UNIQUE,\n" \
356" -- Chapter 2.2.3: Most recent / current IMEISV\n" \
357" imeisv VARCHAR,\n" \
358" -- Chapter 2.1.9: Most recent / current IMEI\n" \
359" imei VARCHAR(14),\n" \
360" -- Chapter 2.4.5\n" \
361" vlr_number VARCHAR(15),\n" \
362" -- Chapter 2.4.6\n" \
363" msc_number VARCHAR(15),\n" \
364" -- Chapter 2.4.8.1\n" \
365" sgsn_number VARCHAR(15),\n" \
366" -- Chapter 2.13.10\n" \
367" sgsn_address VARCHAR,\n" \
368" -- Chapter 2.4.8.2\n" \
369" ggsn_number VARCHAR(15),\n" \
370" -- Chapter 2.4.9.2\n" \
371" gmlc_number VARCHAR(15),\n" \
372" -- Chapter 2.4.23\n" \
373" smsc_number VARCHAR(15),\n" \
374" -- Chapter 2.4.24\n" \
375" periodic_lu_tmr INTEGER,\n" \
376" -- Chapter 2.13.115\n" \
377" periodic_rau_tau_tmr INTEGER,\n" \
378" -- Chapter 2.1.1.2: network access mode\n" \
379" nam_cs BOOLEAN NOT NULL DEFAULT 1,\n" \
380" nam_ps BOOLEAN NOT NULL DEFAULT 1,\n" \
381" -- Chapter 2.1.8\n" \
382" lmsi INTEGER,\n" \
383 \
384" -- The below purged flags might not even be stored non-volatile,\n" \
385" -- refer to TS 23.012 Chapter 3.6.1.4\n" \
386" -- Chapter 2.7.5\n" \
387" ms_purged_cs BOOLEAN NOT NULL DEFAULT 0,\n" \
388" -- Chapter 2.7.6\n" \
389" ms_purged_ps BOOLEAN NOT NULL DEFAULT 0,\n" \
390 \
391" -- Timestamp of last location update seen from subscriber\n" \
392" -- The value is a string which encodes a UTC timestamp in granularity of seconds.\n" \
393" last_lu_seen TIMESTAMP default NULL\n" \
394")\n"
395
396#define SUBSCR_V2_COLUMN_NAMES \
397 "id," \
398 "imsi," \
399 "msisdn," \
400 "imeisv," \
401 "imei," \
402 "vlr_number," \
403 "hlr_number," \
404 "sgsn_number," \
405 "sgsn_address," \
406 "ggsn_number," \
407 "gmlc_number," \
408 "smsc_number," \
409 "periodic_lu_tmr," \
410 "periodic_rau_tau_tmr," \
411 "nam_cs," \
412 "nam_ps," \
413 "lmsi," \
414 "ms_purged_cs," \
415 "ms_purged_ps," \
416 "last_lu_seen"
417
418#define SUBSCR_V3_COLUMN_NAMES \
419 "id," \
420 "imsi," \
421 "msisdn," \
422 "imeisv," \
423 "imei," \
424 "vlr_number," \
425 "msc_number," \
426 "sgsn_number," \
427 "sgsn_address," \
428 "ggsn_number," \
429 "gmlc_number," \
430 "smsc_number," \
431 "periodic_lu_tmr," \
432 "periodic_rau_tau_tmr," \
433 "nam_cs," \
434 "nam_ps," \
435 "lmsi," \
436 "ms_purged_cs," \
437 "ms_purged_ps," \
438 "last_lu_seen"
439
Harald Weltef4159bd2023-06-04 10:48:04 +0200440 const char * const statements[] = {
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100441 "BEGIN TRANSACTION",
442 "CREATE TEMPORARY TABLE subscriber_backup" SUBSCR_V3_CREATE,
443 "INSERT INTO subscriber_backup SELECT " SUBSCR_V2_COLUMN_NAMES " FROM subscriber",
444 "DROP TABLE subscriber",
445 "CREATE TABLE subscriber" SUBSCR_V3_CREATE,
446 "INSERT INTO subscriber SELECT " SUBSCR_V3_COLUMN_NAMES " FROM subscriber_backup",
447 "DROP TABLE subscriber_backup",
448 "COMMIT",
449 "PRAGMA user_version = 3",
450 };
451
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100452 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
453 if (rc != SQLITE_DONE) {
454 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 3\n");
455 return rc;
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100456 }
457 return rc;
458}
459
Neels Hofmeyr07e16022019-11-20 02:36:35 +0100460static int db_upgrade_v4(struct db_context *dbc)
461{
462 int rc;
Harald Weltef4159bd2023-06-04 10:48:04 +0200463 const char * const statements[] = {
Neels Hofmeyr07e16022019-11-20 02:36:35 +0100464 "ALTER TABLE subscriber ADD COLUMN last_lu_seen_ps TIMESTAMP default NULL",
465 "PRAGMA user_version = 4",
466 };
467
468 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
469 if (rc != SQLITE_DONE) {
470 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 4\n");
471 return rc;
472 }
473 return rc;
474}
475
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100476static int db_upgrade_v5(struct db_context *dbc)
477{
478 int rc;
Harald Weltef4159bd2023-06-04 10:48:04 +0200479 const char * const statements[] = {
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100480 "ALTER TABLE subscriber ADD COLUMN vlr_via_proxy VARCHAR",
481 "ALTER TABLE subscriber ADD COLUMN sgsn_via_proxy VARCHAR",
482 "PRAGMA user_version = 5",
483 };
484
485 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
486 if (rc != SQLITE_DONE) {
487 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 5\n");
488 return rc;
489 }
490 return rc;
491}
492
Neels Hofmeyr3f9d1972019-12-12 04:04:53 +0100493static int db_upgrade_v6(struct db_context *dbc)
494{
495 int rc;
Harald Weltef4159bd2023-06-04 10:48:04 +0200496 const char * const statements[] = {
Neels Hofmeyr3f9d1972019-12-12 04:04:53 +0100497 "CREATE TABLE ind (\n"
498 " -- 3G auth IND pool to be used for this VLR\n"
499 " ind INTEGER PRIMARY KEY,\n"
500 " -- VLR identification, usually the GSUP source_name\n"
501 " vlr TEXT NOT NULL,\n"
502 " UNIQUE (vlr)\n"
503 ")"
504 ,
505 "PRAGMA user_version = 6",
506 };
507
508 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
509 if (rc != SQLITE_DONE) {
510 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 6\n");
511 return rc;
512 }
513 return rc;
514}
515
Harald Welte626f5eb2023-05-30 18:28:15 +0200516static int db_upgrade_v7(struct db_context *dbc)
517{
518 int rc;
519 /* SQLite doesn't allow us to change the column type in-place, so we
520 * first rename the old table, create a new table and then copy
521 * the data over before deleting the old table */
522#define CREATE_AUC_3G_V7 \
523"CREATE TABLE auc_3g (\n" \
524" subscriber_id INTEGER PRIMARY KEY, -- subscriber.id\n" \
525" algo_id_3g INTEGER NOT NULL, -- enum osmo_auth_algo value\n" \
526" k VARCHAR(64) NOT NULL, -- hex string: subscriber's secret key (128/256bit)\n" \
527" op VARCHAR(64), -- hex string: operator's secret key (128/256bit)\n" \
528" opc VARCHAR(64), -- hex string: derived from OP and K (128/256bit)\n" \
529" sqn INTEGER NOT NULL DEFAULT 0, -- sequence number of key usage\n" \
530" -- nr of index bits at lower SQN end\n" \
531" ind_bitlen INTEGER NOT NULL DEFAULT 5\n" \
532");"
533 const char * const statements[] = {
534 "BEGIN TRANSACTION",
535 /* rename old table */
536 "ALTER TABLE auc_3g RENAME TO old_auc_3g",
537 /* create new table */
538 CREATE_AUC_3G_V7,
539 /* copy over old data */
540 "INSERT INTO auc_3g SELECT subscriber_id, algo_id_3g, k, op, opc,sqn, ind_bitlen FROM old_auc_3g",
541 /* delete old table */
542 "DROP TABLE old_auc_3g",
543 /* update user_version */
544 "PRAGMA user_version = 7",
545 "COMMIT",
546 };
547
548 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
549 if (rc != SQLITE_DONE) {
550 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 7\n");
551 return rc;
552 }
553 return rc;
554}
555
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100556typedef int (*db_upgrade_func_t)(struct db_context *dbc);
557static db_upgrade_func_t db_upgrade_path[] = {
558 db_upgrade_v1,
559 db_upgrade_v2,
560 db_upgrade_v3,
Neels Hofmeyr07e16022019-11-20 02:36:35 +0100561 db_upgrade_v4,
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100562 db_upgrade_v5,
Neels Hofmeyr3f9d1972019-12-12 04:04:53 +0100563 db_upgrade_v6,
Harald Welte626f5eb2023-05-30 18:28:15 +0200564 db_upgrade_v7,
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100565};
566
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100567static int db_get_user_version(struct db_context *dbc)
568{
569 const char *user_version_sql = "PRAGMA user_version";
570 sqlite3_stmt *stmt;
571 int version, rc;
572
573 rc = sqlite3_prepare_v2(dbc->db, user_version_sql, -1, &stmt, NULL);
574 if (rc != SQLITE_OK) {
575 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", user_version_sql);
576 return -1;
577 }
578 rc = sqlite3_step(stmt);
579 if (rc == SQLITE_ROW) {
580 version = sqlite3_column_int(stmt, 0);
581 } else {
582 LOGP(DDB, LOGL_ERROR, "SQL statement '%s' failed: %d\n", user_version_sql, rc);
583 version = -1;
584 }
585
586 db_remove_reset(stmt);
587 sqlite3_finalize(stmt);
588 return version;
589}
590
591struct db_context *db_open(void *ctx, const char *fname, bool enable_sqlite_logging, bool allow_upgrade)
Harald Weltee72cf552016-04-28 07:18:49 +0200592{
593 struct db_context *dbc = talloc_zero(ctx, struct db_context);
594 unsigned int i;
595 int rc;
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200596 bool has_sqlite_config_sqllog = false;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100597 int version;
Harald Weltee72cf552016-04-28 07:18:49 +0200598
Neels Hofmeyr7f9491f2017-01-30 13:30:47 +0100599 LOGP(DDB, LOGL_NOTICE, "using database: %s\n", fname);
Harald Weltee72cf552016-04-28 07:18:49 +0200600 LOGP(DDB, LOGL_INFO, "Compiled against SQLite3 lib version %s\n", SQLITE_VERSION);
601 LOGP(DDB, LOGL_INFO, "Running with SQLite3 lib version %s\n", sqlite3_libversion());
602
Vadim Yanitskiyfbd736e2018-07-31 22:40:30 +0700603#ifdef SQLITE_USE_TALLOC
604 /* Configure SQLite3 to use talloc memory allocator */
605 rc = db_sqlite3_use_talloc(ctx);
606 if (rc == SQLITE_OK) {
607 LOGP(DDB, LOGL_NOTICE, "SQLite3 is configured to use talloc\n");
608 } else {
609 LOGP(DDB, LOGL_ERROR, "Failed to configure SQLite3 "
610 "to use talloc, using default memory allocator\n");
611 }
612#endif
613
Harald Weltee72cf552016-04-28 07:18:49 +0200614 dbc->fname = talloc_strdup(dbc, fname);
615
616 for (i = 0; i < 0xfffff; i++) {
617 const char *o = sqlite3_compileoption_get(i);
618 if (!o)
619 break;
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200620 LOGP(DDB, LOGL_DEBUG, "SQLite3 compiled with '%s'\n", o);
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200621 if (!strcmp(o, "ENABLE_SQLLOG"))
622 has_sqlite_config_sqllog = true;
Harald Weltee72cf552016-04-28 07:18:49 +0200623 }
624
Neels Hofmeyrd3814b92017-11-21 12:28:07 +0100625 if (enable_sqlite_logging) {
626 rc = sqlite3_config(SQLITE_CONFIG_LOG, sql3_error_log_cb, NULL);
627 if (rc != SQLITE_OK)
628 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 error log callback\n");
629 }
Harald Weltee72cf552016-04-28 07:18:49 +0200630
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200631 if (has_sqlite_config_sqllog) {
632 rc = sqlite3_config(SQLITE_CONFIG_SQLLOG, sql3_sql_log_cb, NULL);
633 if (rc != SQLITE_OK)
634 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 SQL log callback\n");
635 } else
636 LOGP(DDB, LOGL_DEBUG, "Not setting SQL log callback:"
637 " SQLite3 compiled without support for it\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200638
639 rc = sqlite3_open(dbc->fname, &dbc->db);
640 if (rc != SQLITE_OK) {
641 LOGP(DDB, LOGL_ERROR, "Unable to open DB; rc = %d\n", rc);
642 talloc_free(dbc);
643 return NULL;
644 }
645
646 /* enable extended result codes */
647 rc = sqlite3_extended_result_codes(dbc->db, 1);
648 if (rc != SQLITE_OK)
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200649 LOGP(DDB, LOGL_ERROR, "Unable to enable SQLite3 extended result codes\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200650
Harald Welteabd1a542016-05-03 18:50:41 +0200651 char *err_msg;
652 rc = sqlite3_exec(dbc->db, "PRAGMA journal_mode=WAL; PRAGMA synchonous = NORMAL;", 0, 0, &err_msg);
Vadim Yanitskiy15ad7be2020-02-09 05:32:46 +0700653 if (rc != SQLITE_OK) {
Harald Welteabd1a542016-05-03 18:50:41 +0200654 LOGP(DDB, LOGL_ERROR, "Unable to set Write-Ahead Logging: %s\n",
655 err_msg);
Vadim Yanitskiy15ad7be2020-02-09 05:32:46 +0700656 sqlite3_free(err_msg);
657 }
Harald Welteabd1a542016-05-03 18:50:41 +0200658
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100659 version = db_get_user_version(dbc);
660 if (version < 0) {
661 LOGP(DDB, LOGL_ERROR, "Unable to read user version number from database '%s'\n", dbc->fname);
662 goto out_free;
663 }
664
665 /* An empty database will always report version zero. */
666 if (version == 0 && !db_is_bootstrapped_v0(dbc)) {
667 LOGP(DDB, LOGL_NOTICE, "Missing database tables detected; Bootstrapping database '%s'\n", dbc->fname);
668 rc = db_bootstrap(dbc);
669 if (rc != SQLITE_OK) {
670 LOGP(DDB, LOGL_ERROR, "Failed to bootstrap DB: (rc=%d) %s\n",
671 rc, sqlite3_errmsg(dbc->db));
672 goto out_free;
673 }
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100674 version = CURRENT_SCHEMA_VERSION;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100675 }
676
677 LOGP(DDB, LOGL_NOTICE, "Database '%s' has HLR DB schema version %d\n", dbc->fname, version);
678
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100679 for (; allow_upgrade && (version < ARRAY_SIZE(db_upgrade_path)); version++) {
680 db_upgrade_func_t upgrade_func = db_upgrade_path[version];
681 rc = upgrade_func(dbc);
682 if (rc != SQLITE_DONE) {
683 LOGP(DDB, LOGL_ERROR, "Failed to upgrade HLR DB schema to version %d: (rc=%d) %s\n",
684 version+1, rc, sqlite3_errmsg(dbc->db));
685 goto out_free;
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100686 }
687 LOGP(DDB, LOGL_NOTICE, "Database '%s' has been upgraded to HLR DB schema version %d\n",
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100688 dbc->fname, version+1);
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100689 }
690
691 if (version != CURRENT_SCHEMA_VERSION) {
692 if (version < CURRENT_SCHEMA_VERSION) {
693 LOGP(DDB, LOGL_NOTICE, "HLR DB schema version %d is outdated\n", version);
694 if (!allow_upgrade) {
695 LOGP(DDB, LOGL_ERROR, "Not upgrading HLR database to schema version %d; "
696 "use the --db-upgrade option to allow HLR database upgrades\n",
697 CURRENT_SCHEMA_VERSION);
698 }
699 } else
700 LOGP(DDB, LOGL_ERROR, "HLR DB schema version %d is unknown\n", version);
701
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700702 goto out_free;
703 }
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200704
Harald Weltee72cf552016-04-28 07:18:49 +0200705 /* prepare all SQL statements */
706 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
707 rc = sqlite3_prepare_v2(dbc->db, stmt_sql[i], -1,
708 &dbc->stmt[i], NULL);
709 if (rc != SQLITE_OK) {
710 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_sql[i]);
711 goto out_free;
712 }
713 }
714
715 return dbc;
716out_free:
717 db_close(dbc);
718 return NULL;
719}