summaryrefslogtreecommitdiffstats
path: root/openbsc/src/db.c
blob: 543f44ce2939a0dcb5c1c1cc35cbcec2cb1f8ca9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/* Simple HLR/VLR database backend using dbi */
/* (C) 2008 by Jan Luebbe <jluebbe@debian.org>
 * (C) 2009 by Holger Hans Peter Freyther <zecke@selfish.org>
 * (C) 2009 by Harald Welte <laforge@gnumonks.org>
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

#include <openbsc/gsm_data.h>
#include <openbsc/db.h>

#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <dbi/dbi.h>

static char *db_basename = NULL;
static char *db_dirname = NULL;
static dbi_conn conn;

static char *create_stmts[] = {
	"CREATE TABLE IF NOT EXISTS Meta ("
		"id INTEGER PRIMARY KEY AUTOINCREMENT, "
		"key TEXT UNIQUE NOT NULL, "
		"value TEXT NOT NULL"
		")",
	"INSERT OR IGNORE INTO Meta "
		"(key, value) "
		"VALUES "
		"('revision', '1')",
	"CREATE TABLE IF NOT EXISTS Subscriber ("
		"id INTEGER PRIMARY KEY AUTOINCREMENT, "
		"created TIMESTAMP NOT NULL, "
		"updated TIMESTAMP NOT NULL, "
		"imsi NUMERIC UNIQUE NOT NULL, "
		"name TEXT, "
		"extension TEXT UNIQUE, "
		"authorized INTEGER NOT NULL DEFAULT 0, "
		"tmsi TEXT UNIQUE, "
		"lac INTEGER NOT NULL DEFAULT 0"
		")",
	"CREATE TABLE IF NOT EXISTS Equipment ("
		"id INTEGER PRIMARY KEY AUTOINCREMENT, "
		"created TIMESTAMP NOT NULL, "
		"updated TIMESTAMP NOT NULL, "
		"name TEXT, "
		"classmark1 NUMERIC, "
		"classmark2 BLOB, "
		"classmark3 BLOB, "
		"imei NUMERIC UNIQUE NOT NULL"
		")",
	"CREATE TABLE IF NOT EXISTS EquipmentWatch ("
		"id INTEGER PRIMARY KEY AUTOINCREMENT, "
		"created TIMESTAMP NOT NULL, "
		"updated TIMESTAMP NOT NULL, "
		"subscriber_id NUMERIC NOT NULL, "
		"equipment_id NUMERIC NOT NULL, "
		"UNIQUE (subscriber_id, equipment_id) "
		")",
	"CREATE TABLE IF NOT EXISTS SMS ("
		"id INTEGER PRIMARY KEY AUTOINCREMENT, "
		"created TIMESTAMP NOT NULL, "
		"sent TIMESTAMP, "
		"sender_id NUMERIC NOT NULL, "
		"receiver_id NUMERIC NOT NULL, "
		"header NUMERIC, "
		"text TEXT NOT NULL "
		")",
	"CREATE TABLE IF NOT EXISTS VLR ("
		"id INTEGER PRIMARY KEY AUTOINCREMENT, "
		"created TIMESTAMP NOT NULL, "
		"updated TIMESTAMP NOT NULL, "
		"subscriber_id NUMERIC UNIQUE NOT NULL, "
		"last_bts NUMERIC NOT NULL "
		")",
};

void db_error_func(dbi_conn conn, void* data) {
	const char* msg;
	dbi_conn_error(conn, &msg);
	printf("DBI: %s\n", msg);
}

int db_init(const char *name) {
	dbi_initialize(NULL);
	conn = dbi_conn_new("sqlite3");
	if (conn==NULL) {
		printf("DB: Failed to create connection.\n");
		return 1;
	}

	dbi_conn_error_handler( conn, db_error_func, NULL );

	/* MySQL
	dbi_conn_set_option(conn, "host", "localhost");
	dbi_conn_set_option(conn, "username", "your_name");
	dbi_conn_set_option(conn, "password", "your_password");
	dbi_conn_set_option(conn, "dbname", "your_dbname");
	dbi_conn_set_option(conn, "encoding", "UTF-8");
	*/

	/* SqLite 3 */
	db_basename = strdup(name);
	db_dirname = strdup(name);
	dbi_conn_set_option(conn, "sqlite3_dbdir", dirname(db_dirname));
	dbi_conn_set_option(conn, "dbname", basename(db_basename));

	if (dbi_conn_connect(conn) < 0) {
		free(db_dirname);
		free(db_basename);
		db_dirname = db_basename = NULL;
		return 1;
	}

	return 0;
}

