blob: 389a0cac6ccf29220a287490d8703fb0b25298c1 [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. */
371static const char *imsi_to_str(uint8_t *imsi)
372{
373 static char str[17];
374 int i;
375
376 for (i = 0; i < 8; i++) {
377 str[2*i] = imsi_digit_to_char(imsi[i]);
378 str[2*i + 1] = imsi_digit_to_char(imsi[i] >> 4);
379 }
380 str[16] = '\0';
381 return str;
382}
383
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100384static const char *get_ie_imsi_str(union gtpie_member *ie[], int i)
385{
386 uint8_t imsi_buf[8];
387 if (!get_ie_imsi(ie, i, imsi_buf))
388 return NULL;
389 return imsi_to_str(imsi_buf);
390}
391
392static const char *get_ie_apn_str(union gtpie_member *ie[])
393{
394 static char apn_buf[GSM_APN_LENGTH];
395 unsigned int len;
396 if (gtpie_gettlv(ie, GTPIE_APN, 0,
397 &len, apn_buf, sizeof(apn_buf)) != 0)
398 return NULL;
399
400 if (!len)
401 return NULL;
402
403 if (len > (sizeof(apn_buf) - 1))
404 len = sizeof(apn_buf) - 1;
405 apn_buf[len] = '\0';
406
407 return gprs_apn_to_str(apn_buf, (uint8_t*)apn_buf, len);
408}
409
410
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200411/* Validate header, and index information elements. Write decoded packet
412 * information to *res. res->data will point at the given data buffer. On
413 * error, p->rc is set <= 0 (see enum gtp_rc). */
414static void gtp_decode(const uint8_t *data, int data_len,
415 unsigned int from_plane_idx,
416 struct gtp_packet_desc *res)
417{
418 ZERO_STRUCT(res);
419 res->data = (union gtp_packet*)data;
420 res->data_len = data_len;
421 res->plane_idx = from_plane_idx;
422
423 validate_gtp_header(res);
424
425 if (res->rc <= 0) {
426 LOGERR("INVALID: dropping GTP packet.\n");
427 return;
428 }
429
430 LOG("Valid GTP header (v%d)\n", res->version);
431
432 if (res->rc != GTP_RC_PDU) {
433 LOG("no IEs in this GTP packet\n");
434 return;
435 }
436
437 if (gtpie_decaps(res->ie, res->version,
438 (void*)(data + res->header_len),
439 res->data_len - res->header_len) != 0) {
440 res->rc = GTP_RC_INVALID_IE;
441 return;
442 }
443
444#if GTPHUB_DEBUG
445 int i;
446
447 for (i = 0; i < 10; i++) {
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100448 const char *imsi = get_ie_imsi_str(res->ie, i);
449 if (!imsi)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200450 break;
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100451 LOG("| IMSI %s\n", imsi);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200452 }
453
454 for (i = 0; i < 10; i++) {
455 uint8_t nsapi;
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100456 if (!get_ie_nsapi(res->ie, i, &nsapi))
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200457 break;
458 LOG("| NSAPI %d\n", (int)nsapi);
459 }
460
461 for (i = 0; i < 2; i++) {
462 struct gsn_addr addr;
463 if (gsn_addr_get(&addr, res, i) == 0)
464 LOG("| addr %s\n", gsn_addr_to_str(&addr));
465 }
466
467 for (i = 0; i < 10; i++) {
468 uint32_t tei;
469 if (gtpie_gettv4(res->ie, GTPIE_TEI_DI, i, &tei) != 0)
470 break;
471 LOG("| TEI DI (USER) %" PRIu32 " 0x%08" PRIx32 "\n",
472 tei, tei);
473 }
474
475 for (i = 0; i < 10; i++) {
476 uint32_t tei;
477 if (gtpie_gettv4(res->ie, GTPIE_TEI_C, i, &tei) != 0)
478 break;
479 LOG("| TEI (CTRL) %" PRIu32 " 0x%08" PRIx32 "\n",
480 tei, tei);
481 }
482#endif
483}
484
485
486/* expiry */
487
488void expiry_init(struct expiry *exq, int expiry_in_seconds)
489{
490 ZERO_STRUCT(exq);
491 exq->expiry_in_seconds = expiry_in_seconds;
492 INIT_LLIST_HEAD(&exq->items);
493}
494
495void expiry_add(struct expiry *exq, struct expiring_item *item, time_t now)
496{
497 item->expiry = now + exq->expiry_in_seconds;
498
499 /* Add/move to the tail to always sort by expiry, ascending. */
500 llist_del(&item->entry);
501 llist_add_tail(&item->entry, &exq->items);
502}
503
504int expiry_tick(struct expiry *exq, time_t now)
505{
506 int expired = 0;
507 struct expiring_item *m, *n;
508 llist_for_each_entry_safe(m, n, &exq->items, entry) {
509 if (m->expiry <= now) {
510 expiring_item_del(m);
511 expired ++;
512 } else {
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200513 /* The items are added sorted by expiry. So when we hit
514 * an unexpired entry, only more unexpired ones will
515 * follow. */
516 break;
517 }
518 }
519 return expired;
520}
521
522void expiring_item_init(struct expiring_item *item)
523{
524 ZERO_STRUCT(item);
525 INIT_LLIST_HEAD(&item->entry);
526}
527
528void expiring_item_del(struct expiring_item *item)
529{
530 OSMO_ASSERT(item);
531 llist_del(&item->entry);
532 INIT_LLIST_HEAD(&item->entry);
533 if (item->del_cb) {
534 /* avoid loops */
535 del_cb_t del_cb = item->del_cb;
536 item->del_cb = 0;
537 (del_cb)(item);
538 }
539}
540
541
542/* nr_map, nr_pool */
543
544void nr_pool_init(struct nr_pool *pool)
545{
546 *pool = (struct nr_pool){};
547}
548
549nr_t nr_pool_next(struct nr_pool *pool)
550{
551 pool->last_nr ++;
552
553 OSMO_ASSERT(pool->last_nr > 0);
554 /* TODO: gracefully handle running out of TEIs. */
555 /* TODO: random TEIs. */
556
557 return pool->last_nr;
558}
559
560void nr_map_init(struct nr_map *map, struct nr_pool *pool,
561 struct expiry *exq)
562{
563 ZERO_STRUCT(map);
564 map->pool = pool;
565 map->add_items_to_expiry = exq;
566 INIT_LLIST_HEAD(&map->mappings);
567}
568
569void nr_mapping_init(struct nr_mapping *m)
570{
571 ZERO_STRUCT(m);
572 INIT_LLIST_HEAD(&m->entry);
573 expiring_item_init(&m->expiry_entry);
574}
575
576void nr_map_add(struct nr_map *map, struct nr_mapping *mapping, time_t now)
577{
578 /* Generate a mapped number */
579 mapping->repl = nr_pool_next(map->pool);
580
581 /* Add to the tail to always yield a list sorted by expiry, in
582 * ascending order. */
583 llist_add_tail(&mapping->entry, &map->mappings);
584 if (map->add_items_to_expiry)
585 expiry_add(map->add_items_to_expiry,
586 &mapping->expiry_entry,
587 now);
588}
589
590void nr_map_clear(struct nr_map *map)
591{
592 struct nr_mapping *m;
593 struct nr_mapping *n;
594 llist_for_each_entry_safe(m, n, &map->mappings, entry) {
595 nr_mapping_del(m);
596 }
597}
598
599int nr_map_empty(const struct nr_map *map)
600{
601 return llist_empty(&map->mappings);
602}
603
604struct nr_mapping *nr_map_get(const struct nr_map *map,
605 void *origin, nr_t nr_orig)
606{
607 struct nr_mapping *mapping;
608 llist_for_each_entry(mapping, &map->mappings, entry) {
609 if ((mapping->origin == origin)
610 && (mapping->orig == nr_orig))
611 return mapping;
612 }
613 /* Not found. */
614 return NULL;
615}
616
617struct nr_mapping *nr_map_get_inv(const struct nr_map *map, nr_t nr_repl)
618{
619 struct nr_mapping *mapping;
620 llist_for_each_entry(mapping, &map->mappings, entry) {
621 if (mapping->repl == nr_repl) {
622 return mapping;
623 }
624 }
625 /* Not found. */
626 return NULL;
627}
628
629void nr_mapping_del(struct nr_mapping *mapping)
630{
631 OSMO_ASSERT(mapping);
632 llist_del(&mapping->entry);
633 INIT_LLIST_HEAD(&mapping->entry);
634 expiring_item_del(&mapping->expiry_entry);
635}
636
637
638/* gtphub */
639
640const char* const gtphub_plane_idx_names[GTPH_PLANE_N] = {
641 "CTRL",
642 "USER",
643};
644
645const uint16_t gtphub_plane_idx_default_port[GTPH_PLANE_N] = {
646 2123,
647 2152,
648};
649
650time_t gtphub_now(void)
651{
652 struct timespec now_tp;
653 OSMO_ASSERT(clock_gettime(CLOCK_MONOTONIC, &now_tp) >= 0);
654 return now_tp.tv_sec;
655}
656
657/* Remove a gtphub_peer from its list and free it. */
658static void gtphub_peer_del(struct gtphub_peer *peer)
659{
660 nr_map_clear(&peer->seq_map);
661 llist_del(&peer->entry);
662 talloc_free(peer);
663}
664
665static void gtphub_peer_addr_del(struct gtphub_peer_addr *pa)
666{
667 OSMO_ASSERT(llist_empty(&pa->ports));
668 llist_del(&pa->entry);
669 talloc_free(pa);
670}
671
672static void gtphub_peer_port_del(struct gtphub_peer_port *pp)
673{
674 OSMO_ASSERT(pp->ref_count == 0);
675 llist_del(&pp->entry);
676 talloc_free(pp);
677}
678
679/* From the information in the gtp_packet_desc, return the address of a GGSN.
680 * Return -1 on error. */
681static struct gtphub_peer_port *gtphub_resolve_ggsn(struct gtphub *hub,
682 struct gtp_packet_desc *p);
683
684/* See gtphub_ext.c (wrapped by unit test) */
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100685struct gtphub_peer_port *gtphub_resolve_ggsn_addr(struct gtphub *hub,
686 const char *imsi_str,
687 const char *apn_ni_str);
688int gtphub_ares_init(struct gtphub *hub);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200689
690static struct gtphub_peer_port *gtphub_port_find(const struct gtphub_bind *bind,
691 const struct gsn_addr *addr,
692 uint16_t port);
693
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200694static void gtphub_zero(struct gtphub *hub)
695{
696 ZERO_STRUCT(hub);
697}
698
699static int gtphub_sock_init(struct osmo_fd *ofd,
700 const struct gtphub_cfg_addr *addr,
701 osmo_fd_cb_t cb,
702 void *data,
703 int ofd_id)
704{
705 if (!addr->addr_str) {
706 LOGERR("Cannot bind: empty address.\n");
707 return -1;
708 }
709 if (!addr->port) {
710 LOGERR("Cannot bind: zero port not permitted.\n");
711 return -1;
712 }
713
714 ofd->when = BSC_FD_READ;
715 ofd->cb = cb;
716 ofd->data = data;
717 ofd->priv_nr = ofd_id;
718
719 int rc;
720 rc = osmo_sock_init_ofd(ofd,
721 AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP,
722 addr->addr_str, addr->port,
723 OSMO_SOCK_F_BIND);
724 if (rc < 1) {
725 LOGERR("Cannot bind to %s port %d (rc %d)\n",
726 addr->addr_str, (int)addr->port, rc);
727 return -1;
728 }
729
730 return 0;
731}
732
733static void gtphub_bind_init(struct gtphub_bind *b)
734{
735 ZERO_STRUCT(b);
736
737 INIT_LLIST_HEAD(&b->peers);
738}
739
740static int gtphub_bind_start(struct gtphub_bind *b,
741 const struct gtphub_cfg_bind *cfg,
742 osmo_fd_cb_t cb, void *cb_data,
743 unsigned int ofd_id)
744{
745 if (gsn_addr_from_str(&b->local_addr, cfg->bind.addr_str) != 0)
746 return -1;
747 if (gtphub_sock_init(&b->ofd, &cfg->bind, cb, cb_data, ofd_id) != 0)
748 return -1;
749 return 0;
750}
751
752/* Recv datagram from from->fd, optionally write sender's address to *from_addr.
753 * Return the number of bytes read, zero on error. */
754static int gtphub_read(const struct osmo_fd *from,
755 struct osmo_sockaddr *from_addr,
756 uint8_t *buf, size_t buf_len)
757{
758 /* recvfrom requires the available length to be set in *from_addr_len. */
759 if (from_addr)
760 from_addr->l = sizeof(from_addr->a);
761
762 errno = 0;
763 ssize_t received = recvfrom(from->fd, buf, buf_len, 0,
764 (struct sockaddr*)&from_addr->a, &from_addr->l);
765 /* TODO use recvmsg and get a MSG_TRUNC flag to make sure the message
766 * is not truncated. Then maybe reduce buf's size. */
767
768 if (received <= 0) {
769 if (errno != EAGAIN)
770 LOGERR("error: %s\n", strerror(errno));
771 return 0;
772 }
773
774 if (from_addr) {
775 LOG("from %s\n", osmo_sockaddr_to_str(from_addr));
776 }
777
778 if (received <= 0) {
779 LOGERR("error: %s\n", strerror(errno));
780 return 0;
781 }
782
783 LOG("Received %d\n%s\n", (int)received, osmo_hexdump(buf, received));
784 return received;
785}
786
787inline void gtphub_port_ref_count_inc(struct gtphub_peer_port *pp)
788{
789 OSMO_ASSERT(pp->ref_count < UINT_MAX);
790 pp->ref_count++;
791}
792
793inline void gtphub_port_ref_count_dec(struct gtphub_peer_port *pp)
794{
795 OSMO_ASSERT(pp->ref_count > 0);
796 pp->ref_count--;
797}
798
799inline void set_seq(struct gtp_packet_desc *p, uint16_t seq)
800{
801 OSMO_ASSERT(p->version == 1);
802 p->data->gtp1l.h.seq = hton16(seq);
803 p->seq = seq;
804}
805
806inline void set_tei(struct gtp_packet_desc *p, uint32_t tei)
807{
808 OSMO_ASSERT(p->version == 1);
809 p->data->gtp1l.h.tei = hton32(tei);
810 p->header_tei = tei;
811}
812
813static void gtphub_mapping_del_cb(struct expiring_item *expi);
814
815static struct nr_mapping *gtphub_mapping_new()
816{
817 struct nr_mapping *nrm;
818 nrm = talloc_zero(osmo_gtphub_ctx, struct nr_mapping);
819 OSMO_ASSERT(nrm);
820
821 nr_mapping_init(nrm);
822 nrm->expiry_entry.del_cb = gtphub_mapping_del_cb;
823 return nrm;
824}
825
826static const char *gtphub_peer_strb(struct gtphub_peer *peer, char *buf, int buflen)
827{
828 if (llist_empty(&peer->addresses))
829 return "(addressless)";
830
831 struct gtphub_peer_addr *a = llist_first(&peer->addresses,
832 struct gtphub_peer_addr,
833 entry);
834 return gsn_addr_to_strb(&a->addr, buf, buflen);
835}
836
837static const char *gtphub_port_strb(struct gtphub_peer_port *port, char *buf, int buflen)
838{
839 if (!port)
840 return "(null port)";
841
842 snprintf(buf, buflen, "%s port %d",
843 gsn_addr_to_str(&port->peer_addr->addr),
844 (int)port->port);
845 return buf;
846}
847
848const char *gtphub_peer_str(struct gtphub_peer *peer)
849{
850 static char buf[256];
851 return gtphub_peer_strb(peer, buf, sizeof(buf));
852}
853
854const char *gtphub_peer_str2(struct gtphub_peer *peer)
855{
856 static char buf[256];
857 return gtphub_peer_strb(peer, buf, sizeof(buf));
858}
859
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +0100860const char *gtphub_port_str(struct gtphub_peer_port *port)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +0200861{
862 static char buf[256];
863 return gtphub_port_strb(port, buf, sizeof(buf));
864}
865
866static const char *gtphub_port_str2(struct gtphub_peer_port *port)
867{
868 static char buf[256];
869 return gtphub_port_strb(port, buf, sizeof(buf));
870}
871
872static void gtphub_mapping_del_cb(struct expiring_item *expi)
873{
874 expi->del_cb = 0; /* avoid recursion loops */
875
876 struct nr_mapping *nrm = container_of(expi,
877 struct nr_mapping,
878 expiry_entry);
879 llist_del(&nrm->entry);
880 INIT_LLIST_HEAD(&nrm->entry); /* mark unused */
881
882 /* Just for log */
883 struct gtphub_peer_port *from = nrm->origin;
884 OSMO_ASSERT(from);
885 LOG("expired: %d: nr mapping from %s: %d->%d\n",
886 (int)nrm->expiry_entry.expiry,
887 gtphub_port_str(from),
888 (int)nrm->orig, (int)nrm->repl);
889
890 gtphub_port_ref_count_dec(from);
891
892 talloc_free(nrm);
893}
894
895static struct nr_mapping *gtphub_mapping_have(struct nr_map *map,
896 struct gtphub_peer_port *from,
897 nr_t orig_nr,
898 time_t now)
899{
900 struct nr_mapping *nrm;
901
902 nrm = nr_map_get(map, from, orig_nr);
903
904 if (!nrm) {
905 nrm = gtphub_mapping_new();
906 nrm->orig = orig_nr;
907 nrm->origin = from;
908 nr_map_add(map, nrm, now);
909 gtphub_port_ref_count_inc(from);
910 LOG("peer %s: MAP %d --> %d\n",
911 gtphub_port_str(from),
912 (int)(nrm->orig), (int)(nrm->repl));
913 } else {
914 /* restart expiry timeout */
915 expiry_add(map->add_items_to_expiry, &nrm->expiry_entry,
916 now);
917 }
918
919 OSMO_ASSERT(nrm);
920 return nrm;
921}
922
923static uint32_t gtphub_tei_mapping_have(struct gtphub *hub,
924 int plane_idx,
925 struct gtphub_peer_port *from,
926 uint32_t orig_tei,
927 time_t now)
928{
929 struct nr_mapping *nrm = gtphub_mapping_have(&hub->tei_map[plane_idx],
930 from, orig_tei, now);
931 LOG("New %s TEI: (from %s, TEI %d) <-- TEI %d\n",
932 gtphub_plane_idx_names[plane_idx],
933 gtphub_port_str(from),
934 (int)orig_tei, (int)nrm->repl);
935
936 return (uint32_t)nrm->repl;
937}
938
939static int gtphub_map_seq(struct gtp_packet_desc *p,
940 struct gtphub_peer_port *from_port,
941 struct gtphub_peer_port *to_port,
942 time_t now)
943{
944 /* Store a mapping in to_peer's map, so when we later receive a GTP
945 * packet back from to_peer, the seq nr can be unmapped back to its
946 * origin (from_peer here). */
947 struct nr_mapping *nrm;
948 nrm = gtphub_mapping_have(&to_port->peer_addr->peer->seq_map,
949 from_port, p->seq, now);
950
951 /* Change the GTP packet to yield the new, mapped seq nr */
952 set_seq(p, nrm->repl);
953
954 return 0;
955}
956
957static struct gtphub_peer_port *gtphub_unmap_seq(struct gtp_packet_desc *p,
958 struct gtphub_peer_port *responding_port)
959{
960 OSMO_ASSERT(p->version == 1);
961 struct nr_mapping *nrm = nr_map_get_inv(&responding_port->peer_addr->peer->seq_map,
962 p->seq);
963 if (!nrm)
964 return NULL;
965 LOG("peer %p: UNMAP %d <-- %d\n", nrm->origin, (int)(nrm->orig), (int)(nrm->repl));
966 set_seq(p, nrm->orig);
967 return nrm->origin;
968}
969
970static void gtphub_check_restart_counter(struct gtphub *hub,
971 struct gtp_packet_desc *p,
972 struct gtphub_peer_port *from)
973{
974 /* TODO */
975 /* If the peer is sending a Recovery IE (7.7.11) with a restart counter
976 * that doesn't match the peer's previously sent restart counter, clear
977 * that peer and cancel PDP contexts. */
978}
979
980static void gtphub_map_restart_counter(struct gtphub *hub,
981 struct gtp_packet_desc *p,
982 struct gtphub_peer_port *from,
983 struct gtphub_peer_port *to)
984{
985 /* TODO */
986}
987
988/* gtphub_map_ie_teis() and gtphub_unmap_header_tei():
989 *
990 * TEI mapping must happen symmetrically. An SGSN contacts gtphub instead of N
991 * GGSNs, and a GGSN replies to gtphub for N SGSNs. From either end, TEIs may
992 * collide: two GGSNs picking the same TEIs, or two SGSNs picking the same
993 * TEIs. Since the opposite side sees the sender address being gtphub's
994 * address, TEIs among the SGSNs, and among the GGSNs, must not overlap. If a
995 * peer sends a TEI already sent before from a peer of the same side, gtphub
996 * replaces it with a TEI not yet seen from that side and remembers the
997 * mapping.
998 *
999 * Consider two SGSNs A and B contacting two GGSNs C and D thru gtphub.
1000 *
1001 * A: Create PDP Ctx, I have TEI 1.
1002 * ---> gtphub: A has TEI 1, sending 1 for C.
1003 * ---> C: gtphub has TEI 1.
1004 * <--- C: Response to TEI 1: I have TEI 11.
1005 * <--- gtphub: ok, telling A: 11.
1006 * A: gtphub's first TEI is 11. (1)
1007 *
1008 * B: Create PDP Ctx, I have TEIs 1.
1009 * ---> gtphub: 1 already taken for C, sending 2 for B. (map)
1010 * ---> C: gtphub also has 2.
1011 * <--- C: Response to TEI 2: I have TEI 12.
1012 * <--- gtphub: ok, TEI 2 is actually B with TEI 1. (unmap)
1013 * B: gtphub's first TEI is 12, as far as I can tell.
1014 *
1015 * Now the second GGSN comes into play:
1016 *
1017 * A: Create PDP Ctx, I have TEI 2.
1018 * ---> gtphub: A also has TEI 2, but for D, sending 1. (2)
1019 * ---> D: gtphub has 1.
1020 * <--- D: Response to TEI 1: I have TEI 11.
1021 * <--- gtphub: from D, 1 is A. 11 already taken by C, sending 13. (3)
1022 * A: gtphub also has TEI 13. (4)
1023 *
1024 * And some messages routed through:
1025 *
1026 * A: message to TEI 11, see (1).
1027 * ---> gtphub: ok, telling C with TEI 11.
1028 * ---> C: I see, 11 means reply with 1.
1029 * <--- C: Response to TEI 1
1030 * <--- gtphub: 1 from C is actually for A with TEI 1.
1031 * A: ah, my TEI 1, thanks!
1032 *
1033 * A: message to TEI 13, see (4).
1034 * ---> gtphub: ok, but not 13, D wanted TEI 11 instead, see (3).
1035 * ---> D: I see, 11 means reply with 1.
1036 * <--- D: Response to TEI 1
1037 * <--- gtphub: 1 from D is actually for A with TEI 2, see (2).
1038 * A: ah, my TEI 2, thanks!
1039 *
1040 * What if a GGSN initiates a request:
1041 *
1042 * <--- D: Request to gtphub TEI 1
1043 * <--- gtphub: 1 from D is for A with 2, see (2).
1044 * A: my TEI 2 means reply with 13.
1045 * ---> gtphub: 13 was D with 11, see (3).
1046 * ---> D: 11 from gtphub: a reply to my request for TEI 1.
1047 *
1048 * Note that usually, it's the sequence numbers that route a response back to
1049 * the requesting peer. Nevertheless, the TEI mappings must be carried out to
1050 * replace the TEIs in the GTP packet that is relayed.
1051 *
1052 * Also note: the TEI in the GTP header is "reversed" from the TEI in the IEs:
1053 * the TEI in the header is used to send something *to* a peer, while the TEI
1054 * in e.g. a Create PDP Context Request's IE is for routing messages *back*
1055 * later. */
1056
1057static int gtphub_unmap_header_tei(struct gtphub_peer_port **to_port_p,
1058 struct gtphub *hub,
1059 struct gtp_packet_desc *p,
1060 struct gtphub_peer_port *from_port)
1061{
1062 OSMO_ASSERT(p->version == 1);
1063 *to_port_p = NULL;
1064
1065 /* If the header's TEI is zero, no PDP context has been established
1066 * yet. If nonzero, a mapping should actually already exist for this
1067 * TEI, since it must have been announced in a PDP context creation. */
1068 uint32_t tei = p->header_tei;
1069 if (!tei)
1070 return 0;
1071
1072 /* to_peer has previously announced a TEI, which was stored and
1073 * mapped in from_peer's tei_map. */
1074 struct nr_mapping *nrm;
1075 nrm = nr_map_get_inv(&hub->tei_map[p->plane_idx], tei);
1076 if (!nrm) {
1077 LOGERR("Received unknown TEI %" PRIu32 " from %s\n",
1078 tei, gtphub_port_str(from_port));
1079 return -1;
1080 }
1081
1082 struct gtphub_peer_port *to_port = nrm->origin;
1083 uint32_t unmapped_tei = nrm->orig;
1084 set_tei(p, unmapped_tei);
1085
1086 LOG("Unmapped TEI coming from %s: %d -> %d (to %s)\n",
1087 gtphub_port_str(from_port), tei, unmapped_tei,
1088 gtphub_port_str2(to_port));
1089
1090 *to_port_p = to_port;
1091 return 0;
1092}
1093
1094/* Read GSN address IEs from p, and make sure these peer addresses exist in
1095 * bind[plane_idx] with default ports, in their respective planes (both Ctrl
1096 * and User). Map TEIs announced in IEs, and write mapped TEIs in-place into
1097 * the packet p. */
1098static int gtphub_handle_pdp_ctx_ies(struct gtphub *hub,
1099 struct gtphub_bind from_bind[],
1100 struct gtphub_bind to_bind[],
1101 struct gtp_packet_desc *p,
1102 time_t now)
1103{
1104 OSMO_ASSERT(p->plane_idx == GTPH_PLANE_CTRL);
1105
1106 int rc;
1107 int plane_idx;
1108
1109 switch (p->type) {
1110 case GTP_CREATE_PDP_REQ:
1111 case GTP_CREATE_PDP_RSP:
1112 /* Go for it below */
1113 break;
1114 default:
1115 /* Nothing to do for this message type. */
1116 return 0;
1117 }
1118
1119 /* TODO enforce a Request only from SGSN, a Response only from GGSN? */
1120
1121 osmo_static_assert((GTPH_PLANE_CTRL == 0) && (GTPH_PLANE_USER == 1),
1122 plane_nrs_match_GSN_addr_IE_indices);
1123
1124 uint8_t ie_type[] = { GTPIE_TEI_C, GTPIE_TEI_DI };
1125 int ie_mandatory = (p->type == GTP_CREATE_PDP_REQ);
1126
1127 for (plane_idx = 0; plane_idx < 2; plane_idx++) {
1128 struct gsn_addr addr_from_ie;
1129 uint32_t tei_from_ie;
1130 int ie_idx;
1131
1132 /* Fetch GSN Address and TEI from IEs */
1133 rc = gsn_addr_get(&addr_from_ie, p, plane_idx);
1134 if (rc) {
1135 LOGERR("Cannot read %s GSN Address IE\n",
1136 gtphub_plane_idx_names[plane_idx]);
1137 return -1;
1138 }
1139 LOG("Read %s GSN addr %s (%d)\n",
1140 gtphub_plane_idx_names[plane_idx],
1141 gsn_addr_to_str(&addr_from_ie),
1142 addr_from_ie.len);
1143
1144 ie_idx = gtpie_getie(p->ie, ie_type[plane_idx], 0);
1145 if (ie_idx < 0) {
1146 if (ie_mandatory) {
1147 LOGERR("Create PDP Context message invalid:"
1148 " missing IE %d\n", (int)ie_type[plane_idx]);
1149 return -1;
1150 }
1151 tei_from_ie = 0;
1152 }
1153 else
1154 tei_from_ie = ntoh32(p->ie[ie_idx]->tv4.v);
1155
1156 /* Make sure an entry for this peer address with default port
1157 * exists */
1158 struct gtphub_peer_port *peer_from_ie =
1159 gtphub_port_have(hub, &from_bind[plane_idx],
1160 &addr_from_ie,
1161 gtphub_plane_idx_default_port[plane_idx]);
1162
1163 if (tei_from_ie) {
1164 /* Create TEI mapping and replace in GTP packet IE */
1165 uint32_t mapped_tei =
1166 gtphub_tei_mapping_have(hub, plane_idx,
1167 peer_from_ie,
1168 tei_from_ie,
1169 now);
1170 p->ie[ie_idx]->tv4.v = hton32(mapped_tei);
1171 }
1172
1173 /* Replace the GSN address to reflect gtphub. */
1174 rc = gsn_addr_put(&to_bind[plane_idx].local_addr, p, plane_idx);
1175 if (rc) {
1176 LOGERR("Cannot write %s GSN Address IE\n",
1177 gtphub_plane_idx_names[plane_idx]);
1178 return -1;
1179 }
1180 }
1181
1182 return 0;
1183}
1184
1185static int gtphub_write(const struct osmo_fd *to,
1186 const struct osmo_sockaddr *to_addr,
1187 const uint8_t *buf, size_t buf_len)
1188{
1189 errno = 0;
1190 ssize_t sent = sendto(to->fd, buf, buf_len, 0,
1191 (struct sockaddr*)&to_addr->a, to_addr->l);
1192
1193 if (to_addr) {
1194 LOG("to %s\n", osmo_sockaddr_to_str(to_addr));
1195 }
1196
1197 if (sent == -1) {
1198 LOGERR("error: %s\n", strerror(errno));
1199 return -EINVAL;
1200 }
1201
1202 if (sent != buf_len)
1203 LOGERR("sent(%d) != data_len(%d)\n", (int)sent, (int)buf_len);
1204 else
1205 LOG("Sent %d\n%s\n", (int)sent, osmo_hexdump(buf, sent));
1206
1207 return 0;
1208}
1209
1210static int from_ggsns_read_cb(struct osmo_fd *from_ggsns_ofd, unsigned int what)
1211{
1212 unsigned int plane_idx = from_ggsns_ofd->priv_nr;
1213 OSMO_ASSERT(plane_idx < GTPH_PLANE_N);
1214 LOG("\n\n=== reading from GGSN (%s)\n", gtphub_plane_idx_names[plane_idx]);
1215 if (!(what & BSC_FD_READ))
1216 return 0;
1217
1218 struct gtphub *hub = from_ggsns_ofd->data;
1219
1220 static uint8_t buf[4096];
1221 struct osmo_sockaddr from_addr;
1222 struct osmo_sockaddr to_addr;
1223 struct osmo_fd *to_ofd;
1224 size_t len;
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001225 uint8_t *reply_buf;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001226
1227 len = gtphub_read(from_ggsns_ofd, &from_addr, buf, sizeof(buf));
1228 if (len < 1)
1229 return 0;
1230
1231 len = gtphub_from_ggsns_handle_buf(hub, plane_idx, &from_addr, buf, len,
1232 gtphub_now(),
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001233 &reply_buf, &to_ofd, &to_addr);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001234 if (len < 1)
1235 return 0;
1236
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001237 return gtphub_write(to_ofd, &to_addr, reply_buf, len);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001238}
1239
1240static int gtphub_unmap(struct gtphub *hub,
1241 struct gtp_packet_desc *p,
1242 struct gtphub_peer_port *from,
1243 struct gtphub_peer_port *to_proxy,
1244 struct gtphub_peer_port **final_unmapped,
1245 struct gtphub_peer_port **unmapped_from_seq,
1246 struct gtphub_peer_port **unmapped_from_tei)
1247{
1248 /* Always (try to) unmap sequence and TEI numbers, which need to be
1249 * replaced in the packet. Either way, give precedence to the proxy, if
1250 * configured. */
1251
1252 struct gtphub_peer_port *from_seq = NULL;
1253 struct gtphub_peer_port *from_tei = NULL;
1254 struct gtphub_peer_port *unmapped = NULL;
1255
1256 if (unmapped_from_seq)
1257 *unmapped_from_seq = from_seq;
1258 if (unmapped_from_tei)
1259 *unmapped_from_tei = from_tei;
1260 if (final_unmapped)
1261 *final_unmapped = unmapped;
1262
1263 from_seq = gtphub_unmap_seq(p, from);
1264
1265 if (gtphub_unmap_header_tei(&from_tei, hub, p, from) < 0)
1266 return -1;
1267
1268 struct gtphub_peer *from_peer = from->peer_addr->peer;
1269 if (from_seq && from_tei && (from_seq != from_tei)) {
1270 LOGERR("Seq unmap and TEI unmap yield two different peers. Using seq unmap."
1271 "(from %s %s: seq %d yields %s, tei %u yields %s)\n",
1272 gtphub_plane_idx_names[p->plane_idx],
1273 gtphub_peer_str(from_peer),
1274 (int)p->seq,
1275 gtphub_port_str(from_seq),
1276 (int)p->header_tei,
1277 gtphub_port_str2(from_tei)
1278 );
1279 }
1280 unmapped = (from_seq? from_seq : from_tei);
1281
1282 if (unmapped && to_proxy && (unmapped != to_proxy)) {
1283 LOGERR("Unmap yields a different peer than the configured proxy. Using proxy."
1284 " unmapped: %s proxy: %s\n",
1285 gtphub_port_str(unmapped),
1286 gtphub_port_str2(to_proxy)
1287 );
1288 }
1289 unmapped = (to_proxy? to_proxy : unmapped);
1290
1291 if (!unmapped) {
1292 /* Return no error, but returned pointers are all NULL. */
1293 return 0;
1294 }
1295
1296 LOG("from seq %p; from tei %p; unmapped => %p\n",
1297 from_seq, from_tei, unmapped);
1298
1299 if (unmapped_from_seq)
1300 *unmapped_from_seq = from_seq;
1301 if (unmapped_from_tei)
1302 *unmapped_from_tei = from_tei;
1303 if (final_unmapped)
1304 *final_unmapped = unmapped;
1305 return 0;
1306}
1307
1308static int gsn_addr_to_sockaddr(struct gsn_addr *src,
1309 uint16_t port,
1310 struct osmo_sockaddr *dst)
1311{
1312 return osmo_sockaddr_init_udp(dst, gsn_addr_to_str(src), port);
1313}
1314
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001315/* If p is an Echo request, replace p's data with the matching response and
1316 * return 1. If p is no Echo request, return 0, or -1 if an invalid packet is
1317 * detected. */
1318static int gtphub_handle_echo(struct gtphub *hub, struct gtp_packet_desc *p, uint8_t **reply_buf)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001319{
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001320 if (p->type != GTP_ECHO_REQ)
1321 return 0;
1322
1323 static uint8_t echo_response_data[14] = {
1324 0x32, /* flags */
1325 GTP_ECHO_RSP,
1326 0x00, 14 - 8, /* Length in network byte order */
1327 0x00, 0x00, 0x00, 0x00, /* Zero TEI */
1328 0, 0, /* Seq, to be replaced */
1329 0, 0, /* no extensions */
1330 0x0e, /* Recovery IE */
1331 0 /* Recovery counter, to be replaced */
1332 };
1333 uint16_t *seq = (uint16_t*)&echo_response_data[8];
1334 uint8_t *recovery = &echo_response_data[13];
1335
1336 *seq = hton16(p->seq);
1337 *recovery = hub->restart_counter;
1338
1339 *reply_buf = echo_response_data;
1340
1341 return sizeof(echo_response_data);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001342}
1343
1344/* Parse buffer as GTP packet, replace elements in-place and return the ofd and
1345 * address to forward to. Return a pointer to the osmo_fd, but copy the
1346 * sockaddr to *to_addr. The reason for this is that the sockaddr may expire at
1347 * any moment, while the osmo_fd is guaranteed to persist. Return the number of
1348 * bytes to forward, 0 or less on failure. */
1349int gtphub_from_ggsns_handle_buf(struct gtphub *hub,
1350 unsigned int plane_idx,
1351 const struct osmo_sockaddr *from_addr,
1352 uint8_t *buf,
1353 size_t received,
1354 time_t now,
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001355 uint8_t **reply_buf,
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001356 struct osmo_fd **to_ofd,
1357 struct osmo_sockaddr *to_addr)
1358{
1359 LOG("<- rx from GGSN %s\n", osmo_sockaddr_to_str(from_addr));
1360
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001361 static struct gtp_packet_desc p;
1362 gtp_decode(buf, received, plane_idx, &p);
1363
1364 if (p.rc <= 0)
1365 return -1;
1366
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001367 int reply_len;
1368 reply_len = gtphub_handle_echo(hub, &p, reply_buf);
1369 if (reply_len > 0) {
1370 /* It was an echo. Nothing left to do. */
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001371 osmo_sockaddr_copy(to_addr, from_addr);
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001372 *to_ofd = &hub->to_ggsns[plane_idx].ofd;
1373 return reply_len;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001374 }
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001375 if (reply_len < 0)
1376 return -1;
1377
1378 *to_ofd = &hub->to_sgsns[plane_idx].ofd;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001379
1380 /* If a GGSN proxy is configured, check that it's indeed that proxy
1381 * talking to us. A proxy is a forced 1:1 connection, e.g. to another
1382 * gtphub, so no-one else is allowed to talk to us from that side. */
1383 struct gtphub_peer_port *ggsn = hub->ggsn_proxy[plane_idx];
1384 if (ggsn) {
1385 if (osmo_sockaddr_cmp(&ggsn->sa, from_addr) != 0) {
1386 LOGERR("Rejecting: GGSN proxy configured, but GTP packet"
1387 " received on GGSN bind is from another sender:"
1388 " proxy: %s sender: %s\n",
1389 gtphub_port_str(ggsn),
1390 osmo_sockaddr_to_str(from_addr));
1391 return -1;
1392 }
1393 }
1394
1395 if (!ggsn) {
1396 ggsn = gtphub_port_find_sa(&hub->to_ggsns[plane_idx], from_addr);
1397 }
1398
1399 /* If any PDP context has been created, we already have an entry for
1400 * this GGSN. If we don't have an entry, the GGSN has nothing to tell
1401 * us about. */
1402 if (!ggsn) {
1403 LOGERR("Invalid GGSN peer. Dropping packet.\n");
1404 return -1;
1405 }
1406
1407 LOG("GGSN peer: %s\n", gtphub_port_str(ggsn));
1408
1409 struct gtphub_peer_port *sgsn_from_seq;
1410 struct gtphub_peer_port *sgsn;
1411 if (gtphub_unmap(hub, &p, ggsn,
1412 hub->sgsn_proxy[plane_idx],
1413 &sgsn, &sgsn_from_seq,
1414 NULL /* not interested, got it in &sgsn already */
1415 )
1416 != 0) {
1417 return -1;
1418 }
1419
1420 if (!sgsn) {
1421 /* A GGSN initiated request would go to a known TEI. So this is
1422 * bogus. */
1423 LOGERR("No SGSN to send to. Dropping packet.\n");
1424 return -1;
1425 }
1426
1427 if (plane_idx == GTPH_PLANE_CTRL) {
1428 /* This may be a Create PDP Context response. If it is, there are other
1429 * addresses in the GTP message to set up apart from the sender. */
1430 if (gtphub_handle_pdp_ctx_ies(hub, hub->to_ggsns,
1431 hub->to_sgsns, &p, now)
1432 != 0)
1433 return -1;
1434 }
1435
1436 gtphub_check_restart_counter(hub, &p, ggsn);
1437 gtphub_map_restart_counter(hub, &p, ggsn, sgsn);
1438
1439 /* If the GGSN is replying to an SGSN request, the sequence nr has
1440 * already been unmapped above (sgsn_from_seq != NULL), and we need not
1441 * create a new mapping. */
1442 if (!sgsn_from_seq)
1443 gtphub_map_seq(&p, ggsn, sgsn, now);
1444
1445 osmo_sockaddr_copy(to_addr, &sgsn->sa);
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001446
1447 *reply_buf = (uint8_t*)p.data;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001448 return received;
1449}
1450
1451static int from_sgsns_read_cb(struct osmo_fd *from_sgsns_ofd, unsigned int what)
1452{
1453 unsigned int plane_idx = from_sgsns_ofd->priv_nr;
1454 OSMO_ASSERT(plane_idx < GTPH_PLANE_N);
1455 LOG("\n\n=== reading from SGSN (%s)\n", gtphub_plane_idx_names[plane_idx]);
1456
1457 if (!(what & BSC_FD_READ))
1458 return 0;
1459
1460 struct gtphub *hub = from_sgsns_ofd->data;
1461
1462 static uint8_t buf[4096];
1463 struct osmo_sockaddr from_addr;
1464 struct osmo_sockaddr to_addr;
1465 struct osmo_fd *to_ofd;
1466 size_t len;
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001467 uint8_t *reply_buf;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001468
1469 len = gtphub_read(from_sgsns_ofd, &from_addr, buf, sizeof(buf));
1470 if (len < 1)
1471 return 0;
1472
1473 len = gtphub_from_sgsns_handle_buf(hub, plane_idx, &from_addr, buf, len,
1474 gtphub_now(),
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001475 &reply_buf, &to_ofd, &to_addr);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001476 if (len < 1)
1477 return 0;
1478
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001479 return gtphub_write(to_ofd, &to_addr, reply_buf, len);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001480}
1481
1482/* Analogous to gtphub_from_ggsns_handle_buf(), see the comment there. */
1483int gtphub_from_sgsns_handle_buf(struct gtphub *hub,
1484 unsigned int plane_idx,
1485 const struct osmo_sockaddr *from_addr,
1486 uint8_t *buf,
1487 size_t received,
1488 time_t now,
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001489 uint8_t **reply_buf,
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001490 struct osmo_fd **to_ofd,
1491 struct osmo_sockaddr *to_addr)
1492{
1493 LOG("-> rx from SGSN %s\n", osmo_sockaddr_to_str(from_addr));
1494
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001495 static struct gtp_packet_desc p;
1496 gtp_decode(buf, received, plane_idx, &p);
1497
1498 if (p.rc <= 0)
1499 return -1;
1500
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001501 int reply_len;
1502 reply_len = gtphub_handle_echo(hub, &p, reply_buf);
1503 if (reply_len > 0) {
1504 /* It was an echo. Nothing left to do. */
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001505 osmo_sockaddr_copy(to_addr, from_addr);
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001506 *to_ofd = &hub->to_ggsns[plane_idx].ofd;
1507 return reply_len;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001508 }
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001509 if (reply_len < 0)
1510 return -1;
1511
1512 *to_ofd = &hub->to_ggsns[plane_idx].ofd;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001513
1514 /* If an SGSN proxy is configured, check that it's indeed that proxy
1515 * talking to us. A proxy is a forced 1:1 connection, e.g. to another
1516 * gtphub, so no-one else is allowed to talk to us from that side. */
1517 struct gtphub_peer_port *sgsn = hub->sgsn_proxy[plane_idx];
1518 if (sgsn) {
1519 if (osmo_sockaddr_cmp(&sgsn->sa, from_addr) != 0) {
1520 LOGERR("Rejecting: GGSN proxy configured, but GTP packet"
1521 " received on GGSN bind is from another sender:"
1522 " proxy: %s sender: %s\n",
1523 gtphub_port_str(sgsn),
1524 osmo_sockaddr_to_str(from_addr));
1525 return -1;
1526 }
1527 }
1528
1529 if (!sgsn) {
1530 /* If any contact has been made before, we already have an
1531 * entry for this SGSN. */
1532 sgsn = gtphub_port_find_sa(&hub->to_sgsns[plane_idx], from_addr);
1533 }
1534
1535 if (!sgsn) {
1536 /* A new peer. If this is on the Ctrl plane, an SGSN may make
1537 * first contact without being known yet, so create the peer
1538 * struct for the current sender. */
1539 if (plane_idx != GTPH_PLANE_CTRL) {
1540 LOGERR("User plane peer was not announced by PDP Context, discarding: %s\n",
1541 osmo_sockaddr_to_str(from_addr));
1542 return -1;
1543 }
1544
1545 struct gsn_addr from_gsna;
1546 uint16_t from_port;
1547 if (gsn_addr_from_sockaddr(&from_gsna, &from_port, from_addr) != 0)
1548 return -1;
1549
1550 sgsn = gtphub_port_have(hub, &hub->to_sgsns[plane_idx],
1551 &from_gsna, from_port);
1552 }
1553
1554 if (!sgsn) {
1555 /* This could theoretically happen for invalid address data or somesuch. */
1556 LOGERR("Invalid SGSN peer. Dropping packet.\n");
1557 return -1;
1558 }
1559 LOG("SGSN peer: %s\n", gtphub_port_str(sgsn));
1560
1561 struct gtphub_peer_port *ggsn_from_seq;
1562 struct gtphub_peer_port *ggsn;
1563 if (gtphub_unmap(hub, &p, sgsn,
1564 hub->ggsn_proxy[plane_idx],
1565 &ggsn, &ggsn_from_seq,
1566 NULL /* not interested, got it in &ggsn already */
1567 )
1568 != 0) {
1569 return -1;
1570 }
1571
1572 /* See what our GGSN guess would be from the packet data per se. */
1573 /* TODO maybe not do this always? */
1574 struct gtphub_peer_port *ggsn_from_packet;
1575 ggsn_from_packet = gtphub_resolve_ggsn(hub, &p);
1576
1577 if (ggsn_from_packet && ggsn
1578 && (ggsn_from_packet != ggsn)) {
1579 LOGERR("GGSN implied from packet does not match unmapped"
1580 " GGSN, using unmapped GGSN:"
1581 " from packet: %s unmapped: %s\n",
1582 gtphub_port_str(ggsn_from_packet),
1583 gtphub_port_str2(ggsn));
1584 /* TODO return -1; ? */
1585 }
1586
1587 if (!ggsn)
1588 ggsn = ggsn_from_packet;
1589
1590 if (!ggsn) {
1591 LOGERR("No GGSN to send to. Dropping packet.\n");
1592 return -1;
1593 }
1594
1595 if (plane_idx == GTPH_PLANE_CTRL) {
1596 /* This may be a Create PDP Context requst. If it is, there are other
1597 * addresses in the GTP message to set up apart from the sender. */
1598 if (gtphub_handle_pdp_ctx_ies(hub, hub->to_sgsns,
1599 hub->to_ggsns, &p, now)
1600 != 0)
1601 return -1;
1602 }
1603
1604 gtphub_check_restart_counter(hub, &p, sgsn);
1605 gtphub_map_restart_counter(hub, &p, sgsn, ggsn);
1606
1607 /* If the SGSN is replying to a GGSN request, the sequence nr has
1608 * already been unmapped above (unmap_ggsn != NULL), and we need not
1609 * create a new outgoing sequence map. */
1610 if (!ggsn_from_seq)
1611 gtphub_map_seq(&p, sgsn, ggsn, now);
1612
1613 osmo_sockaddr_copy(to_addr, &ggsn->sa);
1614
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001615 *reply_buf = (uint8_t*)p.data;
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001616 return received;
1617}
1618
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001619static void resolved_gssn_del_cb(struct expiring_item *expi)
1620{
1621 struct gtphub_resolved_ggsn *ggsn;
1622 ggsn = container_of(expi, struct gtphub_resolved_ggsn, expiry_entry);
1623
1624 gtphub_port_ref_count_dec(ggsn->peer);
1625 llist_del(&ggsn->entry);
1626
1627 ggsn->expiry_entry.del_cb = 0;
1628 expiring_item_del(&ggsn->expiry_entry);
1629
1630 talloc_free(ggsn);
1631}
1632
1633void gtphub_resolved_ggsn(struct gtphub *hub, const char *apn_oi_str,
1634 struct gsn_addr *resolved_addr,
1635 time_t now)
1636{
1637 struct gtphub_peer_port *pp;
1638 struct gtphub_resolved_ggsn *ggsn;
1639
1640 pp = gtphub_port_have(hub, &hub->to_ggsns[GTPH_PLANE_CTRL],
1641 resolved_addr, 2123);
1642 if (!pp) {
1643 LOGERR("Internal: Cannot create/find peer '%s'\n",
1644 gsn_addr_to_str(resolved_addr));
1645 return;
1646 }
1647
1648 ggsn = talloc_zero(osmo_gtphub_ctx, struct gtphub_resolved_ggsn);
1649 OSMO_ASSERT(ggsn);
1650
1651 ggsn->peer = pp;
1652 gtphub_port_ref_count_inc(pp);
1653
1654 strncpy(ggsn->apn_oi_str, apn_oi_str, sizeof(ggsn->apn_oi_str));
1655
1656 ggsn->expiry_entry.del_cb = resolved_gssn_del_cb;
1657 expiry_add(&hub->expire_tei_maps, &ggsn->expiry_entry, now);
1658
1659 llist_add(&ggsn->entry, &hub->resolved_ggsns);
1660}
1661
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001662static int gtphub_gc_peer_port(struct gtphub_peer_port *pp)
1663{
1664 return pp->ref_count == 0;
1665}
1666
1667static int gtphub_gc_peer_addr(struct gtphub_peer_addr *pa)
1668{
1669 struct gtphub_peer_port *pp, *npp;
1670 llist_for_each_entry_safe(pp, npp, &pa->ports, entry) {
1671 if (gtphub_gc_peer_port(pp)) {
1672 LOG("expired: peer %s\n",
1673 gtphub_port_str(pp));
1674 gtphub_peer_port_del(pp);
1675 }
1676 }
1677 return llist_empty(&pa->ports);
1678}
1679
1680static int gtphub_gc_peer(struct gtphub_peer *p)
1681{
1682 struct gtphub_peer_addr *pa, *npa;
1683 llist_for_each_entry_safe(pa, npa, &p->addresses, entry) {
1684 if (gtphub_gc_peer_addr(pa)) {
1685 gtphub_peer_addr_del(pa);
1686 }
1687 }
1688
1689 /* Note that there's a ref_count in each gtphub_peer_port instance
1690 * listed within p->addresses, referenced by TEI mappings from
1691 * hub->tei_map. As long as those don't expire, this peer will stay. */
1692
1693 LOG("gc peer %p llist_empty %d seq_map_empty %d\n", p,
1694 (int)llist_empty(&p->addresses), (int) nr_map_empty(&p->seq_map));
1695 if (! nr_map_empty(&p->seq_map)) {
1696 printf("not empty\n");
1697 struct nr_mapping *nrm;
1698 llist_for_each_entry(nrm, &p->seq_map.mappings, entry) {
1699 printf("%p %s %d -> %d\n",
1700 nrm->origin, gtphub_port_str(nrm->origin),nrm->orig, nrm->repl);
1701 }
1702 }
1703 return llist_empty(&p->addresses)
1704 && nr_map_empty(&p->seq_map);
1705}
1706
1707static void gtphub_gc_bind(struct gtphub_bind *b)
1708{
1709 struct gtphub_peer *p, *n;
1710 llist_for_each_entry_safe(p, n, &b->peers, entry) {
1711 if (gtphub_gc_peer(p)) {
1712 gtphub_peer_del(p);
1713 }
1714 }
1715}
1716
1717void gtphub_gc(struct gtphub *hub, time_t now)
1718{
1719 int expired;
1720 expired = expiry_tick(&hub->expire_seq_maps, now);
1721 expired += expiry_tick(&hub->expire_tei_maps, now);
1722
1723 /* ... */
1724
1725 if (expired) {
1726 int i;
1727 for (i = 0; i < GTPH_PLANE_N; i++) {
1728 gtphub_gc_bind(&hub->to_sgsns[i]);
1729 gtphub_gc_bind(&hub->to_ggsns[i]);
1730 }
1731 }
1732}
1733
1734static void gtphub_gc_cb(void *data)
1735{
1736 struct gtphub *hub = data;
1737 gtphub_gc(hub, gtphub_now());
1738 osmo_timer_schedule(&hub->gc_timer, GTPH_GC_TICK_SECONDS, 0);
1739}
1740
1741static void gtphub_gc_start(struct gtphub *hub)
1742{
1743 hub->gc_timer.cb = gtphub_gc_cb;
1744 hub->gc_timer.data = hub;
1745
1746 osmo_timer_schedule(&hub->gc_timer, GTPH_GC_TICK_SECONDS, 0);
1747}
1748
1749/* called by unit tests */
1750void gtphub_init(struct gtphub *hub)
1751{
1752 gtphub_zero(hub);
1753
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001754 INIT_LLIST_HEAD(&hub->resolved_ggsns);
1755
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001756 expiry_init(&hub->expire_seq_maps, GTPH_SEQ_MAPPING_EXPIRY_SECS);
1757 expiry_init(&hub->expire_tei_maps, GTPH_TEI_MAPPING_EXPIRY_MINUTES * 60);
1758
1759 int plane_idx;
1760 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1761 nr_pool_init(&hub->tei_pool[plane_idx]);
1762 nr_map_init(&hub->tei_map[plane_idx],
1763 &hub->tei_pool[plane_idx],
1764 &hub->expire_tei_maps);
1765
1766 gtphub_bind_init(&hub->to_ggsns[plane_idx]);
1767 gtphub_bind_init(&hub->to_sgsns[plane_idx]);
1768 }
1769}
1770
1771static int gtphub_make_proxy(struct gtphub *hub,
1772 struct gtphub_peer_port **pp,
1773 struct gtphub_bind *bind,
1774 const struct gtphub_cfg_addr *addr)
1775{
1776 if (!addr->addr_str)
1777 return 0;
1778
1779 struct gsn_addr gsna;
1780 if (gsn_addr_from_str(&gsna, addr->addr_str) != 0)
1781 return -1;
1782
1783 *pp = gtphub_port_have(hub, bind, &gsna, addr->port);
1784
1785 /* This is *the* proxy. Make sure it is never expired. */
1786 gtphub_port_ref_count_inc(*pp);
1787 return 0;
1788}
1789
1790int gtphub_start(struct gtphub *hub, struct gtphub_cfg *cfg)
1791{
1792 int rc;
1793
1794 gtphub_init(hub);
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001795 gtphub_ares_init(hub);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001796
Neels Hofmeyrbb3d6782015-11-09 15:12:25 +01001797 /* TODO set hub->restart_counter from external file. */
1798
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001799 int plane_idx;
1800 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1801 rc = gtphub_bind_start(&hub->to_ggsns[plane_idx],
1802 &cfg->to_ggsns[plane_idx],
1803 from_ggsns_read_cb, hub, plane_idx);
1804 if (rc) {
1805 LOGERR("Failed to bind for GGSNs (%s)\n",
1806 gtphub_plane_idx_names[plane_idx]);
1807 return rc;
1808 }
1809
1810 rc = gtphub_bind_start(&hub->to_sgsns[plane_idx],
1811 &cfg->to_sgsns[plane_idx],
1812 from_sgsns_read_cb, hub, plane_idx);
1813 if (rc) {
1814 LOGERR("Failed to bind for SGSNs (%s)\n",
1815 gtphub_plane_idx_names[plane_idx]);
1816 return rc;
1817 }
1818 }
1819
1820
1821 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1822 if (gtphub_make_proxy(hub,
1823 &hub->sgsn_proxy[plane_idx],
1824 &hub->to_sgsns[plane_idx],
1825 &cfg->sgsn_proxy[plane_idx])
1826 != 0) {
1827 LOGERR("Cannot configure SGSN proxy %s port %d.\n",
1828 cfg->sgsn_proxy[plane_idx].addr_str,
1829 (int)cfg->sgsn_proxy[plane_idx].port);
1830 return -1;
1831 }
1832 if (gtphub_make_proxy(hub,
1833 &hub->ggsn_proxy[plane_idx],
1834 &hub->to_ggsns[plane_idx],
1835 &cfg->ggsn_proxy[plane_idx])
1836 != 0) {
1837 LOGERR("Cannot configure GGSN proxy.\n");
1838 return -1;
1839 }
1840 }
1841
1842 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1843 if (hub->sgsn_proxy[plane_idx])
1844 LOG("Using SGSN %s proxy %s\n",
1845 gtphub_plane_idx_names[plane_idx],
1846 gtphub_port_str(hub->sgsn_proxy[plane_idx]));
1847 }
1848
1849 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1850 if (hub->sgsn_proxy[plane_idx])
1851 LOG("Using GGSN %s proxy %s\n",
1852 gtphub_plane_idx_names[plane_idx],
1853 gtphub_port_str(hub->ggsn_proxy[plane_idx]));
1854 }
1855
1856 gtphub_gc_start(hub);
1857 return 0;
1858}
1859
1860static struct gtphub_peer_addr *gtphub_peer_find_addr(const struct gtphub_peer *peer,
1861 const struct gsn_addr *addr)
1862{
1863 struct gtphub_peer_addr *a;
1864 llist_for_each_entry(a, &peer->addresses, entry) {
1865 if (gsn_addr_same(&a->addr, addr))
1866 return a;
1867 }
1868 return NULL;
1869}
1870
1871static struct gtphub_peer_port *gtphub_addr_find_port(const struct gtphub_peer_addr *a,
1872 uint16_t port)
1873{
1874 OSMO_ASSERT(port);
1875 struct gtphub_peer_port *pp;
1876 llist_for_each_entry(pp, &a->ports, entry) {
1877 if (pp->port == port)
1878 return pp;
1879 }
1880 return NULL;
1881}
1882
1883static struct gtphub_peer_addr *gtphub_addr_find(const struct gtphub_bind *bind,
1884 const struct gsn_addr *addr)
1885{
1886 struct gtphub_peer *peer;
1887 llist_for_each_entry(peer, &bind->peers, entry) {
1888 struct gtphub_peer_addr *a = gtphub_peer_find_addr(peer, addr);
1889 if (a)
1890 return a;
1891 }
1892 return NULL;
1893}
1894
1895static struct gtphub_peer_port *gtphub_port_find(const struct gtphub_bind *bind,
1896 const struct gsn_addr *addr,
1897 uint16_t port)
1898{
1899 struct gtphub_peer_addr *a = gtphub_addr_find(bind, addr);
1900 if (!a)
1901 return NULL;
1902 return gtphub_addr_find_port(a, port);
1903}
1904
1905struct gtphub_peer_port *gtphub_port_find_sa(const struct gtphub_bind *bind,
1906 const struct osmo_sockaddr *addr)
1907{
1908 struct gsn_addr gsna;
1909 uint16_t port;
1910 gsn_addr_from_sockaddr(&gsna, &port, addr);
1911 return gtphub_port_find(bind, &gsna, port);
1912}
1913
1914static struct gtphub_peer *gtphub_peer_new(struct gtphub *hub,
1915 struct gtphub_bind *bind)
1916{
1917 struct gtphub_peer *peer = talloc_zero(osmo_gtphub_ctx, struct gtphub_peer);
1918 OSMO_ASSERT(peer);
1919
1920 INIT_LLIST_HEAD(&peer->addresses);
1921
1922 nr_pool_init(&peer->seq_pool);
1923 nr_map_init(&peer->seq_map, &peer->seq_pool, &hub->expire_seq_maps);
1924
1925 /* TODO use something random to pick the initial sequence nr.
1926 0x6d31 produces the ASCII character sequence 'm1', currently used in
1927 gtphub_nc_test.sh. */
1928 peer->seq_pool.last_nr = 0x6d31 - 1;
1929
1930 llist_add(&peer->entry, &bind->peers);
1931 return peer;
1932}
1933
1934static struct gtphub_peer_addr *gtphub_peer_add_addr(struct gtphub_peer *peer,
1935 const struct gsn_addr *addr)
1936{
1937 struct gtphub_peer_addr *a;
1938 a = talloc_zero(osmo_gtphub_ctx, struct gtphub_peer_addr);
1939 OSMO_ASSERT(a);
1940 a->peer = peer;
1941 gsn_addr_copy(&a->addr, addr);
1942 INIT_LLIST_HEAD(&a->ports);
1943 llist_add(&a->entry, &peer->addresses);
1944
1945 return a;
1946}
1947
1948static struct gtphub_peer_addr *gtphub_addr_have(struct gtphub *hub,
1949 struct gtphub_bind *bind,
1950 const struct gsn_addr *addr)
1951{
1952 struct gtphub_peer_addr *a = gtphub_addr_find(bind, addr);
1953 if (a)
1954 return a;
1955
1956 /* If we haven't found an address, that means we need to create an
1957 * entirely new peer for the new address. More addresses may be added
1958 * to this peer later, but not via this function. */
1959 struct gtphub_peer *peer = gtphub_peer_new(hub, bind);
1960 return gtphub_peer_add_addr(peer, addr);
1961}
1962
1963static struct gtphub_peer_port *gtphub_addr_add_port(struct gtphub_peer_addr *a,
1964 uint16_t port)
1965{
1966 struct gtphub_peer_port *pp;
1967
1968 pp = talloc_zero(osmo_gtphub_ctx, struct gtphub_peer_port);
1969 OSMO_ASSERT(pp);
1970 pp->peer_addr = a;
1971 pp->port = port;
1972
1973 if (gsn_addr_to_sockaddr(&a->addr, port, &pp->sa) != 0) {
1974 talloc_free(pp);
1975 return NULL;
1976 }
1977
1978 llist_add(&pp->entry, &a->ports);
1979
1980 LOG("New peer: %s port %d\n",
1981 gsn_addr_to_str(&a->addr),
1982 (int)port);
1983
1984 return pp;
1985}
1986
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001987struct gtphub_peer_port *gtphub_port_have(struct gtphub *hub,
1988 struct gtphub_bind *bind,
1989 const struct gsn_addr *addr,
1990 uint16_t port)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001991{
1992 struct gtphub_peer_addr *a = gtphub_addr_have(hub, bind, addr);
1993
1994 struct gtphub_peer_port *pp = gtphub_addr_find_port(a, port);
1995 if (pp)
1996 return pp;
1997
1998 return gtphub_addr_add_port(a, port);
1999}
2000
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02002001static struct gtphub_peer_port *gtphub_resolve_ggsn(struct gtphub *hub,
2002 struct gtp_packet_desc *p)
2003{
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01002004 return gtphub_resolve_ggsn_addr(hub,
2005 get_ie_imsi_str(p->ie, 0),
2006 get_ie_apn_str(p->ie));
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02002007}
2008
2009
2010/* TODO move to osmocom/core/socket.c ? */
2011/* The caller is required to call freeaddrinfo(*result), iff zero is returned. */
2012/* use this in osmo_sock_init() to remove dup. */
2013static int _osmo_getaddrinfo(struct addrinfo **result,
2014 uint16_t family, uint16_t type, uint8_t proto,
2015 const char *host, uint16_t port)
2016{
2017 struct addrinfo hints;
2018 char portbuf[16];
2019
2020 sprintf(portbuf, "%u", port);
2021 memset(&hints, '\0', sizeof(struct addrinfo));
2022 hints.ai_family = family;
2023 if (type == SOCK_RAW) {
2024 /* Workaround for glibc, that returns EAI_SERVICE (-8) if
2025 * SOCK_RAW and IPPROTO_GRE is used.
2026 */
2027 hints.ai_socktype = SOCK_DGRAM;
2028 hints.ai_protocol = IPPROTO_UDP;
2029 } else {
2030 hints.ai_socktype = type;
2031 hints.ai_protocol = proto;
2032 }
2033
2034 return getaddrinfo(host, portbuf, &hints, result);
2035}
2036
2037/* TODO move to osmocom/core/socket.c ? */
2038int osmo_sockaddr_init(struct osmo_sockaddr *addr,
2039 uint16_t family, uint16_t type, uint8_t proto,
2040 const char *host, uint16_t port)
2041{
2042 struct addrinfo *res;
2043 int rc;
2044 rc = _osmo_getaddrinfo(&res, family, type, proto, host, port);
2045
2046 if (rc != 0) {
2047 LOGERR("getaddrinfo returned error %d\n", (int)rc);
2048 return -EINVAL;
2049 }
2050
2051 OSMO_ASSERT(res->ai_addrlen <= sizeof(addr->a));
2052 memcpy(&addr->a, res->ai_addr, res->ai_addrlen);
2053 addr->l = res->ai_addrlen;
2054 freeaddrinfo(res);
2055
2056 return 0;
2057}
2058
2059int osmo_sockaddr_to_strs(char *addr_str, size_t addr_str_len,
2060 char *port_str, size_t port_str_len,
2061 const struct osmo_sockaddr *addr,
2062 int flags)
2063{
2064 int rc;
2065
2066 if ((addr->l < 1) || (addr->l > sizeof(addr->a))) {
2067 LOGP(DGTPHUB, LOGL_ERROR, "Invalid address size: %d\n", addr->l);
2068 return -1;
2069 }
2070
2071 if (addr->l > sizeof(addr->a)) {
2072 LOGP(DGTPHUB, LOGL_ERROR, "Invalid address: too long: %d\n", addr->l);
2073 return -1;
2074 }
2075
2076 rc = getnameinfo((struct sockaddr*)&addr->a, addr->l,
2077 addr_str, addr_str_len,
2078 port_str, port_str_len,
2079 flags);
2080
2081 if (rc)
2082 LOGP(DGTPHUB, LOGL_ERROR, "Invalid address: %s: %s\n", gai_strerror(rc),
2083 osmo_hexdump((uint8_t*)&addr->a, addr->l));
2084
2085 return rc;
2086}
2087
2088const char *osmo_sockaddr_to_strb(const struct osmo_sockaddr *addr,
2089 char *buf, size_t buf_len)
2090{
2091 const int portbuf_len = 6;
2092 OSMO_ASSERT(buf_len > portbuf_len);
2093 char *portbuf = buf + buf_len - portbuf_len;
2094 buf_len -= portbuf_len;
2095 if (osmo_sockaddr_to_strs(buf, buf_len,
2096 portbuf, portbuf_len,
2097 addr,
2098 NI_NUMERICHOST | NI_NUMERICSERV))
2099 return NULL;
2100
2101 char *pos = buf + strnlen(buf, buf_len-1);
2102 size_t len = buf_len - (pos - buf);
2103
2104 snprintf(pos, len, " port %s", portbuf);
2105 buf[buf_len-1] = '\0';
2106
2107 return buf;
2108}
2109
2110const char *osmo_sockaddr_to_str(const struct osmo_sockaddr *addr)
2111{
2112 static char buf[256];
2113 const char *result = osmo_sockaddr_to_strb(addr, buf, sizeof(buf));
2114 if (! result)
2115 return "(invalid)";
2116 return result;
2117}
2118
2119int osmo_sockaddr_cmp(const struct osmo_sockaddr *a, const struct osmo_sockaddr *b)
2120{
2121 if (a == b)
2122 return 0;
2123 if (!a)
2124 return -1;
2125 if (!b)
2126 return 1;
2127 if (a->l != b->l) {
2128 /* Lengths are not the same, but determine the order. Will
2129 * anyone ever sort a list by osmo_sockaddr though...? */
2130 int cmp = memcmp(&a->a, &b->a, (a->l < b->l)? a->l : b->l);
2131 if (cmp == 0) {
2132 if (a->l < b->l)
2133 return -1;
2134 else
2135 return 1;
2136 }
2137 return cmp;
2138 }
2139 return memcmp(&a->a, &b->a, a->l);
2140}
2141
2142void osmo_sockaddr_copy(struct osmo_sockaddr *dst, const struct osmo_sockaddr *src)
2143{
2144 OSMO_ASSERT(src->l <= sizeof(dst->a));
2145 memcpy(&dst->a, &src->a, src->l);
2146 dst->l = src->l;
2147}