blob: 29f38cf751acb81779fa6581ff0dbaf092a85e3c [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>
Neels Hofmeyrf13a8bc2019-11-20 02:36:45 +010025#include <errno.h>
Harald Weltee72cf552016-04-28 07:18:49 +020026
Neels Hofmeyr2f758032019-11-20 00:37:07 +010027#include <osmocom/hlr/logging.h>
28#include <osmocom/hlr/db.h>
Neels Hofmeyrf13a8bc2019-11-20 02:36:45 +010029
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +020030#include "db_bootstrap.h"
Harald Weltee72cf552016-04-28 07:18:49 +020031
Stefan Sperling638ba8c2018-12-04 15:07:29 +010032/* This constant is currently duplicated in sql/hlr.sql and must be kept in sync! */
Neels Hofmeyr5bc457e2018-12-29 03:28:38 +010033#define CURRENT_SCHEMA_VERSION 8
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +010034
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020035#define SEL_COLUMNS \
36 "id," \
37 "imsi," \
38 "msisdn," \
Oliver Smith81db3892019-01-09 12:03:51 +010039 "imei," \
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020040 "vlr_number," \
41 "sgsn_number," \
42 "sgsn_address," \
43 "periodic_lu_tmr," \
44 "periodic_rau_tau_tmr," \
45 "nam_cs," \
46 "nam_ps," \
47 "lmsi," \
48 "ms_purged_cs," \
Stefan Sperling638ba8c2018-12-04 15:07:29 +010049 "ms_purged_ps," \
Neels Hofmeyr07e16022019-11-20 02:36:35 +010050 "last_lu_seen," \
Neels Hofmeyrf0c02ad2019-11-25 03:59:50 +010051 "last_lu_seen_ps," \
Neels Hofmeyr5bc457e2018-12-29 03:28:38 +010052 "last_lu_rat_cs," \
53 "last_lu_rat_ps," \
Neels Hofmeyrf0c02ad2019-11-25 03:59:50 +010054 "vlr_via_proxy," \
55 "sgsn_via_proxy"
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020056
Harald Weltee72cf552016-04-28 07:18:49 +020057static const char *stmt_sql[] = {
Neels Hofmeyr9c2bbc82017-10-09 17:30:32 +020058 [DB_STMT_SEL_BY_IMSI] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE imsi = ?",
59 [DB_STMT_SEL_BY_MSISDN] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE msisdn = ?",
60 [DB_STMT_SEL_BY_ID] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE id = ?",
Oliver Smith81db3892019-01-09 12:03:51 +010061 [DB_STMT_SEL_BY_IMEI] = "SELECT " SEL_COLUMNS " FROM subscriber WHERE imei = ?",
Neels Hofmeyrf0c02ad2019-11-25 03:59:50 +010062 [DB_STMT_UPD_VLR_BY_ID] = "UPDATE subscriber SET vlr_number = $number, vlr_via_proxy = $proxy WHERE id = $subscriber_id",
63 [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 +010064 [DB_STMT_UPD_IMEI_BY_IMSI] = "UPDATE subscriber SET imei = $imei WHERE imsi = $imsi",
Neels Hofmeyr0cac0a02017-10-09 17:47:21 +020065 [DB_STMT_AUC_BY_IMSI] =
66 "SELECT id, algo_id_2g, ki, algo_id_3g, k, op, opc, sqn, ind_bitlen"
67 " FROM subscriber"
68 " LEFT JOIN auc_2g ON auc_2g.subscriber_id = subscriber.id"
69 " LEFT JOIN auc_3g ON auc_3g.subscriber_id = subscriber.id"
Neels Hofmeyrc5122f22017-10-09 23:12:57 +020070 " WHERE imsi = $imsi",
Neels Hofmeyr1cbdb702017-10-09 23:03:57 +020071 [DB_STMT_AUC_UPD_SQN] = "UPDATE auc_3g SET sqn = $sqn WHERE subscriber_id = $subscriber_id",
Neels Hofmeyre50121e2017-10-09 17:48:51 +020072 [DB_STMT_UPD_PURGE_CS_BY_IMSI] = "UPDATE subscriber SET ms_purged_cs = $val WHERE imsi = $imsi",
73 [DB_STMT_UPD_PURGE_PS_BY_IMSI] = "UPDATE subscriber SET ms_purged_ps = $val WHERE imsi = $imsi",
Neels Hofmeyre8ccd502017-10-06 04:10:06 +020074 [DB_STMT_UPD_NAM_CS_BY_IMSI] = "UPDATE subscriber SET nam_cs = $val WHERE imsi = $imsi",
75 [DB_STMT_UPD_NAM_PS_BY_IMSI] = "UPDATE subscriber SET nam_ps = $val WHERE imsi = $imsi",
Oliver Smithcd2af5e2019-03-06 13:17:39 +010076 [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 +020077 [DB_STMT_DEL_BY_ID] = "DELETE FROM subscriber WHERE id = $subscriber_id",
78 [DB_STMT_SET_MSISDN_BY_IMSI] = "UPDATE subscriber SET msisdn = $msisdn WHERE imsi = $imsi",
Neels Hofmeyra820ea12018-12-02 19:46:46 +010079 [DB_STMT_DELETE_MSISDN_BY_IMSI] = "UPDATE subscriber SET msisdn = NULL WHERE imsi = $imsi",
Neels Hofmeyr1332a172017-10-10 02:25:00 +020080 [DB_STMT_AUC_2G_INSERT] =
81 "INSERT INTO auc_2g (subscriber_id, algo_id_2g, ki)"
82 " VALUES($subscriber_id, $algo_id_2g, $ki)",
83 [DB_STMT_AUC_2G_DELETE] = "DELETE FROM auc_2g WHERE subscriber_id = $subscriber_id",
84 [DB_STMT_AUC_3G_INSERT] =
85 "INSERT INTO auc_3g (subscriber_id, algo_id_3g, k, op, opc, ind_bitlen)"
86 " VALUES($subscriber_id, $algo_id_3g, $k, $op, $opc, $ind_bitlen)",
87 [DB_STMT_AUC_3G_DELETE] = "DELETE FROM auc_3g WHERE subscriber_id = $subscriber_id",
Neels Hofmeyr5bc457e2018-12-29 03:28:38 +010088 [DB_STMT_SET_LAST_LU_SEEN] = "UPDATE subscriber SET last_lu_seen = datetime($val, 'unixepoch'),"
89 " last_lu_rat_cs = $rat"
90 " WHERE id = $subscriber_id",
91 [DB_STMT_SET_LAST_LU_SEEN_PS] = "UPDATE subscriber SET last_lu_seen_ps = datetime($val, 'unixepoch'),"
92 " last_lu_rat_ps = $rat"
93 " 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 Hofmeyr92d1c4a2019-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",
Neels Hofmeyrce172ef2018-12-26 01:49:53 +010099 [DB_STMT_UPD_RAT_FLAG] = "INSERT OR REPLACE INTO subscriber_rat (subscriber_id, rat, allowed)"
100 " VALUES ($subscriber_id, $rat, $allowed)",
101 [DB_STMT_RAT_BY_ID] =
102 "SELECT rat, allowed"
103 " FROM subscriber_rat"
104 " WHERE subscriber_id = $subscriber_id",
Harald Weltee72cf552016-04-28 07:18:49 +0200105};
106
107static void sql3_error_log_cb(void *arg, int err_code, const char *msg)
108{
109 LOGP(DDB, LOGL_ERROR, "(%d) %s\n", err_code, msg);
110}
111
112static void sql3_sql_log_cb(void *arg, sqlite3 *s3, const char *stmt, int type)
113{
114 switch (type) {
115 case 0:
116 LOGP(DDB, LOGL_DEBUG, "Opened database\n");
117 break;
118 case 1:
Max58d4a842017-02-20 11:06:12 +0100119 LOGP(DDB, LOGL_DEBUG, "%s\n", stmt);
Harald Weltee72cf552016-04-28 07:18:49 +0200120 break;
121 case 2:
122 LOGP(DDB, LOGL_DEBUG, "Closed database\n");
123 break;
124 default:
125 LOGP(DDB, LOGL_DEBUG, "Unknown %d\n", type);
126 break;
127 }
128}
129
Max00b37152017-02-20 11:09:27 +0100130/* remove bindings and reset statement to be re-executed */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200131void db_remove_reset(sqlite3_stmt *stmt)
Max00b37152017-02-20 11:09:27 +0100132{
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200133 sqlite3_clear_bindings(stmt);
Neels Hofmeyr4f3841c2017-11-07 13:24:44 +0100134 /* sqlite3_reset() just repeats an error code already evaluated during sqlite3_step(). */
135 /* coverity[CHECKED_RETURN] */
Neels Hofmeyrd7d96972017-10-06 03:50:30 +0200136 sqlite3_reset(stmt);
Max00b37152017-02-20 11:09:27 +0100137}
138
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200139/** bind text arg and do proper cleanup in case of failure. If param_name is
140 * NULL, bind to the first parameter (useful for SQL statements that have only
141 * one parameter). */
142bool db_bind_text(sqlite3_stmt *stmt, const char *param_name, const char *text)
Max00b37152017-02-20 11:09:27 +0100143{
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200144 int rc;
145 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
146 if (idx < 1) {
147 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
148 param_name);
149 return false;
150 }
151 rc = sqlite3_bind_text(stmt, idx, text, -1, SQLITE_STATIC);
Max00b37152017-02-20 11:09:27 +0100152 if (rc != SQLITE_OK) {
Neels Hofmeyrf3144592017-10-06 03:40:52 +0200153 LOGP(DDB, LOGL_ERROR, "Error binding text to SQL parameter %s: %d\n",
154 param_name ? param_name : "#1", rc);
Max00b37152017-02-20 11:09:27 +0100155 db_remove_reset(stmt);
156 return false;
157 }
Max00b37152017-02-20 11:09:27 +0100158 return true;
159}
160
Neels Hofmeyr28da26e2017-10-06 03:44:57 +0200161/** bind int arg and do proper cleanup in case of failure. If param_name is
162 * NULL, bind to the first parameter (useful for SQL statements that have only
163 * one parameter). */
164bool db_bind_int(sqlite3_stmt *stmt, const char *param_name, int nr)
165{
166 int rc;
167 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
168 if (idx < 1) {
169 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
170 param_name);
171 return false;
172 }
173 rc = sqlite3_bind_int(stmt, idx, nr);
174 if (rc != SQLITE_OK) {
175 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
176 param_name ? param_name : "#1", rc);
177 db_remove_reset(stmt);
178 return false;
179 }
180 return true;
181}
182
183/** bind int64 arg and do proper cleanup in case of failure. If param_name is
184 * NULL, bind to the first parameter (useful for SQL statements that have only
185 * one parameter). */
186bool db_bind_int64(sqlite3_stmt *stmt, const char *param_name, int64_t nr)
187{
188 int rc;
189 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
190 if (idx < 1) {
191 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
192 param_name);
193 return false;
194 }
195 rc = sqlite3_bind_int64(stmt, idx, nr);
196 if (rc != SQLITE_OK) {
197 LOGP(DDB, LOGL_ERROR, "Error binding int64 to SQL parameter %s: %d\n",
198 param_name ? param_name : "#1", rc);
199 db_remove_reset(stmt);
200 return false;
201 }
202 return true;
203}
204
Neels Hofmeyrf0c02ad2019-11-25 03:59:50 +0100205bool db_bind_null(sqlite3_stmt *stmt, const char *param_name)
206{
207 int rc;
208 int idx = param_name ? sqlite3_bind_parameter_index(stmt, param_name) : 1;
209 if (idx < 1) {
210 LOGP(DDB, LOGL_ERROR, "Error composing SQL, cannot bind parameter '%s'\n",
211 param_name);
212 return false;
213 }
214 rc = sqlite3_bind_null(stmt, idx);
215 if (rc != SQLITE_OK) {
216 LOGP(DDB, LOGL_ERROR, "Error binding NULL to SQL parameter %s: %d\n",
217 param_name ? param_name : "#1", rc);
218 db_remove_reset(stmt);
219 return false;
220 }
221 return true;
222}
223
Harald Weltee72cf552016-04-28 07:18:49 +0200224void db_close(struct db_context *dbc)
225{
226 unsigned int i;
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700227 int rc;
Harald Weltee72cf552016-04-28 07:18:49 +0200228
229 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
230 /* it is ok to call finalize on NULL */
231 sqlite3_finalize(dbc->stmt[i]);
232 }
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700233
234 /* Ask sqlite3 to close DB */
235 rc = sqlite3_close(dbc->db);
236 if (rc != SQLITE_OK) { /* Make sure it's actually closed! */
237 LOGP(DDB, LOGL_ERROR, "Couldn't close database: (rc=%d) %s\n",
238 rc, sqlite3_errmsg(dbc->db));
239 }
240
Harald Weltee72cf552016-04-28 07:18:49 +0200241 talloc_free(dbc);
242}
243
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100244static int db_run_statements(struct db_context *dbc, const char **statements, size_t statements_count)
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200245{
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100246 int rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200247 int i;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100248 for (i = 0; i < statements_count; i++) {
249 const char *stmt_str = statements[i];
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200250 sqlite3_stmt *stmt;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100251
252 rc = sqlite3_prepare_v2(dbc->db, stmt_str, -1, &stmt, NULL);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200253 if (rc != SQLITE_OK) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100254 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_str);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700255 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200256 }
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200257 rc = sqlite3_step(stmt);
258 db_remove_reset(stmt);
Vadim Yanitskiydc17e052018-07-30 20:14:16 +0700259 sqlite3_finalize(stmt);
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200260 if (rc != SQLITE_DONE) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100261 LOGP(DDB, LOGL_ERROR, "SQL error: (%d) %s, during stmt '%s'",
262 rc, sqlite3_errmsg(dbc->db), stmt_str);
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700263 return rc;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200264 }
265 }
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100266 return rc;
267}
268
269static int db_bootstrap(struct db_context *dbc)
270{
271 int rc = db_run_statements(dbc, stmt_bootstrap_sql, ARRAY_SIZE(stmt_bootstrap_sql));
272 if (rc != SQLITE_DONE) {
273 LOGP(DDB, LOGL_ERROR, "Cannot bootstrap database\n");
274 return rc;
275 }
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700276 return SQLITE_OK;
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200277}
278
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100279/* https://www.sqlite.org/fileformat2.html#storage_of_the_sql_database_schema */
280static bool db_table_exists(struct db_context *dbc, const char *table_name)
281{
282 const char *table_exists_sql = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
283 sqlite3_stmt *stmt;
284 int rc;
285
286 rc = sqlite3_prepare_v2(dbc->db, table_exists_sql, -1, &stmt, NULL);
287 if (rc != SQLITE_OK) {
288 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", table_exists_sql);
289 return false;
290 }
291
292 if (!db_bind_text(stmt, NULL, table_name))
293 return false;
294
295 rc = sqlite3_step(stmt);
296 db_remove_reset(stmt);
297 sqlite3_finalize(stmt);
298 return (rc == SQLITE_ROW);
299}
300
301/* Indicate whether the database is initialized with tables for schema version 0.
302 * We only check for the 'subscriber' table here because Neels said so. */
303static bool db_is_bootstrapped_v0(struct db_context *dbc)
304{
305 if (!db_table_exists(dbc, "subscriber")) {
306 LOGP(DDB, LOGL_DEBUG, "Table 'subscriber' not found in database '%s'\n", dbc->fname);
307 return false;
308 }
309
310 return true;
311}
312
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100313static int
314db_upgrade_v1(struct db_context *dbc)
315{
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100316 int rc;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100317 const char *statements[] = {
318 "ALTER TABLE subscriber ADD COLUMN last_lu_seen TIMESTAMP default NULL",
319 "PRAGMA user_version = 1",
320 };
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100321
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100322 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100323 if (rc != SQLITE_DONE) {
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100324 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 1\n");
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100325 return rc;
326 }
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100327 return rc;
328}
329
Oliver Smith81db3892019-01-09 12:03:51 +0100330static int db_upgrade_v2(struct db_context *dbc)
331{
Oliver Smith81db3892019-01-09 12:03:51 +0100332 int rc;
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100333 const char *statements[] = {
334 "ALTER TABLE subscriber ADD COLUMN imei VARCHAR(14)",
335 "PRAGMA user_version = 2",
336 };
Oliver Smith81db3892019-01-09 12:03:51 +0100337
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100338 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
Oliver Smith81db3892019-01-09 12:03:51 +0100339 if (rc != SQLITE_DONE) {
Neels Hofmeyrf5459de2019-10-31 01:29:59 +0100340 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 2\n");
Oliver Smith81db3892019-01-09 12:03:51 +0100341 return rc;
342 }
Oliver Smith81db3892019-01-09 12:03:51 +0100343 return rc;
344}
345
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100346static int db_upgrade_v3(struct db_context *dbc)
347{
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100348 int rc;
349
Neels Hofmeyr1f8f1b92019-12-25 18:33:19 +0100350 /* A newer SQLite version would allow simply 'ALTER TABLE subscriber RENAME COLUMN hlr_number TO msc_number'.
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100351 * This is a really expensive workaround for that in order to cover earlier SQLite versions as well:
352 * Create a new table with the new column name and copy the data over (https://www.sqlite.org/faq.html#q11).
353 */
354#define SUBSCR_V3_CREATE \
355"(\n" \
356"-- OsmoHLR's DB scheme is modelled roughly after TS 23.008 version 13.3.0\n" \
357" id INTEGER PRIMARY KEY,\n" \
358" -- Chapter 2.1.1.1\n" \
359" imsi VARCHAR(15) UNIQUE NOT NULL,\n" \
360" -- Chapter 2.1.2\n" \
361" msisdn VARCHAR(15) UNIQUE,\n" \
362" -- Chapter 2.2.3: Most recent / current IMEISV\n" \
363" imeisv VARCHAR,\n" \
364" -- Chapter 2.1.9: Most recent / current IMEI\n" \
365" imei VARCHAR(14),\n" \
366" -- Chapter 2.4.5\n" \
367" vlr_number VARCHAR(15),\n" \
368" -- Chapter 2.4.6\n" \
369" msc_number VARCHAR(15),\n" \
370" -- Chapter 2.4.8.1\n" \
371" sgsn_number VARCHAR(15),\n" \
372" -- Chapter 2.13.10\n" \
373" sgsn_address VARCHAR,\n" \
374" -- Chapter 2.4.8.2\n" \
375" ggsn_number VARCHAR(15),\n" \
376" -- Chapter 2.4.9.2\n" \
377" gmlc_number VARCHAR(15),\n" \
378" -- Chapter 2.4.23\n" \
379" smsc_number VARCHAR(15),\n" \
380" -- Chapter 2.4.24\n" \
381" periodic_lu_tmr INTEGER,\n" \
382" -- Chapter 2.13.115\n" \
383" periodic_rau_tau_tmr INTEGER,\n" \
384" -- Chapter 2.1.1.2: network access mode\n" \
385" nam_cs BOOLEAN NOT NULL DEFAULT 1,\n" \
386" nam_ps BOOLEAN NOT NULL DEFAULT 1,\n" \
387" -- Chapter 2.1.8\n" \
388" lmsi INTEGER,\n" \
389 \
390" -- The below purged flags might not even be stored non-volatile,\n" \
391" -- refer to TS 23.012 Chapter 3.6.1.4\n" \
392" -- Chapter 2.7.5\n" \
393" ms_purged_cs BOOLEAN NOT NULL DEFAULT 0,\n" \
394" -- Chapter 2.7.6\n" \
395" ms_purged_ps BOOLEAN NOT NULL DEFAULT 0,\n" \
396 \
397" -- Timestamp of last location update seen from subscriber\n" \
398" -- The value is a string which encodes a UTC timestamp in granularity of seconds.\n" \
399" last_lu_seen TIMESTAMP default NULL\n" \
400")\n"
401
402#define SUBSCR_V2_COLUMN_NAMES \
403 "id," \
404 "imsi," \
405 "msisdn," \
406 "imeisv," \
407 "imei," \
408 "vlr_number," \
409 "hlr_number," \
410 "sgsn_number," \
411 "sgsn_address," \
412 "ggsn_number," \
413 "gmlc_number," \
414 "smsc_number," \
415 "periodic_lu_tmr," \
416 "periodic_rau_tau_tmr," \
417 "nam_cs," \
418 "nam_ps," \
419 "lmsi," \
420 "ms_purged_cs," \
421 "ms_purged_ps," \
422 "last_lu_seen"
423
424#define SUBSCR_V3_COLUMN_NAMES \
425 "id," \
426 "imsi," \
427 "msisdn," \
428 "imeisv," \
429 "imei," \
430 "vlr_number," \
431 "msc_number," \
432 "sgsn_number," \
433 "sgsn_address," \
434 "ggsn_number," \
435 "gmlc_number," \
436 "smsc_number," \
437 "periodic_lu_tmr," \
438 "periodic_rau_tau_tmr," \
439 "nam_cs," \
440 "nam_ps," \
441 "lmsi," \
442 "ms_purged_cs," \
443 "ms_purged_ps," \
444 "last_lu_seen"
445
446 const char *statements[] = {
447 "BEGIN TRANSACTION",
448 "CREATE TEMPORARY TABLE subscriber_backup" SUBSCR_V3_CREATE,
449 "INSERT INTO subscriber_backup SELECT " SUBSCR_V2_COLUMN_NAMES " FROM subscriber",
450 "DROP TABLE subscriber",
451 "CREATE TABLE subscriber" SUBSCR_V3_CREATE,
452 "INSERT INTO subscriber SELECT " SUBSCR_V3_COLUMN_NAMES " FROM subscriber_backup",
453 "DROP TABLE subscriber_backup",
454 "COMMIT",
455 "PRAGMA user_version = 3",
456 };
457
Neels Hofmeyr7f4dd112019-10-31 21:23:10 +0100458 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
459 if (rc != SQLITE_DONE) {
460 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 3\n");
461 return rc;
Neels Hofmeyra8045da2019-10-31 01:19:44 +0100462 }
463 return rc;
464}
465
Neels Hofmeyr07e16022019-11-20 02:36:35 +0100466static int db_upgrade_v4(struct db_context *dbc)
467{
468 int rc;
469 const char *statements[] = {
470 "ALTER TABLE subscriber ADD COLUMN last_lu_seen_ps TIMESTAMP default NULL",
471 "PRAGMA user_version = 4",
472 };
473
474 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
475 if (rc != SQLITE_DONE) {
476 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 4\n");
477 return rc;
478 }
479 return rc;
480}
481
Neels Hofmeyrf0c02ad2019-11-25 03:59:50 +0100482static int db_upgrade_v5(struct db_context *dbc)
483{
484 int rc;
485 const char *statements[] = {
486 "ALTER TABLE subscriber ADD COLUMN vlr_via_proxy VARCHAR",
487 "ALTER TABLE subscriber ADD COLUMN sgsn_via_proxy VARCHAR",
488 "PRAGMA user_version = 5",
489 };
490
491 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
492 if (rc != SQLITE_DONE) {
493 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 5\n");
494 return rc;
495 }
496 return rc;
497}
498
Neels Hofmeyr92d1c4a2019-12-12 04:04:53 +0100499static int db_upgrade_v6(struct db_context *dbc)
500{
501 int rc;
502 const char *statements[] = {
503 "CREATE TABLE ind (\n"
504 " -- 3G auth IND pool to be used for this VLR\n"
505 " ind INTEGER PRIMARY KEY,\n"
506 " -- VLR identification, usually the GSUP source_name\n"
507 " vlr TEXT NOT NULL,\n"
508 " UNIQUE (vlr)\n"
509 ")"
510 ,
511 "PRAGMA user_version = 6",
512 };
513
514 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
515 if (rc != SQLITE_DONE) {
516 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 6\n");
517 return rc;
518 }
519 return rc;
520}
521
Neels Hofmeyrce172ef2018-12-26 01:49:53 +0100522static int db_upgrade_v7(struct db_context *dbc)
523{
524 int rc;
525 const char *statements[] = {
526 "-- Optional: add subscriber entries to allow or disallow specific RATs (2G or 3G or ...).\n"
527 "-- If a subscriber has no entry, that means that all RATs are allowed (backwards compat).\n"
528 "CREATE TABLE subscriber_rat (\n"
529 " subscriber_id INTEGER, -- subscriber.id\n"
530 " rat TEXT CHECK(rat in ('GERAN-A', 'UTRAN-Iu')) NOT NULL, -- Radio Access Technology, see enum ran_type\n"
531 " allowed BOOLEAN CHECK(allowed in (0, 1)) NOT NULL DEFAULT 0,\n"
532 " UNIQUE (subscriber_id, rat)\n"
533 ")",
534 "CREATE UNIQUE INDEX idx_subscr_rat_flag ON subscriber_rat (subscriber_id, rat)",
535 "PRAGMA user_version = 7",
536 };
537
538 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
539 if (rc != SQLITE_DONE) {
540 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 7\n");
541 return rc;
542 }
543 return rc;
544}
545
Neels Hofmeyr5bc457e2018-12-29 03:28:38 +0100546static int db_upgrade_v8(struct db_context *dbc)
547{
548 int rc;
549 const char *statements[] = {
550 "ALTER TABLE subscriber ADD COLUMN last_lu_rat_cs TEXT default NULL",
551 "ALTER TABLE subscriber ADD COLUMN last_lu_rat_ps TEXT default NULL",
552 "PRAGMA user_version = 8",
553 };
554
555 rc = db_run_statements(dbc, statements, ARRAY_SIZE(statements));
556 if (rc != SQLITE_DONE) {
557 LOGP(DDB, LOGL_ERROR, "Unable to update HLR database schema to version 7\n");
558 return rc;
559 }
560 return rc;
561}
562
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100563typedef int (*db_upgrade_func_t)(struct db_context *dbc);
564static db_upgrade_func_t db_upgrade_path[] = {
565 db_upgrade_v1,
566 db_upgrade_v2,
567 db_upgrade_v3,
Neels Hofmeyr07e16022019-11-20 02:36:35 +0100568 db_upgrade_v4,
Neels Hofmeyrf0c02ad2019-11-25 03:59:50 +0100569 db_upgrade_v5,
Neels Hofmeyr92d1c4a2019-12-12 04:04:53 +0100570 db_upgrade_v6,
Neels Hofmeyrce172ef2018-12-26 01:49:53 +0100571 db_upgrade_v7,
Neels Hofmeyr5bc457e2018-12-29 03:28:38 +0100572 db_upgrade_v8,
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100573};
574
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100575static int db_get_user_version(struct db_context *dbc)
576{
577 const char *user_version_sql = "PRAGMA user_version";
578 sqlite3_stmt *stmt;
579 int version, rc;
580
581 rc = sqlite3_prepare_v2(dbc->db, user_version_sql, -1, &stmt, NULL);
582 if (rc != SQLITE_OK) {
583 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", user_version_sql);
584 return -1;
585 }
586 rc = sqlite3_step(stmt);
587 if (rc == SQLITE_ROW) {
588 version = sqlite3_column_int(stmt, 0);
589 } else {
590 LOGP(DDB, LOGL_ERROR, "SQL statement '%s' failed: %d\n", user_version_sql, rc);
591 version = -1;
592 }
593
594 db_remove_reset(stmt);
595 sqlite3_finalize(stmt);
596 return version;
597}
598
599struct db_context *db_open(void *ctx, const char *fname, bool enable_sqlite_logging, bool allow_upgrade)
Harald Weltee72cf552016-04-28 07:18:49 +0200600{
601 struct db_context *dbc = talloc_zero(ctx, struct db_context);
602 unsigned int i;
603 int rc;
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200604 bool has_sqlite_config_sqllog = false;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100605 int version;
Harald Weltee72cf552016-04-28 07:18:49 +0200606
Neels Hofmeyr7f9491f2017-01-30 13:30:47 +0100607 LOGP(DDB, LOGL_NOTICE, "using database: %s\n", fname);
Harald Weltee72cf552016-04-28 07:18:49 +0200608 LOGP(DDB, LOGL_INFO, "Compiled against SQLite3 lib version %s\n", SQLITE_VERSION);
609 LOGP(DDB, LOGL_INFO, "Running with SQLite3 lib version %s\n", sqlite3_libversion());
610
Vadim Yanitskiyfbd736e2018-07-31 22:40:30 +0700611#ifdef SQLITE_USE_TALLOC
612 /* Configure SQLite3 to use talloc memory allocator */
613 rc = db_sqlite3_use_talloc(ctx);
614 if (rc == SQLITE_OK) {
615 LOGP(DDB, LOGL_NOTICE, "SQLite3 is configured to use talloc\n");
616 } else {
617 LOGP(DDB, LOGL_ERROR, "Failed to configure SQLite3 "
618 "to use talloc, using default memory allocator\n");
619 }
620#endif
621
Harald Weltee72cf552016-04-28 07:18:49 +0200622 dbc->fname = talloc_strdup(dbc, fname);
623
624 for (i = 0; i < 0xfffff; i++) {
625 const char *o = sqlite3_compileoption_get(i);
626 if (!o)
627 break;
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200628 LOGP(DDB, LOGL_DEBUG, "SQLite3 compiled with '%s'\n", o);
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200629 if (!strcmp(o, "ENABLE_SQLLOG"))
630 has_sqlite_config_sqllog = true;
Harald Weltee72cf552016-04-28 07:18:49 +0200631 }
632
Neels Hofmeyrd3814b92017-11-21 12:28:07 +0100633 if (enable_sqlite_logging) {
634 rc = sqlite3_config(SQLITE_CONFIG_LOG, sql3_error_log_cb, NULL);
635 if (rc != SQLITE_OK)
636 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 error log callback\n");
637 }
Harald Weltee72cf552016-04-28 07:18:49 +0200638
Neels Hofmeyrcd83b8a2017-10-06 04:20:37 +0200639 if (has_sqlite_config_sqllog) {
640 rc = sqlite3_config(SQLITE_CONFIG_SQLLOG, sql3_sql_log_cb, NULL);
641 if (rc != SQLITE_OK)
642 LOGP(DDB, LOGL_NOTICE, "Unable to set SQLite3 SQL log callback\n");
643 } else
644 LOGP(DDB, LOGL_DEBUG, "Not setting SQL log callback:"
645 " SQLite3 compiled without support for it\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200646
647 rc = sqlite3_open(dbc->fname, &dbc->db);
648 if (rc != SQLITE_OK) {
649 LOGP(DDB, LOGL_ERROR, "Unable to open DB; rc = %d\n", rc);
650 talloc_free(dbc);
651 return NULL;
652 }
653
654 /* enable extended result codes */
655 rc = sqlite3_extended_result_codes(dbc->db, 1);
656 if (rc != SQLITE_OK)
Neels Hofmeyre9c0c5b2017-10-10 16:52:22 +0200657 LOGP(DDB, LOGL_ERROR, "Unable to enable SQLite3 extended result codes\n");
Harald Weltee72cf552016-04-28 07:18:49 +0200658
Harald Welteabd1a542016-05-03 18:50:41 +0200659 char *err_msg;
660 rc = sqlite3_exec(dbc->db, "PRAGMA journal_mode=WAL; PRAGMA synchonous = NORMAL;", 0, 0, &err_msg);
661 if (rc != SQLITE_OK)
662 LOGP(DDB, LOGL_ERROR, "Unable to set Write-Ahead Logging: %s\n",
663 err_msg);
664
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100665 version = db_get_user_version(dbc);
666 if (version < 0) {
667 LOGP(DDB, LOGL_ERROR, "Unable to read user version number from database '%s'\n", dbc->fname);
668 goto out_free;
669 }
670
671 /* An empty database will always report version zero. */
672 if (version == 0 && !db_is_bootstrapped_v0(dbc)) {
673 LOGP(DDB, LOGL_NOTICE, "Missing database tables detected; Bootstrapping database '%s'\n", dbc->fname);
674 rc = db_bootstrap(dbc);
675 if (rc != SQLITE_OK) {
676 LOGP(DDB, LOGL_ERROR, "Failed to bootstrap DB: (rc=%d) %s\n",
677 rc, sqlite3_errmsg(dbc->db));
678 goto out_free;
679 }
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100680 version = CURRENT_SCHEMA_VERSION;
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100681 }
682
683 LOGP(DDB, LOGL_NOTICE, "Database '%s' has HLR DB schema version %d\n", dbc->fname, version);
684
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100685 for (; allow_upgrade && (version < ARRAY_SIZE(db_upgrade_path)); version++) {
686 db_upgrade_func_t upgrade_func = db_upgrade_path[version];
687 rc = upgrade_func(dbc);
688 if (rc != SQLITE_DONE) {
689 LOGP(DDB, LOGL_ERROR, "Failed to upgrade HLR DB schema to version %d: (rc=%d) %s\n",
690 version+1, rc, sqlite3_errmsg(dbc->db));
691 goto out_free;
Stefan Sperling638ba8c2018-12-04 15:07:29 +0100692 }
693 LOGP(DDB, LOGL_NOTICE, "Database '%s' has been upgraded to HLR DB schema version %d\n",
Neels Hofmeyr981e1262019-11-05 02:00:19 +0100694 dbc->fname, version+1);
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100695 }
696
697 if (version != CURRENT_SCHEMA_VERSION) {
698 if (version < CURRENT_SCHEMA_VERSION) {
699 LOGP(DDB, LOGL_NOTICE, "HLR DB schema version %d is outdated\n", version);
700 if (!allow_upgrade) {
Neels Hofmeyrce172ef2018-12-26 01:49:53 +0100701 LOGP(DDB, LOGL_ERROR, "Not upgrading HLR database from schema version %d to %d; "
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100702 "use the --db-upgrade option to allow HLR database upgrades\n",
Neels Hofmeyrce172ef2018-12-26 01:49:53 +0100703 version, CURRENT_SCHEMA_VERSION);
Stefan Sperling8f3a7cc2018-11-27 12:10:45 +0100704 }
705 } else
706 LOGP(DDB, LOGL_ERROR, "HLR DB schema version %d is unknown\n", version);
707
Vadim Yanitskiy050eb1d2018-07-30 20:48:19 +0700708 goto out_free;
709 }
Neels Hofmeyr7750d2c2017-10-24 23:26:27 +0200710
Harald Weltee72cf552016-04-28 07:18:49 +0200711 /* prepare all SQL statements */
712 for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
713 rc = sqlite3_prepare_v2(dbc->db, stmt_sql[i], -1,
714 &dbc->stmt[i], NULL);
715 if (rc != SQLITE_OK) {
716 LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_sql[i]);
717 goto out_free;
718 }
719 }
720
721 return dbc;
722out_free:
723 db_close(dbc);
724 return NULL;
725}