int db_prepare() {
	dbi_result result;
	int i;

	for (i = 0; i < ARRAY_SIZE(create_stmts); i++) {
		result = dbi_conn_query(conn, create_stmts[i]);
		if (result==NULL) {
			printf("DB: Failed to create some table.\n");
			return 1;
		}
		dbi_result_free(result);
	}

	return 0;
}

int db_fini() {
	dbi_conn_close(conn);
	dbi_shutdown();

	if (db_dirname)
	    free(db_dirname);
	if (db_basename)
	    free(db_basename);
	return 0;
}

struct gsm_subscriber* db_create_subscriber(char *imsi) {
	dbi_result result;
	struct gsm_subscriber* subscr;

	/* Is this subscriber known in the db? */
	subscr = db_get_subscriber(GSM_SUBSCRIBER_IMSI, imsi); 
	if (subscr) {
		result = dbi_conn_queryf(conn,
                         "UPDATE Subscriber set updated = datetime('now') "
                         "WHERE imsi = %s " , imsi);
		if (result==NULL) {
			printf("DB: failed to update timestamp\n");
		} else {
			dbi_result_free(result);
		}
		return subscr;
	}

	subscr = subscr_alloc();
	if (!subscr)
		return NULL;
	result = dbi_conn_queryf(conn,
		"INSERT INTO Subscriber "
		"(imsi, created, updated) "
		"VALUES "
		"(%s, datetime('now'), datetime('now')) ",
		imsi
	);
	if (result==NULL) {
		printf("DB: Failed to create Subscriber by IMSI.\n");
	}
	subscr->id = dbi_conn_sequence_last(conn, NULL);
	strncpy(subscr->imsi, imsi, GSM_IMSI_LENGTH-1);
	dbi_result_free(result);
	printf("DB: New Subscriber: ID %llu, IMSI %s\n", subscr->id, subscr->imsi);
	return subscr;
}

struct gsm_subscriber *db_get_subscriber(enum gsm_subscriber_field field, const char *id) {
	dbi_result result;
	const char *string;
	char *quoted;
	struct gsm_subscriber *subscr;

	switch (field) {
	case GSM_SUBSCRIBER_IMSI:
		dbi_conn_quote_string_copy(conn, id, &quoted);
		result = dbi_conn_queryf(conn,
			"SELECT * FROM Subscriber "
			"WHERE imsi = %s ",
			quoted
		);
		free(quoted);
		break;
	case GSM_SUBSCRIBER_TMSI:
		dbi_conn_quote_string_copy(conn, id, &quoted);
		result = dbi_conn_queryf(conn,
			"SELECT * FROM Subscriber "
			"WHERE tmsi = %s ",
			quoted
		);
		free(quoted);
		break;
	case GSM_SUBSCRIBER_EXTENSION:
		dbi_conn_quote_string_copy(conn, id, &quoted);
		result = dbi_conn_queryf(conn,
			"SELECT * FROM Subscriber "
			"WHERE extension = %s ",
			quoted
		);
		free(quoted);
		break;
	default:
		printf("DB: Unknown query selector for Subscriber.\n");
		return NULL;
	}
	if (result==NULL) {
		printf("DB: Failed to query Subscriber.\n");
		return NULL;
	}
	if (!dbi_result_next_row(result)) {
		printf("DB: Failed to find the Subscriber. '%u' '%s'\n",
			field, id);
		dbi_result_free(result);
		return NULL;
	}

	subscr = subscr_alloc();
	subscr->id = dbi_result_get_ulonglong(result, "id");
	string = dbi_result_get_string(result, "imsi");
	if (string)
		strncpy(subscr->imsi, string, GSM_IMSI_LENGTH);

