diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/Makefile.am | 34 | ||||
-rw-r--r-- | src/e1_input.c | 842 | ||||
-rw-r--r-- | src/e1_input_vty.c | 399 | ||||
-rw-r--r-- | src/init.c | 29 | ||||
-rw-r--r-- | src/input/dahdi.c | 749 | ||||
-rw-r--r-- | src/input/ipa.c | 516 | ||||
-rw-r--r-- | src/input/ipaccess.c | 980 | ||||
-rw-r--r-- | src/input/lapd.c | 710 | ||||
-rw-r--r-- | src/input/lapd_pcap.c | 178 | ||||
-rw-r--r-- | src/input/misdn.c | 788 | ||||
-rw-r--r-- | src/input/rs232.c | 300 | ||||
-rw-r--r-- | src/input/unixsocket.c | 346 | ||||
-rw-r--r-- | src/ipa_proxy.c | 658 | ||||
-rw-r--r-- | src/subchan_demux.c | 353 | ||||
-rw-r--r-- | src/trau/osmo_ortp.c | 655 | ||||
-rw-r--r-- | src/trau_frame.c | 328 |
16 files changed, 7865 insertions, 0 deletions
diff --git a/src/Makefile.am b/src/Makefile.am new file mode 100644 index 0000000..7395d17 --- /dev/null +++ b/src/Makefile.am @@ -0,0 +1,34 @@ +# This is _NOT_ the library release version, it's an API version. +# Please read chapter "Library interface versions" of the libtool documentation +# before making any modifications: https://www.gnu.org/software/libtool/manual/html_node/Versioning.html +ABIS_LIBVERSION=6:0:0 +TRAU_LIBVERSION=2:0:0 + +AM_CPPFLAGS = $(all_includes) -I$(top_srcdir)/include -I$(top_builddir) +AM_CFLAGS= -Wall $(LIBOSMOCORE_CFLAGS) $(LIBOSMOGSM_CFLAGS) $(LIBOSMOVTY_CFLAGS) $(COVERAGE_CFLAGS) +AM_LDFLAGS = $(COVERAGE_LDFLAGS) +COMMONLIBS = $(LIBOSMOCORE_LIBS) $(LIBOSMOGSM_LIBS) $(LIBOSMOVTY_LIBS) + +lib_LTLIBRARIES = libosmoabis.la libosmotrau.la + +libosmoabis_la_LDFLAGS = $(AM_LDFLAGS) -version-info $(ABIS_LIBVERSION) +libosmoabis_la_LIBADD = $(COMMONLIBS) +libosmoabis_la_SOURCES = init.c \ + e1_input.c \ + e1_input_vty.c \ + ipa_proxy.c \ + subchan_demux.c \ + trau_frame.c \ + input/dahdi.c \ + input/ipa.c \ + input/ipaccess.c \ + input/lapd.c \ + input/lapd_pcap.c \ + input/misdn.c \ + input/rs232.c \ + input/unixsocket.c + +libosmotrau_la_CFLAGS = $(AM_CFLAGS) $(ORTP_CFLAGS) +libosmotrau_la_LDFLAGS = $(AM_LDFLAGS) -version-info $(TRAU_LIBVERSION) +libosmotrau_la_LIBADD = $(COMMONLIBS) $(ORTP_LIBS) +libosmotrau_la_SOURCES = trau/osmo_ortp.c diff --git a/src/e1_input.c b/src/e1_input.c new file mode 100644 index 0000000..3cf810f --- /dev/null +++ b/src/e1_input.c @@ -0,0 +1,842 @@ +/* OpenBSC Abis interface to E1 */ + +/* (C) 2008-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 "internal.h" +#include "../config.h" + +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> +#include <errno.h> +#include <string.h> +#include <time.h> +#include <fcntl.h> +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <arpa/inet.h> + +#include <osmocom/abis/lapd.h> + +#include <osmocom/core/linuxlist.h> +#include <osmocom/core/talloc.h> +#include <osmocom/core/rate_ctr.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/signal.h> +#include <osmocom/abis/e1_input.h> + +#define NUM_E1_TS 32 + +static void *tall_e1inp_ctx; + +/* list of all E1 drivers */ +LLIST_HEAD(e1inp_driver_list); + +/* list of all E1 lines */ +LLIST_HEAD(e1inp_line_list); + +static void *tall_sigl_ctx; + +static const struct rate_ctr_desc e1inp_ctr_d[] = { + [E1I_CTR_HDLC_ABORT] = { + "hdlc.abort", "HDLC abort" + }, + [E1I_CTR_HDLC_BADFCS] = { + "hdlc.bad_fcs", "HLDC Bad FCS" + }, + [E1I_CTR_HDLC_OVERR] = { + "hdlc.overrun", "HDLC Overrun" + }, + [E1I_CTR_ALARM] = { + "alarm", "Alarm" + }, + [E1I_CTR_REMOVED] = { + "removed", "Line removed" + }, +}; + +static const struct rate_ctr_group_desc e1inp_ctr_g_d = { + .group_name_prefix = "e1inp", + .group_description = "E1 Input subsystem", + .num_ctr = ARRAY_SIZE(e1inp_ctr_d), + .ctr_desc = e1inp_ctr_d, +}; + +/* + * pcap writing of the misdn load + * pcap format is from http://wiki.wireshark.org/Development/LibpcapFileFormat + */ +#define DLT_LINUX_LAPD 177 +#define PCAP_INPUT 0 +#define PCAP_OUTPUT 1 + +struct pcap_hdr { + uint32_t magic_number; + uint16_t version_major; + uint16_t version_minor; + int32_t thiszone; + uint32_t sigfigs; + uint32_t snaplen; + uint32_t network; +} __attribute__((packed)); + +struct pcaprec_hdr { + uint32_t ts_sec; + uint32_t ts_usec; + uint32_t incl_len; + uint32_t orig_len; +} __attribute__((packed)); + +struct fake_linux_lapd_header { + uint16_t pkttype; + uint16_t hatype; + uint16_t halen; + uint64_t addr; + int16_t protocol; +} __attribute__((packed)); + +struct lapd_header { + uint8_t ea1 : 1; + uint8_t cr : 1; + uint8_t sapi : 6; + uint8_t ea2 : 1; + uint8_t tei : 7; + uint8_t control_foo; /* fake UM's ... */ +} __attribute__((packed)); + +osmo_static_assert(offsetof(struct fake_linux_lapd_header, hatype) == 2, hatype_offset); +osmo_static_assert(offsetof(struct fake_linux_lapd_header, halen) == 4, halen_offset); +osmo_static_assert(offsetof(struct fake_linux_lapd_header, addr) == 6, addr_offset); +osmo_static_assert(offsetof(struct fake_linux_lapd_header, protocol) == 14, proto_offset); +osmo_static_assert(sizeof(struct fake_linux_lapd_header) == 16, lapd_header_size); + + +static int pcap_fd = -1; + +int e1_set_pcap_fd(int fd) +{ + struct pcap_hdr header = { + .magic_number = 0xa1b2c3d4, + .version_major = 2, + .version_minor = 4, + .thiszone = 0, + .sigfigs = 0, + .snaplen = 65535, + .network = DLT_LINUX_LAPD, + }; + + pcap_fd = fd; + return write(pcap_fd, &header, sizeof(header)); +} + +/* This currently only works for the D-Channel */ +static void write_pcap_packet(int direction, int sapi, int tei, + struct msgb *msg) { + if (pcap_fd < 0) + return; + + time_t cur_time; + struct tm *tm; + + struct fake_linux_lapd_header header = { + .pkttype = 4, + .hatype = 0, + .halen = 0, + .addr = direction == PCAP_OUTPUT ? 0x0 : 0x1, + .protocol = ntohs(48), + }; + + struct lapd_header lapd_header = { + .ea1 = 0, + .cr = direction == PCAP_OUTPUT ? 1 : 0, + .sapi = sapi & 0x3F, + .ea2 = 1, + .tei = tei & 0x7F, + .control_foo = 0x03 /* UI */, + }; + + struct pcaprec_hdr payload_header = { + .ts_sec = 0, + .ts_usec = 0, + .incl_len = msgb_l2len(msg) + sizeof(struct fake_linux_lapd_header) + + sizeof(struct lapd_header), + .orig_len = msgb_l2len(msg) + sizeof(struct fake_linux_lapd_header) + + sizeof(struct lapd_header), + }; + + + cur_time = time(NULL); + tm = localtime(&cur_time); + payload_header.ts_sec = mktime(tm); + + write(pcap_fd, &payload_header, sizeof(payload_header)); + write(pcap_fd, &header, sizeof(header)); + write(pcap_fd, &lapd_header, sizeof(lapd_header)); + write(pcap_fd, msg->l2h, msgb_l2len(msg)); +} + +const struct value_string e1inp_sign_type_names[5] = { + { E1INP_SIGN_NONE, "None" }, + { E1INP_SIGN_OML, "OML" }, + { E1INP_SIGN_RSL, "RSL" }, + { E1INP_SIGN_OSMO, "OSMO" }, + { 0, NULL } +}; + +const char *e1inp_signtype_name(enum e1inp_sign_type tp) +{ + return get_value_string(e1inp_sign_type_names, tp); +} + +const struct value_string e1inp_ts_type_names[6] = { + { E1INP_TS_TYPE_NONE, "None" }, + { E1INP_TS_TYPE_SIGN, "Signalling" }, + { E1INP_TS_TYPE_TRAU, "TRAU" }, + { E1INP_TS_TYPE_RAW, "RAW" }, + { E1INP_TS_TYPE_HDLC, "HDLC" }, + { 0, NULL } +}; + +const char *e1inp_tstype_name(enum e1inp_ts_type tp) +{ + return get_value_string(e1inp_ts_type_names, tp); +} + +int abis_sendmsg(struct msgb *msg) +{ + struct e1inp_sign_link *sign_link = msg->dst; + struct e1inp_driver *e1inp_driver; + struct e1inp_ts *e1i_ts; + + msg->l2h = msg->data; + + /* don't know how to route this message. */ + if (sign_link == NULL) { + LOGP(DLINP, LOGL_ERROR, "abis_sendmsg: msg->dst == NULL: %s\n", + osmo_hexdump(msg->data, msg->len)); + talloc_free(msg); + return -EINVAL; + } + e1i_ts = sign_link->ts; + if (!osmo_timer_pending(&e1i_ts->sign.tx_timer)) { + /* notify the driver we have something to write */ + e1inp_driver = sign_link->ts->line->driver; + e1inp_driver->want_write(e1i_ts); + } + msgb_enqueue(&sign_link->tx_list, msg); + + /* we only need to write a 'Fake LAPD' packet here, if the + * underlying driver hides LAPD from us. If we use the + * libosmocore LAPD implementation, it will take care of writing + * the _actual_ LAPD packet */ + if (!e1i_ts->lapd) { + write_pcap_packet(PCAP_OUTPUT, sign_link->sapi, + sign_link->tei, msg); + } + + return 0; +} + +int abis_rsl_sendmsg(struct msgb *msg) +{ + return abis_sendmsg(msg); +} + +/* Timeslot */ +int e1inp_ts_config_trau(struct e1inp_ts *ts, struct e1inp_line *line, + int (*trau_rcv_cb)(struct subch_demux *dmx, int ch, + uint8_t *data, int len, void *_priv)) +{ + if (ts->type == E1INP_TS_TYPE_TRAU && ts->line && line) + return 0; + + ts->type = E1INP_TS_TYPE_TRAU; + ts->line = line; + + subchan_mux_init(&ts->trau.mux); + ts->trau.demux.out_cb = trau_rcv_cb; + ts->trau.demux.data = ts; + subch_demux_init(&ts->trau.demux); + return 0; +} + +int e1inp_ts_config_sign(struct e1inp_ts *ts, struct e1inp_line *line) +{ + if (ts->type == E1INP_TS_TYPE_SIGN && ts->line && line) + return 0; + + ts->type = E1INP_TS_TYPE_SIGN; + ts->line = line; + + if (line && line->driver) + ts->sign.delay = line->driver->default_delay; + else + ts->sign.delay = 100000; + INIT_LLIST_HEAD(&ts->sign.sign_links); + return 0; +} + +int e1inp_ts_config_raw(struct e1inp_ts *ts, struct e1inp_line *line, + void (*raw_recv_cb)(struct e1inp_ts *ts, + struct msgb *msg)) +{ + if (ts->type == E1INP_TS_TYPE_RAW && ts->line && line) + return 0; + + ts->type = E1INP_TS_TYPE_RAW; + ts->line = line; + ts->raw.recv_cb = raw_recv_cb; + INIT_LLIST_HEAD(&ts->raw.tx_queue); + + return 0; +} + +int e1inp_ts_config_hdlc(struct e1inp_ts *ts, struct e1inp_line *line, + void (*hdlc_recv_cb)(struct e1inp_ts *ts, + struct msgb *msg)) +{ + if (ts->type == E1INP_TS_TYPE_HDLC && ts->line && line) + return 0; + + ts->type = E1INP_TS_TYPE_HDLC; + ts->line = line; + ts->hdlc.recv_cb = hdlc_recv_cb; + INIT_LLIST_HEAD(&ts->hdlc.tx_queue); + + return 0; +} + +struct e1inp_line *e1inp_line_find(uint8_t e1_nr) +{ + struct e1inp_line *e1i_line; + + /* iterate over global list of e1 lines */ + llist_for_each_entry(e1i_line, &e1inp_line_list, list) { + if (e1i_line->num == e1_nr) + return e1i_line; + } + return NULL; +} + +struct e1inp_line * +e1inp_line_create(uint8_t e1_nr, const char *driver_name) +{ + struct e1inp_driver *driver; + struct e1inp_line *line; + int i; + + line = e1inp_line_find(e1_nr); + if (line) { + LOGP(DLINP, LOGL_ERROR, "E1 Line %u already exists\n", + e1_nr); + return NULL; + } + + driver = e1inp_driver_find(driver_name); + if (!driver) { + LOGP(DLINP, LOGL_ERROR, "No such E1 driver '%s'\n", + driver_name); + return NULL; + } + + line = talloc_zero(tall_e1inp_ctx, struct e1inp_line); + if (!line) + return NULL; + + line->driver = driver; + line->num = e1_nr; + + line->rate_ctr = rate_ctr_group_alloc(line, &e1inp_ctr_g_d, line->num); + if (!line->rate_ctr) { + LOGP(DLINP, LOGL_ERROR, "Cannot allocate counter group\n"); + talloc_free(line); + return NULL; + } + + line->num_ts = NUM_E1_TS; + for (i = 0; i < line->num_ts; i++) { + line->ts[i].num = i+1; + line->ts[i].line = line; + } + line->refcnt++; + llist_add_tail(&line->list, &e1inp_line_list); + + return line; +} + +struct e1inp_line * +e1inp_line_clone(void *ctx, struct e1inp_line *line) +{ + struct e1inp_line *clone; + + /* clone virtual E1 line for this new OML link. */ + clone = talloc_zero(ctx, struct e1inp_line); + if (clone == NULL) + return NULL; + + memcpy(clone, line, sizeof(struct e1inp_line)); + clone->refcnt = 1; + return clone; +} + +void e1inp_line_get(struct e1inp_line *line) +{ + line->refcnt++; +} + +void e1inp_line_put(struct e1inp_line *line) +{ + line->refcnt--; + if (line->refcnt == 0) + talloc_free(line); +} + +void +e1inp_line_bind_ops(struct e1inp_line *line, const struct e1inp_line_ops *ops) +{ + line->ops = ops; +} + +#if 0 +struct e1inp_line *e1inp_line_find_create(uint8_t e1_nr) +{ + struct e1inp_line *line; + int i; + + line = e1inp_line_find(e1_nr); + if (line) + return line; + + line = talloc_zero(tall_e1inp_ctx, struct e1inp_line); + if (!line) + return NULL; + + line->num = e1_nr; + for (i = 0; i < NUM_E1_TS; i++) { + line->ts[i].num = i+1; + line->ts[i].line = line; + } + llist_add_tail(&line->list, &e1inp_line_list); + + return line; +} +#endif + +static struct e1inp_ts *e1inp_ts_get(uint8_t e1_nr, uint8_t ts_nr) +{ + struct e1inp_line *e1i_line; + + e1i_line = e1inp_line_find(e1_nr); + if (!e1i_line) + return NULL; + + return &e1i_line->ts[ts_nr-1]; +} + +struct subch_mux *e1inp_get_mux(uint8_t e1_nr, uint8_t ts_nr) +{ + struct e1inp_ts *e1i_ts = e1inp_ts_get(e1_nr, ts_nr); + + if (!e1i_ts) + return NULL; + + return &e1i_ts->trau.mux; +} + +/* Signalling Link */ + +struct e1inp_sign_link *e1inp_lookup_sign_link(struct e1inp_ts *e1i, + uint8_t tei, uint8_t sapi) +{ + struct e1inp_sign_link *link; + + llist_for_each_entry(link, &e1i->sign.sign_links, list) { + if (link->sapi == sapi && link->tei == tei) + return link; + } + + return NULL; +} + +/* create a new signalling link in a E1 timeslot */ + +struct e1inp_sign_link * +e1inp_sign_link_create(struct e1inp_ts *ts, enum e1inp_sign_type type, + struct gsm_bts_trx *trx, uint8_t tei, + uint8_t sapi) +{ + struct e1inp_sign_link *link; + + if (ts->type != E1INP_TS_TYPE_SIGN) + return NULL; + + link = talloc_zero(tall_sigl_ctx, struct e1inp_sign_link); + if (!link) + return NULL; + + link->ts = ts; + link->type = type; + INIT_LLIST_HEAD(&link->tx_list); + link->trx = trx; + link->tei = tei; + link->sapi = sapi; + + llist_add_tail(&link->list, &ts->sign.sign_links); + + return link; +} + +void e1inp_sign_link_destroy(struct e1inp_sign_link *link) +{ + struct msgb *msg; + + llist_del(&link->list); + while (!llist_empty(&link->tx_list)) { + msg = msgb_dequeue(&link->tx_list); + msgb_free(msg); + } + + if (link->ts->type == E1INP_TS_TYPE_SIGN) + osmo_timer_del(&link->ts->sign.tx_timer); + + if (link->ts->line->driver->close) + link->ts->line->driver->close(link); + + e1inp_line_put(link->ts->line); + talloc_free(link); +} + +/* XXX */ +/* the E1 driver tells us he has received something on a TS */ +int e1inp_rx_ts(struct e1inp_ts *ts, struct msgb *msg, + uint8_t tei, uint8_t sapi) +{ + struct e1inp_sign_link *link; + int ret = 0; + + switch (ts->type) { + case E1INP_TS_TYPE_SIGN: + /* we only need to write a 'Fake LAPD' packet here, if + * the underlying driver hides LAPD from us. If we use + * the libosmocore LAPD implementation, it will take + * care of writing the _actual_ LAPD packet */ + if (!ts->lapd) + write_pcap_packet(PCAP_INPUT, sapi, tei, msg); + /* consult the list of signalling links */ + link = e1inp_lookup_sign_link(ts, tei, sapi); + if (!link) { + LOGP(DLMI, LOGL_ERROR, "didn't find signalling link for " + "tei %d, sapi %d\n", tei, sapi); + msgb_free(msg); + return -EINVAL; + } + if (!ts->line->ops->sign_link) { + LOGP(DLINP, LOGL_ERROR, "Fix your application, " + "no action set for signalling messages.\n"); + msgb_free(msg); + return -ENOENT; + } + msg->dst = link; + ts->line->ops->sign_link(msg); + break; + case E1INP_TS_TYPE_TRAU: + ret = subch_demux_in(&ts->trau.demux, msg->l2h, msgb_l2len(msg)); + msgb_free(msg); + break; + case E1INP_TS_TYPE_RAW: + ts->raw.recv_cb(ts, msg); + break; + case E1INP_TS_TYPE_HDLC: + ts->hdlc.recv_cb(ts, msg); + break; + default: + ret = -EINVAL; + LOGP(DLMI, LOGL_ERROR, "unknown TS type %u\n", ts->type); + msgb_free(msg); + break; + } + + return ret; +} + +/*! \brief Receive some data from the L1/HDLC into LAPD of a timeslot + * \param[in] e1i_ts E1 Timeslot data structure + * \param[in] msg Message buffer containing full LAPD message + * + * This is a wrapper around e1inp_rx_ts(), but feeding the incoming + * message first into our LAPD code. This allows a driver to read raw + * (HDLC decoded) data from the timeslot, instead of a LAPD stack + * present in any underlying driver. + */ +int e1inp_rx_ts_lapd(struct e1inp_ts *e1i_ts, struct msgb *msg) +{ + unsigned int sapi, tei; + int ret = 0, error = 0; + + sapi = msg->data[0] >> 2; + if ((msg->data[0] & 0x1)) + tei = 0; + else + tei = msg->data[1] >> 1; + + DEBUGP(DLMI, "<= len = %d, sapi(%d) tei(%d)\n", msg->len, sapi, tei); + + ret = lapd_receive(e1i_ts->lapd, msg, &error); + if (ret < 0) { + switch(error) { + case LAPD_ERR_UNKNOWN_TEI: + /* We don't know about this TEI, probably the BSC + * lost local states (it crashed or it was stopped), + * notify the driver to see if it can do anything to + * recover the existing signalling links with the BTS. + */ + e1inp_event(e1i_ts, S_L_INP_TEI_UNKNOWN, tei, sapi); + return -EIO; + } + } + + return 0; +} + +void e1inp_dlsap_up(struct osmo_dlsap_prim *dp, uint8_t tei, uint8_t sapi, + void *rx_cbdata) +{ + struct e1inp_ts *e1i_ts = rx_cbdata; + struct msgb *msg = dp->oph.msg; + + switch (dp->oph.primitive) { + case PRIM_DL_EST: + DEBUGP(DLMI, "DL_EST: sapi(%d) tei(%d)\n", sapi, tei); + e1inp_event(e1i_ts, S_L_INP_TEI_UP, tei, sapi); + break; + case PRIM_DL_REL: + DEBUGP(DLMI, "DL_REL: sapi(%d) tei(%d)\n", sapi, tei); + e1inp_event(e1i_ts, S_L_INP_TEI_DN, tei, sapi); + break; + case PRIM_DL_DATA: + case PRIM_DL_UNIT_DATA: + if (dp->oph.operation == PRIM_OP_INDICATION) { + msg->l2h = msg->l3h; + DEBUGP(DLMI, "RX: %s sapi=%d tei=%d\n", + osmo_hexdump(msgb_l2(msg), msgb_l2len(msg)), + sapi, tei); + e1inp_rx_ts(e1i_ts, msg, tei, sapi); + return; + } + break; + case PRIM_MDL_ERROR: + DEBUGP(DLMI, "MDL_EERROR: cause(%d)\n", dp->u.error_ind.cause); + break; + default: + printf("ERROR: unknown prim\n"); + break; + } + + msgb_free(msg); + + return; +} + +#define TSX_ALLOC_SIZE 4096 + +/* called by driver if it wants to transmit on a given TS */ +struct msgb *e1inp_tx_ts(struct e1inp_ts *e1i_ts, + struct e1inp_sign_link **sign_link) +{ + struct e1inp_sign_link *link; + struct msgb *msg = NULL; + int len; + + switch (e1i_ts->type) { + case E1INP_TS_TYPE_SIGN: + /* FIXME: implement this round robin */ + llist_for_each_entry(link, &e1i_ts->sign.sign_links, list) { + msg = msgb_dequeue(&link->tx_list); + if (msg) { + if (sign_link) + *sign_link = link; + break; + } + } + break; + case E1INP_TS_TYPE_TRAU: + msg = msgb_alloc(TSX_ALLOC_SIZE, "TRAU_TX"); + if (!msg) + return NULL; + len = subchan_mux_out(&e1i_ts->trau.mux, msg->data, 40); + if (len != 40) { + LOGP(DLMI, LOGL_ERROR, + "cannot transmit, failed to mux\n"); + msgb_free(msg); + return NULL; + } + msgb_put(msg, 40); + break; + case E1INP_TS_TYPE_RAW: + /* Get msgb from tx_queue */ + msg = msgb_dequeue(&e1i_ts->raw.tx_queue); + break; + case E1INP_TS_TYPE_HDLC: + /* Get msgb from tx_queue */ + msg = msgb_dequeue(&e1i_ts->hdlc.tx_queue); + break; + default: + LOGP(DLMI, LOGL_ERROR, "unsupported E1 TS type %u\n", e1i_ts->type); + return NULL; + } + return msg; +} + +static int e1inp_int_snd_event(struct e1inp_ts *ts, + struct e1inp_sign_link *link, int evt) +{ + struct input_signal_data isd; + isd.line = ts->line; + isd.ts_nr = ts->num; + isd.link_type = link->type; + isd.trx = link->trx; + isd.tei = link->tei; + isd.sapi = link->sapi; + + /* report further upwards */ + osmo_signal_dispatch(SS_L_INPUT, evt, &isd); + return 0; +} + + +/* called by driver in case some kind of link state event */ +int e1inp_event(struct e1inp_ts *ts, int evt, uint8_t tei, uint8_t sapi) +{ + struct e1inp_sign_link *link; + + link = e1inp_lookup_sign_link(ts, tei, sapi); + if (!link) + return -EINVAL; + return e1inp_int_snd_event(ts, link, evt); +} + +void e1inp_close_socket(struct e1inp_ts *ts, + struct e1inp_sign_link *sign_link, + struct osmo_fd *bfd) +{ + e1inp_int_snd_event(ts, sign_link, S_L_INP_TEI_DN); + /* the first e1inp_sign_link_destroy call closes the socket. */ + if (bfd->fd != -1) { + osmo_fd_unregister(bfd); + close(bfd->fd); + bfd->fd = -1; + } +} + +/* register a driver with the E1 core */ +int e1inp_driver_register(struct e1inp_driver *drv) +{ + llist_add_tail(&drv->list, &e1inp_driver_list); + return 0; +} + +struct e1inp_driver *e1inp_driver_find(const char *name) +{ + struct e1inp_driver *drv; + + llist_for_each_entry(drv, &e1inp_driver_list, list) { + if (!strcasecmp(name, drv->name)) + return drv; + } + return NULL; +} + +int e1inp_line_update(struct e1inp_line *line) +{ + struct input_signal_data isd; + int i, rc; + + e1inp_line_get(line); + + if (line->driver && line->ops && line->driver->line_update) { + rc = line->driver->line_update(line); + } else + rc = 0; + + /* Set the PCAP file descriptor for all timeslots that have + * software LAPD instances, to ensure the osmo_lapd_pcap code is + * used to write PCAP files (if requested) */ + for (i = 0; i < ARRAY_SIZE(line->ts); i++) { + struct e1inp_ts *e1i_ts = &line->ts[i]; + if (e1i_ts->lapd) + e1i_ts->lapd->pcap_fd = pcap_fd; + } + + /* Send a signal to anyone who is interested in new lines being + * configured */ + memset(&isd, 0, sizeof(isd)); + isd.line = line; + osmo_signal_dispatch(SS_L_INPUT, S_L_INP_LINE_INIT, &isd); + + return rc; +} + +static int e1i_sig_cb(unsigned int subsys, unsigned int signal, + void *handler_data, void *signal_data) +{ + if (subsys != SS_L_GLOBAL || + signal != S_L_GLOBAL_SHUTDOWN) + return 0; + + if (pcap_fd) { + close(pcap_fd); + pcap_fd = -1; + } + + return 0; +} + +const struct value_string e1inp_signal_names[] = { + { S_L_INP_NONE, "NONE" }, + { S_L_INP_TEI_UP, "TEI-UP" }, + { S_L_INP_TEI_DN, "TEI-DOWN" }, + { S_L_INP_TEI_UNKNOWN, "TEI-UNKNOWN" }, + { S_L_INP_LINE_INIT, "LINE-INIT" }, + { S_L_INP_LINE_ALARM, "LINE-ALARM" }, + { S_L_INP_LINE_NOALARM, "LINE-NOALARM" }, + { 0, NULL } +}; + +void e1inp_misdn_init(void); +void e1inp_dahdi_init(void); +void e1inp_ipaccess_init(void); +void e1inp_rs232_init(void); +void e1inp_unixsocket_init(void); + +void e1inp_init(void) +{ + tall_e1inp_ctx = talloc_named_const(libosmo_abis_ctx, 1, "e1inp"); + tall_sigl_ctx = talloc_named_const(tall_e1inp_ctx, 1, + "e1inp_sign_link"); + osmo_signal_register_handler(SS_L_GLOBAL, e1i_sig_cb, NULL); + + e1inp_misdn_init(); +#ifdef HAVE_DAHDI_USER_H + e1inp_dahdi_init(); +#endif + e1inp_ipaccess_init(); + e1inp_rs232_init(); + e1inp_unixsocket_init(); +} diff --git a/src/e1_input_vty.c b/src/e1_input_vty.c new file mode 100644 index 0000000..9d69586 --- /dev/null +++ b/src/e1_input_vty.c @@ -0,0 +1,399 @@ +/* E1 vty interface */ +/* (C) 2011 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 "internal.h" + +#include <stdlib.h> +#include <unistd.h> +#include <string.h> + +#include <osmocom/core/linuxlist.h> +#include <osmocom/core/talloc.h> +#include <osmocom/core/utils.h> +#include <osmocom/gsm/gsm_utils.h> + +#include <osmocom/vty/command.h> +#include <osmocom/vty/buffer.h> +#include <osmocom/vty/vty.h> +#include <osmocom/vty/logging.h> +#include <osmocom/vty/misc.h> +#include <osmocom/vty/telnet_interface.h> + +#include <osmocom/abis/e1_input.h> + +/* CONFIG */ + +#define E1_DRIVER_NAMES "(misdn|misdn_lapd|dahdi|ipa|unixsocket)" +#define E1_DRIVER_HELP "mISDN supported E1 Card (kernel LAPD)\n" \ + "mISDN supported E1 Card (userspace LAPD)\n" \ + "DAHDI supported E1/T1/J1 Card\n" \ + "IPA TCP/IP input\n" \ + "HSL TCP/IP input\n" \ + "Unix socket input\n" + +#define E1_LINE_HELP "Configure E1/T1/J1 Line\n" "Line Number\n" + +DEFUN(cfg_e1line_driver, cfg_e1_line_driver_cmd, + "e1_line <0-255> driver " E1_DRIVER_NAMES, + E1_LINE_HELP "Set driver for this line\n" + E1_DRIVER_HELP) +{ + struct e1inp_line *line; + int e1_nr = atoi(argv[0]); + + line = e1inp_line_find(e1_nr); + if (line) { + vty_out(vty, "%% Line %d already exists%s", e1_nr, VTY_NEWLINE); + return CMD_WARNING; + } + line = e1inp_line_create(e1_nr, argv[1]); + if (!line) { + vty_out(vty, "%% Error creating line %d%s", e1_nr, VTY_NEWLINE); + return CMD_WARNING; + } + + return CMD_SUCCESS; +} + +DEFUN(cfg_e1line_port, cfg_e1_line_port_cmd, + "e1_line <0-255> port <0-255>", + E1_LINE_HELP "Set physical port/span/card number\n" + "E1/T1 Port/Span/Card number\n") +{ + struct e1inp_line *line; + int e1_nr = atoi(argv[0]); + + line = e1inp_line_find(e1_nr); + if (!line) { + vty_out(vty, "%% Line %d doesn't exist%s", e1_nr, VTY_NEWLINE); + return CMD_WARNING; + } + + line->port_nr = atoi(argv[1]); + + return CMD_SUCCESS; +} + +DEFUN(cfg_e1line_socket, cfg_e1_line_socket_cmd, + "e1_line <0-255> socket .SOCKET", + E1_LINE_HELP "Set socket path for unixsocket\n" + "socket path\n") +{ + struct e1inp_line *line; + int e1_nr = atoi(argv[0]); + + line = e1inp_line_find(e1_nr); + if (!line) { + vty_out(vty, "%% Line %d doesn't exist%s", e1_nr, VTY_NEWLINE); + return CMD_WARNING; + } + + line->sock_path = talloc_strdup(line, argv[1]); + + return CMD_SUCCESS; +} + +#define KEEPALIVE_HELP "Enable keep-alive probing\n" +static int set_keepalive_params(struct vty *vty, int e1_nr, + int idle, int num_probes, int probe_interval) +{ + struct e1inp_line *line = e1inp_line_find(e1_nr); + + if (!line) { + vty_out(vty, "%% Line %d doesn't exist%s", e1_nr, VTY_NEWLINE); + return CMD_WARNING; + } + if (!line->driver->has_keepalive && num_probes != 0) { + vty_out(vty, "%% Driver '%s' does not support keep alive%s", + line->driver->name, VTY_NEWLINE); + return CMD_WARNING; + } + + line->keepalive_idle_timeout = idle; + line->keepalive_num_probes = num_probes; + line->keepalive_probe_interval = probe_interval; + + return CMD_SUCCESS; +} + +DEFUN(cfg_e1line_keepalive, cfg_e1_line_keepalive_cmd, + "e1_line <0-255> keepalive", + E1_LINE_HELP KEEPALIVE_HELP) +{ + return set_keepalive_params(vty, atoi(argv[0]), + E1INP_USE_DEFAULT, E1INP_USE_DEFAULT, + E1INP_USE_DEFAULT); +} + +DEFUN(cfg_e1line_keepalive_params, cfg_e1_line_keepalive_params_cmd, + "e1_line <0-255> keepalive <1-300> <1-20> <1-300>", + E1_LINE_HELP KEEPALIVE_HELP + "Idle interval in seconds before probes are sent\n" + "Number of probes to sent\n" + "Delay between probe packets in seconds\n") +{ + return set_keepalive_params(vty, atoi(argv[0]), + atoi(argv[1]), atoi(argv[2]), atoi(argv[3])); +} + +DEFUN(cfg_e1line_no_keepalive, cfg_e1_line_no_keepalive_cmd, + "no e1_line <0-255> keepalive", + NO_STR E1_LINE_HELP KEEPALIVE_HELP) +{ + return set_keepalive_params(vty, atoi(argv[0]), 0, 0, 0); +} + +DEFUN(cfg_e1line_name, cfg_e1_line_name_cmd, + "e1_line <0-255> name .LINE", + E1_LINE_HELP "Set name for this line\n" "Human readable name\n") +{ + struct e1inp_line *line; + int e1_nr = atoi(argv[0]); + + line = e1inp_line_find(e1_nr); + if (!line) { + vty_out(vty, "%% Line %d doesn't exist%s", e1_nr, VTY_NEWLINE); + return CMD_WARNING; + } + if (line->name) { + talloc_free((void *)line->name); + line->name = NULL; + } + line->name = talloc_strdup(line, argv[1]); + + return CMD_SUCCESS; +} + +DEFUN(cfg_e1inp, cfg_e1inp_cmd, + "e1_input", + "Configure E1/T1/J1 TDM input\n") +{ + vty->node = L_E1INP_NODE; + + return CMD_SUCCESS; +} + +DEFUN(cfg_ipa_bind, + cfg_ipa_bind_cmd, + "ipa bind A.B.C.D", + "ipa driver config\n" + "Set ipa local bind address\n" + "Listen on this IP address (default 0.0.0.0)\n") +{ + e1inp_ipa_set_bind_addr(argv[0]); + return CMD_SUCCESS; +} + +static int e1inp_config_write(struct vty *vty) +{ + struct e1inp_line *line; + + if (llist_empty(&e1inp_line_list)) + return CMD_SUCCESS; + + vty_out(vty, "e1_input%s", VTY_NEWLINE); + + llist_for_each_entry(line, &e1inp_line_list, list) { + vty_out(vty, " e1_line %u driver %s%s", line->num, + line->driver->name, VTY_NEWLINE); + vty_out(vty, " e1_line %u port %u%s", line->num, + line->port_nr, VTY_NEWLINE); + if (line->name) + vty_out(vty, " e1_line %u name %s%s", line->num, + line->name, VTY_NEWLINE); + if (!line->keepalive_num_probes) + vty_out(vty, " no e1_line %u keepalive%s", line->num, + VTY_NEWLINE); + else if (line->keepalive_idle_timeout == E1INP_USE_DEFAULT && + line->keepalive_num_probes == E1INP_USE_DEFAULT && + line->keepalive_probe_interval == E1INP_USE_DEFAULT) + vty_out(vty, " e1_line %u keepalive%s", line->num, + VTY_NEWLINE); + else + vty_out(vty, " e1_line %u keepalive %d %d %d%s", + line->num, + line->keepalive_idle_timeout, + line->keepalive_num_probes, + line->keepalive_probe_interval, + VTY_NEWLINE); + + } + + const char *ipa_bind = e1inp_ipa_get_bind_addr(); + if (ipa_bind && (strcmp(ipa_bind, "0.0.0.0") != 0)) + vty_out(vty, " ipa bind %s%s", + ipa_bind, VTY_NEWLINE); + + return CMD_SUCCESS; +} + +/* SHOW */ + +static void e1drv_dump_vty(struct vty *vty, struct e1inp_driver *drv) +{ + vty_out(vty, "E1 Input Driver %s%s", drv->name, VTY_NEWLINE); +} + +DEFUN(show_e1drv, + show_e1drv_cmd, + "show e1_driver", + SHOW_STR "Display information about available E1 drivers\n") +{ + struct e1inp_driver *drv; + + llist_for_each_entry(drv, &e1inp_driver_list, list) + e1drv_dump_vty(vty, drv); + + return CMD_SUCCESS; +} + +static void e1line_dump_vty(struct vty *vty, struct e1inp_line *line, + int stats) +{ + vty_out(vty, "E1 Line Number %u, Name %s, Driver %s%s", + line->num, line->name ? line->name : "", + line->driver->name, VTY_NEWLINE); + if (line->driver->vty_show) + line->driver->vty_show(vty, line); + if (stats) + vty_out_rate_ctr_group(vty, " ", line->rate_ctr); +} + +DEFUN(show_e1line, + show_e1line_cmd, + "show e1_line [line_nr] [stats]", + SHOW_STR "Display information about a E1 line\n" + "E1 Line Number\n" "Include statistics\n") +{ + struct e1inp_line *line; + int stats = 0; + + if (argc >= 1 && strcmp(argv[0], "stats")) { + int num = atoi(argv[0]); + if (argc >= 2) + stats = 1; + llist_for_each_entry(line, &e1inp_line_list, list) { + if (line->num == num) { + e1line_dump_vty(vty, line, stats); + return CMD_SUCCESS; + } + } + return CMD_WARNING; + } + + if (argc >= 1 && !strcmp(argv[0], "stats")) + stats = 1; + + llist_for_each_entry(line, &e1inp_line_list, list) + e1line_dump_vty(vty, line, stats); + + return CMD_SUCCESS; +} + +static void e1ts_dump_vty(struct vty *vty, struct e1inp_ts *ts) +{ + if (ts->type == E1INP_TS_TYPE_NONE) + return; + vty_out(vty, "E1 Timeslot %2u of Line %u is Type %s%s", + ts->num, ts->line->num, e1inp_tstype_name(ts->type), + VTY_NEWLINE); +} + +DEFUN(show_e1ts, + show_e1ts_cmd, + "show e1_timeslot [line_nr] [ts_nr]", + SHOW_STR "Display information about a E1 timeslot\n" + "E1 Line Number\n" "E1 Timeslot Number\n") +{ + struct e1inp_line *line = NULL; + struct e1inp_ts *ts; + int ts_nr; + + if (argc <= 0) { + llist_for_each_entry(line, &e1inp_line_list, list) { + for (ts_nr = 0; ts_nr < line->num_ts; ts_nr++) { + ts = &line->ts[ts_nr]; + e1ts_dump_vty(vty, ts); + } + } + return CMD_SUCCESS; + } + if (argc >= 1) { + int num = atoi(argv[0]); + struct e1inp_line *l; + llist_for_each_entry(l, &e1inp_line_list, list) { + if (l->num == num) { + line = l; + break; + } + } + if (!line) { + vty_out(vty, "E1 line %s is invalid%s", + argv[0], VTY_NEWLINE); + return CMD_WARNING; + } + } + if (argc >= 2) { + ts_nr = atoi(argv[1]); + if (ts_nr >= line->num_ts) { + vty_out(vty, "E1 timeslot %s is invalid%s", + argv[1], VTY_NEWLINE); + return CMD_WARNING; + } + ts = &line->ts[ts_nr]; + e1ts_dump_vty(vty, ts); + return CMD_SUCCESS; + } else { + for (ts_nr = 0; ts_nr < line->num_ts; ts_nr++) { + ts = &line->ts[ts_nr]; + e1ts_dump_vty(vty, ts); + } + return CMD_SUCCESS; + } + return CMD_SUCCESS; +} + + +struct cmd_node e1inp_node = { + L_E1INP_NODE, + "%s(config-e1_input)# ", + 1, +}; + +int e1inp_vty_init(void) +{ + install_element(CONFIG_NODE, &cfg_e1inp_cmd); + install_node(&e1inp_node, e1inp_config_write); + + vty_install_default(L_E1INP_NODE); + install_element(L_E1INP_NODE, &cfg_e1_line_driver_cmd); + install_element(L_E1INP_NODE, &cfg_e1_line_port_cmd); + install_element(L_E1INP_NODE, &cfg_e1_line_socket_cmd); + install_element(L_E1INP_NODE, &cfg_e1_line_name_cmd); + install_element(L_E1INP_NODE, &cfg_e1_line_keepalive_cmd); + install_element(L_E1INP_NODE, &cfg_e1_line_keepalive_params_cmd); + install_element(L_E1INP_NODE, &cfg_e1_line_no_keepalive_cmd); + + install_element(L_E1INP_NODE, &cfg_ipa_bind_cmd); + + install_element_ve(&show_e1drv_cmd); + install_element_ve(&show_e1line_cmd); + install_element_ve(&show_e1ts_cmd); + + return 0; +} diff --git a/src/init.c b/src/init.c new file mode 100644 index 0000000..73453c4 --- /dev/null +++ b/src/init.c @@ -0,0 +1,29 @@ +/* (C) 2011 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 "internal.h" +#include <osmocom/core/utils.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/talloc.h> + +void *libosmo_abis_ctx; + +void libosmo_abis_init(void *ctx) +{ + libosmo_abis_ctx = talloc_named_const(ctx, 0, "abis"); + e1inp_init(); +} diff --git a/src/input/dahdi.c b/src/input/dahdi.c new file mode 100644 index 0000000..911f862 --- /dev/null +++ b/src/input/dahdi.c @@ -0,0 +1,749 @@ +/* OpenBSC Abis input driver for DAHDI */ + +/* (C) 2008-2011 by Harald Welte <laforge@gnumonks.org> + * (C) 2009 by Holger Hans Peter Freyther <zecke@selfish.org> + * (C) 2010 by Digium and Matthew Fredrickson <creslin@digium.com> + * + * All Rights Reserved + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +#include "config.h" + +#ifdef HAVE_DAHDI_USER_H + +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> +#include <errno.h> +#include <string.h> +#include <time.h> +#include <sys/fcntl.h> +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <arpa/inet.h> +#include <dahdi/user.h> + +#include <osmocom/core/talloc.h> +#include <osmocom/core/select.h> +#include <osmocom/core/msgb.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/signal.h> +#include <osmocom/core/rate_ctr.h> + +#include <osmocom/vty/vty.h> + +#include <osmocom/abis/subchan_demux.h> +#include <osmocom/abis/e1_input.h> + +#include <osmocom/abis/lapd.h> + +#define TS1_ALLOC_SIZE 300 + +struct span_cfg { + struct llist_head list; + + unsigned int span_nr; + unsigned int chan_base; + unsigned int chan_num; +}; + +static struct span_cfg *span_cfgs[DAHDI_MAX_SPANS]; + +static int reread_span_cfgs(void) +{ + struct dahdi_spaninfo si; + unsigned int basechan = 1; + int span_nr; + int fd; + + if ((fd = open("/dev/dahdi/ctl", O_RDWR)) < 0) { + LOGP(DLMI, LOGL_ERROR, "Unable to open DAHDI ctl: %s\n", + strerror(errno)); + return -EIO; + } + + for (span_nr = 1; span_nr < DAHDI_MAX_SPANS; span_nr++) { + struct span_cfg *scfg; + /* our array index starts at 0, but DAHDI span at 1 */ + int i = span_nr - 1; + + /* clear any old cached information */ + if (span_cfgs[i]) { + talloc_free(span_cfgs[i]); + span_cfgs[i] = NULL; + } + + memset(&si, 0, sizeof(si)); + si.spanno = span_nr; + if (ioctl(fd, DAHDI_SPANSTAT, &si)) + continue; + + /* create and link new span_cfg */ + scfg = talloc_zero(NULL, struct span_cfg); + if (!scfg) { + close(fd); + return -ENOMEM; + } + scfg->span_nr = span_nr; + scfg->chan_num = si.totalchans; + scfg->chan_base = basechan; + span_cfgs[i] = scfg; + + basechan += si.totalchans; + } + + close(fd); + + return 0; +} + +/* Corresponds to dahdi/user.h, only PRI related events */ +static const struct value_string dahdi_evt_names[] = { + { DAHDI_EVENT_NONE, "NONE" }, + { DAHDI_EVENT_ALARM, "ALARM" }, + { DAHDI_EVENT_NOALARM, "NOALARM" }, + { DAHDI_EVENT_ABORT, "HDLC ABORT" }, + { DAHDI_EVENT_OVERRUN, "HDLC OVERRUN" }, + { DAHDI_EVENT_BADFCS, "HDLC BAD FCS" }, + { DAHDI_EVENT_REMOVED, "REMOVED" }, + { 0, NULL } +}; + +static void handle_dahdi_exception(struct e1inp_ts *ts) +{ + int rc, evt; + struct e1inp_line *line = ts->line; + struct input_signal_data isd; + + rc = ioctl(ts->driver.dahdi.fd.fd, DAHDI_GETEVENT, &evt); + if (rc < 0) + return; + + LOGP(DLMI, LOGL_NOTICE, "Line %u(%s) / TS %u DAHDI EVENT %s\n", + ts->line->num, ts->line->name, ts->num, + get_value_string(dahdi_evt_names, evt)); + + isd.line = ts->line; + isd.ts_nr = ts->num; + + switch (evt) { + case DAHDI_EVENT_ALARM: + /* we should notify the code that the line is gone */ + osmo_signal_dispatch(SS_L_INPUT, S_L_INP_LINE_ALARM, &isd); + rate_ctr_inc(&line->rate_ctr->ctr[E1I_CTR_ALARM]); + break; + case DAHDI_EVENT_NOALARM: + /* alarm has gone, we should re-start the SABM requests */ + osmo_signal_dispatch(SS_L_INPUT, S_L_INP_LINE_NOALARM, &isd); + break; + case DAHDI_EVENT_ABORT: + rate_ctr_inc(&line->rate_ctr->ctr[E1I_CTR_HDLC_ABORT]); + break; + case DAHDI_EVENT_OVERRUN: + rate_ctr_inc(&line->rate_ctr->ctr[E1I_CTR_HDLC_OVERR]); + break; + case DAHDI_EVENT_BADFCS: + rate_ctr_inc(&line->rate_ctr->ctr[E1I_CTR_HDLC_BADFCS]); + break; + case DAHDI_EVENT_REMOVED: + rate_ctr_inc(&line->rate_ctr->ctr[E1I_CTR_REMOVED]); + break; + } +} + +static int handle_ts1_read(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct msgb *msg = msgb_alloc(TS1_ALLOC_SIZE, "DAHDI TS1"); + int ret; + + if (!msg) + return -ENOMEM; + + ret = read(bfd->fd, msg->data, TS1_ALLOC_SIZE - 16); + if (ret == -1) + handle_dahdi_exception(e1i_ts); + else if (ret < 0) { + perror("read "); + } + msgb_put(msg, ret - 2); + if (ret <= 3) { + perror("read "); + } + + return e1inp_rx_ts_lapd(e1i_ts, msg); +} + +static int ts_want_write(struct e1inp_ts *e1i_ts) +{ + /* We never include the DAHDI B-Channel FD into the + * writeset, since it doesn't support poll() based + * write flow control */ + if (e1i_ts->type == E1INP_TS_TYPE_TRAU) { + LOGP(DLINP, LOGL_DEBUG, "Trying to write TRAU ts\n"); + return 0; + } + + e1i_ts->driver.dahdi.fd.when |= BSC_FD_WRITE; + + return 0; +} + +static void timeout_ts1_write(void *data) +{ + struct e1inp_ts *e1i_ts = (struct e1inp_ts *)data; + + /* trigger write of ts1, due to tx delay timer */ + ts_want_write(e1i_ts); +} + +static void dahdi_write_msg(struct msgb *msg, void *cbdata) +{ + struct osmo_fd *bfd = cbdata; + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + int ret; + + ret = write(bfd->fd, msg->data, msg->len + 2); + msgb_free(msg); + if (ret == -1) + handle_dahdi_exception(e1i_ts); + else if (ret < 0) + LOGP(DLMI, LOGL_NOTICE, "%s write failed %d\n", __func__, ret); +} + +static int handle_ts1_write(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct e1inp_sign_link *sign_link; + struct msgb *msg; + + bfd->when &= ~BSC_FD_WRITE; + + /* get the next msg for this timeslot */ + msg = e1inp_tx_ts(e1i_ts, &sign_link); + if (!msg) { + /* no message after tx delay timer */ + return 0; + } + + DEBUGP(DLMI, "TX: %s\n", osmo_hexdump(msg->data, msg->len)); + lapd_transmit(e1i_ts->lapd, sign_link->tei, + sign_link->sapi, msg); + + /* set tx delay timer for next event */ + osmo_timer_setup(&e1i_ts->sign.tx_timer, timeout_ts1_write, e1i_ts); + osmo_timer_schedule(&e1i_ts->sign.tx_timer, 0, 50000); + + return 0; +} + +static void handle_hdlc_write(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct msgb *msg; + int ret; + + /* get the next msg for this timeslot */ + msg = e1inp_tx_ts(e1i_ts, NULL); + if (!msg) + return; + + ret = write(bfd->fd, msg->data, msg->len + 2); + msgb_free(msg); + if (ret == -1) + handle_dahdi_exception(e1i_ts); + else if (ret < 0) + LOGP(DLMI, LOGL_NOTICE, "%s write failed %d\n", __func__, ret); +} + +static int handle_hdlc_read(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct msgb *msg = msgb_alloc(TS1_ALLOC_SIZE, "DAHDI HDLC Rx"); + int ret; + + if (!msg) + return -ENOMEM; + + ret = read(bfd->fd, msg->data, TS1_ALLOC_SIZE - 16); + if (ret == -1) + handle_dahdi_exception(e1i_ts); + else if (ret < 0) { + perror("read "); + } + msgb_put(msg, ret - 2); + if (ret <= 3) { + perror("read "); + } + + return e1inp_rx_ts(e1i_ts, msg, 0, 0); +} + +static int invertbits = 1; + +static uint8_t flip_table[256]; + +static void init_flip_bits(void) +{ + int i,k; + + for (i = 0 ; i < 256 ; i++) { + uint8_t sample = 0 ; + for (k = 0; k<8; k++) { + if ( i & 1 << k ) sample |= 0x80 >> k; + } + flip_table[i] = sample; + } +} + +static uint8_t * flip_buf_bits ( uint8_t * buf , int len) +{ + int i; + uint8_t * start = buf; + + for (i = 0 ; i < len; i++) { + buf[i] = flip_table[(uint8_t)buf[i]]; + } + + return start; +} + +#define D_BCHAN_TX_GRAN 160 +/* write to a B channel TS */ +static int handle_tsX_write(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + uint8_t tx_buf[D_BCHAN_TX_GRAN]; + struct subch_mux *mx = &e1i_ts->trau.mux; + int ret; + + ret = subchan_mux_out(mx, tx_buf, D_BCHAN_TX_GRAN); + + if (ret != D_BCHAN_TX_GRAN) { + LOGP(DLINP, LOGL_DEBUG, "Huh, got ret of %d\n", ret); + if (ret < 0) + return ret; + } + + DEBUGP(DLMIB, "BCHAN TX: %s\n", + osmo_hexdump(tx_buf, D_BCHAN_TX_GRAN)); + + if (invertbits) { + flip_buf_bits(tx_buf, ret); + } + + ret = write(bfd->fd, tx_buf, ret); + if (ret < D_BCHAN_TX_GRAN) + LOGP(DLINP, LOGL_DEBUG, "send returns %d instead of %d\n", + ret, D_BCHAN_TX_GRAN); + + return ret; +} + +#define D_TSX_ALLOC_SIZE (D_BCHAN_TX_GRAN) +/* FIXME: read from a B channel TS */ +static int handle_tsX_read(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct msgb *msg = msgb_alloc(D_TSX_ALLOC_SIZE, "DAHDI TSx"); + int ret; + + if (!msg) + return -ENOMEM; + + ret = read(bfd->fd, msg->data, D_TSX_ALLOC_SIZE); + if (ret < 0 || ret != D_TSX_ALLOC_SIZE) { + LOGP(DLINP, LOGL_DEBUG, "read error %d %s\n", + ret, strerror(errno)); + return ret; + } + + if (invertbits) { + flip_buf_bits(msg->data, ret); + } + + msgb_put(msg, ret); + + msg->l2h = msg->data; + DEBUGP(DLMIB, "BCHAN RX: %s\n", + osmo_hexdump(msgb_l2(msg), ret)); + ret = e1inp_rx_ts(e1i_ts, msg, 0, 0); + /* physical layer indicates that data has been sent, + * we thus can send some more data */ + ret = handle_tsX_write(bfd); + + return ret; +} + +/* write to a raw channel TS */ +static int handle_ts_raw_write(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct msgb *msg; + int ret; + + /* get the next msg for this timeslot */ + msg = e1inp_tx_ts(e1i_ts, NULL); + if (!msg) + return 0; + + if (msg->len != D_BCHAN_TX_GRAN) { + /* This might lead to a transmit underrun, as we call tx + * from the rx path, as there's no select/poll on dahdi + * */ + LOGP(DLINP, LOGL_NOTICE, "unexpected msg->len = %u, " + "expected %u\n", msg->len, D_BCHAN_TX_GRAN); + } + + DEBUGP(DLMIB, "RAW CHAN TX: %s\n", + osmo_hexdump(msg->data, msg->len)); + + if (0/*invertbits*/) { + flip_buf_bits(msg->data, msg->len); + } + + ret = write(bfd->fd, msg->data, msg->len); + if (ret < msg->len) + LOGP(DLINP, LOGL_DEBUG, "send returns %d instead of %d\n", + ret, msg->len); + msgb_free(msg); + + return ret; +} + +static int handle_ts_raw_read(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct msgb *msg = msgb_alloc(D_TSX_ALLOC_SIZE, "DAHDI Raw TS"); + int ret; + + if (!msg) + return -ENOMEM; + + ret = read(bfd->fd, msg->data, D_TSX_ALLOC_SIZE); + if (ret < 0 || ret != D_TSX_ALLOC_SIZE) { + LOGP(DLINP, LOGL_DEBUG, "read error %d %s\n", + ret, strerror(errno)); + return ret; + } + + if (0/*invertbits*/) { + flip_buf_bits(msg->data, ret); + } + + msgb_put(msg, ret); + + msg->l2h = msg->data; + DEBUGP(DLMIB, "RAW CHAN RX: %s\n", + osmo_hexdump(msgb_l2(msg), ret)); + ret = e1inp_rx_ts(e1i_ts, msg, 0, 0); + /* physical layer indicates that data has been sent, + * we thus can send some more data */ + ret = handle_ts_raw_write(bfd); + + return ret; +} + +/* callback from select.c in case one of the fd's can be read/written */ +static int dahdi_fd_cb(struct osmo_fd *bfd, unsigned int what) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + unsigned int idx = ts_nr-1; + struct e1inp_ts *e1i_ts = &line->ts[idx]; + int rc = 0; + + switch (e1i_ts->type) { + case E1INP_TS_TYPE_SIGN: + if (what & BSC_FD_EXCEPT) + handle_dahdi_exception(e1i_ts); + if (what & BSC_FD_READ) + rc = handle_ts1_read(bfd); + if (what & BSC_FD_WRITE) + rc = handle_ts1_write(bfd); + break; + case E1INP_TS_TYPE_HDLC: + if (what & BSC_FD_EXCEPT) + handle_dahdi_exception(e1i_ts); + if (what & BSC_FD_READ) + rc = handle_hdlc_read(bfd); + if (what & BSC_FD_WRITE) + handle_hdlc_write(bfd); + break; + case E1INP_TS_TYPE_TRAU: + if (what & BSC_FD_EXCEPT) + handle_dahdi_exception(e1i_ts); + if (what & BSC_FD_READ) + rc = handle_tsX_read(bfd); + if (what & BSC_FD_WRITE) + rc = handle_tsX_write(bfd); + /* We never include the DAHDI B-Channel FD into the + * writeset, since it doesn't support poll() based + * write flow control */ + break; + case E1INP_TS_TYPE_RAW: + if (what & BSC_FD_EXCEPT) + handle_dahdi_exception(e1i_ts); + if (what & BSC_FD_READ) + rc = handle_ts_raw_read(bfd); + if (what & BSC_FD_WRITE) + rc = handle_ts_raw_write(bfd); + /* We never include the DAHDI B-Channel FD into the + * writeset, since it doesn't support poll() based + * write flow control */ + break; + default: + LOGP(DLINP, LOGL_NOTICE, + "unknown E1 TS type %u\n", e1i_ts->type); + break; + } + + return rc; +} + +static void dahdi_vty_show(struct vty *vty, struct e1inp_line *line) +{ + struct span_cfg *scfg; + + if (line->port_nr >= ARRAY_SIZE(span_cfgs)) + return; + + scfg = span_cfgs[line->port_nr]; + if (!scfg) { + vty_out(vty, "DAHDI Span %u non-existant%s", + line->port_nr+1, VTY_NEWLINE); + return; + } + + vty_out(vty, "DAHDI Span #%u, Base Nr %u, Timeslots: %u%s", + line->port_nr+1, scfg->chan_base, scfg->chan_num, + VTY_NEWLINE); +} + +static int dahdi_e1_line_update(struct e1inp_line *line); + +struct e1inp_driver dahdi_driver = { + .name = "dahdi", + .want_write = ts_want_write, + .line_update = &dahdi_e1_line_update, + .vty_show = &dahdi_vty_show, +}; + +int dahdi_set_bufinfo(int fd, int as_sigchan) +{ + struct dahdi_bufferinfo bi; + int x = 0; + + if (ioctl(fd, DAHDI_GET_BUFINFO, &bi)) { + LOGP(DLINP, LOGL_ERROR, "Error getting bufinfo\n"); + return -EIO; + } + + if (as_sigchan) { + bi.numbufs = 4; + bi.bufsize = 512; + } else { + bi.numbufs = 8; + bi.bufsize = D_BCHAN_TX_GRAN; + bi.txbufpolicy = DAHDI_POLICY_WHEN_FULL; + } + + if (ioctl(fd, DAHDI_SET_BUFINFO, &bi)) { + LOGP(DLINP, LOGL_ERROR, "Error setting bufinfo\n"); + return -EIO; + } + + if (!as_sigchan) { + if (ioctl(fd, DAHDI_AUDIOMODE, &x)) { + LOGP(DLINP, LOGL_ERROR, "Error setting bufinfo\n"); + return -EIO; + } + } else { + int one = 1; + ioctl(fd, DAHDI_HDLCFCSMODE, &one); + /* we cannot reliably check for the ioctl return value here + * as this command will fail if the slot _already_ was a + * signalling slot before :( */ + } + return 0; +} + +static int dahdi_e1_setup(struct e1inp_line *line) +{ + struct span_cfg *scfg; + int ts, ret; + + reread_span_cfgs(); + + scfg = span_cfgs[line->port_nr]; + if (!scfg) { + LOGP(DLMI, LOGL_ERROR, "Line %u(%s): DAHDI Port %u (Span %u) " + "doesn't exist\n", line->num, line->name, line->port_nr, + line->port_nr+1); + return -EIO; + } + + line->num_ts = scfg->chan_num; + + /* TS0 is CRC4, don't need any fd for it */ + for (ts = 1; ts <= scfg->chan_num; ts++) { + unsigned int idx = ts-1; + char openstr[128]; + struct e1inp_ts *e1i_ts = &line->ts[idx]; + struct osmo_fd *bfd = &e1i_ts->driver.dahdi.fd; + int dev_nr; + + /* unregister FD if it was already registered */ + if (bfd->list.next && bfd->list.next != LLIST_POISON1) + osmo_fd_unregister(bfd); + + /* DAHDI device names/numbers just keep incrementing + * even over multiple boards. So TS1 of the second + * board will be 32 */ + dev_nr = scfg->chan_base + idx; + + bfd->data = line; + bfd->priv_nr = ts; + bfd->cb = dahdi_fd_cb; + snprintf(openstr, sizeof(openstr), "/dev/dahdi/%d", dev_nr); + + switch (e1i_ts->type) { + case E1INP_TS_TYPE_NONE: + /* close/release LAPD instance, if any */ + if (e1i_ts->lapd) { + lapd_instance_free(e1i_ts->lapd); + e1i_ts->lapd = NULL; + } + if (bfd->fd) { + close(bfd->fd); + bfd->fd = 0; + } + continue; + break; + case E1INP_TS_TYPE_SIGN: + if (!bfd->fd) + bfd->fd = open(openstr, O_RDWR | O_NONBLOCK); + if (bfd->fd == -1) { + LOGP(DLINP, LOGL_ERROR, + "%s could not open %s %s\n", + __func__, openstr, strerror(errno)); + return -EIO; + } + bfd->when = BSC_FD_READ | BSC_FD_EXCEPT; + ret = dahdi_set_bufinfo(bfd->fd, 1); + if (ret < 0) + return ret; + + if (!e1i_ts->lapd) + e1i_ts->lapd = lapd_instance_alloc(1, + dahdi_write_msg, bfd, e1inp_dlsap_up, + e1i_ts, &lapd_profile_abis); + break; + case E1INP_TS_TYPE_HDLC: + if (!bfd->fd) + bfd->fd = open(openstr, O_RDWR | O_NONBLOCK); + if (bfd->fd == -1) { + LOGP(DLINP, LOGL_ERROR, + "%s could not open %s %s\n", + __func__, openstr, strerror(errno)); + return -EIO; + } + bfd->when = BSC_FD_READ | BSC_FD_EXCEPT; + ret = dahdi_set_bufinfo(bfd->fd, 1); + if (ret < 0) + return ret; + break; + case E1INP_TS_TYPE_TRAU: + case E1INP_TS_TYPE_RAW: + /* close/release LAPD instance, if any */ + if (e1i_ts->lapd) { + lapd_instance_free(e1i_ts->lapd); + e1i_ts->lapd = NULL; + } + if (!bfd->fd) + bfd->fd = open(openstr, O_RDWR | O_NONBLOCK); + if (bfd->fd == -1) { + LOGP(DLINP, LOGL_ERROR, + "%s could not open %s %s\n", + __func__, openstr, strerror(errno)); + return -EIO; + } + ret = dahdi_set_bufinfo(bfd->fd, 0); + if (ret < 0) + return -EIO; + /* We never include the DAHDI B-Channel FD into the + * writeset, since it doesn't support poll() based + * write flow control */ + bfd->when = BSC_FD_READ | BSC_FD_EXCEPT;// | BSC_FD_WRITE; + break; + } + + if (bfd->fd < 0) { + LOGP(DLINP, LOGL_ERROR, + "%s could not open %s %s\n", + __func__, openstr, strerror(errno)); + return bfd->fd; + } + + ret = osmo_fd_register(bfd); + if (ret < 0) { + LOGP(DLINP, LOGL_ERROR, + "could not register FD: %s\n", + strerror(ret)); + return ret; + } + } + + return 0; +} + +static int dahdi_e1_line_update(struct e1inp_line *line) +{ + if (line->driver != &dahdi_driver) + return -EINVAL; + + return dahdi_e1_setup(line); +} + +int e1inp_dahdi_init(void) +{ + init_flip_bits(); + + /* register the driver with the core */ + return e1inp_driver_register(&dahdi_driver); +} + +#endif /* HAVE_DAHDI_USER_H */ diff --git a/src/input/ipa.c b/src/input/ipa.c new file mode 100644 index 0000000..ce155ce --- /dev/null +++ b/src/input/ipa.c @@ -0,0 +1,516 @@ +#include "internal.h" + +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> +#include <errno.h> +#include <string.h> +#include <time.h> +#include <sys/fcntl.h> +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <arpa/inet.h> + +#include <osmocom/core/select.h> +#include <osmocom/gsm/tlv.h> +#include <osmocom/core/msgb.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/talloc.h> +#include <osmocom/abis/e1_input.h> +#include <osmocom/abis/ipaccess.h> +#include <osmocom/core/socket.h> +#include <osmocom/core/backtrace.h> + +#include <osmocom/abis/ipa.h> + +void ipa_msg_push_header(struct msgb *msg, uint8_t proto) +{ + struct ipaccess_head *hh; + + msg->l2h = msg->data; + hh = (struct ipaccess_head *) msgb_push(msg, sizeof(*hh)); + hh->proto = proto; + hh->len = htons(msgb_l2len(msg)); +} + +void ipa_client_conn_close(struct ipa_client_conn *link) +{ + /* be safe against multiple calls */ + if (link->ofd->fd != -1) { + osmo_fd_unregister(link->ofd); + close(link->ofd->fd); + link->ofd->fd = -1; + } + msgb_free(link->pending_msg); + link->pending_msg = NULL; +} + +static void ipa_client_read(struct ipa_client_conn *link) +{ + struct osmo_fd *ofd = link->ofd; + struct msgb *msg; + int ret; + + LOGP(DLINP, LOGL_DEBUG, "message received\n"); + + ret = ipa_msg_recv_buffered(ofd->fd, &msg, &link->pending_msg); + if (ret < 0) { + if (ret == -EAGAIN) + return; + if (ret == -EPIPE || ret == -ECONNRESET) + LOGP(DLINP, LOGL_ERROR, "lost connection with server\n"); + ipa_client_conn_close(link); + if (link->updown_cb) + link->updown_cb(link, 0); + return; + } else if (ret == 0) { + LOGP(DLINP, LOGL_ERROR, "connection closed with server\n"); + ipa_client_conn_close(link); + if (link->updown_cb) + link->updown_cb(link, 0); + return; + } + if (link->read_cb) + link->read_cb(link, msg); +} + +static void ipa_client_write(struct ipa_client_conn *link) +{ + if (link->write_cb) + link->write_cb(link); +} + +static int ipa_client_write_default_cb(struct ipa_client_conn *link) +{ + struct osmo_fd *ofd = link->ofd; + struct msgb *msg; + struct llist_head *lh; + int ret; + + LOGP(DLINP, LOGL_DEBUG, "sending data\n"); + + if (llist_empty(&link->tx_queue)) { + ofd->when &= ~BSC_FD_WRITE; + return 0; + } + lh = link->tx_queue.next; + llist_del(lh); + msg = llist_entry(lh, struct msgb, list); + + ret = send(link->ofd->fd, msg->data, msg->len, 0); + if (ret < 0) { + if (errno == EPIPE || errno == ENOTCONN) { + ipa_client_conn_close(link); + if (link->updown_cb) + link->updown_cb(link, 0); + } + LOGP(DLINP, LOGL_ERROR, "error to send\n"); + } + msgb_free(msg); + return 0; +} + +static int ipa_client_fd_cb(struct osmo_fd *ofd, unsigned int what) +{ + struct ipa_client_conn *link = ofd->data; + int error, ret; + socklen_t len = sizeof(error); + + switch(link->state) { + case IPA_CLIENT_LINK_STATE_CONNECTING: + ret = getsockopt(ofd->fd, SOL_SOCKET, SO_ERROR, &error, &len); + if (ret >= 0 && error > 0) { + ipa_client_conn_close(link); + if (link->updown_cb) + link->updown_cb(link, 0); + return 0; + } + ofd->when &= ~BSC_FD_WRITE; + LOGP(DLINP, LOGL_NOTICE, "connection done.\n"); + link->state = IPA_CLIENT_LINK_STATE_CONNECTED; + if (link->updown_cb) + link->updown_cb(link, 1); + break; + case IPA_CLIENT_LINK_STATE_CONNECTED: + if (what & BSC_FD_READ) { + LOGP(DLINP, LOGL_DEBUG, "connected read\n"); + ipa_client_read(link); + } + if (what & BSC_FD_WRITE) { + LOGP(DLINP, LOGL_DEBUG, "connected write\n"); + ipa_client_write(link); + } + break; + default: + break; + } + return 0; +} + +struct ipa_client_conn * +ipa_client_conn_create(void *ctx, struct e1inp_ts *ts, + int priv_nr, const char *addr, uint16_t port, + void (*updown_cb)(struct ipa_client_conn *link, int up), + int (*read_cb)(struct ipa_client_conn *link, + struct msgb *msgb), + int (*write_cb)(struct ipa_client_conn *link), + void *data) +{ + struct ipa_client_conn *ipa_link; + + ipa_link = talloc_zero(ctx, struct ipa_client_conn); + if (!ipa_link) + return NULL; + + if (ts) { + if (ts->line->driver == NULL) { + talloc_free(ipa_link); + return NULL; + } + ipa_link->ofd = &ts->driver.ipaccess.fd; + } else { + ipa_link->ofd = talloc_zero(ctx, struct osmo_fd); + if (ipa_link->ofd == NULL) { + talloc_free(ipa_link); + return NULL; + } + } + + ipa_link->ofd->when |= BSC_FD_READ | BSC_FD_WRITE; + ipa_link->ofd->priv_nr = priv_nr; + ipa_link->ofd->cb = ipa_client_fd_cb; + ipa_link->ofd->data = ipa_link; + ipa_link->ofd->fd = -1; + ipa_link->state = IPA_CLIENT_LINK_STATE_CONNECTING; + ipa_link->addr = talloc_strdup(ipa_link, addr); + ipa_link->port = port; + ipa_link->updown_cb = updown_cb; + ipa_link->read_cb = read_cb; + /* default to generic write callback if not set. */ + if (write_cb == NULL) + ipa_link->write_cb = ipa_client_write_default_cb; + else + ipa_link->write_cb = write_cb; + + if (ts) + ipa_link->line = ts->line; + ipa_link->data = data; + INIT_LLIST_HEAD(&ipa_link->tx_queue); + + return ipa_link; +} + +void ipa_client_conn_destroy(struct ipa_client_conn *link) +{ + talloc_free(link); +} + +int ipa_client_conn_open(struct ipa_client_conn *link) +{ + int ret; + + link->state = IPA_CLIENT_LINK_STATE_CONNECTING; + ret = osmo_sock_init(AF_INET, SOCK_STREAM, IPPROTO_TCP, + link->addr, link->port, + OSMO_SOCK_F_CONNECT|OSMO_SOCK_F_NONBLOCK); + if (ret < 0) + return ret; + link->ofd->fd = ret; + link->ofd->when |= BSC_FD_WRITE; + if (osmo_fd_register(link->ofd) < 0) { + close(ret); + link->ofd->fd = -1; + return -EIO; + } + + return 0; +} + +void ipa_client_conn_send(struct ipa_client_conn *link, struct msgb *msg) +{ + msgb_enqueue(&link->tx_queue, msg); + link->ofd->when |= BSC_FD_WRITE; +} + +size_t ipa_client_conn_clear_queue(struct ipa_client_conn *link) +{ + size_t deleted = 0; + + while (!llist_empty(&link->tx_queue)) { + struct msgb *msg = msgb_dequeue(&link->tx_queue); + msgb_free(msg); + deleted += 1; + } + + link->ofd->when &= ~BSC_FD_WRITE; + return deleted; +} + +static int ipa_server_fd_cb(struct osmo_fd *ofd, unsigned int what) +{ + int fd, ret; + struct sockaddr_in sa; + socklen_t sa_len = sizeof(sa); + struct ipa_server_link *link = ofd->data; + + fd = accept(ofd->fd, (struct sockaddr *)&sa, &sa_len); + if (fd < 0) { + LOGP(DLINP, LOGL_ERROR, "failed to accept from origin " + "peer, reason=`%s'\n", strerror(errno)); + return fd; + } + LOGP(DLINP, LOGL_NOTICE, "accept()ed new link from %s to port %u\n", + inet_ntoa(sa.sin_addr), link->port); + + ret = link->accept_cb(link, fd); + if (ret < 0) { + LOGP(DLINP, LOGL_ERROR, + "failed to processs accept()ed new link, " + "reason=`%s'\n", strerror(-ret)); + close(fd); + return ret; + } + + return 0; +} + +struct ipa_server_link * +ipa_server_link_create(void *ctx, struct e1inp_line *line, + const char *addr, uint16_t port, + int (*accept_cb)(struct ipa_server_link *link, int fd), + void *data) +{ + struct ipa_server_link *ipa_link; + + OSMO_ASSERT(accept_cb != NULL); + + ipa_link = talloc_zero(ctx, struct ipa_server_link); + if (!ipa_link) + return NULL; + + ipa_link->ofd.when |= BSC_FD_READ | BSC_FD_WRITE; + ipa_link->ofd.cb = ipa_server_fd_cb; + ipa_link->ofd.data = ipa_link; + ipa_link->addr = talloc_strdup(ipa_link, addr); + ipa_link->port = port; + ipa_link->accept_cb = accept_cb; + ipa_link->line = line; + ipa_link->data = data; + + return ipa_link; + +} + +void ipa_server_link_destroy(struct ipa_server_link *link) +{ + talloc_free(link); +} + +int ipa_server_link_open(struct ipa_server_link *link) +{ + int ret; + + ret = osmo_sock_init(AF_INET, SOCK_STREAM, IPPROTO_TCP, + link->addr, link->port, OSMO_SOCK_F_BIND); + if (ret < 0) + return ret; + + link->ofd.fd = ret; + if (osmo_fd_register(&link->ofd) < 0) { + close(ret); + return -EIO; + } + return 0; +} + +void ipa_server_link_close(struct ipa_server_link *link) +{ + osmo_fd_unregister(&link->ofd); + close(link->ofd.fd); +} + +static void ipa_server_conn_read(struct ipa_server_conn *conn) +{ + struct osmo_fd *ofd = &conn->ofd; + struct msgb *msg; + int ret; + + LOGP(DLINP, LOGL_DEBUG, "message received\n"); + + ret = ipa_msg_recv_buffered(ofd->fd, &msg, &conn->pending_msg); + if (ret < 0) { + if (ret == -EAGAIN) + return; + if (ret == -EPIPE || ret == -ECONNRESET) + LOGP(DLINP, LOGL_ERROR, "lost connection with server\n"); + ipa_server_conn_destroy(conn); + return; + } else if (ret == 0) { + LOGP(DLINP, LOGL_ERROR, "connection closed with server\n"); + ipa_server_conn_destroy(conn); + return; + } + if (conn->cb) + conn->cb(conn, msg); + + return; +} + +static void ipa_server_conn_write(struct ipa_server_conn *conn) +{ + struct osmo_fd *ofd = &conn->ofd; + struct msgb *msg; + struct llist_head *lh; + int ret; + + LOGP(DLINP, LOGL_DEBUG, "sending data\n"); + + if (llist_empty(&conn->tx_queue)) { + ofd->when &= ~BSC_FD_WRITE; + return; + } + lh = conn->tx_queue.next; + llist_del(lh); + msg = llist_entry(lh, struct msgb, list); + + ret = send(conn->ofd.fd, msg->data, msg->len, 0); + if (ret < 0) { + LOGP(DLINP, LOGL_ERROR, "error to send\n"); + } + msgb_free(msg); +} + +static int ipa_server_conn_cb(struct osmo_fd *ofd, unsigned int what) +{ + struct ipa_server_conn *conn = ofd->data; + + LOGP(DLINP, LOGL_DEBUG, "connected read/write\n"); + if (what & BSC_FD_READ) + ipa_server_conn_read(conn); + if (what & BSC_FD_WRITE) + ipa_server_conn_write(conn); + + return 0; +} + +struct ipa_server_conn * +ipa_server_conn_create(void *ctx, struct ipa_server_link *link, int fd, + int (*cb)(struct ipa_server_conn *conn, struct msgb *msg), + int (*closed_cb)(struct ipa_server_conn *conn), void *data) +{ + struct ipa_server_conn *conn; + struct sockaddr_in sa; + socklen_t sa_len = sizeof(sa); + + conn = talloc_zero(ctx, struct ipa_server_conn); + if (conn == NULL) { + LOGP(DLINP, LOGL_ERROR, "cannot allocate new peer in server, " + "reason=`%s'\n", strerror(errno)); + return NULL; + } + conn->server = link; + conn->ofd.fd = fd; + conn->ofd.data = conn; + conn->ofd.cb = ipa_server_conn_cb; + conn->ofd.when = BSC_FD_READ; + conn->cb = cb; + conn->closed_cb = closed_cb; + conn->data = data; + INIT_LLIST_HEAD(&conn->tx_queue); + + if (!getpeername(fd, (struct sockaddr *)&sa, &sa_len)) { + char *str = inet_ntoa(sa.sin_addr); + conn->addr = talloc_strdup(conn, str); + conn->port = ntohs(sa.sin_port); + } + + if (osmo_fd_register(&conn->ofd) < 0) { + LOGP(DLINP, LOGL_ERROR, "could not register FD\n"); + talloc_free(conn); + return NULL; + } + return conn; +} + +int ipa_server_conn_ccm(struct ipa_server_conn *conn, struct msgb *msg) +{ + struct tlv_parsed tlvp; + uint8_t msg_type = *(msg->l2h); + struct ipaccess_unit unit_data = {}; + char *unitid; + int len, rc; + + /* shared CCM handling on both server and client */ + rc = ipa_ccm_rcvmsg_base(msg, &conn->ofd); + switch (rc) { + case -1: + /* error in IPA CCM processing */ + goto err; + case 1: + /* IPA CCM message that was handled in _base */ + return 0; + case 0: + /* IPA CCM message that we need to handle */ + break; + default: + /* Error */ + LOGP(DLINP, LOGL_ERROR, "Unexpected return from " + "ipa_ccm_rcvmsg_base: %d\n", rc); + goto err; + } + + switch (msg_type) { + case IPAC_MSGT_ID_RESP: + rc = ipa_ccm_idtag_parse(&tlvp, (uint8_t *)msg->l2h + 2, + msgb_l2len(msg)-2); + if (rc < 0) { + LOGP(DLINP, LOGL_ERROR, "IPA CCM RESPonse with " + "malformed TLVs\n"); + goto err; + } + if (!TLVP_PRESENT(&tlvp, IPAC_IDTAG_UNIT)) { + LOGP(DLINP, LOGL_ERROR, "IPA CCM RESP without " + "unit ID\n"); + goto err; + } + len = TLVP_LEN(&tlvp, IPAC_IDTAG_UNIT); + if (len < 1) { + LOGP(DLINP, LOGL_ERROR, "IPA CCM RESP with short" + "unit ID\n"); + goto err; + } + unitid = (char *) TLVP_VAL(&tlvp, IPAC_IDTAG_UNIT); + unitid[len-1] = '\0'; + ipa_parse_unitid(unitid, &unit_data); + + /* FIXME */ + rc = conn->ccm_cb(conn, msg, &tlvp, &unit_data); + if (rc < 0) + goto err; + break; + default: + LOGP(DLINP, LOGL_ERROR, "Unknown IPA message type\n"); + break; + } + return 0; +err: + /* in case of any error, we close the connection */ + ipa_server_conn_destroy(conn); + return -1; +} + +void ipa_server_conn_destroy(struct ipa_server_conn *conn) +{ + close(conn->ofd.fd); + msgb_free(conn->pending_msg); + osmo_fd_unregister(&conn->ofd); + if (conn->closed_cb) + conn->closed_cb(conn); + talloc_free(conn); +} + +void ipa_server_conn_send(struct ipa_server_conn *conn, struct msgb *msg) +{ + msgb_enqueue(&conn->tx_queue, msg); + conn->ofd.when |= BSC_FD_WRITE; +} diff --git a/src/input/ipaccess.c b/src/input/ipaccess.c new file mode 100644 index 0000000..63ee167 --- /dev/null +++ b/src/input/ipaccess.c @@ -0,0 +1,980 @@ +/* OpenBSC Abis input driver for ip.access */ + +/* (C) 2009 by Harald Welte <laforge@gnumonks.org> + * (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 "internal.h" + +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdbool.h> +#include <errno.h> +#include <netinet/tcp.h> +#include <string.h> +#include <time.h> +#include <fcntl.h> +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <arpa/inet.h> + +#include <osmocom/core/select.h> +#include <osmocom/gsm/tlv.h> +#include <osmocom/core/msgb.h> +#include <osmocom/core/macaddr.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/talloc.h> +#include <osmocom/abis/e1_input.h> +#include <osmocom/abis/ipaccess.h> +#include <osmocom/core/socket.h> +#include <osmocom/abis/ipa.h> +#include <osmocom/core/backtrace.h> +#include <osmocom/gsm/ipa.h> + +static void *tall_ipa_ctx; + +#define TS1_ALLOC_SIZE 900 + +#define DEFAULT_TCP_KEEPALIVE_IDLE_TIMEOUT 30 +#define DEFAULT_TCP_KEEPALIVE_INTERVAL 3 +#define DEFAULT_TCP_KEEPALIVE_RETRY_COUNT 10 + +static int ipaccess_drop(struct osmo_fd *bfd, struct e1inp_line *line) +{ + int ret = 1; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + + /* Error case: we did not see any ID_RESP yet for this socket. */ + if (bfd->fd != -1) { + LOGP(DLINP, LOGL_ERROR, "Forcing socket shutdown with " + "no signal link set\n"); + osmo_fd_unregister(bfd); + close(bfd->fd); + bfd->fd = -1; + ret = -ENOENT; + } + + msgb_free(e1i_ts->pending_msg); + e1i_ts->pending_msg = NULL; + + /* e1inp_sign_link_destroy releases the socket descriptors for us. */ + line->ops->sign_link_down(line); + + return ret; +} + +static int ipaccess_rcvmsg(struct e1inp_line *line, struct msgb *msg, + struct osmo_fd *bfd) +{ + struct tlv_parsed tlvp; + uint8_t msg_type = *(msg->l2h); + struct ipaccess_unit unit_data = {}; + struct e1inp_sign_link *sign_link; + char *unitid; + int len, ret; + + /* Handle IPA PING, PONG and ID_ACK messages. */ + ret = ipa_ccm_rcvmsg_base(msg, bfd); + switch(ret) { + case -1: + /* error in IPA control message handling */ + goto err; + case 1: + /* this is an IPA control message, skip further processing */ + return 0; + case 0: + /* this is not an IPA control message, continue */ + break; + default: + LOGP(DLINP, LOGL_ERROR, "Unexpected return from " + "ipa_ccm_rcvmsg_base " + "(ret=%d)\n", ret); + goto err; + } + + switch (msg_type) { + case IPAC_MSGT_ID_RESP: + DEBUGP(DLMI, "ID_RESP\n"); + /* parse tags, search for Unit ID */ + ret = ipa_ccm_idtag_parse(&tlvp, (uint8_t *)msg->l2h + 2, + msgb_l2len(msg)-2); + DEBUGP(DLMI, "\n"); + if (ret < 0) { + LOGP(DLINP, LOGL_ERROR, "IPA response message " + "with malformed TLVs\n"); + ret = -EINVAL; + goto err; + } + if (!TLVP_PRESENT(&tlvp, IPAC_IDTAG_UNIT)) { + LOGP(DLINP, LOGL_ERROR, "IPA response message " + "without unit ID\n"); + ret = -EINVAL; + goto err; + + } + len = TLVP_LEN(&tlvp, IPAC_IDTAG_UNIT); + if (len < 1) { + LOGP(DLINP, LOGL_ERROR, "IPA response message " + "with too small unit ID\n"); + ret = -EINVAL; + goto err; + } + unitid = (char *) TLVP_VAL(&tlvp, IPAC_IDTAG_UNIT); + unitid[len - 1] = '\0'; + ipa_parse_unitid(unitid, &unit_data); + + if (!line->ops->sign_link_up) { + LOGP(DLINP, LOGL_ERROR, + "Unable to set signal link, closing socket.\n"); + ret = -EINVAL; + goto err; + } + /* the BSC creates the new sign links at this stage. */ + if (bfd->priv_nr == E1INP_SIGN_OML) { + sign_link = + line->ops->sign_link_up(&unit_data, line, + E1INP_SIGN_OML); + if (sign_link == NULL) { + LOGP(DLINP, LOGL_ERROR, + "Unable to set signal link, " + "closing socket.\n"); + ret = -EINVAL; + goto err; + } + } else if (bfd->priv_nr == E1INP_SIGN_RSL) { + struct e1inp_ts *ts; + struct osmo_fd *newbfd; + struct e1inp_line *new_line; + + sign_link = + line->ops->sign_link_up(&unit_data, line, + E1INP_SIGN_RSL); + if (sign_link == NULL) { + LOGP(DLINP, LOGL_ERROR, + "Unable to set signal link, " + "closing socket.\n"); + ret = -EINVAL; + goto err; + } + /* this is a bugtrap, the BSC should be using the + * virtual E1 line used by OML for this RSL link. */ + if (sign_link->ts->line == line) { + LOGP(DLINP, LOGL_ERROR, + "Fix your BSC, you should use the " + "E1 line used by the OML link for " + "your RSL link.\n"); + return 0; + } + /* Finally, we know which OML link is associated with + * this RSL link, attach it to this socket. */ + bfd->data = new_line = sign_link->ts->line; + e1inp_line_get(new_line); + ts = &new_line->ts[E1INP_SIGN_RSL+unit_data.trx_id-1]; + newbfd = &ts->driver.ipaccess.fd; + + /* get rid of our old temporary bfd */ + memcpy(newbfd, bfd, sizeof(*newbfd)); + newbfd->priv_nr = E1INP_SIGN_RSL + unit_data.trx_id; + osmo_fd_unregister(bfd); + bfd->fd = -1; + ret = osmo_fd_register(newbfd); + if (ret < 0) { + LOGP(DLINP, LOGL_ERROR, + "could not register FD\n"); + goto err; + } + /* now we can release the dummy RSL line. */ + e1inp_line_put(line); + } + break; + default: + LOGP(DLINP, LOGL_ERROR, "Unknown IPA message type\n"); + ret = -EINVAL; + goto err; + } + return 0; +err: + osmo_fd_unregister(bfd); + close(bfd->fd); + bfd->fd = -1; + e1inp_line_put(line); + return ret; +} + +static int handle_ts1_read(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct e1inp_sign_link *link; + struct ipaccess_head *hh; + struct msgb *msg = NULL; + int ret, rc; + + ret = ipa_msg_recv_buffered(bfd->fd, &msg, &e1i_ts->pending_msg); + if (ret < 0) { + if (ret == -EAGAIN) + return 0; + LOGP(DLINP, LOGL_NOTICE, "Sign link problems, " + "closing socket. Reason: %s\n", strerror(-ret)); + goto err; + } else if (ret == 0) { + LOGP(DLINP, LOGL_NOTICE, "Sign link vanished, dead socket\n"); + goto err; + } + DEBUGP(DLMI, "RX %u: %s\n", ts_nr, osmo_hexdump(msgb_l2(msg), msgb_l2len(msg))); + + hh = (struct ipaccess_head *) msg->data; + if (hh->proto == IPAC_PROTO_IPACCESS) { + ipaccess_rcvmsg(line, msg, bfd); + msgb_free(msg); + return 0; + } else if (e1i_ts->type == E1INP_TS_TYPE_NONE) { + /* this sign link is not know yet.. complain. */ + LOGP(DLINP, LOGL_ERROR, "Timeslot is not configured.\n"); + ret = -EINVAL; + goto err_msg; + } + /* BIG FAT WARNING: bfd might no longer exist here, since ipaccess_rcvmsg() + * might have free'd it !!! */ + + link = e1inp_lookup_sign_link(e1i_ts, hh->proto, 0); + if (!link) { + LOGP(DLINP, LOGL_ERROR, "no matching signalling link for " + "hh->proto=0x%02x\n", hh->proto); + ret = -EINVAL; + goto err_msg; + } + msg->dst = link; + + /* XXX better use e1inp_ts_rx? */ + if (!e1i_ts->line->ops->sign_link) { + LOGP(DLINP, LOGL_ERROR, "Fix your application, " + "no action set for signalling messages.\n"); + ret = -EINVAL; + goto err_msg; + } + rc = e1i_ts->line->ops->sign_link(msg); + if (rc < 0) { + /* Don't close the signalling link if the upper layers report + * an error, that's too strict. BTW, the signalling layer is + * resposible for releasing the message. + */ + LOGP(DLINP, LOGL_ERROR, "Bad signalling message," + " sign_link returned error: %s.\n", strerror(-rc)); + } + + return 0; +err_msg: + msgb_free(msg); +err: + ipaccess_drop(bfd, line); + return ret; +} + +static int ts_want_write(struct e1inp_ts *e1i_ts) +{ + e1i_ts->driver.ipaccess.fd.when |= BSC_FD_WRITE; + + return 0; +} + +static void ipaccess_close(struct e1inp_sign_link *sign_link) +{ + struct e1inp_ts *e1i_ts = sign_link->ts; + struct osmo_fd *bfd = &e1i_ts->driver.ipaccess.fd; + return e1inp_close_socket(e1i_ts, sign_link, bfd); +} + +static void timeout_ts1_write(void *data) +{ + struct e1inp_ts *e1i_ts = (struct e1inp_ts *)data; + + /* trigger write of ts1, due to tx delay timer */ + ts_want_write(e1i_ts); +} + +static int __handle_ts1_write(struct osmo_fd *bfd, struct e1inp_line *line) +{ + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct e1inp_sign_link *sign_link; + struct msgb *msg; + int ret; + + bfd->when &= ~BSC_FD_WRITE; + + /* get the next msg for this timeslot */ + msg = e1inp_tx_ts(e1i_ts, &sign_link); + if (!msg) { + /* no message after tx delay timer */ + return 0; + } + + switch (sign_link->type) { + case E1INP_SIGN_OML: + case E1INP_SIGN_RSL: + case E1INP_SIGN_OSMO: + break; + default: + bfd->when |= BSC_FD_WRITE; /* come back for more msg */ + ret = -EINVAL; + goto out; + } + + msg->l2h = msg->data; + ipa_prepend_header(msg, sign_link->tei); + + DEBUGP(DLMI, "TX %u: %s\n", ts_nr, osmo_hexdump(msg->l2h, msgb_l2len(msg))); + + ret = send(bfd->fd, msg->data, msg->len, 0); + if (ret != msg->len) { + LOGP(DLINP, LOGL_ERROR, "failed to send A-bis IPA signalling " + "message. Reason: %s\n", strerror(errno)); + goto err; + } + + /* set tx delay timer for next event */ + osmo_timer_setup(&e1i_ts->sign.tx_timer, timeout_ts1_write, e1i_ts); + + /* Reducing this might break the nanoBTS 900 init. */ + osmo_timer_schedule(&e1i_ts->sign.tx_timer, 0, e1i_ts->sign.delay); + +out: + msgb_free(msg); + return ret; +err: + ipaccess_drop(bfd, line); + msgb_free(msg); + return ret; +} + +static int handle_ts1_write(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + + return __handle_ts1_write(bfd, line); +} + +static int ipaccess_bts_write_cb(struct ipa_client_conn *link) +{ + struct e1inp_line *line = link->line; + + return __handle_ts1_write(link->ofd, line); +} + +/* callback from select.c in case one of the fd's can be read/written */ +int ipaccess_fd_cb(struct osmo_fd *bfd, unsigned int what) +{ + int rc = 0; + + if (what & BSC_FD_READ) + rc = handle_ts1_read(bfd); + if (what & BSC_FD_WRITE) + rc = handle_ts1_write(bfd); + + return rc; +} + +static int ipaccess_line_update(struct e1inp_line *line); + +struct e1inp_driver ipaccess_driver = { + .name = "ipa", + .want_write = ts_want_write, + .line_update = ipaccess_line_update, + .close = ipaccess_close, + .default_delay = 0, + .has_keepalive = 1, +}; + +static void update_fd_settings(struct e1inp_line *line, int fd) +{ + int ret; + int val; + + if (line->keepalive_num_probes) { + /* Enable TCP keepalive to find out if the connection is gone */ + val = 1; + ret = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)); + if (ret < 0) + LOGP(DLINP, LOGL_NOTICE, "Failed to set keepalive: %s\n", + strerror(errno)); + else + LOGP(DLINP, LOGL_NOTICE, "Keepalive is set: %i\n", ret); + +#if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL) && defined(TCP_KEEPCNT) + /* The following options are not portable! */ + val = line->keepalive_idle_timeout > 0 ? + line->keepalive_idle_timeout : + DEFAULT_TCP_KEEPALIVE_IDLE_TIMEOUT; + ret = setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, + &val, sizeof(val)); + if (ret < 0) + LOGP(DLINP, LOGL_NOTICE, + "Failed to set keepalive idle time: %s\n", + strerror(errno)); + val = line->keepalive_probe_interval > -1 ? + line->keepalive_probe_interval : + DEFAULT_TCP_KEEPALIVE_INTERVAL; + ret = setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, + &val, sizeof(val)); + if (ret < 0) + LOGP(DLINP, LOGL_NOTICE, + "Failed to set keepalive interval: %s\n", + strerror(errno)); + val = line->keepalive_num_probes > 0 ? + line->keepalive_num_probes : + DEFAULT_TCP_KEEPALIVE_RETRY_COUNT; + ret = setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, + &val, sizeof(val)); + if (ret < 0) + LOGP(DLINP, LOGL_NOTICE, + "Failed to set keepalive count: %s\n", + strerror(errno)); +#endif + } +} + +/* callback of the OML listening filedescriptor */ +static int ipaccess_bsc_oml_cb(struct ipa_server_link *link, int fd) +{ + int ret; + int idx = 0; + int i; + struct e1inp_line *line; + struct e1inp_ts *e1i_ts; + struct osmo_fd *bfd; + + /* clone virtual E1 line for this new OML link. */ + line = e1inp_line_clone(tall_ipa_ctx, link->line); + if (line == NULL) { + LOGP(DLINP, LOGL_ERROR, "could not clone E1 line\n"); + return -ENOMEM; + } + + /* create virrtual E1 timeslots for signalling */ + e1inp_ts_config_sign(&line->ts[E1INP_SIGN_OML-1], line); + + /* initialize the fds */ + for (i = 0; i < ARRAY_SIZE(line->ts); ++i) + line->ts[i].driver.ipaccess.fd.fd = -1; + + e1i_ts = &line->ts[idx]; + + bfd = &e1i_ts->driver.ipaccess.fd; + bfd->fd = fd; + bfd->data = line; + bfd->priv_nr = E1INP_SIGN_OML; + bfd->cb = ipaccess_fd_cb; + bfd->when = BSC_FD_READ; + ret = osmo_fd_register(bfd); + if (ret < 0) { + LOGP(DLINP, LOGL_ERROR, "could not register FD\n"); + goto err_line; + } + + update_fd_settings(line, bfd->fd); + + /* Request ID. FIXME: request LOCATION, HW/SW VErsion, Unit Name, Serno */ + ret = ipa_ccm_send_id_req(bfd->fd); + if (ret < 0) { + LOGP(DLINP, LOGL_ERROR, "could not send ID REQ. Reason: %s\n", + strerror(errno)); + goto err_socket; + } + return ret; + +err_socket: + osmo_fd_unregister(bfd); +err_line: + close(bfd->fd); + bfd->fd = -1; + e1inp_line_put(line); + return ret; +} + +static int ipaccess_bsc_rsl_cb(struct ipa_server_link *link, int fd) +{ + struct e1inp_line *line; + struct e1inp_ts *e1i_ts; + struct osmo_fd *bfd; + int i, ret; + + /* We don't know yet which OML link to associate it with. Thus, we + * allocate a temporary E1 line until we have received ID. */ + line = e1inp_line_clone(tall_ipa_ctx, link->line); + if (line == NULL) { + LOGP(DLINP, LOGL_ERROR, "could not clone E1 line\n"); + return -ENOMEM; + } + /* initialize the fds */ + for (i = 0; i < ARRAY_SIZE(line->ts); ++i) + line->ts[i].driver.ipaccess.fd.fd = -1; + + /* we need this to initialize this in case to avoid crashes in case + * that the socket is closed before we've seen an ID_RESP. */ + e1inp_ts_config_sign(&line->ts[E1INP_SIGN_OML-1], line); + + e1i_ts = &line->ts[E1INP_SIGN_RSL-1]; + + bfd = &e1i_ts->driver.ipaccess.fd; + bfd->fd = fd; + bfd->data = line; + bfd->priv_nr = E1INP_SIGN_RSL; + bfd->cb = ipaccess_fd_cb; + bfd->when = BSC_FD_READ; + ret = osmo_fd_register(bfd); + if (ret < 0) { + LOGP(DLINP, LOGL_ERROR, "could not register FD\n"); + goto err_line; + } + /* Request ID. FIXME: request LOCATION, HW/SW VErsion, Unit Name, Serno */ + ret = ipa_ccm_send_id_req(bfd->fd); + if (ret < 0) { + LOGP(DLINP, LOGL_ERROR, "could not send ID REQ. Reason: %s\n", + strerror(errno)); + goto err_socket; + } + update_fd_settings(line, bfd->fd); + return ret; + +err_socket: + osmo_fd_unregister(bfd); +err_line: + close(bfd->fd); + bfd->fd = -1; + e1inp_line_put(line); + return ret; +} + +#define IPA_STRING_MAX 64 + +static struct msgb * +ipa_bts_id_resp(struct ipaccess_unit *dev, uint8_t *data, int len, int trx_nr) +{ + struct msgb *nmsg; + char str[IPA_STRING_MAX]; + uint8_t *tag; + + memset(str, 0, sizeof(str)); + + nmsg = ipa_msg_alloc(0); + if (!nmsg) + return NULL; + + *msgb_put(nmsg, 1) = IPAC_MSGT_ID_RESP; + while (len) { + if (len < 2) { + LOGP(DLINP, LOGL_NOTICE, + "Short read of ipaccess tag\n"); + msgb_free(nmsg); + return NULL; + } + switch (data[1]) { + case IPAC_IDTAG_UNIT: + snprintf(str, sizeof(str), "%u/%u/%u", + dev->site_id, dev->bts_id, trx_nr); + break; + case IPAC_IDTAG_MACADDR: + snprintf(str, sizeof(str), + "%02x:%02x:%02x:%02x:%02x:%02x", + dev->mac_addr[0], dev->mac_addr[1], + dev->mac_addr[2], dev->mac_addr[3], + dev->mac_addr[4], dev->mac_addr[5]); + break; + case IPAC_IDTAG_LOCATION1: + if (dev->location1) + strncpy(str, dev->location1, IPA_STRING_MAX); + break; + case IPAC_IDTAG_LOCATION2: + if (dev->location2) + strncpy(str, dev->location2, IPA_STRING_MAX); + break; + case IPAC_IDTAG_EQUIPVERS: + if (dev->equipvers) + strncpy(str, dev->equipvers, IPA_STRING_MAX); + break; + case IPAC_IDTAG_SWVERSION: + if (dev->swversion) + strncpy(str, dev->swversion, IPA_STRING_MAX); + break; + case IPAC_IDTAG_UNITNAME: + snprintf(str, sizeof(str), + "%s-%02x-%02x-%02x-%02x-%02x-%02x", + dev->unit_name, + dev->mac_addr[0], dev->mac_addr[1], + dev->mac_addr[2], dev->mac_addr[3], + dev->mac_addr[4], dev->mac_addr[5]); + break; + case IPAC_IDTAG_SERNR: + if (dev->serno) + strncpy(str, dev->serno, IPA_STRING_MAX); + break; + default: + LOGP(DLINP, LOGL_NOTICE, + "Unknown ipaccess tag 0x%02x\n", *data); + msgb_free(nmsg); + return NULL; + } + str[IPA_STRING_MAX-1] = '\0'; + + LOGP(DLINP, LOGL_INFO, " tag %d: %s\n", data[1], str); + tag = msgb_put(nmsg, 3 + strlen(str) + 1); + tag[0] = 0x00; + tag[1] = 1 + strlen(str) + 1; + tag[2] = data[1]; + memcpy(tag + 3, str, strlen(str) + 1); + data += 2; + len -= 2; + } + ipa_msg_push_header(nmsg, IPAC_PROTO_IPACCESS); + return nmsg; +} + +static struct msgb *ipa_bts_id_ack(void) +{ + struct msgb *nmsg2; + + nmsg2 = ipa_msg_alloc(0); + if (!nmsg2) + return NULL; + + *msgb_put(nmsg2, 1) = IPAC_MSGT_ID_ACK; + ipa_msg_push_header(nmsg2, IPAC_PROTO_IPACCESS); + + return nmsg2; +} + +static void ipaccess_bts_updown_cb(struct ipa_client_conn *link, int up) +{ + struct e1inp_line *line = link->line; + + if (up) + return; + + if (line->ops->sign_link_down) + line->ops->sign_link_down(line); +} + +/* handle incoming message to BTS, check if it is an IPA CCM, and if yes, + * handle it accordingly (PING/PONG/ID_REQ/ID_RESP/ID_ACK) */ +int ipaccess_bts_handle_ccm(struct ipa_client_conn *link, + struct ipaccess_unit *dev, struct msgb *msg) +{ + struct ipaccess_head *hh = (struct ipaccess_head *) msg->data; + struct msgb *rmsg; + int ret = 0; + + /* special handling for IPA CCM. */ + if (hh->proto == IPAC_PROTO_IPACCESS) { + uint8_t msg_type = *(msg->l2h); + + /* ping, pong and acknowledgment cases. */ + ret = ipa_ccm_rcvmsg_bts_base(msg, link->ofd); + if (ret < 0) + goto err; + + /* this is a request for identification from the BSC. */ + if (msg_type == IPAC_MSGT_ID_GET) { + uint8_t *data = msgb_l2(msg); + int len = msgb_l2len(msg); + int trx_nr = 0; + + if (link->ofd->priv_nr >= E1INP_SIGN_RSL) + trx_nr = link->ofd->priv_nr - E1INP_SIGN_RSL; + + LOGP(DLINP, LOGL_NOTICE, "received ID get\n"); + rmsg = ipa_bts_id_resp(dev, data + 1, len - 1, trx_nr); + ret = ipa_send(link->ofd->fd, rmsg->data, rmsg->len); + if (ret != rmsg->len) { + LOGP(DLINP, LOGL_ERROR, "cannot send ID_RESP " + "message. Reason: %s\n", strerror(errno)); + goto err_rmsg; + } + msgb_free(rmsg); + + /* send ID_ACK. */ + rmsg = ipa_bts_id_ack(); + ret = ipa_send(link->ofd->fd, rmsg->data, rmsg->len); + if (ret != rmsg->len) { + LOGP(DLINP, LOGL_ERROR, "cannot send ID_ACK " + "message. Reason: %s\n", strerror(errno)); + goto err_rmsg; + } + msgb_free(rmsg); + } + return 1; + } + + return 0; + +err_rmsg: + msgb_free(rmsg); +err: + ipa_client_conn_close(link); + return -1; +} + +static int ipaccess_bts_read_cb(struct ipa_client_conn *link, struct msgb *msg) +{ + struct ipaccess_head *hh = (struct ipaccess_head *) msg->data; + struct e1inp_ts *e1i_ts = NULL; + struct e1inp_sign_link *sign_link; + int ret = 0; + + /* special handling for IPA CCM. */ + if (hh->proto == IPAC_PROTO_IPACCESS) { + uint8_t msg_type = *(msg->l2h); + + /* this is a request for identification from the BSC. */ + if (msg_type == IPAC_MSGT_ID_GET) { + if (!link->line->ops->sign_link_up) { + LOGP(DLINP, LOGL_ERROR, + "Unable to set signal link, " + "closing socket.\n"); + ret = -EINVAL; + goto err; + } + } + } + + /* core CCM handling */ + ret = ipaccess_bts_handle_ccm(link, link->line->ops->cfg.ipa.dev, msg); + if (ret < 0) + goto err; + + if (ret == 1 && hh->proto == IPAC_PROTO_IPACCESS) { + uint8_t msg_type = *(msg->l2h); + + if (msg_type == IPAC_MSGT_ID_GET) { + sign_link = link->line->ops->sign_link_up(msg, + link->line, + link->ofd->priv_nr); + if (sign_link == NULL) { + LOGP(DLINP, LOGL_ERROR, + "Unable to set signal link, " + "closing socket.\n"); + ret = -EINVAL; + goto err; + } + } + msgb_free(msg); + return ret; + } else if (link->port == IPA_TCP_PORT_OML) + e1i_ts = &link->line->ts[0]; + else if (link->port == IPA_TCP_PORT_RSL) + e1i_ts = &link->line->ts[link->ofd->priv_nr-1]; + + OSMO_ASSERT(e1i_ts != NULL); + + /* look up for some existing signaling link. */ + sign_link = e1inp_lookup_sign_link(e1i_ts, hh->proto, 0); + if (sign_link == NULL) { + LOGP(DLINP, LOGL_ERROR, "no matching signalling link for " + "hh->proto=0x%02x\n", hh->proto); + ret = -EIO; + goto err; + } + msg->dst = sign_link; + + /* XXX better use e1inp_ts_rx? */ + if (!link->line->ops->sign_link) { + LOGP(DLINP, LOGL_ERROR, "Fix your application, " + "no action set for signalling messages.\n"); + ret = -ENOENT; + goto err; + } + link->line->ops->sign_link(msg); + return 0; + +err: + ipa_client_conn_close(link); + msgb_free(msg); + return ret; +} + +struct ipaccess_line { + int line_already_initialized; +}; + +static int ipaccess_line_update(struct e1inp_line *line) +{ + int ret = -ENOENT; + struct ipaccess_line *il; + + if (!line->driver_data) + line->driver_data = talloc_zero(line, struct ipaccess_line); + + if (!line->driver_data) { + LOGP(DLINP, LOGL_ERROR, "ipaccess: OOM in line update\n"); + return -ENOMEM; + } + il = line->driver_data; + + /* We only initialize this line once. */ + if (il->line_already_initialized) + return 0; + + il->line_already_initialized = 1; + + switch(line->ops->cfg.ipa.role) { + case E1INP_LINE_R_BSC: { + struct ipa_server_link *oml_link, *rsl_link; + const char *ipa = e1inp_ipa_get_bind_addr(); + + LOGP(DLINP, LOGL_NOTICE, "enabling ipaccess BSC mode on %s " + "with OML %u and RSL %u TCP ports\n", ipa, + IPA_TCP_PORT_OML, IPA_TCP_PORT_RSL); + + oml_link = ipa_server_link_create(tall_ipa_ctx, line, ipa, + IPA_TCP_PORT_OML, + ipaccess_bsc_oml_cb, NULL); + if (oml_link == NULL) { + LOGP(DLINP, LOGL_ERROR, "cannot create OML " + "BSC link: %s\n", strerror(errno)); + return -ENOMEM; + } + if (ipa_server_link_open(oml_link) < 0) { + LOGP(DLINP, LOGL_ERROR, "cannot open OML BSC link: %s\n", + strerror(errno)); + ipa_server_link_destroy(oml_link); + return -EIO; + } + rsl_link = ipa_server_link_create(tall_ipa_ctx, line, ipa, + IPA_TCP_PORT_RSL, + ipaccess_bsc_rsl_cb, NULL); + if (rsl_link == NULL) { + LOGP(DLINP, LOGL_ERROR, "cannot create RSL " + "BSC link: %s\n", strerror(errno)); + return -ENOMEM; + } + if (ipa_server_link_open(rsl_link) < 0) { + LOGP(DLINP, LOGL_ERROR, "cannot open RSL BSC link: %s\n", + strerror(errno)); + ipa_server_link_destroy(rsl_link); + return -EIO; + } + ret = 0; + break; + } + case E1INP_LINE_R_BTS: { + struct ipa_client_conn *link; + + LOGP(DLINP, LOGL_NOTICE, "enabling ipaccess BTS mode, " + "OML connecting to %s:%u\n", line->ops->cfg.ipa.addr, + IPA_TCP_PORT_OML); + + link = ipa_client_conn_create(tall_ipa_ctx, + &line->ts[E1INP_SIGN_OML-1], + E1INP_SIGN_OML, + line->ops->cfg.ipa.addr, + IPA_TCP_PORT_OML, + ipaccess_bts_updown_cb, + ipaccess_bts_read_cb, + ipaccess_bts_write_cb, + line); + if (link == NULL) { + LOGP(DLINP, LOGL_ERROR, "cannot create OML " + "BTS link: %s\n", strerror(errno)); + return -ENOMEM; + } + if (ipa_client_conn_open(link) < 0) { + LOGP(DLINP, LOGL_ERROR, "cannot open OML BTS link: %s\n", + strerror(errno)); + ipa_client_conn_close(link); + ipa_client_conn_destroy(link); + return -EIO; + } + ret = 0; + break; + } + default: + break; + } + return ret; +} + + +/* backwards compatibility */ +int e1inp_ipa_bts_rsl_connect(struct e1inp_line *line, + const char *rem_addr, uint16_t rem_port) +{ + return e1inp_ipa_bts_rsl_connect_n(line, rem_addr, rem_port, 0); +} + +int e1inp_ipa_bts_rsl_connect_n(struct e1inp_line *line, + const char *rem_addr, uint16_t rem_port, + uint8_t trx_nr) +{ + struct ipa_client_conn *rsl_link; + + if (E1INP_SIGN_RSL+trx_nr-1 >= NUM_E1_TS) { + LOGP(DLINP, LOGL_ERROR, "cannot create RSL BTS link: " + "trx_nr (%d) out of range\n", trx_nr); + return -EINVAL; + } + + rsl_link = ipa_client_conn_create(tall_ipa_ctx, + &line->ts[E1INP_SIGN_RSL+trx_nr-1], + E1INP_SIGN_RSL+trx_nr, + rem_addr, rem_port, + ipaccess_bts_updown_cb, + ipaccess_bts_read_cb, + ipaccess_bts_write_cb, + line); + if (rsl_link == NULL) { + LOGP(DLINP, LOGL_ERROR, "cannot create RSL " + "BTS link: %s\n", strerror(errno)); + return -ENOMEM; + } + if (ipa_client_conn_open(rsl_link) < 0) { + LOGP(DLINP, LOGL_ERROR, "cannot open RSL BTS link: %s\n", + strerror(errno)); + ipa_client_conn_close(rsl_link); + ipa_client_conn_destroy(rsl_link); + return -EIO; + } + return 0; +} + +void e1inp_ipaccess_init(void) +{ + tall_ipa_ctx = talloc_named_const(libosmo_abis_ctx, 1, "ipa"); + e1inp_driver_register(&ipaccess_driver); +} + +void e1inp_ipa_set_bind_addr(const char *ip_bind_addr) +{ + talloc_free((char*)ipaccess_driver.bind_addr); + ipaccess_driver.bind_addr = NULL; + + if (ip_bind_addr) + ipaccess_driver.bind_addr = talloc_strdup(tall_ipa_ctx, + ip_bind_addr); +} + +const char *e1inp_ipa_get_bind_addr(void) +{ + return ipaccess_driver.bind_addr? + ipaccess_driver.bind_addr + : "0.0.0.0"; +} diff --git a/src/input/lapd.c b/src/input/lapd.c new file mode 100644 index 0000000..4b5077b --- /dev/null +++ b/src/input/lapd.c @@ -0,0 +1,710 @@ +/* OpenBSC minimal LAPD implementation */ + +/* (C) 2009 by oystein@homelien.no + * (C) 2009 by Holger Hans Peter Freyther <zecke@selfish.org> + * (C) 2010 by Digium and Matthew Fredrickson <creslin@digium.com> + * (C) 2011 by Harald Welte <laforge@gnumonks.org> + * (C) 2011 by Andreas Eversberg <jolly@eversberg.eu> + * + * All Rights Reserved + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +#include "internal.h" + +#include <stdio.h> +#include <string.h> +#include <errno.h> + +#include <osmocom/core/linuxlist.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/talloc.h> +#include <osmocom/core/msgb.h> +#include <osmocom/core/timer.h> +#include <osmocom/abis/lapd.h> +#include <osmocom/abis/lapd_pcap.h> + +#define LAPD_ADDR2(sapi, cr) ((((sapi) & 0x3f) << 2) | (((cr) & 0x1) << 1)) +#define LAPD_ADDR3(tei) ((((tei) & 0x7f) << 1) | 0x1) + +#define LAPD_ADDR_SAPI(addr) ((addr) >> 2) +#define LAPD_ADDR_CR(addr) (((addr) >> 1) & 0x1) +#define LAPD_ADDR_EA(addr) ((addr) & 0x1) +#define LAPD_ADDR_TEI(addr) ((addr) >> 1) + +#define LAPD_CTRL_I4(ns) (((ns) & 0x7f) << 1) +#define LAPD_CTRL_I5(nr, p) ((((nr) & 0x7f) << 1) | ((p) & 0x1)) +#define LAPD_CTRL_S4(s) ((((s) & 0x3) << 2) | 0x1) +#define LAPD_CTRL_S5(nr, p) ((((nr) & 0x7f) << 1) | ((p) & 0x1)) +#define LAPD_CTRL_U4(u, p) ((((u) & 0x1c) << (5-2)) | (((p) & 0x1) << 4) | (((u) & 0x3) << 2) | 0x3) + +#define LAPD_CTRL_is_I(ctrl) (((ctrl) & 0x1) == 0) +#define LAPD_CTRL_is_S(ctrl) (((ctrl) & 0x3) == 1) +#define LAPD_CTRL_is_U(ctrl) (((ctrl) & 0x3) == 3) + +#define LAPD_CTRL_U_BITS(ctrl) ((((ctrl) & 0xC) >> 2) | ((ctrl) & 0xE0) >> 3) +#define LAPD_CTRL_U_PF(ctrl) (((ctrl) >> 4) & 0x1) + +#define LAPD_CTRL_S_BITS(ctrl) (((ctrl) & 0xC) >> 2) +#define LAPD_CTRL_S_PF(ctrl) (ctrl & 0x1) + +#define LAPD_CTRL_I_Ns(ctrl) (((ctrl) & 0xFE) >> 1) +#define LAPD_CTRL_I_P(ctrl) (ctrl & 0x1) +#define LAPD_CTRL_Nr(ctrl) (((ctrl) & 0xFE) >> 1) + +#define LAPD_LEN(len) ((len << 2) | 0x1) +#define LAPD_EL 0x1 + +#define LAPD_SET_K(n, o) {n,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o} + +const struct lapd_profile lapd_profile_isdn = { + .k = LAPD_SET_K(7,7), + .n200 = 3, + .n201 = 260, + .n202 = 3, + .t200_sec = 1, .t200_usec = 0, + .t201_sec = 1, .t201_usec = 0, + .t202_sec = 2, .t202_usec = 0, + .t203_sec = 10, .t203_usec = 0, + .short_address = 0 +}; + +const struct lapd_profile lapd_profile_abis = { + .k = LAPD_SET_K(2,1), + .n200 = 3, + .n201 = 260, + .n202 = 0, /* infinite */ + .t200_sec = 0, .t200_usec = 240000, + .t201_sec = 1, .t201_usec = 0, + .t202_sec = 2, .t202_usec = 0, + .t203_sec = 10, .t203_usec = 0, + .short_address = 0 +}; + +/* Ericssons OM2000 lapd dialect requires a sabm frame retransmission + * timeout of exactly 300 msek. Shorter or longer retransmission will + * cause the link establishment to fail permanently. Since the BTS is + * periodically scanning through all timeslots to find the timeslot + * where the bsc is transmitting its sabm frames the normal maximum + * retransmission (n200) of 3 is not enough. In order not to miss + * the bts, n200 has been increased to 50, which is an educated + * guess. */ + +const struct lapd_profile lapd_profile_abis_ericsson = { + .k = LAPD_SET_K(2,1), + .n200 = 50, + .n201 = 260, + .n202 = 0, /* infinite */ + .t200_sec = 0, .t200_usec = 300000, + .t201_sec = 1, .t201_usec = 0, + .t202_sec = 2, .t202_usec = 0, + .t203_sec = 10, .t203_usec = 0, + .short_address = 0 +}; + +const struct lapd_profile lapd_profile_sat = { + .k = LAPD_SET_K(15,15), + .n200 = 5, + .n201 = 260, + .n202 = 5, + .t200_sec = 2, .t200_usec = 400000, + .t201_sec = 2, .t201_usec = 400000, + .t202_sec = 2, .t202_usec = 400000, + .t203_sec = 20, .t203_usec = 0, + .short_address = 1 +}; + +typedef enum { + LAPD_TEI_NONE = 0, + LAPD_TEI_ASSIGNED, + LAPD_TEI_ACTIVE, +} lapd_tei_state; + +const char *lapd_tei_states[] = { + "NONE", + "ASSIGNED", + "ACTIVE", +}; + +/* Structure representing an allocated TEI within a LAPD instance. */ +struct lapd_tei { + struct llist_head list; + struct lapd_instance *li; + uint8_t tei; + lapd_tei_state state; + + struct llist_head sap_list; +}; + +/* Structure representing a SAP within a TEI. It includes exactly one datalink + * instance. */ +struct lapd_sap { + struct llist_head list; + struct lapd_tei *tei; + uint8_t sapi; + + struct lapd_datalink dl; +}; + +/* Resolve TEI structure from given numeric TEI */ +static struct lapd_tei *teip_from_tei(struct lapd_instance *li, uint8_t tei) +{ + struct lapd_tei *lt; + + llist_for_each_entry(lt, &li->tei_list, list) { + if (lt->tei == tei) + return lt; + } + return NULL; +}; + +/* Change state of TEI */ +static void lapd_tei_set_state(struct lapd_tei *teip, int newstate) +{ + LOGP(DLLAPD, LOGL_INFO, "LAPD state change on TEI %d: %s -> %s\n", + teip->tei, lapd_tei_states[teip->state], + lapd_tei_states[newstate]); + teip->state = newstate; +}; + +/* Allocate a new TEI */ +struct lapd_tei *lapd_tei_alloc(struct lapd_instance *li, uint8_t tei) +{ + struct lapd_tei *teip; + + teip = talloc_zero(li, struct lapd_tei); + if (!teip) + return NULL; + + teip->li = li; + teip->tei = tei; + llist_add(&teip->list, &li->tei_list); + INIT_LLIST_HEAD(&teip->sap_list); + + lapd_tei_set_state(teip, LAPD_TEI_ASSIGNED); + + return teip; +} + +/* Find a SAP within a given TEI */ +static struct lapd_sap *lapd_sap_find(struct lapd_tei *teip, uint8_t sapi) +{ + struct lapd_sap *sap; + + llist_for_each_entry(sap, &teip->sap_list, list) { + if (sap->sapi == sapi) + return sap; + } + + return NULL; +} + +static int send_ph_data_req(struct lapd_msg_ctx *lctx, struct msgb *msg); +static int send_dlsap(struct osmo_dlsap_prim *dp, struct lapd_msg_ctx *lctx); + +/* Allocate a new SAP within a given TEI */ +static struct lapd_sap *lapd_sap_alloc(struct lapd_tei *teip, uint8_t sapi) +{ + struct lapd_sap *sap; + struct lapd_datalink *dl; + struct lapd_instance *li; + struct lapd_profile *profile; + int k; + + sap = talloc_zero(teip, struct lapd_sap); + if (!sap) + return NULL; + + LOGP(DLLAPD, LOGL_NOTICE, + "LAPD Allocating SAP for SAPI=%u / TEI=%u (dl=%p, sap=%p)\n", + sapi, teip->tei, &sap->dl, sap); + + sap->sapi = sapi; + sap->tei = teip; + dl = &sap->dl; + li = teip->li; + profile = &li->profile; + + k = profile->k[sapi & 0x3f]; + LOGP(DLLAPD, LOGL_NOTICE, "k=%d N200=%d N201=%d T200=%d.%d T203=%d.%d" + "\n", k, profile->n200, profile->n201, profile->t200_sec, + profile->t200_usec, profile->t203_sec, profile->t203_usec); + lapd_dl_init(dl, k, 128, profile->n201); + dl->use_sabme = 1; /* use SABME instead of SABM (GSM) */ + dl->send_ph_data_req = send_ph_data_req; + dl->send_dlsap = send_dlsap; + dl->n200 = profile->n200; + dl->n200_est_rel = profile->n200; + dl->t200_sec = profile->t200_sec; dl->t200_usec = profile->t200_usec; + dl->t203_sec = profile->t203_sec; dl->t203_usec = profile->t203_usec; + dl->lctx.dl = &sap->dl; + dl->lctx.sapi = sapi; + dl->lctx.tei = teip->tei; + dl->lctx.n201 = profile->n201; + + lapd_set_mode(&sap->dl, (teip->li->network_side) ? LAPD_MODE_NETWORK + : LAPD_MODE_USER); + + llist_add(&sap->list, &teip->sap_list); + + return sap; +} + +/* Free SAP instance, including the datalink */ +static void lapd_sap_free(struct lapd_sap *sap) +{ + LOGP(DLLAPD, LOGL_NOTICE, + "LAPD Freeing SAP for SAPI=%u / TEI=%u (dl=%p, sap=%p)\n", + sap->sapi, sap->tei->tei, &sap->dl, sap); + + /* free datalink structures and timers */ + lapd_dl_exit(&sap->dl); + + llist_del(&sap->list); + talloc_free(sap); +} + +/* Free TEI instance */ +static void lapd_tei_free(struct lapd_tei *teip) +{ + struct lapd_sap *sap, *sap2; + + llist_for_each_entry_safe(sap, sap2, &teip->sap_list, list) { + lapd_sap_free(sap); + } + + llist_del(&teip->list); + talloc_free(teip); +} + +/* Input function into TEI manager */ +static int lapd_tei_receive(struct lapd_instance *li, uint8_t *data, int len) +{ + uint8_t entity; + uint8_t ref; + uint8_t mt; + uint8_t action; + uint8_t e; + uint8_t resp[8]; + struct lapd_tei *teip; + struct msgb *msg; + + if (len < 5) { + LOGP(DLLAPD, LOGL_ERROR, "LAPD TEIMGR frame receive len %d < 5" + ", ignoring\n", len); + return -EINVAL; + }; + + entity = data[0]; + ref = data[1]; + mt = data[3]; + action = data[4] >> 1; + e = data[4] & 1; + + DEBUGP(DLLAPD, "LAPD TEIMGR: entity %x, ref %x, mt %x, action %x, " + "e %x\n", entity, ref, mt, action, e); + + switch (mt) { + case 0x01: /* IDENTITY REQUEST */ + DEBUGP(DLLAPD, "LAPD TEIMGR: identity request for TEI %u\n", + action); + + teip = teip_from_tei(li, action); + if (!teip) { + LOGP(DLLAPD, LOGL_INFO, "TEI MGR: New TEI %u\n", + action); + teip = lapd_tei_alloc(li, action); + if (!teip) + return -ENOMEM; + } + + /* Send ACCEPT */ + memmove(resp, "\xfe\xff\x03\x0f\x00\x00\x02\x00", 8); + resp[7] = (action << 1) | 1; + msg = msgb_alloc_headroom(56, 56, "DL EST"); + msg->l2h = msgb_push(msg, 8); + memcpy(msg->l2h, resp, 8); + + /* write to PCAP file, if enabled. */ + osmo_pcap_lapd_write(li->pcap_fd, OSMO_LAPD_PCAP_OUTPUT, msg); + + LOGP(DLLAPD, LOGL_DEBUG, "TX: %s\n", + osmo_hexdump(msg->data, msg->len)); + li->transmit_cb(msg, li->transmit_cbdata); + + if (teip->state == LAPD_TEI_NONE) + lapd_tei_set_state(teip, LAPD_TEI_ASSIGNED); + break; + default: + LOGP(DLLAPD, LOGL_NOTICE, "LAPD TEIMGR: unknown mt %x " + "action %x\n", mt, action); + break; + }; + + return 0; +} + +/* General input function for any data received for this LAPD instance */ +int lapd_receive(struct lapd_instance *li, struct msgb *msg, int *error) +{ + int i; + struct lapd_msg_ctx lctx; + int rc; + struct lapd_sap *sap; + struct lapd_tei *teip; + + /* write to PCAP file, if enabled. */ + osmo_pcap_lapd_write(li->pcap_fd, OSMO_LAPD_PCAP_INPUT, msg); + + LOGP(DLLAPD, LOGL_DEBUG, "RX: %s\n", osmo_hexdump(msg->data, msg->len)); + if (msg->len < 2) { + LOGP(DLLAPD, LOGL_ERROR, "LAPD frame receive len %d < 2, " + "ignoring\n", msg->len); + *error = LAPD_ERR_BAD_LEN; + return -EINVAL; + }; + msg->l2h = msg->data; + + memset(&lctx, 0, sizeof(lctx)); + + i = 0; + /* adress field */ + lctx.sapi = LAPD_ADDR_SAPI(msg->l2h[i]); + lctx.cr = LAPD_ADDR_CR(msg->l2h[i]); + lctx.lpd = 0; + if (!LAPD_ADDR_EA(msg->l2h[i])) { + if (msg->len < 3) { + LOGP(DLLAPD, LOGL_ERROR, "LAPD frame with TEI receive " + "len %d < 3, ignoring\n", msg->len); + *error = LAPD_ERR_BAD_LEN; + return -EINVAL; + }; + i++; + lctx.tei = LAPD_ADDR_TEI(msg->l2h[i]); + } + i++; + /* control field */ + if (LAPD_CTRL_is_I(msg->l2h[i])) { + lctx.format = LAPD_FORM_I; + lctx.n_send = LAPD_CTRL_I_Ns(msg->l2h[i]); + i++; + if (msg->len < 3 && i == 2) { + LOGP(DLLAPD, LOGL_ERROR, "LAPD I frame without TEI " + "receive len %d < 3, ignoring\n", msg->len); + *error = LAPD_ERR_BAD_LEN; + return -EINVAL; + }; + if (msg->len < 4 && i == 3) { + LOGP(DLLAPD, LOGL_ERROR, "LAPD I frame with TEI " + "receive len %d < 4, ignoring\n", msg->len); + *error = LAPD_ERR_BAD_LEN; + return -EINVAL; + }; + lctx.n_recv = LAPD_CTRL_Nr(msg->l2h[i]); + lctx.p_f = LAPD_CTRL_I_P(msg->l2h[i]); + } else if (LAPD_CTRL_is_S(msg->l2h[i])) { + lctx.format = LAPD_FORM_S; + lctx.s_u = LAPD_CTRL_S_BITS(msg->l2h[i]); + i++; + if (msg->len < 3 && i == 2) { + LOGP(DLLAPD, LOGL_ERROR, "LAPD S frame without TEI " + "receive len %d < 3, ignoring\n", msg->len); + *error = LAPD_ERR_BAD_LEN; + return -EINVAL; + }; + if (msg->len < 4 && i == 3) { + LOGP(DLLAPD, LOGL_ERROR, "LAPD S frame with TEI " + "receive len %d < 4, ignoring\n", msg->len); + *error = LAPD_ERR_BAD_LEN; + return -EINVAL; + }; + lctx.n_recv = LAPD_CTRL_Nr(msg->l2h[i]); + lctx.p_f = LAPD_CTRL_S_PF(msg->l2h[i]); + } else if (LAPD_CTRL_is_U(msg->l2h[i])) { + lctx.format = LAPD_FORM_U; + lctx.s_u = LAPD_CTRL_U_BITS(msg->l2h[i]); + lctx.p_f = LAPD_CTRL_U_PF(msg->l2h[i]); + } else + lctx.format = LAPD_FORM_UKN; + i++; + /* length */ + msg->l3h = msg->l2h + i; + msgb_pull(msg, i); + lctx.length = msg->len; + + /* perform TEI assignment, if received */ + if (lctx.tei == 127) { + rc = lapd_tei_receive(li, msg->data, msg->len); + msgb_free(msg); + return rc; + } + + /* resolve TEI and SAPI */ + teip = teip_from_tei(li, lctx.tei); + if (!teip) { + LOGP(DLLAPD, LOGL_NOTICE, "LAPD Unknown TEI %u\n", lctx.tei); + *error = LAPD_ERR_UNKNOWN_TEI; + msgb_free(msg); + return -EINVAL; + } + sap = lapd_sap_find(teip, lctx.sapi); + if (!sap) { + LOGP(DLLAPD, LOGL_INFO, "LAPD No SAP for TEI=%u / SAPI=%u, " + "allocating\n", lctx.tei, lctx.sapi); + sap = lapd_sap_alloc(teip, lctx.sapi); + if (!sap) { + *error = LAPD_ERR_NO_MEM; + msgb_free(msg); + return -ENOMEM; + } + } + lctx.dl = &sap->dl; + lctx.n201 = lctx.dl->maxf; + + if (msg->len > lctx.n201) { + LOGP(DLLAPD, LOGL_ERROR, "message len %d > N201(%d) " + "(discarding)\n", msg->len, lctx.n201); + msgb_free(msg); + *error = LAPD_ERR_BAD_LEN; + return -EINVAL; + } + + /* send to LAPD */ + return lapd_ph_data_ind(msg, &lctx); +} + +/* Start a (user-side) SAP for the specified TEI/SAPI on the LAPD instance */ +int lapd_sap_start(struct lapd_instance *li, uint8_t tei, uint8_t sapi) +{ + struct lapd_sap *sap; + struct lapd_tei *teip; + struct osmo_dlsap_prim dp; + struct msgb *msg; + + teip = teip_from_tei(li, tei); + if (!teip) + teip = lapd_tei_alloc(li, tei); + + sap = lapd_sap_find(teip, sapi); + if (sap) + return -EEXIST; + + sap = lapd_sap_alloc(teip, sapi); + if (!sap) + return -ENOMEM; + + LOGP(DLLAPD, LOGL_NOTICE, "LAPD DL-ESTABLISH request TEI=%d SAPI=%d\n", + tei, sapi); + + /* prepare prim */ + msg = msgb_alloc_headroom(56, 56, "DL EST"); + msg->l3h = msg->data; + osmo_prim_init(&dp.oph, 0, PRIM_DL_EST, PRIM_OP_REQUEST, msg); + + /* send to L2 */ + return lapd_recv_dlsap(&dp, &sap->dl.lctx); +} + +/* Stop a (user-side) SAP for the specified TEI/SAPI on the LAPD instance */ +int lapd_sap_stop(struct lapd_instance *li, uint8_t tei, uint8_t sapi) +{ + struct lapd_tei *teip; + struct lapd_sap *sap; + struct osmo_dlsap_prim dp; + struct msgb *msg; + + teip = teip_from_tei(li, tei); + if (!teip) + return -ENODEV; + + sap = lapd_sap_find(teip, sapi); + if (!sap) + return -ENODEV; + + LOGP(DLLAPD, LOGL_NOTICE, "LAPD DL-RELEASE request TEI=%d SAPI=%d\n", + tei, sapi); + + /* prepare prim */ + msg = msgb_alloc_headroom(56, 56, "DL REL"); + msg->l3h = msg->data; + osmo_prim_init(&dp.oph, 0, PRIM_DL_REL, PRIM_OP_REQUEST, msg); + + /* send to L2 */ + return lapd_recv_dlsap(&dp, &sap->dl.lctx); +} + +/* Transmit Data (DL-DATA request) on the given LAPD Instance / TEI / SAPI */ +void lapd_transmit(struct lapd_instance *li, uint8_t tei, uint8_t sapi, + struct msgb *msg) +{ + struct lapd_tei *teip = teip_from_tei(li, tei); + struct lapd_sap *sap; + struct osmo_dlsap_prim dp; + + if (!teip) { + LOGP(DLLAPD, LOGL_ERROR, "LAPD Cannot transmit on " + "non-existing TEI %u\n", tei); + msgb_free(msg); + return; + } + + sap = lapd_sap_find(teip, sapi); + if (!sap) { + LOGP(DLLAPD, LOGL_INFO, "LAPD Tx on unknown SAPI=%u " + "in TEI=%u\n", sapi, tei); + msgb_free(msg); + return; + } + + /* prepare prim */ + msg->l3h = msg->data; + osmo_prim_init(&dp.oph, 0, PRIM_DL_DATA, PRIM_OP_REQUEST, msg); + + /* send to L2 */ + lapd_recv_dlsap(&dp, &sap->dl.lctx); +}; + +static int send_ph_data_req(struct lapd_msg_ctx *lctx, struct msgb *msg) +{ + struct lapd_datalink *dl = lctx->dl; + struct lapd_sap *sap = + container_of(dl, struct lapd_sap, dl); + struct lapd_instance *li = sap->tei->li; + int format = lctx->format; + int addr_len; + + /* control field */ + switch (format) { + case LAPD_FORM_I: + msg->l2h = msgb_push(msg, 2); + msg->l2h[0] = LAPD_CTRL_I4(lctx->n_send); + msg->l2h[1] = LAPD_CTRL_I5(lctx->n_recv, lctx->p_f); + break; + case LAPD_FORM_S: + msg->l2h = msgb_push(msg, 2); + msg->l2h[0] = LAPD_CTRL_S4(lctx->s_u); + msg->l2h[1] = LAPD_CTRL_S5(lctx->n_recv, lctx->p_f); + break; + case LAPD_FORM_U: + msg->l2h = msgb_push(msg, 1); + msg->l2h[0] = LAPD_CTRL_U4(lctx->s_u, lctx->p_f); + break; + default: + msgb_free(msg); + return -EINVAL; + } + /* address field */ + if (li->profile.short_address && lctx->tei == 0) + addr_len = 1; + else + addr_len = 2; + msg->l2h = msgb_push(msg, addr_len); + msg->l2h[0] = LAPD_ADDR2(lctx->sapi, lctx->cr); + if (addr_len == 1) + msg->l2h[0] |= 0x1; + else + msg->l2h[1] = LAPD_ADDR3(lctx->tei); + + /* write to PCAP file, if enabled. */ + osmo_pcap_lapd_write(li->pcap_fd, OSMO_LAPD_PCAP_OUTPUT, msg); + + /* forward frame to L1 */ + LOGP(DLLAPD, LOGL_DEBUG, "TX: %s\n", osmo_hexdump(msg->data, msg->len)); + li->transmit_cb(msg, li->transmit_cbdata); + + return 0; +} + +/* A DL-SAP message is received from datalink instance and forwarded to L3 */ +static int send_dlsap(struct osmo_dlsap_prim *dp, struct lapd_msg_ctx *lctx) +{ + struct lapd_datalink *dl = lctx->dl; + struct lapd_sap *sap = + container_of(dl, struct lapd_sap, dl); + struct lapd_instance *li; + uint8_t tei, sapi; + char *op = (dp->oph.operation == PRIM_OP_INDICATION) ? "indication" + : "confirm"; + + li = sap->tei->li; + tei = lctx->tei; + sapi = lctx->sapi; + + switch (dp->oph.primitive) { + case PRIM_DL_EST: + LOGP(DLLAPD, LOGL_NOTICE, "LAPD DL-ESTABLISH %s TEI=%d " + "SAPI=%d\n", op, lctx->tei, lctx->sapi); + break; + case PRIM_DL_REL: + LOGP(DLLAPD, LOGL_NOTICE, "LAPD DL-RELEASE %s TEI=%d " + "SAPI=%d\n", op, lctx->tei, lctx->sapi); + lapd_sap_free(sap); + /* note: sap and dl is now gone, don't use it anymore */ + break; + default: + ; + } + + li->receive_cb(dp, tei, sapi, li->receive_cbdata); + + return 0; +} + +/* Allocate a new LAPD instance */ +struct lapd_instance *lapd_instance_alloc(int network_side, + void (*tx_cb)(struct msgb *msg, void *cbdata), void *tx_cbdata, + void (*rx_cb)(struct osmo_dlsap_prim *odp, uint8_t tei, uint8_t sapi, + void *rx_cbdata), void *rx_cbdata, + const struct lapd_profile *profile) +{ + struct lapd_instance *li; + + li = talloc_zero(NULL, struct lapd_instance); + if (!li) + return NULL; + + li->network_side = network_side; + li->transmit_cb = tx_cb; + li->transmit_cbdata = tx_cbdata; + li->receive_cb = rx_cb; + li->receive_cbdata = rx_cbdata; + li->pcap_fd = -1; + memcpy(&li->profile, profile, sizeof(li->profile)); + + INIT_LLIST_HEAD(&li->tei_list); + + return li; +} + +/* Change lapd-profile on the fly (use with caution!) */ +void lapd_instance_set_profile(struct lapd_instance *li, + const struct lapd_profile *profile) +{ + memcpy(&li->profile, profile, sizeof(li->profile)); +} + +void lapd_instance_free(struct lapd_instance *li) +{ + struct lapd_tei *teip, *teip2; + + /* Free all TEI instances */ + llist_for_each_entry_safe(teip, teip2, &li->tei_list, list) { + lapd_tei_free(teip); + } + + talloc_free(li); +} diff --git a/src/input/lapd_pcap.c b/src/input/lapd_pcap.c new file mode 100644 index 0000000..7374694 --- /dev/null +++ b/src/input/lapd_pcap.c @@ -0,0 +1,178 @@ +/* (C) 2008-2012 by Harald Welte <laforge@gnumonks.org> + * + * All Rights Reserved + * + * Author: Harald Welte <laforge@gnumonks.org> + * Pablo Neira Ayuso <pablo@gnumonks.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +#include <stdio.h> +#include <stdint.h> +#include <stddef.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <unistd.h> +#include <sys/time.h> +#include <arpa/inet.h> +#include <string.h> +#include <errno.h> + +#include <osmocom/core/msgb.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/utils.h> + +#include <osmocom/abis/lapd_pcap.h> + +/* + * pcap writing of the mlapd load + * pcap format is from http://wiki.wireshark.org/Development/LibpcapFileFormat + */ +#define DLT_LINUX_LAPD 177 +#define LINUX_SLL_HOST 0 +#define LINUX_SLL_OUTGOING 4 + +struct pcap_hdr { + uint32_t magic_number; + uint16_t version_major; + uint16_t version_minor; + int32_t thiszone; + uint32_t sigfigs; + uint32_t snaplen; + uint32_t network; +} __attribute__((packed)); + +struct pcap_rechdr { + uint32_t ts_sec; + uint32_t ts_usec; + uint32_t incl_len; + uint32_t orig_len; +} __attribute__((packed)); + +struct pcap_lapdhdr { + uint16_t pkttype; + uint16_t hatype; + uint16_t halen; + uint8_t addr[8]; + int16_t protocol; +} __attribute__((packed)); + +osmo_static_assert(offsetof(struct pcap_lapdhdr, hatype) == 2, hatype_offset); +osmo_static_assert(offsetof(struct pcap_lapdhdr, halen) == 4, halen_offset); +osmo_static_assert(offsetof(struct pcap_lapdhdr, addr) == 6, addr_offset); +osmo_static_assert(offsetof(struct pcap_lapdhdr, protocol) == 14, proto_offset); +osmo_static_assert(sizeof(struct pcap_lapdhdr) == 16, lapd_header_size); + +int osmo_pcap_lapd_set_fd(int fd) +{ + struct pcap_hdr pcap_header = { + .magic_number = 0xa1b2c3d4, + .version_major = 2, + .version_minor = 4, + .thiszone = 0, + .sigfigs = 0, + .snaplen = 65535, + .network = DLT_LINUX_LAPD, + }; + + if (write(fd, &pcap_header, sizeof(pcap_header)) + != sizeof(pcap_header)) { + LOGP(DLLAPD, LOGL_ERROR, "cannot write PCAP header: %s\n", + strerror(errno)); + close(fd); + return -1; + } + + return 0; +} + +int osmo_pcap_lapd_open(char *filename, mode_t mode) +{ + int fd, rc; + + LOGP(DLLAPD, LOGL_NOTICE, "opening LAPD pcap file `%s'\n", filename); + + fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, mode); + if (fd < 0) { + LOGP(DLLAPD, LOGL_ERROR, "failed to open PCAP file: %s\n", + strerror(errno)); + return -1; + } + + rc = osmo_pcap_lapd_set_fd(fd); + if (rc < 0) { + close(fd); + return rc; + } + + return fd; +} + +/* This currently only works for the D-Channel */ +int osmo_pcap_lapd_write(int fd, int direction, struct msgb *msg) +{ + int numbytes = 0; + struct timeval tv; + struct pcap_rechdr pcap_rechdr; + struct pcap_lapdhdr header; + char buf[sizeof(struct pcap_rechdr) + + sizeof(struct pcap_lapdhdr) + msg->len]; + + /* PCAP file has not been opened, skip. */ + if (fd < 0) + return 0; + + pcap_rechdr.ts_sec = 0; + pcap_rechdr.ts_usec = 0; + pcap_rechdr.incl_len = msg->len + sizeof(struct pcap_lapdhdr); + pcap_rechdr.orig_len = msg->len + sizeof(struct pcap_lapdhdr); + + if (direction == OSMO_LAPD_PCAP_OUTPUT) + header.pkttype = htons(LINUX_SLL_OUTGOING); + else + header.pkttype = htons(LINUX_SLL_HOST); + header.hatype = 0; + header.halen = 0; + header.addr[0] = 0x01; /* we are the network side */ + header.protocol = ntohs(48); + + gettimeofday(&tv, NULL); + pcap_rechdr.ts_sec = tv.tv_sec; + pcap_rechdr.ts_usec = tv.tv_usec; + + memcpy(buf + numbytes, &pcap_rechdr, sizeof(pcap_rechdr)); + numbytes += sizeof(pcap_rechdr); + + memcpy(buf + numbytes, &header, sizeof(header)); + numbytes += sizeof(header); + + memcpy(buf + numbytes, msg->data, msg->len); + numbytes += msg->len; + + if (write(fd, buf, numbytes) != numbytes) { + LOGP(DLLAPD, LOGL_ERROR, "cannot write packet to PCAP: %s\n", + strerror(errno)); + return -1; + } + return numbytes; +} + +int osmo_pcap_lapd_close(int fd) +{ + LOGP(DLLAPD, LOGL_NOTICE, "closing LAPD pcap file\n"); + return close(fd); +} diff --git a/src/input/misdn.c b/src/input/misdn.c new file mode 100644 index 0000000..347b7bf --- /dev/null +++ b/src/input/misdn.c @@ -0,0 +1,788 @@ +/* OpenBSC Abis input driver for mISDNuser */ + +/* (C) 2008-2011 by Harald Welte <laforge@gnumonks.org> + * (C) 2009 by Holger Hans Peter Freyther <zecke@selfish.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/>. + * + */ + +/*! \file misdn.c + * \brief Osmocom A-bis input driver for mISDN + * + * This driver has two modes of operations, exported via two different + * \ref e1_input_driver structures: + * "misdn" is the classic version and it uses the in-kernel LAPD + * implementation. This is somewhat limited in e.g. the fact that + * you can only have one E1 timeslot in signaling mode. + * "misdn_lapd" is a newer version which uses userspace LAPD code + * contained in libosmo-abis. It offers the same flexibilty as the + * DAHDI driver, i.e. any number of signaling slots. + */ + +#include "internal.h" + +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> +#include <errno.h> +#include <string.h> +#include <time.h> +#include <sys/socket.h> +#include <sys/types.h> +#include <sys/ioctl.h> +#include <arpa/inet.h> +#include <mISDNif.h> + +//#define AF_COMPATIBILITY_FUNC +//#include <compat_af_isdn.h> +#ifndef AF_ISDN +#define AF_ISDN 34 +#define PF_ISDN AF_ISDN +#endif + +#include <osmocom/core/select.h> +#include <osmocom/core/utils.h> +#include <osmocom/core/msgb.h> +#include <osmocom/core/logging.h> +#include <osmocom/abis/e1_input.h> +#include <osmocom/abis/lapd.h> +#include <osmocom/core/talloc.h> + +#define TS1_ALLOC_SIZE 300 + +/*! \brief driver-specific data for \ref e1inp_line::driver_data */ +struct misdn_line { + int use_userspace_lapd; + int dummy_dchannel; +}; + +const struct value_string prim_names[] = { + { PH_CONTROL_IND, "PH_CONTROL_IND" }, + { PH_DATA_IND, "PH_DATA_IND" }, + { PH_DATA_CNF, "PH_DATA_CNF" }, + { PH_ACTIVATE_IND, "PH_ACTIVATE_IND" }, + { DL_ESTABLISH_IND, "DL_ESTABLISH_IND" }, + { DL_ESTABLISH_CNF, "DL_ESTABLISH_CNF" }, + { DL_RELEASE_IND, "DL_RELEASE_IND" }, + { DL_RELEASE_CNF, "DL_RELEASE_CNF" }, + { DL_DATA_IND, "DL_DATA_IND" }, + { DL_UNITDATA_IND, "DL_UNITDATA_IND" }, + { DL_INFORMATION_IND, "DL_INFORMATION_IND" }, + { MPH_ACTIVATE_IND, "MPH_ACTIVATE_IND" }, + { MPH_DEACTIVATE_IND, "MPH_DEACTIVATE_IND" }, + { 0, NULL } +}; + +static int handle_ts1_read(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + struct misdn_line *mline = line->driver_data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct e1inp_sign_link *link; + struct msgb *msg = msgb_alloc(TS1_ALLOC_SIZE, "mISDN TS1"); + struct sockaddr_mISDN l2addr; + struct mISDNhead *hh; + socklen_t alen; + int ret; + + if (!msg) + return -ENOMEM; + + hh = (struct mISDNhead *) msg->data; + + alen = sizeof(l2addr); + ret = recvfrom(bfd->fd, msg->data, 300, 0, + (struct sockaddr *) &l2addr, &alen); + if (ret < 0) { + fprintf(stderr, "recvfrom error %s\n", strerror(errno)); + msgb_free(msg); + return ret; + } + + if (alen != sizeof(l2addr)) { + fprintf(stderr, "%s error len\n", __func__); + msgb_free(msg); + return -EINVAL; + } + + msgb_put(msg, ret); + + DEBUGP(DLMI, "alen =%d, dev(%d) channel(%d) sapi(%d) tei(%d)\n", + alen, l2addr.dev, l2addr.channel, l2addr.sapi, l2addr.tei); + + DEBUGP(DLMI, "<= len = %d, prim(0x%x) id(0x%x): %s\n", + ret, hh->prim, hh->id, get_value_string(prim_names, hh->prim)); + + switch (hh->prim) { + case DL_INFORMATION_IND: + /* mISDN tells us which channel number is allocated for this + * tuple of (SAPI, TEI). */ + DEBUGP(DLMI, "DL_INFORMATION_IND: use channel(%d) sapi(%d) tei(%d) for now\n", + l2addr.channel, l2addr.sapi, l2addr.tei); + link = e1inp_lookup_sign_link(e1i_ts, l2addr.tei, l2addr.sapi); + if (!link) { + DEBUGPC(DLMI, "mISDN message for unknown sign_link\n"); + msgb_free(msg); + return -EINVAL; + } + /* save the channel number in the driver private struct */ + link->driver.misdn.channel = l2addr.channel; + msgb_free(msg); + break; + case DL_ESTABLISH_IND: + DEBUGP(DLMI, "DL_ESTABLISH_IND: channel(%d) sapi(%d) tei(%d)\n", + l2addr.channel, l2addr.sapi, l2addr.tei); + /* For some strange reason, sometimes the DL_INFORMATION_IND tells + * us the wrong channel, and we only get the real channel number + * during the DL_ESTABLISH_IND */ + link = e1inp_lookup_sign_link(e1i_ts, l2addr.tei, l2addr.sapi); + if (!link) { + DEBUGPC(DLMI, "mISDN message for unknown sign_link\n"); + msgb_free(msg); + return -EINVAL; + } + /* save the channel number in the driver private struct */ + link->driver.misdn.channel = l2addr.channel; + ret = e1inp_event(e1i_ts, S_L_INP_TEI_UP, l2addr.tei, l2addr.sapi); + msgb_free(msg); + break; + case DL_RELEASE_IND: + DEBUGP(DLMI, "DL_RELEASE_IND: channel(%d) sapi(%d) tei(%d)\n", + l2addr.channel, l2addr.sapi, l2addr.tei); + ret = e1inp_event(e1i_ts, S_L_INP_TEI_DN, l2addr.tei, l2addr.sapi); + msgb_free(msg); + break; + case DL_DATA_IND: + case DL_UNITDATA_IND: + msg->l2h = msg->data + MISDN_HEADER_LEN; + DEBUGP(DLMI, "RX: %s\n", osmo_hexdump(msgb_l2(msg), ret - MISDN_HEADER_LEN)); + if (mline->use_userspace_lapd) { + LOGP(DLMI, LOGL_ERROR, "DL_DATA_IND but userspace LAPD ?!?\n"); + msgb_free(msg); + return -EIO; + } + ret = e1inp_rx_ts(e1i_ts, msg, l2addr.tei, l2addr.sapi); + break; + case PH_ACTIVATE_IND: + DEBUGP(DLMI, "PH_ACTIVATE_IND: channel(%d) sapi(%d) tei(%d)\n", + l2addr.channel, l2addr.sapi, l2addr.tei); + msgb_free(msg); + break; + case PH_DEACTIVATE_IND: + DEBUGP(DLMI, "PH_DEACTIVATE_IND: channel(%d) sapi(%d) tei(%d)\n", + l2addr.channel, l2addr.sapi, l2addr.tei); + msgb_free(msg); + break; + case PH_DATA_IND: + if (!mline->use_userspace_lapd) { + LOGP(DLMI, LOGL_ERROR, "PH_DATA_IND but kernel LAPD ?!?\n"); + return -EIO; + } + /* remove the Misdn Header */ + msgb_pull(msg, MISDN_HEADER_LEN); + /* hand into the LAPD code */ + DEBUGP(DLMI, "RX: %s\n", osmo_hexdump(msg->data, msg->len)); + ret = e1inp_rx_ts_lapd(e1i_ts, msg); + break; + default: + msgb_free(msg); + break; + } + return ret; +} + +static int ts_want_write(struct e1inp_ts *e1i_ts) +{ + /* We never include the mISDN B-Channel FD into the + * writeset, since it doesn't support poll() based + * write flow control */ + if (e1i_ts->type == E1INP_TS_TYPE_TRAU) + return 0; + + e1i_ts->driver.misdn.fd.when |= BSC_FD_WRITE; + + return 0; +} + +static void timeout_ts1_write(void *data) +{ + struct e1inp_ts *e1i_ts = (struct e1inp_ts *)data; + + /* trigger write of ts1, due to tx delay timer */ + ts_want_write(e1i_ts); +} + +static int handle_ts1_write(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + struct misdn_line *mline = line->driver_data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct e1inp_sign_link *sign_link; + struct sockaddr_mISDN sa; + struct msgb *msg; + struct mISDNhead *hh; + uint8_t *l2_data; + int ret; + + bfd->when &= ~BSC_FD_WRITE; + + /* get the next msg for this timeslot */ + msg = e1inp_tx_ts(e1i_ts, &sign_link); + if (!msg) { + /* no message after tx delay timer */ + return 0; + } + + if (mline->use_userspace_lapd) { + DEBUGP(DLMI, "TX %u/%u/%u: %s\n", + line->num, sign_link->tei, sign_link->sapi, + osmo_hexdump(msg->data, msg->len)); + lapd_transmit(e1i_ts->lapd, sign_link->tei, + sign_link->sapi, msg); + ret = 0; + } else { + l2_data = msg->data; + + /* prepend the mISDNhead */ + hh = (struct mISDNhead *) msgb_push(msg, sizeof(*hh)); + hh->prim = DL_DATA_REQ; + + DEBUGP(DLMI, "TX channel(%d) TEI(%d) SAPI(%d): %s\n", + sign_link->driver.misdn.channel, sign_link->tei, + sign_link->sapi, osmo_hexdump(l2_data, msg->len - MISDN_HEADER_LEN)); + + /* construct the sockaddr */ + sa.family = AF_ISDN; + sa.sapi = sign_link->sapi; + sa.dev = sign_link->tei; + sa.channel = sign_link->driver.misdn.channel; + + ret = sendto(bfd->fd, msg->data, msg->len, 0, + (struct sockaddr *)&sa, sizeof(sa)); + if (ret < 0) + fprintf(stderr, "%s sendto failed %d\n", __func__, ret); + + msgb_free(msg); + } + + + /* set tx delay timer for next event */ + osmo_timer_setup(&e1i_ts->sign.tx_timer, timeout_ts1_write, e1i_ts); + osmo_timer_schedule(&e1i_ts->sign.tx_timer, 0, e1i_ts->sign.delay); + + return ret; +} + +/*! \brief call-back from LAPD code, called when it wants to Tx data */ +static void misdn_write_msg(struct msgb *msg, void *cbdata) +{ + struct osmo_fd *bfd = cbdata; +// struct e1inp_line *line = bfd->data; +// unsigned int ts_nr = bfd->priv_nr; +// struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct mISDNhead *hh; + int ret; + + DEBUGP(DLMI, "PH_DATA_REQ: len=%d %s\n", msg->len, + osmo_hexdump(msg->data, msg->len)); + + hh = (struct mISDNhead *) msgb_push(msg, MISDN_HEADER_LEN); + hh->prim = PH_DATA_REQ; + hh->id = 0; + + ret = write(bfd->fd, msg->data, msg->len); + if (ret < 0) + LOGP(DLMI, LOGL_NOTICE, "write failed %d\n", ret); + + msgb_free(msg); +} + +/* write to a B channel TS */ +static int handle_tsX_write(struct osmo_fd *bfd, int len) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct mISDNhead *hh; + uint8_t tx_buf[len + sizeof(*hh)]; + struct subch_mux *mx = &e1i_ts->trau.mux; + int ret; + + hh = (struct mISDNhead *) tx_buf; + hh->prim = PH_DATA_REQ; + hh->id = 0; + + subchan_mux_out(mx, tx_buf+sizeof(*hh), len); + + DEBUGP(DLMIB, "BCHAN TX: %s\n", + osmo_hexdump(tx_buf+sizeof(*hh), len)); + + ret = send(bfd->fd, tx_buf, sizeof(*hh) + len, 0); + if (ret < sizeof(*hh) + len) + DEBUGP(DLMIB, "send returns %d instead of %zu\n", ret, + sizeof(*hh) + len); + + return ret; +} + +#define TSX_ALLOC_SIZE 4096 +/* FIXME: read from a B channel TS */ +static int handle_tsX_read(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct msgb *msg = msgb_alloc(TSX_ALLOC_SIZE, "mISDN TSx"); + struct mISDNhead *hh; + int ret; + + if (!msg) + return -ENOMEM; + + hh = (struct mISDNhead *) msg->data; + + ret = recv(bfd->fd, msg->data, TSX_ALLOC_SIZE, 0); + if (ret < 0) { + fprintf(stderr, "recvfrom error %s\n", strerror(errno)); + return ret; + } + + msgb_put(msg, ret); + + if (hh->prim != PH_CONTROL_IND) + DEBUGP(DLMIB, "<= BCHAN len = %d, prim(0x%x) id(0x%x): %s\n", + ret, hh->prim, hh->id, + get_value_string(prim_names, hh->prim)); + + switch (hh->prim) { + case PH_DATA_IND: + msg->l2h = msg->data + MISDN_HEADER_LEN; + DEBUGP(DLMIB, "BCHAN RX: %s\n", + osmo_hexdump(msgb_l2(msg), ret - MISDN_HEADER_LEN)); + /* the number of bytes received indicates that data to send */ + handle_tsX_write(bfd, msgb_l2len(msg)); + return e1inp_rx_ts(e1i_ts, msg, 0, 0); + case PH_ACTIVATE_IND: + case PH_DATA_CNF: + break; + default: + break; + } + /* FIXME: why do we free signalling msgs in the caller, and trau not? */ + msgb_free(msg); + + return ret; +} + +/* write to a raw channel TS */ +static int handle_ts_raw_write(struct osmo_fd *bfd, unsigned int len) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct msgb *msg; + struct mISDNhead *hh; + int ret; + + /* get the next msg for this timeslot */ + msg = e1inp_tx_ts(e1i_ts, NULL); + if (!msg) + return 0; + + if (msg->len != len) { + /* This might lead to a transmit underrun, as we call tx + * from the rx path, as there's no select/poll on dahdi + * */ + LOGP(DLINP, LOGL_NOTICE, "unexpected msg->len = %u, " + "expected %u\n", msg->len, len); + } + + DEBUGP(DLMIB, "RAW CHAN TX: %s\n", + osmo_hexdump(msg->data, msg->len)); + + hh = (struct mISDNhead *) msgb_push(msg, sizeof(*hh)); + hh->prim = PH_DATA_REQ; + hh->id = 0; + + ret = write(bfd->fd, msg->data, msg->len); + if (ret < msg->len) + LOGP(DLINP, LOGL_DEBUG, "send returns %d instead of %d\n", + ret, msg->len); + msgb_free(msg); + + return ret; +} + +static int handle_ts_raw_read(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + struct e1inp_ts *e1i_ts = &line->ts[ts_nr-1]; + struct msgb *msg = msgb_alloc(TSX_ALLOC_SIZE, "mISDN Tx RAW"); + struct mISDNhead *hh; + int ret; + + if (!msg) + return -ENOMEM; + + hh = (struct mISDNhead *) msg->data; + + ret = recv(bfd->fd, msg->data, TSX_ALLOC_SIZE, 0); + if (ret < 0) { + fprintf(stderr, "recvfrom error %s\n", strerror(errno)); + return ret; + } + + msgb_put(msg, ret); + + if (hh->prim != PH_CONTROL_IND) + DEBUGP(DLMIB, "<= RAW CHAN len = %d, prim(0x%x) id(0x%x): %s\n", + ret, hh->prim, hh->id, + get_value_string(prim_names, hh->prim)); + + switch (hh->prim) { + case PH_DATA_IND: + msg->l2h = msg->data + MISDN_HEADER_LEN; + DEBUGP(DLMIB, "RAW CHAN RX: %s\n", + osmo_hexdump(msgb_l2(msg), ret - MISDN_HEADER_LEN)); + /* the number of bytes received indicates that data to send */ + handle_ts_raw_write(bfd, msgb_l2len(msg)); + return e1inp_rx_ts(e1i_ts, msg, 0, 0); + case PH_ACTIVATE_IND: + case PH_DATA_CNF: + break; + default: + break; + } + /* FIXME: why do we free signalling msgs in the caller, and trau not? */ + msgb_free(msg); + + return ret; +} + +/* callback from select.c in case one of the fd's can be read/written */ +static int misdn_fd_cb(struct osmo_fd *bfd, unsigned int what) +{ + struct e1inp_line *line = bfd->data; + unsigned int ts_nr = bfd->priv_nr; + unsigned int idx = ts_nr-1; + struct e1inp_ts *e1i_ts = &line->ts[idx]; + int rc = 0; + + switch (e1i_ts->type) { + case E1INP_TS_TYPE_SIGN: + if (what & BSC_FD_READ) + rc = handle_ts1_read(bfd); + if (what & BSC_FD_WRITE) + rc = handle_ts1_write(bfd); + break; + case E1INP_TS_TYPE_TRAU: + if (what & BSC_FD_READ) + rc = handle_tsX_read(bfd); + /* We never include the mISDN B-Channel FD into the + * writeset, since it doesn't support poll() based + * write flow control */ + break; + case E1INP_TS_TYPE_RAW: + if (what & BSC_FD_READ) + rc = handle_ts_raw_read(bfd); + /* We never include the mISDN B-Channel FD into the + * writeset, since it doesn't support poll() based + * write flow control */ + break; + default: + fprintf(stderr, "unknown E1 TS type %u\n", e1i_ts->type); + break; + } + + return rc; +} + +static int activate_bchan(struct e1inp_line *line, int ts, int act) +{ + struct mISDNhead hh; + int ret; + unsigned int idx = ts-1; + struct e1inp_ts *e1i_ts = &line->ts[idx]; + struct osmo_fd *bfd = &e1i_ts->driver.misdn.fd; + + fprintf(stdout, "activate bchan\n"); + if (act) + hh.prim = PH_ACTIVATE_REQ; + else + hh.prim = PH_DEACTIVATE_REQ; + + hh.id = MISDN_ID_ANY; + ret = sendto(bfd->fd, &hh, sizeof(hh), 0, NULL, 0); + if (ret < 0) { + fprintf(stdout, "could not send ACTIVATE_RQ %s\n", + strerror(errno)); + } + + return ret; +} + +static int mi_e1_line_update(struct e1inp_line *line); +static int mi_e1_line_update_lapd(struct e1inp_line *line); + +struct e1inp_driver misdn_driver = { + .name = "misdn", + .want_write = ts_want_write, + .default_delay = 50000, + .line_update = &mi_e1_line_update, +}; + +struct e1inp_driver misdn_lapd_driver = { + .name = "misdn_lapd", + .want_write = ts_want_write, + .default_delay = 50000, + .line_update = &mi_e1_line_update_lapd, +}; + +static int mi_e1_setup(struct e1inp_line *line, int release_l2) +{ + struct misdn_line *mline = line->driver_data; + int ts, ret; + + mline->dummy_dchannel = -1; + if (mline->use_userspace_lapd) { + /* Open dummy d-channel in order to use b-channels. + * Also it is required to define the mode. + */ + if (mline->dummy_dchannel < 0) { + struct sockaddr_mISDN addr; + + mline->dummy_dchannel = socket(PF_ISDN, SOCK_DGRAM, + ISDN_P_NT_E1); + if (mline->dummy_dchannel < 0) { + fprintf(stderr, "%s could not open socket %s\n", + __func__, strerror(errno)); + return mline->dummy_dchannel; + } + memset(&addr, 0, sizeof(addr)); + addr.family = AF_ISDN; + addr.dev = line->port_nr; + addr.channel = 0; + addr.sapi = 0; + addr.tei = GROUP_TEI; + ret = bind(mline->dummy_dchannel, + (struct sockaddr *) &addr, sizeof(addr)); + if (ret < 0) { + fprintf(stderr, "could not bind l2 socket %s\n", + strerror(errno)); + return -EIO; + } + } + } + + /* TS0 is CRC4, don't need any fd for it */ + for (ts = 1; ts < NUM_E1_TS; ts++) { + unsigned int idx = ts-1; + struct e1inp_ts *e1i_ts = &line->ts[idx]; + struct osmo_fd *bfd = &e1i_ts->driver.misdn.fd; + struct sockaddr_mISDN addr; + + bfd->data = line; + bfd->priv_nr = ts; + bfd->cb = misdn_fd_cb; + + switch (e1i_ts->type) { + case E1INP_TS_TYPE_NONE: + continue; + break; + case E1INP_TS_TYPE_HDLC: + bfd->fd = socket(PF_ISDN, SOCK_DGRAM, + ISDN_P_B_HDLC); + bfd->when = BSC_FD_READ; + break; + case E1INP_TS_TYPE_SIGN: + if (mline->use_userspace_lapd) + bfd->fd = socket(PF_ISDN, SOCK_DGRAM, + ISDN_P_B_HDLC); + else + bfd->fd = socket(PF_ISDN, SOCK_DGRAM, + ISDN_P_LAPD_NT); + bfd->when = BSC_FD_READ; + break; + case E1INP_TS_TYPE_TRAU: + case E1INP_TS_TYPE_RAW: + bfd->fd = socket(PF_ISDN, SOCK_DGRAM, ISDN_P_B_RAW); + /* We never include the mISDN B-Channel FD into the + * writeset, since it doesn't support poll() based + * write flow control */ + bfd->when = BSC_FD_READ; + break; + } + + if (bfd->fd < 0) { + fprintf(stderr, "%s could not open socket %s\n", + __func__, strerror(errno)); + return bfd->fd; + } + + memset(&addr, 0, sizeof(addr)); + addr.family = AF_ISDN; + addr.dev = line->port_nr; + switch (e1i_ts->type) { + case E1INP_TS_TYPE_SIGN: + if (mline->use_userspace_lapd) { + addr.channel = ts; + e1i_ts->lapd = lapd_instance_alloc(1, + misdn_write_msg, bfd, e1inp_dlsap_up, + e1i_ts, &lapd_profile_abis); + } else { + addr.channel = 0; + /* SAPI not supported yet in kernel */ + //addr.sapi = e1inp_ts->sign.sapi; + addr.sapi = 0; + addr.tei = GROUP_TEI; + } + break; + case E1INP_TS_TYPE_HDLC: + case E1INP_TS_TYPE_TRAU: + addr.channel = ts; + break; + default: + DEBUGP(DLMI, "unsupported E1 TS type: %u\n", + e1i_ts->type); + break; + } + + ret = bind(bfd->fd, (struct sockaddr *) &addr, sizeof(addr)); + if (ret < 0) { + fprintf(stderr, "could not bind l2 socket %s\n", + strerror(errno)); + return -EIO; + } + + if (e1i_ts->type == E1INP_TS_TYPE_SIGN) { + if (!mline->use_userspace_lapd) { + ret = ioctl(bfd->fd, IMCLEAR_L2, &release_l2); + if (ret < 0) { + fprintf(stderr, "could not send IOCTL IMCLEAN_L2 %s\n", strerror(errno)); + return -EIO; + } + } else + activate_bchan(line, ts, 1); + } + + /* FIXME: only activate B-Channels once we start to + * use them to conserve CPU power */ + if (e1i_ts->type == E1INP_TS_TYPE_TRAU) + activate_bchan(line, ts, 1); + + ret = osmo_fd_register(bfd); + if (ret < 0) { + fprintf(stderr, "could not register FD: %s\n", + strerror(-ret)); + return ret; + } + } + + return 0; +} + +static int _mi_e1_line_update(struct e1inp_line *line) +{ + struct mISDN_devinfo devinfo; + int sk, ret, cnt; + + if (line->driver != &misdn_driver && + line->driver != &misdn_lapd_driver) + return -EINVAL; + + /* open the ISDN card device */ + sk = socket(PF_ISDN, SOCK_RAW, ISDN_P_BASE); + if (sk < 0) { + fprintf(stderr, "%s could not open socket %s\n", + __func__, strerror(errno)); + return sk; + } + + ret = ioctl(sk, IMGETCOUNT, &cnt); + if (ret) { + fprintf(stderr, "%s error getting interf count: %s\n", + __func__, strerror(errno)); + close(sk); + return -ENODEV; + } + //DEBUGP(DLMI,"%d device%s found\n", cnt, (cnt==1)?"":"s"); + printf("%d device%s found\n", cnt, (cnt==1)?"":"s"); +#if 1 + devinfo.id = line->port_nr; + ret = ioctl(sk, IMGETDEVINFO, &devinfo); + if (ret < 0) { + fprintf(stdout, "error getting info for device %d: %s\n", + line->port_nr, strerror(errno)); + close(sk); + return -ENODEV; + } + fprintf(stdout, " id: %d\n", devinfo.id); + fprintf(stdout, " Dprotocols: %08x\n", devinfo.Dprotocols); + fprintf(stdout, " Bprotocols: %08x\n", devinfo.Bprotocols); + fprintf(stdout, " protocol: %d\n", devinfo.protocol); + fprintf(stdout, " nrbchan: %d\n", devinfo.nrbchan); + fprintf(stdout, " name: %s\n", devinfo.name); +#endif + close(sk); + + if (!(devinfo.Dprotocols & (1 << ISDN_P_NT_E1))) { + fprintf(stderr, "error: card is not of type E1 (NT-mode)\n"); + return -EINVAL; + } + + ret = mi_e1_setup(line, 1); + if (ret) + return ret; + + return 0; +} + +static int mi_e1_line_update(struct e1inp_line *line) +{ + struct misdn_line *ml; + + if (!line->driver_data) + line->driver_data = talloc_zero(line, struct misdn_line); + + ml = line->driver_data; + ml->use_userspace_lapd = 0; + + return _mi_e1_line_update(line); +} + +static int mi_e1_line_update_lapd(struct e1inp_line *line) +{ + struct misdn_line *ml; + + if (!line->driver_data) + line->driver_data = talloc_zero(line, struct misdn_line); + + ml = line->driver_data; + ml->use_userspace_lapd = 1; + + return _mi_e1_line_update(line); +} + +void e1inp_misdn_init(void) +{ + /* register the driver with the core */ + e1inp_driver_register(&misdn_driver); + e1inp_driver_register(&misdn_lapd_driver); +} diff --git a/src/input/rs232.c b/src/input/rs232.c new file mode 100644 index 0000000..9da01a3 --- /dev/null +++ b/src/input/rs232.c @@ -0,0 +1,300 @@ +/* T-Link interface using POSIX serial port */ + +/* (C) 2008-2011 by Harald Welte <laforge@gnumonks.org> + * + * All Rights Reserved + * + * Authors: Harald Welte <laforge@gnumonks.org> + * Pablo Neira Ayuso <pablo@gnumonks.org> + * + * 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 <unistd.h> +#include <stdlib.h> +#include <stdio.h> +#include <errno.h> +#include <string.h> +#include <termios.h> +#include <fcntl.h> + +#include <osmocom/core/select.h> +#include <osmocom/core/msgb.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/talloc.h> +#include <osmocom/abis/e1_input.h> + +static void *tall_rs232_ctx; + +struct serial_handle { + struct e1inp_line *line; + + struct msgb *rx_msg; + unsigned int rxmsg_bytes_missing; + + unsigned int delay_ms; +}; + +#define CRAPD_HDR_LEN 10 + +static int handle_ser_write(struct osmo_fd *bfd); + +static void rs232_build_msg(struct msgb *msg) +{ + uint8_t *crapd; + unsigned int len; + + msg->l2h = msg->data; + + /* prepend CRAPD header */ + crapd = msgb_push(msg, CRAPD_HDR_LEN); + + len = msg->len - 2; + + crapd[0] = (len >> 8) & 0xff; + crapd[1] = len & 0xff; /* length of bytes startign at crapd[2] */ + crapd[2] = 0x00; + crapd[3] = 0x07; + crapd[4] = 0x01; + crapd[5] = 0x3e; + crapd[6] = 0x00; + crapd[7] = 0x00; + crapd[8] = msg->len - 10; /* length of bytes starting at crapd[10] */ + crapd[9] = crapd[8] ^ 0x38; +} + +/* select.c callback in case we can write to the rs232 */ +static int handle_ser_write(struct osmo_fd *bfd) +{ + struct serial_handle *sh = bfd->data; + struct e1inp_ts *e1i_ts = &sh->line->ts[0]; + struct e1inp_sign_link *sign_link; + struct msgb *msg; + int written; + + bfd->when &= ~BSC_FD_WRITE; + + /* get the next msg for this timeslot */ + msg = e1inp_tx_ts(e1i_ts, &sign_link); + if (!msg) { + /* no message after tx delay timer */ + return 0; + } + DEBUGP(DLMI, "rs232 TX: %s\n", osmo_hexdump(msg->data, msg->len)); + + rs232_build_msg(msg); + + /* send over serial line */ + written = write(bfd->fd, msg->data, msg->len); + if (written < msg->len) { + LOGP(DLMI, LOGL_ERROR, "rs232: short write\n"); + msgb_free(msg); + return -1; + } + + msgb_free(msg); + usleep(sh->delay_ms*1000); + + return 0; +} + +#define SERIAL_ALLOC_SIZE 300 + +/* select.c callback in case we can read from the rs232 */ +static int handle_ser_read(struct osmo_fd *bfd) +{ + struct serial_handle *sh = bfd->data; + struct msgb *msg; + int rc = 0; + + if (!sh->rx_msg) { + sh->rx_msg = msgb_alloc(SERIAL_ALLOC_SIZE, "rs232 Rx"); + sh->rx_msg->l2h = NULL; + } + msg = sh->rx_msg; + + /* first read two byes to obtain length */ + if (msg->len < 2) { + rc = read(bfd->fd, msg->tail, 2 - msg->len); + if (rc < 0) { + LOGP(DLMI, LOGL_ERROR, "rs232: error reading from " + "serial port: %s\n", strerror(errno)); + msgb_free(msg); + return rc; + } + msgb_put(msg, rc); + + if (msg->len >= 2) { + /* parse CRAPD payload length */ + if (msg->data[0] != 0) { + LOGP(DLMI, LOGL_ERROR, + "Suspicious header byte 0: 0x%02x\n", + msg->data[0]); + } + sh->rxmsg_bytes_missing = msg->data[0] << 8; + sh->rxmsg_bytes_missing += msg->data[1]; + + if (sh->rxmsg_bytes_missing < CRAPD_HDR_LEN -2) { + LOGP(DLMI, LOGL_ERROR, + "Invalid length in hdr: %u\n", + sh->rxmsg_bytes_missing); + } + } + } else { + /* try to read as many of the missing bytes as are available */ + rc = read(bfd->fd, msg->tail, sh->rxmsg_bytes_missing); + if (rc < 0) { + LOGP(DLMI, LOGL_ERROR, "rs232: error reading from " + "serial port: %s", strerror(errno)); + msgb_free(msg); + return rc; + } + msgb_put(msg, rc); + sh->rxmsg_bytes_missing -= rc; + + if (sh->rxmsg_bytes_missing == 0) { + struct e1inp_ts *e1i_ts = &sh->line->ts[0]; + + /* we have one complete message now */ + sh->rx_msg = NULL; + + if (msg->len > CRAPD_HDR_LEN) + msg->l2h = msg->data + CRAPD_HDR_LEN; + + DEBUGP(DLMI, "rs232 RX: %s", + osmo_hexdump(msg->data, msg->len)); + + /* don't use e1inp_tx_ts() here, this header does not + * contain any SAPI and TEI values. */ + if (!e1i_ts->line->ops->sign_link) { + LOGP(DLMI, LOGL_ERROR, "rs232: no callback set, " + "skipping message.\n"); + return -EINVAL; + } + e1i_ts->line->ops->sign_link(msg); + } + } + + return rc; +} + +/* select.c callback */ +static int serial_fd_cb(struct osmo_fd *bfd, unsigned int what) +{ + int rc = 0; + + if (what & BSC_FD_READ) + rc = handle_ser_read(bfd); + + if (rc < 0) + return rc; + + if (what & BSC_FD_WRITE) + rc = handle_ser_write(bfd); + + return rc; +} + +static int rs232_want_write(struct e1inp_ts *e1i_ts) +{ + e1i_ts->driver.rs232.fd.when |= BSC_FD_WRITE; + + return 0; +} + +static int +rs232_setup(struct e1inp_line *line, const char *serial_port, unsigned int delay_ms) +{ + int rc; + struct osmo_fd *bfd = &line->ts[0].driver.rs232.fd; + struct serial_handle *ser_handle; + struct termios tio; + + rc = open(serial_port, O_RDWR); + if (rc < 0) { + LOGP(DLMI, LOGL_ERROR, "rs232: cannot open serial port: %s", + strerror(errno)); + return rc; + } + bfd->fd = rc; + + /* set baudrate */ + rc = tcgetattr(bfd->fd, &tio); + if (rc < 0) { + LOGP(DLMI, LOGL_ERROR, "rs232: tcgetattr says: %s", + strerror(errno)); + return rc; + } + cfsetispeed(&tio, B19200); + cfsetospeed(&tio, B19200); + tio.c_cflag |= (CREAD | CLOCAL | CS8); + tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS); + tio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); + tio.c_iflag |= (INPCK | ISTRIP); + tio.c_iflag &= ~(ISTRIP | IXON | IXOFF | IGNBRK | INLCR | ICRNL | IGNCR); + tio.c_oflag &= ~(OPOST); + rc = tcsetattr(bfd->fd, TCSADRAIN, &tio); + if (rc < 0) { + LOGP(DLMI, LOGL_ERROR, "rs232: tcsetattr says: %s", + strerror(errno)); + return rc; + } + + ser_handle = talloc_zero(tall_rs232_ctx, struct serial_handle); + if (ser_handle == NULL) { + close(bfd->fd); + LOGP(DLMI, LOGL_ERROR, "rs232: cannot allocate memory for " + "serial handler\n"); + return -ENOMEM; + } + ser_handle->line = line; + ser_handle->delay_ms = delay_ms; + + bfd->when = BSC_FD_READ; + bfd->cb = serial_fd_cb; + bfd->data = ser_handle; + + rc = osmo_fd_register(bfd); + if (rc < 0) { + close(bfd->fd); + LOGP(DLMI, LOGL_ERROR, "rs232: could not register FD: %s\n", + strerror(-rc)); + return rc; + } + + return 0; +} + +static int rs232_line_update(struct e1inp_line *line); + +static struct e1inp_driver rs232_driver = { + .name = "rs232", + .want_write = rs232_want_write, + .line_update = rs232_line_update, +}; + +static int rs232_line_update(struct e1inp_line *line) +{ + if (line->driver != &rs232_driver) + return -EINVAL; + + return rs232_setup(line, line->ops->cfg.rs232.port, + line->ops->cfg.rs232.delay); +} + +int e1inp_rs232_init(void) +{ + return e1inp_driver_register(&rs232_driver); +} diff --git a/src/input/unixsocket.c b/src/input/unixsocket.c new file mode 100644 index 0000000..63bd796 --- /dev/null +++ b/src/input/unixsocket.c @@ -0,0 +1,346 @@ +/* OpenBSC Abis receive lapd over a unix socket */ + +/* (C) 2016 by sysmocom s.f.m.c. GmbH + * + * Author: Alexander Couzens <lynxis@fe80.eu> + * Based on other e1_input drivers. + * + * All Rights Reserved + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +#include <errno.h> +#include <stdio.h> +#include <unistd.h> +#include <sys/socket.h> +#include <limits.h> +#include <string.h> + +#include <osmocom/core/talloc.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/socket.h> + +#include <osmocom/abis/e1_input.h> +#include <osmocom/abis/lapd.h> +#include <osmocom/abis/e1_input.h> + +#include <osmocom/abis/unixsocket_proto.h> +#include "internal.h" + +void *tall_unixsocket_ctx; +#define UNIXSOCKET_ALLOC_SIZE 1600 +#define UNIXSOCKET_SOCK_PATH_DEFAULT "/tmp/osmo_abis_line_" + +struct unixsocket_line { + struct osmo_fd fd; +}; + +static int unixsocket_line_update(struct e1inp_line *line); +static int ts_want_write(struct e1inp_ts *e1i_ts); + +static int unixsocket_exception_cb(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + + LOGP(DLINP, LOGL_ERROR, + "Socket connection failure, reconnecting... (line=%p, fd=%d)\n", + line, bfd->fd); + + /* Unregister faulty file descriptor from select loop */ + if(osmo_fd_is_registered(bfd)) { + LOGP(DLINP, LOGL_DEBUG, + "removing inactive socket from select loop... (line=%p, fd=%d)\n", + line, bfd->fd); + osmo_fd_unregister(bfd); + } + + /* Close faulty file descriptor */ + close(bfd->fd); + + unixsocket_line_update(line); + + return 0; +} + +static int unixsocket_read_cb(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + struct msgb *msg = msgb_alloc(UNIXSOCKET_ALLOC_SIZE, "UNIXSOCKET TS"); + uint8_t version; + uint8_t controldata; + int ret; + + if (!msg) + return -ENOMEM; + + ret = read(bfd->fd, msg->data, UNIXSOCKET_ALLOC_SIZE - 16); + if (ret == 0) { + unixsocket_exception_cb(bfd); + goto fail; + } else if (ret < 0) { + perror("read "); + goto fail; + } else if (ret < 2) { + /* packet must be at least 2 byte long to hold version + control/data header */ + LOGP(DLMI, LOGL_ERROR, "received to small packet: %d < 2", ret); + ret = -1; + goto fail; + } + msgb_put(msg, ret); + + LOGP(DLMI, LOGL_DEBUG, "rx msg: %s (fd=%d)\n", + osmo_hexdump_nospc(msg->data, msg->len), bfd->fd); + + /* check version header */ + version = msgb_pull_u8(msg); + controldata = msgb_pull_u8(msg); + + if (version != UNIXSOCKET_PROTO_VERSION) { + LOGP(DLMI, LOGL_ERROR, "received message with invalid version %d. valid: %d", + ret, UNIXSOCKET_PROTO_VERSION); + ret = -1; + goto fail; + } + + switch (controldata) { + case UNIXSOCKET_PROTO_DATA: + return e1inp_rx_ts_lapd(&line->ts[0], msg); + case UNIXSOCKET_PROTO_CONTROL: + LOGP(DLMI, LOGL_ERROR, "received (invalid) control message."); + ret = -1; + break; + default: + LOGP(DLMI, LOGL_ERROR, "received invalid message."); + ret = -1; + break; + } +fail: + msgb_free(msg); + return ret; +} + +static void timeout_ts1_write(void *data) +{ + struct e1inp_ts *e1i_ts = (struct e1inp_ts *)data; + + /* trigger write of ts1, due to tx delay timer */ + ts_want_write(e1i_ts); +} + +static int unixsocket_write_cb(struct osmo_fd *bfd) +{ + struct e1inp_line *line = bfd->data; + struct e1inp_ts *e1i_ts = &line->ts[0]; + struct msgb *msg; + struct e1inp_sign_link *sign_link; + + bfd->when &= ~BSC_FD_WRITE; + + /* get the next msg for this timeslot */ + msg = e1inp_tx_ts(e1i_ts, &sign_link); + if (!msg) { + /* no message after tx delay timer */ + LOGP(DLINP, LOGL_INFO, + "no message available (line=%p)\n", line); + return 0; + } + + /* set tx delay timer for next event */ + osmo_timer_setup(&e1i_ts->sign.tx_timer, timeout_ts1_write, e1i_ts); + + osmo_timer_schedule(&e1i_ts->sign.tx_timer, 0, e1i_ts->sign.delay); + + LOGP(DLINP, LOGL_DEBUG, "sending: %s (line=%p)\n", + msgb_hexdump(msg), line); + lapd_transmit(e1i_ts->lapd, sign_link->tei, + sign_link->sapi, msg); + + return 0; +} + +static int unixsocket_cb(struct osmo_fd *bfd, unsigned int what) +{ + int ret = 0; + + if (what & BSC_FD_READ) + ret = unixsocket_read_cb(bfd); + if (what & BSC_FD_WRITE) + ret = unixsocket_write_cb(bfd); + + return ret; +} + +static int ts_want_write(struct e1inp_ts *e1i_ts) +{ + struct unixsocket_line *line = e1i_ts->line->driver_data; + + line->fd.when |= BSC_FD_WRITE; + + return 0; +} + +static void unixsocket_write_msg(struct msgb *msg, struct osmo_fd *bfd) { + int ret; + + LOGP(DLMI, LOGL_DEBUG, "tx msg: %s (fd=%d)\n", + osmo_hexdump_nospc(msg->data, msg->len), bfd->fd); + + ret = write(bfd->fd, msg->data, msg->len); + msgb_free(msg); + if (ret == -1) + unixsocket_exception_cb(bfd); + else if (ret < 0) + LOGP(DLMI, LOGL_NOTICE, "%s write failed %d\n", __func__, ret); +} + +/*! + * \brief unixsocket_write_msg lapd callback for data to unixsocket + * \param msg + * \param cbdata + */ +static void unixsocket_write_msg_lapd_cb(struct msgb *msg, void *cbdata) +{ + struct osmo_fd *bfd = cbdata; + + /* data|control */ + msgb_push_u8(msg, UNIXSOCKET_PROTO_DATA); + /* add version header */ + msgb_push_u8(msg, UNIXSOCKET_PROTO_VERSION); + + unixsocket_write_msg(msg, bfd); +} + +static int unixsocket_line_update(struct e1inp_line *line) +{ + struct unixsocket_line *config; + char sock_path[PATH_MAX]; + int ret = 0; + int i; + + if (line->sock_path) + strcpy(sock_path, line->sock_path); + else + sprintf(sock_path, "%s%d", UNIXSOCKET_SOCK_PATH_DEFAULT, + line->num); + + LOGP(DLINP, LOGL_NOTICE, "line update (line=%p)\n", line); + + if (!line->driver_data) + line->driver_data = talloc_zero(line, struct unixsocket_line); + + if (!line->driver_data) { + LOGP(DLINP, LOGL_ERROR, + "OOM in line update (line=%p)\n", line); + return -ENOMEM; + } + + config = line->driver_data; + config->fd.data = line; + config->fd.when = BSC_FD_READ; + config->fd.cb = unixsocket_cb; + + /* Open unix domain socket */ + ret = osmo_sock_unix_init(SOCK_SEQPACKET, 0, sock_path, + OSMO_SOCK_F_CONNECT); + if (ret < 0) { + /* Note: We will not free the allocated driver_data memory if + * opening the socket fails. The caller may want to call this + * function multiple times using config->fd.data as line + * parameter. Freeing now would destroy that reference. */ + LOGP(DLINP, LOGL_ERROR, + "unable to open socket: %s (line=%p, fd=%d)\n", sock_path, + line, config->fd.fd); + return ret; + } + LOGP(DLINP, LOGL_DEBUG, + "successfully opend (new) socket: %s (line=%p, fd=%d, ret=%d)\n", + sock_path, line, config->fd.fd, ret); + config->fd.fd = ret; + + /* Register socket in select loop */ + if (osmo_fd_register(&config->fd) < 0) { + LOGP(DLINP, LOGL_ERROR, + "error registering new socket (line=%p, fd=%d)\n", + line, config->fd.fd); + close(config->fd.fd); + return -EIO; + } + + /* Set line parameter */ + for (i = 0; i < ARRAY_SIZE(line->ts); i++) { + struct e1inp_ts *e1i_ts = &line->ts[i]; + if (!e1i_ts->lapd) { + e1i_ts->lapd = lapd_instance_alloc(1, + unixsocket_write_msg_lapd_cb, &config->fd, + e1inp_dlsap_up, e1i_ts, &lapd_profile_abis); + } + } + + /* Ensure ericsson-superchannel is turned of when + * a new connection is made */ + e1inp_ericsson_set_altc(line, 0); + + return ret; +} + +struct e1inp_driver unixsocket_driver = { + .name = "unixsocket", + .want_write = ts_want_write, + .line_update = unixsocket_line_update, + .default_delay = 0, +}; + +void e1inp_unixsocket_init(void) +{ + tall_unixsocket_ctx = talloc_named_const(libosmo_abis_ctx, 1, "unixsocket"); + e1inp_driver_register(&unixsocket_driver); +} + +void e1inp_ericsson_set_altc(struct e1inp_line *unixline, int superchannel) +{ + struct unixsocket_line *config; + struct msgb *msg; + + if (!unixline) + return; + + if (unixline->driver != &unixsocket_driver) { + LOGP(DLMI, LOGL_NOTICE, "altc is only supported by unixsocket\n"); + return; + } + + config = unixline->driver_data; + if (!config) { + LOGP(DLMI, LOGL_NOTICE, "e1inp driver not yet initialized.\n"); + return; + } + + + msg = msgb_alloc_headroom(200, 100, "ALTC"); + + /* version header */ + msgb_put_u8(msg, UNIXSOCKET_PROTO_VERSION); + /* data|control */ + msgb_put_u8(msg, UNIXSOCKET_PROTO_CONTROL); + + /* magic */ + msgb_put_u32(msg, 0x23004200); + msgb_put_u8(msg, superchannel ? 1 : 0); + + unixsocket_write_msg(msg, &config->fd); +} + diff --git a/src/ipa_proxy.c b/src/ipa_proxy.c new file mode 100644 index 0000000..6053bb8 --- /dev/null +++ b/src/ipa_proxy.c @@ -0,0 +1,658 @@ +#include "internal.h" + +#include <stdio.h> +#include <stdbool.h> +#include <unistd.h> +#include <stdlib.h> +#include <errno.h> +#include <string.h> +#include <time.h> +#include <sys/fcntl.h> +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <arpa/inet.h> + +#include <osmocom/core/select.h> +#include <osmocom/core/bitvec.h> +#include <osmocom/gsm/tlv.h> +#include <osmocom/core/msgb.h> +#include <osmocom/core/logging.h> +#include <osmocom/core/talloc.h> +#include <osmocom/abis/e1_input.h> +#include <osmocom/abis/ipaccess.h> +#include <osmocom/core/socket.h> + +#include <osmocom/abis/ipa.h> +#include <osmocom/vty/vty.h> +#include <osmocom/vty/command.h> + +static void *tall_ipa_proxy_ctx; + +/* + * data structures used by the IPA VTY commands + */ +static LLIST_HEAD(ipa_instance_list); + +enum ipa_proxy_instance_net_type { + IPA_INSTANCE_T_NONE, + IPA_INSTANCE_T_BIND, + IPA_INSTANCE_T_CONNECT, + IPA_INSTANCE_T_MAX +}; + +struct ipa_proxy_instance_net { + char *addr; + uint16_t port; + enum ipa_proxy_instance_net_type type; +}; + +struct ipa_proxy_instance { + struct llist_head head; +#define IPA_INSTANCE_NAME 16 + char name[IPA_INSTANCE_NAME]; + struct ipa_proxy_instance_net net; + int refcnt; +}; + +static LLIST_HEAD(ipa_proxy_route_list); + +/* Several routes pointing to the same instances share this. */ +struct ipa_proxy_route_shared { + int refcnt; + + /* this file descriptor is used to accept() new connections. */ + struct osmo_fd bfd; + + struct { + struct ipa_proxy_instance *inst; + struct bitvec streamid_map; + uint8_t streamid_map_data[(0xff+1)/8]; + uint8_t streamid[0xff + 1]; + } src; + struct { + struct ipa_proxy_instance *inst; + struct bitvec streamid_map; + uint8_t streamid_map_data[(0xff+1)/8]; + uint8_t streamid[0xff + 1]; + } dst; + + struct llist_head conn_list; +}; + +/* One route is composed of two instances. */ +struct ipa_proxy_route { + struct llist_head head; + + struct { + uint8_t streamid; + } src; + struct { + uint8_t streamid; + } dst; + + struct ipa_proxy_route_shared *shared; +}; + +enum ipa_conn_state { + IPA_CONN_S_NONE, + IPA_CONN_S_CONNECTING, + IPA_CONN_S_CONNECTED, + IPA_CONN_S_MAX +}; + +/* One route may forward more than one connection. */ +struct ipa_proxy_conn { + struct llist_head head; + + struct ipa_server_conn *src; + struct ipa_client_conn *dst; + struct ipa_proxy_route *route; +}; + +/* + * socket callbacks used by IPA VTY commands + */ +static int ipa_sock_dst_cb(struct ipa_client_conn *link, struct msgb *msg) +{ + struct ipaccess_head *hh; + struct ipa_proxy_conn *conn = link->data; + + LOGP(DLINP, LOGL_NOTICE, "received message from client side\n"); + + hh = (struct ipaccess_head *)msg->data; + /* check if we have a route for this message. */ + if (bitvec_get_bit_pos( + &conn->route->shared->dst.streamid_map, + hh->proto) != ONE) { + LOGP(DLINP, LOGL_NOTICE, "we don't have a " + "route for streamid 0x%x\n", hh->proto); + msgb_free(msg); + return 0; + } + /* mangle message, if required. */ + hh->proto = conn->route->shared->src.streamid[hh->proto]; + + ipa_server_conn_send(conn->src, msg); + return 0; +} + +static int ipa_sock_src_cb(struct ipa_server_conn *peer, struct msgb *msg) +{ + struct ipaccess_head *hh; + struct ipa_proxy_conn *conn = peer->data; + + LOGP(DLINP, LOGL_NOTICE, "received message from server side\n"); + + hh = (struct ipaccess_head *)msg->data; + /* check if we have a route for this message. */ + if (bitvec_get_bit_pos(&conn->route->shared->src.streamid_map, + hh->proto) != ONE) { + LOGP(DLINP, LOGL_NOTICE, "we don't have a " + "route for streamid 0x%x\n", hh->proto); + msgb_free(msg); + return 0; + } + /* mangle message, if required. */ + hh->proto = conn->route->shared->dst.streamid[hh->proto]; + + ipa_client_conn_send(conn->dst, msg); + return 0; +} + +static int +ipa_sock_src_accept_cb(struct ipa_server_link *link, int fd) +{ + struct ipa_proxy_route *route = link->data; + struct ipa_proxy_conn *conn; + + conn = talloc_zero(tall_ipa_proxy_ctx, struct ipa_proxy_conn); + if (conn == NULL) { + LOGP(DLINP, LOGL_ERROR, "cannot allocate memory for " + "origin IPA\n"); + close(fd); + return -ENOMEM; + } + conn->route = route; + + conn->src = ipa_server_conn_create(tall_ipa_proxy_ctx, link, fd, + ipa_sock_src_cb, NULL, conn); + if (conn->src == NULL) { + LOGP(DLINP, LOGL_ERROR, "could not create server peer: %s\n", + strerror(errno)); + return -ENOMEM; + } + + LOGP(DLINP, LOGL_NOTICE, "now trying to connect to destination\n"); + + conn->dst = ipa_client_conn_create(NULL, NULL, 0, + route->shared->dst.inst->net.addr, + route->shared->dst.inst->net.port, + NULL, + ipa_sock_dst_cb, + NULL, + conn); + if (conn->dst == NULL) { + LOGP(DLINP, LOGL_ERROR, "could not create client: %s\n", + strerror(errno)); + return -ENOMEM; + } + if (ipa_client_conn_open(conn->dst) < 0) { + LOGP(DLINP, LOGL_ERROR, "could not start client: %s\n", + strerror(errno)); + return -ENOMEM; + } + llist_add(&conn->head, &route->shared->conn_list); + return 0; +} + +/* + * VTY commands for IPA + */ +static int __ipa_instance_add(struct vty *vty, int argc, const char *argv[]) +{ + struct ipa_proxy_instance *ipi; + enum ipa_proxy_instance_net_type type; + struct in_addr addr; + uint16_t port; + + if (argc < 4) + return CMD_ERR_INCOMPLETE; + + llist_for_each_entry(ipi, &ipa_instance_list, head) { + if (strncmp(ipi->name, argv[0], IPA_INSTANCE_NAME) != 0) + continue; + + vty_out(vty, "%% instance `%s' already exists%s", + ipi->name, VTY_NEWLINE); + return CMD_WARNING; + } + if (strncmp(argv[1], "bind", IPA_INSTANCE_NAME) == 0) + type = IPA_INSTANCE_T_BIND; + else if (strncmp(argv[1], "connect", IPA_INSTANCE_NAME) == 0) + type = IPA_INSTANCE_T_CONNECT; + else + return CMD_ERR_INCOMPLETE; + + if (inet_aton(argv[2], &addr) < 0) { + vty_out(vty, "%% invalid address %s%s", argv[1], VTY_NEWLINE); + return CMD_WARNING; + } + port = atoi(argv[3]); + + ipi = talloc_zero(tall_ipa_proxy_ctx, struct ipa_proxy_instance); + if (ipi == NULL) { + vty_out(vty, "%% can't allocate memory for new instance%s", + VTY_NEWLINE); + return CMD_WARNING; + } + strncpy(ipi->name, argv[0], IPA_INSTANCE_NAME); + ipi->name[IPA_INSTANCE_NAME - 1] = '\0'; + ipi->net.type = type; + ipi->net.addr = talloc_strdup(tall_ipa_proxy_ctx, argv[2]); + ipi->net.port = port; + llist_add_tail(&ipi->head, &ipa_instance_list); + + return CMD_SUCCESS; +} + +DEFUN(ipa_instance_add, ipa_instance_add_cmd, + "ipa instance NAME (bind|connect) IP tcp port PORT", + "Bind or connect instance to address and port") +{ + return __ipa_instance_add(vty, argc, argv); +} + +DEFUN(ipa_instance_del, ipa_instance_del_cmd, + "no ipa instance NAME", + "Delete instance to address and port") +{ + struct ipa_proxy_instance *ipi; + + if (argc < 1) + return CMD_ERR_INCOMPLETE; + + llist_for_each_entry(ipi, &ipa_instance_list, head) { + if (strncmp(ipi->name, argv[0], IPA_INSTANCE_NAME) != 0) + continue; + + if (ipi->refcnt > 0) { + vty_out(vty, "%% instance `%s' is in use%s", + ipi->name, VTY_NEWLINE); + return CMD_WARNING; + } + llist_del(&ipi->head); + talloc_free(ipi); + return CMD_SUCCESS; + } + vty_out(vty, "%% instance `%s' does not exist%s", + ipi->name, VTY_NEWLINE); + + return CMD_WARNING; +} + +DEFUN(ipa_instance_show, ipa_instance_show_cmd, + "ipa instance show", "Show existing ipaccess proxy instances") +{ + struct ipa_proxy_instance *this; + + llist_for_each_entry(this, &ipa_instance_list, head) { + vty_out(vty, "instance %s %s %s tcp port %u%s", + this->name, this->net.addr, + this->net.type == IPA_INSTANCE_T_BIND ? + "bind" : "connect", + this->net.port, VTY_NEWLINE); + } + return CMD_SUCCESS; +} + +static int __ipa_route_add(struct vty *vty, int argc, const char *argv[]) +{ + struct ipa_proxy_instance *ipi = vty->index; + struct ipa_proxy_instance *src = NULL, *dst = NULL; + uint32_t src_streamid, dst_streamid; + struct ipa_proxy_route *route, *matching_route = NULL; + struct ipa_proxy_route_shared *shared = NULL; + int ret; + + if (argc < 4) + return CMD_ERR_INCOMPLETE; + + llist_for_each_entry(ipi, &ipa_instance_list, head) { + if (strncmp(ipi->name, argv[0], IPA_INSTANCE_NAME) == 0) { + src = ipi; + continue; + } + if (strncmp(ipi->name, argv[2], IPA_INSTANCE_NAME) == 0) { + dst = ipi; + continue; + } + } + if (src == NULL) { + vty_out(vty, "%% instance `%s' does not exists%s", + argv[0], VTY_NEWLINE); + return CMD_WARNING; + } + if (dst == NULL) { + vty_out(vty, "%% instance `%s' does not exists%s", + argv[2], VTY_NEWLINE); + return CMD_WARNING; + } + if (src->net.type != IPA_INSTANCE_T_BIND) { + vty_out(vty, "%% instance `%s' is not of bind type%s", + argv[0], VTY_NEWLINE); + return CMD_WARNING; + } + if (dst->net.type != IPA_INSTANCE_T_CONNECT) { + vty_out(vty, "%% instance `%s' is not of connect type%s", + argv[2], VTY_NEWLINE); + return CMD_WARNING; + } + src_streamid = strtoul(argv[1], NULL, 16); + if (src_streamid > 0xff) { + vty_out(vty, "%% source streamid must be " + ">= 0x00 and <= 0xff%s", VTY_NEWLINE); + return CMD_WARNING; + } + dst_streamid = strtoul(argv[3], NULL, 16); + if (dst_streamid > 0xff) { + vty_out(vty, "%% destination streamid must be " + ">= 0x00 and <= 0xff%s", VTY_NEWLINE); + return CMD_WARNING; + } + llist_for_each_entry(route, &ipa_proxy_route_list, head) { + if (route->shared->src.inst == src && + route->shared->dst.inst == dst) { + if (route->src.streamid == src_streamid && + route->dst.streamid == dst_streamid) { + vty_out(vty, "%% this route already exists%s", + VTY_NEWLINE); + return CMD_WARNING; + } + matching_route = route; + break; + } + } + /* new route for this configuration. */ + route = talloc_zero(tall_ipa_proxy_ctx, struct ipa_proxy_route); + if (route == NULL) { + vty_out(vty, "%% can't allocate memory for new route%s", + VTY_NEWLINE); + return CMD_WARNING; + } + route->src.streamid = src_streamid; + route->dst.streamid = dst_streamid; + + if (matching_route != NULL) { + /* there's already a master route for these configuration. */ + if (matching_route->shared->src.inst != src) { + vty_out(vty, "%% route does not contain " + "source instance `%s'%s", + argv[0], VTY_NEWLINE); + return CMD_WARNING; + } + if (matching_route->shared->dst.inst != dst) { + vty_out(vty, "%% route does not contain " + "destination instance `%s'%s", + argv[2], VTY_NEWLINE); + return CMD_WARNING; + } + /* use already existing shared routing information. */ + shared = matching_route->shared; + } else { + struct ipa_server_link *link; + + /* this is a brand new route, allocate shared routing info. */ + shared = talloc_zero(tall_ipa_proxy_ctx, struct ipa_proxy_route_shared); + if (shared == NULL) { + vty_out(vty, "%% can't allocate memory for " + "new route shared%s", VTY_NEWLINE); + return CMD_WARNING; + } + shared->src.streamid_map.data_len = + sizeof(shared->src.streamid_map_data); + shared->src.streamid_map.data = + shared->src.streamid_map_data; + shared->dst.streamid_map.data_len = + sizeof(shared->dst.streamid_map_data); + shared->dst.streamid_map.data = + shared->dst.streamid_map_data; + + link = ipa_server_link_create(tall_ipa_proxy_ctx, NULL, + "0.0.0.0", + src->net.port, + ipa_sock_src_accept_cb, route); + if (link == NULL) { + vty_out(vty, "%% can't bind instance `%s' to port%s", + src->name, VTY_NEWLINE); + return CMD_WARNING; + } + if (ipa_server_link_open(link) < 0) { + vty_out(vty, "%% can't bind instance `%s' to port%s", + src->name, VTY_NEWLINE); + return CMD_WARNING; + } + INIT_LLIST_HEAD(&shared->conn_list); + } + route->shared = shared; + src->refcnt++; + route->shared->src.inst = src; + dst->refcnt++; + route->shared->dst.inst = dst; + shared->src.streamid[src_streamid] = dst_streamid; + shared->dst.streamid[dst_streamid] = src_streamid; + ret = bitvec_set_bit_pos(&shared->src.streamid_map, src_streamid, ONE); + if (ret < 0) { + vty_out(vty, "%% bad bitmask (?)%s", VTY_NEWLINE); + return CMD_WARNING; + } + ret = bitvec_set_bit_pos(&shared->dst.streamid_map, dst_streamid, ONE); + if (ret < 0) { + vty_out(vty, "%% bad bitmask (?)%s", VTY_NEWLINE); + return CMD_WARNING; + } + shared->refcnt++; + + llist_add_tail(&route->head, &ipa_proxy_route_list); + return CMD_SUCCESS; +} + +DEFUN(ipa_route_add, ipa_route_add_cmd, + "ipa route instance NAME streamid HEXNUM " + "instance NAME streamid HEXNUM", "Add IPA route") +{ + return __ipa_route_add(vty, argc, argv); +} + +DEFUN(ipa_route_del, ipa_route_del_cmd, + "no ipa route instance NAME streamid HEXNUM " + "instance NAME streamid HEXNUM", "Delete IPA route") +{ + struct ipa_proxy_instance *ipi = vty->index; + struct ipa_proxy_instance *src = NULL, *dst = NULL; + uint32_t src_streamid, dst_streamid; + struct ipa_proxy_route *route, *matching_route = NULL; + struct ipa_proxy_conn *conn, *tmp; + + if (argc < 4) + return CMD_ERR_INCOMPLETE; + + llist_for_each_entry(ipi, &ipa_instance_list, head) { + if (strncmp(ipi->name, argv[0], IPA_INSTANCE_NAME) == 0) { + src = ipi; + continue; + } + if (strncmp(ipi->name, argv[2], IPA_INSTANCE_NAME) == 0) { + dst = ipi; + continue; + } + } + if (src == NULL) { + vty_out(vty, "%% instance `%s' does not exists%s", + argv[0], VTY_NEWLINE); + return CMD_WARNING; + } + if (dst == NULL) { + vty_out(vty, "%% instance `%s' does not exists%s", + argv[2], VTY_NEWLINE); + return CMD_WARNING; + } + if (src->net.type != IPA_INSTANCE_T_BIND) { + vty_out(vty, "%% instance `%s' is not of bind type%s", + argv[0], VTY_NEWLINE); + return CMD_WARNING; + } + if (dst->net.type != IPA_INSTANCE_T_CONNECT) { + vty_out(vty, "%% instance `%s' is not of connect type%s", + argv[2], VTY_NEWLINE); + return CMD_WARNING; + } + src_streamid = strtoul(argv[1], NULL, 16); + if (src_streamid > 0xff) { + vty_out(vty, "%% source streamid must be " + ">= 0x00 and <= 0xff%s", VTY_NEWLINE); + return CMD_WARNING; + } + dst_streamid = strtoul(argv[3], NULL, 16); + if (dst_streamid > 0xff) { + vty_out(vty, "%% destination streamid must be " + ">= 0x00 and <= 0xff%s", VTY_NEWLINE); + return CMD_WARNING; + } + llist_for_each_entry(route, &ipa_proxy_route_list, head) { + if (route->shared->src.inst == src && + route->shared->dst.inst == dst && + route->src.streamid == src_streamid && + route->dst.streamid == dst_streamid) { + matching_route = route; + break; + } + } + if (matching_route == NULL) { + vty_out(vty, "%% no route with that configuration%s", + VTY_NEWLINE); + return CMD_WARNING; + } + /* delete this route from list. */ + llist_del(&matching_route->head); + + if (--matching_route->shared->refcnt == 0) { + /* nobody else using this route, release all resources. */ + llist_for_each_entry_safe(conn, tmp, + &matching_route->shared->conn_list, head) { + ipa_server_conn_destroy(conn->src); + llist_del(&conn->head); + talloc_free(conn); + } + osmo_fd_unregister(&route->shared->bfd); + close(route->shared->bfd.fd); + route->shared->bfd.fd = -1; + + talloc_free(route->shared); + } else { + /* otherwise, revert the mapping that this route applies. */ + bitvec_set_bit_pos(&matching_route->shared->src.streamid_map, + src_streamid, ZERO); + bitvec_set_bit_pos(&matching_route->shared->dst.streamid_map, + dst_streamid, ZERO); + matching_route->shared->src.streamid[src_streamid] = 0x00; + matching_route->shared->dst.streamid[dst_streamid] = 0x00; + } + matching_route->shared->src.inst->refcnt--; + matching_route->shared->dst.inst->refcnt--; + talloc_free(matching_route); + + return CMD_SUCCESS; +} + +DEFUN(ipa_route_show, ipa_route_show_cmd, + "ipa route show", "Show existing ipaccess proxy routes") +{ + struct ipa_proxy_route *this; + + llist_for_each_entry(this, &ipa_proxy_route_list, head) { + vty_out(vty, "route instance %s streamid 0x%.2x " + "instance %s streamid 0x%.2x%s", + this->shared->src.inst->name, this->src.streamid, + this->shared->dst.inst->name, this->dst.streamid, + VTY_NEWLINE); + } + return CMD_SUCCESS; +} + +/* + * Config for ipaccess-proxy + */ +DEFUN(ipa_cfg, ipa_cfg_cmd, "ipa", "Configure the ipaccess proxy") +{ + vty->index = NULL; + vty->node = L_IPA_NODE; + return CMD_SUCCESS; +} + +/* all these below look like enable commands, but without the ipa prefix. */ +DEFUN(ipa_route_cfg_add, ipa_route_cfg_add_cmd, + "route instance NAME streamid HEXNUM " + "instance NAME streamid HEXNUM", "Add IPA route") +{ + return __ipa_route_add(vty, argc, argv); +} + +DEFUN(ipa_instance_cfg_add, ipa_instance_cfg_add_cmd, + "instance NAME (bind|connect) IP tcp port PORT", + "Bind or connect instance to address and port") +{ + return __ipa_instance_add(vty, argc, argv); +} + +struct cmd_node ipa_node = { + L_IPA_NODE, + "%s(config-ipa)# ", + 1, +}; + +static int ipa_cfg_write(struct vty *vty) +{ + bool heading = false; + struct ipa_proxy_instance *inst; + struct ipa_proxy_route *route; + + llist_for_each_entry(inst, &ipa_instance_list, head) { + if (!heading) { + vty_out(vty, "ipa%s", VTY_NEWLINE); + heading = true; + } + vty_out(vty, " instance %s %s %s tcp port %u%s", + inst->name, + inst->net.type == IPA_INSTANCE_T_BIND ? + "bind" : "connect", + inst->net.addr, + inst->net.port, VTY_NEWLINE); + } + llist_for_each_entry(route, &ipa_proxy_route_list, head) { + vty_out(vty, " route instance %s streamid 0x%.2x " + "instance %s streamid 0x%.2x%s", + route->shared->src.inst->name, route->src.streamid, + route->shared->dst.inst->name, route->dst.streamid, + VTY_NEWLINE); + } + return CMD_SUCCESS; +} + +void ipa_proxy_vty_init(void) +{ + tall_ipa_proxy_ctx = + talloc_named_const(libosmo_abis_ctx, 1, "ipa_proxy"); + + install_element(ENABLE_NODE, &ipa_instance_add_cmd); + install_element(ENABLE_NODE, &ipa_instance_del_cmd); + install_element(ENABLE_NODE, &ipa_instance_show_cmd); + install_element(ENABLE_NODE, &ipa_route_add_cmd); + install_element(ENABLE_NODE, &ipa_route_del_cmd); + install_element(ENABLE_NODE, &ipa_route_show_cmd); + + install_element(CONFIG_NODE, &ipa_cfg_cmd); + install_node(&ipa_node, ipa_cfg_write); + vty_install_default(L_IPA_NODE); + install_element(L_IPA_NODE, &ipa_instance_cfg_add_cmd); + install_element(L_IPA_NODE, &ipa_route_cfg_add_cmd); +} diff --git a/src/subchan_demux.c b/src/subchan_demux.c new file mode 100644 index 0000000..238056c --- /dev/null +++ b/src/subchan_demux.c @@ -0,0 +1,353 @@ +/* A E1 sub-channel (de)multiplexer with TRAU frame sync */ + +/* (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 "internal.h" + +#include <unistd.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> + +#include <osmocom/abis/subchan_demux.h> +#include <osmocom/abis/trau_frame.h> +#include <osmocom/core/talloc.h> + +/*! \addtogroup subchan_demux + * @{ + * + * \file subchan_demux.c + */ + +void *tall_tqe_ctx; + +static inline void append_bit(struct demux_subch *sch, uint8_t bit) +{ + sch->out_bitbuf[sch->out_idx++] = bit; +} + +#define SYNC_HDR_BITS 16 + +/* check if we have just completed the 16 bit zero + 1 bit one sync + * header, in accordance with GSM TS 08.60 Chapter 4.8.1 */ +static int sync_hdr_complete(struct demux_subch *sch, uint8_t bit) +{ + if (bit == 0) + sch->consecutive_zeros++; + else { + if (sch->consecutive_zeros >= SYNC_HDR_BITS) { + sch->consecutive_zeros = 0; + return 1; + } + sch->consecutive_zeros = 0; + } + + return 0; +} + +/* resynchronize to current location */ +static void resync_to_here(struct demux_subch *sch) +{ + memset(sch->out_bitbuf, 0, SYNC_HDR_BITS); + sch->out_bitbuf[SYNC_HDR_BITS] = 1; + + /* set index in a way that we can continue receiving bits after + * the end of the SYNC header */ + sch->out_idx = SYNC_HDR_BITS + 1; + sch->in_sync = 1; +} + +/*! \brief initialize subchannel demuxer structure + * \param[in,out] dmx subchannel demuxer + */ +int subch_demux_init(struct subch_demux *dmx) +{ + int i; + + dmx->chan_activ = 0; + for (i = 0; i < NR_SUBCH; i++) { + struct demux_subch *sch = &dmx->subch[i]; + sch->out_idx = 0; + memset(sch->out_bitbuf, 0xff, sizeof(sch->out_bitbuf)); + } + return 0; +} + +/*! \brief Input some data from the 64k full-slot into subchannel demux + * \param[in] dmx subchannel demuxer + * \param[in] data pointer to buffer containing input data + * \param[in] len length of \a data in bytes + * \returns 0 in case of success, <0 otherwise. + * + * Input some arbitrary (modulo 4) number of bytes of a 64k E1 channel, + * split it into the 16k subchannels */ +int subch_demux_in(struct subch_demux *dmx, uint8_t *data, int len) +{ + int i, c; + + for (i = 0; i < len; i++) { + uint8_t inbyte = data[i]; + + for (c = 0; c < NR_SUBCH; c++) { + struct demux_subch *sch = &dmx->subch[c]; + uint8_t inbits; + uint8_t bit; + + /* ignore inactive subchannels */ + if (!(dmx->chan_activ & (1 << c))) + continue; + + inbits = inbyte >> (c << 1); + + /* two bits for each subchannel */ + if (inbits & 0x01) + bit = 1; + else + bit = 0; + append_bit(sch, bit); + + if (sync_hdr_complete(sch, bit)) + resync_to_here(sch); + + if (inbits & 0x02) + bit = 1; + else + bit = 0; + append_bit(sch, bit); + + if (sync_hdr_complete(sch, bit)) + resync_to_here(sch); + + /* FIXME: verify the first bit in octet 2, 4, 6, ... + * according to TS 08.60 4.8.1 */ + + /* once we have reached TRAU_FRAME_BITS, call + * the TRAU frame handler callback function */ + if (sch->out_idx >= TRAU_FRAME_BITS) { + if (sch->in_sync) { + dmx->out_cb(dmx, c, sch->out_bitbuf, + sch->out_idx, dmx->data); + sch->in_sync = 0; + } + sch->out_idx = 0; + } + } + } + return i; +} + +/*! \brief activate a given sub-channel + * \param[in] dmx subchannel demuxer + * \param[in] subch sub-channel number + * \returns 0 in case of success, <0 otherwise + * + * Activating a sub-channel will casuse the \ref subch_demux::out_cb + * callback to be called for any incoming data from the full slot + */ +int subch_demux_activate(struct subch_demux *dmx, int subch) +{ + if (subch >= NR_SUBCH) + return -EINVAL; + + dmx->chan_activ |= (1 << subch); + return 0; +} + +/*! \brief deactivate a given sub-channel + * \param[in] dmx subchannel demuxer + * \param[in] subch sub-channel number + * \returns 0 in case of success, <0 otherwise + * + * Deactivating a sub-channel will casuse the \ref subch_demux::out_cb + * callback no longer to be called. + */ +int subch_demux_deactivate(struct subch_demux *dmx, int subch) +{ + if (subch >= NR_SUBCH) + return -EINVAL; + + dmx->chan_activ &= ~(1 << subch); + return 0; +} + +/* MULTIPLEXER */ + +static int alloc_add_idle_frame(struct subch_mux *mx, int sch_nr) +{ + /* allocate and initialize with idle pattern */ + return subchan_mux_enqueue(mx, sch_nr, trau_idle_frame(), + TRAU_FRAME_BITS); +} + +/* return the requested number of bits from the specified subchannel */ +static int get_subch_bits(struct subch_mux *mx, int subch, + uint8_t *bits, int num_requested) +{ + struct mux_subch *sch = &mx->subch[subch]; + int num_bits = 0; + + while (num_bits < num_requested) { + struct subch_txq_entry *txe; + int num_bits_left; + int num_bits_thistime; + + /* make sure we have a valid entry at top of tx queue. + * if not, add an idle frame */ + if (llist_empty(&sch->tx_queue)) + alloc_add_idle_frame(mx, subch); + + if (llist_empty(&sch->tx_queue)) + return -EIO; + + txe = llist_entry(sch->tx_queue.next, struct subch_txq_entry, list); + num_bits_left = txe->bit_len - txe->next_bit; + + if (num_bits_left < num_requested) + num_bits_thistime = num_bits_left; + else + num_bits_thistime = num_requested; + + /* pull the bits from the txe */ + memcpy(bits + num_bits, txe->bits + txe->next_bit, num_bits_thistime); + txe->next_bit += num_bits_thistime; + + /* free the tx_queue entry if it is fully consumed */ + if (txe->next_bit >= txe->bit_len) { + llist_del(&txe->list); + talloc_free(txe); + } + + /* increment global number of bits dequeued */ + num_bits += num_bits_thistime; + } + + return num_requested; +} + +/* compact an array of 8 single-bit bytes into one byte of 8 bits */ +static uint8_t compact_bits(const uint8_t *bits) +{ + uint8_t ret = 0; + int i; + + for (i = 0; i < 8; i++) + ret |= (bits[i] ? 1 : 0) << i; + + return ret; +} + +/* obtain a single output byte from the subchannel muxer */ +static int mux_output_byte(struct subch_mux *mx, uint8_t *byte) +{ + uint8_t bits[8]; + int rc; + + /* combine two bits of every subchan */ + rc = get_subch_bits(mx, 0, &bits[0], 2); + rc = get_subch_bits(mx, 1, &bits[2], 2); + rc = get_subch_bits(mx, 2, &bits[4], 2); + rc = get_subch_bits(mx, 3, &bits[6], 2); + + *byte = compact_bits(bits); + + return rc; +} + +/*! \brief Request the output of some muxed bytes from the subchan muxer + * \param[in] mx subchannel muxer + * \param[out] data caller-allocated buffer for data + * \param[in] len number of bytes to be filled into \a data + * \returns actual number of bytes filled into \a data + */ +int subchan_mux_out(struct subch_mux *mx, uint8_t *data, int len) +{ + int i; + + for (i = 0; i < len; i++) { + int rc; + rc = mux_output_byte(mx, &data[i]); + if (rc < 0) + break; + } + return i; +} + +/* evict the 'num_evict' number of oldest entries in the queue */ +static void tx_queue_evict(struct mux_subch *sch, int num_evict) +{ + struct subch_txq_entry *tqe; + int i; + + for (i = 0; i < num_evict; i++) { + if (llist_empty(&sch->tx_queue)) + return; + + tqe = llist_entry(sch->tx_queue.next, struct subch_txq_entry, list); + llist_del(&tqe->list); + talloc_free(tqe); + } +} + +/*! \brief enqueue some data into the tx_queue of a given subchannel + * \param[in] mx subchannel muxer instance + * \param[in] s_nr subchannel number + * \param[in] data pointer to buffer with data + * \param[in] len length of \a data + * \returns 0 in case of success, <0 in case of error + */ +int subchan_mux_enqueue(struct subch_mux *mx, int s_nr, const uint8_t *data, + int len) +{ + struct mux_subch *sch = &mx->subch[s_nr]; + unsigned int list_len = llist_count(&sch->tx_queue); + struct subch_txq_entry *tqe = talloc_zero_size(tall_tqe_ctx, + sizeof(*tqe) + len); + if (!tqe) + return -ENOMEM; + + tqe->bit_len = len; + memcpy(tqe->bits, data, len); + + if (list_len > 2) + tx_queue_evict(sch, list_len-2); + + llist_add_tail(&tqe->list, &sch->tx_queue); + + return 0; +} + +/*! \brief initialize one subchannel muxer instance + * \param[in,out] mx subchannel muxer instance, caller-allocated + * \returns 0 in success, < 0 in case of error + */ +int subchan_mux_init(struct subch_mux *mx) +{ + int i; + + memset(mx, 0, sizeof(*mx)); + for (i = 0; i < NR_SUBCH; i++) { + struct mux_subch *sch = &mx->subch[i]; + INIT_LLIST_HEAD(&sch->tx_queue); + } + + return 0; +} + +/* }@ */ diff --git a/src/trau/osmo_ortp.c b/src/trau/osmo_ortp.c new file mode 100644 index 0000000..c49a23d --- /dev/null +++ b/src/trau/osmo_ortp.c @@ -0,0 +1,655 @@ +/* (C) 2011 by Harald Welte <laforge@gnumonks.org> + * (C) 2011 by On-Waves e.h.f + * All Rights Reserved + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +/*! \file osmo_ortp.c + * \brief Integration of libortp into osmocom framework (select, logging) + */ + +#include <stdint.h> +#include <stdbool.h> +#include <inttypes.h> +#include <netdb.h> + +#include <osmocom/core/logging.h> +#include <osmocom/core/talloc.h> +#include <osmocom/core/utils.h> +#include <osmocom/core/select.h> +#include <osmocom/trau/osmo_ortp.h> + +#include <ortp/ortp.h> +#include <ortp/rtp.h> +#include <ortp/port.h> +#include <ortp/rtpsession.h> + +#include "config.h" + +static PayloadType *payload_type_efr; +static PayloadType *payload_type_hr; +static RtpProfile *osmo_pt_profile; + +static void *tall_rtp_ctx; + +/* malloc integration */ + +static void *osmo_ortp_malloc(size_t sz) +{ + return talloc_size(tall_rtp_ctx, sz); +} + +static void *osmo_ortp_realloc(void *ptr, size_t sz) +{ + return talloc_realloc_size(tall_rtp_ctx, ptr, sz); +} + +static void osmo_ortp_free(void *ptr) +{ + talloc_free(ptr); +} + +static OrtpMemoryFunctions osmo_ortp_memfn = { + .malloc_fun = osmo_ortp_malloc, + .realloc_fun = osmo_ortp_realloc, + .free_fun = osmo_ortp_free +}; + +/* logging */ + +struct level_map { + OrtpLogLevel ortp; + int osmo_level; +}; +static const struct level_map level_map[] = { + { ORTP_DEBUG, LOGL_DEBUG }, + { ORTP_MESSAGE, LOGL_INFO }, + { ORTP_WARNING, LOGL_NOTICE }, + { ORTP_ERROR, LOGL_ERROR }, + { ORTP_FATAL, LOGL_FATAL }, +}; +static int ortp_to_osmo_lvl(OrtpLogLevel lev) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(level_map); i++) { + if (level_map[i].ortp == lev) + return level_map[i].osmo_level; + } + /* default */ + return LOGL_ERROR; +} + +static void my_ortp_logfn( +#if HAVE_ORTP_LOG_DOMAIN + const char *domain, +#endif + OrtpLogLevel lev, const char *fmt, va_list args) +{ + osmo_vlogp(DLMIB, ortp_to_osmo_lvl(lev), __FILE__, 0, + 0, fmt, args); +} + +/* ORTP signal callbacks */ + +static void ortp_sig_cb_ssrc(RtpSession *rs, void *data) +{ + int port = rtp_session_get_local_port(rs); + uint32_t ssrc = rtp_session_get_recv_ssrc(rs); + + LOGP(DLMIB, LOGL_INFO, + "osmo-ortp(%d): ssrc_changed to 0x%08x\n", port, ssrc); +} + +static void ortp_sig_cb_pt(RtpSession *rs, void *data) +{ + int port = rtp_session_get_local_port(rs); + int pt = rtp_session_get_recv_payload_type(rs); + + LOGP(DLMIB, LOGL_NOTICE, + "osmo-ortp(%d): payload_type_changed to 0x%02x\n", port, pt); +} + +static void ortp_sig_cb_net(RtpSession *rs, void *data) +{ + int port = rtp_session_get_local_port(rs); + + LOGP(DLMIB, LOGL_ERROR, + "osmo-ortp(%d): network_error %s\n", port, (char *)data); +} + +static void ortp_sig_cb_ts(RtpSession *rs, void *data) +{ + int port = rtp_session_get_local_port(rs); + uint32_t ts = rtp_session_get_current_recv_ts(rs); + + LOGP(DLMIB, LOGL_NOTICE, + "osmo-ortp(%d): timestamp_jump, new TS %d, resyncing\n", port, ts); + rtp_session_resync(rs); +} + +static inline bool recv_with_cb(struct osmo_rtp_socket *rs) +{ + uint8_t *payload; + mblk_t *mblk = rtp_session_recvm_with_ts(rs->sess, rs->rx_user_ts); + if (!mblk) + return false; + + int plen = rtp_get_payload(mblk, &payload); + /* hand into receiver */ + if (rs->rx_cb && plen > 0) + rs->rx_cb(rs, payload, plen, rtp_get_seqnumber(mblk), + rtp_get_timestamp(mblk), rtp_get_markbit(mblk)); + freemsg(mblk); + if (plen > 0) + return true; + return false; +} + +/*! \brief poll the socket for incoming data + * \param[in] rs the socket to be polled + * \returns number of packets received + handed to the rx_cb + */ +int osmo_rtp_socket_poll(struct osmo_rtp_socket *rs) +{ + if (rs->flags & OSMO_RTP_F_DISABLED) + return 0; + + if (recv_with_cb(rs)) + return 1; + + LOGP(DLMIB, LOGL_INFO, "osmo_rtp_socket_poll(%u): ERROR!\n", + rs->rx_user_ts); + return 0; +} + +/* Osmo FD callbacks */ + +static int osmo_rtp_fd_cb(struct osmo_fd *fd, unsigned int what) +{ + struct osmo_rtp_socket *rs = fd->data; + + if (what & BSC_FD_READ) { + /* in polling mode, we don't want to be called here */ + if (rs->flags & OSMO_RTP_F_POLL) { + fd->when &= ~BSC_FD_READ; + return 0; + } + if (!recv_with_cb(rs)) + LOGP(DLMIB, LOGL_INFO, "recvm_with_ts(%u): ERROR!\n", + rs->rx_user_ts); + rs->rx_user_ts += 160; + } + /* writing is not queued at the moment, so BSC_FD_WRITE + * shouldn't occur */ + return 0; +} + +/* Internal API coming from rtpsession_priv.h, used in osmo_rtcp_fd_cb */ +#pragma message ("Using internal ortp API: rtp_session_rtcp_rec") +int rtp_session_rtcp_recv(RtpSession * session); + +static int osmo_rtcp_fd_cb(struct osmo_fd *fd, unsigned int what) +{ + struct osmo_rtp_socket *rs = fd->data; + + /* We probably don't need this at all, as + * rtp_session_recvm_with_ts() will alway also poll the RTCP + * file descriptor for new data */ + return rtp_session_rtcp_recv(rs->sess); +} + +static int osmo_rtp_socket_fdreg(struct osmo_rtp_socket *rs) +{ + int rc; + + rs->rtp_bfd.fd = rtp_session_get_rtp_socket(rs->sess); + rs->rtcp_bfd.fd = rtp_session_get_rtcp_socket(rs->sess); + rs->rtp_bfd.when = rs->rtcp_bfd.when = BSC_FD_READ; + rs->rtp_bfd.data = rs->rtcp_bfd.data = rs; + rs->rtp_bfd.cb = osmo_rtp_fd_cb; + rs->rtcp_bfd.cb = osmo_rtcp_fd_cb; + + rc = osmo_fd_register(&rs->rtp_bfd); + if (rc < 0) + return rc; + + rc = osmo_fd_register(&rs->rtcp_bfd); + if (rc < 0) { + osmo_fd_unregister(&rs->rtp_bfd); + return rc; + } + + return 0; +} + +static void create_payload_types() +{ + PayloadType *pt; + + /* EFR */ + pt = payload_type_new(); + pt->type = PAYLOAD_AUDIO_PACKETIZED; + pt->clock_rate = 8000; + pt->mime_type = "EFR"; + pt->normal_bitrate = 12200; + pt->channels = 1; + payload_type_efr = pt; + + /* HR */ + pt = payload_type_new(); + pt->type = PAYLOAD_AUDIO_PACKETIZED; + pt->clock_rate = 8000; + pt->mime_type = "HR"; + pt->normal_bitrate = 6750; /* FIXME */ + pt->channels = 1; + payload_type_hr = pt; + + /* create a new RTP profile as clone of AV profile */ + osmo_pt_profile = rtp_profile_clone(&av_profile); + + /* add the GSM specific payload types. They are all dynamically + * assigned, but in the Osmocom GSM system we have allocated + * them as follows: */ + rtp_profile_set_payload(osmo_pt_profile, RTP_PT_GSM_EFR, payload_type_efr); + rtp_profile_set_payload(osmo_pt_profile, RTP_PT_GSM_HALF, payload_type_hr); + rtp_profile_set_payload(osmo_pt_profile, RTP_PT_AMR, &payload_type_amr); +} + +/* public functions */ + +/*! \brief initialize Osmocom RTP code + * \param[in] ctx default talloc context for library-internal allocations + */ +void osmo_rtp_init(void *ctx) +{ + tall_rtp_ctx = ctx; + ortp_set_memory_functions(&osmo_ortp_memfn); + ortp_init(); + ortp_set_log_level_mask( +#if HAVE_ORTP_LOG_DOMAIN + ORTP_LOG_DOMAIN, +#endif + 0xffff); + + ortp_set_log_handler(my_ortp_logfn); + create_payload_types(); +} + +/*! \brief Set Osmocom RTP socket parameters + * \param[in] rs OsmoRTP socket + * \param[in] param defined which parameter to set + OSMO_RTP_P_JITBUF - enables regular jitter buffering + OSMO_RTP_P_JIT_ADAP - enables adaptive jitter buffering + * \param[in] val Size of jitter buffer (in ms), 0 means disable buffering + * \returns negative value on error, 0 or 1 otherwise + (depending on whether given jitter buffering is enabled) + */ +int osmo_rtp_socket_set_param(struct osmo_rtp_socket *rs, + enum osmo_rtp_param param, int val) +{ + switch (param) { + case OSMO_RTP_P_JIT_ADAP: + rtp_session_enable_adaptive_jitter_compensation(rs->sess, + (bool)val); + /* fall-through on-purpose - we have to set val anyway */ + case OSMO_RTP_P_JITBUF: + rtp_session_enable_jitter_buffer(rs->sess, + (val) ? TRUE : FALSE); + if (val) + rtp_session_set_jitter_compensation(rs->sess, val); + break; + default: + return -EINVAL; + } + if (param == OSMO_RTP_P_JIT_ADAP) + return rtp_session_adaptive_jitter_compensation_enabled(rs->sess); + return rtp_session_jitter_buffer_enabled(rs->sess); +} + +/*! \brief Create a new RTP socket + * \param[in] talloc_cxt talloc context for this allocation. NULL for + * dafault context + * \param[in] flags Flags like OSMO_RTP_F_POLL + * \returns pointer to library-allocated \a struct osmo_rtp_socket + */ +struct osmo_rtp_socket *osmo_rtp_socket_create(void *talloc_ctx, unsigned int flags) +{ + struct osmo_rtp_socket *rs; + + if (!talloc_ctx) + talloc_ctx = tall_rtp_ctx; + + rs = talloc_zero(talloc_ctx, struct osmo_rtp_socket); + if (!rs) + return NULL; + + rs->flags = OSMO_RTP_F_DISABLED | flags; + rs->sess = rtp_session_new(RTP_SESSION_SENDRECV); + if (!rs->sess) { + talloc_free(rs); + return NULL; + } + rtp_session_set_data(rs->sess, rs); + rtp_session_set_profile(rs->sess, osmo_pt_profile); + rtp_session_set_jitter_compensation(rs->sess, 100); + + rtp_session_signal_connect(rs->sess, "ssrc_changed", + (RtpCallback) ortp_sig_cb_ssrc, + RTP_SIGNAL_PTR_CAST(rs)); + + rtp_session_signal_connect(rs->sess, "payload_type_changed", + (RtpCallback) ortp_sig_cb_pt, + RTP_SIGNAL_PTR_CAST(rs)); + + rtp_session_signal_connect(rs->sess, "network_error", + (RtpCallback) ortp_sig_cb_net, + RTP_SIGNAL_PTR_CAST(rs)); + + rtp_session_signal_connect(rs->sess, "timestamp_jump", + (RtpCallback) ortp_sig_cb_ts, + RTP_SIGNAL_PTR_CAST(rs)); + + /* initialize according to the RFC */ + rtp_session_set_seq_number(rs->sess, random()); + rs->tx_timestamp = random(); + + + return rs; +} + +/*! \brief bind a RTP socket to a local port + * \param[in] rs OsmoRTP socket + * \param[in] ip hostname/ip as string + * \param[in] port UDP port number, -1 for random selection + * \returns 0 on success, <0 on error + */ +int osmo_rtp_socket_bind(struct osmo_rtp_socket *rs, const char *ip, int port) +{ + int rc, rtcp = (-1 != port) ? port + 1 : -1; + rc = rtp_session_set_local_addr(rs->sess, ip, port, rtcp); + + if (rc < 0) + return rc; + + rs->rtp_bfd.fd = rtp_session_get_rtp_socket(rs->sess); + rs->rtcp_bfd.fd = rtp_session_get_rtcp_socket(rs->sess); + + return 0; +} + +/*! \brief connect a OsmoRTP socket to a remote port + * \param[in] rs OsmoRTP socket + * \param[in] ip String representation of remote hostname or IP address + * \param[in] port UDP port number to connect to + * + * If the OsmoRTP socket is not in POLL mode, this function will also + * cause the RTP and RTCP file descriptors to be registred with the + * libosmocore select() loop integration. + * + * \returns 0 on success, <0 in case of error + */ +int osmo_rtp_socket_connect(struct osmo_rtp_socket *rs, const char *ip, uint16_t port) +{ + int rc; + if (!port) { + LOGP(DLMIB, LOGL_INFO, "osmo_rtp_socket_connect() refused to " + "set remote %s:%u\n", ip, port); + return 0; + } + + /* We don't want the connected mode enabled during + * rtp_session_set_remote_addr(), because that will already setup a + * connection and updating the remote address will no longer have an + * effect. Contrary to what one may expect, this must be 0 at first, + * and we're setting to 1 further down to establish a connection once + * the first RTP packet is received (OS#1661). */ + rtp_session_set_connected_mode(rs->sess, 0); + + rc = rtp_session_set_remote_addr(rs->sess, ip, port); + if (rc < 0) + return rc; + + /* enable the use of connect() so later getsockname() will + * actually return the IP address that was chosen for the local + * sid of the connection */ + rtp_session_set_connected_mode(rs->sess, 1); + rs->flags &= ~OSMO_RTP_F_DISABLED; + + if (rs->flags & OSMO_RTP_F_POLL) + return rc; + else + return osmo_rtp_socket_fdreg(rs); +} + +/*! \brief Increment timestamp on a RTP socket without sending any packet + * \param[in] rs OsmoRTP socket + * \param[in] duration duration in number of RTP clock ticks + * + * Useful to keep the RTP internal clock up to date if an RTP frame should be + * send at a given time but no audio content is available. When next packet is + * sent, the receiver will see a different increase on the sequence number and + * the timestamp, and it should then take it as a synchronization point. For + * that same reason, it is advisable to enable the marker bit on the next RTP + * packet to be sent after calling this function. + * + * \returns 0 on success, <0 in case of error. + */ +int osmo_rtp_skipped_frame(struct osmo_rtp_socket *rs, unsigned int duration) +{ + if (rs->flags & OSMO_RTP_F_DISABLED) + return 0; + + rs->tx_timestamp += duration; + return 0; +} + +/*! \brief Send one RTP frame via a RTP socket + * \param[in] rs OsmoRTP socket + * \param[in] payload pointer to buffer with RTP payload data + * \param[in] payload_len length of \a payload in bytes + * \param[in] duration duration in number of RTP clock ticks + * \returns 0 on success, <0 in case of error. + */ +int osmo_rtp_send_frame(struct osmo_rtp_socket *rs, const uint8_t *payload, + unsigned int payload_len, unsigned int duration) +{ + return osmo_rtp_send_frame_ext(rs, payload, payload_len, duration, + false); +} + +/*! \brief Send one RTP frame via a RTP socket + * \param[in] rs OsmoRTP socket + * \param[in] payload pointer to buffer with RTP payload data + * \param[in] payload_len length of \a payload in bytes + * \param[in] duration duration in number of RTP clock ticks + * \param[in] marker the status of Marker bit in RTP header + * \returns 0 on success, <0 in case of error. + */ +int osmo_rtp_send_frame_ext(struct osmo_rtp_socket *rs, const uint8_t *payload, + unsigned int payload_len, unsigned int duration, + bool marker) +{ + mblk_t *mblk; + int rc; + + if (rs->flags & OSMO_RTP_F_DISABLED) + return 0; + + mblk = rtp_session_create_packet(rs->sess, RTP_FIXED_HEADER_SIZE, + payload, payload_len); + if (!mblk) + return -ENOMEM; + + rtp_set_markbit(mblk, marker); + rc = rtp_session_sendm_with_ts(rs->sess, mblk, + rs->tx_timestamp); + rs->tx_timestamp += duration; + if (rc < 0) { + /* no need to free() the mblk, as rtp_session_rtp_send() + * unconditionally free()s the mblk even in case of + * error */ + return rc; + } + + return rc; +} + +/*! \brief Set the payload type of a RTP socket + * \param[in] rs OsmoRTP socket + * \param[in] payload_type RTP payload type + * \returns 0 on success, < 0 otherwise + */ +int osmo_rtp_socket_set_pt(struct osmo_rtp_socket *rs, int payload_type) +{ + int rc; + + rc = rtp_session_set_payload_type(rs->sess, payload_type); + //rtp_session_set_rtcp_report_interval(rs->sess, 5*1000); + + return rc; +} + +/*! \brief completely close the RTP socket and release all resources + * \param[in] rs OsmoRTP socket to be released + * \returns 0 on success + */ +int osmo_rtp_socket_free(struct osmo_rtp_socket *rs) +{ + if (rs->rtp_bfd.list.next && rs->rtp_bfd.list.next != LLIST_POISON1) + osmo_fd_unregister(&rs->rtp_bfd); + + if (rs->rtcp_bfd.list.next && rs->rtcp_bfd.list.next != LLIST_POISON1) + osmo_fd_unregister(&rs->rtcp_bfd); + + if (rs->sess) { + rtp_session_release_sockets(rs->sess); + rtp_session_destroy(rs->sess); + rs->sess = NULL; + } + + talloc_free(rs); + + return 0; +} + +/*! \brief obtain the locally bound IPv4 address and UDP port + * \param[in] rs OsmoRTP socket + * \param[out] ip Pointer to caller-allocated uint32_t for IPv4 address + * \oaram[out] port Pointer to caller-allocated int for UDP port number + * \returns 0 on success, <0 on error, -EIO in case of IPv6 socket + */ +int osmo_rtp_get_bound_ip_port(struct osmo_rtp_socket *rs, + uint32_t *ip, int *port) +{ + int rc; + struct sockaddr_storage ss; + struct sockaddr_in *sin = (struct sockaddr_in *) &ss; + socklen_t alen = sizeof(ss); + + rc = getsockname(rs->rtp_bfd.fd, (struct sockaddr *)&ss, &alen); + if (rc < 0) + return rc; + + if (ss.ss_family != AF_INET) + return -EIO; + + *ip = ntohl(sin->sin_addr.s_addr); + *port = rtp_session_get_local_port(rs->sess); + + return 0; +} + +/*! \brief obtain the locally bound address and port + * \param[in] rs OsmoRTP socket + * \param[out] addr caller-allocated char ** to which the string pointer for + * the address is stored + * \param[out] port caller-allocated int * to which the port number is + * stored + * \returns 0 on success, <0 in case of error + */ +int osmo_rtp_get_bound_addr(struct osmo_rtp_socket *rs, + const char **addr, int *port) +{ + int rc; + struct sockaddr_storage ss; + socklen_t alen = sizeof(ss); + static char hostbuf[256]; + + memset(hostbuf, 0, sizeof(hostbuf)); + + rc = getsockname(rs->rtp_bfd.fd, (struct sockaddr *)&ss, &alen); + if (rc < 0) + return rc; + + rc = getnameinfo((struct sockaddr *)&ss, alen, + hostbuf, sizeof(hostbuf), NULL, 0, + NI_NUMERICHOST); + if (rc < 0) + return rc; + + *port = rtp_session_get_local_port(rs->sess); + *addr = hostbuf; + + return 0; +} + + +void osmo_rtp_socket_log_stats(struct osmo_rtp_socket *rs, + int subsys, int level, + const char *pfx) +{ + const rtp_stats_t *stats; + + stats = rtp_session_get_stats(rs->sess); + if (!stats) + return; + + LOGP(subsys, level, "%sRTP Tx(%"PRIu64" pkts, %"PRIu64" bytes) " + "Rx(%"PRIu64" pkts, %"PRIu64" bytes, %"PRIu64" late, " + "%"PRIu64" loss, %"PRIu64" qmax)\n", + pfx, stats->packet_sent, stats->sent, + stats->packet_recv, stats->hw_recv, stats->outoftime, + stats->cum_packet_loss, stats->discarded); +} + +void osmo_rtp_socket_stats(struct osmo_rtp_socket *rs, + uint32_t *sent_packets, uint32_t *sent_octets, + uint32_t *recv_packets, uint32_t *recv_octets, + uint32_t *recv_lost, uint32_t *last_jitter) +{ + const rtp_stats_t *stats; + + *sent_packets = *sent_octets = *recv_packets = *recv_octets = 0; + *recv_lost = *last_jitter = 0; + + stats = rtp_session_get_stats(rs->sess); + if (stats) { + /* truncate from 64bit to 32bit here */ + *sent_packets = stats->packet_sent; + *sent_octets = stats->sent; + *recv_packets = stats->packet_recv; + *recv_octets = stats->recv; + *recv_lost = stats->cum_packet_loss; + } + + const jitter_stats_t *jitter; + + jitter = rtp_session_get_jitter_stats(rs->sess); + if (jitter) + *last_jitter = jitter->jitter; +} diff --git a/src/trau_frame.c b/src/trau_frame.c new file mode 100644 index 0000000..2f5a003 --- /dev/null +++ b/src/trau_frame.c @@ -0,0 +1,328 @@ +/* TRAU frame handling according to GSM TS 08.60 */ + +/* (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 "internal.h" + +#include <unistd.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> + +#include <osmocom/abis/trau_frame.h> +#include <osmocom/abis/subchan_demux.h> +#include <osmocom/core/logging.h> + +/*! \addtogroup trau_frame + * @{ + * + * \file trau_frame.c + */ + +static uint32_t get_bits(const uint8_t *bitbuf, int offset, int num) +{ + int i; + uint32_t ret = 0; + + for (i = offset; i < offset + num; i++) { + ret = ret << 1; + if (bitbuf[i]) + ret |= 1; + } + return ret; +} + +/* Decode according to 3.1.1 */ +static void decode_fr(struct decoded_trau_frame *fr, const uint8_t *trau_bits) +{ + int i; + int d_idx = 0; + + /* C1 .. C15 */ + memcpy(fr->c_bits+0, trau_bits+17, 15); + /* C16 .. C21 */ + memcpy(fr->c_bits+15, trau_bits+310, 6); + /* T1 .. T4 */ + memcpy(fr->t_bits+0, trau_bits+316, 4); + /* D1 .. D255 */ + for (i = 32; i < 304; i+= 16) { + memcpy(fr->d_bits + d_idx, trau_bits+i+1, 15); + d_idx += 15; + } + /* D256 .. D260 */ + memcpy(fr->d_bits + d_idx, trau_bits + 305, 5); +} + +/* Decode according to 3.1.2 */ +static void decode_amr(struct decoded_trau_frame *fr, const uint8_t *trau_bits) +{ + int i; + int d_idx = 0; + + /* C1 .. C15 */ + memcpy(fr->c_bits+0, trau_bits+17, 15); + /* C16 .. C25 */ + memcpy(fr->c_bits+15, trau_bits+33, 10); + /* T1 .. T4 */ + memcpy(fr->t_bits+0, trau_bits+316, 4); + /* D1 .. D5 */ + memcpy(fr->d_bits, trau_bits+43, 5); + /* D6 .. D245 */ + for (i = 48; i < 304; i += 16) { + memcpy(fr->d_bits + d_idx, trau_bits+i+1, 15); + d_idx += 15; + } + /* D246 .. D256 */ + memcpy(fr->d_bits + d_idx, trau_bits + 305, 11); +} + +static void decode_data(struct decoded_trau_frame *fr, const uint8_t *trau_bits) +{ + /* C1 .. C15 */ + memcpy(fr->c_bits+0, trau_bits+17, 15); + /* octets 4 .. 39 */ + memcpy(fr->d_bits, trau_bits+32, 288); +} + +int decode_trau_frame(struct decoded_trau_frame *fr, const uint8_t *trau_bits) +{ + uint8_t cbits5 = get_bits(trau_bits, 17, 5); + + switch (cbits5) { + case TRAU_FT_FR_UP: + case TRAU_FT_FR_DOWN: + case TRAU_FT_IDLE_UP: + case TRAU_FT_IDLE_DOWN: + case TRAU_FT_EFR: + decode_fr(fr, trau_bits); + break; + case TRAU_FT_AMR: + decode_amr(fr, trau_bits); + break; + case TRAU_FT_DATA_UP: + case TRAU_FT_DATA_DOWN: + decode_data(fr, trau_bits); + break; + case TRAU_FT_OM_UP: + case TRAU_FT_OM_DOWN: + case TRAU_FT_D145_SYNC: + case TRAU_FT_EDATA: + LOGP(DLMUX, LOGL_NOTICE, "can't decode unimplemented TRAU " + "Frame Type 0x%02x\n", cbits5); + return -1; + break; + default: + LOGP(DLMUX, LOGL_NOTICE, "can't decode unknown TRAU " + "Frame Type 0x%02x\n", cbits5); + return -1; + break; + } + + return 0; +} + +const uint8_t ft_fr_down_bits[] = { 1, 1, 1, 0, 0 }; +const uint8_t ft_idle_down_bits[] = { 0, 1, 1, 1, 0 }; +const uint8_t ft_data_down_bits[] = { 1, 0, 1, 1, 0 }; + +/*! \brief modify an uplink TRAU frame so we can send it downlink + * \param[in,out] fr the uplink TRAU frame that is to be converted + * \returns 0 in case of success, < 0 in caes of error + */ +int trau_frame_up2down(struct decoded_trau_frame *fr) +{ + uint8_t cbits5 = get_bits(fr->c_bits, 0, 5); + + switch (cbits5) { + case TRAU_FT_FR_UP: + memcpy(fr->c_bits, ft_fr_down_bits, 5); + /* clear time alignment */ + memset(fr->c_bits+5, 0, 6); + /* FIXME: SP / BFI in case of DTx */ + /* C12 .. C21 are spare and coded as '1' */ + memset(fr->c_bits+11, 0x01, 10); + break; + case TRAU_FT_EFR: + /* clear time alignment */ + memset(fr->c_bits+5, 0, 6); + /* set UFE appropriately */ + fr->c_bits[11] = 1; /* C12 (UFE), good frame (TODO) */ + /* C13 .. C15 are spare and coded as '1' */ + memset(fr->c_bits+12, 0x01, 3); + /* SP / BFI in case of DTx */ + fr->c_bits[15] = 1; /* C16 (SP), no DTX (TODO) */ + /* C17 .. C21 are spare and coded as '1' */ + memset(fr->c_bits+16, 0x01, 5); + break; + case TRAU_FT_IDLE_UP: + memcpy(fr->c_bits, ft_idle_down_bits, 5); + /* clear time alignment */ + memset(fr->c_bits+5, 0, 6); + /* FIXME: SP / BFI in case of DTx */ + /* C12 .. C21 are spare and coded as '1' */ + memset(fr->c_bits+11, 0x01, 10); + break; + case TRAU_FT_DATA_UP: + memcpy(fr->c_bits, ft_data_down_bits, 5); + break; + case TRAU_FT_FR_DOWN: + case TRAU_FT_IDLE_DOWN: + case TRAU_FT_OM_DOWN: + case TRAU_FT_DATA_DOWN: + /* we cannot convert a downlink to a downlink frame */ + return -EINVAL; + break; + case TRAU_FT_AMR: + case TRAU_FT_OM_UP: + case TRAU_FT_D145_SYNC: + case TRAU_FT_EDATA: + LOGP(DLMUX, LOGL_NOTICE, "unimplemented TRAU Frame Type " + "0x%02x\n", cbits5); + return -1; + break; + default: + LOGP(DLMUX, LOGL_NOTICE, "unknown TRAU Frame Type " + "0x%02x\n", cbits5); + return -1; + break; + } + + return 0; + +} + +static void encode_fr(uint8_t *trau_bits, const struct decoded_trau_frame *fr) +{ + int i; + int d_idx = 0; + + trau_bits[16] = 1; + /* C1 .. C15 */ + memcpy(trau_bits+17, fr->c_bits+0, 15); + /* D1 .. D255 */ + for (i = 32; i < 304; i+= 16) { + trau_bits[i] = 1; + memcpy(trau_bits+i+1, fr->d_bits + d_idx, 15); + d_idx += 15; + } + /* D256 .. D260 */ + trau_bits[304] = 1; + memcpy(trau_bits + 305, fr->d_bits + d_idx, 5); + /* C16 .. C21 */ + memcpy(trau_bits+310, fr->c_bits+15, 6); + + /* FIXME: handle timing adjustment */ + + /* T1 .. T4 */ + memcpy(trau_bits+316, fr->t_bits+0, 4); +} + +static void encode_data(uint8_t *trau_bits, const struct decoded_trau_frame *fr) +{ + trau_bits[16] = 1; + /* C1 .. C15 */ + memcpy(trau_bits+17, fr->c_bits+0, 15); + /* octets 4 .. 39 */ + memcpy(trau_bits+32, fr->d_bits, 288); +} + +/*! \brief encode a TRAU frame from the decoded bits + * \param[out] trau_bits output buffer, will contain encoded bits + * \param[in] fr decoded trau frame structure + * \returns 0 in case of success, < 0 in case of error + */ +int encode_trau_frame(uint8_t *trau_bits, const struct decoded_trau_frame *fr) +{ + uint8_t cbits5 = get_bits(fr->c_bits, 0, 5); + + /* 16 bits of sync header */ + memset(trau_bits, 0, 16); + + switch (cbits5) { + case TRAU_FT_FR_UP: + case TRAU_FT_FR_DOWN: + case TRAU_FT_IDLE_UP: + case TRAU_FT_IDLE_DOWN: + case TRAU_FT_EFR: + encode_fr(trau_bits, fr); + break; + case TRAU_FT_DATA_UP: + case TRAU_FT_DATA_DOWN: + encode_data(trau_bits, fr); + break; + case TRAU_FT_AMR: + case TRAU_FT_OM_UP: + case TRAU_FT_OM_DOWN: + case TRAU_FT_D145_SYNC: + case TRAU_FT_EDATA: + LOGP(DLMUX, LOGL_NOTICE, "unimplemented TRAU Frame Type " + "0x%02x\n", cbits5); + return -1; + break; + default: + LOGP(DLMUX, LOGL_NOTICE, "unknown TRAU Frame Type " + "0x%02x\n", cbits5); + return -1; + break; + } + + return 0; +} + +static struct decoded_trau_frame fr_idle_frame = { + .c_bits = { 0, 1, 1, 1, 0 }, /* IDLE DOWNLINK 3.5.5 */ + .t_bits = { 1, 1, 1, 1 }, +}; +static uint8_t encoded_idle_frame[TRAU_FRAME_BITS]; +static int dbits_initted = 0; + +/*! \brief return pointer to global buffer containing a TRAU idle frame + */ +uint8_t *trau_idle_frame(void) +{ + /* only initialize during the first call */ + if (!dbits_initted) { + /* set all D-bits to 1 */ + memset(&fr_idle_frame.d_bits, 0x01, 260); + + memset(&fr_idle_frame.c_bits, 0x01, 25); /* spare are set to 1 */ + /* set Downlink Idle Speech Frame pattern */ + fr_idle_frame.c_bits[0] = 0; /* C1 */ + fr_idle_frame.c_bits[1] = 1; /* C2 */ + fr_idle_frame.c_bits[2] = 1; /* C3 */ + fr_idle_frame.c_bits[3] = 1; /* C4 */ + fr_idle_frame.c_bits[4] = 0; /* C5 */ + /* set no Time Alignment pattern */ + fr_idle_frame.c_bits[5] = 0; /* C6 */ + fr_idle_frame.c_bits[6] = 0; /* C7 */ + fr_idle_frame.c_bits[7] = 0; /* C8 */ + fr_idle_frame.c_bits[8] = 0; /* C9 */ + fr_idle_frame.c_bits[9] = 0; /* C10 */ + fr_idle_frame.c_bits[10] = 0; /* C11 */ + /* already set to 1, but maybe we need to modify it in the future */ + fr_idle_frame.c_bits[11] = 1; /* C12 (UFE), good frame */ + fr_idle_frame.c_bits[15] = 1; /* C16 (SP), no DTX */ + + encode_fr(encoded_idle_frame, &fr_idle_frame); + dbits_initted = 1; /* set it to 1 to not call it again */ + } + return encoded_idle_frame; +} + +/* }@ */ |