aboutsummaryrefslogtreecommitdiffstats
path: root/openbsc/src/osmo-bsc_nat
diff options
context:
space:
mode:
authorHarald Welte <laforge@gnumonks.org>2011-03-03 23:36:48 +0100
committerHarald Welte <laforge@gnumonks.org>2011-03-03 23:36:48 +0100
commita17faf8512992a53a14e8b615f5369be05c5f0cc (patch)
tree044ab53a68634ddcf12130bbc1275e86423e449f /openbsc/src/osmo-bsc_nat
parent31c00f7d6fa63937f2c973157d196a427f6eef95 (diff)
Rename bsc_nat -> osmo-bsc_nat and bsc_mgcp -> osmo-bsc_mgcp
This now enforces a unique structure: All of our main daemon programs start with an "osmo-" prefix.
Diffstat (limited to 'openbsc/src/osmo-bsc_nat')
-rw-r--r--openbsc/src/osmo-bsc_nat/Makefile.am13
-rw-r--r--openbsc/src/osmo-bsc_nat/bsc_filter.c216
-rw-r--r--openbsc/src/osmo-bsc_nat/bsc_mgcp_utils.c764
-rw-r--r--openbsc/src/osmo-bsc_nat/bsc_nat.c1387
-rw-r--r--openbsc/src/osmo-bsc_nat/bsc_nat_utils.c893
-rw-r--r--openbsc/src/osmo-bsc_nat/bsc_nat_vty.c788
-rw-r--r--openbsc/src/osmo-bsc_nat/bsc_sccp.c249
-rw-r--r--openbsc/src/osmo-bsc_nat/bsc_ussd.c363
8 files changed, 4673 insertions, 0 deletions
diff --git a/openbsc/src/osmo-bsc_nat/Makefile.am b/openbsc/src/osmo-bsc_nat/Makefile.am
new file mode 100644
index 000000000..c7905ce3a
--- /dev/null
+++ b/openbsc/src/osmo-bsc_nat/Makefile.am
@@ -0,0 +1,13 @@
+INCLUDES = $(all_includes) -I$(top_srcdir)/include -I$(top_builddir)
+AM_CFLAGS=-Wall $(LIBOSMOCORE_CFLAGS) $(LIBOSMOVTY_CFLAGS) $(LIBOSMOSCCP_CFLAGS) $(COVERAGE_CFLAGS)
+AM_LDFLAGS = $(LIBOSMOCORE_LIBS) $(LIBOSMOVTY_LIBS) $(COVERAGE_LDFLAGS)
+
+bin_PROGRAMS = osmo-bsc_nat
+
+
+osmo_bsc_nat_SOURCES = bsc_filter.c bsc_mgcp_utils.c bsc_nat.c bsc_nat_utils.c \
+ bsc_nat_vty.c bsc_sccp.c bsc_ussd.c
+osmo_bsc_nat_LDADD = $(top_builddir)/src/common/libcommon.a \
+ $(top_builddir)/src/mgcp/libmgcp.a $(top_builddir)/src/bsc/libbsc.a \
+ $(top_builddir)/src/abis/libabis.a $(top_builddir)/src/trau/libtrau.a \
+ -lrt $(LIBOSMOSCCP_LIBS)
diff --git a/openbsc/src/osmo-bsc_nat/bsc_filter.c b/openbsc/src/osmo-bsc_nat/bsc_filter.c
new file mode 100644
index 000000000..73e987893
--- /dev/null
+++ b/openbsc/src/osmo-bsc_nat/bsc_filter.c
@@ -0,0 +1,216 @@
+/* BSC Multiplexer/NAT */
+
+/*
+ * (C) 2010 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * (C) 2010 by On-Waves
+ * 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 <openbsc/bsc_nat.h>
+#include <openbsc/bsc_nat_sccp.h>
+#include <openbsc/ipaccess.h>
+#include <openbsc/debug.h>
+
+#include <osmocore/talloc.h>
+#include <osmocore/protocol/gsm_08_08.h>
+
+#include <osmocom/sccp/sccp.h>
+
+/*
+ * The idea is to have a simple struct describing a IPA packet with
+ * SCCP SSN and the GSM 08.08 payload and decide. We will both have
+ * a white and a blacklist of packets we want to handle.
+ *
+ * TODO: Implement a "NOT" in the filter language.
+ */
+
+#define ALLOW_ANY -1
+
+#define FILTER_TO_BSC 1
+#define FILTER_TO_MSC 2
+#define FILTER_TO_BOTH 3
+
+
+struct bsc_pkt_filter {
+ int ipa_proto;
+ int dest_ssn;
+ int bssap;
+ int gsm;
+ int filter_dir;
+};
+
+static struct bsc_pkt_filter black_list[] = {
+ /* filter reset messages to the MSC */
+ { IPAC_PROTO_SCCP, SCCP_SSN_BSSAP, 0, BSS_MAP_MSG_RESET, FILTER_TO_MSC },
+
+ /* filter reset ack messages to the BSC */
+ { IPAC_PROTO_SCCP, SCCP_SSN_BSSAP, 0, BSS_MAP_MSG_RESET_ACKNOWLEDGE, FILTER_TO_BSC },
+
+ /* filter ip access */
+ { IPAC_PROTO_IPACCESS, ALLOW_ANY, ALLOW_ANY, ALLOW_ANY, FILTER_TO_MSC },
+};
+
+static struct bsc_pkt_filter white_list[] = {
+ /* allow IPAC_PROTO_SCCP messages to both sides */
+ { IPAC_PROTO_SCCP, ALLOW_ANY, ALLOW_ANY, ALLOW_ANY, FILTER_TO_BOTH },
+
+ /* allow MGCP messages to both sides */
+ { IPAC_PROTO_MGCP_OLD, ALLOW_ANY, ALLOW_ANY, ALLOW_ANY, FILTER_TO_BOTH },
+};
+
+struct bsc_nat_parsed *bsc_nat_parse(struct msgb *msg)
+{
+ struct sccp_parse_result result;
+ struct bsc_nat_parsed *parsed;
+ struct ipaccess_head *hh;
+
+ /* quick fail */
+ if (msg->len < 4)
+ return NULL;
+
+ parsed = talloc_zero(msg, struct bsc_nat_parsed);
+ if (!parsed)
+ return NULL;
+
+ /* more init */
+ parsed->ipa_proto = parsed->called_ssn = parsed->calling_ssn = -1;
+ parsed->sccp_type = parsed->bssap = parsed->gsm_type = -1;
+
+ /* start parsing */
+ hh = (struct ipaccess_head *) msg->data;
+ parsed->ipa_proto = hh->proto;
+
+ msg->l2h = &hh->data[0];
+
+ /* do a size check on the input */
+ if (ntohs(hh->len) != msgb_l2len(msg)) {
+ LOGP(DINP, LOGL_ERROR, "Wrong input length?\n");
+ talloc_free(parsed);
+ return NULL;
+ }
+
+ /* analyze sccp down here */
+ if (parsed->ipa_proto == IPAC_PROTO_SCCP) {
+ memset(&result, 0, sizeof(result));
+ if (sccp_parse_header(msg, &result) != 0) {
+ talloc_free(parsed);
+ return 0;
+ }
+
+ if (msg->l3h && msgb_l3len(msg) < 3) {
+ LOGP(DNAT, LOGL_ERROR, "Not enough space or GSM payload\n");
+ talloc_free(parsed);
+ return 0;
+ }
+
+ parsed->sccp_type = sccp_determine_msg_type(msg);
+ parsed->src_local_ref = result.source_local_reference;
+ parsed->dest_local_ref = result.destination_local_reference;
+ parsed->called_ssn = result.called.ssn;
+ parsed->calling_ssn = result.calling.ssn;
+
+ /* in case of connection confirm we have no payload */
+ if (msg->l3h) {
+ parsed->bssap = msg->l3h[0];
+ parsed->gsm_type = msg->l3h[2];
+ }
+ }
+
+ return parsed;
+}
+
+int bsc_nat_filter_ipa(int dir, struct msgb *msg, struct bsc_nat_parsed *parsed)
+{
+ int i;
+
+ /* go through the blacklist now */
+ for (i = 0; i < ARRAY_SIZE(black_list); ++i) {
+ /* ignore the rule? */
+ if (black_list[i].filter_dir != FILTER_TO_BOTH
+ && black_list[i].filter_dir != dir)
+ continue;
+
+ /* the proto is not blacklisted */
+ if (black_list[i].ipa_proto != ALLOW_ANY
+ && black_list[i].ipa_proto != parsed->ipa_proto)
+ continue;
+
+ if (parsed->ipa_proto == IPAC_PROTO_SCCP) {
+ /* the SSN is not blacklisted */
+ if (black_list[i].dest_ssn != ALLOW_ANY
+ && black_list[i].dest_ssn != parsed->called_ssn)
+ continue;
+
+ /* bssap */
+ if (black_list[i].bssap != ALLOW_ANY
+ && black_list[i].bssap != parsed->bssap)
+ continue;
+
+ /* gsm */
+ if (black_list[i].gsm != ALLOW_ANY
+ && black_list[i].gsm != parsed->gsm_type)
+ continue;
+
+ /* blacklisted */
+ LOGP(DNAT, LOGL_INFO, "Blacklisted with rule %d\n", i);
+ return 1;
+ } else {
+ /* blacklisted, we have no content sniffing yet */
+ LOGP(DNAT, LOGL_INFO, "Blacklisted with rule %d\n", i);
+ return 1;
+ }
+ }
+
+ /* go through the whitelust now */
+ for (i = 0; i < ARRAY_SIZE(white_list); ++i) {
+ /* ignore the rule? */
+ if (white_list[i].filter_dir != FILTER_TO_BOTH
+ && white_list[i].filter_dir != dir)
+ continue;
+
+ /* the proto is not whitelisted */
+ if (white_list[i].ipa_proto != ALLOW_ANY
+ && white_list[i].ipa_proto != parsed->ipa_proto)
+ continue;
+
+ if (parsed->ipa_proto == IPAC_PROTO_SCCP) {
+ /* the SSN is not whitelisted */
+ if (white_list[i].dest_ssn != ALLOW_ANY
+ && white_list[i].dest_ssn != parsed->called_ssn)
+ continue;
+
+ /* bssap */
+ if (white_list[i].bssap != ALLOW_ANY
+ && white_list[i].bssap != parsed->bssap)
+ continue;
+
+ /* gsm */
+ if (white_list[i].gsm != ALLOW_ANY
+ && white_list[i].gsm != parsed->gsm_type)
+ continue;
+
+ /* whitelisted */
+ LOGP(DNAT, LOGL_INFO, "Whitelisted with rule %d\n", i);
+ return 0;
+ } else {
+ /* whitelisted */
+ return 0;
+ }
+ }
+
+ return 1;
+}
diff --git a/openbsc/src/osmo-bsc_nat/bsc_mgcp_utils.c b/openbsc/src/osmo-bsc_nat/bsc_mgcp_utils.c
new file mode 100644
index 000000000..9eac00bf4
--- /dev/null
+++ b/openbsc/src/osmo-bsc_nat/bsc_mgcp_utils.c
@@ -0,0 +1,764 @@
+/*
+ * (C) 2010 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * (C) 2010 by On-Waves
+ * 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 <openbsc/bsc_nat.h>
+#include <openbsc/bsc_nat_sccp.h>
+#include <openbsc/gsm_data.h>
+#include <openbsc/debug.h>
+#include <openbsc/ipaccess.h>
+#include <openbsc/mgcp.h>
+#include <openbsc/mgcp_internal.h>
+
+#include <osmocom/sccp/sccp.h>
+
+#include <osmocore/talloc.h>
+#include <osmocore/gsm0808.h>
+#include <osmocore/protocol/gsm_08_08.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <errno.h>
+#include <unistd.h>
+
+int bsc_mgcp_nr_multiplexes(int max_endpoints)
+{
+ int div = max_endpoints / 32;
+
+ if ((max_endpoints % 32) != 0)
+ div += 1;
+
+ return div;
+}
+
+static int bsc_init_endps_if_needed(struct bsc_connection *con)
+{
+ int multiplexes;
+
+ /* we have done that */
+ if (con->_endpoint_status)
+ return 0;
+
+ /* we have no config... */
+ if (!con->cfg)
+ return -1;
+
+ multiplexes = bsc_mgcp_nr_multiplexes(con->cfg->max_endpoints);
+ con->number_multiplexes = multiplexes;
+ con->max_endpoints = con->cfg->max_endpoints;
+ con->_endpoint_status = talloc_zero_array(con, char, 32 * multiplexes + 1);
+ return con->_endpoint_status == NULL;
+}
+
+static int bsc_assign_endpoint(struct bsc_connection *bsc, struct sccp_connections *con)
+{
+ int multiplex;
+ int timeslot;
+ const int number_endpoints = bsc->max_endpoints;
+ int i;
+
+ mgcp_endpoint_to_timeslot(bsc->last_endpoint, &multiplex, &timeslot);
+ timeslot += 1;
+
+ for (i = 0; i < number_endpoints; ++i) {
+ int endpoint;
+
+ /* Wrap around timeslots */
+ if (timeslot == 0)
+ timeslot = 1;
+
+ if (timeslot == 0x1f) {
+ timeslot = 1;
+ multiplex += 1;
+ }
+
+ /* Wrap around the multiplex */
+ if (multiplex >= bsc->number_multiplexes)
+ multiplex = 0;
+
+ endpoint = mgcp_timeslot_to_endpoint(multiplex, timeslot);
+
+ /* Now check if we are allowed to assign this one */
+ if (endpoint >= bsc->max_endpoints) {
+ multiplex = 0;
+ timeslot = 1;
+ endpoint = mgcp_timeslot_to_endpoint(multiplex, timeslot);
+ }
+
+
+ if (bsc->_endpoint_status[endpoint] == 0) {
+ bsc->_endpoint_status[endpoint] = 1;
+ con->bsc_endp = endpoint;
+ bsc->last_endpoint = endpoint;
+ return 0;
+ }
+
+ timeslot += 1;
+ }
+
+ return -1;
+}
+
+static uint16_t create_cic(int endpoint)
+{
+ int timeslot, multiplex;
+
+ mgcp_endpoint_to_timeslot(endpoint, &multiplex, &timeslot);
+ return (multiplex << 5) | (timeslot & 0x1f);
+}
+
+int bsc_mgcp_assign_patch(struct sccp_connections *con, struct msgb *msg)
+{
+ struct sccp_connections *mcon;
+ struct tlv_parsed tp;
+ uint16_t cic;
+ uint8_t timeslot;
+ uint8_t multiplex;
+ unsigned int endp;
+
+ if (!msg->l3h) {
+ LOGP(DNAT, LOGL_ERROR, "Assignment message should have l3h pointer.\n");
+ return -1;
+ }
+
+ if (msgb_l3len(msg) < 3) {
+ LOGP(DNAT, LOGL_ERROR, "Assignment message has not enough space for GSM0808.\n");
+ return -1;
+ }
+
+ tlv_parse(&tp, gsm0808_att_tlvdef(), msg->l3h + 3, msgb_l3len(msg) - 3, 0, 0);
+ if (!TLVP_PRESENT(&tp, GSM0808_IE_CIRCUIT_IDENTITY_CODE)) {
+ LOGP(DNAT, LOGL_ERROR, "Circuit identity code not found in assignment message.\n");
+ return -1;
+ }
+
+ cic = ntohs(*(uint16_t *)TLVP_VAL(&tp, GSM0808_IE_CIRCUIT_IDENTITY_CODE));
+ timeslot = cic & 0x1f;
+ multiplex = (cic & ~0x1f) >> 5;
+
+
+ endp = mgcp_timeslot_to_endpoint(multiplex, timeslot);
+
+ if (endp >= con->bsc->nat->mgcp_cfg->trunk.number_endpoints) {
+ LOGP(DNAT, LOGL_ERROR,
+ "MSC attempted to assign bad endpoint 0x%x\n",
+ endp);
+ return -1;
+ }
+
+ /* find stale connections using that endpoint */
+ llist_for_each_entry(mcon, &con->bsc->nat->sccp_connections, list_entry) {
+ if (mcon->msc_endp == endp) {
+ LOGP(DNAT, LOGL_ERROR,
+ "Endpoint %d was assigned to 0x%x and now 0x%x\n",
+ endp,
+ sccp_src_ref_to_int(&mcon->patched_ref),
+ sccp_src_ref_to_int(&con->patched_ref));
+ bsc_mgcp_dlcx(mcon);
+ }
+ }
+
+ con->msc_endp = endp;
+ if (bsc_init_endps_if_needed(con->bsc) != 0)
+ return -1;
+ if (bsc_assign_endpoint(con->bsc, con) != 0)
+ return -1;
+
+ /*
+ * now patch the message for the new CIC...
+ * still assumed to be one multiplex only
+ */
+ cic = htons(create_cic(con->bsc_endp));
+ memcpy((uint8_t *) TLVP_VAL(&tp, GSM0808_IE_CIRCUIT_IDENTITY_CODE),
+ &cic, sizeof(cic));
+
+ return 0;
+}
+
+static void bsc_mgcp_free_endpoint(struct bsc_nat *nat, int i)
+{
+ if (nat->bsc_endpoints[i].transaction_id) {
+ talloc_free(nat->bsc_endpoints[i].transaction_id);
+ nat->bsc_endpoints[i].transaction_id = NULL;
+ }
+
+ nat->bsc_endpoints[i].transaction_state = 0;
+ nat->bsc_endpoints[i].bsc = NULL;
+}
+
+void bsc_mgcp_free_endpoints(struct bsc_nat *nat)
+{
+ int i;
+
+ for (i = 1; i < nat->mgcp_cfg->trunk.number_endpoints; ++i){
+ bsc_mgcp_free_endpoint(nat, i);
+ mgcp_free_endp(&nat->mgcp_cfg->trunk.endpoints[i]);
+ }
+}
+
+/* send a MDCX where we do not want a response */
+static void bsc_mgcp_send_mdcx(struct bsc_connection *bsc, int port, struct mgcp_endpoint *endp)
+{
+ char buf[2096];
+ int len;
+
+ len = snprintf(buf, sizeof(buf),
+ "MDCX 23 %x@mgw MGCP 1.0\r\n"
+ "Z: noanswer\r\n"
+ "\r\n"
+ "c=IN IP4 %s\r\n"
+ "m=audio %d RTP/AVP 255\r\n",
+ port,
+ bsc->nat->mgcp_cfg->source_addr,
+ endp->bts_end.local_port);
+ if (len < 0) {
+ LOGP(DMGCP, LOGL_ERROR, "snprintf for DLCX failed.\n");
+ return;
+ }
+
+ #warning "The MDCX is not send to the BSC. It should"
+}
+
+static void bsc_mgcp_send_dlcx(struct bsc_connection *bsc, int endpoint)
+{
+ char buf[2096];
+ int len;
+
+ len = snprintf(buf, sizeof(buf),
+ "DLCX 26 %x@mgw MGCP 1.0\r\n"
+ "Z: noanswer\r\n", endpoint);
+ if (len < 0) {
+ LOGP(DMGCP, LOGL_ERROR, "snprintf for DLCX failed.\n");
+ return;
+ }
+
+ bsc_write_mgcp(bsc, (uint8_t *) buf, len);
+}
+
+void bsc_mgcp_init(struct sccp_connections *con)
+{
+ con->msc_endp = -1;
+ con->bsc_endp = -1;
+}
+
+void bsc_mgcp_dlcx(struct sccp_connections *con)
+{
+ /* send a DLCX down the stream */
+ if (con->bsc_endp != -1 && con->bsc->_endpoint_status) {
+ if (con->bsc->_endpoint_status[con->bsc_endp] != 1)
+ LOGP(DNAT, LOGL_ERROR, "Endpoint 0x%x was not in use\n", con->bsc_endp);
+ con->bsc->_endpoint_status[con->bsc_endp] = 0;
+ bsc_mgcp_send_dlcx(con->bsc, con->bsc_endp);
+ bsc_mgcp_free_endpoint(con->bsc->nat, con->msc_endp);
+ }
+
+ bsc_mgcp_init(con);
+}
+
+
+struct sccp_connections *bsc_mgcp_find_con(struct bsc_nat *nat, int endpoint)
+{
+ struct sccp_connections *con = NULL;
+ struct sccp_connections *sccp;
+
+ llist_for_each_entry(sccp, &nat->sccp_connections, list_entry) {
+ if (sccp->msc_endp == -1)
+ continue;
+ if (sccp->msc_endp != endpoint)
+ continue;
+
+ con = sccp;
+ }
+
+ if (con)
+ return con;
+
+ LOGP(DMGCP, LOGL_ERROR, "Failed to find the connection.\n");
+ return NULL;
+}
+
+int bsc_mgcp_policy_cb(struct mgcp_trunk_config *tcfg, int endpoint, int state, const char *transaction_id)
+{
+ struct bsc_nat *nat;
+ struct bsc_endpoint *bsc_endp;
+ struct sccp_connections *sccp;
+ struct mgcp_endpoint *mgcp_endp;
+ struct msgb *bsc_msg;
+
+ nat = tcfg->cfg->data;
+ bsc_endp = &nat->bsc_endpoints[endpoint];
+ mgcp_endp = &nat->mgcp_cfg->trunk.endpoints[endpoint];
+
+ if (bsc_endp->transaction_id) {
+ LOGP(DMGCP, LOGL_ERROR, "Endpoint 0x%x had pending transaction: '%s'\n",
+ endpoint, bsc_endp->transaction_id);
+ talloc_free(bsc_endp->transaction_id);
+ bsc_endp->transaction_id = NULL;
+ bsc_endp->transaction_state = 0;
+ }
+ bsc_endp->bsc = NULL;
+
+ sccp = bsc_mgcp_find_con(nat, endpoint);
+
+ if (!sccp) {
+ LOGP(DMGCP, LOGL_ERROR, "Did not find BSC for change on endpoint: 0x%x state: %d\n", endpoint, state);
+
+ switch (state) {
+ case MGCP_ENDP_CRCX:
+ return MGCP_POLICY_REJECT;
+ break;
+ case MGCP_ENDP_DLCX:
+ return MGCP_POLICY_CONT;
+ break;
+ case MGCP_ENDP_MDCX:
+ return MGCP_POLICY_CONT;
+ break;
+ default:
+ LOGP(DMGCP, LOGL_FATAL, "Unhandled state: %d\n", state);
+ return MGCP_POLICY_CONT;
+ break;
+ }
+ }
+
+ /* we need to generate a new and patched message */
+ bsc_msg = bsc_mgcp_rewrite((char *) nat->mgcp_msg, nat->mgcp_length, sccp->bsc_endp,
+ nat->mgcp_cfg->source_addr, mgcp_endp->bts_end.local_port);
+ if (!bsc_msg) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to patch the msg.\n");
+ return MGCP_POLICY_CONT;
+ }
+
+
+ bsc_endp->transaction_id = talloc_strdup(nat, transaction_id);
+ bsc_endp->transaction_state = state;
+ bsc_endp->bsc = sccp->bsc;
+
+ /* we need to update some bits */
+ if (state == MGCP_ENDP_CRCX) {
+ struct sockaddr_in sock;
+ socklen_t len = sizeof(sock);
+ if (getpeername(sccp->bsc->write_queue.bfd.fd, (struct sockaddr *) &sock, &len) != 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Can not get the peername...%d/%s\n",
+ errno, strerror(errno));
+ } else {
+ mgcp_endp->bts_end.addr = sock.sin_addr;
+ }
+
+ /* send the message and a fake MDCX to force sending of a dummy packet */
+ bsc_write(sccp->bsc, bsc_msg, IPAC_PROTO_MGCP_OLD);
+ bsc_mgcp_send_mdcx(sccp->bsc, sccp->bsc_endp, mgcp_endp);
+ return MGCP_POLICY_DEFER;
+ } else if (state == MGCP_ENDP_DLCX) {
+ /* we will free the endpoint now and send a DLCX to the BSC */
+ msgb_free(bsc_msg);
+ bsc_mgcp_dlcx(sccp);
+ return MGCP_POLICY_CONT;
+ } else {
+ bsc_write(sccp->bsc, bsc_msg, IPAC_PROTO_MGCP_OLD);
+ return MGCP_POLICY_DEFER;
+ }
+}
+
+/*
+ * We do have a failure, free data downstream..
+ */
+static void free_chan_downstream(struct mgcp_endpoint *endp, struct bsc_endpoint *bsc_endp,
+ struct bsc_connection *bsc)
+{
+ LOGP(DMGCP, LOGL_ERROR, "No CI, freeing endpoint 0x%x in state %d\n",
+ ENDPOINT_NUMBER(endp), bsc_endp->transaction_state);
+
+ /* if a CRCX failed... send a DLCX down the stream */
+ if (bsc_endp->transaction_state == MGCP_ENDP_CRCX) {
+ struct sccp_connections *con;
+ con = bsc_mgcp_find_con(bsc->nat, ENDPOINT_NUMBER(endp));
+ if (!con) {
+ LOGP(DMGCP, LOGL_ERROR,
+ "No SCCP connection for endp 0x%x\n",
+ ENDPOINT_NUMBER(endp));
+ } else {
+ if (con->bsc == bsc) {
+ bsc_mgcp_send_dlcx(bsc, con->bsc_endp);
+ } else {
+ LOGP(DMGCP, LOGL_ERROR,
+ "Endpoint belongs to a different BSC\n");
+ }
+ }
+ }
+
+ bsc_mgcp_free_endpoint(bsc->nat, ENDPOINT_NUMBER(endp));
+ mgcp_free_endp(endp);
+}
+
+/*
+ * We have received a msg from the BSC. We will see if we know
+ * this transaction and if it belongs to the BSC. Then we will
+ * need to patch the content to point to the local network and we
+ * need to update the I: that was assigned by the BSS.
+ */
+void bsc_mgcp_forward(struct bsc_connection *bsc, struct msgb *msg)
+{
+ struct msgb *output;
+ struct bsc_endpoint *bsc_endp = NULL;
+ struct mgcp_endpoint *endp = NULL;
+ int i, code;
+ char transaction_id[60];
+
+ /* Some assumption that our buffer is big enough.. and null terminate */
+ if (msgb_l2len(msg) > 2000) {
+ LOGP(DMGCP, LOGL_ERROR, "MGCP message too long.\n");
+ return;
+ }
+
+ msg->l2h[msgb_l2len(msg)] = '\0';
+
+ if (bsc_mgcp_parse_response((const char *) msg->l2h, &code, transaction_id) != 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to parse response code.\n");
+ return;
+ }
+
+ for (i = 1; i < bsc->nat->mgcp_cfg->trunk.number_endpoints; ++i) {
+ if (bsc->nat->bsc_endpoints[i].bsc != bsc)
+ continue;
+ /* no one listening? a bug? */
+ if (!bsc->nat->bsc_endpoints[i].transaction_id)
+ continue;
+ if (strcmp(transaction_id, bsc->nat->bsc_endpoints[i].transaction_id) != 0)
+ continue;
+
+ endp = &bsc->nat->mgcp_cfg->trunk.endpoints[i];
+ bsc_endp = &bsc->nat->bsc_endpoints[i];
+ break;
+ }
+
+ if (!bsc_endp) {
+ LOGP(DMGCP, LOGL_ERROR, "Could not find active endpoint: %s for msg: '%s'\n",
+ transaction_id, (const char *) msg->l2h);
+ return;
+ }
+
+ endp->ci = bsc_mgcp_extract_ci((const char *) msg->l2h);
+ if (endp->ci == CI_UNUSED) {
+ free_chan_downstream(endp, bsc_endp, bsc);
+ return;
+ }
+
+ /* free some stuff */
+ talloc_free(bsc_endp->transaction_id);
+ bsc_endp->transaction_id = NULL;
+ bsc_endp->transaction_state = 0;
+
+ /*
+ * rewrite the information. In case the endpoint was deleted
+ * there should be nothing for us to rewrite so putting endp->rtp_port
+ * with the value of 0 should be no problem.
+ */
+ output = bsc_mgcp_rewrite((char * ) msg->l2h, msgb_l2len(msg), -1,
+ bsc->nat->mgcp_cfg->source_addr, endp->net_end.local_port);
+
+ if (!output) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to rewrite MGCP msg.\n");
+ return;
+ }
+
+ if (write_queue_enqueue(&bsc->nat->mgcp_cfg->gw_fd, output) != 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to queue MGCP msg.\n");
+ msgb_free(output);
+ }
+}
+
+int bsc_mgcp_parse_response(const char *str, int *code, char transaction[60])
+{
+ /* we want to parse two strings */
+ return sscanf(str, "%3d %59s\n", code, transaction) != 2;
+}
+
+uint32_t bsc_mgcp_extract_ci(const char *str)
+{
+ unsigned int ci;
+ char *res = strstr(str, "I: ");
+ if (!res) {
+ LOGP(DMGCP, LOGL_ERROR, "No CI in msg '%s'\n", str);
+ return CI_UNUSED;
+ }
+
+ if (sscanf(res, "I: %u", &ci) != 1) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to parse CI in msg '%s'\n", str);
+ return CI_UNUSED;
+ }
+
+ return ci;
+}
+
+static void patch_mgcp(struct msgb *output, const char *op, const char *tok,
+ int endp, int len, int cr)
+{
+ int slen;
+ int ret;
+ char buf[40];
+
+ buf[0] = buf[39] = '\0';
+ ret = sscanf(tok, "%*s %s", buf);
+
+ slen = sprintf((char *) output->l3h, "%s %s %x@mgw MGCP 1.0%s",
+ op, buf, endp, cr ? "\r\n" : "\n");
+ output->l3h = msgb_put(output, slen);
+}
+
+/* we need to replace some strings... */
+struct msgb *bsc_mgcp_rewrite(char *input, int length, int endpoint, const char *ip, int port)
+{
+ static const char *crcx_str = "CRCX ";
+ static const char *dlcx_str = "DLCX ";
+ static const char *mdcx_str = "MDCX ";
+
+ static const char *ip_str = "c=IN IP4 ";
+ static const char *aud_str = "m=audio ";
+
+ char buf[128];
+ char *running, *token;
+ struct msgb *output;
+
+ if (length > 4096 - 128) {
+ LOGP(DMGCP, LOGL_ERROR, "Input is too long.\n");
+ return NULL;
+ }
+
+ output = msgb_alloc_headroom(4096, 128, "MGCP rewritten");
+ if (!output) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to allocate new MGCP msg.\n");
+ return NULL;
+ }
+
+ running = input;
+ output->l2h = output->data;
+ output->l3h = output->l2h;
+ for (token = strsep(&running, "\n"); running; token = strsep(&running, "\n")) {
+ int len = strlen(token);
+ int cr = len > 0 && token[len - 1] == '\r';
+
+ if (strncmp(crcx_str, token, (sizeof crcx_str) - 1) == 0) {
+ patch_mgcp(output, "CRCX", token, endpoint, len, cr);
+ } else if (strncmp(dlcx_str, token, (sizeof dlcx_str) - 1) == 0) {
+ patch_mgcp(output, "DLCX", token, endpoint, len, cr);
+ } else if (strncmp(mdcx_str, token, (sizeof mdcx_str) - 1) == 0) {
+ patch_mgcp(output, "MDCX", token, endpoint, len, cr);
+ } else if (strncmp(ip_str, token, (sizeof ip_str) - 1) == 0) {
+ output->l3h = msgb_put(output, strlen(ip_str));
+ memcpy(output->l3h, ip_str, strlen(ip_str));
+ output->l3h = msgb_put(output, strlen(ip));
+ memcpy(output->l3h, ip, strlen(ip));
+
+ if (cr) {
+ output->l3h = msgb_put(output, 2);
+ output->l3h[0] = '\r';
+ output->l3h[1] = '\n';
+ } else {
+ output->l3h = msgb_put(output, 1);
+ output->l3h[0] = '\n';
+ }
+ } else if (strncmp(aud_str, token, (sizeof aud_str) - 1) == 0) {
+ int payload;
+ if (sscanf(token, "m=audio %*d RTP/AVP %d", &payload) != 1) {
+ LOGP(DMGCP, LOGL_ERROR, "Could not parsed audio line.\n");
+ msgb_free(output);
+ return NULL;
+ }
+
+ snprintf(buf, sizeof(buf)-1, "m=audio %d RTP/AVP %d%s",
+ port, payload, cr ? "\r\n" : "\n");
+ buf[sizeof(buf)-1] = '\0';
+
+ output->l3h = msgb_put(output, strlen(buf));
+ memcpy(output->l3h, buf, strlen(buf));
+ } else {
+ output->l3h = msgb_put(output, len + 1);
+ memcpy(output->l3h, token, len);
+ output->l3h[len] = '\n';
+ }
+ }
+
+ return output;
+}
+
+static int mgcp_do_read(struct bsc_fd *fd)
+{
+ struct bsc_nat *nat;
+ struct msgb *msg, *resp;
+ int rc;
+
+ nat = fd->data;
+
+ rc = read(fd->fd, nat->mgcp_msg, sizeof(nat->mgcp_msg) - 1);
+ if (rc <= 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to read errno: %d\n", errno);
+ return -1;
+ }
+
+ nat->mgcp_msg[rc] = '\0';
+ nat->mgcp_length = rc;
+
+ msg = msgb_alloc(sizeof(nat->mgcp_msg), "MGCP GW Read");
+ if (!msg) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to create buffer.\n");
+ return -1;
+ }
+
+ msg->l2h = msgb_put(msg, rc);
+ memcpy(msg->l2h, nat->mgcp_msg, msgb_l2len(msg));
+ resp = mgcp_handle_message(nat->mgcp_cfg, msg);
+ msgb_free(msg);
+
+ /* we do have a direct answer... e.g. AUEP */
+ if (resp) {
+ if (write_queue_enqueue(&nat->mgcp_cfg->gw_fd, resp) != 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to enqueue msg.\n");
+ msgb_free(resp);
+ }
+ }
+
+ return 0;
+}
+
+static int mgcp_do_write(struct bsc_fd *bfd, struct msgb *msg)
+{
+ int rc;
+
+ rc = write(bfd->fd, msg->data, msg->len);
+
+ if (rc != msg->len) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to write msg to MGCP CallAgent.\n");
+ return -1;
+ }
+
+ return rc;
+}
+
+int bsc_mgcp_nat_init(struct bsc_nat *nat)
+{
+ int on;
+ struct sockaddr_in addr;
+ struct mgcp_config *cfg = nat->mgcp_cfg;
+
+ if (!cfg->call_agent_addr) {
+ LOGP(DMGCP, LOGL_ERROR, "The BSC nat requires the call agent ip to be set.\n");
+ return -1;
+ }
+
+ if (cfg->bts_ip) {
+ LOGP(DMGCP, LOGL_ERROR, "Do not set the BTS ip for the nat.\n");
+ return -1;
+ }
+
+ cfg->gw_fd.bfd.fd = socket(AF_INET, SOCK_DGRAM, 0);
+ if (cfg->gw_fd.bfd.fd < 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to create MGCP socket. errno: %d\n", errno);
+ return -1;
+ }
+
+ on = 1;
+ setsockopt(cfg->gw_fd.bfd.fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
+
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(cfg->source_port);
+ inet_aton(cfg->source_addr, &addr.sin_addr);
+
+ if (bind(cfg->gw_fd.bfd.fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to bind. errno: %d\n", errno);
+ close(cfg->gw_fd.bfd.fd);
+ cfg->gw_fd.bfd.fd = -1;
+ return -1;
+ }
+
+ addr.sin_port = htons(2727);
+ inet_aton(cfg->call_agent_addr, &addr.sin_addr);
+ if (connect(cfg->gw_fd.bfd.fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to connect to: '%s'. errno: %d\n",
+ cfg->call_agent_addr, errno);
+ close(cfg->gw_fd.bfd.fd);
+ cfg->gw_fd.bfd.fd = -1;
+ return -1;
+ }
+
+ write_queue_init(&cfg->gw_fd, 10);
+ cfg->gw_fd.bfd.when = BSC_FD_READ;
+ cfg->gw_fd.bfd.data = nat;
+ cfg->gw_fd.read_cb = mgcp_do_read;
+ cfg->gw_fd.write_cb = mgcp_do_write;
+
+ if (bsc_register_fd(&cfg->gw_fd.bfd) != 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to register MGCP fd.\n");
+ close(cfg->gw_fd.bfd.fd);
+ cfg->gw_fd.bfd.fd = -1;
+ return -1;
+ }
+
+ /* some more MGCP config handling */
+ cfg->data = nat;
+ cfg->policy_cb = bsc_mgcp_policy_cb;
+ cfg->trunk.force_realloc = 1;
+
+ if (cfg->bts_ip)
+ talloc_free(cfg->bts_ip);
+ cfg->bts_ip = "";
+
+ nat->bsc_endpoints = talloc_zero_array(nat,
+ struct bsc_endpoint,
+ cfg->trunk.number_endpoints + 1);
+ if (!nat->bsc_endpoints) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to allocate nat endpoints\n");
+ close(cfg->gw_fd.bfd.fd);
+ cfg->gw_fd.bfd.fd = -1;
+ return -1;
+ }
+
+ if (mgcp_reset_transcoder(cfg) < 0) {
+ LOGP(DMGCP, LOGL_ERROR, "Failed to send packet to the transcoder.\n");
+ talloc_free(nat->bsc_endpoints);
+ nat->bsc_endpoints = NULL;
+ close(cfg->gw_fd.bfd.fd);
+ cfg->gw_fd.bfd.fd = -1;
+ return -1;
+ }
+
+ return 0;
+}
+
+void bsc_mgcp_clear_endpoints_for(struct bsc_connection *bsc)
+{
+ struct rate_ctr *ctr = NULL;
+ int i;
+
+ if (bsc->cfg)
+ ctr = &bsc->cfg->stats.ctrg->ctr[BCFG_CTR_DROPPED_CALLS];
+
+ for (i = 1; i < bsc->nat->mgcp_cfg->trunk.number_endpoints; ++i) {
+ struct bsc_endpoint *bsc_endp = &bsc->nat->bsc_endpoints[i];
+
+ if (bsc_endp->bsc != bsc)
+ continue;
+
+ if (ctr)
+ rate_ctr_inc(ctr);
+
+ bsc_mgcp_free_endpoint(bsc->nat, i);
+ mgcp_free_endp(&bsc->nat->mgcp_cfg->trunk.endpoints[i]);
+ }
+}
diff --git a/openbsc/src/osmo-bsc_nat/bsc_nat.c b/openbsc/src/osmo-bsc_nat/bsc_nat.c
new file mode 100644
index 000000000..643b3c4ba
--- /dev/null
+++ b/openbsc/src/osmo-bsc_nat/bsc_nat.c
@@ -0,0 +1,1387 @@
+/* BSC Multiplexer/NAT */
+
+/*
+ * (C) 2010 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * (C) 2010 by On-Waves
+ * (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 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 <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include <unistd.h>
+
+#define _GNU_SOURCE
+#include <getopt.h>
+
+#include <openbsc/debug.h>
+#include <openbsc/bsc_msc.h>
+#include <openbsc/bsc_nat.h>
+#include <openbsc/bsc_nat_sccp.h>
+#include <openbsc/ipaccess.h>
+#include <openbsc/abis_nm.h>
+#include <openbsc/socket.h>
+#include <openbsc/vty.h>
+
+#include <osmocore/gsm0808.h>
+#include <osmocore/talloc.h>
+#include <osmocore/process.h>
+
+#include <osmocore/protocol/gsm_08_08.h>
+
+#include <osmocom/vty/telnet_interface.h>
+#include <osmocom/vty/vty.h>
+
+#include <osmocom/sccp/sccp.h>
+
+#include "../../bscconfig.h"
+
+#define SCCP_CLOSE_TIME 20
+#define SCCP_CLOSE_TIME_TIMEOUT 19
+
+struct log_target *stderr_target;
+static const char *config_file = "bsc-nat.cfg";
+static struct in_addr local_addr;
+static struct bsc_fd bsc_listen;
+static const char *msc_ip = NULL;
+static struct timer_list sccp_close;
+static int daemonize = 0;
+
+const char *openbsc_copyright =
+ "Copyright (C) 2010 Holger Hans Peter Freyther and On-Waves\r\n"
+ "License AGPLv3+: GNU AGPL version 3 or later <http://gnu.org/licenses/agpl-3.0.html>\r\n"
+ "This is free software: you are free to change and redistribute it.\r\n"
+ "There is NO WARRANTY, to the extent permitted by law.\r\n";
+
+static struct bsc_nat *nat;
+static void bsc_send_data(struct bsc_connection *bsc, const uint8_t *data, unsigned int length, int);
+static void msc_send_reset(struct bsc_msc_connection *con);
+static void bsc_stat_reject(int filter, struct bsc_connection *bsc, int normal);
+
+struct bsc_config *bsc_config_num(struct bsc_nat *nat, int num)
+{
+ struct bsc_config *conf;
+
+ llist_for_each_entry(conf, &nat->bsc_configs, entry)
+ if (conf->nr == num)
+ return conf;
+
+ return NULL;
+}
+
+static void queue_for_msc(struct bsc_msc_connection *con, struct msgb *msg)
+{
+ if (!con) {
+ LOGP(DINP, LOGL_ERROR, "No MSC Connection assigned. Check your code.\n");
+ msgb_free(msg);
+ return;
+ }
+
+
+ if (write_queue_enqueue(&con->write_queue, msg) != 0) {
+ LOGP(DINP, LOGL_ERROR, "Failed to enqueue the write.\n");
+ msgb_free(msg);
+ }
+}
+
+static void send_reset_ack(struct bsc_connection *bsc)
+{
+ static const uint8_t gsm_reset_ack[] = {
+ 0x09, 0x00, 0x03, 0x07, 0x0b, 0x04, 0x43, 0x01,
+ 0x00, 0xfe, 0x04, 0x43, 0x5c, 0x00, 0xfe, 0x03,
+ 0x00, 0x01, 0x31,
+ };
+
+ bsc_send_data(bsc, gsm_reset_ack, sizeof(gsm_reset_ack), IPAC_PROTO_SCCP);
+}
+
+static void send_ping(struct bsc_connection *bsc)
+{
+ static const uint8_t id_ping[] = {
+ IPAC_MSGT_PING,
+ };
+
+ bsc_send_data(bsc, id_ping, sizeof(id_ping), IPAC_PROTO_IPACCESS);
+}
+
+static void send_pong(struct bsc_connection *bsc)
+{
+ static const uint8_t id_pong[] = {
+ IPAC_MSGT_PONG,
+ };
+
+ bsc_send_data(bsc, id_pong, sizeof(id_pong), IPAC_PROTO_IPACCESS);
+}
+
+static void bsc_pong_timeout(void *_bsc)
+{
+ struct bsc_connection *bsc = _bsc;
+
+ LOGP(DNAT, LOGL_ERROR, "BSC Nr: %d PONG timeout.\n", bsc->cfg->nr);
+ bsc_close_connection(bsc);
+}
+
+static void bsc_ping_timeout(void *_bsc)
+{
+ struct bsc_connection *bsc = _bsc;
+
+ if (bsc->nat->ping_timeout < 0)
+ return;
+
+ send_ping(bsc);
+
+ /* send another ping in 20 seconds */
+ bsc_schedule_timer(&bsc->ping_timeout, bsc->nat->ping_timeout, 0);
+
+ /* also start a pong timer */
+ bsc_schedule_timer(&bsc->pong_timeout, bsc->nat->pong_timeout, 0);
+}
+
+static void start_ping_pong(struct bsc_connection *bsc)
+{
+ bsc->pong_timeout.data = bsc;
+ bsc->pong_timeout.cb = bsc_pong_timeout;
+ bsc->ping_timeout.data = bsc;
+ bsc->ping_timeout.cb = bsc_ping_timeout;
+
+ bsc_ping_timeout(bsc);
+}
+
+static void send_id_ack(struct bsc_connection *bsc)
+{
+ static const uint8_t id_ack[] = {
+ IPAC_MSGT_ID_ACK
+ };
+
+ bsc_send_data(bsc, id_ack, sizeof(id_ack), IPAC_PROTO_IPACCESS);
+}
+
+static void send_id_req(struct bsc_connection *bsc)
+{
+ static const uint8_t id_req[] = {
+ IPAC_MSGT_ID_GET,
+ 0x01, IPAC_IDTAG_UNIT,
+ 0x01, IPAC_IDTAG_MACADDR,
+ 0x01, IPAC_IDTAG_LOCATION1,
+ 0x01, IPAC_IDTAG_LOCATION2,
+ 0x01, IPAC_IDTAG_EQUIPVERS,
+ 0x01, IPAC_IDTAG_SWVERSION,
+ 0x01, IPAC_IDTAG_UNITNAME,
+ 0x01, IPAC_IDTAG_SERNR,
+ };
+
+ bsc_send_data(bsc, id_req, sizeof(id_req), IPAC_PROTO_IPACCESS);
+}
+
+static void nat_send_rlsd_msc(struct sccp_connections *conn)
+{
+ struct sccp_connection_released *rel;
+ struct msgb *msg;
+
+ msg = msgb_alloc_headroom(4096, 128, "rlsd");
+ if (!msg) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate clear command.\n");
+ return;
+ }
+
+ msg->l2h = msgb_put(msg, sizeof(*rel));
+ rel = (struct sccp_connection_released *) msg->l2h;
+ rel->type = SCCP_MSG_TYPE_RLSD;
+ rel->release_cause = SCCP_RELEASE_CAUSE_SCCP_FAILURE;
+ rel->destination_local_reference = conn->remote_ref;
+ rel->source_local_reference = conn->patched_ref;
+
+ ipaccess_prepend_header(msg, IPAC_PROTO_SCCP);
+
+ queue_for_msc(conn->msc_con, msg);
+}
+
+static void nat_send_rlsd_bsc(struct sccp_connections *conn)
+{
+ struct sccp_connection_released *rel;
+ struct msgb *msg;
+
+ msg = msgb_alloc_headroom(4096, 128, "rlsd");
+ if (!msg) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate clear command.\n");
+ return;
+ }
+
+ msg->l2h = msgb_put(msg, sizeof(*rel));
+ rel = (struct sccp_connection_released *) msg->l2h;
+ rel->type = SCCP_MSG_TYPE_RLSD;
+ rel->release_cause = SCCP_RELEASE_CAUSE_SCCP_FAILURE;
+ rel->destination_local_reference = conn->real_ref;
+ rel->source_local_reference = conn->remote_ref;
+
+ bsc_write(conn->bsc, msg, IPAC_PROTO_SCCP);
+}
+
+static struct msgb *nat_creat_clrc(struct sccp_connections *conn, uint8_t cause)
+{
+ struct msgb *msg;
+ struct msgb *sccp;
+
+ msg = gsm0808_create_clear_command(cause);
+ if (!msg) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate clear command.\n");
+ return NULL;
+ }
+
+ sccp = sccp_create_dt1(&conn->real_ref, msg->data, msg->len);
+ if (!sccp) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate SCCP msg.\n");
+ msgb_free(msg);
+ return NULL;
+ }
+
+ msgb_free(msg);
+ return sccp;
+}
+
+static int nat_send_clrc_bsc(struct sccp_connections *conn)
+{
+ struct msgb *sccp;
+
+ sccp = nat_creat_clrc(conn, 0x20);
+ if (!sccp)
+ return -1;
+ return bsc_write(conn->bsc, sccp, IPAC_PROTO_SCCP);
+}
+
+static void nat_send_rlc(struct bsc_msc_connection *msc_con,
+ struct sccp_source_reference *src,
+ struct sccp_source_reference *dst)
+{
+ struct sccp_connection_release_complete *rlc;
+ struct msgb *msg;
+
+ msg = msgb_alloc_headroom(4096, 128, "rlc");
+ if (!msg) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate clear command.\n");
+ return;
+ }
+
+ msg->l2h = msgb_put(msg, sizeof(*rlc));
+ rlc = (struct sccp_connection_release_complete *) msg->l2h;
+ rlc->type = SCCP_MSG_TYPE_RLC;
+ rlc->destination_local_reference = *dst;
+ rlc->source_local_reference = *src;
+
+ ipaccess_prepend_header(msg, IPAC_PROTO_SCCP);
+
+ queue_for_msc(msc_con, msg);
+}
+
+static void send_mgcp_reset(struct bsc_connection *bsc)
+{
+ static const uint8_t mgcp_reset[] = {
+ "RSIP 1 13@mgw MGCP 1.0\r\n"
+ };
+
+ bsc_write_mgcp(bsc, mgcp_reset, sizeof mgcp_reset - 1);
+}
+
+/*
+ * Below is the handling of messages coming
+ * from the MSC and need to be forwarded to
+ * a real BSC.
+ */
+static void initialize_msc_if_needed(struct bsc_msc_connection *msc_con)
+{
+ if (msc_con->first_contact)
+ return;
+
+ msc_con->first_contact = 1;
+ msc_send_reset(msc_con);
+}
+
+static void send_id_get_response(struct bsc_msc_connection *msc_con)
+{
+ struct msgb *msg = bsc_msc_id_get_resp(nat->token);
+ if (!msg)
+ return;
+
+ ipaccess_prepend_header(msg, IPAC_PROTO_IPACCESS);
+ queue_for_msc(msc_con, msg);
+}
+
+/*
+ * Currently we are lacking refcounting so we need to copy each message.
+ */
+static void bsc_send_data(struct bsc_connection *bsc, const uint8_t *data, unsigned int length, int proto)
+{
+ struct msgb *msg;
+
+ if (length > 4096 - 128) {
+ LOGP(DINP, LOGL_ERROR, "Can not send message of that size.\n");
+ return;
+ }
+
+ msg = msgb_alloc_headroom(4096, 128, "to-bsc");
+ if (!msg) {
+ LOGP(DINP, LOGL_ERROR, "Failed to allocate memory for BSC msg.\n");
+ return;
+ }
+
+ msg->l2h = msgb_put(msg, length);
+ memcpy(msg->data, data, length);
+
+ bsc_write(bsc, msg, proto);
+}
+
+/*
+ * Update the release statistics
+ */
+static void bsc_stat_reject(int filter, struct bsc_connection *bsc, int normal)
+{
+ if (!bsc->cfg) {
+ LOGP(DNAT, LOGL_ERROR, "BSC is not authenticated.");
+ return;
+ }
+
+ if (filter >= 0) {
+ LOGP(DNAT, LOGL_ERROR, "Connection was not rejected");
+ return;
+ }
+
+ if (filter == -1)
+ rate_ctr_inc(&bsc->cfg->stats.ctrg->ctr[BCFG_CTR_ILL_PACKET]);
+ else if (normal)
+ rate_ctr_inc(&bsc->cfg->stats.ctrg->ctr[BCFG_CTR_REJECTED_MSG]);
+ else
+ rate_ctr_inc(&bsc->cfg->stats.ctrg->ctr[BCFG_CTR_REJECTED_CR]);
+}
+
+/*
+ * Release an established connection. We will have to release it to the BSC
+ * and to the network and we do it the following way.
+ * 1.) Give up on the MSC side
+ * 1.1) Send a RLSD message, it is a bit non standard but should work, we
+ * ignore the RLC... we might complain about it. Other options would
+ * be to send a Release Request, handle the Release Complete..
+ * 1.2) Mark the data structure to be con_local and wait for 2nd
+ *
+ * 2.) Give up on the BSC side
+ * 2.1) Depending on the con type reject the service, or just close it
+ */
+static void bsc_send_con_release(struct bsc_connection *bsc, struct sccp_connections *con)
+{
+ struct msgb *rlsd;
+ /* 1. release the network */
+ rlsd = sccp_create_rlsd(&con->patched_ref, &con->remote_ref,
+ SCCP_RELEASE_CAUSE_END_USER_ORIGINATED);
+ if (!rlsd)
+ LOGP(DNAT, LOGL_ERROR, "Failed to create RLSD message.\n");
+ else {
+ ipaccess_prepend_header(rlsd, IPAC_PROTO_SCCP);
+ queue_for_msc(con->msc_con, rlsd);
+ }
+ con->con_local = 1;
+ con->msc_con = NULL;
+
+ /* 2. release the BSC side */
+ if (con->con_type == NAT_CON_TYPE_LU) {
+ struct msgb *payload, *udt;
+ payload = gsm48_create_loc_upd_rej(GSM48_REJECT_PLMN_NOT_ALLOWED);
+
+ if (payload) {
+ gsm0808_prepend_dtap_header(payload, 0);
+ udt = sccp_create_dt1(&con->real_ref, payload->data, payload->len);
+ if (udt)
+ bsc_write(bsc, udt, IPAC_PROTO_SCCP);
+ else
+ LOGP(DNAT, LOGL_ERROR, "Failed to create DT1\n");
+
+ msgb_free(payload);
+ } else {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate LU Reject.\n");
+ }
+ }
+
+ nat_send_clrc_bsc(con);
+
+ rlsd = sccp_create_rlsd(&con->remote_ref, &con->real_ref,
+ SCCP_RELEASE_CAUSE_END_USER_ORIGINATED);
+ if (!rlsd) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate RLSD for the BSC.\n");
+ sccp_connection_destroy(con);
+ return;
+ }
+
+ con->con_type = NAT_CON_TYPE_LOCAL_REJECT;
+ bsc_write(bsc, rlsd, IPAC_PROTO_SCCP);
+}
+
+static void bsc_send_con_refuse(struct bsc_connection *bsc,
+ struct bsc_nat_parsed *parsed, int con_type)
+{
+ struct msgb *payload;
+ struct msgb *refuse;
+
+ if (con_type == NAT_CON_TYPE_LU)
+ payload = gsm48_create_loc_upd_rej(GSM48_REJECT_PLMN_NOT_ALLOWED);
+ else if (con_type == NAT_CON_TYPE_CM_SERV_REQ)
+ payload = gsm48_create_mm_serv_rej(GSM48_REJECT_PLMN_NOT_ALLOWED);
+ else {
+ LOGP(DNAT, LOGL_ERROR, "Unknown connection type: %d\n", con_type);
+ payload = NULL;
+ }
+
+ /*
+ * Some BSCs do not handle the payload inside a SCCP CREF msg
+ * so we will need to:
+ * 1.) Allocate a local connection and mark it as local..
+ * 2.) queue data for downstream.. and the RLC should delete everything
+ */
+ if (payload) {
+ struct msgb *cc, *udt, *clear, *rlsd;
+ struct sccp_connections *con;
+ con = create_sccp_src_ref(bsc, parsed);
+ if (!con)
+ goto send_refuse;
+
+ /* declare it local and assign a unique remote_ref */
+ con->con_type = NAT_CON_TYPE_LOCAL_REJECT;
+ con->con_local = 1;
+ con->has_remote_ref = 1;
+ con->remote_ref = con->patched_ref;
+
+ /* 1. create a confirmation */
+ cc = sccp_create_cc(&con->remote_ref, &con->real_ref);
+ if (!cc)
+ goto send_refuse;
+
+ /* 2. create the DT1 */
+ gsm0808_prepend_dtap_header(payload, 0);
+ udt = sccp_create_dt1(&con->real_ref, payload->data, payload->len);
+ if (!udt) {
+ msgb_free(cc);
+ goto send_refuse;
+ }
+
+ /* 3. send a Clear Command */
+ clear = nat_creat_clrc(con, 0x20);
+ if (!clear) {
+ msgb_free(cc);
+ msgb_free(udt);
+ goto send_refuse;
+ }
+
+ /* 4. send a RLSD */
+ rlsd = sccp_create_rlsd(&con->remote_ref, &con->real_ref,
+ SCCP_RELEASE_CAUSE_END_USER_ORIGINATED);
+ if (!rlsd) {
+ msgb_free(cc);
+ msgb_free(udt);
+ msgb_free(clear);
+ goto send_refuse;
+ }
+
+ bsc_write(bsc, cc, IPAC_PROTO_SCCP);
+ bsc_write(bsc, udt, IPAC_PROTO_SCCP);
+ bsc_write(bsc, clear, IPAC_PROTO_SCCP);
+ bsc_write(bsc, rlsd, IPAC_PROTO_SCCP);
+ msgb_free(payload);
+ return;
+ }
+
+
+send_refuse:
+ if (payload)
+ msgb_free(payload);
+
+ refuse = sccp_create_refuse(parsed->src_local_ref,
+ SCCP_REFUSAL_SCCP_FAILURE, NULL, 0);
+ if (!refuse) {
+ LOGP(DNAT, LOGL_ERROR,
+ "Creating refuse msg failed for SCCP 0x%x on BSC Nr: %d.\n",
+ sccp_src_ref_to_int(parsed->src_local_ref), bsc->cfg->nr);
+ return;
+ }
+
+ bsc_write(bsc, refuse, IPAC_PROTO_SCCP);
+}
+
+
+static int forward_sccp_to_bts(struct bsc_msc_connection *msc_con, struct msgb *msg)
+{
+ struct sccp_connections *con = NULL;
+ struct bsc_connection *bsc;
+ struct bsc_nat_parsed *parsed;
+ int proto;
+
+ /* filter, drop, patch the message? */
+ parsed = bsc_nat_parse(msg);
+ if (!parsed) {
+ LOGP(DNAT, LOGL_ERROR, "Can not parse msg from BSC.\n");
+ return -1;
+ }
+
+ if (bsc_nat_filter_ipa(DIR_BSC, msg, parsed))
+ goto exit;
+
+ proto = parsed->ipa_proto;
+
+ /* Route and modify the SCCP packet */
+ if (proto == IPAC_PROTO_SCCP) {
+ switch (parsed->sccp_type) {
+ case SCCP_MSG_TYPE_UDT:
+ /* forward UDT messages to every BSC */
+ goto send_to_all;
+ break;
+ case SCCP_MSG_TYPE_RLSD:
+ case SCCP_MSG_TYPE_CREF:
+ case SCCP_MSG_TYPE_DT1:
+ case SCCP_MSG_TYPE_IT:
+ con = patch_sccp_src_ref_to_bsc(msg, parsed, nat);
+ if (parsed->gsm_type == BSS_MAP_MSG_ASSIGMENT_RQST) {
+ counter_inc(nat->stats.sccp.calls);
+
+ if (con) {
+ struct rate_ctr_group *ctrg;
+ ctrg = con->bsc->cfg->stats.ctrg;
+ rate_ctr_inc(&ctrg->ctr[BCFG_CTR_SCCP_CALLS]);
+ if (bsc_mgcp_assign_patch(con, msg) != 0)
+ LOGP(DNAT, LOGL_ERROR, "Failed to assign...\n");
+ } else
+ LOGP(DNAT, LOGL_ERROR, "Assignment command but no BSC.\n");
+ }
+ break;
+ case SCCP_MSG_TYPE_CC:
+ con = patch_sccp_src_ref_to_bsc(msg, parsed, nat);
+ if (!con || update_sccp_src_ref(con, parsed) != 0)
+ goto exit;
+ break;
+ case SCCP_MSG_TYPE_RLC:
+ LOGP(DNAT, LOGL_ERROR, "Unexpected release complete from MSC.\n");
+ goto exit;
+ break;
+ case SCCP_MSG_TYPE_CR:
+ /* MSC never opens a SCCP connection, fall through */
+ default:
+ goto exit;
+ }
+
+ if (!con && parsed->sccp_type == SCCP_MSG_TYPE_RLSD) {
+ LOGP(DNAT, LOGL_NOTICE, "Sending fake RLC on RLSD message to network.\n");
+ /* Exchange src/dest for the reply */
+ nat_send_rlc(msc_con, parsed->dest_local_ref, parsed->src_local_ref);
+ } else if (!con)
+ LOGP(DNAT, LOGL_ERROR, "Unknown connection for msg type: 0x%x from the MSC.\n", parsed->sccp_type);
+ }
+
+ talloc_free(parsed);
+ if (!con)
+ return -1;
+ if (!con->bsc->authenticated) {
+ LOGP(DNAT, LOGL_ERROR, "Selected BSC not authenticated.\n");
+ return -1;
+ }
+
+ bsc_send_data(con->bsc, msg->l2h, msgb_l2len(msg), proto);
+ return 0;
+
+send_to_all:
+ /*
+ * Filter Paging from the network. We do not want to send a PAGING
+ * Command to every BSC in our network. We will analys the PAGING
+ * message and then send it to the authenticated messages...
+ */
+ if (parsed->ipa_proto == IPAC_PROTO_SCCP && parsed->gsm_type == BSS_MAP_MSG_PAGING) {
+ int lac;
+ bsc = bsc_nat_find_bsc(nat, msg, &lac);
+ if (bsc && bsc->cfg->forbid_paging)
+ LOGP(DNAT, LOGL_DEBUG, "Paging forbidden for BTS: %d\n", bsc->cfg->nr);
+ else if (bsc)
+ bsc_send_data(bsc, msg->l2h, msgb_l2len(msg), parsed->ipa_proto);
+ else if (lac != -1)
+ LOGP(DNAT, LOGL_ERROR, "Could not determine BSC for paging on lac: %d/0x%x\n",
+ lac, lac);
+
+ goto exit;
+ }
+ /* currently send this to every BSC connected */
+ llist_for_each_entry(bsc, &nat->bsc_connections, list_entry) {
+ if (!bsc->authenticated)
+ continue;
+
+ bsc_send_data(bsc, msg->l2h, msgb_l2len(msg), parsed->ipa_proto);
+ }
+
+exit:
+ talloc_free(parsed);
+ return 0;
+}
+
+static void msc_connection_was_lost(struct bsc_msc_connection *con)
+{
+ struct bsc_connection *bsc, *tmp;
+
+ LOGP(DMSC, LOGL_ERROR, "Closing all connections downstream.\n");
+ llist_for_each_entry_safe(bsc, tmp, &nat->bsc_connections, list_entry)
+ bsc_close_connection(bsc);
+
+ bsc_mgcp_free_endpoints(nat);
+ bsc_msc_schedule_connect(con);
+}
+
+static void msc_connection_connected(struct bsc_msc_connection *con)
+{
+ counter_inc(nat->stats.msc.reconn);
+}
+
+static void msc_send_reset(struct bsc_msc_connection *msc_con)
+{
+ static const uint8_t reset[] = {
+ 0x00, 0x12, 0xfd,
+ 0x09, 0x00, 0x03, 0x05, 0x07, 0x02, 0x42, 0xfe,
+ 0x02, 0x42, 0xfe, 0x06, 0x00, 0x04, 0x30, 0x04,
+ 0x01, 0x20
+ };
+
+ struct msgb *msg;
+
+ msg = msgb_alloc_headroom(4096, 128, "08.08 reset");
+ if (!msg) {
+ LOGP(DMSC, LOGL_ERROR, "Failed to allocate reset msg.\n");
+ return;
+ }
+
+ msg->l2h = msgb_put(msg, sizeof(reset));
+ memcpy(msg->l2h, reset, msgb_l2len(msg));
+
+ queue_for_msc(msc_con, msg);
+
+ LOGP(DMSC, LOGL_NOTICE, "Scheduled GSM0808 reset msg for the MSC.\n");
+}
+
+static int ipaccess_msc_read_cb(struct bsc_fd *bfd)
+{
+ int error;
+ struct bsc_msc_connection *msc_con;
+ struct msgb *msg = ipaccess_read_msg(bfd, &error);
+ struct ipaccess_head *hh;
+
+ msc_con = (struct bsc_msc_connection *) bfd->data;
+
+ if (!msg) {
+ if (error == 0)
+ LOGP(DNAT, LOGL_FATAL, "The connection the MSC was lost, exiting\n");
+ else
+ LOGP(DNAT, LOGL_ERROR, "Failed to parse ip access message: %d\n", error);
+
+ bsc_msc_lost(msc_con);
+ return -1;
+ }
+
+ LOGP(DNAT, LOGL_DEBUG, "MSG from MSC: %s proto: %d\n", hexdump(msg->data, msg->len), msg->l2h[0]);
+
+ /* handle base message handling */
+ hh = (struct ipaccess_head *) msg->data;
+ ipaccess_rcvmsg_base(msg, bfd);
+
+ /* initialize the networking. This includes sending a GSM08.08 message */
+ if (hh->proto == IPAC_PROTO_IPACCESS) {
+ if (msg->l2h[0] == IPAC_MSGT_ID_ACK)
+ initialize_msc_if_needed(msc_con);
+ else if (msg->l2h[0] == IPAC_MSGT_ID_GET)
+ send_id_get_response(msc_con);
+ } else if (hh->proto == IPAC_PROTO_SCCP)
+ forward_sccp_to_bts(msc_con, msg);
+
+ msgb_free(msg);
+ return 0;
+}
+
+static int ipaccess_msc_write_cb(struct bsc_fd *bfd, struct msgb *msg)
+{
+ int rc;
+ rc = write(bfd->fd, msg->data, msg->len);
+
+ if (rc != msg->len) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to write MSG to MSC.\n");
+ return -1;
+ }
+
+ return rc;
+}
+
+/*
+ * Below is the handling of messages coming
+ * from the BSC and need to be forwarded to
+ * a real BSC.
+ */
+
+/*
+ * Remove the connection from the connections list,
+ * remove it from the patching of SCCP header lists
+ * as well. Maybe in the future even close connection..
+ */
+void bsc_close_connection(struct bsc_connection *connection)
+{
+ struct sccp_connections *sccp_patch, *tmp;
+ struct rate_ctr *ctr = NULL;
+
+ /* stop the timeout timer */
+ bsc_del_timer(&connection->id_timeout);
+ bsc_del_timer(&connection->ping_timeout);
+ bsc_del_timer(&connection->pong_timeout);
+
+ if (connection->cfg)
+ ctr = &connection->cfg->stats.ctrg->ctr[BCFG_CTR_DROPPED_SCCP];
+
+ /* remove all SCCP connections */
+ llist_for_each_entry_safe(sccp_patch, tmp, &nat->sccp_connections, list_entry) {
+ if (sccp_patch->bsc != connection)
+ continue;
+
+ if (ctr)
+ rate_ctr_inc(ctr);
+ if (sccp_patch->has_remote_ref && !sccp_patch->con_local)
+ nat_send_rlsd_msc(sccp_patch);
+ sccp_connection_destroy(sccp_patch);
+ }
+
+ /* close endpoints allocated by this BSC */
+ bsc_mgcp_clear_endpoints_for(connection);
+
+ bsc_unregister_fd(&connection->write_queue.bfd);
+ close(connection->write_queue.bfd.fd);
+ write_queue_clear(&connection->write_queue);
+ llist_del(&connection->list_entry);
+
+ talloc_free(connection);
+}
+
+static void ipaccess_close_bsc(void *data)
+{
+ struct sockaddr_in sock;
+ socklen_t len = sizeof(sock);
+ struct bsc_connection *conn = data;
+
+
+ getpeername(conn->write_queue.bfd.fd, (struct sockaddr *) &sock, &len);
+ LOGP(DNAT, LOGL_ERROR, "BSC on %s didn't respond to identity request. Closing.\n",
+ inet_ntoa(sock.sin_addr));
+ bsc_close_connection(conn);
+}
+
+static void ipaccess_auth_bsc(struct tlv_parsed *tvp, struct bsc_connection *bsc)
+{
+ struct bsc_config *conf;
+ const char *token = (const char *) TLVP_VAL(tvp, IPAC_IDTAG_UNITNAME);
+ const int len = TLVP_LEN(tvp, IPAC_IDTAG_UNITNAME);
+
+ if (bsc->cfg) {
+ LOGP(DNAT, LOGL_ERROR, "Reauth on fd %d bsc nr %d\n",
+ bsc->write_queue.bfd.fd, bsc->cfg->nr);
+ return;
+ }
+
+ llist_for_each_entry(conf, &bsc->nat->bsc_configs, entry) {
+ if (strncmp(conf->token, token, len) == 0) {
+ rate_ctr_inc(&conf->stats.ctrg->ctr[BCFG_CTR_NET_RECONN]);
+ bsc->authenticated = 1;
+ bsc->cfg = conf;
+ bsc_del_timer(&bsc->id_timeout);
+ LOGP(DNAT, LOGL_NOTICE, "Authenticated bsc nr: %d on fd %d\n",
+ conf->nr, bsc->write_queue.bfd.fd);
+ start_ping_pong(bsc);
+ return;
+ }
+ }
+
+ LOGP(DNAT, LOGL_ERROR, "No bsc found for token %s on fd: %d.\n", token,
+ bsc->write_queue.bfd.fd);
+}
+
+static void handle_con_stats(struct sccp_connections *con)
+{
+ struct rate_ctr_group *ctrg;
+ int id = bsc_conn_type_to_ctr(con);
+
+ if (id == -1)
+ return;
+
+ if (!con->bsc || !con->bsc->cfg)
+ return;
+
+ ctrg = con->bsc->cfg->stats.ctrg;
+ rate_ctr_inc(&ctrg->ctr[id]);
+}
+
+static int forward_sccp_to_msc(struct bsc_connection *bsc, struct msgb *msg)
+{
+ int con_filter = 0;
+ char *imsi = NULL;
+ struct bsc_msc_connection *con_msc = NULL;
+ struct bsc_connection *con_bsc = NULL;
+ int con_type;
+ struct bsc_nat_parsed *parsed;
+
+ /* Parse and filter messages */
+ parsed = bsc_nat_parse(msg);
+ if (!parsed) {
+ LOGP(DNAT, LOGL_ERROR, "Can not parse msg from BSC.\n");
+ msgb_free(msg);
+ return -1;
+ }
+
+ if (bsc_nat_filter_ipa(DIR_MSC, msg, parsed))
+ goto exit;
+
+ /*
+ * check authentication after filtering to not reject auth
+ * responses coming from the BSC. We have to make sure that
+ * nothing from the exit path will forward things to the MSC
+ */
+ if (!bsc->authenticated) {
+ LOGP(DNAT, LOGL_ERROR, "BSC is not authenticated.\n");
+ msgb_free(msg);
+ return -1;
+ }
+
+
+ /* modify the SCCP entries */
+ if (parsed->ipa_proto == IPAC_PROTO_SCCP) {
+ int filter;
+ struct sccp_connections *con;
+ switch (parsed->sccp_type) {
+ case SCCP_MSG_TYPE_CR:
+ filter = bsc_nat_filter_sccp_cr(bsc, msg, parsed, &con_type, &imsi);
+ if (filter < 0) {
+ bsc_stat_reject(filter, bsc, 0);
+ goto exit3;
+ }
+
+ if (!create_sccp_src_ref(bsc, parsed))
+ goto exit2;
+ con = patch_sccp_src_ref_to_msc(msg, parsed, bsc);
+ con->msc_con = bsc->nat->msc_con;
+ con_msc = con->msc_con;
+ con->con_type = con_type;
+ con->imsi_checked = filter;
+ if (imsi)
+ con->imsi = talloc_steal(con, imsi);
+ imsi = NULL;
+ con_bsc = con->bsc;
+ handle_con_stats(con);
+ break;
+ case SCCP_MSG_TYPE_RLSD:
+ case SCCP_MSG_TYPE_CREF:
+ case SCCP_MSG_TYPE_DT1:
+ case SCCP_MSG_TYPE_CC:
+ case SCCP_MSG_TYPE_IT:
+ con = patch_sccp_src_ref_to_msc(msg, parsed, bsc);
+ if (con) {
+ /* only filter non local connections */
+ if (!con->con_local) {
+ filter = bsc_nat_filter_dt(bsc, msg, con, parsed);
+ if (filter < 0) {
+ bsc_stat_reject(filter, bsc, 1);
+ bsc_send_con_release(bsc, con);
+ con = NULL;
+ goto exit2;
+ }
+
+ /* hand data to a side channel */
+ if (bsc_check_ussd(con, parsed, msg) == 1)
+ con->con_local = 2;
+
+ /*
+ * Optionally rewrite setup message. This can
+ * replace the msg and the parsed structure becomes
+ * invalid.
+ */
+ msg = bsc_nat_rewrite_setup(bsc->nat, msg, parsed, con->imsi);
+ talloc_free(parsed);
+ parsed = NULL;
+ }
+
+ con_bsc = con->bsc;
+ con_msc = con->msc_con;
+ con_filter = con->con_local;
+ }
+
+ break;
+ case SCCP_MSG_TYPE_RLC:
+ con = patch_sccp_src_ref_to_msc(msg, parsed, bsc);
+ if (con) {
+ con_bsc = con->bsc;
+ con_msc = con->msc_con;
+ con_filter = con->con_local;
+ }
+ remove_sccp_src_ref(bsc, msg, parsed);
+ break;
+ case SCCP_MSG_TYPE_UDT:
+ /* simply forward everything */
+ con = NULL;
+ break;
+ default:
+ LOGP(DNAT, LOGL_ERROR, "Not forwarding to msc sccp type: 0x%x\n", parsed->sccp_type);
+ con = NULL;
+ goto exit2;
+ break;
+ }
+ } else if (parsed->ipa_proto == IPAC_PROTO_MGCP_OLD) {
+ bsc_mgcp_forward(bsc, msg);
+ goto exit2;
+ } else {
+ LOGP(DNAT, LOGL_ERROR, "Not forwarding unknown stream id: 0x%x\n", parsed->ipa_proto);
+ goto exit2;
+ }
+
+ if (con_msc && con_bsc != bsc) {
+ LOGP(DNAT, LOGL_ERROR, "The connection belongs to a different BTS: input: %d con: %d\n",
+ bsc->cfg->nr, con_bsc->cfg->nr);
+ goto exit2;
+ }
+
+ /* do not forward messages to the MSC */
+ if (con_filter)
+ goto exit2;
+
+ if (!con_msc) {
+ LOGP(DNAT, LOGL_ERROR, "Not forwarding data bsc_nr: %d ipa: %d type: 0x%x\n",
+ bsc->cfg->nr,
+ parsed ? parsed->ipa_proto : -1,
+ parsed ? parsed->sccp_type : -1);
+ goto exit2;
+ }
+
+ /* send the non-filtered but maybe modified msg */
+ queue_for_msc(con_msc, msg);
+ if (parsed)
+ talloc_free(parsed);
+ return 0;
+
+exit:
+ /* if we filter out the reset send an ack to the BSC */
+ if (parsed->bssap == 0 && parsed->gsm_type == BSS_MAP_MSG_RESET) {
+ send_reset_ack(bsc);
+ send_reset_ack(bsc);
+ } else if (parsed->ipa_proto == IPAC_PROTO_IPACCESS) {
+ /* do we know who is handling this? */
+ if (msg->l2h[0] == IPAC_MSGT_ID_RESP) {
+ struct tlv_parsed tvp;
+ ipaccess_idtag_parse(&tvp,
+ (unsigned char *) msg->l2h + 2,
+ msgb_l2len(msg) - 2);
+ if (TLVP_PRESENT(&tvp, IPAC_IDTAG_UNITNAME))
+ ipaccess_auth_bsc(&tvp, bsc);
+ }
+
+ goto exit2;
+ }
+
+exit2:
+ if (imsi)
+ talloc_free(imsi);
+ talloc_free(parsed);
+ msgb_free(msg);
+ return -1;
+
+exit3:
+ /* send a SCCP Connection Refused */
+ if (imsi)
+ talloc_free(imsi);
+ bsc_send_con_refuse(bsc, parsed, con_type);
+ talloc_free(parsed);
+ msgb_free(msg);
+ return -1;
+}
+
+static int ipaccess_bsc_read_cb(struct bsc_fd *bfd)
+{
+ int error;
+ struct bsc_connection *bsc = bfd->data;
+ struct msgb *msg = ipaccess_read_msg(bfd, &error);
+ struct ipaccess_head *hh;
+
+ if (!msg) {
+ if (error == 0)
+ LOGP(DNAT, LOGL_ERROR,
+ "The connection to the BSC Nr: %d was lost. Cleaning it\n",
+ bsc->cfg ? bsc->cfg->nr : -1);
+ else
+ LOGP(DNAT, LOGL_ERROR,
+ "Stream error on BSC Nr: %d. Failed to parse ip access message: %d\n",
+ bsc->cfg ? bsc->cfg->nr : -1, error);
+
+ bsc_close_connection(bsc);
+ return -1;
+ }
+
+
+ LOGP(DNAT, LOGL_DEBUG, "MSG from BSC: %s proto: %d\n", hexdump(msg->data, msg->len), msg->l2h[0]);
+
+ /* Handle messages from the BSC */
+ hh = (struct ipaccess_head *) msg->data;
+
+ /* stop the pong timeout */
+ if (hh->proto == IPAC_PROTO_IPACCESS) {
+ if (msg->l2h[0] == IPAC_MSGT_PONG) {
+ bsc_del_timer(&bsc->pong_timeout);
+ msgb_free(msg);
+ return 0;
+ } else if (msg->l2h[0] == IPAC_MSGT_PING) {
+ send_pong(bsc);
+ msgb_free(msg);
+ return 0;
+ }
+ }
+
+ /* FIXME: Currently no PONG is sent to the BSC */
+ /* FIXME: Currently no ID ACK is sent to the BSC */
+ forward_sccp_to_msc(bsc, msg);
+
+ return 0;
+}
+
+static int ipaccess_listen_bsc_cb(struct bsc_fd *bfd, unsigned int what)
+{
+ struct bsc_connection *bsc;
+ int fd, rc, on;
+ struct sockaddr_in sa;
+ socklen_t sa_len = sizeof(sa);
+
+ if (!(what & BSC_FD_READ))
+ return 0;
+
+ fd = accept(bfd->fd, (struct sockaddr *) &sa, &sa_len);
+ if (fd < 0) {
+ perror("accept");
+ return fd;
+ }
+
+ /* count the reconnect */
+ counter_inc(nat->stats.bsc.reconn);
+
+ /*
+ * if we are not connected to a msc... just close the socket
+ */
+ if (!bsc_nat_msc_is_connected(nat)) {
+ LOGP(DNAT, LOGL_NOTICE, "Disconnecting BSC due lack of MSC connection.\n");
+ close(fd);
+ return 0;
+ }
+
+ on = 1;
+ rc = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
+ if (rc != 0)
+ LOGP(DNAT, LOGL_ERROR, "Failed to set TCP_NODELAY: %s\n", strerror(errno));
+
+ rc = setsockopt(fd, IPPROTO_IP, IP_TOS,
+ &nat->bsc_ip_dscp, sizeof(nat->bsc_ip_dscp));
+ if (rc != 0)
+ LOGP(DNAT, LOGL_ERROR, "Failed to set IP_TOS: %s\n", strerror(errno));
+
+ /* todo... do something with the connection */
+ /* todo... use GNUtls to see if we want to trust this as a BTS */
+
+ /*
+ *
+ */
+ bsc = bsc_connection_alloc(nat);
+ if (!bsc) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate BSC struct.\n");
+ close(fd);
+ return -1;
+ }
+
+ bsc->write_queue.bfd.data = bsc;
+ bsc->write_queue.bfd.fd = fd;
+ bsc->write_queue.read_cb = ipaccess_bsc_read_cb;
+ bsc->write_queue.write_cb = bsc_write_cb;
+ bsc->write_queue.bfd.when = BSC_FD_READ;
+ if (bsc_register_fd(&bsc->write_queue.bfd) < 0) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to register BSC fd.\n");
+ close(fd);
+ talloc_free(bsc);
+ return -2;
+ }
+
+ LOGP(DNAT, LOGL_NOTICE, "BSC connection on %d with IP: %s\n",
+ fd, inet_ntoa(sa.sin_addr));
+ llist_add(&bsc->list_entry, &nat->bsc_connections);
+ send_id_ack(bsc);
+ send_id_req(bsc);
+ send_mgcp_reset(bsc);
+
+ /*
+ * start the hangup timer
+ */
+ bsc->id_timeout.data = bsc;
+ bsc->id_timeout.cb = ipaccess_close_bsc;
+ bsc_schedule_timer(&bsc->id_timeout, nat->auth_timeout, 0);
+ return 0;
+}
+
+static void print_usage()
+{
+ printf("Usage: bsc_nat\n");
+}
+
+static void print_help()
+{
+ printf(" Some useful help...\n");
+ printf(" -h --help this text\n");
+ printf(" -d option --debug=DRLL:DCC:DMM:DRR:DRSL:DNM enable debugging\n");
+ printf(" -D --daemonize Fork the process into a background daemon\n");
+ printf(" -s --disable-color\n");
+ printf(" -c --config-file filename The config file to use.\n");
+ printf(" -m --msc=IP. The address of the MSC.\n");
+ printf(" -l --local=IP. The local address of this BSC.\n");
+}
+
+static void handle_options(int argc, char **argv)
+{
+ while (1) {
+ int option_index = 0, c;
+ static struct option long_options[] = {
+ {"help", 0, 0, 'h'},
+ {"debug", 1, 0, 'd'},
+ {"config-file", 1, 0, 'c'},
+ {"disable-color", 0, 0, 's'},
+ {"timestamp", 0, 0, 'T'},
+ {"msc", 1, 0, 'm'},
+ {"local", 1, 0, 'l'},
+ {0, 0, 0, 0}
+ };
+
+ c = getopt_long(argc, argv, "hd:sTPc:m:l:",
+ long_options, &option_index);
+ if (c == -1)
+ break;
+
+ switch (c) {
+ case 'h':
+ print_usage();
+ print_help();
+ exit(0);
+ case 's':
+ log_set_use_color(stderr_target, 0);
+ break;
+ case 'd':
+ log_parse_category_mask(stderr_target, optarg);
+ break;
+ case 'c':
+ config_file = strdup(optarg);
+ break;
+ case 'T':
+ log_set_print_timestamp(stderr_target, 1);
+ break;
+ case 'm':
+ msc_ip = optarg;
+ break;
+ case 'l':
+ inet_aton(optarg, &local_addr);
+ break;
+ default:
+ /* ignore */
+ break;
+ }
+ }
+}
+
+static void signal_handler(int signal)
+{
+ switch (signal) {
+ case SIGABRT:
+ /* in case of abort, we want to obtain a talloc report
+ * and then return to the caller, who will abort the process */
+ case SIGUSR1:
+ talloc_report_full(tall_bsc_ctx, stderr);
+ break;
+ default:
+ break;
+ }
+}
+
+static void sccp_close_unconfirmed(void *_data)
+{
+ struct sccp_connections *conn, *tmp1;
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+
+ llist_for_each_entry_safe(conn, tmp1, &nat->sccp_connections, list_entry) {
+ if (conn->has_remote_ref)
+ continue;
+
+ int diff = (now.tv_sec - conn->creation_time.tv_sec) / 60;
+ if (diff < SCCP_CLOSE_TIME_TIMEOUT)
+ continue;
+
+ LOGP(DNAT, LOGL_ERROR, "SCCP connection 0x%x/0x%x was never confirmed.\n",
+ sccp_src_ref_to_int(&conn->real_ref),
+ sccp_src_ref_to_int(&conn->patched_ref));
+ sccp_connection_destroy(conn);
+ }
+
+ bsc_schedule_timer(&sccp_close, SCCP_CLOSE_TIME, 0);
+}
+
+extern void *tall_msgb_ctx;
+extern void *tall_ctr_ctx;
+static void talloc_init_ctx()
+{
+ tall_bsc_ctx = talloc_named_const(NULL, 0, "nat");
+ tall_msgb_ctx = talloc_named_const(tall_bsc_ctx, 0, "msgb");
+ tall_ctr_ctx = talloc_named_const(tall_bsc_ctx, 0, "counter");
+}
+
+extern enum node_type bsc_vty_go_parent(struct vty *vty);
+
+static struct vty_app_info vty_info = {
+ .name = "OsmoBSCNAT",
+ .version = PACKAGE_VERSION,
+ .go_parent_cb = bsc_vty_go_parent,
+ .is_config_node = bsc_vty_is_config_node,
+};
+
+int main(int argc, char **argv)
+{
+ int rc;
+
+ talloc_init_ctx();
+
+ log_init(&log_info);
+ stderr_target = log_target_create_stderr();
+ log_add_target(stderr_target);
+ log_set_all_filter(stderr_target, 1);
+
+ nat = bsc_nat_alloc();
+ if (!nat) {
+ fprintf(stderr, "Failed to allocate the BSC nat.\n");
+ return -4;
+ }
+
+ nat->mgcp_cfg = mgcp_config_alloc();
+ if (!nat->mgcp_cfg) {
+ fprintf(stderr, "Failed to allocate MGCP cfg.\n");
+ return -5;
+ }
+
+ vty_info.copyright = openbsc_copyright;
+ vty_init(&vty_info);
+ logging_vty_add_cmds();
+ bsc_nat_vty_init(nat);
+
+
+ /* parse options */
+ local_addr.s_addr = INADDR_ANY;
+ handle_options(argc, argv);
+
+ rate_ctr_init(tall_bsc_ctx);
+
+ /* init vty and parse */
+ telnet_init(tall_bsc_ctx, NULL, 4244);
+ if (mgcp_parse_config(config_file, nat->mgcp_cfg) < 0) {
+ fprintf(stderr, "Failed to parse the config file: '%s'\n", config_file);
+ return -3;
+ }
+
+ /* over rule the VTY config */
+ if (msc_ip)
+ bsc_nat_set_msc_ip(nat, msc_ip);
+
+ /* seed the PRNG */
+ srand(time(NULL));
+
+ /*
+ * Setup the MGCP code..
+ */
+ if (bsc_mgcp_nat_init(nat) != 0)
+ return -4;
+
+ /* connect to the MSC */
+ nat->msc_con = bsc_msc_create(nat->msc_ip, nat->msc_port, 0);
+ if (!nat->msc_con) {
+ fprintf(stderr, "Creating a bsc_msc_connection failed.\n");
+ exit(1);
+ }
+
+ nat->msc_con->connection_loss = msc_connection_was_lost;
+ nat->msc_con->connected = msc_connection_connected;
+ nat->msc_con->write_queue.read_cb = ipaccess_msc_read_cb;
+ nat->msc_con->write_queue.write_cb = ipaccess_msc_write_cb;;
+ nat->msc_con->write_queue.bfd.data = nat->msc_con;
+ bsc_msc_connect(nat->msc_con);
+
+ /* wait for the BSC */
+ rc = make_sock(&bsc_listen, IPPROTO_TCP, ntohl(local_addr.s_addr),
+ 5000, ipaccess_listen_bsc_cb);
+ if (rc != 0) {
+ fprintf(stderr, "Failed to listen for BSC.\n");
+ exit(1);
+ }
+
+ rc = bsc_ussd_init(nat);
+ if (rc != 0) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to bind the USSD socket.\n");
+ exit(1);
+ }
+
+ signal(SIGABRT, &signal_handler);
+ signal(SIGUSR1, &signal_handler);
+ signal(SIGPIPE, SIG_IGN);
+
+ if (daemonize) {
+ rc = osmo_daemonize();
+ if (rc < 0) {
+ perror("Error during daemonize");
+ exit(1);
+ }
+ }
+
+ /* recycle timer */
+ sccp_set_log_area(DSCCP);
+ sccp_close.cb = sccp_close_unconfirmed;
+ sccp_close.data = NULL;
+ bsc_schedule_timer(&sccp_close, SCCP_CLOSE_TIME, 0);
+
+ while (1) {
+ bsc_select_main(0);
+ }
+
+ return 0;
+}
+
+/* Close all connections handed out to the USSD module */
+int bsc_close_ussd_connections(struct bsc_nat *nat)
+{
+ struct sccp_connections *con;
+ llist_for_each_entry(con, &nat->sccp_connections, list_entry) {
+ if (con->con_local != 2)
+ continue;
+ if (!con->bsc)
+ continue;
+
+ nat_send_clrc_bsc(con);
+ nat_send_rlsd_bsc(con);
+ }
+
+ return 0;
+}
diff --git a/openbsc/src/osmo-bsc_nat/bsc_nat_utils.c b/openbsc/src/osmo-bsc_nat/bsc_nat_utils.c
new file mode 100644
index 000000000..cd294ccfb
--- /dev/null
+++ b/openbsc/src/osmo-bsc_nat/bsc_nat_utils.c
@@ -0,0 +1,893 @@
+
+/* BSC Multiplexer/NAT Utilities */
+
+/*
+ * (C) 2010 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * (C) 2010 by On-Waves
+ * 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 <openbsc/bsc_nat.h>
+#include <openbsc/bsc_nat_sccp.h>
+#include <openbsc/bsc_msc.h>
+#include <openbsc/gsm_data.h>
+#include <openbsc/debug.h>
+#include <openbsc/ipaccess.h>
+#include <openbsc/vty.h>
+
+#include <osmocore/linuxlist.h>
+#include <osmocore/talloc.h>
+#include <osmocore/gsm0808.h>
+
+#include <osmocore/protocol/gsm_08_08.h>
+
+#include <osmocom/sccp/sccp.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+
+static const struct rate_ctr_desc bsc_cfg_ctr_description[] = {
+ [BCFG_CTR_SCCP_CONN] = { "sccp.conn", "SCCP Connections "},
+ [BCFG_CTR_SCCP_CALLS] = { "sccp.calls", "SCCP Assignment Commands "},
+ [BCFG_CTR_NET_RECONN] = { "net.reconnects", "Network reconnects "},
+ [BCFG_CTR_DROPPED_SCCP] = { "dropped.sccp", "Dropped SCCP connections."},
+ [BCFG_CTR_DROPPED_CALLS] = { "dropped.calls", "Dropped active calls. "},
+ [BCFG_CTR_REJECTED_CR] = { "rejected.cr", "Rejected CR due filter "},
+ [BCFG_CTR_REJECTED_MSG] = { "rejected.msg", "Rejected MSG due filter "},
+ [BCFG_CTR_ILL_PACKET] = { "rejected.ill", "Rejected due parse error "},
+ [BCFG_CTR_CON_TYPE_LU] = { "conn.lu", "Conn Location Update "},
+ [BCFG_CTR_CON_CMSERV_RQ] = { "conn.rq", "Conn CM Service Req "},
+ [BCFG_CTR_CON_PAG_RESP] = { "conn.pag", "Conn Paging Response "},
+ [BCFG_CTR_CON_SSA] = { "conn.ssa", "Conn USSD "},
+ [BCFG_CTR_CON_OTHER] = { "conn.other", "Conn Other "},
+};
+
+static const struct rate_ctr_group_desc bsc_cfg_ctrg_desc = {
+ .group_name_prefix = "nat.bsc",
+ .group_description = "NAT BSC Statistics",
+ .num_ctr = ARRAY_SIZE(bsc_cfg_ctr_description),
+ .ctr_desc = bsc_cfg_ctr_description,
+};
+
+static const struct rate_ctr_desc acc_list_ctr_description[] = {
+ [ACC_LIST_BSC_FILTER] = { "access-list.bsc-filter", "Rejected by rule for BSC"},
+ [ACC_LIST_NAT_FILTER] = { "access-list.nat-filter", "Rejected by rule for NAT"},
+};
+
+static const struct rate_ctr_group_desc bsc_cfg_acc_list_desc = {
+ .group_name_prefix = "nat.filter",
+ .group_description = "NAT Access-List Statistics",
+ .num_ctr = ARRAY_SIZE(acc_list_ctr_description),
+ .ctr_desc = acc_list_ctr_description,
+};
+
+struct bsc_nat *bsc_nat_alloc(void)
+{
+ struct bsc_nat *nat = talloc_zero(tall_bsc_ctx, struct bsc_nat);
+ if (!nat)
+ return NULL;
+
+ INIT_LLIST_HEAD(&nat->sccp_connections);
+ INIT_LLIST_HEAD(&nat->bsc_connections);
+ INIT_LLIST_HEAD(&nat->bsc_configs);
+ INIT_LLIST_HEAD(&nat->access_lists);
+
+ nat->stats.sccp.conn = counter_alloc("nat.sccp.conn");
+ nat->stats.sccp.calls = counter_alloc("nat.sccp.calls");
+ nat->stats.bsc.reconn = counter_alloc("nat.bsc.conn");
+ nat->stats.bsc.auth_fail = counter_alloc("nat.bsc.auth_fail");
+ nat->stats.msc.reconn = counter_alloc("nat.msc.conn");
+ nat->stats.ussd.reconn = counter_alloc("nat.ussd.conn");
+ nat->msc_ip = talloc_strdup(nat, "127.0.0.1");
+ nat->msc_port = 5000;
+ nat->auth_timeout = 2;
+ nat->ping_timeout = 20;
+ nat->pong_timeout = 5;
+ return nat;
+}
+
+void bsc_nat_set_msc_ip(struct bsc_nat *nat, const char *ip)
+{
+ bsc_replace_string(nat, &nat->msc_ip, ip);
+}
+
+struct bsc_connection *bsc_connection_alloc(struct bsc_nat *nat)
+{
+ struct bsc_connection *con = talloc_zero(nat, struct bsc_connection);
+ if (!con)
+ return NULL;
+
+ con->nat = nat;
+ write_queue_init(&con->write_queue, 100);
+ return con;
+}
+
+struct bsc_config *bsc_config_alloc(struct bsc_nat *nat, const char *token)
+{
+ struct bsc_config *conf = talloc_zero(nat, struct bsc_config);
+ if (!conf)
+ return NULL;
+
+ conf->token = talloc_strdup(conf, token);
+ conf->nr = nat->num_bsc;
+ conf->nat = nat;
+ conf->max_endpoints = 32;
+
+ INIT_LLIST_HEAD(&conf->lac_list);
+
+ llist_add_tail(&conf->entry, &nat->bsc_configs);
+ ++nat->num_bsc;
+
+ conf->stats.ctrg = rate_ctr_group_alloc(conf, &bsc_cfg_ctrg_desc, conf->nr);
+ if (!conf->stats.ctrg) {
+ talloc_free(conf);
+ return NULL;
+ }
+
+ return conf;
+}
+
+void bsc_config_free(struct bsc_config *cfg)
+{
+ rate_ctr_group_free(cfg->stats.ctrg);
+}
+
+void bsc_config_add_lac(struct bsc_config *cfg, int _lac)
+{
+ struct bsc_lac_entry *lac;
+
+ llist_for_each_entry(lac, &cfg->lac_list, entry)
+ if (lac->lac == _lac)
+ return;
+
+ lac = talloc_zero(cfg, struct bsc_lac_entry);
+ if (!lac) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate.\n");
+ return;
+ }
+
+ lac->lac = _lac;
+ llist_add_tail(&lac->entry, &cfg->lac_list);
+}
+
+void bsc_config_del_lac(struct bsc_config *cfg, int _lac)
+{
+ struct bsc_lac_entry *lac;
+
+ llist_for_each_entry(lac, &cfg->lac_list, entry)
+ if (lac->lac == _lac) {
+ llist_del(&lac->entry);
+ talloc_free(lac);
+ return;
+ }
+}
+
+int bsc_config_handles_lac(struct bsc_config *cfg, int lac_nr)
+{
+ struct bsc_lac_entry *entry;
+
+ llist_for_each_entry(entry, &cfg->lac_list, entry)
+ if (entry->lac == lac_nr)
+ return 1;
+
+ return 0;
+}
+
+void sccp_connection_destroy(struct sccp_connections *conn)
+{
+ LOGP(DNAT, LOGL_DEBUG, "Destroy 0x%x <-> 0x%x mapping for con %p\n",
+ sccp_src_ref_to_int(&conn->real_ref),
+ sccp_src_ref_to_int(&conn->patched_ref), conn->bsc);
+ bsc_mgcp_dlcx(conn);
+ llist_del(&conn->list_entry);
+ talloc_free(conn);
+}
+
+struct bsc_connection *bsc_nat_find_bsc(struct bsc_nat *nat, struct msgb *msg, int *lac_out)
+{
+ struct bsc_connection *bsc;
+ int data_length;
+ const uint8_t *data;
+ struct tlv_parsed tp;
+ int i = 0;
+
+ *lac_out = -1;
+
+ if (!msg->l3h || msgb_l3len(msg) < 3) {
+ LOGP(DNAT, LOGL_ERROR, "Paging message is too short.\n");
+ return NULL;
+ }
+
+ tlv_parse(&tp, gsm0808_att_tlvdef(), msg->l3h + 3, msgb_l3len(msg) - 3, 0, 0);
+ if (!TLVP_PRESENT(&tp, GSM0808_IE_CELL_IDENTIFIER_LIST)) {
+ LOGP(DNAT, LOGL_ERROR, "No CellIdentifier List inside paging msg.\n");
+ return NULL;
+ }
+
+ data_length = TLVP_LEN(&tp, GSM0808_IE_CELL_IDENTIFIER_LIST);
+ data = TLVP_VAL(&tp, GSM0808_IE_CELL_IDENTIFIER_LIST);
+
+ /* No need to try a different BSS */
+ if (data[0] == CELL_IDENT_BSS) {
+ return NULL;
+ } else if (data[0] != CELL_IDENT_LAC) {
+ LOGP(DNAT, LOGL_ERROR, "Unhandled cell ident discrminator: %d\n", data[0]);
+ return NULL;
+ }
+
+ /* Currently we only handle one BSC */
+ for (i = 1; i < data_length - 1; i += 2) {
+ unsigned int _lac = ntohs(*(unsigned int *) &data[i]);
+ *lac_out = _lac;
+ llist_for_each_entry(bsc, &nat->bsc_connections, list_entry) {
+ if (!bsc->cfg)
+ continue;
+ if (!bsc->authenticated)
+ continue;
+ if (!bsc_config_handles_lac(bsc->cfg, _lac))
+ continue;
+
+ return bsc;
+ }
+ }
+
+ return NULL;
+}
+
+int bsc_write_mgcp(struct bsc_connection *bsc, const uint8_t *data, unsigned int length)
+{
+ struct msgb *msg;
+
+ if (length > 4096 - 128) {
+ LOGP(DINP, LOGL_ERROR, "Can not send message of that size.\n");
+ return -1;
+ }
+
+ msg = msgb_alloc_headroom(4096, 128, "to-bsc");
+ if (!msg) {
+ LOGP(DINP, LOGL_ERROR, "Failed to allocate memory for BSC msg.\n");
+ return -1;
+ }
+
+ /* copy the data */
+ msg->l3h = msgb_put(msg, length);
+ memcpy(msg->l3h, data, length);
+
+ return bsc_write(bsc, msg, IPAC_PROTO_MGCP_OLD);
+}
+
+int bsc_write(struct bsc_connection *bsc, struct msgb *msg, int proto)
+{
+ return bsc_do_write(&bsc->write_queue, msg, proto);
+}
+
+int bsc_do_write(struct write_queue *queue, struct msgb *msg, int proto)
+{
+ /* prepend the header */
+ ipaccess_prepend_header(msg, proto);
+ return bsc_write_msg(queue, msg);
+}
+
+int bsc_write_msg(struct write_queue *queue, struct msgb *msg)
+{
+ if (write_queue_enqueue(queue, msg) != 0) {
+ LOGP(DINP, LOGL_ERROR, "Failed to enqueue the write.\n");
+ msgb_free(msg);
+ return -1;
+ }
+
+ return 0;
+}
+
+int bsc_nat_lst_check_allow(struct bsc_nat_acc_lst *lst, const char *mi_string)
+{
+ struct bsc_nat_acc_lst_entry *entry;
+
+ llist_for_each_entry(entry, &lst->fltr_list, list) {
+ if (!entry->imsi_allow)
+ continue;
+ if (regexec(&entry->imsi_allow_re, mi_string, 0, NULL, 0) == 0)
+ return 0;
+ }
+
+ return 1;
+}
+
+static int lst_check_deny(struct bsc_nat_acc_lst *lst, const char *mi_string)
+{
+ struct bsc_nat_acc_lst_entry *entry;
+
+ llist_for_each_entry(entry, &lst->fltr_list, list) {
+ if (!entry->imsi_deny)
+ continue;
+ if (regexec(&entry->imsi_deny_re, mi_string, 0, NULL, 0) == 0)
+ return 0;
+ }
+
+ return 1;
+}
+
+/* apply white/black list */
+static int auth_imsi(struct bsc_connection *bsc, const char *mi_string)
+{
+ /*
+ * Now apply blacklist/whitelist of the BSC and the NAT.
+ * 1.) Allow directly if the IMSI is allowed at the BSC
+ * 2.) Reject if the IMSI is not allowed at the BSC
+ * 3.) Reject if the IMSI not allowed at the global level.
+ * 4.) Allow directly if the IMSI is allowed at the global level
+ */
+ struct bsc_nat_acc_lst *nat_lst = NULL;
+ struct bsc_nat_acc_lst *bsc_lst = NULL;
+
+ bsc_lst = bsc_nat_acc_lst_find(bsc->nat, bsc->cfg->acc_lst_name);
+ nat_lst = bsc_nat_acc_lst_find(bsc->nat, bsc->nat->acc_lst_name);
+
+
+ if (bsc_lst) {
+ /* 1. BSC allow */
+ if (bsc_nat_lst_check_allow(bsc_lst, mi_string) == 0)
+ return 1;
+
+ /* 2. BSC deny */
+ if (lst_check_deny(bsc_lst, mi_string) == 0) {
+ LOGP(DNAT, LOGL_ERROR,
+ "Filtering %s by imsi_deny on bsc nr: %d.\n", mi_string, bsc->cfg->nr);
+ rate_ctr_inc(&bsc_lst->stats->ctr[ACC_LIST_BSC_FILTER]);
+ return -2;
+ }
+
+ }
+
+ /* 3. NAT deny */
+ if (nat_lst) {
+ if (lst_check_deny(nat_lst, mi_string) == 0) {
+ LOGP(DNAT, LOGL_ERROR,
+ "Filtering %s by nat imsi_deny on bsc nr: %d.\n", mi_string, bsc->cfg->nr);
+ rate_ctr_inc(&nat_lst->stats->ctr[ACC_LIST_NAT_FILTER]);
+ return -3;
+ }
+ }
+
+ return 1;
+}
+
+static int _cr_check_loc_upd(struct bsc_connection *bsc,
+ uint8_t *data, unsigned int length,
+ char **imsi)
+{
+ uint8_t mi_type;
+ struct gsm48_loc_upd_req *lu;
+ char mi_string[GSM48_MI_SIZE];
+
+ if (length < sizeof(*lu)) {
+ LOGP(DNAT, LOGL_ERROR,
+ "LU does not fit. Length is %d \n", length);
+ return -1;
+ }
+
+ lu = (struct gsm48_loc_upd_req *) data;
+ mi_type = lu->mi[0] & GSM_MI_TYPE_MASK;
+
+ /*
+ * We can only deal with the IMSI. This will fail for a phone that
+ * will send the TMSI of a previous network to us.
+ */
+ if (mi_type != GSM_MI_TYPE_IMSI)
+ return 0;
+
+ gsm48_mi_to_string(mi_string, sizeof(mi_string), lu->mi, lu->mi_len);
+ *imsi = talloc_strdup(bsc, mi_string);
+ return auth_imsi(bsc, mi_string);
+}
+
+static int _cr_check_cm_serv_req(struct bsc_connection *bsc,
+ uint8_t *data, unsigned int length,
+ int *con_type, char **imsi)
+{
+ static const uint32_t classmark_offset =
+ offsetof(struct gsm48_service_request, classmark);
+
+ char mi_string[GSM48_MI_SIZE];
+ uint8_t mi_type;
+ int rc;
+ struct gsm48_service_request *req;
+
+ /* unfortunately in Phase1 the classmark2 length is variable */
+
+ if (length < sizeof(*req)) {
+ LOGP(DNAT, LOGL_ERROR,
+ "CM Serv Req does not fit. Length is %d\n", length);
+ return -1;
+ }
+
+ req = (struct gsm48_service_request *) data;
+ if (req->cm_service_type == 0x8)
+ *con_type = NAT_CON_TYPE_SSA;
+ rc = gsm48_extract_mi((uint8_t *) &req->classmark,
+ length - classmark_offset, mi_string, &mi_type);
+ if (rc < 0) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to parse the classmark2/mi. error: %d\n", rc);
+ return -1;
+ }
+
+ /* we have to let the TMSI or such pass */
+ if (mi_type != GSM_MI_TYPE_IMSI)
+ return 0;
+
+ *imsi = talloc_strdup(bsc, mi_string);
+ return auth_imsi(bsc, mi_string);
+}
+
+static int _cr_check_pag_resp(struct bsc_connection *bsc,
+ uint8_t *data, unsigned int length,
+ char **imsi)
+{
+ struct gsm48_pag_resp *resp;
+ char mi_string[GSM48_MI_SIZE];
+ uint8_t mi_type;
+
+ if (length < sizeof(*resp)) {
+ LOGP(DNAT, LOGL_ERROR, "PAG RESP does not fit. Length was %d.\n", length);
+ return -1;
+ }
+
+ resp = (struct gsm48_pag_resp *) data;
+ if (gsm48_paging_extract_mi(resp, length, mi_string, &mi_type) < 0) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to extract the MI.\n");
+ return -1;
+ }
+
+ /* we need to let it pass for now */
+ if (mi_type != GSM_MI_TYPE_IMSI)
+ return 0;
+
+ *imsi = talloc_strdup(bsc, mi_string);
+ return auth_imsi(bsc, mi_string);
+}
+
+static int _dt_check_id_resp(struct bsc_connection *bsc,
+ uint8_t *data, unsigned int length,
+ struct sccp_connections *con)
+{
+ char mi_string[GSM48_MI_SIZE];
+ uint8_t mi_type;
+ int ret;
+
+ if (length < 2) {
+ LOGP(DNAT, LOGL_ERROR, "mi does not fit.\n");
+ return -1;
+ }
+
+ if (data[0] < length - 1) {
+ LOGP(DNAT, LOGL_ERROR, "mi length too big.\n");
+ return -2;
+ }
+
+ mi_type = data[1] & GSM_MI_TYPE_MASK;
+ gsm48_mi_to_string(mi_string, sizeof(mi_string), &data[1], data[0]);
+
+ if (mi_type != GSM_MI_TYPE_IMSI)
+ return 0;
+
+ ret = auth_imsi(bsc, mi_string);
+ con->imsi_checked = 1;
+ con->imsi = talloc_strdup(con, mi_string);
+ return ret;
+}
+
+/* Filter out CR data... */
+int bsc_nat_filter_sccp_cr(struct bsc_connection *bsc, struct msgb *msg,
+ struct bsc_nat_parsed *parsed, int *con_type,
+ char **imsi)
+{
+ struct tlv_parsed tp;
+ struct gsm48_hdr *hdr48;
+ int hdr48_len;
+ int len;
+ uint8_t msg_type;
+
+ *con_type = NAT_CON_TYPE_NONE;
+ *imsi = NULL;
+
+ if (parsed->gsm_type != BSS_MAP_MSG_COMPLETE_LAYER_3) {
+ LOGP(DNAT, LOGL_ERROR,
+ "Rejecting CR message due wrong GSM Type %d\n", parsed->gsm_type);
+ return -1;
+ }
+
+ /* the parsed has had some basic l3 length check */
+ len = msg->l3h[1];
+ if (msgb_l3len(msg) - 3 < len) {
+ LOGP(DNAT, LOGL_ERROR,
+ "The CR Data has not enough space...\n");
+ return -1;
+ }
+
+ msg->l4h = &msg->l3h[3];
+ len -= 1;
+
+ tlv_parse(&tp, gsm0808_att_tlvdef(), msg->l4h, len, 0, 0);
+
+ if (!TLVP_PRESENT(&tp, GSM0808_IE_LAYER_3_INFORMATION)) {
+ LOGP(DNAT, LOGL_ERROR, "CR Data does not contain layer3 information.\n");
+ return -1;
+ }
+
+ hdr48_len = TLVP_LEN(&tp, GSM0808_IE_LAYER_3_INFORMATION);
+
+ if (hdr48_len < sizeof(*hdr48)) {
+ LOGP(DNAT, LOGL_ERROR, "GSM48 header does not fit.\n");
+ return -1;
+ }
+
+ hdr48 = (struct gsm48_hdr *) TLVP_VAL(&tp, GSM0808_IE_LAYER_3_INFORMATION);
+
+ msg_type = hdr48->msg_type & 0xbf;
+ if (hdr48->proto_discr == GSM48_PDISC_MM &&
+ msg_type == GSM48_MT_MM_LOC_UPD_REQUEST) {
+ *con_type = NAT_CON_TYPE_LU;
+ return _cr_check_loc_upd(bsc, &hdr48->data[0], hdr48_len - sizeof(*hdr48), imsi);
+ } else if (hdr48->proto_discr == GSM48_PDISC_MM &&
+ msg_type == GSM48_MT_MM_CM_SERV_REQ) {
+ *con_type = NAT_CON_TYPE_CM_SERV_REQ;
+ return _cr_check_cm_serv_req(bsc, &hdr48->data[0],
+ hdr48_len - sizeof(*hdr48),
+ con_type, imsi);
+ } else if (hdr48->proto_discr == GSM48_PDISC_RR &&
+ msg_type == GSM48_MT_RR_PAG_RESP) {
+ *con_type = NAT_CON_TYPE_PAG_RESP;
+ return _cr_check_pag_resp(bsc, &hdr48->data[0], hdr48_len - sizeof(*hdr48), imsi);
+ } else {
+ /* We only want to filter the above, let other things pass */
+ *con_type = NAT_CON_TYPE_OTHER;
+ return 0;
+ }
+}
+
+struct gsm48_hdr *bsc_unpack_dtap(struct bsc_nat_parsed *parsed,
+ struct msgb *msg, uint32_t *len)
+{
+ /* gsm_type is actually the size of the dtap */
+ *len = parsed->gsm_type;
+ if (*len < msgb_l3len(msg) - 3) {
+ LOGP(DNAT, LOGL_ERROR, "Not enough space for DTAP.\n");
+ return NULL;
+ }
+
+ if (*len < sizeof(struct gsm48_hdr)) {
+ LOGP(DNAT, LOGL_ERROR, "GSM48 header does not fit.\n");
+ return NULL;
+ }
+
+ msg->l4h = &msg->l3h[3];
+ return (struct gsm48_hdr *) msg->l4h;
+}
+
+int bsc_nat_filter_dt(struct bsc_connection *bsc, struct msgb *msg,
+ struct sccp_connections *con, struct bsc_nat_parsed *parsed)
+{
+ uint32_t len;
+ uint8_t msg_type;
+ struct gsm48_hdr *hdr48;
+
+ if (con->imsi_checked)
+ return 0;
+
+ /* only care about DTAP messages */
+ if (parsed->bssap != BSSAP_MSG_DTAP)
+ return 0;
+
+ hdr48 = bsc_unpack_dtap(parsed, msg, &len);
+ if (!hdr48)
+ return -1;
+
+ msg_type = hdr48->msg_type & 0xbf;
+ if (hdr48->proto_discr == GSM48_PDISC_MM &&
+ msg_type == GSM48_MT_MM_ID_RESP) {
+ return _dt_check_id_resp(bsc, &hdr48->data[0], len - sizeof(*hdr48), con);
+ } else {
+ return 0;
+ }
+}
+
+void bsc_parse_reg(void *ctx, regex_t *reg, char **imsi, int argc, const char **argv)
+{
+ if (*imsi) {
+ talloc_free(*imsi);
+ *imsi = NULL;
+ }
+ regfree(reg);
+
+ if (argc > 0) {
+ *imsi = talloc_strdup(ctx, argv[0]);
+ regcomp(reg, argv[0], 0);
+ }
+}
+
+static const char *con_types [] = {
+ [NAT_CON_TYPE_NONE] = "n/a",
+ [NAT_CON_TYPE_LU] = "Location Update",
+ [NAT_CON_TYPE_CM_SERV_REQ] = "CM Serv Req",
+ [NAT_CON_TYPE_PAG_RESP] = "Paging Response",
+ [NAT_CON_TYPE_SSA] = "Supplementar Service Activation",
+ [NAT_CON_TYPE_LOCAL_REJECT] = "Local Reject",
+ [NAT_CON_TYPE_OTHER] = "Other",
+};
+
+const char *bsc_con_type_to_string(int type)
+{
+ return con_types[type];
+}
+
+struct bsc_nat_acc_lst *bsc_nat_acc_lst_find(struct bsc_nat *nat, const char *name)
+{
+ struct bsc_nat_acc_lst *lst;
+
+ if (!name)
+ return NULL;
+
+ llist_for_each_entry(lst, &nat->access_lists, list)
+ if (strcmp(lst->name, name) == 0)
+ return lst;
+
+ return NULL;
+}
+
+struct bsc_nat_acc_lst *bsc_nat_acc_lst_get(struct bsc_nat *nat, const char *name)
+{
+ struct bsc_nat_acc_lst *lst;
+
+ lst = bsc_nat_acc_lst_find(nat, name);
+ if (lst)
+ return lst;
+
+ lst = talloc_zero(nat, struct bsc_nat_acc_lst);
+ if (!lst) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate access list");
+ return NULL;
+ }
+
+ /* TODO: get the index right */
+ lst->stats = rate_ctr_group_alloc(lst, &bsc_cfg_acc_list_desc, 0);
+ if (!lst->stats) {
+ talloc_free(lst);
+ return NULL;
+ }
+
+ INIT_LLIST_HEAD(&lst->fltr_list);
+ lst->name = talloc_strdup(lst, name);
+ llist_add_tail(&lst->list, &nat->access_lists);
+ return lst;
+}
+
+void bsc_nat_acc_lst_delete(struct bsc_nat_acc_lst *lst)
+{
+ llist_del(&lst->list);
+ rate_ctr_group_free(lst->stats);
+ talloc_free(lst);
+}
+
+struct bsc_nat_acc_lst_entry *bsc_nat_acc_lst_entry_create(struct bsc_nat_acc_lst *lst)
+{
+ struct bsc_nat_acc_lst_entry *entry;
+
+ entry = talloc_zero(lst, struct bsc_nat_acc_lst_entry);
+ if (!entry)
+ return NULL;
+
+ llist_add_tail(&entry->list, &lst->fltr_list);
+ return entry;
+}
+
+int bsc_nat_msc_is_connected(struct bsc_nat *nat)
+{
+ return nat->msc_con->is_connected;
+}
+
+static const int con_to_ctr[] = {
+ [NAT_CON_TYPE_NONE] = -1,
+ [NAT_CON_TYPE_LU] = BCFG_CTR_CON_TYPE_LU,
+ [NAT_CON_TYPE_CM_SERV_REQ] = BCFG_CTR_CON_CMSERV_RQ,
+ [NAT_CON_TYPE_PAG_RESP] = BCFG_CTR_CON_PAG_RESP,
+ [NAT_CON_TYPE_SSA] = BCFG_CTR_CON_SSA,
+ [NAT_CON_TYPE_LOCAL_REJECT] = -1,
+ [NAT_CON_TYPE_OTHER] = BCFG_CTR_CON_OTHER,
+};
+
+int bsc_conn_type_to_ctr(struct sccp_connections *conn)
+{
+ return con_to_ctr[conn->con_type];
+}
+
+int bsc_write_cb(struct bsc_fd *bfd, struct msgb *msg)
+{
+ int rc;
+
+ rc = write(bfd->fd, msg->data, msg->len);
+ if (rc != msg->len)
+ LOGP(DNAT, LOGL_ERROR, "Failed to write message to the BSC.\n");
+
+ return rc;
+}
+
+/**
+ * Rewrite non global numbers... according to rules based on the IMSI
+ */
+struct msgb *bsc_nat_rewrite_setup(struct bsc_nat *nat, struct msgb *msg, struct bsc_nat_parsed *parsed, const char *imsi)
+{
+ struct tlv_parsed tp;
+ struct gsm48_hdr *hdr48;
+ uint32_t len;
+ uint8_t msg_type;
+ unsigned int payload_len;
+ struct gsm_mncc_number called;
+ struct msg_entry *entry;
+ char *new_number = NULL;
+ struct msgb *out, *sccp;
+ uint8_t *outptr;
+ const uint8_t *msgptr;
+ int sec_len;
+
+ if (!imsi || strlen(imsi) < 5)
+ return msg;
+
+ if (!nat->num_rewr)
+ return msg;
+
+ /* only care about DTAP messages */
+ if (parsed->bssap != BSSAP_MSG_DTAP)
+ return msg;
+ if (!parsed->dest_local_ref)
+ return msg;
+
+ hdr48 = bsc_unpack_dtap(parsed, msg, &len);
+ if (!hdr48)
+ return msg;
+
+ msg_type = hdr48->msg_type & 0xbf;
+ if (hdr48->proto_discr != GSM48_PDISC_CC ||
+ msg_type != GSM48_MT_CC_SETUP)
+ return msg;
+
+ /* decode and rewrite the message */
+ payload_len = len - sizeof(*hdr48);
+ tlv_parse(&tp, &gsm48_att_tlvdef, hdr48->data, payload_len, 0, 0);
+
+ /* no number, well let us ignore it */
+ if (!TLVP_PRESENT(&tp, GSM48_IE_CALLED_BCD))
+ return msg;
+
+ memset(&called, 0, sizeof(called));
+ gsm48_decode_called(&called,
+ TLVP_VAL(&tp, GSM48_IE_CALLED_BCD) - 1);
+
+ /* check if it looks international and stop */
+ if (called.plan != 1)
+ return msg;
+ if (called.type == 1)
+ return msg;
+ if (strncmp(called.number, "00", 2) == 0)
+ return msg;
+
+ /* need to find a replacement and then fix it */
+ llist_for_each_entry(entry, &nat->num_rewr->entry, list) {
+ regex_t reg;
+ regmatch_t matches[2];
+
+ if (entry->mcc[0] != '*' && strncmp(entry->mcc, imsi, 3) != 0)
+ continue;
+ if (entry->mnc[0] != '*' && strncmp(entry->mnc, imsi + 3, 2) != 0)
+ continue;
+
+ if (entry->text[0] == '+') {
+ LOGP(DNAT, LOGL_ERROR,
+ "Plus is not allowed in the number");
+ continue;
+ }
+
+ /* We have an entry for the IMSI. Need to match now */
+ if (regcomp(&reg, entry->option, REG_EXTENDED) != 0) {
+ LOGP(DNAT, LOGL_ERROR,
+ "Regexp '%s' is not valid.\n", entry->option);
+ continue;
+ }
+
+ /* this regexp matches... */
+ if (regexec(&reg, called.number, 2, matches, 0) == 0 &&
+ matches[1].rm_eo != -1)
+ new_number = talloc_asprintf(msg, "%s%s",
+ entry->text,
+ &called.number[matches[1].rm_so]);
+ regfree(&reg);
+
+ if (new_number)
+ break;
+ }
+
+ if (!new_number) {
+ LOGP(DNAT, LOGL_DEBUG, "No IMSI match found, returning message.\n");
+ return msg;
+ }
+
+ if (strlen(new_number) > sizeof(called.number)) {
+ LOGP(DNAT, LOGL_ERROR, "Number is too long for structure.\n");
+ talloc_free(new_number);
+ return msg;
+ }
+
+ /*
+ * Need to create a new message now based on the old onew
+ * with a new number. We can sadly not patch this in place
+ * so we will need to regenerate it.
+ */
+
+ out = msgb_alloc_headroom(4096, 128, "changed-setup");
+ if (!out) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate.\n");
+ talloc_free(new_number);
+ return msg;
+ }
+
+ /* copy the header */
+ outptr = msgb_put(out, sizeof(*hdr48));
+ memcpy(outptr, hdr48, sizeof(*hdr48));
+
+ /* copy everything up to the number */
+ sec_len = TLVP_VAL(&tp, GSM48_IE_CALLED_BCD) - 2 - &hdr48->data[0];
+ outptr = msgb_put(out, sec_len);
+ memcpy(outptr, &hdr48->data[0], sec_len);
+
+ /* create the new number */
+ if (strncmp(new_number, "00", 2) == 0) {
+ called.type = 1;
+ strncpy(called.number, new_number + 2, sizeof(called.number));
+ } else {
+ strncpy(called.number, new_number, sizeof(called.number));
+ }
+ gsm48_encode_called(out, &called);
+
+ /* copy thre rest */
+ msgptr = TLVP_VAL(&tp, GSM48_IE_CALLED_BCD) +
+ TLVP_LEN(&tp, GSM48_IE_CALLED_BCD);
+ sec_len = payload_len - (msgptr - &hdr48->data[0]);
+ outptr = msgb_put(out, sec_len);
+ memcpy(outptr, msgptr, sec_len);
+
+ /* wrap with DTAP, SCCP, then IPA. TODO: Stop copying */
+ gsm0808_prepend_dtap_header(out, 0);
+ sccp = sccp_create_dt1(parsed->dest_local_ref, out->data, out->len);
+ if (!sccp) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate.\n");
+ talloc_free(new_number);
+ talloc_free(out);
+ return msg;
+ }
+
+ ipaccess_prepend_header(sccp, IPAC_PROTO_SCCP);
+
+ /* give up memory, we are done */
+ talloc_free(new_number);
+ /* the parsed hangs off from msg but it needs to survive */
+ talloc_steal(sccp, parsed);
+ msgb_free(msg);
+ msgb_free(out);
+ out = NULL;
+ return sccp;
+}
+
diff --git a/openbsc/src/osmo-bsc_nat/bsc_nat_vty.c b/openbsc/src/osmo-bsc_nat/bsc_nat_vty.c
new file mode 100644
index 000000000..786db2dc2
--- /dev/null
+++ b/openbsc/src/osmo-bsc_nat/bsc_nat_vty.c
@@ -0,0 +1,788 @@
+/* OpenBSC NAT interface to quagga VTY */
+/* (C) 2010 by Holger Hans Peter Freyther
+ * (C) 2010 by On-Waves
+ * 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 <openbsc/vty.h>
+#include <openbsc/bsc_nat.h>
+#include <openbsc/bsc_nat_sccp.h>
+#include <openbsc/bsc_msc.h>
+#include <openbsc/gsm_04_08.h>
+#include <openbsc/mgcp.h>
+#include <openbsc/vty.h>
+
+#include <osmocore/talloc.h>
+#include <osmocore/rate_ctr.h>
+#include <osmocore/utils.h>
+
+#include <osmocom/sccp/sccp.h>
+
+#include <stdlib.h>
+
+static struct bsc_nat *_nat;
+
+static struct cmd_node nat_node = {
+ NAT_NODE,
+ "%s(nat)#",
+ 1,
+};
+
+static struct cmd_node bsc_node = {
+ NAT_BSC_NODE,
+ "%s(bsc)#",
+ 1,
+};
+
+static void write_acc_lst(struct vty *vty, struct bsc_nat_acc_lst *lst)
+{
+ struct bsc_nat_acc_lst_entry *entry;
+
+ llist_for_each_entry(entry, &lst->fltr_list, list) {
+ if (entry->imsi_allow)
+ vty_out(vty, " access-list %s imsi-allow %s%s",
+ lst->name, entry->imsi_allow, VTY_NEWLINE);
+ if (entry->imsi_deny)
+ vty_out(vty, " access-list %s imsi-deny %s%s",
+ lst->name, entry->imsi_deny, VTY_NEWLINE);
+ }
+}
+
+static int config_write_nat(struct vty *vty)
+{
+ struct bsc_nat_acc_lst *lst;
+
+ vty_out(vty, "nat%s", VTY_NEWLINE);
+ vty_out(vty, " msc ip %s%s", _nat->msc_ip, VTY_NEWLINE);
+ vty_out(vty, " msc port %d%s", _nat->msc_port, VTY_NEWLINE);
+ vty_out(vty, " timeout auth %d%s", _nat->auth_timeout, VTY_NEWLINE);
+ vty_out(vty, " timeout ping %d%s", _nat->ping_timeout, VTY_NEWLINE);
+ vty_out(vty, " timeout pong %d%s", _nat->pong_timeout, VTY_NEWLINE);
+ if (_nat->token)
+ vty_out(vty, " token %s%s", _nat->token, VTY_NEWLINE);
+ vty_out(vty, " ip-dscp %d%s", _nat->bsc_ip_dscp, VTY_NEWLINE);
+ if (_nat->acc_lst_name)
+ vty_out(vty, " access-list-name %s%s", _nat->acc_lst_name, VTY_NEWLINE);
+ if (_nat->ussd_lst_name)
+ vty_out(vty, " ussd-list-name %s%s", _nat->ussd_lst_name, VTY_NEWLINE);
+ if (_nat->ussd_query)
+ vty_out(vty, " ussd-query %s%s", _nat->ussd_query, VTY_NEWLINE);
+ if (_nat->ussd_token)
+ vty_out(vty, " ussd-token %s%s", _nat->ussd_token, VTY_NEWLINE);
+ if (_nat->ussd_local)
+ vty_out(vty, " ussd-local-ip %s%s", _nat->ussd_local, VTY_NEWLINE);
+
+ if (_nat->num_rewr_name)
+ vty_out(vty, " number-rewrite %s%s", _nat->num_rewr_name, VTY_NEWLINE);
+
+ llist_for_each_entry(lst, &_nat->access_lists, list) {
+ write_acc_lst(vty, lst);
+ }
+
+ return CMD_SUCCESS;
+}
+
+static void dump_lac(struct vty *vty, struct bsc_config *cfg)
+{
+ struct bsc_lac_entry *lac;
+ llist_for_each_entry(lac, &cfg->lac_list, entry)
+ vty_out(vty, " location_area_code %u%s", lac->lac, VTY_NEWLINE);
+}
+
+static void config_write_bsc_single(struct vty *vty, struct bsc_config *bsc)
+{
+ vty_out(vty, " bsc %u%s", bsc->nr, VTY_NEWLINE);
+ vty_out(vty, " token %s%s", bsc->token, VTY_NEWLINE);
+ dump_lac(vty, bsc);
+ vty_out(vty, " paging forbidden %d%s", bsc->forbid_paging, VTY_NEWLINE);
+ if (bsc->description)
+ vty_out(vty, " description %s%s", bsc->description, VTY_NEWLINE);
+ if (bsc->acc_lst_name)
+ vty_out(vty, " access-list-name %s%s", bsc->acc_lst_name, VTY_NEWLINE);
+ vty_out(vty, " max-endpoints %d%s", bsc->max_endpoints, VTY_NEWLINE);
+}
+
+static int config_write_bsc(struct vty *vty)
+{
+ struct bsc_config *bsc;
+
+ llist_for_each_entry(bsc, &_nat->bsc_configs, entry)
+ config_write_bsc_single(vty, bsc);
+ return CMD_SUCCESS;
+}
+
+
+DEFUN(show_sccp, show_sccp_cmd, "show sccp connections",
+ SHOW_STR "Display information about current SCCP connections")
+{
+ struct sccp_connections *con;
+ vty_out(vty, "Listing all open SCCP connections%s", VTY_NEWLINE);
+
+ llist_for_each_entry(con, &_nat->sccp_connections, list_entry) {
+ vty_out(vty, "For BSC Nr: %d BSC ref: 0x%x; MUX ref: 0x%x; Network has ref: %d ref: 0x%x MSC/BSC mux: 0x%x/0x%x type: %s%s",
+ con->bsc->cfg ? con->bsc->cfg->nr : -1,
+ sccp_src_ref_to_int(&con->real_ref),
+ sccp_src_ref_to_int(&con->patched_ref),
+ con->has_remote_ref,
+ sccp_src_ref_to_int(&con->remote_ref),
+ con->msc_endp, con->bsc_endp,
+ bsc_con_type_to_string(con->con_type),
+ VTY_NEWLINE);
+ }
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(show_bsc, show_bsc_cmd, "show bsc connections",
+ SHOW_STR "Display information about current BSCs")
+{
+ struct bsc_connection *con;
+ struct sockaddr_in sock;
+ socklen_t len = sizeof(sock);
+
+ llist_for_each_entry(con, &_nat->bsc_connections, list_entry) {
+ getpeername(con->write_queue.bfd.fd, (struct sockaddr *) &sock, &len);
+ vty_out(vty, "BSC nr: %d auth: %d fd: %d peername: %s%s",
+ con->cfg ? con->cfg->nr : -1,
+ con->authenticated, con->write_queue.bfd.fd,
+ inet_ntoa(sock.sin_addr), VTY_NEWLINE);
+ }
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(show_bsc_mgcp, show_bsc_mgcp_cmd, "show bsc mgcp NR",
+ SHOW_STR "Display the MGCP status for a given BSC")
+{
+ struct bsc_connection *con;
+ int nr = atoi(argv[0]);
+ int i, j, endp;
+
+ llist_for_each_entry(con, &_nat->bsc_connections, list_entry) {
+ int max;
+ if (!con->cfg)
+ continue;
+ if (con->cfg->nr != nr)
+ continue;
+
+ /* this bsc has no audio endpoints yet */
+ if (!con->_endpoint_status)
+ continue;
+
+ vty_out(vty, "MGCP Status for %d%s", con->cfg->nr, VTY_NEWLINE);
+ max = bsc_mgcp_nr_multiplexes(con->max_endpoints);
+ for (i = 0; i < max; ++i) {
+ for (j = 0; j < 32; ++j) {
+ endp = mgcp_timeslot_to_endpoint(i, j);
+ vty_out(vty, " Endpoint 0x%x %s%s", endp,
+ con->_endpoint_status[endp] == 0
+ ? "free" : "allocated",
+ VTY_NEWLINE);
+ }
+ }
+ break;
+ }
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(show_bsc_cfg, show_bsc_cfg_cmd, "show bsc config",
+ SHOW_STR "Display information about known BSC configs")
+{
+ struct bsc_config *conf;
+ llist_for_each_entry(conf, &_nat->bsc_configs, entry) {
+ vty_out(vty, "BSC token: '%s' nr: %u%s",
+ conf->token, conf->nr, VTY_NEWLINE);
+ if (conf->acc_lst_name)
+ vty_out(vty, " access-list: %s%s",
+ conf->acc_lst_name, VTY_NEWLINE);
+ vty_out(vty, " paging forbidden: %d%s",
+ conf->forbid_paging, VTY_NEWLINE);
+ if (conf->description)
+ vty_out(vty, " description: %s%s", conf->description, VTY_NEWLINE);
+ else
+ vty_out(vty, " No description.%s", VTY_NEWLINE);
+
+ }
+
+ return CMD_SUCCESS;
+}
+
+static void dump_stat_total(struct vty *vty, struct bsc_nat *nat)
+{
+ vty_out(vty, "NAT statistics%s", VTY_NEWLINE);
+ vty_out(vty, " SCCP Connections %lu total, %lu calls%s",
+ counter_get(nat->stats.sccp.conn),
+ counter_get(nat->stats.sccp.calls), VTY_NEWLINE);
+ vty_out(vty, " MSC Connections %lu%s",
+ counter_get(nat->stats.msc.reconn), VTY_NEWLINE);
+ vty_out(vty, " MSC Connected: %d%s",
+ nat->msc_con->is_connected, VTY_NEWLINE);
+ vty_out(vty, " BSC Connections %lu total, %lu auth failed.%s",
+ counter_get(nat->stats.bsc.reconn),
+ counter_get(nat->stats.bsc.auth_fail), VTY_NEWLINE);
+}
+
+static void dump_stat_bsc(struct vty *vty, struct bsc_config *conf)
+{
+ int connected = 0;
+ struct bsc_connection *con;
+
+ vty_out(vty, " BSC nr: %d%s",
+ conf->nr, VTY_NEWLINE);
+ vty_out_rate_ctr_group(vty, " ", conf->stats.ctrg);
+
+ llist_for_each_entry(con, &conf->nat->bsc_connections, list_entry) {
+ if (con->cfg != conf)
+ continue;
+ connected = 1;
+ break;
+ }
+
+ vty_out(vty, " Connected: %d%s", connected, VTY_NEWLINE);
+}
+
+DEFUN(show_stats,
+ show_stats_cmd,
+ "show statistics [NR]",
+ SHOW_STR "Display network statistics")
+{
+ struct bsc_config *conf;
+
+ int nr = -1;
+
+ if (argc == 1)
+ nr = atoi(argv[0]);
+
+ dump_stat_total(vty, _nat);
+ llist_for_each_entry(conf, &_nat->bsc_configs, entry) {
+ if (argc == 1 && nr != conf->nr)
+ continue;
+ dump_stat_bsc(vty, conf);
+ }
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(show_stats_lac,
+ show_stats_lac_cmd,
+ "show statistics-by-lac <0-65535>",
+ SHOW_STR "Display network statistics by lac\n"
+ "The lac of the BSC\n")
+{
+ int lac;
+ struct bsc_config *conf;
+
+ lac = atoi(argv[0]);
+
+ dump_stat_total(vty, _nat);
+ llist_for_each_entry(conf, &_nat->bsc_configs, entry) {
+ if (!bsc_config_handles_lac(conf, lac))
+ continue;
+ dump_stat_bsc(vty, conf);
+ }
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(show_msc,
+ show_msc_cmd,
+ "show msc connection",
+ SHOW_STR "Show the status of the MSC connection.")
+{
+ if (!_nat->msc_con) {
+ vty_out(vty, "The MSC is not yet configured.\n");
+ return CMD_WARNING;
+ }
+
+ vty_out(vty, "MSC on %s:%d is connected: %d%s\n",
+ _nat->msc_con->ip, _nat->msc_con->port,
+ _nat->msc_con->is_connected, VTY_NEWLINE);
+ return CMD_SUCCESS;
+}
+
+DEFUN(close_bsc,
+ close_bsc_cmd,
+ "close bsc connection BSC_NR",
+ "Close the connection with the BSC identified by the config number.")
+{
+ struct bsc_connection *bsc;
+ int bsc_nr = atoi(argv[0]);
+
+ llist_for_each_entry(bsc, &_nat->bsc_connections, list_entry) {
+ if (!bsc->cfg || bsc->cfg->nr != bsc_nr)
+ continue;
+ bsc_close_connection(bsc);
+ break;
+ }
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat, cfg_nat_cmd, "nat", "Configute the NAT")
+{
+ vty->index = _nat;
+ vty->node = NAT_NODE;
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_msc_ip,
+ cfg_nat_msc_ip_cmd,
+ "msc ip A.B.C.D",
+ "Set the IP address of the MSC.")
+{
+ bsc_nat_set_msc_ip(_nat, argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_msc_port,
+ cfg_nat_msc_port_cmd,
+ "msc port <1-65500>",
+ "Set the port of the MSC.")
+{
+ _nat->msc_port = atoi(argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_auth_time,
+ cfg_nat_auth_time_cmd,
+ "timeout auth <1-256>",
+ "The time to wait for an auth response.")
+{
+ _nat->auth_timeout = atoi(argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_ping_time,
+ cfg_nat_ping_time_cmd,
+ "timeout ping NR",
+ "Send a ping every NR seconds. Negative to disable.")
+{
+ _nat->ping_timeout = atoi(argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_pong_time,
+ cfg_nat_pong_time_cmd,
+ "timeout pong NR",
+ "Wait NR seconds for the PONG response. Should be smaller than ping.")
+{
+ _nat->pong_timeout = atoi(argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_token, cfg_nat_token_cmd,
+ "token TOKEN",
+ "Set a token for the NAT")
+{
+ bsc_replace_string(_nat, &_nat->token, argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_bsc_ip_dscp, cfg_nat_bsc_ip_dscp_cmd,
+ "ip-dscp <0-255>",
+ "Set the IP DSCP for the BSCs to use\n" "Set the IP_TOS attribute")
+{
+ _nat->bsc_ip_dscp = atoi(argv[0]);
+ return CMD_SUCCESS;
+}
+
+ALIAS_DEPRECATED(cfg_nat_bsc_ip_dscp, cfg_nat_bsc_ip_tos_cmd,
+ "ip-tos <0-255>",
+ "Use ip-dscp in the future.\n" "Set the DSCP\n")
+
+
+DEFUN(cfg_nat_acc_lst_name,
+ cfg_nat_acc_lst_name_cmd,
+ "access-list-name NAME",
+ "Set the name of the access list to use.\n"
+ "The name of the to be used access list.")
+{
+ bsc_replace_string(_nat, &_nat->acc_lst_name, argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_number_rewrite,
+ cfg_nat_number_rewrite_cmd,
+ "number-rewrite FILENAME",
+ "Set the file with rewriting rules.\n" "Filename")
+{
+ bsc_replace_string(_nat, &_nat->num_rewr_name, argv[0]);
+ if (_nat->num_rewr_name) {
+ if (_nat->num_rewr)
+ talloc_free(_nat->num_rewr);
+ _nat->num_rewr = msg_entry_parse(_nat, _nat->num_rewr_name);
+ return _nat->num_rewr == NULL ? CMD_WARNING : CMD_SUCCESS;
+ } else {
+ if (_nat->num_rewr)
+ talloc_free(_nat->num_rewr);
+ _nat->num_rewr = NULL;
+ return CMD_SUCCESS;
+ }
+}
+
+DEFUN(cfg_nat_ussd_lst_name,
+ cfg_nat_ussd_lst_name_cmd,
+ "ussd-list-name NAME",
+ "Set the name of the access list to check for IMSIs for USSD message\n"
+ "The name of the access list for HLR USSD handling")
+{
+ bsc_replace_string(_nat, &_nat->ussd_lst_name, argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_ussd_query,
+ cfg_nat_ussd_query_cmd,
+ "ussd-query QUERY",
+ "Set the USSD query to match with the ussd-list-name\n"
+ "The query to match")
+{
+ bsc_replace_string(_nat, &_nat->ussd_query, argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_ussd_token,
+ cfg_nat_ussd_token_cmd,
+ "ussd-token TOKEN",
+ "Set the token used to identify the USSD module\n" "Secret key\n")
+{
+ bsc_replace_string(_nat, &_nat->ussd_token, argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_nat_ussd_local,
+ cfg_nat_ussd_local_cmd,
+ "ussd-local-ip A.B.C.D",
+ "Set the IP to listen for the USSD Provider\n" "IP Address\n")
+{
+ bsc_replace_string(_nat, &_nat->ussd_local, argv[0]);
+ return CMD_SUCCESS;
+}
+
+/* per BSC configuration */
+DEFUN(cfg_bsc, cfg_bsc_cmd, "bsc BSC_NR", "Select a BSC to configure")
+{
+ int bsc_nr = atoi(argv[0]);
+ struct bsc_config *bsc;
+
+ if (bsc_nr > _nat->num_bsc) {
+ vty_out(vty, "%% The next unused BSC number is %u%s",
+ _nat->num_bsc, VTY_NEWLINE);
+ return CMD_WARNING;
+ } else if (bsc_nr == _nat->num_bsc) {
+ /* allocate a new one */
+ bsc = bsc_config_alloc(_nat, "unknown");
+ } else
+ bsc = bsc_config_num(_nat, bsc_nr);
+
+ if (!bsc)
+ return CMD_WARNING;
+
+ vty->index = bsc;
+ vty->node = NAT_BSC_NODE;
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_bsc_token, cfg_bsc_token_cmd, "token TOKEN", "Set the token")
+{
+ struct bsc_config *conf = vty->index;
+
+ bsc_replace_string(conf, &conf->token, argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_bsc_lac, cfg_bsc_lac_cmd, "location_area_code <0-65535>",
+ "Set the Location Area Code (LAC) of this BSC")
+{
+ struct bsc_config *tmp;
+ struct bsc_config *conf = vty->index;
+
+ int lac = atoi(argv[0]);
+
+ if (lac == GSM_LAC_RESERVED_DETACHED || lac == GSM_LAC_RESERVED_ALL_BTS) {
+ vty_out(vty, "%% LAC %d is reserved by GSM 04.08%s",
+ lac, VTY_NEWLINE);
+ return CMD_WARNING;
+ }
+
+ /* verify that the LACs are unique */
+ llist_for_each_entry(tmp, &_nat->bsc_configs, entry) {
+ if (bsc_config_handles_lac(tmp, lac)) {
+ vty_out(vty, "%% LAC %d is already used.%s", lac, VTY_NEWLINE);
+ return CMD_ERR_INCOMPLETE;
+ }
+ }
+
+ bsc_config_add_lac(conf, lac);
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_bsc_no_lac, cfg_bsc_no_lac_cmd,
+ "no location_area_code <0-65535>",
+ NO_STR "Set the Location Area Code (LAC) of this BSC")
+{
+ int lac = atoi(argv[0]);
+ struct bsc_config *conf = vty->index;
+
+ bsc_config_del_lac(conf, lac);
+ return CMD_SUCCESS;
+}
+
+
+
+DEFUN(cfg_lst_imsi_allow,
+ cfg_lst_imsi_allow_cmd,
+ "access-list NAME imsi-allow [REGEXP]",
+ "Allow IMSIs matching the REGEXP\n"
+ "The name of the access-list\n"
+ "The regexp of allowed IMSIs\n")
+{
+ struct bsc_nat_acc_lst *acc;
+ struct bsc_nat_acc_lst_entry *entry;
+
+ acc = bsc_nat_acc_lst_get(_nat, argv[0]);
+ if (!acc)
+ return CMD_WARNING;
+
+ entry = bsc_nat_acc_lst_entry_create(acc);
+ if (!entry)
+ return CMD_WARNING;
+
+ bsc_parse_reg(acc, &entry->imsi_allow_re, &entry->imsi_allow, argc - 1, &argv[1]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_lst_imsi_deny,
+ cfg_lst_imsi_deny_cmd,
+ "access-list NAME imsi-deny [REGEXP]",
+ "Allow IMSIs matching the REGEXP\n"
+ "The name of the access-list\n"
+ "The regexp of to be denied IMSIs\n")
+{
+ struct bsc_nat_acc_lst *acc;
+ struct bsc_nat_acc_lst_entry *entry;
+
+ acc = bsc_nat_acc_lst_get(_nat, argv[0]);
+ if (!acc)
+ return CMD_WARNING;
+
+ entry = bsc_nat_acc_lst_entry_create(acc);
+ if (!entry)
+ return CMD_WARNING;
+
+ bsc_parse_reg(acc, &entry->imsi_deny_re, &entry->imsi_deny, argc - 1, &argv[1]);
+ return CMD_SUCCESS;
+}
+
+/* naming to follow Zebra... */
+DEFUN(cfg_lst_no,
+ cfg_lst_no_cmd,
+ "no access-list NAME",
+ NO_STR "Remove an access-list by name\n"
+ "The access-list to remove\n")
+{
+ struct bsc_nat_acc_lst *acc;
+ acc = bsc_nat_acc_lst_find(_nat, argv[0]);
+ if (!acc)
+ return CMD_WARNING;
+
+ bsc_nat_acc_lst_delete(acc);
+ return CMD_SUCCESS;
+}
+
+DEFUN(show_acc_lst,
+ show_acc_lst_cmd,
+ "show access-list NAME",
+ SHOW_STR "The name of the access list\n")
+{
+ struct bsc_nat_acc_lst *acc;
+ acc = bsc_nat_acc_lst_find(_nat, argv[0]);
+ if (!acc)
+ return CMD_WARNING;
+
+ vty_out(vty, "access-list %s%s", acc->name, VTY_NEWLINE);
+ vty_out_rate_ctr_group(vty, " ", acc->stats);
+
+ return CMD_SUCCESS;
+}
+
+
+DEFUN(cfg_bsc_acc_lst_name,
+ cfg_bsc_acc_lst_name_cmd,
+ "access-list-name NAME",
+ "Set the name of the access list to use.\n"
+ "The name of the to be used access list.")
+{
+ struct bsc_config *conf = vty->index;
+
+ bsc_replace_string(conf, &conf->acc_lst_name, argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_bsc_max_endps, cfg_bsc_max_endps_cmd,
+ "max-endpoints <1-1024>",
+ "Highest endpoint to use (exclusively)\n" "Number of ports\n")
+{
+ struct bsc_config *conf = vty->index;
+
+ conf->max_endpoints = atoi(argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_bsc_paging,
+ cfg_bsc_paging_cmd,
+ "paging forbidden (0|1)",
+ "Forbid sending PAGING REQUESTS to the BSC.")
+{
+ struct bsc_config *conf = vty->index;
+
+ if (strcmp("1", argv[0]) == 0)
+ conf->forbid_paging = 1;
+ else
+ conf->forbid_paging = 0;
+
+ return CMD_SUCCESS;
+}
+
+DEFUN(cfg_bsc_desc,
+ cfg_bsc_desc_cmd,
+ "description DESC",
+ "Provide a description for the given BSC.")
+{
+ struct bsc_config *conf = vty->index;
+
+ bsc_replace_string(conf, &conf->description, argv[0]);
+ return CMD_SUCCESS;
+}
+
+DEFUN(test_regex, test_regex_cmd,
+ "test regex PATTERN STRING",
+ "Check if the string is matching the current pattern.")
+{
+ regex_t reg;
+ char *str = NULL;
+
+ memset(&reg, 0, sizeof(reg));
+ bsc_parse_reg(_nat, &reg, &str, 1, argv);
+
+ vty_out(vty, "String matches allow pattern: %d%s",
+ regexec(&reg, argv[1], 0, NULL, 0) == 0, VTY_NEWLINE);
+
+ talloc_free(str);
+ regfree(&reg);
+ return CMD_SUCCESS;
+}
+
+DEFUN(set_last_endp, set_last_endp_cmd,
+ "set bsc last-used-endpoint <0-9999999999> <0-1024>",
+ "Set a value\n" "Operate on a BSC\n"
+ "Last used endpoint for an assignment\n" "BSC configuration number\n"
+ "Endpoint number used\n")
+{
+ struct bsc_connection *con;
+ int nr = atoi(argv[0]);
+ int endp = atoi(argv[1]);
+
+
+ llist_for_each_entry(con, &_nat->bsc_connections, list_entry) {
+ if (!con->cfg)
+ continue;
+ if (con->cfg->nr != nr)
+ continue;
+
+ con->last_endpoint = endp;
+ vty_out(vty, "Updated the last endpoint for %d to %d.%s",
+ con->cfg->nr, con->last_endpoint, VTY_NEWLINE);
+ }
+
+ return CMD_SUCCESS;
+}
+
+int bsc_nat_vty_init(struct bsc_nat *nat)
+{
+ _nat = nat;
+
+ /* show commands */
+ install_element_ve(&show_sccp_cmd);
+ install_element_ve(&show_bsc_cmd);
+ install_element_ve(&show_bsc_cfg_cmd);
+ install_element_ve(&show_stats_cmd);
+ install_element_ve(&show_stats_lac_cmd);
+ install_element_ve(&close_bsc_cmd);
+ install_element_ve(&show_msc_cmd);
+ install_element_ve(&test_regex_cmd);
+ install_element_ve(&show_bsc_mgcp_cmd);
+ install_element_ve(&show_acc_lst_cmd);
+
+ install_element(ENABLE_NODE, &set_last_endp_cmd);
+
+ /* nat group */
+ install_element(CONFIG_NODE, &cfg_nat_cmd);
+ install_node(&nat_node, config_write_nat);
+ install_default(NAT_NODE);
+ install_element(NAT_NODE, &ournode_exit_cmd);
+ install_element(NAT_NODE, &ournode_end_cmd);
+ install_element(NAT_NODE, &cfg_nat_msc_ip_cmd);
+ install_element(NAT_NODE, &cfg_nat_msc_port_cmd);
+ install_element(NAT_NODE, &cfg_nat_auth_time_cmd);
+ install_element(NAT_NODE, &cfg_nat_ping_time_cmd);
+ install_element(NAT_NODE, &cfg_nat_pong_time_cmd);
+ install_element(NAT_NODE, &cfg_nat_token_cmd);
+ install_element(NAT_NODE, &cfg_nat_bsc_ip_dscp_cmd);
+ install_element(NAT_NODE, &cfg_nat_bsc_ip_tos_cmd);
+ install_element(NAT_NODE, &cfg_nat_acc_lst_name_cmd);
+ install_element(NAT_NODE, &cfg_nat_ussd_lst_name_cmd);
+ install_element(NAT_NODE, &cfg_nat_ussd_query_cmd);
+ install_element(NAT_NODE, &cfg_nat_ussd_token_cmd);
+ install_element(NAT_NODE, &cfg_nat_ussd_local_cmd);
+
+ /* access-list */
+ install_element(NAT_NODE, &cfg_lst_imsi_allow_cmd);
+ install_element(NAT_NODE, &cfg_lst_imsi_deny_cmd);
+ install_element(NAT_NODE, &cfg_lst_no_cmd);
+
+ /* number rewriting */
+ install_element(NAT_NODE, &cfg_nat_number_rewrite_cmd);
+
+ /* BSC subgroups */
+ install_element(NAT_NODE, &cfg_bsc_cmd);
+ install_node(&bsc_node, config_write_bsc);
+ install_default(NAT_BSC_NODE);
+ install_element(NAT_BSC_NODE, &ournode_exit_cmd);
+ install_element(NAT_BSC_NODE, &ournode_end_cmd);
+ install_element(NAT_BSC_NODE, &cfg_bsc_token_cmd);
+ install_element(NAT_BSC_NODE, &cfg_bsc_lac_cmd);
+ install_element(NAT_BSC_NODE, &cfg_bsc_no_lac_cmd);
+ install_element(NAT_BSC_NODE, &cfg_bsc_paging_cmd);
+ install_element(NAT_BSC_NODE, &cfg_bsc_desc_cmd);
+ install_element(NAT_BSC_NODE, &cfg_bsc_acc_lst_name_cmd);
+ install_element(NAT_BSC_NODE, &cfg_bsc_max_endps_cmd);
+
+ mgcp_vty_init();
+
+ return 0;
+}
+
+
+/* called by the telnet interface... we have our own init above */
+int bsc_vty_init(void)
+{
+ return 0;
+}
diff --git a/openbsc/src/osmo-bsc_nat/bsc_sccp.c b/openbsc/src/osmo-bsc_nat/bsc_sccp.c
new file mode 100644
index 000000000..72de11201
--- /dev/null
+++ b/openbsc/src/osmo-bsc_nat/bsc_sccp.c
@@ -0,0 +1,249 @@
+/* SCCP patching and handling routines */
+/*
+ * (C) 2010 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * (C) 2010 by On-Waves
+ * 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 <openbsc/debug.h>
+#include <openbsc/bsc_nat.h>
+#include <openbsc/bsc_nat_sccp.h>
+
+#include <osmocom/sccp/sccp.h>
+
+#include <osmocore/talloc.h>
+
+#include <string.h>
+#include <time.h>
+
+static int equal(struct sccp_source_reference *ref1, struct sccp_source_reference *ref2)
+{
+ return memcmp(ref1, ref2, sizeof(*ref1)) == 0;
+}
+
+/*
+ * SCCP patching below
+ */
+
+/* check if we are using this ref for patched already */
+static int sccp_ref_is_free(struct sccp_source_reference *ref, struct bsc_nat *nat)
+{
+ struct sccp_connections *conn;
+
+ llist_for_each_entry(conn, &nat->sccp_connections, list_entry) {
+ if (memcmp(ref, &conn->patched_ref, sizeof(*ref)) == 0)
+ return -1;
+ }
+
+ return 0;
+}
+
+/* copied from sccp.c */
+static int assign_src_local_reference(struct sccp_source_reference *ref, struct bsc_nat *nat)
+{
+ static uint32_t last_ref = 0x50000;
+ int wrapped = 0;
+
+ do {
+ struct sccp_source_reference reference;
+ reference.octet1 = (last_ref >> 0) & 0xff;
+ reference.octet2 = (last_ref >> 8) & 0xff;
+ reference.octet3 = (last_ref >> 16) & 0xff;
+
+ ++last_ref;
+ /* do not use the reversed word and wrap around */
+ if ((last_ref & 0x00FFFFFF) == 0x00FFFFFF) {
+ LOGP(DNAT, LOGL_NOTICE, "Wrapped searching for a free code\n");
+ last_ref = 0;
+ ++wrapped;
+ }
+
+ if (sccp_ref_is_free(&reference, nat) == 0) {
+ *ref = reference;
+ return 0;
+ }
+ } while (wrapped != 2);
+
+ LOGP(DNAT, LOGL_ERROR, "Finding a free reference failed\n");
+ return -1;
+}
+
+struct sccp_connections *create_sccp_src_ref(struct bsc_connection *bsc,
+ struct bsc_nat_parsed *parsed)
+{
+ struct sccp_connections *conn;
+
+ /* Some commercial BSCs like to reassign there SRC ref */
+ llist_for_each_entry(conn, &bsc->nat->sccp_connections, list_entry) {
+ if (conn->bsc != bsc)
+ continue;
+ if (memcmp(&conn->real_ref, parsed->src_local_ref, sizeof(conn->real_ref)) != 0)
+ continue;
+
+ /* the BSC has reassigned the SRC ref and we failed to keep track */
+ memset(&conn->remote_ref, 0, sizeof(conn->remote_ref));
+ if (assign_src_local_reference(&conn->patched_ref, bsc->nat) != 0) {
+ LOGP(DNAT, LOGL_ERROR, "BSC %d reused src ref: %d and we failed to generate a new id.\n",
+ bsc->cfg->nr, sccp_src_ref_to_int(parsed->src_local_ref));
+ bsc_mgcp_dlcx(conn);
+ llist_del(&conn->list_entry);
+ talloc_free(conn);
+ return NULL;
+ } else {
+ clock_gettime(CLOCK_MONOTONIC, &conn->creation_time);
+ bsc_mgcp_dlcx(conn);
+ return conn;
+ }
+ }
+
+
+ conn = talloc_zero(bsc->nat, struct sccp_connections);
+ if (!conn) {
+ LOGP(DNAT, LOGL_ERROR, "Memory allocation failure.\n");
+ return NULL;
+ }
+
+ conn->bsc = bsc;
+ clock_gettime(CLOCK_MONOTONIC, &conn->creation_time);
+ conn->real_ref = *parsed->src_local_ref;
+ if (assign_src_local_reference(&conn->patched_ref, bsc->nat) != 0) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to assign a ref.\n");
+ talloc_free(conn);
+ return NULL;
+ }
+
+ bsc_mgcp_init(conn);
+ llist_add_tail(&conn->list_entry, &bsc->nat->sccp_connections);
+ rate_ctr_inc(&bsc->cfg->stats.ctrg->ctr[BCFG_CTR_SCCP_CONN]);
+ counter_inc(bsc->cfg->nat->stats.sccp.conn);
+
+ LOGP(DNAT, LOGL_DEBUG, "Created 0x%x <-> 0x%x mapping for con %p\n",
+ sccp_src_ref_to_int(&conn->real_ref),
+ sccp_src_ref_to_int(&conn->patched_ref), bsc);
+
+ return conn;
+}
+
+int update_sccp_src_ref(struct sccp_connections *sccp, struct bsc_nat_parsed *parsed)
+{
+ if (!parsed->dest_local_ref || !parsed->src_local_ref) {
+ LOGP(DNAT, LOGL_ERROR, "CC MSG should contain both local and dest address.\n");
+ return -1;
+ }
+
+ sccp->remote_ref = *parsed->src_local_ref;
+ sccp->has_remote_ref = 1;
+ LOGP(DNAT, LOGL_DEBUG, "Updating 0x%x to remote 0x%x on %p\n",
+ sccp_src_ref_to_int(&sccp->patched_ref),
+ sccp_src_ref_to_int(&sccp->remote_ref), sccp->bsc);
+
+ return 0;
+}
+
+void remove_sccp_src_ref(struct bsc_connection *bsc, struct msgb *msg, struct bsc_nat_parsed *parsed)
+{
+ struct sccp_connections *conn;
+
+ llist_for_each_entry(conn, &bsc->nat->sccp_connections, list_entry) {
+ if (memcmp(parsed->src_local_ref,
+ &conn->patched_ref, sizeof(conn->patched_ref)) == 0) {
+
+ sccp_connection_destroy(conn);
+ return;
+ }
+ }
+
+ LOGP(DNAT, LOGL_ERROR, "Can not remove connection: 0x%x\n",
+ sccp_src_ref_to_int(parsed->src_local_ref));
+}
+
+/*
+ * We have a message from the MSC to the BSC. The MSC is using
+ * an address that was assigned by the MUX, we need to update the
+ * dest reference to the real network.
+ */
+struct sccp_connections *patch_sccp_src_ref_to_bsc(struct msgb *msg,
+ struct bsc_nat_parsed *parsed,
+ struct bsc_nat *nat)
+{
+ struct sccp_connections *conn;
+
+ if (!parsed->dest_local_ref) {
+ LOGP(DNAT, LOGL_ERROR, "MSG should contain dest_local_ref.\n");
+ return NULL;
+ }
+
+
+ llist_for_each_entry(conn, &nat->sccp_connections, list_entry) {
+ if (!equal(parsed->dest_local_ref, &conn->patched_ref))
+ continue;
+
+ /* Change the dest address to the real one */
+ *parsed->dest_local_ref = conn->real_ref;
+ return conn;
+ }
+
+ return NULL;
+}
+
+/*
+ * These are message to the MSC. We will need to find the BSC
+ * Connection by either the SRC or the DST local reference.
+ *
+ * In case of a CR we need to work by the SRC local reference
+ * in all other cases we need to work by the destination local
+ * reference..
+ */
+struct sccp_connections *patch_sccp_src_ref_to_msc(struct msgb *msg,
+ struct bsc_nat_parsed *parsed,
+ struct bsc_connection *bsc)
+{
+ struct sccp_connections *conn;
+
+ llist_for_each_entry(conn, &bsc->nat->sccp_connections, list_entry) {
+ if (conn->bsc != bsc)
+ continue;
+
+ if (parsed->src_local_ref) {
+ if (equal(parsed->src_local_ref, &conn->real_ref)) {
+ *parsed->src_local_ref = conn->patched_ref;
+ return conn;
+ }
+ } else if (parsed->dest_local_ref) {
+ if (equal(parsed->dest_local_ref, &conn->remote_ref))
+ return conn;
+ } else {
+ LOGP(DNAT, LOGL_ERROR, "Header has neither loc/dst ref.\n");
+ return NULL;
+ }
+ }
+
+ return NULL;
+}
+
+struct sccp_connections *bsc_nat_find_con_by_bsc(struct bsc_nat *nat,
+ struct sccp_source_reference *ref)
+{
+ struct sccp_connections *conn;
+
+ llist_for_each_entry(conn, &nat->sccp_connections, list_entry) {
+ if (memcmp(ref, &conn->real_ref, sizeof(*ref)) == 0)
+ return conn;
+ }
+
+ return NULL;
+}
diff --git a/openbsc/src/osmo-bsc_nat/bsc_ussd.c b/openbsc/src/osmo-bsc_nat/bsc_ussd.c
new file mode 100644
index 000000000..c121abe5d
--- /dev/null
+++ b/openbsc/src/osmo-bsc_nat/bsc_ussd.c
@@ -0,0 +1,363 @@
+/* USSD Filter Code */
+
+/*
+ * (C) 2010 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * (C) 2010 by On-Waves
+ * 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 <openbsc/bsc_nat.h>
+#include <openbsc/bsc_nat_sccp.h>
+#include <openbsc/ipaccess.h>
+#include <openbsc/socket.h>
+
+#include <osmocore/protocol/gsm_08_08.h>
+#include <osmocore/gsm0480.h>
+#include <osmocore/talloc.h>
+#include <osmocore/tlv.h>
+
+#include <osmocom/sccp/sccp.h>
+
+#include <sys/socket.h>
+#include <string.h>
+#include <unistd.h>
+
+struct bsc_nat_ussd_con {
+ struct write_queue queue;
+ struct bsc_nat *nat;
+ int authorized;
+
+ struct timer_list auth_timeout;
+};
+
+static void ussd_auth_con(struct tlv_parsed *, struct bsc_nat_ussd_con *);
+
+static struct bsc_nat_ussd_con *bsc_nat_ussd_alloc(struct bsc_nat *nat)
+{
+ struct bsc_nat_ussd_con *con;
+
+ con = talloc_zero(nat, struct bsc_nat_ussd_con);
+ if (!con)
+ return NULL;
+
+ con->nat = nat;
+ return con;
+}
+
+static void bsc_nat_ussd_destroy(struct bsc_nat_ussd_con *con)
+{
+ if (con->nat->ussd_con == con) {
+ bsc_close_ussd_connections(con->nat);
+ con->nat->ussd_con = NULL;
+ }
+
+ close(con->queue.bfd.fd);
+ bsc_unregister_fd(&con->queue.bfd);
+ bsc_del_timer(&con->auth_timeout);
+ write_queue_clear(&con->queue);
+ talloc_free(con);
+}
+
+static int forward_sccp(struct bsc_nat *nat, struct msgb *msg)
+{
+ struct sccp_connections *con;
+ struct bsc_nat_parsed *parsed;
+
+
+ parsed = bsc_nat_parse(msg);
+ if (!parsed) {
+ LOGP(DNAT, LOGL_ERROR, "Can not parse msg from USSD.\n");
+ msgb_free(msg);
+ return -1;
+ }
+
+ if (!parsed->dest_local_ref) {
+ LOGP(DNAT, LOGL_ERROR, "No destination local reference.\n");
+ msgb_free(msg);
+ return -1;
+ }
+
+ con = bsc_nat_find_con_by_bsc(nat, parsed->dest_local_ref);
+ if (!con || !con->bsc) {
+ LOGP(DNAT, LOGL_ERROR, "No active connection found.\n");
+ msgb_free(msg);
+ return -1;
+ }
+
+ talloc_free(parsed);
+ bsc_write_msg(&con->bsc->write_queue, msg);
+ return 0;
+}
+
+static int ussd_read_cb(struct bsc_fd *bfd)
+{
+ int error;
+ struct bsc_nat_ussd_con *conn = bfd->data;
+ struct msgb *msg = ipaccess_read_msg(bfd, &error);
+ struct ipaccess_head *hh;
+
+ if (!msg) {
+ LOGP(DNAT, LOGL_ERROR, "USSD Connection was lost.\n");
+ bsc_nat_ussd_destroy(conn);
+ return -1;
+ }
+
+ LOGP(DNAT, LOGL_NOTICE, "MSG from USSD: %s proto: %d\n",
+ hexdump(msg->data, msg->len), msg->l2h[0]);
+ hh = (struct ipaccess_head *) msg->data;
+
+ if (hh->proto == IPAC_PROTO_IPACCESS) {
+ if (msg->l2h[0] == IPAC_MSGT_ID_RESP) {
+ struct tlv_parsed tvp;
+ ipaccess_idtag_parse(&tvp,
+ (unsigned char *) msg->l2h + 2,
+ msgb_l2len(msg) - 2);
+ if (TLVP_PRESENT(&tvp, IPAC_IDTAG_UNITNAME))
+ ussd_auth_con(&tvp, conn);
+ }
+
+ msgb_free(msg);
+ } else if (hh->proto == IPAC_PROTO_SCCP) {
+ forward_sccp(conn->nat, msg);
+ } else {
+ msgb_free(msg);
+ }
+
+ return 0;
+}
+
+static void ussd_auth_cb(void *_data)
+{
+ LOGP(DNAT, LOGL_ERROR, "USSD module didn't authenticate\n");
+ bsc_nat_ussd_destroy((struct bsc_nat_ussd_con *) _data);
+}
+
+static void ussd_auth_con(struct tlv_parsed *tvp, struct bsc_nat_ussd_con *conn)
+{
+ const char *token;
+ int len;
+ if (!conn->nat->ussd_token) {
+ LOGP(DNAT, LOGL_ERROR, "No USSD token set. Closing\n");
+ bsc_nat_ussd_destroy(conn);
+ return;
+ }
+
+ token = (const char *) TLVP_VAL(tvp, IPAC_IDTAG_UNITNAME);
+ len = TLVP_LEN(tvp, IPAC_IDTAG_UNITNAME);
+ if (strncmp(conn->nat->ussd_token, token, len) != 0) {
+ LOGP(DNAT, LOGL_ERROR, "Wrong USSD token by client: %d\n",
+ conn->queue.bfd.fd);
+ bsc_nat_ussd_destroy(conn);
+ return;
+ }
+
+ /* it is authenticated now */
+ if (conn->nat->ussd_con && conn->nat->ussd_con != conn)
+ bsc_nat_ussd_destroy(conn->nat->ussd_con);
+
+ LOGP(DNAT, LOGL_ERROR, "USSD token specified. USSD provider is connected.\n");
+ bsc_del_timer(&conn->auth_timeout);
+ conn->authorized = 1;
+ conn->nat->ussd_con = conn;
+}
+
+static void ussd_start_auth(struct bsc_nat_ussd_con *conn)
+{
+ struct msgb *msg;
+
+ conn->auth_timeout.data = conn;
+ conn->auth_timeout.cb = ussd_auth_cb;
+ bsc_schedule_timer(&conn->auth_timeout, conn->nat->auth_timeout, 0);
+
+ msg = msgb_alloc_headroom(4096, 128, "auth message");
+ if (!msg) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate auth msg\n");
+ return;
+ }
+
+ msgb_v_put(msg, IPAC_MSGT_ID_GET);
+ bsc_do_write(&conn->queue, msg, IPAC_PROTO_IPACCESS);
+}
+
+static int ussd_listen_cb(struct bsc_fd *bfd, unsigned int what)
+{
+ struct bsc_nat_ussd_con *conn;
+ struct bsc_nat *nat;
+ struct sockaddr_in sa;
+ socklen_t sa_len = sizeof(sa);
+ int fd;
+
+ if (!(what & BSC_FD_READ))
+ return 0;
+
+ fd = accept(bfd->fd, (struct sockaddr *) &sa, &sa_len);
+ if (fd < 0) {
+ perror("accept");
+ return fd;
+ }
+
+ nat = (struct bsc_nat *) bfd->data;
+ counter_inc(nat->stats.ussd.reconn);
+
+ conn = bsc_nat_ussd_alloc(nat);
+ if (!conn) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to allocate USSD con struct.\n");
+ close(fd);
+ return -1;
+ }
+
+ write_queue_init(&conn->queue, 10);
+ conn->queue.bfd.data = conn;
+ conn->queue.bfd.fd = fd;
+ conn->queue.bfd.when = BSC_FD_READ;
+ conn->queue.read_cb = ussd_read_cb;
+ conn->queue.write_cb = bsc_write_cb;
+
+ if (bsc_register_fd(&conn->queue.bfd) < 0) {
+ LOGP(DNAT, LOGL_ERROR, "Failed to register USSD fd.\n");
+ bsc_nat_ussd_destroy(conn);
+ return -1;
+ }
+
+ LOGP(DNAT, LOGL_NOTICE, "USSD Connection on %d with IP: %s\n",
+ fd, inet_ntoa(sa.sin_addr));
+
+ /* do authentication */
+ ussd_start_auth(conn);
+ return 0;
+}
+
+int bsc_ussd_init(struct bsc_nat *nat)
+{
+ struct in_addr addr;
+
+ addr.s_addr = INADDR_ANY;
+ if (nat->ussd_local)
+ inet_aton(nat->ussd_local, &addr);
+
+ nat->ussd_listen.data = nat;
+ return make_sock(&nat->ussd_listen, IPPROTO_TCP,
+ ntohl(addr.s_addr), 5001, ussd_listen_cb);
+}
+
+static int forward_ussd(struct sccp_connections *con, const struct ussd_request *req,
+ struct msgb *input)
+{
+ struct msgb *msg, *copy;
+ struct ipac_msgt_sccp_state *state;
+ struct bsc_nat_ussd_con *ussd;
+
+ if (!con->bsc->nat->ussd_con)
+ return -1;
+
+ msg = msgb_alloc_headroom(4096, 128, "forward ussd");
+ if (!msg) {
+ LOGP(DNAT, LOGL_ERROR, "Allocation failed, not forwarding.\n");
+ return -1;
+ }
+
+ copy = msgb_alloc_headroom(4096, 128, "forward bts");
+ if (!copy) {
+ LOGP(DNAT, LOGL_ERROR, "Allocation failed, not forwarding.\n");
+ msgb_free(msg);
+ return -1;
+ }
+
+ copy->l2h = msgb_put(copy, msgb_l2len(input));
+ memcpy(copy->l2h, input->l2h, msgb_l2len(input));
+
+ msg->l2h = msgb_put(msg, 1);
+ msg->l2h[0] = IPAC_MSGT_SCCP_OLD;
+
+ /* fill out the data */
+ state = (struct ipac_msgt_sccp_state *) msgb_put(msg, sizeof(*state));
+ state->trans_id = req->transaction_id;
+ state->invoke_id = req->invoke_id;
+ memcpy(&state->src_ref, &con->remote_ref, sizeof(con->remote_ref));
+ memcpy(&state->dst_ref, &con->real_ref, sizeof(con->real_ref));
+ memcpy(state->imsi, con->imsi, strlen(con->imsi));
+
+ ussd = con->bsc->nat->ussd_con;
+ bsc_do_write(&ussd->queue, msg, IPAC_PROTO_IPACCESS);
+ bsc_do_write(&ussd->queue, copy, IPAC_PROTO_SCCP);
+
+ return 0;
+}
+
+int bsc_check_ussd(struct sccp_connections *con, struct bsc_nat_parsed *parsed,
+ struct msgb *msg)
+{
+ uint32_t len;
+ uint8_t msg_type;
+ struct gsm48_hdr *hdr48;
+ struct bsc_nat_acc_lst *lst;
+ struct ussd_request req;
+
+ /*
+ * various checks to avoid the decoding work. Right now we only want to
+ * decode if the connection was created for USSD, we do have a USSD access
+ * list, a query, a IMSI and such...
+ */
+ if (con->con_type != NAT_CON_TYPE_SSA)
+ return 0;
+
+ if (!con->imsi)
+ return 0;
+
+ if (!con->bsc->nat->ussd_lst_name)
+ return 0;
+ if (!con->bsc->nat->ussd_query)
+ return 0;
+
+ if (parsed->bssap != BSSAP_MSG_DTAP)
+ return 0;
+
+ if (strlen(con->imsi) > GSM_IMSI_LENGTH)
+ return 0;
+
+ hdr48 = bsc_unpack_dtap(parsed, msg, &len);
+ if (!hdr48)
+ return 0;
+
+ msg_type = hdr48->msg_type & 0xbf;
+ if (hdr48->proto_discr != GSM48_PDISC_NC_SS || msg_type != GSM0480_MTYPE_REGISTER)
+ return 0;
+
+ /* now check if it is a IMSI we care about */
+ lst = bsc_nat_acc_lst_find(con->bsc->nat, con->bsc->nat->ussd_lst_name);
+ if (!lst)
+ return 0;
+
+ if (bsc_nat_lst_check_allow(lst, con->imsi) != 0)
+ return 0;
+
+ /* now decode the message and see if we really want to handle it */
+ memset(&req, 0, sizeof(req));
+ if (gsm0480_decode_ussd_request(hdr48, len, &req) != 1)
+ return 0;
+ if (req.text[0] == 0xff)
+ return 0;
+
+ if (strcmp(req.text, con->bsc->nat->ussd_query) != 0)
+ return 0;
+
+ /* found a USSD query for our subscriber */
+ LOGP(DNAT, LOGL_NOTICE, "Found USSD query for %s\n", con->imsi);
+ if (forward_ussd(con, &req, msg) != 0)
+ return 0;
+ return 1;
+}