	string = dbi_result_get_string(result, "tmsi");
	if (string)
		strncpy(subscr->tmsi, string, GSM_TMSI_LENGTH);

	string = dbi_result_get_string(result, "name");
	if (string)
		strncpy(subscr->name, string, GSM_NAME_LENGTH);

	string = dbi_result_get_string(result, "extension");
	if (string)
		strncpy(subscr->extension, string, GSM_EXTENSION_LENGTH);

	subscr->lac = dbi_result_get_uint(result, "lac");
	subscr->authorized = dbi_result_get_uint(result, "authorized");
	printf("DB: Found Subscriber: ID %llu, IMSI %s, NAME '%s', TMSI %s, EXTEN '%s', LAC %hu, AUTH %u\n",
		subscr->id, subscr->imsi, subscr->name, subscr->tmsi, subscr->extension,
		subscr->lac, subscr->authorized);
	dbi_result_free(result);
	return subscr;
}

int db_sync_subscriber(struct gsm_subscriber* subscriber) {
	dbi_result result;
	result = dbi_conn_queryf(conn,
		"UPDATE Subscriber "
		"SET updated = datetime('now'), "
		"tmsi = '%s', "
		"lac = %i, "
		"authorized = %i "
		"WHERE imsi = %s ",
		subscriber->tmsi, subscriber->lac, subscriber->authorized, subscriber->imsi
	);

	if (result==NULL) {
		printf("DB: Failed to update Subscriber (by IMSI).\n");
		return 1;
	}
	dbi_result_free(result);
	return 0;
}

int db_sync_equipment(struct gsm_equipment *equip)
{
	dbi_result result;
	unsigned char *cm2, *cm3;

	dbi_conn_quote_binary_copy(conn, equip->classmark2,
				   equip->classmark2_len, &cm2);
	dbi_conn_quote_binary_copy(conn, equip->classmark3,
				   equip->classmark3_len, &cm3);

	result = dbi_conn_queryf(conn,
		"UPDATE Equipment SET "
			"updated = datetime('now'), "
			"classmark1 = %u, "
			"classmark2 = %s, "
			"classmark3 = %s "
		"WHERE imei = '%s' ",
		equip->classmark1, cm2, cm3, equip->imei);

	free(cm2);
	free(cm3);

	if (!result) {
		printf("DB: Failed to update Equipment\n");
		return -EIO;
	}

	dbi_result_free(result);
	return 0;
}

int db_subscriber_alloc_tmsi(struct gsm_subscriber* subscriber) {
	dbi_result result=NULL;
	char* tmsi_quoted;
	for (;;) {
		sprintf(subscriber->tmsi, "%i", rand());
		dbi_conn_quote_string_copy(conn, subscriber->tmsi, &tmsi_quoted);
		result = dbi_conn_queryf(conn,
			"SELECT * FROM Subscriber "
			"WHERE tmsi = %s ",
			tmsi_quoted
		);
		free(tmsi_quoted);
		if (result==NULL) {
			printf("DB: Failed to query Subscriber while allocating new TMSI.\n");
			return 1;
		}
		if (dbi_result_get_numrows(result)){
			dbi_result_free(result);
			continue;
		}
		if (!dbi_result_next_row(result)) {
			dbi_result_free(result);
			printf("DB: Allocated TMSI %s for IMSI %s.\n", subscriber->tmsi, subscriber->imsi);
			return db_sync_subscriber(subscriber);
		}
		dbi_result_free(result);
	}
	return 0;
}

