blob: 76fe78add8bd5c95f2e71a4508510c70242a24ad [file] [log] [blame]
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001/* GTP Hub Implementation */
2
3/* (C) 2015 by sysmocom s.f.m.c. GmbH <info@sysmocom.de>
4 * All Rights Reserved
5 *
6 * Author: Neels Hofmeyr
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#include <string.h>
23#include <errno.h>
24#include <inttypes.h>
25#include <time.h>
26#include <limits.h>
27#include <sys/socket.h>
28#include <netinet/in.h>
29#include <arpa/inet.h>
30
31#include <gtp.h>
32#include <gtpie.h>
33
34#include <openbsc/gtphub.h>
35#include <openbsc/debug.h>
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +010036#include <openbsc/gprs_utils.h>
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +020037
38#include <osmocom/core/utils.h>
39#include <osmocom/core/logging.h>
40#include <osmocom/core/socket.h>
41
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +010042
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +020043#define GTPHUB_DEBUG 1
44
45static const int GTPH_GC_TICK_SECONDS = 1;
46
47void *osmo_gtphub_ctx;
48
49#define LOGERR(fmt, args...) \
50 LOGP(DGTPHUB, LOGL_ERROR, fmt, ##args)
51
52#define LOG(fmt, args...) \
53 LOGP(DGTPHUB, LOGL_NOTICE, fmt, ##args)
54
55#define ZERO_STRUCT(struct_pointer) memset(struct_pointer, '\0', sizeof(*(struct_pointer)))
56
57/* TODO move this to osmocom/core/select.h ? */
58typedef int (*osmo_fd_cb_t)(struct osmo_fd *fd, unsigned int what);
59
60/* TODO move this to osmocom/core/linuxlist.h ? */
61#define __llist_first(head) (((head)->next == (head)) ? NULL : (head)->next)
62#define llist_first(head, type, entry) llist_entry(__llist_first(head), type, entry)
63
64/* TODO move GTP header stuff to openggsn/gtp/ ? See gtp_decaps*() */
65
66enum gtp_rc {
67 GTP_RC_UNKNOWN = 0,
68 GTP_RC_TINY = 1, /* no IEs (like ping/pong) */
69 GTP_RC_PDU = 2, /* a real packet with IEs */
70
71 GTP_RC_TOOSHORT = -1,
72 GTP_RC_UNSUPPORTED_VERSION = -2,
73 GTP_RC_INVALID_IE = -3,
74};
75
76struct gtp_packet_desc {
77 union gtp_packet *data;
78 int data_len;
79 int header_len;
80 int version;
81 uint8_t type;
82 uint16_t seq;
83 uint32_t header_tei;
84 int rc; /* enum gtp_rc */
85 unsigned int plane_idx;
86 union gtpie_member *ie[GTPIE_SIZE];
87};
88
89void gsn_addr_copy(struct gsn_addr *gsna, const struct gsn_addr *src)
90{
91 memcpy(gsna, src, sizeof(struct gsn_addr));
92}
93
94/* Decode sa to gsna. Return 0 on success. If port is non-NULL, the port number
95 * from sa is also returned. */
96int gsn_addr_from_sockaddr(struct gsn_addr *gsna, uint16_t *port,
97 const struct osmo_sockaddr *sa)
98{
99 char addr_str[256];
100 char port_str[6];
101
102 if (osmo_sockaddr_to_strs(addr_str, sizeof(addr_str),
103 port_str, sizeof(port_str),
104 sa, (NI_NUMERICHOST | NI_NUMERICSERV))
105 != 0) {
106 return -1;
107 }
108
109 if (port)
110 *port = atoi(port_str);
111
112 return gsn_addr_from_str(gsna, addr_str);
113}
114
115int gsn_addr_from_str(struct gsn_addr *gsna, const char *numeric_addr_str)
116{
117 int af = AF_INET;
118 gsna->len = 4;
119 const char *pos = numeric_addr_str;
120 for (; *pos; pos++) {
121 if (*pos == ':') {
122 af = AF_INET6;
123 gsna->len = 16;
124 break;
125 }
126 }
127
128 int rc = inet_pton(af, numeric_addr_str, gsna->buf);
129 if (rc != 1) {
130 LOGERR("Cannot resolve numeric address: '%s'\n", numeric_addr_str);
131 return -1;
132 }
133 return 0;
134}
135
136const char *gsn_addr_to_str(const struct gsn_addr *gsna)
137{
138 static char buf[INET6_ADDRSTRLEN + 1];
139 return gsn_addr_to_strb(gsna, buf, sizeof(buf));
140}
141
142const char *gsn_addr_to_strb(const struct gsn_addr *gsna,
143 char *strbuf,
144 int strbuf_len)
145{
146 int af;
147 switch (gsna->len) {
148 case 4:
149 af = AF_INET;
150 break;
151 case 16:
152 af = AF_INET6;
153 break;
154 default:
155 return NULL;
156 }
157
158 const char *r = inet_ntop(af, gsna->buf, strbuf, strbuf_len);
159 if (!r) {
160 LOGERR("Cannot convert gsn_addr to string: %s: len=%d, buf=%s\n",
161 strerror(errno),
162 (int)gsna->len,
163 osmo_hexdump(gsna->buf, sizeof(gsna->buf)));
164 }
165 return r;
166}
167
168int gsn_addr_same(const struct gsn_addr *a, const struct gsn_addr *b)
169{
170 if (a == b)
171 return 1;
172 if ((!a) || (!b))
173 return 0;
174 if (a->len != b->len)
175 return 0;
176 return (memcmp(a->buf, b->buf, a->len) == 0)? 1 : 0;
177}
178
179static int gsn_addr_get(struct gsn_addr *gsna, const struct gtp_packet_desc *p, int idx)
180{
181 if (p->rc != GTP_RC_PDU)
182 return -1;
183
184 unsigned int len;
185 /* gtpie.h fails to declare gtpie_gettlv()'s first arg as const. */
186 if (gtpie_gettlv((union gtpie_member**)p->ie, GTPIE_GSN_ADDR, idx,
187 &len, gsna->buf, sizeof(gsna->buf))
188 != 0)
189 return -1;
190 gsna->len = len;
191 return 0;
192}
193
194static int gsn_addr_put(const struct gsn_addr *gsna, struct gtp_packet_desc *p, int idx)
195{
196 if (p->rc != GTP_RC_PDU)
197 return -1;
198
199 int ie_idx;
200 ie_idx = gtpie_getie(p->ie, GTPIE_GSN_ADDR, idx);
201
202 if (ie_idx < 0)
203 return -1;
204
205 struct gtpie_tlv *ie = &p->ie[ie_idx]->tlv;
206 int ie_l = ntoh16(ie->l);
207 if (ie_l != gsna->len) {
208 LOG("Not implemented: replace an IE address of different size:"
209 " replace %d with %d\n", (int)ie_l, (int)gsna->len);
210 return -1;
211 }
212
213 memcpy(ie->v, gsna->buf, (int)ie_l);
214 return 0;
215}
216
217/* Validate GTP version 0 data; analogous to validate_gtp1_header(), see there.
218 */
219void validate_gtp0_header(struct gtp_packet_desc *p)
220{
221 const struct gtp0_header *pheader = &(p->data->gtp0.h);
222 p->rc = GTP_RC_UNKNOWN;
223 p->header_len = 0;
224
225 OSMO_ASSERT(p->data_len >= 1);
226 OSMO_ASSERT(p->version == 0);
227
228 if (p->data_len < GTP0_HEADER_SIZE) {
229 LOGERR("GTP0 packet too short: %d\n", p->data_len);
230 p->rc = GTP_RC_TOOSHORT;
231 return;
232 }
233
234 p->type = ntoh8(pheader->type);
235 p->seq = ntoh16(pheader->seq);
236 p->header_tei = 0; /* TODO */
237
238 if (p->data_len == GTP0_HEADER_SIZE) {
239 p->rc = GTP_RC_TINY;
240 p->header_len = GTP0_HEADER_SIZE;
241 return;
242 }
243
244 /* Check packet length field versus length of packet */
245 if (p->data_len != (ntoh16(pheader->length) + GTP0_HEADER_SIZE)) {
246 LOGERR("GTP packet length field (%d + %d) does not match"
247 " actual length (%d)\n",
248 GTP0_HEADER_SIZE, (int)ntoh16(pheader->length),
249 p->data_len);
250 p->rc = GTP_RC_TOOSHORT;
251 return;
252 }
253
254 LOG("GTP v0 TID = %" PRIu64 "\n", pheader->tid);
255 p->header_len = GTP0_HEADER_SIZE;
256 p->rc = GTP_RC_PDU;
257}
258
259/* Validate GTP version 1 data, and update p->rc with the result, as well as
260 * p->header_len in case of a valid header. */
261void validate_gtp1_header(struct gtp_packet_desc *p)
262{
263 const struct gtp1_header_long *pheader = &(p->data->gtp1l.h);
264 p->rc = GTP_RC_UNKNOWN;
265 p->header_len = 0;
266
267 OSMO_ASSERT(p->data_len >= 1);
268 OSMO_ASSERT(p->version == 1);
269
270 if ((p->data_len < GTP1_HEADER_SIZE_LONG)
271 && (p->data_len != GTP1_HEADER_SIZE_SHORT)){
272 LOGERR("GTP packet too short: %d\n", p->data_len);
273 p->rc = GTP_RC_TOOSHORT;
274 return;
275 }
276
277 p->type = ntoh8(pheader->type);
278 p->header_tei = ntoh32(pheader->tei);
279 p->seq = ntoh16(pheader->seq);
280
281 LOG("|GTPv1\n");
282 LOG("| type = %" PRIu8 " 0x%02" PRIx8 "\n",
283 p->type, p->type);
284 LOG("| length = %" PRIu16 " 0x%04" PRIx16 "\n",
285 ntoh16(pheader->length), ntoh16(pheader->length));
286 LOG("| TEI = %" PRIu32 " 0x%08" PRIx32 "\n",
287 p->header_tei, p->header_tei);
288 LOG("| seq = %" PRIu16 " 0x%04" PRIx16 "\n",
289 p->seq, p->seq);
290 LOG("| npdu = %" PRIu8 " 0x%02" PRIx8 "\n",
291 pheader->npdu, pheader->npdu);
292 LOG("| next = %" PRIu8 " 0x%02" PRIx8 "\n",
293 pheader->next, pheader->next);
294
295 if (p->data_len <= GTP1_HEADER_SIZE_LONG) {
296 p->rc = GTP_RC_TINY;
297 p->header_len = GTP1_HEADER_SIZE_SHORT;
298 return;
299 }
300
301 /* Check packet length field versus length of packet */
302 if (p->data_len != (ntoh16(pheader->length) + GTP1_HEADER_SIZE_SHORT)) {
303 LOGERR("GTP packet length field (%d + %d) does not match"
304 " actual length (%d)\n",
305 GTP1_HEADER_SIZE_SHORT, (int)ntoh16(pheader->length),
306 p->data_len);
307 p->rc = GTP_RC_TOOSHORT;
308 return;
309 }
310
311 p->rc = GTP_RC_PDU;
312 p->header_len = GTP1_HEADER_SIZE_LONG;
313}
314
315/* Examine whether p->data of size p->data_len has a valid GTP header. Set
316 * p->version, p->rc and p->header_len. On error, p->rc <= 0 (see enum
317 * gtp_rc). p->data must point at a buffer with p->data_len set. */
318void validate_gtp_header(struct gtp_packet_desc *p)
319{
320 p->rc = GTP_RC_UNKNOWN;
321
322 /* Need at least 1 byte in order to check version */
323 if (p->data_len < 1) {
324 LOGERR("Discarding packet - too small: %d\n", p->data_len);
325 p->rc = GTP_RC_TOOSHORT;
326 return;
327 }
328
329 p->version = p->data->flags >> 5;
330
331 switch (p->version) {
332 case 0:
333 validate_gtp0_header(p);
334 break;
335 case 1:
336 validate_gtp1_header(p);
337 break;
338 default:
339 LOGERR("Unsupported GTP version: %d\n", p->version);
340 p->rc = GTP_RC_UNSUPPORTED_VERSION;
341 break;
342 }
343}
344
345
346/* Return the value of the i'th IMSI IEI by copying to *imsi.
347 * The first IEI is reached by passing i = 0.
348 * imsi must point at allocated space of (at least) 8 bytes.
349 * Return 1 on success, or 0 if not found. */
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100350static int get_ie_imsi(union gtpie_member *ie[], int i, uint8_t *imsi)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200351{
352 return gtpie_gettv0(ie, GTPIE_IMSI, i, imsi, 8) == 0;
353}
354
355/* Analogous to get_ie_imsi(). nsapi must point at a single uint8_t. */
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100356static int get_ie_nsapi(union gtpie_member *ie[], int i, uint8_t *nsapi)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200357{
358 return gtpie_gettv1(ie, GTPIE_NSAPI, i, nsapi) == 0;
359}
360
361static char imsi_digit_to_char(uint8_t nibble)
362{
363 nibble &= 0x0f;
364 if (nibble > 9)
365 return (nibble == 0x0f) ? '\0' : '?';
366 return '0' + nibble;
367}
368
369/* Return a human readable IMSI string, in a static buffer.
370 * imsi must point at 8 octets of IMSI IE encoded IMSI data. */
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100371static int imsi_to_str(uint8_t *imsi, const char **imsi_str)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200372{
373 static char str[17];
374 int i;
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100375 char c;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200376
377 for (i = 0; i < 8; i++) {
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100378 c = imsi_digit_to_char(imsi[i]);
379 if (c == '?')
380 return -1;
381 str[2*i] = c;
382
383 c = imsi_digit_to_char(imsi[i] >> 4);
384 if (c == '?')
385 return -1;
386 str[2*i + 1] = c;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200387 }
388 str[16] = '\0';
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100389 *imsi_str = str;
390 return 1;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200391}
392
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100393/* Return 0 if not present, 1 if present and decoded successfully, -1 if
394 * present but cannot be decoded. */
395static int get_ie_imsi_str(union gtpie_member *ie[], int i, const char **imsi_str)
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100396{
397 uint8_t imsi_buf[8];
398 if (!get_ie_imsi(ie, i, imsi_buf))
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100399 return 0;
400 return imsi_to_str(imsi_buf, imsi_str);
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100401}
402
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100403/* Return 0 if not present, 1 if present and decoded successfully, -1 if
404 * present but cannot be decoded. */
405static int get_ie_apn_str(union gtpie_member *ie[], const char **apn_str)
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100406{
407 static char apn_buf[GSM_APN_LENGTH];
408 unsigned int len;
409 if (gtpie_gettlv(ie, GTPIE_APN, 0,
410 &len, apn_buf, sizeof(apn_buf)) != 0)
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100411 return 0;
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100412
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100413 if (len < 2) {
414 LOGERR("APN IE: invalid length: %d\n",
415 (int)len);
416 return -1;
417 }
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100418
419 if (len > (sizeof(apn_buf) - 1))
420 len = sizeof(apn_buf) - 1;
421 apn_buf[len] = '\0';
422
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100423 *apn_str = gprs_apn_to_str(apn_buf, (uint8_t*)apn_buf, len);
424 if (!(*apn_str)) {
425 LOGERR("APN IE: present but cannot be decoded: %s\n",
426 osmo_hexdump((uint8_t*)apn_buf, len));
427 return -1;
428 }
429 return 1;
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100430}
431
432
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200433/* Validate header, and index information elements. Write decoded packet
434 * information to *res. res->data will point at the given data buffer. On
435 * error, p->rc is set <= 0 (see enum gtp_rc). */
436static void gtp_decode(const uint8_t *data, int data_len,
437 unsigned int from_plane_idx,
438 struct gtp_packet_desc *res)
439{
440 ZERO_STRUCT(res);
441 res->data = (union gtp_packet*)data;
442 res->data_len = data_len;
443 res->plane_idx = from_plane_idx;
444
445 validate_gtp_header(res);
446
447 if (res->rc <= 0) {
448 LOGERR("INVALID: dropping GTP packet.\n");
449 return;
450 }
451
452 LOG("Valid GTP header (v%d)\n", res->version);
453
454 if (res->rc != GTP_RC_PDU) {
455 LOG("no IEs in this GTP packet\n");
456 return;
457 }
458
459 if (gtpie_decaps(res->ie, res->version,
460 (void*)(data + res->header_len),
461 res->data_len - res->header_len) != 0) {
462 res->rc = GTP_RC_INVALID_IE;
463 return;
464 }
465
466#if GTPHUB_DEBUG
467 int i;
468
469 for (i = 0; i < 10; i++) {
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100470 const char *imsi;
471 if (get_ie_imsi_str(res->ie, i, &imsi) < 1)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200472 break;
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100473 LOG("| IMSI %s\n", imsi);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200474 }
475
476 for (i = 0; i < 10; i++) {
477 uint8_t nsapi;
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100478 if (!get_ie_nsapi(res->ie, i, &nsapi))
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200479 break;
480 LOG("| NSAPI %d\n", (int)nsapi);
481 }
482
483 for (i = 0; i < 2; i++) {
484 struct gsn_addr addr;
485 if (gsn_addr_get(&addr, res, i) == 0)
486 LOG("| addr %s\n", gsn_addr_to_str(&addr));
487 }
488
489 for (i = 0; i < 10; i++) {
490 uint32_t tei;
491 if (gtpie_gettv4(res->ie, GTPIE_TEI_DI, i, &tei) != 0)
492 break;
493 LOG("| TEI DI (USER) %" PRIu32 " 0x%08" PRIx32 "\n",
494 tei, tei);
495 }
496
497 for (i = 0; i < 10; i++) {
498 uint32_t tei;
499 if (gtpie_gettv4(res->ie, GTPIE_TEI_C, i, &tei) != 0)
500 break;
501 LOG("| TEI (CTRL) %" PRIu32 " 0x%08" PRIx32 "\n",
502 tei, tei);
503 }
504#endif
505}
506
507
508/* expiry */
509
510void expiry_init(struct expiry *exq, int expiry_in_seconds)
511{
512 ZERO_STRUCT(exq);
513 exq->expiry_in_seconds = expiry_in_seconds;
514 INIT_LLIST_HEAD(&exq->items);
515}
516
517void expiry_add(struct expiry *exq, struct expiring_item *item, time_t now)
518{
519 item->expiry = now + exq->expiry_in_seconds;
520
521 /* Add/move to the tail to always sort by expiry, ascending. */
522 llist_del(&item->entry);
523 llist_add_tail(&item->entry, &exq->items);
524}
525
526int expiry_tick(struct expiry *exq, time_t now)
527{
528 int expired = 0;
529 struct expiring_item *m, *n;
530 llist_for_each_entry_safe(m, n, &exq->items, entry) {
531 if (m->expiry <= now) {
532 expiring_item_del(m);
533 expired ++;
534 } else {
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200535 /* The items are added sorted by expiry. So when we hit
536 * an unexpired entry, only more unexpired ones will
537 * follow. */
538 break;
539 }
540 }
541 return expired;
542}
543
544void expiring_item_init(struct expiring_item *item)
545{
546 ZERO_STRUCT(item);
547 INIT_LLIST_HEAD(&item->entry);
548}
549
550void expiring_item_del(struct expiring_item *item)
551{
552 OSMO_ASSERT(item);
553 llist_del(&item->entry);
554 INIT_LLIST_HEAD(&item->entry);
555 if (item->del_cb) {
556 /* avoid loops */
557 del_cb_t del_cb = item->del_cb;
558 item->del_cb = 0;
559 (del_cb)(item);
560 }
561}
562
563
564/* nr_map, nr_pool */
565
566void nr_pool_init(struct nr_pool *pool)
567{
568 *pool = (struct nr_pool){};
569}
570
571nr_t nr_pool_next(struct nr_pool *pool)
572{
573 pool->last_nr ++;
574
575 OSMO_ASSERT(pool->last_nr > 0);
576 /* TODO: gracefully handle running out of TEIs. */
577 /* TODO: random TEIs. */
578
579 return pool->last_nr;
580}
581
582void nr_map_init(struct nr_map *map, struct nr_pool *pool,
583 struct expiry *exq)
584{
585 ZERO_STRUCT(map);
586 map->pool = pool;
587 map->add_items_to_expiry = exq;
588 INIT_LLIST_HEAD(&map->mappings);
589}
590
591void nr_mapping_init(struct nr_mapping *m)
592{
593 ZERO_STRUCT(m);
594 INIT_LLIST_HEAD(&m->entry);
595 expiring_item_init(&m->expiry_entry);
596}
597
598void nr_map_add(struct nr_map *map, struct nr_mapping *mapping, time_t now)
599{
600 /* Generate a mapped number */
601 mapping->repl = nr_pool_next(map->pool);
602
603 /* Add to the tail to always yield a list sorted by expiry, in
604 * ascending order. */
605 llist_add_tail(&mapping->entry, &map->mappings);
606 if (map->add_items_to_expiry)
607 expiry_add(map->add_items_to_expiry,
608 &mapping->expiry_entry,
609 now);
610}
611
612void nr_map_clear(struct nr_map *map)
613{
614 struct nr_mapping *m;
615 struct nr_mapping *n;
616 llist_for_each_entry_safe(m, n, &map->mappings, entry) {
617 nr_mapping_del(m);
618 }
619}
620
621int nr_map_empty(const struct nr_map *map)
622{
623 return llist_empty(&map->mappings);
624}
625
626struct nr_mapping *nr_map_get(const struct nr_map *map,
627 void *origin, nr_t nr_orig)
628{
629 struct nr_mapping *mapping;
630 llist_for_each_entry(mapping, &map->mappings, entry) {
631 if ((mapping->origin == origin)
632 && (mapping->orig == nr_orig))
633 return mapping;
634 }
635 /* Not found. */
636 return NULL;
637}
638
639struct nr_mapping *nr_map_get_inv(const struct nr_map *map, nr_t nr_repl)
640{
641 struct nr_mapping *mapping;
642 llist_for_each_entry(mapping, &map->mappings, entry) {
643 if (mapping->repl == nr_repl) {
644 return mapping;
645 }
646 }
647 /* Not found. */
648 return NULL;
649}
650
651void nr_mapping_del(struct nr_mapping *mapping)
652{
653 OSMO_ASSERT(mapping);
654 llist_del(&mapping->entry);
655 INIT_LLIST_HEAD(&mapping->entry);
656 expiring_item_del(&mapping->expiry_entry);
657}
658
659
660/* gtphub */
661
662const char* const gtphub_plane_idx_names[GTPH_PLANE_N] = {
663 "CTRL",
664 "USER",
665};
666
667const uint16_t gtphub_plane_idx_default_port[GTPH_PLANE_N] = {
668 2123,
669 2152,
670};
671
672time_t gtphub_now(void)
673{
674 struct timespec now_tp;
675 OSMO_ASSERT(clock_gettime(CLOCK_MONOTONIC, &now_tp) >= 0);
676 return now_tp.tv_sec;
677}
678
679/* Remove a gtphub_peer from its list and free it. */
680static void gtphub_peer_del(struct gtphub_peer *peer)
681{
682 nr_map_clear(&peer->seq_map);
683 llist_del(&peer->entry);
684 talloc_free(peer);
685}
686
687static void gtphub_peer_addr_del(struct gtphub_peer_addr *pa)
688{
689 OSMO_ASSERT(llist_empty(&pa->ports));
690 llist_del(&pa->entry);
691 talloc_free(pa);
692}
693
694static void gtphub_peer_port_del(struct gtphub_peer_port *pp)
695{
696 OSMO_ASSERT(pp->ref_count == 0);
697 llist_del(&pp->entry);
698 talloc_free(pp);
699}
700
701/* From the information in the gtp_packet_desc, return the address of a GGSN.
702 * Return -1 on error. */
Neels Hofmeyr5b664f42015-11-10 20:32:13 +0100703static int gtphub_resolve_ggsn(struct gtphub *hub,
704 struct gtp_packet_desc *p,
705 struct gtphub_peer_port **pp);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200706
707/* See gtphub_ext.c (wrapped by unit test) */
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100708struct gtphub_peer_port *gtphub_resolve_ggsn_addr(struct gtphub *hub,
709 const char *imsi_str,
710 const char *apn_ni_str);
711int gtphub_ares_init(struct gtphub *hub);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200712
713static struct gtphub_peer_port *gtphub_port_find(const struct gtphub_bind *bind,
714 const struct gsn_addr *addr,
715 uint16_t port);
716
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200717static void gtphub_zero(struct gtphub *hub)
718{
719 ZERO_STRUCT(hub);
720}
721
722static int gtphub_sock_init(struct osmo_fd *ofd,
723 const struct gtphub_cfg_addr *addr,
724 osmo_fd_cb_t cb,
725 void *data,
726 int ofd_id)
727{
728 if (!addr->addr_str) {
729 LOGERR("Cannot bind: empty address.\n");
730 return -1;
731 }
732 if (!addr->port) {
733 LOGERR("Cannot bind: zero port not permitted.\n");
734 return -1;
735 }
736
737 ofd->when = BSC_FD_READ;
738 ofd->cb = cb;
739 ofd->data = data;
740 ofd->priv_nr = ofd_id;
741
742 int rc;
743 rc = osmo_sock_init_ofd(ofd,
744 AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP,
745 addr->addr_str, addr->port,
746 OSMO_SOCK_F_BIND);
747 if (rc < 1) {
748 LOGERR("Cannot bind to %s port %d (rc %d)\n",
749 addr->addr_str, (int)addr->port, rc);
750 return -1;
751 }
752
753 return 0;
754}
755
756static void gtphub_bind_init(struct gtphub_bind *b)
757{
758 ZERO_STRUCT(b);
759
760 INIT_LLIST_HEAD(&b->peers);
761}
762
763static int gtphub_bind_start(struct gtphub_bind *b,
764 const struct gtphub_cfg_bind *cfg,
765 osmo_fd_cb_t cb, void *cb_data,
766 unsigned int ofd_id)
767{
768 if (gsn_addr_from_str(&b->local_addr, cfg->bind.addr_str) != 0)
769 return -1;
770 if (gtphub_sock_init(&b->ofd, &cfg->bind, cb, cb_data, ofd_id) != 0)
771 return -1;
772 return 0;
773}
774
775/* Recv datagram from from->fd, optionally write sender's address to *from_addr.
776 * Return the number of bytes read, zero on error. */
777static int gtphub_read(const struct osmo_fd *from,
778 struct osmo_sockaddr *from_addr,
779 uint8_t *buf, size_t buf_len)
780{
781 /* recvfrom requires the available length to be set in *from_addr_len. */
782 if (from_addr)
783 from_addr->l = sizeof(from_addr->a);
784
785 errno = 0;
786 ssize_t received = recvfrom(from->fd, buf, buf_len, 0,
787 (struct sockaddr*)&from_addr->a, &from_addr->l);
788 /* TODO use recvmsg and get a MSG_TRUNC flag to make sure the message
789 * is not truncated. Then maybe reduce buf's size. */
790
791 if (received <= 0) {
792 if (errno != EAGAIN)
793 LOGERR("error: %s\n", strerror(errno));
794 return 0;
795 }
796
797 if (from_addr) {
798 LOG("from %s\n", osmo_sockaddr_to_str(from_addr));
799 }
800
801 if (received <= 0) {
802 LOGERR("error: %s\n", strerror(errno));
803 return 0;
804 }
805
806 LOG("Received %d\n%s\n", (int)received, osmo_hexdump(buf, received));
807 return received;
808}
809
810inline void gtphub_port_ref_count_inc(struct gtphub_peer_port *pp)
811{
812 OSMO_ASSERT(pp->ref_count < UINT_MAX);
813 pp->ref_count++;
814}
815
816inline void gtphub_port_ref_count_dec(struct gtphub_peer_port *pp)
817{
818 OSMO_ASSERT(pp->ref_count > 0);
819 pp->ref_count--;
820}
821
822inline void set_seq(struct gtp_packet_desc *p, uint16_t seq)
823{
824 OSMO_ASSERT(p->version == 1);
825 p->data->gtp1l.h.seq = hton16(seq);
826 p->seq = seq;
827}
828
829inline void set_tei(struct gtp_packet_desc *p, uint32_t tei)
830{
831 OSMO_ASSERT(p->version == 1);
832 p->data->gtp1l.h.tei = hton32(tei);
833 p->header_tei = tei;
834}
835
836static void gtphub_mapping_del_cb(struct expiring_item *expi);
837
838static struct nr_mapping *gtphub_mapping_new()
839{
840 struct nr_mapping *nrm;
841 nrm = talloc_zero(osmo_gtphub_ctx, struct nr_mapping);
842 OSMO_ASSERT(nrm);
843
844 nr_mapping_init(nrm);
845 nrm->expiry_entry.del_cb = gtphub_mapping_del_cb;
846 return nrm;
847}
848
849static const char *gtphub_peer_strb(struct gtphub_peer *peer, char *buf, int buflen)
850{
851 if (llist_empty(&peer->addresses))
852 return "(addressless)";
853
854 struct gtphub_peer_addr *a = llist_first(&peer->addresses,
855 struct gtphub_peer_addr,
856 entry);
857 return gsn_addr_to_strb(&a->addr, buf, buflen);
858}
859
860static const char *gtphub_port_strb(struct gtphub_peer_port *port, char *buf, int buflen)
861{
862 if (!port)
863 return "(null port)";
864
865 snprintf(buf, buflen, "%s port %d",
866 gsn_addr_to_str(&port->peer_addr->addr),
867 (int)port->port);
868 return buf;
869}
870
871const char *gtphub_peer_str(struct gtphub_peer *peer)
872{
873 static char buf[256];
874 return gtphub_peer_strb(peer, buf, sizeof(buf));
875}
876
877const char *gtphub_peer_str2(struct gtphub_peer *peer)
878{
879 static char buf[256];
880 return gtphub_peer_strb(peer, buf, sizeof(buf));
881}
882
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100883const char *gtphub_port_str(struct gtphub_peer_port *port)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200884{
885 static char buf[256];
886 return gtphub_port_strb(port, buf, sizeof(buf));
887}
888
889static const char *gtphub_port_str2(struct gtphub_peer_port *port)
890{
891 static char buf[256];
892 return gtphub_port_strb(port, buf, sizeof(buf));
893}
894
895static void gtphub_mapping_del_cb(struct expiring_item *expi)
896{
897 expi->del_cb = 0; /* avoid recursion loops */
898
899 struct nr_mapping *nrm = container_of(expi,
900 struct nr_mapping,
901 expiry_entry);
902 llist_del(&nrm->entry);
903 INIT_LLIST_HEAD(&nrm->entry); /* mark unused */
904
905 /* Just for log */
906 struct gtphub_peer_port *from = nrm->origin;
907 OSMO_ASSERT(from);
908 LOG("expired: %d: nr mapping from %s: %d->%d\n",
909 (int)nrm->expiry_entry.expiry,
910 gtphub_port_str(from),
911 (int)nrm->orig, (int)nrm->repl);
912
913 gtphub_port_ref_count_dec(from);
914
915 talloc_free(nrm);
916}
917
918static struct nr_mapping *gtphub_mapping_have(struct nr_map *map,
919 struct gtphub_peer_port *from,
920 nr_t orig_nr,
921 time_t now)
922{
923 struct nr_mapping *nrm;
924
925 nrm = nr_map_get(map, from, orig_nr);
926
927 if (!nrm) {
928 nrm = gtphub_mapping_new();
929 nrm->orig = orig_nr;
930 nrm->origin = from;
931 nr_map_add(map, nrm, now);
932 gtphub_port_ref_count_inc(from);
933 LOG("peer %s: MAP %d --> %d\n",
934 gtphub_port_str(from),
935 (int)(nrm->orig), (int)(nrm->repl));
936 } else {
937 /* restart expiry timeout */
938 expiry_add(map->add_items_to_expiry, &nrm->expiry_entry,
939 now);
940 }
941
942 OSMO_ASSERT(nrm);
943 return nrm;
944}
945
946static uint32_t gtphub_tei_mapping_have(struct gtphub *hub,
947 int plane_idx,
948 struct gtphub_peer_port *from,
949 uint32_t orig_tei,
950 time_t now)
951{
952 struct nr_mapping *nrm = gtphub_mapping_have(&hub->tei_map[plane_idx],
953 from, orig_tei, now);
954 LOG("New %s TEI: (from %s, TEI %d) <-- TEI %d\n",
955 gtphub_plane_idx_names[plane_idx],
956 gtphub_port_str(from),
957 (int)orig_tei, (int)nrm->repl);
958
959 return (uint32_t)nrm->repl;
960}
961
962static int gtphub_map_seq(struct gtp_packet_desc *p,
963 struct gtphub_peer_port *from_port,
964 struct gtphub_peer_port *to_port,
965 time_t now)
966{
967 /* Store a mapping in to_peer's map, so when we later receive a GTP
968 * packet back from to_peer, the seq nr can be unmapped back to its
969 * origin (from_peer here). */
970 struct nr_mapping *nrm;
971 nrm = gtphub_mapping_have(&to_port->peer_addr->peer->seq_map,
972 from_port, p->seq, now);
973
974 /* Change the GTP packet to yield the new, mapped seq nr */
975 set_seq(p, nrm->repl);
976
977 return 0;
978}
979
980static struct gtphub_peer_port *gtphub_unmap_seq(struct gtp_packet_desc *p,
981 struct gtphub_peer_port *responding_port)
982{
983 OSMO_ASSERT(p->version == 1);
984 struct nr_mapping *nrm = nr_map_get_inv(&responding_port->peer_addr->peer->seq_map,
985 p->seq);
986 if (!nrm)
987 return NULL;
988 LOG("peer %p: UNMAP %d <-- %d\n", nrm->origin, (int)(nrm->orig), (int)(nrm->repl));
989 set_seq(p, nrm->orig);
990 return nrm->origin;
991}
992
993static void gtphub_check_restart_counter(struct gtphub *hub,
994 struct gtp_packet_desc *p,
995 struct gtphub_peer_port *from)
996{
997 /* TODO */
998 /* If the peer is sending a Recovery IE (7.7.11) with a restart counter
999 * that doesn't match the peer's previously sent restart counter, clear
1000 * that peer and cancel PDP contexts. */
1001}
1002
1003static void gtphub_map_restart_counter(struct gtphub *hub,
1004 struct gtp_packet_desc *p,
1005 struct gtphub_peer_port *from,
1006 struct gtphub_peer_port *to)
1007{
1008 /* TODO */
1009}
1010
1011/* gtphub_map_ie_teis() and gtphub_unmap_header_tei():
1012 *
1013 * TEI mapping must happen symmetrically. An SGSN contacts gtphub instead of N
1014 * GGSNs, and a GGSN replies to gtphub for N SGSNs. From either end, TEIs may
1015 * collide: two GGSNs picking the same TEIs, or two SGSNs picking the same
1016 * TEIs. Since the opposite side sees the sender address being gtphub's
1017 * address, TEIs among the SGSNs, and among the GGSNs, must not overlap. If a
1018 * peer sends a TEI already sent before from a peer of the same side, gtphub
1019 * replaces it with a TEI not yet seen from that side and remembers the
1020 * mapping.
1021 *
1022 * Consider two SGSNs A and B contacting two GGSNs C and D thru gtphub.
1023 *
1024 * A: Create PDP Ctx, I have TEI 1.
1025 * ---> gtphub: A has TEI 1, sending 1 for C.
1026 * ---> C: gtphub has TEI 1.
1027 * <--- C: Response to TEI 1: I have TEI 11.
1028 * <--- gtphub: ok, telling A: 11.
1029 * A: gtphub's first TEI is 11. (1)
1030 *
1031 * B: Create PDP Ctx, I have TEIs 1.
1032 * ---> gtphub: 1 already taken for C, sending 2 for B. (map)
1033 * ---> C: gtphub also has 2.
1034 * <--- C: Response to TEI 2: I have TEI 12.
1035 * <--- gtphub: ok, TEI 2 is actually B with TEI 1. (unmap)
1036 * B: gtphub's first TEI is 12, as far as I can tell.
1037 *
1038 * Now the second GGSN comes into play:
1039 *
1040 * A: Create PDP Ctx, I have TEI 2.
1041 * ---> gtphub: A also has TEI 2, but for D, sending 1. (2)
1042 * ---> D: gtphub has 1.
1043 * <--- D: Response to TEI 1: I have TEI 11.
1044 * <--- gtphub: from D, 1 is A. 11 already taken by C, sending 13. (3)
1045 * A: gtphub also has TEI 13. (4)
1046 *
1047 * And some messages routed through:
1048 *
1049 * A: message to TEI 11, see (1).
1050 * ---> gtphub: ok, telling C with TEI 11.
1051 * ---> C: I see, 11 means reply with 1.
1052 * <--- C: Response to TEI 1
1053 * <--- gtphub: 1 from C is actually for A with TEI 1.
1054 * A: ah, my TEI 1, thanks!
1055 *
1056 * A: message to TEI 13, see (4).
1057 * ---> gtphub: ok, but not 13, D wanted TEI 11 instead, see (3).
1058 * ---> D: I see, 11 means reply with 1.
1059 * <--- D: Response to TEI 1
1060 * <--- gtphub: 1 from D is actually for A with TEI 2, see (2).
1061 * A: ah, my TEI 2, thanks!
1062 *
1063 * What if a GGSN initiates a request:
1064 *
1065 * <--- D: Request to gtphub TEI 1
1066 * <--- gtphub: 1 from D is for A with 2, see (2).
1067 * A: my TEI 2 means reply with 13.
1068 * ---> gtphub: 13 was D with 11, see (3).
1069 * ---> D: 11 from gtphub: a reply to my request for TEI 1.
1070 *
1071 * Note that usually, it's the sequence numbers that route a response back to
1072 * the requesting peer. Nevertheless, the TEI mappings must be carried out to
1073 * replace the TEIs in the GTP packet that is relayed.
1074 *
1075 * Also note: the TEI in the GTP header is "reversed" from the TEI in the IEs:
1076 * the TEI in the header is used to send something *to* a peer, while the TEI
1077 * in e.g. a Create PDP Context Request's IE is for routing messages *back*
1078 * later. */
1079
1080static int gtphub_unmap_header_tei(struct gtphub_peer_port **to_port_p,
1081 struct gtphub *hub,
1082 struct gtp_packet_desc *p,
1083 struct gtphub_peer_port *from_port)
1084{
1085 OSMO_ASSERT(p->version == 1);
1086 *to_port_p = NULL;
1087
1088 /* If the header's TEI is zero, no PDP context has been established
1089 * yet. If nonzero, a mapping should actually already exist for this
1090 * TEI, since it must have been announced in a PDP context creation. */
1091 uint32_t tei = p->header_tei;
1092 if (!tei)
1093 return 0;
1094
1095 /* to_peer has previously announced a TEI, which was stored and
1096 * mapped in from_peer's tei_map. */
1097 struct nr_mapping *nrm;
1098 nrm = nr_map_get_inv(&hub->tei_map[p->plane_idx], tei);
1099 if (!nrm) {
1100 LOGERR("Received unknown TEI %" PRIu32 " from %s\n",
1101 tei, gtphub_port_str(from_port));
1102 return -1;
1103 }
1104
1105 struct gtphub_peer_port *to_port = nrm->origin;
1106 uint32_t unmapped_tei = nrm->orig;
1107 set_tei(p, unmapped_tei);
1108
1109 LOG("Unmapped TEI coming from %s: %d -> %d (to %s)\n",
1110 gtphub_port_str(from_port), tei, unmapped_tei,
1111 gtphub_port_str2(to_port));
1112
1113 *to_port_p = to_port;
1114 return 0;
1115}
1116
1117/* Read GSN address IEs from p, and make sure these peer addresses exist in
1118 * bind[plane_idx] with default ports, in their respective planes (both Ctrl
1119 * and User). Map TEIs announced in IEs, and write mapped TEIs in-place into
1120 * the packet p. */
1121static int gtphub_handle_pdp_ctx_ies(struct gtphub *hub,
1122 struct gtphub_bind from_bind[],
1123 struct gtphub_bind to_bind[],
1124 struct gtp_packet_desc *p,
1125 time_t now)
1126{
1127 OSMO_ASSERT(p->plane_idx == GTPH_PLANE_CTRL);
1128
1129 int rc;
1130 int plane_idx;
1131
1132 switch (p->type) {
1133 case GTP_CREATE_PDP_REQ:
1134 case GTP_CREATE_PDP_RSP:
1135 /* Go for it below */
1136 break;
1137 default:
1138 /* Nothing to do for this message type. */
1139 return 0;
1140 }
1141
1142 /* TODO enforce a Request only from SGSN, a Response only from GGSN? */
1143
1144 osmo_static_assert((GTPH_PLANE_CTRL == 0) && (GTPH_PLANE_USER == 1),
1145 plane_nrs_match_GSN_addr_IE_indices);
1146
1147 uint8_t ie_type[] = { GTPIE_TEI_C, GTPIE_TEI_DI };
1148 int ie_mandatory = (p->type == GTP_CREATE_PDP_REQ);
1149
1150 for (plane_idx = 0; plane_idx < 2; plane_idx++) {
1151 struct gsn_addr addr_from_ie;
1152 uint32_t tei_from_ie;
1153 int ie_idx;
1154
1155 /* Fetch GSN Address and TEI from IEs */
1156 rc = gsn_addr_get(&addr_from_ie, p, plane_idx);
1157 if (rc) {
1158 LOGERR("Cannot read %s GSN Address IE\n",
1159 gtphub_plane_idx_names[plane_idx]);
1160 return -1;
1161 }
1162 LOG("Read %s GSN addr %s (%d)\n",
1163 gtphub_plane_idx_names[plane_idx],
1164 gsn_addr_to_str(&addr_from_ie),
1165 addr_from_ie.len);
1166
1167 ie_idx = gtpie_getie(p->ie, ie_type[plane_idx], 0);
1168 if (ie_idx < 0) {
1169 if (ie_mandatory) {
1170 LOGERR("Create PDP Context message invalid:"
1171 " missing IE %d\n", (int)ie_type[plane_idx]);
1172 return -1;
1173 }
1174 tei_from_ie = 0;
1175 }
1176 else
1177 tei_from_ie = ntoh32(p->ie[ie_idx]->tv4.v);
1178
1179 /* Make sure an entry for this peer address with default port
1180 * exists */
1181 struct gtphub_peer_port *peer_from_ie =
1182 gtphub_port_have(hub, &from_bind[plane_idx],
1183 &addr_from_ie,
1184 gtphub_plane_idx_default_port[plane_idx]);
1185
1186 if (tei_from_ie) {
1187 /* Create TEI mapping and replace in GTP packet IE */
1188 uint32_t mapped_tei =
1189 gtphub_tei_mapping_have(hub, plane_idx,
1190 peer_from_ie,
1191 tei_from_ie,
1192 now);
1193 p->ie[ie_idx]->tv4.v = hton32(mapped_tei);
1194 }
1195
1196 /* Replace the GSN address to reflect gtphub. */
1197 rc = gsn_addr_put(&to_bind[plane_idx].local_addr, p, plane_idx);
1198 if (rc) {
1199 LOGERR("Cannot write %s GSN Address IE\n",
1200 gtphub_plane_idx_names[plane_idx]);
1201 return -1;
1202 }
1203 }
1204
1205 return 0;
1206}
1207
1208static int gtphub_write(const struct osmo_fd *to,
1209 const struct osmo_sockaddr *to_addr,
1210 const uint8_t *buf, size_t buf_len)
1211{
1212 errno = 0;
1213 ssize_t sent = sendto(to->fd, buf, buf_len, 0,
1214 (struct sockaddr*)&to_addr->a, to_addr->l);
1215
1216 if (to_addr) {
1217 LOG("to %s\n", osmo_sockaddr_to_str(to_addr));
1218 }
1219
1220 if (sent == -1) {
1221 LOGERR("error: %s\n", strerror(errno));
1222 return -EINVAL;
1223 }
1224
1225 if (sent != buf_len)
1226 LOGERR("sent(%d) != data_len(%d)\n", (int)sent, (int)buf_len);
1227 else
1228 LOG("Sent %d\n%s\n", (int)sent, osmo_hexdump(buf, sent));
1229
1230 return 0;
1231}
1232
1233static int from_ggsns_read_cb(struct osmo_fd *from_ggsns_ofd, unsigned int what)
1234{
1235 unsigned int plane_idx = from_ggsns_ofd->priv_nr;
1236 OSMO_ASSERT(plane_idx < GTPH_PLANE_N);
1237 LOG("\n\n=== reading from GGSN (%s)\n", gtphub_plane_idx_names[plane_idx]);
1238 if (!(what & BSC_FD_READ))
1239 return 0;
1240
1241 struct gtphub *hub = from_ggsns_ofd->data;
1242
1243 static uint8_t buf[4096];
1244 struct osmo_sockaddr from_addr;
1245 struct osmo_sockaddr to_addr;
1246 struct osmo_fd *to_ofd;
1247 size_t len;
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001248 uint8_t *reply_buf;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001249
1250 len = gtphub_read(from_ggsns_ofd, &from_addr, buf, sizeof(buf));
1251 if (len < 1)
1252 return 0;
1253
1254 len = gtphub_from_ggsns_handle_buf(hub, plane_idx, &from_addr, buf, len,
1255 gtphub_now(),
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001256 &reply_buf, &to_ofd, &to_addr);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001257 if (len < 1)
1258 return 0;
1259
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001260 return gtphub_write(to_ofd, &to_addr, reply_buf, len);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001261}
1262
1263static int gtphub_unmap(struct gtphub *hub,
1264 struct gtp_packet_desc *p,
1265 struct gtphub_peer_port *from,
1266 struct gtphub_peer_port *to_proxy,
1267 struct gtphub_peer_port **final_unmapped,
1268 struct gtphub_peer_port **unmapped_from_seq,
1269 struct gtphub_peer_port **unmapped_from_tei)
1270{
1271 /* Always (try to) unmap sequence and TEI numbers, which need to be
1272 * replaced in the packet. Either way, give precedence to the proxy, if
1273 * configured. */
1274
1275 struct gtphub_peer_port *from_seq = NULL;
1276 struct gtphub_peer_port *from_tei = NULL;
1277 struct gtphub_peer_port *unmapped = NULL;
1278
1279 if (unmapped_from_seq)
1280 *unmapped_from_seq = from_seq;
1281 if (unmapped_from_tei)
1282 *unmapped_from_tei = from_tei;
1283 if (final_unmapped)
1284 *final_unmapped = unmapped;
1285
1286 from_seq = gtphub_unmap_seq(p, from);
1287
1288 if (gtphub_unmap_header_tei(&from_tei, hub, p, from) < 0)
1289 return -1;
1290
1291 struct gtphub_peer *from_peer = from->peer_addr->peer;
1292 if (from_seq && from_tei && (from_seq != from_tei)) {
1293 LOGERR("Seq unmap and TEI unmap yield two different peers. Using seq unmap."
1294 "(from %s %s: seq %d yields %s, tei %u yields %s)\n",
1295 gtphub_plane_idx_names[p->plane_idx],
1296 gtphub_peer_str(from_peer),
1297 (int)p->seq,
1298 gtphub_port_str(from_seq),
1299 (int)p->header_tei,
1300 gtphub_port_str2(from_tei)
1301 );
1302 }
1303 unmapped = (from_seq? from_seq : from_tei);
1304
1305 if (unmapped && to_proxy && (unmapped != to_proxy)) {
1306 LOGERR("Unmap yields a different peer than the configured proxy. Using proxy."
1307 " unmapped: %s proxy: %s\n",
1308 gtphub_port_str(unmapped),
1309 gtphub_port_str2(to_proxy)
1310 );
1311 }
1312 unmapped = (to_proxy? to_proxy : unmapped);
1313
1314 if (!unmapped) {
1315 /* Return no error, but returned pointers are all NULL. */
1316 return 0;
1317 }
1318
1319 LOG("from seq %p; from tei %p; unmapped => %p\n",
1320 from_seq, from_tei, unmapped);
1321
1322 if (unmapped_from_seq)
1323 *unmapped_from_seq = from_seq;
1324 if (unmapped_from_tei)
1325 *unmapped_from_tei = from_tei;
1326 if (final_unmapped)
1327 *final_unmapped = unmapped;
1328 return 0;
1329}
1330
1331static int gsn_addr_to_sockaddr(struct gsn_addr *src,
1332 uint16_t port,
1333 struct osmo_sockaddr *dst)
1334{
1335 return osmo_sockaddr_init_udp(dst, gsn_addr_to_str(src), port);
1336}
1337
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001338/* If p is an Echo request, replace p's data with the matching response and
1339 * return 1. If p is no Echo request, return 0, or -1 if an invalid packet is
1340 * detected. */
1341static int gtphub_handle_echo(struct gtphub *hub, struct gtp_packet_desc *p, uint8_t **reply_buf)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001342{
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001343 if (p->type != GTP_ECHO_REQ)
1344 return 0;
1345
1346 static uint8_t echo_response_data[14] = {
1347 0x32, /* flags */
1348 GTP_ECHO_RSP,
1349 0x00, 14 - 8, /* Length in network byte order */
1350 0x00, 0x00, 0x00, 0x00, /* Zero TEI */
1351 0, 0, /* Seq, to be replaced */
1352 0, 0, /* no extensions */
1353 0x0e, /* Recovery IE */
1354 0 /* Recovery counter, to be replaced */
1355 };
1356 uint16_t *seq = (uint16_t*)&echo_response_data[8];
1357 uint8_t *recovery = &echo_response_data[13];
1358
1359 *seq = hton16(p->seq);
1360 *recovery = hub->restart_counter;
1361
1362 *reply_buf = echo_response_data;
1363
1364 return sizeof(echo_response_data);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001365}
1366
1367/* Parse buffer as GTP packet, replace elements in-place and return the ofd and
1368 * address to forward to. Return a pointer to the osmo_fd, but copy the
1369 * sockaddr to *to_addr. The reason for this is that the sockaddr may expire at
1370 * any moment, while the osmo_fd is guaranteed to persist. Return the number of
1371 * bytes to forward, 0 or less on failure. */
1372int gtphub_from_ggsns_handle_buf(struct gtphub *hub,
1373 unsigned int plane_idx,
1374 const struct osmo_sockaddr *from_addr,
1375 uint8_t *buf,
1376 size_t received,
1377 time_t now,
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001378 uint8_t **reply_buf,
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001379 struct osmo_fd **to_ofd,
1380 struct osmo_sockaddr *to_addr)
1381{
1382 LOG("<- rx from GGSN %s\n", osmo_sockaddr_to_str(from_addr));
1383
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001384 static struct gtp_packet_desc p;
1385 gtp_decode(buf, received, plane_idx, &p);
1386
1387 if (p.rc <= 0)
1388 return -1;
1389
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001390 int reply_len;
1391 reply_len = gtphub_handle_echo(hub, &p, reply_buf);
1392 if (reply_len > 0) {
1393 /* It was an echo. Nothing left to do. */
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001394 osmo_sockaddr_copy(to_addr, from_addr);
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001395 *to_ofd = &hub->to_ggsns[plane_idx].ofd;
1396 return reply_len;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001397 }
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001398 if (reply_len < 0)
1399 return -1;
1400
1401 *to_ofd = &hub->to_sgsns[plane_idx].ofd;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001402
1403 /* If a GGSN proxy is configured, check that it's indeed that proxy
1404 * talking to us. A proxy is a forced 1:1 connection, e.g. to another
1405 * gtphub, so no-one else is allowed to talk to us from that side. */
1406 struct gtphub_peer_port *ggsn = hub->ggsn_proxy[plane_idx];
1407 if (ggsn) {
1408 if (osmo_sockaddr_cmp(&ggsn->sa, from_addr) != 0) {
1409 LOGERR("Rejecting: GGSN proxy configured, but GTP packet"
1410 " received on GGSN bind is from another sender:"
1411 " proxy: %s sender: %s\n",
1412 gtphub_port_str(ggsn),
1413 osmo_sockaddr_to_str(from_addr));
1414 return -1;
1415 }
1416 }
1417
1418 if (!ggsn) {
1419 ggsn = gtphub_port_find_sa(&hub->to_ggsns[plane_idx], from_addr);
1420 }
1421
1422 /* If any PDP context has been created, we already have an entry for
1423 * this GGSN. If we don't have an entry, the GGSN has nothing to tell
1424 * us about. */
1425 if (!ggsn) {
1426 LOGERR("Invalid GGSN peer. Dropping packet.\n");
1427 return -1;
1428 }
1429
1430 LOG("GGSN peer: %s\n", gtphub_port_str(ggsn));
1431
1432 struct gtphub_peer_port *sgsn_from_seq;
1433 struct gtphub_peer_port *sgsn;
1434 if (gtphub_unmap(hub, &p, ggsn,
1435 hub->sgsn_proxy[plane_idx],
1436 &sgsn, &sgsn_from_seq,
1437 NULL /* not interested, got it in &sgsn already */
1438 )
1439 != 0) {
1440 return -1;
1441 }
1442
1443 if (!sgsn) {
1444 /* A GGSN initiated request would go to a known TEI. So this is
1445 * bogus. */
1446 LOGERR("No SGSN to send to. Dropping packet.\n");
1447 return -1;
1448 }
1449
1450 if (plane_idx == GTPH_PLANE_CTRL) {
1451 /* This may be a Create PDP Context response. If it is, there are other
1452 * addresses in the GTP message to set up apart from the sender. */
1453 if (gtphub_handle_pdp_ctx_ies(hub, hub->to_ggsns,
1454 hub->to_sgsns, &p, now)
1455 != 0)
1456 return -1;
1457 }
1458
1459 gtphub_check_restart_counter(hub, &p, ggsn);
1460 gtphub_map_restart_counter(hub, &p, ggsn, sgsn);
1461
1462 /* If the GGSN is replying to an SGSN request, the sequence nr has
1463 * already been unmapped above (sgsn_from_seq != NULL), and we need not
1464 * create a new mapping. */
1465 if (!sgsn_from_seq)
1466 gtphub_map_seq(&p, ggsn, sgsn, now);
1467
1468 osmo_sockaddr_copy(to_addr, &sgsn->sa);
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001469
1470 *reply_buf = (uint8_t*)p.data;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001471 return received;
1472}
1473
1474static int from_sgsns_read_cb(struct osmo_fd *from_sgsns_ofd, unsigned int what)
1475{
1476 unsigned int plane_idx = from_sgsns_ofd->priv_nr;
1477 OSMO_ASSERT(plane_idx < GTPH_PLANE_N);
1478 LOG("\n\n=== reading from SGSN (%s)\n", gtphub_plane_idx_names[plane_idx]);
1479
1480 if (!(what & BSC_FD_READ))
1481 return 0;
1482
1483 struct gtphub *hub = from_sgsns_ofd->data;
1484
1485 static uint8_t buf[4096];
1486 struct osmo_sockaddr from_addr;
1487 struct osmo_sockaddr to_addr;
1488 struct osmo_fd *to_ofd;
1489 size_t len;
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001490 uint8_t *reply_buf;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001491
1492 len = gtphub_read(from_sgsns_ofd, &from_addr, buf, sizeof(buf));
1493 if (len < 1)
1494 return 0;
1495
1496 len = gtphub_from_sgsns_handle_buf(hub, plane_idx, &from_addr, buf, len,
1497 gtphub_now(),
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001498 &reply_buf, &to_ofd, &to_addr);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001499 if (len < 1)
1500 return 0;
1501
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001502 return gtphub_write(to_ofd, &to_addr, reply_buf, len);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001503}
1504
1505/* Analogous to gtphub_from_ggsns_handle_buf(), see the comment there. */
1506int gtphub_from_sgsns_handle_buf(struct gtphub *hub,
1507 unsigned int plane_idx,
1508 const struct osmo_sockaddr *from_addr,
1509 uint8_t *buf,
1510 size_t received,
1511 time_t now,
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001512 uint8_t **reply_buf,
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001513 struct osmo_fd **to_ofd,
1514 struct osmo_sockaddr *to_addr)
1515{
1516 LOG("-> rx from SGSN %s\n", osmo_sockaddr_to_str(from_addr));
1517
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001518 static struct gtp_packet_desc p;
1519 gtp_decode(buf, received, plane_idx, &p);
1520
1521 if (p.rc <= 0)
1522 return -1;
1523
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001524 int reply_len;
1525 reply_len = gtphub_handle_echo(hub, &p, reply_buf);
1526 if (reply_len > 0) {
1527 /* It was an echo. Nothing left to do. */
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001528 osmo_sockaddr_copy(to_addr, from_addr);
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001529 *to_ofd = &hub->to_ggsns[plane_idx].ofd;
1530 return reply_len;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001531 }
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001532 if (reply_len < 0)
1533 return -1;
1534
1535 *to_ofd = &hub->to_ggsns[plane_idx].ofd;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001536
1537 /* If an SGSN proxy is configured, check that it's indeed that proxy
1538 * talking to us. A proxy is a forced 1:1 connection, e.g. to another
1539 * gtphub, so no-one else is allowed to talk to us from that side. */
1540 struct gtphub_peer_port *sgsn = hub->sgsn_proxy[plane_idx];
1541 if (sgsn) {
1542 if (osmo_sockaddr_cmp(&sgsn->sa, from_addr) != 0) {
1543 LOGERR("Rejecting: GGSN proxy configured, but GTP packet"
1544 " received on GGSN bind is from another sender:"
1545 " proxy: %s sender: %s\n",
1546 gtphub_port_str(sgsn),
1547 osmo_sockaddr_to_str(from_addr));
1548 return -1;
1549 }
1550 }
1551
1552 if (!sgsn) {
1553 /* If any contact has been made before, we already have an
1554 * entry for this SGSN. */
1555 sgsn = gtphub_port_find_sa(&hub->to_sgsns[plane_idx], from_addr);
1556 }
1557
1558 if (!sgsn) {
1559 /* A new peer. If this is on the Ctrl plane, an SGSN may make
1560 * first contact without being known yet, so create the peer
1561 * struct for the current sender. */
1562 if (plane_idx != GTPH_PLANE_CTRL) {
1563 LOGERR("User plane peer was not announced by PDP Context, discarding: %s\n",
1564 osmo_sockaddr_to_str(from_addr));
1565 return -1;
1566 }
1567
1568 struct gsn_addr from_gsna;
1569 uint16_t from_port;
1570 if (gsn_addr_from_sockaddr(&from_gsna, &from_port, from_addr) != 0)
1571 return -1;
1572
1573 sgsn = gtphub_port_have(hub, &hub->to_sgsns[plane_idx],
1574 &from_gsna, from_port);
1575 }
1576
1577 if (!sgsn) {
1578 /* This could theoretically happen for invalid address data or somesuch. */
1579 LOGERR("Invalid SGSN peer. Dropping packet.\n");
1580 return -1;
1581 }
1582 LOG("SGSN peer: %s\n", gtphub_port_str(sgsn));
1583
1584 struct gtphub_peer_port *ggsn_from_seq;
1585 struct gtphub_peer_port *ggsn;
1586 if (gtphub_unmap(hub, &p, sgsn,
1587 hub->ggsn_proxy[plane_idx],
1588 &ggsn, &ggsn_from_seq,
1589 NULL /* not interested, got it in &ggsn already */
1590 )
1591 != 0) {
1592 return -1;
1593 }
1594
1595 /* See what our GGSN guess would be from the packet data per se. */
1596 /* TODO maybe not do this always? */
1597 struct gtphub_peer_port *ggsn_from_packet;
Neels Hofmeyr5b664f42015-11-10 20:32:13 +01001598 if (gtphub_resolve_ggsn(hub, &p, &ggsn_from_packet) < 0)
1599 return -1;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001600
1601 if (ggsn_from_packet && ggsn
1602 && (ggsn_from_packet != ggsn)) {
1603 LOGERR("GGSN implied from packet does not match unmapped"
1604 " GGSN, using unmapped GGSN:"
1605 " from packet: %s unmapped: %s\n",
1606 gtphub_port_str(ggsn_from_packet),
1607 gtphub_port_str2(ggsn));
1608 /* TODO return -1; ? */
1609 }
1610
1611 if (!ggsn)
1612 ggsn = ggsn_from_packet;
1613
1614 if (!ggsn) {
1615 LOGERR("No GGSN to send to. Dropping packet.\n");
1616 return -1;
1617 }
1618
1619 if (plane_idx == GTPH_PLANE_CTRL) {
1620 /* This may be a Create PDP Context requst. If it is, there are other
1621 * addresses in the GTP message to set up apart from the sender. */
1622 if (gtphub_handle_pdp_ctx_ies(hub, hub->to_sgsns,
1623 hub->to_ggsns, &p, now)
1624 != 0)
1625 return -1;
1626 }
1627
1628 gtphub_check_restart_counter(hub, &p, sgsn);
1629 gtphub_map_restart_counter(hub, &p, sgsn, ggsn);
1630
1631 /* If the SGSN is replying to a GGSN request, the sequence nr has
1632 * already been unmapped above (unmap_ggsn != NULL), and we need not
1633 * create a new outgoing sequence map. */
1634 if (!ggsn_from_seq)
1635 gtphub_map_seq(&p, sgsn, ggsn, now);
1636
1637 osmo_sockaddr_copy(to_addr, &ggsn->sa);
1638
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001639 *reply_buf = (uint8_t*)p.data;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001640 return received;
1641}
1642
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001643static void resolved_gssn_del_cb(struct expiring_item *expi)
1644{
1645 struct gtphub_resolved_ggsn *ggsn;
1646 ggsn = container_of(expi, struct gtphub_resolved_ggsn, expiry_entry);
1647
1648 gtphub_port_ref_count_dec(ggsn->peer);
1649 llist_del(&ggsn->entry);
1650
1651 ggsn->expiry_entry.del_cb = 0;
1652 expiring_item_del(&ggsn->expiry_entry);
1653
1654 talloc_free(ggsn);
1655}
1656
1657void gtphub_resolved_ggsn(struct gtphub *hub, const char *apn_oi_str,
1658 struct gsn_addr *resolved_addr,
1659 time_t now)
1660{
1661 struct gtphub_peer_port *pp;
1662 struct gtphub_resolved_ggsn *ggsn;
1663
1664 pp = gtphub_port_have(hub, &hub->to_ggsns[GTPH_PLANE_CTRL],
1665 resolved_addr, 2123);
1666 if (!pp) {
1667 LOGERR("Internal: Cannot create/find peer '%s'\n",
1668 gsn_addr_to_str(resolved_addr));
1669 return;
1670 }
1671
1672 ggsn = talloc_zero(osmo_gtphub_ctx, struct gtphub_resolved_ggsn);
1673 OSMO_ASSERT(ggsn);
1674
1675 ggsn->peer = pp;
1676 gtphub_port_ref_count_inc(pp);
1677
1678 strncpy(ggsn->apn_oi_str, apn_oi_str, sizeof(ggsn->apn_oi_str));
1679
1680 ggsn->expiry_entry.del_cb = resolved_gssn_del_cb;
1681 expiry_add(&hub->expire_tei_maps, &ggsn->expiry_entry, now);
1682
1683 llist_add(&ggsn->entry, &hub->resolved_ggsns);
1684}
1685
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001686static int gtphub_gc_peer_port(struct gtphub_peer_port *pp)
1687{
1688 return pp->ref_count == 0;
1689}
1690
1691static int gtphub_gc_peer_addr(struct gtphub_peer_addr *pa)
1692{
1693 struct gtphub_peer_port *pp, *npp;
1694 llist_for_each_entry_safe(pp, npp, &pa->ports, entry) {
1695 if (gtphub_gc_peer_port(pp)) {
1696 LOG("expired: peer %s\n",
1697 gtphub_port_str(pp));
1698 gtphub_peer_port_del(pp);
1699 }
1700 }
1701 return llist_empty(&pa->ports);
1702}
1703
1704static int gtphub_gc_peer(struct gtphub_peer *p)
1705{
1706 struct gtphub_peer_addr *pa, *npa;
1707 llist_for_each_entry_safe(pa, npa, &p->addresses, entry) {
1708 if (gtphub_gc_peer_addr(pa)) {
1709 gtphub_peer_addr_del(pa);
1710 }
1711 }
1712
1713 /* Note that there's a ref_count in each gtphub_peer_port instance
1714 * listed within p->addresses, referenced by TEI mappings from
1715 * hub->tei_map. As long as those don't expire, this peer will stay. */
1716
1717 LOG("gc peer %p llist_empty %d seq_map_empty %d\n", p,
1718 (int)llist_empty(&p->addresses), (int) nr_map_empty(&p->seq_map));
1719 if (! nr_map_empty(&p->seq_map)) {
1720 printf("not empty\n");
1721 struct nr_mapping *nrm;
1722 llist_for_each_entry(nrm, &p->seq_map.mappings, entry) {
1723 printf("%p %s %d -> %d\n",
1724 nrm->origin, gtphub_port_str(nrm->origin),nrm->orig, nrm->repl);
1725 }
1726 }
1727 return llist_empty(&p->addresses)
1728 && nr_map_empty(&p->seq_map);
1729}
1730
1731static void gtphub_gc_bind(struct gtphub_bind *b)
1732{
1733 struct gtphub_peer *p, *n;
1734 llist_for_each_entry_safe(p, n, &b->peers, entry) {
1735 if (gtphub_gc_peer(p)) {
1736 gtphub_peer_del(p);
1737 }
1738 }
1739}
1740
1741void gtphub_gc(struct gtphub *hub, time_t now)
1742{
1743 int expired;
1744 expired = expiry_tick(&hub->expire_seq_maps, now);
1745 expired += expiry_tick(&hub->expire_tei_maps, now);
1746
1747 /* ... */
1748
1749 if (expired) {
1750 int i;
1751 for (i = 0; i < GTPH_PLANE_N; i++) {
1752 gtphub_gc_bind(&hub->to_sgsns[i]);
1753 gtphub_gc_bind(&hub->to_ggsns[i]);
1754 }
1755 }
1756}
1757
1758static void gtphub_gc_cb(void *data)
1759{
1760 struct gtphub *hub = data;
1761 gtphub_gc(hub, gtphub_now());
1762 osmo_timer_schedule(&hub->gc_timer, GTPH_GC_TICK_SECONDS, 0);
1763}
1764
1765static void gtphub_gc_start(struct gtphub *hub)
1766{
1767 hub->gc_timer.cb = gtphub_gc_cb;
1768 hub->gc_timer.data = hub;
1769
1770 osmo_timer_schedule(&hub->gc_timer, GTPH_GC_TICK_SECONDS, 0);
1771}
1772
1773/* called by unit tests */
1774void gtphub_init(struct gtphub *hub)
1775{
1776 gtphub_zero(hub);
1777
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001778 INIT_LLIST_HEAD(&hub->resolved_ggsns);
1779
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001780 expiry_init(&hub->expire_seq_maps, GTPH_SEQ_MAPPING_EXPIRY_SECS);
1781 expiry_init(&hub->expire_tei_maps, GTPH_TEI_MAPPING_EXPIRY_MINUTES * 60);
1782
1783 int plane_idx;
1784 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1785 nr_pool_init(&hub->tei_pool[plane_idx]);
1786 nr_map_init(&hub->tei_map[plane_idx],
1787 &hub->tei_pool[plane_idx],
1788 &hub->expire_tei_maps);
1789
1790 gtphub_bind_init(&hub->to_ggsns[plane_idx]);
1791 gtphub_bind_init(&hub->to_sgsns[plane_idx]);
1792 }
1793}
1794
1795static int gtphub_make_proxy(struct gtphub *hub,
1796 struct gtphub_peer_port **pp,
1797 struct gtphub_bind *bind,
1798 const struct gtphub_cfg_addr *addr)
1799{
1800 if (!addr->addr_str)
1801 return 0;
1802
1803 struct gsn_addr gsna;
1804 if (gsn_addr_from_str(&gsna, addr->addr_str) != 0)
1805 return -1;
1806
1807 *pp = gtphub_port_have(hub, bind, &gsna, addr->port);
1808
1809 /* This is *the* proxy. Make sure it is never expired. */
1810 gtphub_port_ref_count_inc(*pp);
1811 return 0;
1812}
1813
1814int gtphub_start(struct gtphub *hub, struct gtphub_cfg *cfg)
1815{
1816 int rc;
1817
1818 gtphub_init(hub);
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001819 gtphub_ares_init(hub);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001820
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001821 /* TODO set hub->restart_counter from external file. */
1822
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001823 int plane_idx;
1824 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1825 rc = gtphub_bind_start(&hub->to_ggsns[plane_idx],
1826 &cfg->to_ggsns[plane_idx],
1827 from_ggsns_read_cb, hub, plane_idx);
1828 if (rc) {
1829 LOGERR("Failed to bind for GGSNs (%s)\n",
1830 gtphub_plane_idx_names[plane_idx]);
1831 return rc;
1832 }
1833
1834 rc = gtphub_bind_start(&hub->to_sgsns[plane_idx],
1835 &cfg->to_sgsns[plane_idx],
1836 from_sgsns_read_cb, hub, plane_idx);
1837 if (rc) {
1838 LOGERR("Failed to bind for SGSNs (%s)\n",
1839 gtphub_plane_idx_names[plane_idx]);
1840 return rc;
1841 }
1842 }
1843
1844
1845 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1846 if (gtphub_make_proxy(hub,
1847 &hub->sgsn_proxy[plane_idx],
1848 &hub->to_sgsns[plane_idx],
1849 &cfg->sgsn_proxy[plane_idx])
1850 != 0) {
1851 LOGERR("Cannot configure SGSN proxy %s port %d.\n",
1852 cfg->sgsn_proxy[plane_idx].addr_str,
1853 (int)cfg->sgsn_proxy[plane_idx].port);
1854 return -1;
1855 }
1856 if (gtphub_make_proxy(hub,
1857 &hub->ggsn_proxy[plane_idx],
1858 &hub->to_ggsns[plane_idx],
1859 &cfg->ggsn_proxy[plane_idx])
1860 != 0) {
1861 LOGERR("Cannot configure GGSN proxy.\n");
1862 return -1;
1863 }
1864 }
1865
1866 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1867 if (hub->sgsn_proxy[plane_idx])
1868 LOG("Using SGSN %s proxy %s\n",
1869 gtphub_plane_idx_names[plane_idx],
1870 gtphub_port_str(hub->sgsn_proxy[plane_idx]));
1871 }
1872
1873 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1874 if (hub->sgsn_proxy[plane_idx])
1875 LOG("Using GGSN %s proxy %s\n",
1876 gtphub_plane_idx_names[plane_idx],
1877 gtphub_port_str(hub->ggsn_proxy[plane_idx]));
1878 }
1879
1880 gtphub_gc_start(hub);
1881 return 0;
1882}
1883
1884static struct gtphub_peer_addr *gtphub_peer_find_addr(const struct gtphub_peer *peer,
1885 const struct gsn_addr *addr)
1886{
1887 struct gtphub_peer_addr *a;
1888 llist_for_each_entry(a, &peer->addresses, entry) {
1889 if (gsn_addr_same(&a->addr, addr))
1890 return a;
1891 }
1892 return NULL;
1893}
1894
1895static struct gtphub_peer_port *gtphub_addr_find_port(const struct gtphub_peer_addr *a,
1896 uint16_t port)
1897{
1898 OSMO_ASSERT(port);
1899 struct gtphub_peer_port *pp;
1900 llist_for_each_entry(pp, &a->ports, entry) {
1901 if (pp->port == port)
1902 return pp;
1903 }
1904 return NULL;
1905}
1906
1907static struct gtphub_peer_addr *gtphub_addr_find(const struct gtphub_bind *bind,
1908 const struct gsn_addr *addr)
1909{
1910 struct gtphub_peer *peer;
1911 llist_for_each_entry(peer, &bind->peers, entry) {
1912 struct gtphub_peer_addr *a = gtphub_peer_find_addr(peer, addr);
1913 if (a)
1914 return a;
1915 }
1916 return NULL;
1917}
1918
1919static struct gtphub_peer_port *gtphub_port_find(const struct gtphub_bind *bind,
1920 const struct gsn_addr *addr,
1921 uint16_t port)
1922{
1923 struct gtphub_peer_addr *a = gtphub_addr_find(bind, addr);
1924 if (!a)
1925 return NULL;
1926 return gtphub_addr_find_port(a, port);
1927}
1928
1929struct gtphub_peer_port *gtphub_port_find_sa(const struct gtphub_bind *bind,
1930 const struct osmo_sockaddr *addr)
1931{
1932 struct gsn_addr gsna;
1933 uint16_t port;
1934 gsn_addr_from_sockaddr(&gsna, &port, addr);
1935 return gtphub_port_find(bind, &gsna, port);
1936}
1937
1938static struct gtphub_peer *gtphub_peer_new(struct gtphub *hub,
1939 struct gtphub_bind *bind)
1940{
1941 struct gtphub_peer *peer = talloc_zero(osmo_gtphub_ctx, struct gtphub_peer);
1942 OSMO_ASSERT(peer);
1943
1944 INIT_LLIST_HEAD(&peer->addresses);
1945
1946 nr_pool_init(&peer->seq_pool);
1947 nr_map_init(&peer->seq_map, &peer->seq_pool, &hub->expire_seq_maps);
1948
1949 /* TODO use something random to pick the initial sequence nr.
1950 0x6d31 produces the ASCII character sequence 'm1', currently used in
1951 gtphub_nc_test.sh. */
1952 peer->seq_pool.last_nr = 0x6d31 - 1;
1953
1954 llist_add(&peer->entry, &bind->peers);
1955 return peer;
1956}
1957
1958static struct gtphub_peer_addr *gtphub_peer_add_addr(struct gtphub_peer *peer,
1959 const struct gsn_addr *addr)
1960{
1961 struct gtphub_peer_addr *a;
1962 a = talloc_zero(osmo_gtphub_ctx, struct gtphub_peer_addr);
1963 OSMO_ASSERT(a);
1964 a->peer = peer;
1965 gsn_addr_copy(&a->addr, addr);
1966 INIT_LLIST_HEAD(&a->ports);
1967 llist_add(&a->entry, &peer->addresses);
1968
1969 return a;
1970}
1971
1972static struct gtphub_peer_addr *gtphub_addr_have(struct gtphub *hub,
1973 struct gtphub_bind *bind,
1974 const struct gsn_addr *addr)
1975{
1976 struct gtphub_peer_addr *a = gtphub_addr_find(bind, addr);
1977 if (a)
1978 return a;
1979
1980 /* If we haven't found an address, that means we need to create an
1981 * entirely new peer for the new address. More addresses may be added
1982 * to this peer later, but not via this function. */
1983 struct gtphub_peer *peer = gtphub_peer_new(hub, bind);
1984 return gtphub_peer_add_addr(peer, addr);
1985}
1986
1987static struct gtphub_peer_port *gtphub_addr_add_port(struct gtphub_peer_addr *a,
1988 uint16_t port)
1989{
1990 struct gtphub_peer_port *pp;
1991
1992 pp = talloc_zero(osmo_gtphub_ctx, struct gtphub_peer_port);
1993 OSMO_ASSERT(pp);
1994 pp->peer_addr = a;
1995 pp->port = port;
1996
1997 if (gsn_addr_to_sockaddr(&a->addr, port, &pp->sa) != 0) {
1998 talloc_free(pp);
1999 return NULL;
2000 }
2001
2002 llist_add(&pp->entry, &a->ports);
2003
2004 LOG("New peer: %s port %d\n",
2005 gsn_addr_to_str(&a->addr),
2006 (int)port);
2007
2008 return pp;
2009}
2010
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01002011struct gtphub_peer_port *gtphub_port_have(struct gtphub *hub,
2012 struct gtphub_bind *bind,
2013 const struct gsn_addr *addr,
2014 uint16_t port)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02002015{
2016 struct gtphub_peer_addr *a = gtphub_addr_have(hub, bind, addr);
2017
2018 struct gtphub_peer_port *pp = gtphub_addr_find_port(a, port);
2019 if (pp)
2020 return pp;
2021
2022 return gtphub_addr_add_port(a, port);
2023}
2024
Neels Hofmeyr5b664f42015-11-10 20:32:13 +01002025/* Return 0 if the message in p is not applicable for GGSN resolution, -1 if
2026 * resolution should be possible but failed, and 1 if resolution was
2027 * successful. *pp will be set to NULL if <1 is returned. */
2028static int gtphub_resolve_ggsn(struct gtphub *hub,
2029 struct gtp_packet_desc *p,
2030 struct gtphub_peer_port **pp)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02002031{
Neels Hofmeyr5b664f42015-11-10 20:32:13 +01002032 *pp = NULL;
2033
2034 /* TODO determine from message type whether IEs should be present? */
2035
2036 int rc;
2037 const char *imsi_str;
2038 rc = get_ie_imsi_str(p->ie, 0, &imsi_str);
2039 if (rc < 1)
2040 return rc;
2041 OSMO_ASSERT(imsi_str);
2042
2043 const char *apn_str;
2044 rc = get_ie_apn_str(p->ie, &apn_str);
2045 if (rc < 1)
2046 return rc;
2047 OSMO_ASSERT(apn_str);
2048
2049 *pp = gtphub_resolve_ggsn_addr(hub, imsi_str, apn_str);
2050 return (*pp)? 1 : -1;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02002051}
2052
2053
2054/* TODO move to osmocom/core/socket.c ? */
2055/* The caller is required to call freeaddrinfo(*result), iff zero is returned. */
2056/* use this in osmo_sock_init() to remove dup. */
2057static int _osmo_getaddrinfo(struct addrinfo **result,
2058 uint16_t family, uint16_t type, uint8_t proto,
2059 const char *host, uint16_t port)
2060{
2061 struct addrinfo hints;
2062 char portbuf[16];
2063
2064 sprintf(portbuf, "%u", port);
2065 memset(&hints, '\0', sizeof(struct addrinfo));
2066 hints.ai_family = family;
2067 if (type == SOCK_RAW) {
2068 /* Workaround for glibc, that returns EAI_SERVICE (-8) if
2069 * SOCK_RAW and IPPROTO_GRE is used.
2070 */
2071 hints.ai_socktype = SOCK_DGRAM;
2072 hints.ai_protocol = IPPROTO_UDP;
2073 } else {
2074 hints.ai_socktype = type;
2075 hints.ai_protocol = proto;
2076 }
2077
2078 return getaddrinfo(host, portbuf, &hints, result);
2079}
2080
2081/* TODO move to osmocom/core/socket.c ? */
2082int osmo_sockaddr_init(struct osmo_sockaddr *addr,
2083 uint16_t family, uint16_t type, uint8_t proto,
2084 const char *host, uint16_t port)
2085{
2086 struct addrinfo *res;
2087 int rc;
2088 rc = _osmo_getaddrinfo(&res, family, type, proto, host, port);
2089
2090 if (rc != 0) {
2091 LOGERR("getaddrinfo returned error %d\n", (int)rc);
2092 return -EINVAL;
2093 }
2094
2095 OSMO_ASSERT(res->ai_addrlen <= sizeof(addr->a));
2096 memcpy(&addr->a, res->ai_addr, res->ai_addrlen);
2097 addr->l = res->ai_addrlen;
2098 freeaddrinfo(res);
2099
2100 return 0;
2101}
2102
2103int osmo_sockaddr_to_strs(char *addr_str, size_t addr_str_len,
2104 char *port_str, size_t port_str_len,
2105 const struct osmo_sockaddr *addr,
2106 int flags)
2107{
2108 int rc;
2109
2110 if ((addr->l < 1) || (addr->l > sizeof(addr->a))) {
2111 LOGP(DGTPHUB, LOGL_ERROR, "Invalid address size: %d\n", addr->l);
2112 return -1;
2113 }
2114
2115 if (addr->l > sizeof(addr->a)) {
2116 LOGP(DGTPHUB, LOGL_ERROR, "Invalid address: too long: %d\n", addr->l);
2117 return -1;
2118 }
2119
2120 rc = getnameinfo((struct sockaddr*)&addr->a, addr->l,
2121 addr_str, addr_str_len,
2122 port_str, port_str_len,
2123 flags);
2124
2125 if (rc)
2126 LOGP(DGTPHUB, LOGL_ERROR, "Invalid address: %s: %s\n", gai_strerror(rc),
2127 osmo_hexdump((uint8_t*)&addr->a, addr->l));
2128
2129 return rc;
2130}
2131
2132const char *osmo_sockaddr_to_strb(const struct osmo_sockaddr *addr,
2133 char *buf, size_t buf_len)
2134{
2135 const int portbuf_len = 6;
2136 OSMO_ASSERT(buf_len > portbuf_len);
2137 char *portbuf = buf + buf_len - portbuf_len;
2138 buf_len -= portbuf_len;
2139 if (osmo_sockaddr_to_strs(buf, buf_len,
2140 portbuf, portbuf_len,
2141 addr,
2142 NI_NUMERICHOST | NI_NUMERICSERV))
2143 return NULL;
2144
2145 char *pos = buf + strnlen(buf, buf_len-1);
2146 size_t len = buf_len - (pos - buf);
2147
2148 snprintf(pos, len, " port %s", portbuf);
2149 buf[buf_len-1] = '\0';
2150
2151 return buf;
2152}
2153
2154const char *osmo_sockaddr_to_str(const struct osmo_sockaddr *addr)
2155{
2156 static char buf[256];
2157 const char *result = osmo_sockaddr_to_strb(addr, buf, sizeof(buf));
2158 if (! result)
2159 return "(invalid)";
2160 return result;
2161}
2162
2163int osmo_sockaddr_cmp(const struct osmo_sockaddr *a, const struct osmo_sockaddr *b)
2164{
2165 if (a == b)
2166 return 0;
2167 if (!a)
2168 return -1;
2169 if (!b)
2170 return 1;
2171 if (a->l != b->l) {
2172 /* Lengths are not the same, but determine the order. Will
2173 * anyone ever sort a list by osmo_sockaddr though...? */
2174 int cmp = memcmp(&a->a, &b->a, (a->l < b->l)? a->l : b->l);
2175 if (cmp == 0) {
2176 if (a->l < b->l)
2177 return -1;
2178 else
2179 return 1;
2180 }
2181 return cmp;
2182 }
2183 return memcmp(&a->a, &b->a, a->l);
2184}
2185
2186void osmo_sockaddr_copy(struct osmo_sockaddr *dst, const struct osmo_sockaddr *src)
2187{
2188 OSMO_ASSERT(src->l <= sizeof(dst->a));
2189 memcpy(&dst->a, &src->a, src->l);
2190 dst->l = src->l;
2191}