blob: 09a17b6481cbaf70956e32a13df11fdaee5a4302 [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",
59 [DB_STMT_SEL_FILTER_CS] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE nam_cs = $search ORDER BY last_lu_seen",
60 [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 +020061 [DB_STMT_SEL_BY_IMSI] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE imsi = ?",
62 [DB_STMT_SEL_BY_MSISDN] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE msisdn = ?",
63 [DB_STMT_SEL_BY_ID] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE id = ?",
Oliver Smith81db3892019-01-09 12:03:51 +010064 [DB_STMT_SEL_BY_IMEI] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE imei = ?",
Neels Hofmeyr04c23752019-11-25 03:59:50 +010065 [DB_STMT_UPD_VLR_BY_ID] = "UPDATE subscriber SET vlr_number = $number, vlr_via_proxy = $proxy WHERE id = $subscriber_id",
66 [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 +010067 [DB_STMT_UPD_IMEI_BY_IMSI] = "UPDATE subscriber SET imei = $imei WHERE imsi = $imsi",
Neels Hofmeyr0cac0a02017-10-09 17:47:21 +020068 [DB_STMT_AUC_BY_IMSI] =
69 "SELECT id, algo_id_2g, ki, algo_id_3g, k, op, opc, sqn, ind_bitlen"
70 " FROM subscriber"
71 " LEFT JOIN auc_2g ON auc_2g.subscriber_id = subscriber.id"
72 " LEFT JOIN auc_3g ON auc_3g.subscriber_id = subscriber.id"
Neels Hofmeyrc5122f22017-10-09 23:12:57 +020073 " WHERE imsi = $imsi",
Neels Hofmeyr1cbdb702017-10-09 23:03:57 +020074 [DB_STMT_AUC_UPD_SQN] = "UPDATE auc_3g SET sqn = $sqn WHERE subscriber_id = $subscriber_id",
Neels Hofmeyre50121e2017-10-09 17:48:51 +020075 [DB_STMT_UPD_PURGE_CS_BY_IMSI] = "UPDATE subscriber SET ms_purged_cs = $val WHERE imsi = $imsi",
76 [DB_STMT_UPD_PURGE_PS_BY_IMSI] = "UPDATE subscriber SET ms_purged_ps = $val WHERE imsi = $imsi",
Neels Hofmeyre8ccd502017-10-06 04:10:06 +020077 [DB_STMT_UPD_NAM_CS_BY_IMSI] = "UPDATE subscriber SET nam_cs = $val WHERE imsi = $imsi",
78 [DB_STMT_UPD_NAM_PS_BY_IMSI] = "UPDATE subscriber SET nam_ps = $val WHERE imsi = $imsi",
Oliver Smithcd2af5e2019-03-06 13:17:39 +010079 [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 +020080 [DB_STMT_DEL_BY_ID] = "DELETE FROM subscriber WHERE id = $subscriber_id",
81 [DB_STMT_SET_MSISDN_BY_IMSI] = "UPDATE subscriber SET msisdn = $msisdn WHERE imsi = $imsi",
Neels Hofmeyra820ea12018-12-02 19:46:46 +010082 [DB_STMT_DELETE_MSISDN_BY_IMSI] = "UPDATE subscriber SET msisdn = NULL WHERE imsi = $imsi",
Neels Hofmeyr1332a172017-10-10 02:25:00 +020083 [DB_STMT_AUC_2G_INSERT] =
84 "INSERT INTO auc_2g (subscriber_id, algo_id_2g, ki)"
85 " VALUES($subscriber_id, $algo_id_2g, $ki)",
86 [DB_STMT_AUC_2G_DELETE] = "DELETE FROM auc_2g WHERE subscriber_id = $subscriber_id",
87 [DB_STMT_AUC_3G_INSERT] =
88 "INSERT INTO auc_3g (subscriber_id, algo_id_3g, k, op, opc, ind_bitlen)"
89 " VALUES($subscriber_id, $algo_id_3g, $k, $op, $opc, $ind_bitlen)",
90 [DB_STMT_AUC_3G_DELETE] = "DELETE FROM auc_3g WHERE subscriber_id = $subscriber_id",
Stefan Sperling638ba8c2018-12-04 15:07:29 +010091 [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 +010092 [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 +010093 [DB_STMT_EXISTS_BY_IMSI] = "SELECT 1 FROM subscriber WHERE imsi = $imsi",
Vadim Yanitskiyc13599d2019-03-30 17:03:42 +070094 [DB_STMT_EXISTS_BY_MSISDN] = "SELECT 1 FROM subscriber WHERE msisdn = $msisdn",
Harald Weltee72cf552016-04-28 07:18:49 +020095};
96
97static void sql3_error_log_cb(void *arg, int err_code, const char *msg)
98{
99 LOGP(DDB, LOGL_ERROR, "(%d) %s\n", err_code, msg);
100}
101
102static void sql3_sql_log_cb(void *arg, sqlite3 *s3, const char *stmt, int type)
103{
104 switch (type) {
105 case 0:
106 LOGP(DDB, LOGL_DEBUG, "Opened database\n");
107 break;
108 case 1:
Max58d4a842017-02-20 11:06:12 +0100109 LOGP(DDB, LOGL_DEBUG, "%s\n", stmt);
Harald Weltee72cf552016-04-28 07:18:49 +0200110 break;
111 case 2:
112 LOGP(DDB, LOGL_DEBUG, "Closed database\n");
113 break;
114 default:
115 LOGP(DDB, LOGL_DEBUG, "Unknown %d\n", type);
116 break;
117 }
118}
119
Max00b37152017-02-20 11:09:27 +0100120/* remove bindings and reset statement to be re-executed */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200121void db_remove_reset(sqlite3_stmt *stmt)
Max00b37152017-02-20 11:09:27 +0100122{
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200123 sqlite3_clear_bindings(stmt);
Neels Hofmeyr4f3841c2017-11-07 13:24:44 +0100124 /* sqlite3_reset() just repeats an error code already evaluated during sqlite3_step(). */
125 /* coverity[CHECKED_RETURN] */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200126 sqlite3_reset(stmt);
Max00b37152017-02-20 11:09:27 +0100127}
128
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200129/** bind text arg and do proper cleanup in case of failure. If param_name is
130 * NULL, bind to the first parameter (useful for SQL statements that have only
131 * one parameter). */
132bool db_bind_text(sqlite3_stmt *stmt, const char *param_name, const char *text)
Max00b37152017-02-20 11:09:27 +0100133{
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200134 int rc;
135 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
136 if (idx < 1) {
137 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
138 param_name);
139 return false;
140 }
141 rc = sqlite3_bind_text(stmt, idx, text, -1, SQLITE_STATIC);
Max00b37152017-02-20 11:09:27 +0100142 if (rc != SQLITE_OK) {
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200143 LOGP(DDB, LOGL_ERROR, "Error binding text to SQL parameter %s: %d\n",
144 param_name ? param_name : "#1", rc);
Max00b37152017-02-20 11:09:27 +0100145 db_remove_reset(stmt);
146 return false;
147 }
Max00b37152017-02-20 11:09:27 +0100148 return true;
149}
150
Neels Hofmeyr28da26e2017-10-06 03:44:57 +0200151/** bind int arg and do proper cleanup in case of failure. If param_name is
152 * NULL, bind to the first parameter (useful for SQL statements that have only
153 * one parameter). */
154bool db_bind_int(sqlite3_stmt *stmt, const char *param_name, int nr)
155{
156 int rc;
157 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
158 if (idx < 1) {
159 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
160 param_name);
161 return false;
162 }
163 rc = sqlite3_bind_int(stmt, idx, nr);
164 if (rc != SQLITE_OK) {
165 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
166 param_name ? param_name : "#1", rc);
167 db_remove_reset(stmt);
168 return false;
169 }
170 return true;
171}
172
173/** bind int64 arg and do proper cleanup in case of failure. If param_name is
174 * NULL, bind to the first parameter (useful for SQL statements that have only
175 * one parameter). */
176bool db_bind_int64(sqlite3_stmt *stmt, const char *param_name, int64_t nr)
177{
178 int rc;
179 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
180 if (idx < 1) {
181 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
182 param_name);
183 return false;
184 }
185 rc = sqlite3_bind_int64(stmt, idx, nr);
186 if (rc != SQLITE_OK) {
187 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
188 param_name ? param_name : "#1", rc);
189 db_remove_reset(stmt);
190 return false;
191 }
192 return true;
193}
194
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100195bool db_bind_null(sqlite3_stmt *stmt, const char *param_name)
196{
197 int rc;
198 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
199 if (idx < 1) {
200 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
201 param_name);
202 return false;
203 }
204 rc = sqlite3_bind_null(stmt, idx);
205 if (rc != SQLITE_OK) {
206 LOGP(DDB, LOGL_ERROR, "Error binding NULL to SQL parameter %s: %d\n",
207 param_name ? param_name : "#1", rc);
208 db_remove_reset(stmt);
209 return false;
210 }
211 return true;
212}
213
Harald Weltee72cf552016-04-28 07:18:49 +0200214void db_close(struct db_context *dbc)
215{
216 unsigned int i;
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700217 int rc;
Harald Weltee72cf552016-04-28 07:18:49 +0200218
219 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
220 /* it is ok to call finalize on NULL */
221 sqlite3_finalize(dbc->stmt[i]);
222 }
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700223
224 /* Ask sqlite3 to close DB */
225 rc = sqlite3_close(dbc->db);
226 if (rc != SQLITE_OK) { /* Make sure it's actually closed! */
227 LOGP(DDB, LOGL_ERROR, "Couldn't close database: (rc=%d) %s\n",
228 rc, sqlite3_errmsg(dbc->db));
229 }
230
Harald Weltee72cf552016-04-28 07:18:49 +0200231 talloc_free(dbc);
232}
233
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100234static int db_run_statements(struct db_context *dbc, const char **statements, size_t statements_count)
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200235{
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100236 int rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200237 int i;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100238 for (i = 0; i < statements_count; i++) {
239 const char *stmt_str = statements[i];
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200240 sqlite3_stmt *stmt;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100241
242 rc = sqlite3_prepare_v2(dbc->db, stmt_str, -1, &stmt, NULL);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200243 if (rc != SQLITE_OK) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100244 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_str);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700245 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200246 }
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200247 rc = sqlite3_step(stmt);
248 db_remove_reset(stmt);
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700249 sqlite3_finalize(stmt);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200250 if (rc != SQLITE_DONE) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100251 LOGP(DDB, LOGL_ERROR, "SQL error: (%d) %s, during stmt '%s'",
252 rc, sqlite3_errmsg(dbc->db), stmt_str);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700253 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200254 }
255 }
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100256 return rc;
257}
258
259static int db_bootstrap(struct db_context *dbc)
260{
261 int rc = db_run_statements(dbc, stmt_bootstrap_sql, ARRAY_SIZE(stmt_bootstrap_sql));
262 if (rc != SQLITE_DONE) {
263 LOGP(DDB, LOGL_ERROR, "Cannot bootstrap database\n");
264 return rc;
265 }
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700266 return SQLITE_OK;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200267}
268
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100269/* https://www.sqlite.org/fileformat2.html#storage_of_the_sql_database_schema */
270static bool db_table_exists(struct db_context *dbc, const char *table_name)
271{
272 const char *table_exists_sql = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
273 sqlite3_stmt *stmt;
274 int rc;
275
276 rc = sqlite3_prepare_v2(dbc->db, table_exists_sql, -1, &stmt, NULL);
277 if (rc != SQLITE_OK) {
278 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", table_exists_sql);
279 return false;
280 }
281
282 if (!db_bind_text(stmt, NULL, table_name))
283 return false;
284
285 rc = sqlite3_step(stmt);
286 db_remove_reset(stmt);
287 sqlite3_finalize(stmt);
288 return (rc == SQLITE_ROW);
289}
290
291/* Indicate whether the database is initialized with tables for schema version 0.
292 * We only check for the 'subscriber' table here because Neels said so. */
293static bool db_is_bootstrapped_v0(struct db_context *dbc)
294{
295 if (!db_table_exists(dbc, "subscriber")) {
296 LOGP(DDB, LOGL_DEBUG, "Table 'subscriber' not found in database '%s'\n", dbc->fname);
297 return false;
298 }
299
300 return true;
301}
302
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100303static int
304db_upgrade_v1(struct db_context *dbc)
305{
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100306 int rc;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100307 const char *statements[] = {
308 "ALTER TABLE subscriber ADD COLUMN last_lu_seen TIMESTAMP default NULL",
309 "PRAGMA user_version = 1",
310 };
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100311
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100312 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100313 if (rc != SQLITE_DONE) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100314 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 1\n");
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100315 return rc;
316 }
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100317 return rc;
318}
319
Oliver Smith81db3892019-01-09 12:03:51 +0100320static int db_upgrade_v2(struct db_context *dbc)
321{
Oliver Smith81db3892019-01-09 12:03:51 +0100322 int rc;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100323 const char *statements[] = {
324 "ALTER TABLE subscriber ADD COLUMN imei VARCHAR(14)",
325 "PRAGMA user_version = 2",
326 };
Oliver Smith81db3892019-01-09 12:03:51 +0100327
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100328 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
Oliver Smith81db3892019-01-09 12:03:51 +0100329 if (rc != SQLITE_DONE) {
Neels Hofmeyrf5459de2019-10-31 01:29:59 +0100330 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 2\n");
Oliver Smith81db3892019-01-09 12:03:51 +0100331 return rc;
332 }
Oliver Smith81db3892019-01-09 12:03:51 +0100333 return rc;
334}
335
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100336static int db_upgrade_v3(struct db_context *dbc)
337{
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100338 int rc;
339
340 /* A newer SQLite version would allow simply 'ATLER TABLE subscriber RENAME COLUMN hlr_number TO msc_number'.
341 * This is a really expensive workaround for that in order to cover earlier SQLite versions as well:
342 * Create a new table with the new column name and copy the data over (https://www.sqlite.org/faq.html#q11).
343 */
344#define SUBSCR_V3_CREATE \
345"(\n" \
346"-- OsmoHLR's DB scheme is modelled roughly after TS 23.008 version 13.3.0\n" \
347" id INTEGER PRIMARY KEY,\n" \
348" -- Chapter 2.1.1.1\n" \
349" imsi VARCHAR(15) UNIQUE NOT NULL,\n" \
350" -- Chapter 2.1.2\n" \
351" msisdn VARCHAR(15) UNIQUE,\n" \
352" -- Chapter 2.2.3: Most recent / current IMEISV\n" \
353" imeisv VARCHAR,\n" \
354" -- Chapter 2.1.9: Most recent / current IMEI\n" \
355" imei VARCHAR(14),\n" \
356" -- Chapter 2.4.5\n" \
357" vlr_number VARCHAR(15),\n" \
358" -- Chapter 2.4.6\n" \
359" msc_number VARCHAR(15),\n" \
360" -- Chapter 2.4.8.1\n" \
361" sgsn_number VARCHAR(15),\n" \
362" -- Chapter 2.13.10\n" \
363" sgsn_address VARCHAR,\n" \
364" -- Chapter 2.4.8.2\n" \
365" ggsn_number VARCHAR(15),\n" \
366" -- Chapter 2.4.9.2\n" \
367" gmlc_number VARCHAR(15),\n" \
368" -- Chapter 2.4.23\n" \
369" smsc_number VARCHAR(15),\n" \
370" -- Chapter 2.4.24\n" \
371" periodic_lu_tmr INTEGER,\n" \
372" -- Chapter 2.13.115\n" \
373" periodic_rau_tau_tmr INTEGER,\n" \
374" -- Chapter 2.1.1.2: network access mode\n" \
375" nam_cs BOOLEAN NOT NULL DEFAULT 1,\n" \
376" nam_ps BOOLEAN NOT NULL DEFAULT 1,\n" \
377" -- Chapter 2.1.8\n" \
378" lmsi INTEGER,\n" \
379 \
380" -- The below purged flags might not even be stored non-volatile,\n" \
381" -- refer to TS 23.012 Chapter 3.6.1.4\n" \
382" -- Chapter 2.7.5\n" \
383" ms_purged_cs BOOLEAN NOT NULL DEFAULT 0,\n" \
384" -- Chapter 2.7.6\n" \
385" ms_purged_ps BOOLEAN NOT NULL DEFAULT 0,\n" \
386 \
387" -- Timestamp of last location update seen from subscriber\n" \
388" -- The value is a string which encodes a UTC timestamp in granularity of seconds.\n" \
389" last_lu_seen TIMESTAMP default NULL\n" \
390")\n"
391
392#define SUBSCR_V2_COLUMN_NAMES \
393 "id," \
394 "imsi," \
395 "msisdn," \
396 "imeisv," \
397 "imei," \
398 "vlr_number," \
399 "hlr_number," \
400 "sgsn_number," \
401 "sgsn_address," \
402 "ggsn_number," \
403 "gmlc_number," \
404 "smsc_number," \
405 "periodic_lu_tmr," \
406 "periodic_rau_tau_tmr," \
407 "nam_cs," \
408 "nam_ps," \
409 "lmsi," \
410 "ms_purged_cs," \
411 "ms_purged_ps," \
412 "last_lu_seen"
413
414#define SUBSCR_V3_COLUMN_NAMES \
415 "id," \
416 "imsi," \
417 "msisdn," \
418 "imeisv," \
419 "imei," \
420 "vlr_number," \
421 "msc_number," \
422 "sgsn_number," \
423 "sgsn_address," \
424 "ggsn_number," \
425 "gmlc_number," \
426 "smsc_number," \
427 "periodic_lu_tmr," \
428 "periodic_rau_tau_tmr," \
429 "nam_cs," \
430 "nam_ps," \
431 "lmsi," \
432 "ms_purged_cs," \
433 "ms_purged_ps," \
434 "last_lu_seen"
435
436 const char *statements[] = {
437 "BEGIN TRANSACTION",
438 "CREATE TEMPORARY TABLE subscriber_backup" SUBSCR_V3_CREATE,
439 "INSERT INTO subscriber_backup SELECT " SUBSCR_V2_COLUMN_NAMES " FROM subscriber",
440 "DROP TABLE subscriber",
441 "CREATE TABLE subscriber" SUBSCR_V3_CREATE,
442 "INSERT INTO subscriber SELECT " SUBSCR_V3_COLUMN_NAMES " FROM subscriber_backup",
443 "DROP TABLE subscriber_backup",
444 "COMMIT",
445 "PRAGMA user_version = 3",
446 };
447
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100448 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
449 if (rc != SQLITE_DONE) {
450 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 3\n");
451 return rc;
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100452 }
453 return rc;
454}
455
Neels Hofmeyr07e16022019-11-20 02:36:35 +0100456static int db_upgrade_v4(struct db_context *dbc)
457{
458 int rc;
459 const char *statements[] = {
460 "ALTER TABLE subscriber ADD COLUMN last_lu_seen_ps TIMESTAMP default NULL",
461 "PRAGMA user_version = 4",
462 };
463
464 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
465 if (rc != SQLITE_DONE) {
466 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 4\n");
467 return rc;
468 }
469 return rc;
470}
471
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100472static int db_upgrade_v5(struct db_context *dbc)
473{
474 int rc;
475 const char *statements[] = {
476 "ALTER TABLE subscriber ADD COLUMN vlr_via_proxy VARCHAR",
477 "ALTER TABLE subscriber ADD COLUMN sgsn_via_proxy VARCHAR",
478 "PRAGMA user_version = 5",
479 };
480
481 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
482 if (rc != SQLITE_DONE) {
483 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 5\n");
484 return rc;
485 }
486 return rc;
487}
488
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100489typedef int (*db_upgrade_func_t)(struct db_context *dbc);
490static db_upgrade_func_t db_upgrade_path[] = {
491 db_upgrade_v1,
492 db_upgrade_v2,
493 db_upgrade_v3,
Neels Hofmeyr07e16022019-11-20 02:36:35 +0100494 db_upgrade_v4,
Neels Hofmeyr04c23752019-11-25 03:59:50 +0100495 db_upgrade_v5,
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100496};
497
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100498static int db_get_user_version(struct db_context *dbc)
499{
500 const char *user_version_sql = "PRAGMA user_version";
501 sqlite3_stmt *stmt;
502 int version, rc;
503
504 rc = sqlite3_prepare_v2(dbc->db, user_version_sql, -1, &stmt, NULL);
505 if (rc != SQLITE_OK) {
506 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", user_version_sql);
507 return -1;
508 }
509 rc = sqlite3_step(stmt);
510 if (rc == SQLITE_ROW) {
511 version = sqlite3_column_int(stmt, 0);
512 } else {
513 LOGP(DDB, LOGL_ERROR, "SQL statement '%s' failed: %d\n", user_version_sql, rc);
514 version = -1;
515 }
516
517 db_remove_reset(stmt);
518 sqlite3_finalize(stmt);
519 return version;
520}
521
522struct db_context *db_open(void *ctx, const char *fname, bool enable_sqlite_logging, bool allow_upgrade)
Harald Weltee72cf552016-04-28 07:18:49 +0200523{
524 struct db_context *dbc = talloc_zero(ctx, struct db_context);
525 unsigned int i;
526 int rc;
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200527 bool has_sqlite_config_sqllog = false;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100528 int version;
Harald Weltee72cf552016-04-28 07:18:49 +0200529
Neels Hofmeyr7f9491f2017-01-30 13:30:47 +0100530 LOGP(DDB, LOGL_NOTICE, "using database: %s\n", fname);
Harald Weltee72cf552016-04-28 07:18:49 +0200531 LOGP(DDB, LOGL_INFO, "Compiled against SQLite3 lib version %s\n", SQLITE_VERSION);
532 LOGP(DDB, LOGL_INFO, "Running with SQLite3 lib version %s\n", sqlite3_libversion());
533
Vadim Yanitskiyfbd736e2018-07-31 22:40:30 +0700534#ifdef SQLITE_USE_TALLOC
535 /* Configure SQLite3 to use talloc memory allocator */
536 rc = db_sqlite3_use_talloc(ctx);
537 if (rc == SQLITE_OK) {
538 LOGP(DDB, LOGL_NOTICE, "SQLite3 is configured to use talloc\n");
539 } else {
540 LOGP(DDB, LOGL_ERROR, "Failed to configure SQLite3 "
541 "to use talloc, using default memory allocator\n");
542 }
543#endif
544
Harald Weltee72cf552016-04-28 07:18:49 +0200545 dbc->fname = talloc_strdup(dbc, fname);
546
547 for (i = 0; i < 0xfffff; i++) {
548 const char *o = sqlite3_compileoption_get(i);
549 if (!o)
550 break;
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200551 LOGP(DDB, LOGL_DEBUG, "SQLite3 compiled with '%s'\n", o);
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200552 if (!strcmp(o, "ENABLE_SQLLOG"))
553 has_sqlite_config_sqllog = true;
Harald Weltee72cf552016-04-28 07:18:49 +0200554 }
555
Neels Hofmeyrd3814b92017-11-21 12:28:07 +0100556 if (enable_sqlite_logging) {
557 rc = sqlite3_config(SQLITE_CONFIG_LOG, sql3_error_log_cb, NULL);
558 if (rc != SQLITE_OK)
559 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 error log callback\n");
560 }
Harald Weltee72cf552016-04-28 07:18:49 +0200561
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200562 if (has_sqlite_config_sqllog) {
563 rc = sqlite3_config(SQLITE_CONFIG_SQLLOG, sql3_sql_log_cb, NULL);
564 if (rc != SQLITE_OK)
565 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 SQL log callback\n");
566 } else
567 LOGP(DDB, LOGL_DEBUG, "Not setting SQL log callback:"
568 " SQLite3 compiled without support for it\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200569
570 rc = sqlite3_open(dbc->fname, &dbc->db);
571 if (rc != SQLITE_OK) {
572 LOGP(DDB, LOGL_ERROR, "Unable to open DB; rc = %d\n", rc);
573 talloc_free(dbc);
574 return NULL;
575 }
576
577 /* enable extended result codes */
578 rc = sqlite3_extended_result_codes(dbc->db, 1);
579 if (rc != SQLITE_OK)
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200580 LOGP(DDB, LOGL_ERROR, "Unable to enable SQLite3 extended result codes\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200581
Harald Welteabd1a542016-05-03 18:50:41 +0200582 char *err_msg;
583 rc = sqlite3_exec(dbc->db, "PRAGMA journal_mode=WAL; PRAGMA synchonous = NORMAL;", 0, 0, &err_msg);
Vadim Yanitskiy15ad7be2020-02-09 05:32:46 +0700584 if (rc != SQLITE_OK) {
Harald Welteabd1a542016-05-03 18:50:41 +0200585 LOGP(DDB, LOGL_ERROR, "Unable to set Write-Ahead Logging: %s\n",
586 err_msg);
Vadim Yanitskiy15ad7be2020-02-09 05:32:46 +0700587 sqlite3_free(err_msg);
588 }
Harald Welteabd1a542016-05-03 18:50:41 +0200589
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100590 version = db_get_user_version(dbc);
591 if (version < 0) {
592 LOGP(DDB, LOGL_ERROR, "Unable to read user version number from database '%s'\n", dbc->fname);
593 goto out_free;
594 }
595
596 /* An empty database will always report version zero. */
597 if (version == 0 && !db_is_bootstrapped_v0(dbc)) {
598 LOGP(DDB, LOGL_NOTICE, "Missing database tables detected; Bootstrapping database '%s'\n", dbc->fname);
599 rc = db_bootstrap(dbc);
600 if (rc != SQLITE_OK) {
601 LOGP(DDB, LOGL_ERROR, "Failed to bootstrap DB: (rc=%d) %s\n",
602 rc, sqlite3_errmsg(dbc->db));
603 goto out_free;
604 }
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100605 version = CURRENT_SCHEMA_VERSION;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100606 }
607
608 LOGP(DDB, LOGL_NOTICE, "Database '%s' has HLR DB schema version %d\n", dbc->fname, version);
609
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100610 for (; allow_upgrade && (version < ARRAY_SIZE(db_upgrade_path)); version++) {
611 db_upgrade_func_t upgrade_func = db_upgrade_path[version];
612 rc = upgrade_func(dbc);
613 if (rc != SQLITE_DONE) {
614 LOGP(DDB, LOGL_ERROR, "Failed to upgrade HLR DB schema to version %d: (rc=%d) %s\n",
615 version+1, rc, sqlite3_errmsg(dbc->db));
616 goto out_free;
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100617 }
618 LOGP(DDB, LOGL_NOTICE, "Database '%s' has been upgraded to HLR DB schema version %d\n",
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100619 dbc->fname, version+1);
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100620 }
621
622 if (version != CURRENT_SCHEMA_VERSION) {
623 if (version < CURRENT_SCHEMA_VERSION) {
624 LOGP(DDB, LOGL_NOTICE, "HLR DB schema version %d is outdated\n", version);
625 if (!allow_upgrade) {
626 LOGP(DDB, LOGL_ERROR, "Not upgrading HLR database to schema version %d; "
627 "use the --db-upgrade option to allow HLR database upgrades\n",
628 CURRENT_SCHEMA_VERSION);
629 }
630 } else
631 LOGP(DDB, LOGL_ERROR, "HLR DB schema version %d is unknown\n", version);
632
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700633 goto out_free;
634 }
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200635
Harald Weltee72cf552016-04-28 07:18:49 +0200636 /* prepare all SQL statements */
637 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
638 rc = sqlite3_prepare_v2(dbc->db, stmt_sql[i], -1,
639 &dbc->stmt[i], NULL);
640 if (rc != SQLITE_OK) {
641 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_sql[i]);
642 goto out_free;
643 }
644 }
645
646 return dbc;
647out_free:
648 db_close(dbc);
649 return NULL;
650}