int db_subscriber_assoc_imei(struct gsm_subscriber* subscriber, char imei[GSM_IMEI_LENGTH]) {
	u_int64_t equipment_id, watch_id;
	dbi_result result;

	strncpy(subscriber->equipment.imei, imei,
		sizeof(subscriber->equipment.imei)-1),

	result = dbi_conn_queryf(conn,
		"INSERT OR IGNORE INTO Equipment "
		"(imei, created, updated) "
		"VALUES "
		"(%s, datetime('now'), datetime('now')) ",
		imei
	);
	if (result==NULL) {
		printf("DB: Failed to create Equipment by IMEI.\n");
		return 1;
	}
	equipment_id = 0;
	if (dbi_result_get_numrows_affected(result)) {
		equipment_id = dbi_conn_sequence_last(conn, NULL);
	}
	dbi_result_free(result);
	if (equipment_id) {
		printf("DB: New Equipment: ID %llu, IMEI %s\n", equipment_id, imei);
	}
	else {
		result = dbi_conn_queryf(conn,
			"SELECT id FROM Equipment "
			"WHERE imei = %s ",
			imei
		);
		if (result==NULL) {
			printf("DB: Failed to query Equipment by IMEI.\n");
			return 1;
		}
		if (!dbi_result_next_row(result)) {
			printf("DB: Failed to find the Equipment.\n");
			dbi_result_free(result);
			return 1;
		}
		equipment_id = dbi_result_get_ulonglong(result, "id");
		dbi_result_free(result);
	}

	result = dbi_conn_queryf(conn,
		"INSERT OR IGNORE INTO EquipmentWatch "
		"(subscriber_id, equipment_id, created, updated) "
		"VALUES "
		"(%llu, %llu, datetime('now'), datetime('now')) ",
		subscriber->id, equipment_id
	);
	if (result==NULL) {
		printf("DB: Failed to create EquipmentWatch.\n");
		return 1;
	}
	watch_id = 0;
	if (dbi_result_get_numrows_affected(result)) {
		watch_id = dbi_conn_sequence_last(conn, NULL);
	}
	dbi_result_free(result);
	if (watch_id) {
		printf("DB: New EquipmentWatch: ID %llu, IMSI %s, IMEI %s\n", equipment_id, subscriber->imsi, imei);
	}
	else {
		result = dbi_conn_queryf(conn,
			"UPDATE EquipmentWatch "
			"SET updated = datetime('now') "
			"WHERE subscriber_id = %llu AND equipment_id = %llu ",
			subscriber->id, equipment_id
		);
		if (result==NULL) {
			printf("DB: Failed to update EquipmentWatch.\n");
			return 1;
		}
		dbi_result_free(result);
		printf("DB: Updated EquipmentWatch: ID %llu, IMSI %s, IMEI %s\n", equipment_id, subscriber->imsi, imei);
	}

	return 0;
}

/* store an [unsent] SMS to the database */
int db_sms_store(struct gsm_sms *sms)
{
	dbi_result result;
	char *q_text;

	dbi_conn_quote_string_copy(conn, (char *)sms->text, &q_text);
	result = dbi_conn_queryf(conn,
		"INSERT INTO SMS "
		"(created,sender_id,receiver_id,header,text) VALUES "
		"(datetime('now'),%llu,%llu,%s,%s)",
		sms->sender->id,
		sms->receiver ? sms->receiver->id : 0,
		NULL, q_text);
	free(q_text);

	if (!result)
		return -EIO;

	dbi_result_free(result);
	return 0;
}

/* retrieve the next unsent SMS with ID >= min_id */
struct gsm_sms *db_sms_get_unsent(int min_id)
{
	dbi_result result;
	struct gsm_sms *sms = malloc(sizeof(*sms));

	if (!sms) {
		free(sms);
		return NULL;
	}

	result = dbi_conn_queryf(conn,
		"SELECT * FROM SMS "
		"WHERE id >= %llu ORDER BY id", min_id);
	if (!result) {
		free(sms);
		return NULL;
	}

	/* FIXME: fill gsm_sms from database */

	dbi_result_free(result);
	return sms;
}

/* mark a given SMS as read */
int db_sms_mark_sent(struct gsm_sms *sms)
{
	dbi_result result;

	result = dbi_conn_queryf(conn,
		"UPDATE SMS "
		"SET sent = datetime('now') "
		"WHERE id = %llu", sms->id);
	if (!result) {
		printf("DB: Failed to mark SMS %llu as sent.\n", sms->id);
		return 1;
	}

	dbi_result_free(result);
	return 0;
}