initial import of osmo-gsup-hlr code so far
diff --git a/src/Makefile b/src/Makefile
new file mode 100644
index 0000000..d7c597e
--- /dev/null
+++ b/src/Makefile
@@ -0,0 +1,16 @@
+LDFLAGS += -losmocore -losmogsm -losmoabis -lsqlite3 -ltalloc
+CFLAGS += -g -Wall
+
+OBJS = auc.o db.o db_auc.o logging.o
+
+db_test: db_test.o rand_fake.o $(OBJS)
+	$(CC) $(LDFLAGS) -o $@ $^
+
+hlr: hlr.o gsup_server.o rand_urandom.o $(OBJS)
+	$(CC) $(LDFLAGS) -o $@ $^
+
+%.o: %.c
+	$(CC) $(CFLAGS) -o $@ -c $^
+
+clean:
+	rm -f *.o db_test
diff --git a/src/auc.c b/src/auc.c
new file mode 100644
index 0000000..8ceafad
--- /dev/null
+++ b/src/auc.c
@@ -0,0 +1,94 @@
+/* (C) 2015 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 Affero General Public License as published by
+ * the Free Software Foundation; either version 3 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include <string.h>
+
+#include <osmocom/core/utils.h>
+#include <osmocom/crypt/auth.h>
+
+#include "logging.h"
+#include "rand.h"
+
+/* compute given number of vectors using either aud2g or aud2g or a combination
+ * of both.  Handles re-synchrnization if rand_auts and auts are set */
+int auc_compute_vectors(struct osmo_auth_vector *vec, unsigned int num_vec,
+			struct osmo_sub_auth_data *aud2g,
+			struct osmo_sub_auth_data *aud3g,
+			const uint8_t *rand_auts, const uint8_t *auts)
+{
+	unsigned int i;
+	uint8_t rand[16];
+	int rc;
+
+	if (aud2g->algo == OSMO_AUTH_ALG_NONE)
+		aud2g = NULL;
+	if (aud3g->algo == OSMO_AUTH_ALG_NONE)
+		aud3g = NULL;
+
+	if (!aud2g && !aud3g)
+		return -1;
+
+	/* compute quintuples */
+	for (i = 0; i < num_vec; i++) {
+		rc = rand_get(rand, sizeof(rand));
+		if (rc != sizeof(rand)) {
+			LOGP(DAUC, LOGL_ERROR, "Unable to read %zu random "
+			     "bytes: rc=%d\n", sizeof(rand), rc);
+			goto out;
+		}
+
+		if (aud2g && !aud3g) {
+			/* 2G only case: output directly to vec */
+			rc = osmo_auth_gen_vec(vec+i, aud2g, rand);
+			if (rc < 0) {
+				LOGP(DAUC, LOGL_ERROR, "Error in 2G vector "
+				     "generation: %d\n", rc);
+				goto out;
+			}
+		} else if (aud3g) {
+			/* 3G or 3G + 2G case */
+			if (rand_auts && auts)
+				rc = osmo_auth_gen_vec_auts(vec+i, aud3g,
+							    rand_auts,
+							    auts, rand);
+			else
+				rc = osmo_auth_gen_vec(vec+i, aud3g, rand);
+			if (rc < 0) {
+				LOGP(DAUC, LOGL_ERROR, "Error in 3G vector "
+				     "generation: %d\n", rc);
+				goto out;
+			}
+		}
+		if (aud2g && aud3g) {
+			/* separate 2G + 3G case: patch 2G into 3G */
+			struct osmo_auth_vector vtmp;
+			rc = osmo_auth_gen_vec(&vtmp, aud2g, rand);
+			if (rc < 0) {
+				LOGP(DAUC, LOGL_ERROR, "Error in 2G vector "
+				     "generation: %d\n", rc);
+				goto out;
+			}
+			memcpy(&vec[i].kc, vtmp.kc, sizeof(vec[i].kc));
+			memcpy(&vec[i].sres, vtmp.sres, sizeof(vec[i].sres));
+			vec[i].auth_types |= OSMO_AUTH_TYPE_GSM;
+		}
+	}
+out:
+	return i;
+}
diff --git a/src/auc.h b/src/auc.h
new file mode 100644
index 0000000..f5b6765
--- /dev/null
+++ b/src/auc.h
@@ -0,0 +1,8 @@
+#pragma once
+
+#include <osmocom/crypt/auth.h>
+
+int auc_compute_vectors(struct osmo_auth_vector *vec, unsigned int num_vec,
+			struct osmo_sub_auth_data *aud2g,
+			struct osmo_sub_auth_data *aud3g,
+			const uint8_t *rand_auts, const uint8_t *auts);
diff --git a/src/db.c b/src/db.c
new file mode 100644
index 0000000..b4fadca
--- /dev/null
+++ b/src/db.c
@@ -0,0 +1,121 @@
+/* (C) 2015 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 Affero General Public License as published by
+ * the Free Software Foundation; either version 3 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include <osmocom/core/utils.h>
+
+#include <sqlite3.h>
+
+#include "logging.h"
+#include "db.h"
+
+static const char *stmt_sql[] = {
+	[SEL_BY_IMSI] = "SELECT * FROM subscriber WHERE imsi = ?",
+	[UPD_BY_IMSI] = "UPDATE subscriber SET vlr_number = ? WHERE imsi = ?",
+	[AUC_BY_IMSI] = "SELECT id, algo_id_2g, ki, algo_id_3g, k, op, opc, sqn FROM subscriber LEFT JOIN auc_2g ON auc_2g.subscriber_id = subscriber.id LEFT JOIN auc_3g ON auc_3g.subscriber_id = subscriber.id WHERE imsi = ?",
+	[AUC_UPD_SQN] = "UPDATE auc_3g SET sqn = ? WHERE subscriber_id = ?",
+};
+
+static void sql3_error_log_cb(void *arg, int err_code, const char *msg)
+{
+	LOGP(DDB, LOGL_ERROR, "(%d) %s\n", err_code, msg);
+}
+
+static void sql3_sql_log_cb(void *arg, sqlite3 *s3, const char *stmt, int type)
+{
+	switch (type) {
+	case 0:
+		LOGP(DDB, LOGL_DEBUG, "Opened database\n");
+		break;
+	case 1:
+		LOGP(DDB, LOGL_DEBUG, stmt);
+		break;
+	case 2:
+		LOGP(DDB, LOGL_DEBUG, "Closed database\n");
+		break;
+	default:
+		LOGP(DDB, LOGL_DEBUG, "Unknown %d\n", type);
+		break;
+	}
+}
+
+void db_close(struct db_context *dbc)
+{
+	unsigned int i;
+
+	for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
+		/* it is ok to call finalize on NULL */
+		sqlite3_finalize(dbc->stmt[i]);
+	}
+	sqlite3_close(dbc->db);
+	talloc_free(dbc);
+}
+
+struct db_context *db_open(void *ctx, const char *fname)
+{
+	struct db_context *dbc = talloc_zero(ctx, struct db_context);
+	unsigned int i;
+	int rc;
+
+	LOGP(DDB, LOGL_INFO, "Compiled against SQLite3 lib version %s\n", SQLITE_VERSION);
+	LOGP(DDB, LOGL_INFO, "Running with SQLite3 lib version %s\n", sqlite3_libversion());
+
+	dbc->fname = talloc_strdup(dbc, fname);
+
+	for (i = 0; i < 0xfffff; i++) {
+		const char *o = sqlite3_compileoption_get(i);
+		if (!o)
+			break;
+		LOGP(DDB, LOGL_DEBUG, "SQlite3 compiled with '%s'\n", o);
+	}
+
+	rc = sqlite3_config(SQLITE_CONFIG_LOG, sql3_error_log_cb, NULL);
+	if (rc != SQLITE_OK)
+		LOGP(DDB, LOGL_NOTICE, "Unable to set SQlite3 error log callback\n");
+
+	rc = sqlite3_config(SQLITE_CONFIG_SQLLOG, sql3_sql_log_cb, NULL);
+	if (rc != SQLITE_OK)
+		LOGP(DDB, LOGL_NOTICE, "Unable to set SQlite3 SQL statement log callback\n");
+
+	rc = sqlite3_open(dbc->fname, &dbc->db);
+	if (rc != SQLITE_OK) {
+		LOGP(DDB, LOGL_ERROR, "Unable to open DB; rc = %d\n", rc);
+		talloc_free(dbc);
+		return NULL;
+	}
+
+	/* enable extended result codes */
+	rc = sqlite3_extended_result_codes(dbc->db, 1);
+	if (rc != SQLITE_OK)
+		LOGP(DDB, LOGL_ERROR, "Unable to enable SQlite3 extended result codes\n");
+
+	/* prepare all SQL statements */
+	for (i = 0; i < ARRAY_SIZE(dbc->stmt); i++) {
+		rc = sqlite3_prepare_v2(dbc->db, stmt_sql[i], -1,
+					&dbc->stmt[i], NULL);
+		if (rc != SQLITE_OK) {
+			LOGP(DDB, LOGL_ERROR, "Unable to prepare SQL statement '%s'\n", stmt_sql[i]);
+			goto out_free;
+		}
+	}
+
+	return dbc;
+out_free:
+	db_close(dbc);
+	return NULL;
+}
diff --git a/src/db.h b/src/db.h
new file mode 100644
index 0000000..f0545a4
--- /dev/null
+++ b/src/db.h
@@ -0,0 +1,35 @@
+#pragma once
+
+#include <sqlite3.h>
+
+enum stmt_idx {
+	SEL_BY_IMSI	= 0,
+	UPD_BY_IMSI	= 1,
+	AUC_BY_IMSI	= 2,
+	AUC_UPD_SQN	= 3,
+	_NUM_STMT
+};
+
+struct db_context {
+	char *fname;
+	sqlite3 *db;
+	sqlite3_stmt *stmt[_NUM_STMT];
+};
+
+void db_close(struct db_context *dbc);
+struct db_context *db_open(void *ctx, const char *fname);
+
+#include <osmocom/crypt/auth.h>
+
+/* obtain the authentication data for a given imsi */
+int db_get_auth_data(struct db_context *dbc, const char *imsi,
+		     struct osmo_sub_auth_data *aud2g,
+		     struct osmo_sub_auth_data *aud3g,
+		     uint64_t *suscr_id);
+
+int db_update_sqn(struct db_context *dbc, uint64_t id,
+		      uint64_t new_sqn);
+
+int db_get_auc(struct db_context *dbc, const char *imsi,
+	    struct osmo_auth_vector *vec, unsigned int num_vec,
+	    const uint8_t *rand_auts, const uint8_t *auts);
diff --git a/src/db_auc.c b/src/db_auc.c
new file mode 100644
index 0000000..fa5f3e5
--- /dev/null
+++ b/src/db_auc.c
@@ -0,0 +1,208 @@
+/* (C) 2015 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 Affero General Public License as published by
+ * the Free Software Foundation; either version 3 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include <string.h>
+
+#include <osmocom/core/utils.h>
+#include <osmocom/crypt/auth.h>
+
+#include <sqlite3.h>
+
+#include "logging.h"
+#include "db.h"
+#include "auc.h"
+#include "rand.h"
+
+#define LOGAUC(imsi, level, fmt, args ...)	LOGP(DAUC, level, "%s: " fmt, imsi, ## args)
+
+/* update the SQN for a given subscriber ID */
+int db_update_sqn(struct db_context *dbc, uint64_t id,
+		      uint64_t new_sqn)
+{
+	sqlite3_stmt *stmt = dbc->stmt[AUC_UPD_SQN];
+	int rc;
+
+	/* bind new SQN and subscriber ID */
+	rc = sqlite3_bind_int64(stmt, 1, new_sqn);
+	if (rc != SQLITE_OK) {
+		LOGP(DAUC, LOGL_ERROR, "Error binding SQN: %d\n", rc);
+		return -1;
+	}
+
+	rc = sqlite3_bind_int64(stmt, 2, id);
+	if (rc != SQLITE_OK) {
+		LOGP(DAUC, LOGL_ERROR, "Error binding Subscrber ID: %d\n", rc);
+		return -1;
+	}
+
+	/* execute the statement */
+	rc = sqlite3_step(stmt);
+	if (rc != SQLITE_DONE) {
+		LOGP(DAUC, LOGL_ERROR, "Error updating SQN: %d\n", rc);
+		return -2;
+	}
+
+	/* remove bindings and reset statement to be re-executed */
+	rc = sqlite3_clear_bindings(stmt);
+	if (rc != SQLITE_OK) {
+		LOGP(DAUC, LOGL_ERROR, "Error clerearing bindings: %d\n", rc);
+	}
+	rc = sqlite3_reset(stmt);
+	if (rc != SQLITE_OK) {
+		LOGP(DAUC, LOGL_ERROR, "Error in sqlite3_reset: %d\n", rc);
+	}
+
+	return 0;
+}
+
+/* obtain the authentication data for a given imsi */
+int db_get_auth_data(struct db_context *dbc, const char *imsi,
+		     struct osmo_sub_auth_data *aud2g,
+		     struct osmo_sub_auth_data *aud3g,
+		     uint64_t *subscr_id)
+{
+	sqlite3_stmt *stmt = dbc->stmt[AUC_BY_IMSI];
+	int rc;
+
+	memset(aud2g, 0, sizeof(*aud2g));
+	memset(aud3g, 0, sizeof(*aud3g));
+
+	/* bind the IMSI value */
+	rc = sqlite3_bind_text(stmt, 1, imsi, -1,
+				SQLITE_STATIC);
+	if (rc != SQLITE_OK) {
+		LOGAUC(imsi, LOGL_ERROR, "Error binding IMSI: %d\n", rc);
+	}
+
+	/* execute the statement */
+	rc = sqlite3_step(stmt);
+	if (rc != SQLITE_ROW) {
+		LOGAUC(imsi, LOGL_ERROR, "Error executing SQL: %d\n", rc);
+		goto out;
+	}
+
+	/* as an optimization, we retrieve the subscriber ID, to ensure we can
+	 * update the SQN later without having to go back via a JOIN with the
+	 * subscriber table. */
+	if (subscr_id)
+		*subscr_id = sqlite3_column_int64(stmt, 0);
+
+	for (int i = 0; i < 10; i++)
+		LOGAUC(imsi, LOGL_DEBUG, "col_type(%d)=%d\n", i,
+				sqlite3_column_type(stmt, i));
+
+	/* obtain result values using sqlite3_column_*() */
+	if (sqlite3_column_type(stmt, 1) == SQLITE_INTEGER) {
+		/* we do have some 2G authentication data */
+		const uint8_t *ki;
+
+		aud2g->algo = sqlite3_column_int(stmt, 1);
+		ki = sqlite3_column_text(stmt, 2);
+#if 0
+		if (sqlite3_column_bytes(stmt, 2) != sizeof(aud2g->u.gsm.ki)) {
+			LOGAUC(imsi, LOGL_ERROR, "Error reading Ki: %d\n", rc);
+			goto end_2g;
+		}
+#endif
+		memcpy(&aud2g->u.gsm.ki, ki, sizeof(aud2g->u.gsm.ki));
+		aud2g->type = OSMO_AUTH_TYPE_GSM;
+	} else
+		LOGAUC(imsi, LOGL_DEBUG, "No 2G Auth Data\n");
+//end_2g:
+	if (sqlite3_column_type(stmt, 3) == SQLITE_INTEGER) {
+		/* we do have some 3G authentication data */
+		const uint8_t *k, *op, *opc;
+
+		aud3g->algo = sqlite3_column_int(stmt, 3);
+		k = sqlite3_column_text(stmt, 4);
+		if (!k) {
+			LOGAUC(imsi, LOGL_ERROR, "Error reading K: %d\n", rc);
+			goto out;
+		}
+		memcpy(&aud3g->u.umts.k, k, sizeof(aud3g->u.umts.k));
+		/* UMTS Subscribers can have either OP or OPC */
+		op = sqlite3_column_text(stmt, 5);
+		if (!op) {
+			opc = sqlite3_column_text(stmt, 6);
+			if (!opc) {
+				LOGAUC(imsi, LOGL_ERROR, "Error reading OPC: %d\n", rc);
+				goto out;
+			}
+			memcpy(&aud3g->u.umts.opc, opc, sizeof(aud3g->u.umts.opc));
+			aud3g->u.umts.opc_is_op = 0;
+		} else {
+			memcpy(&aud3g->u.umts.opc, op, sizeof(aud3g->u.umts.opc));
+			aud3g->u.umts.opc_is_op = 1;
+		}
+		aud3g->u.umts.sqn = sqlite3_column_int64(stmt, 7);
+		/* FIXME: amf? */
+		aud3g->type = OSMO_AUTH_TYPE_UMTS;
+	} else
+		LOGAUC(imsi, LOGL_DEBUG, "No 3G Auth Data\n");
+out:
+	/* remove bindings and reset statement to be re-executed */
+	rc = sqlite3_clear_bindings(stmt);
+	if (rc != SQLITE_OK) {
+		LOGAUC(imsi, LOGL_ERROR, "Error in sqlite3_clear_bindings(): %d\n", rc);
+	}
+	rc = sqlite3_reset(stmt);
+	if (rc != SQLITE_OK) {
+		LOGAUC(imsi, LOGL_ERROR, "Error in sqlite3_reset(): %d\n", rc);
+	}
+
+	if (aud2g->type == 0 && aud3g->type == 0)
+		return -1;
+
+	return 0;
+}
+
+int db_get_auc(struct db_context *dbc, const char *imsi,
+	    struct osmo_auth_vector *vec, unsigned int num_vec,
+	    const uint8_t *rand_auts, const uint8_t *auts)
+{
+	struct osmo_sub_auth_data aud2g, aud3g;
+	uint64_t subscr_id;
+	int rc;
+
+	rc = db_get_auth_data(dbc, imsi, &aud2g, &aud3g, &subscr_id);
+	if (rc < 0)
+		return rc;
+
+	LOGAUC(imsi, LOGL_INFO, "Calling to generate %u vectors\n", num_vec);
+	rc = auc_compute_vectors(vec, num_vec, &aud2g, &aud3g, rand_auts, auts);
+	if (rc < 0)
+		num_vec = 0;
+	else
+		num_vec = rc;
+	LOGAUC(imsi, LOGL_INFO, "Generated %u vectors\n", num_vec);
+
+	/* Update SQN in database, as needed */
+	if (aud3g.algo) {
+		LOGAUC(imsi, LOGL_DEBUG, "Updating SQN in DB\n");
+		rc = db_update_sqn(dbc, subscr_id, aud3g.u.umts.sqn);
+		/* don't tell caller we generated any triplets in case of
+		 * update error */
+		if (rc < 0) {
+			LOGAUC(imsi, LOGL_ERROR, "Error updating SQN: %d\n", rc);
+			num_vec = 0;
+		}
+	}
+
+	return num_vec;
+}
diff --git a/src/db_test.c b/src/db_test.c
new file mode 100644
index 0000000..75fcb62
--- /dev/null
+++ b/src/db_test.c
@@ -0,0 +1,84 @@
+#include <string.h>
+
+#include <osmocom/core/utils.h>
+#include <osmocom/core/application.h>
+
+#include "db.h"
+#include "rand.h"
+#include "logging.h"
+
+static struct db_context *g_dbc;
+
+static int test(const char *imsi)
+{
+	struct osmo_auth_vector vec[3];
+	int rc, i;
+
+	/* initialize all vectors with a known token pattern */
+	memset(vec, 0x55, sizeof(vec));
+	for (i = 0; i < ARRAY_SIZE(vec); i++)
+		vec[i].res_len = 0;
+
+	rc = db_get_auc(g_dbc, imsi, vec, ARRAY_SIZE(vec), NULL, NULL);
+	if (rc <= 0) {
+		LOGP(DMAIN, LOGL_ERROR, "Cannot obtain auth tuples for '%s'\n", imsi);
+		return rc;
+	}
+	LOGP(DMAIN, LOGL_INFO, "Obtained %u tuples for subscriber IMSI %s\n",
+		rc, imsi);
+
+	for (i = 0; i < rc; i++) {
+		struct osmo_auth_vector *v = vec + i;
+		LOGP(DMAIN, LOGL_DEBUG, "Tuple %u, auth_types=0x%x\n", i, v->auth_types);
+		LOGP(DMAIN, LOGL_DEBUG, "RAND=%s\n", osmo_hexdump_nospc(v->rand, sizeof(v->rand)));
+		LOGP(DMAIN, LOGL_DEBUG, "AUTN=%s\n", osmo_hexdump_nospc(v->autn, sizeof(v->autn)));
+		LOGP(DMAIN, LOGL_DEBUG, "CK=%s\n", osmo_hexdump_nospc(v->ck, sizeof(v->ck)));
+		LOGP(DMAIN, LOGL_DEBUG, "IK=%s\n", osmo_hexdump_nospc(v->ik, sizeof(v->ik)));
+		LOGP(DMAIN, LOGL_DEBUG, "RES=%s\n", osmo_hexdump_nospc(v->res, v->res_len));
+		LOGP(DMAIN, LOGL_DEBUG, "Kc=%s\n", osmo_hexdump_nospc(v->kc, sizeof(v->kc)));
+		LOGP(DMAIN, LOGL_DEBUG, "SRES=%s\n", osmo_hexdump_nospc(v->sres, sizeof(v->sres)));
+	}
+
+	return rc;
+}
+
+int main(int argc, char **argv)
+{
+	int rc;
+
+	rc = osmo_init_logging(&hlr_log_info);
+	if (rc < 0) {
+		fprintf(stderr, "Error initializing logging\n");
+		exit(1);
+	}
+	LOGP(DMAIN, LOGL_NOTICE, "hlr starting\n");
+
+	rc = rand_init();
+	if (rc < 0) {
+		LOGP(DMAIN, LOGL_ERROR, "Error initializing random source\n");
+		exit(1);
+	}
+
+	g_dbc = db_open(NULL, "hlr.db");
+	if (!g_dbc) {
+		LOGP(DMAIN, LOGL_ERROR, "Error opening database\n");
+		exit(1);
+	}
+
+	/* non-existing subscriber */
+	rc = test("901990123456789");
+	/* 2G only AUC data (COMP128v1 / MILENAGE) */
+	rc = test("901990000000001");
+	/* 2G + 3G AUC data (COMP128v1 / MILENAGE) */
+	rc = test("901990000000002");
+	/* 3G AUC data (MILENAGE) */
+	rc = test("901990000000003");
+
+	LOGP(DMAIN, LOGL_NOTICE, "Exiting\n");
+
+	db_close(g_dbc);
+
+	log_fini();
+
+	exit(0);
+}
diff --git a/src/gsup_server.c b/src/gsup_server.c
new file mode 100644
index 0000000..41a03f4
--- /dev/null
+++ b/src/gsup_server.c
@@ -0,0 +1,204 @@
+#include <errno.h>
+
+#include <osmocom/core/msgb.h>
+#include <osmocom/core/logging.h>
+#include <osmocom/core/linuxlist.h>
+#include <osmocom/abis/ipa.h>
+#include <osmocom/abis/ipaccess.h>
+
+#include "gsup_server.h"
+
+static void osmo_gsup_server_send(struct osmo_gsup_conn *conn,
+			     int proto_ext, struct msgb *msg_tx)
+{
+	ipa_prepend_header_ext(msg_tx, proto_ext);
+	ipa_msg_push_header(msg_tx, IPAC_PROTO_OSMO);
+	ipa_server_conn_send(conn->conn, msg_tx);
+}
+
+int osmo_gsup_conn_send(struct osmo_gsup_conn *conn, struct msgb *msg)
+{
+	if (!conn) {
+		msgb_free(msg);
+		return -ENOTCONN;
+	}
+
+	osmo_gsup_server_send(conn, IPAC_PROTO_EXT_GSUP, msg);
+
+	return 0;
+}
+
+static int osmo_gsup_conn_oap_handle(struct osmo_gsup_conn *conn,
+				struct msgb *msg_rx)
+{
+	int rc;
+	struct msgb *msg_tx;
+#if 0
+	rc = oap_handle(&conn->oap_state, msg_rx, &msg_tx);
+	msgb_free(msg_rx);
+	if (rc < 0)
+		return rc;
+
+	if (msg_tx)
+		osmo_gsup_conn_send(conn, IPAC_PROTO_EXT_OAP, msg_tx);
+#endif
+	return 0;
+}
+
+
+/* Data from a given client has arrived over the socket */
+static int osmo_gsup_server_read_cb(struct ipa_server_conn *conn,
+			       struct msgb *msg)
+{
+	struct ipaccess_head *hh = (struct ipaccess_head *) msg->data;
+	struct ipaccess_head_ext *he = (struct ipaccess_head_ext *) msgb_l2(msg);
+	struct osmo_gsup_conn *clnt = (struct osmo_gsup_conn *)conn->data;
+	int rc;
+	static struct ipaccess_unit ipa_dev = {
+		.unit_name = "HLR",
+		/* FIXME */
+	};
+
+	msg->l2h = &hh->data[0];
+
+	/* FIXME: not BTS for server side? */
+#if 0
+	rc = ipaccess_bts_handle_ccm(conn, &ipa_dev, msg);
+
+	if (rc < 0) {
+		LOGP(DLGSUP, LOGL_NOTICE,
+		     "GSUP received an invalid IPA/CCM message from %s:%d\n",
+		     conn->addr, conn->port);
+		/* Link has been closed */
+		clnt->is_connected = 0;
+		msgb_free(msg);
+		return -1;
+	}
+
+	if (rc == 1) {
+		uint8_t msg_type = *(msg->l2h);
+		/* CCM message */
+		if (msg_type == IPAC_MSGT_PONG) {
+			LOGP(DLGSUP, LOGL_DEBUG, "GSUP receiving PONG\n");
+			clnt->got_ipa_pong = 1;
+		}
+
+		msgb_free(msg);
+		return 0;
+	}
+#endif
+
+	if (hh->proto != IPAC_PROTO_OSMO)
+		goto invalid;
+
+	if (!he || msgb_l2len(msg) < sizeof(*he))
+		goto invalid;
+
+	msg->l2h = &he->data[0];
+
+	if (he->proto == IPAC_PROTO_EXT_GSUP) {
+		OSMO_ASSERT(clnt->server->read_cb != NULL);
+		clnt->server->read_cb(clnt, msg);
+		/* expecting read_cb() to free msg */
+	} else if (he->proto == IPAC_PROTO_EXT_OAP) {
+		return osmo_gsup_conn_oap_handle(clnt, msg);
+		/* osmo_gsup_client_oap_handle frees msg */
+	} else
+		goto invalid;
+
+	return 0;
+
+invalid:
+	LOGP(DLGSUP, LOGL_NOTICE,
+	     "GSUP received an invalid IPA message from %s:%d, size = %d\n",
+	     conn->addr, conn->port, msgb_length(msg));
+	msgb_free(msg);
+	return -1;
+
+}
+
+static int osmo_gsup_server_closed_cb(struct ipa_server_conn *conn)
+{
+	struct osmo_gsup_conn *clnt = (struct osmo_gsup_conn *)conn->data;
+
+	LOGP(DLGSUP, LOGL_INFO, "Lost GSUP client %s:%d\n",
+		conn->addr, conn->port);
+
+	llist_del(&clnt->list);
+
+	return 0;
+}
+
+/* a client has connected to the server socket and we have accept()ed it */
+static int osmo_gsup_server_accept_cb(struct ipa_server_link *link, int fd)
+{
+	struct osmo_gsup_conn *conn;
+	struct osmo_gsup_server *gsups =
+		(struct osmo_gsup_server *) link->data;
+
+	conn = talloc_zero(link->data, struct osmo_gsup_conn);
+	OSMO_ASSERT(conn);
+
+	conn->conn = ipa_server_conn_create(conn, link, fd,
+					   osmo_gsup_server_read_cb,
+					   osmo_gsup_server_closed_cb, conn);
+	OSMO_ASSERT(conn->conn);
+
+	/* link data structure with server structure */
+	conn->server = gsups;
+	llist_add_tail(&conn->list, &gsups->clients);
+
+	LOGP(DLGSUP, LOGL_INFO, "New GSUP client %s:%d\n",
+		conn->conn->addr, conn->conn->port);
+#if 0
+	rc = oap_init(&gsups->oap_config, &conn->oap_state);
+	if (rc != 0)
+		goto failed;
+failed:
+#endif
+	return 0;
+}
+
+struct osmo_gsup_server *
+osmo_gsup_server_create(void *ctx, const char *ip_addr,
+			uint16_t tcp_port,
+			osmo_gsup_read_cb_t read_cb)
+{
+	struct osmo_gsup_server *gsups;
+	int rc;
+
+	gsups = talloc_zero(ctx, struct osmo_gsup_server);
+	OSMO_ASSERT(gsups);
+
+	INIT_LLIST_HEAD(&gsups->clients);
+
+	gsups->link = ipa_server_link_create(gsups,
+					/* no e1inp */ NULL,
+					ip_addr, tcp_port,
+					osmo_gsup_server_accept_cb,
+					gsups);
+	if (!gsups->link)
+		goto failed;
+
+	gsups->read_cb = read_cb;
+
+	rc = ipa_server_link_open(gsups->link);
+	if (rc < 0)
+		goto failed;
+
+	return gsups;
+
+failed:
+	osmo_gsup_server_destroy(gsups);
+	return NULL;
+}
+
+void osmo_gsup_server_destroy(struct osmo_gsup_server *gsups)
+{
+	if (gsups->link) {
+		ipa_server_link_close(gsups->link);
+		ipa_server_link_destroy(gsups->link);
+		gsups->link = NULL;
+	}
+	talloc_free(gsups);
+}
diff --git a/src/gsup_server.h b/src/gsup_server.h
new file mode 100644
index 0000000..390bf2e
--- /dev/null
+++ b/src/gsup_server.h
@@ -0,0 +1,40 @@
+#pragma once
+
+#include <osmocom/core/linuxlist.h>
+#include <osmocom/core/msgb.h>
+#include <osmocom/abis/ipa.h>
+#include <osmocom/abis/ipaccess.h>
+
+struct osmo_gsup_conn;
+
+/* Expects message in msg->l2h */
+typedef int (*osmo_gsup_read_cb_t)(struct osmo_gsup_conn *conn, struct msgb *msg);
+
+struct osmo_gsup_server {
+	/* list of osmo_gsup_conn */
+	struct llist_head clients;
+
+	struct ipa_server_link *link;
+	osmo_gsup_read_cb_t read_cb;
+};
+
+
+/* a single connection to a given client (SGSN, MSC) */
+struct osmo_gsup_conn {
+	struct llist_head list;
+
+	struct osmo_gsup_server *server;
+	struct ipa_server_conn *conn;
+	//struct oap_state oap_state;
+};
+
+
+int osmo_gsup_conn_send(struct osmo_gsup_conn *conn, struct msgb *msg);
+
+struct osmo_gsup_server *osmo_gsup_server_create(void *ctx,
+					const char *ip_addr,
+					uint16_t tcp_port,
+					osmo_gsup_read_cb_t read_cb);
+
+void osmo_gsup_server_destroy(struct osmo_gsup_server *gsups);
+
diff --git a/src/hlr.c b/src/hlr.c
new file mode 100644
index 0000000..be0e96e
--- /dev/null
+++ b/src/hlr.c
@@ -0,0 +1,109 @@
+#include <osmocom/core/msgb.h>
+#include <osmocom/core/logging.h>
+#include <osmocom/core/application.h>
+#include <osmocom/gsm/gsup.h>
+
+#include "db.h"
+#include "logging.h"
+#include "gsup_server.h"
+#include "rand.h"
+
+static struct db_context *g_dbc;
+
+/* process an incoming SAI request */
+static int rx_send_auth_info(struct osmo_gsup_conn *conn,
+			     const struct osmo_gsup_message *gsup)
+{
+	struct osmo_gsup_message gsup_out;
+	struct msgb *msg_out;
+	int rc;
+
+	/* initialize return message structure */
+	memset(&gsup_out, 0, sizeof(gsup_out));
+	gsup_out.message_type = OSMO_GSUP_MSGT_SEND_AUTH_INFO_RESULT;
+	memcpy(&gsup_out.imsi, &gsup->imsi, sizeof(gsup_out.imsi));
+
+	rc = db_get_auc(g_dbc, gsup->imsi, gsup_out.auth_vectors,
+			ARRAY_SIZE(gsup_out.auth_vectors),
+			NULL /* gsup->rand_auts */, gsup->auts);
+	if (rc <= 0) {
+		gsup_out.message_type = OSMO_GSUP_MSGT_SEND_AUTH_INFO_ERROR;
+	}
+
+	msg_out = msgb_alloc(1024, "GSUP response");
+	osmo_gsup_encode(msg_out, &gsup_out);
+	return osmo_gsup_conn_send(conn, msg_out);
+}
+
+static int read_cb(struct osmo_gsup_conn *conn, struct msgb *msg)
+{
+	static struct osmo_gsup_message gsup;
+	int rc;
+
+	rc = osmo_gsup_decode(msgb_l3(msg), msgb_l3len(msg), &gsup);
+	if (rc < 0) {
+		LOGP(DMAIN, LOGL_ERROR, "error in GSUP decode: %d\n", rc);
+		return rc;
+	}
+
+	switch (gsup.message_type) {
+	/* requests sent to us */
+	case OSMO_GSUP_MSGT_SEND_AUTH_INFO_REQUEST:
+		rx_send_auth_info(conn, &gsup);
+		break;
+	case OSMO_GSUP_MSGT_UPDATE_LOCATION_REQUEST:
+		break;
+	/* responses to requests sent by us */
+	case OSMO_GSUP_MSGT_INSERT_DATA_ERROR:
+		break;
+	case OSMO_GSUP_MSGT_INSERT_DATA_RESULT:
+		break;
+	default:
+		LOGP(DMAIN, LOGL_DEBUG, "Unhandled GSUP message type %u\n",
+			gsup.message_type);
+		break;
+	}
+	return 0;
+}
+
+
+int main(int argc, char **argv)
+{
+	struct osmo_gsup_server *gs;
+	int rc;
+
+	rc = osmo_init_logging(&hlr_log_info);
+	if (rc < 0) {
+		fprintf(stderr, "Error initializing logging\n");
+		exit(1);
+	}
+	LOGP(DMAIN, LOGL_NOTICE, "hlr starting\n");
+
+	rc = rand_init();
+	if (rc < 0) {
+		LOGP(DMAIN, LOGL_FATAL, "Error initializing random source\n");
+		exit(1);
+	}
+
+	g_dbc = db_open(NULL, "hlr.db");
+	if (!g_dbc) {
+		LOGP(DMAIN, LOGL_FATAL, "Error opening database\n");
+		exit(1);
+	}
+
+	gs = osmo_gsup_server_create(NULL, NULL, 2222, read_cb);
+	if (!gs) {
+		LOGP(DMAIN, LOGL_FATAL, "Error starting GSUP server\n");
+		exit(1);
+	}
+
+	while (1) {
+		osmo_select_main(0);
+	}
+
+	db_close(g_dbc);
+
+	log_fini();
+
+	exit(0);
+}
diff --git a/src/logging.c b/src/logging.c
new file mode 100644
index 0000000..54c8900
--- /dev/null
+++ b/src/logging.c
@@ -0,0 +1,33 @@
+#include <osmocom/core/utils.h>
+#include "logging.h"
+
+const struct log_info_cat hlr_log_info_cat[] = {
+	[DMAIN] = {
+		.name = "DMAIN",
+		.description = "Main Program",
+		.enabled = 1, .loglevel = LOGL_DEBUG,
+	},
+	[DDB] = {
+		.name = "DDB",
+		.description = "Database Layer",
+		.color = "\033[1;31m",
+		.enabled = 1, .loglevel = LOGL_DEBUG,
+	},
+	[DLGSUP] = {
+		.name = "DLGSUP",
+		.description = "GSUP Protocol",
+		.color = "\033[1;32m",
+		.enabled = 1, .loglevel = LOGL_INFO,
+	},
+	[DAUC] = {
+		.name = "DAUC",
+		.description = "Authentication Center",
+		.color = "\033[1;33m",
+		.enabled = 1, .loglevel = LOGL_DEBUG,
+	},
+};
+
+const struct log_info hlr_log_info = {
+	.cat = hlr_log_info_cat,
+	.num_cat = ARRAY_SIZE(hlr_log_info_cat),
+};
diff --git a/src/logging.h b/src/logging.h
new file mode 100644
index 0000000..fdaf5d1
--- /dev/null
+++ b/src/logging.h
@@ -0,0 +1,12 @@
+#pragma once
+
+#include <osmocom/core/logging.h>
+
+enum {
+	DMAIN,
+	DDB,
+	DGSUP,
+	DAUC,
+};
+
+extern const struct log_info hlr_log_info;
diff --git a/src/rand.h b/src/rand.h
new file mode 100644
index 0000000..9c5aedf
--- /dev/null
+++ b/src/rand.h
@@ -0,0 +1,7 @@
+#pragma once
+
+#include <stdint.h>
+
+int rand_init(void);
+
+int rand_get(uint8_t *rand, unsigned int len);
diff --git a/src/rand_fake.c b/src/rand_fake.c
new file mode 100644
index 0000000..ad0cc68
--- /dev/null
+++ b/src/rand_fake.c
@@ -0,0 +1,52 @@
+/* (C) 2012 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 Affero General Public License as published by
+ * the Free Software Foundation; either version 3 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+
+#include <stdio.h>
+#include <string.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <sys/stat.h>
+
+static uint8_t ctr = 0;
+
+static void print_msg(void)
+{
+	static int printed = 0;
+	if (!printed) {
+		fprintf(stderr, "Using fake random generator for deterministic "
+			"test results. NEVER USE THIS IN PRODUCTION\n");
+		printed = 1;
+	}
+}
+
+int rand_init(void)
+{
+	print_msg();
+	return 0;
+}
+
+int rand_get(uint8_t *rand, unsigned int len)
+{
+	print_msg();
+	memset(rand, ctr, len);
+	ctr++;
+	return len;
+}
diff --git a/src/rand_urandom.c b/src/rand_urandom.c
new file mode 100644
index 0000000..68243ca
--- /dev/null
+++ b/src/rand_urandom.c
@@ -0,0 +1,38 @@
+/* (C) 2012 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 Affero General Public License as published by
+ * the Free Software Foundation; either version 3 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+
+#include <stdio.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <sys/stat.h>
+
+static int rand_fd = -1;
+int rand_init(void)
+{
+	rand_fd = open("/dev/urandom", O_RDONLY);
+
+	return rand_fd;
+}
+
+int rand_get(uint8_t *rand, unsigned int len)
+{
+	return read(rand_fd, rand, len);
+}