blob: eae4cf2cf1a361b39e2f80594f58f4f6586b4479 [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;
1225
1226 len = gtphub_read(from_ggsns_ofd, &from_addr, buf, sizeof(buf));
1227 if (len < 1)
1228 return 0;
1229
1230 len = gtphub_from_ggsns_handle_buf(hub, plane_idx, &from_addr, buf, len,
1231 gtphub_now(),
1232 &to_ofd, &to_addr);
1233 if (len < 1)
1234 return 0;
1235
1236 return gtphub_write(to_ofd, &to_addr, buf, len);
1237}
1238
1239static int gtphub_unmap(struct gtphub *hub,
1240 struct gtp_packet_desc *p,
1241 struct gtphub_peer_port *from,
1242 struct gtphub_peer_port *to_proxy,
1243 struct gtphub_peer_port **final_unmapped,
1244 struct gtphub_peer_port **unmapped_from_seq,
1245 struct gtphub_peer_port **unmapped_from_tei)
1246{
1247 /* Always (try to) unmap sequence and TEI numbers, which need to be
1248 * replaced in the packet. Either way, give precedence to the proxy, if
1249 * configured. */
1250
1251 struct gtphub_peer_port *from_seq = NULL;
1252 struct gtphub_peer_port *from_tei = NULL;
1253 struct gtphub_peer_port *unmapped = NULL;
1254
1255 if (unmapped_from_seq)
1256 *unmapped_from_seq = from_seq;
1257 if (unmapped_from_tei)
1258 *unmapped_from_tei = from_tei;
1259 if (final_unmapped)
1260 *final_unmapped = unmapped;
1261
1262 from_seq = gtphub_unmap_seq(p, from);
1263
1264 if (gtphub_unmap_header_tei(&from_tei, hub, p, from) < 0)
1265 return -1;
1266
1267 struct gtphub_peer *from_peer = from->peer_addr->peer;
1268 if (from_seq && from_tei && (from_seq != from_tei)) {
1269 LOGERR("Seq unmap and TEI unmap yield two different peers. Using seq unmap."
1270 "(from %s %s: seq %d yields %s, tei %u yields %s)\n",
1271 gtphub_plane_idx_names[p->plane_idx],
1272 gtphub_peer_str(from_peer),
1273 (int)p->seq,
1274 gtphub_port_str(from_seq),
1275 (int)p->header_tei,
1276 gtphub_port_str2(from_tei)
1277 );
1278 }
1279 unmapped = (from_seq? from_seq : from_tei);
1280
1281 if (unmapped && to_proxy && (unmapped != to_proxy)) {
1282 LOGERR("Unmap yields a different peer than the configured proxy. Using proxy."
1283 " unmapped: %s proxy: %s\n",
1284 gtphub_port_str(unmapped),
1285 gtphub_port_str2(to_proxy)
1286 );
1287 }
1288 unmapped = (to_proxy? to_proxy : unmapped);
1289
1290 if (!unmapped) {
1291 /* Return no error, but returned pointers are all NULL. */
1292 return 0;
1293 }
1294
1295 LOG("from seq %p; from tei %p; unmapped => %p\n",
1296 from_seq, from_tei, unmapped);
1297
1298 if (unmapped_from_seq)
1299 *unmapped_from_seq = from_seq;
1300 if (unmapped_from_tei)
1301 *unmapped_from_tei = from_tei;
1302 if (final_unmapped)
1303 *final_unmapped = unmapped;
1304 return 0;
1305}
1306
1307static int gsn_addr_to_sockaddr(struct gsn_addr *src,
1308 uint16_t port,
1309 struct osmo_sockaddr *dst)
1310{
1311 return osmo_sockaddr_init_udp(dst, gsn_addr_to_str(src), port);
1312}
1313
1314static int gtphub_handle_echo(const struct gtp_packet_desc *p)
1315{
1316 /* TODO */
1317 return 0;
1318}
1319
1320/* Parse buffer as GTP packet, replace elements in-place and return the ofd and
1321 * address to forward to. Return a pointer to the osmo_fd, but copy the
1322 * sockaddr to *to_addr. The reason for this is that the sockaddr may expire at
1323 * any moment, while the osmo_fd is guaranteed to persist. Return the number of
1324 * bytes to forward, 0 or less on failure. */
1325int gtphub_from_ggsns_handle_buf(struct gtphub *hub,
1326 unsigned int plane_idx,
1327 const struct osmo_sockaddr *from_addr,
1328 uint8_t *buf,
1329 size_t received,
1330 time_t now,
1331 struct osmo_fd **to_ofd,
1332 struct osmo_sockaddr *to_addr)
1333{
1334 LOG("<- rx from GGSN %s\n", osmo_sockaddr_to_str(from_addr));
1335
1336 *to_ofd = &hub->to_sgsns[plane_idx].ofd;
1337
1338 static struct gtp_packet_desc p;
1339 gtp_decode(buf, received, plane_idx, &p);
1340
1341 if (p.rc <= 0)
1342 return -1;
1343
1344 int rc;
1345 rc = gtphub_handle_echo(&p);
1346 if (rc == 1) {
1347 /* It was en echo. Nothing left to do. */
1348 /* (*to_ofd already set above.) */
1349 osmo_sockaddr_copy(to_addr, from_addr);
1350 return 0;
1351 }
1352 if (rc < 0)
1353 return -1; /* Invalid packet. */
1354
1355 /* If a GGSN proxy is configured, check that it's indeed that proxy
1356 * talking to us. A proxy is a forced 1:1 connection, e.g. to another
1357 * gtphub, so no-one else is allowed to talk to us from that side. */
1358 struct gtphub_peer_port *ggsn = hub->ggsn_proxy[plane_idx];
1359 if (ggsn) {
1360 if (osmo_sockaddr_cmp(&ggsn->sa, from_addr) != 0) {
1361 LOGERR("Rejecting: GGSN proxy configured, but GTP packet"
1362 " received on GGSN bind is from another sender:"
1363 " proxy: %s sender: %s\n",
1364 gtphub_port_str(ggsn),
1365 osmo_sockaddr_to_str(from_addr));
1366 return -1;
1367 }
1368 }
1369
1370 if (!ggsn) {
1371 ggsn = gtphub_port_find_sa(&hub->to_ggsns[plane_idx], from_addr);
1372 }
1373
1374 /* If any PDP context has been created, we already have an entry for
1375 * this GGSN. If we don't have an entry, the GGSN has nothing to tell
1376 * us about. */
1377 if (!ggsn) {
1378 LOGERR("Invalid GGSN peer. Dropping packet.\n");
1379 return -1;
1380 }
1381
1382 LOG("GGSN peer: %s\n", gtphub_port_str(ggsn));
1383
1384 struct gtphub_peer_port *sgsn_from_seq;
1385 struct gtphub_peer_port *sgsn;
1386 if (gtphub_unmap(hub, &p, ggsn,
1387 hub->sgsn_proxy[plane_idx],
1388 &sgsn, &sgsn_from_seq,
1389 NULL /* not interested, got it in &sgsn already */
1390 )
1391 != 0) {
1392 return -1;
1393 }
1394
1395 if (!sgsn) {
1396 /* A GGSN initiated request would go to a known TEI. So this is
1397 * bogus. */
1398 LOGERR("No SGSN to send to. Dropping packet.\n");
1399 return -1;
1400 }
1401
1402 if (plane_idx == GTPH_PLANE_CTRL) {
1403 /* This may be a Create PDP Context response. If it is, there are other
1404 * addresses in the GTP message to set up apart from the sender. */
1405 if (gtphub_handle_pdp_ctx_ies(hub, hub->to_ggsns,
1406 hub->to_sgsns, &p, now)
1407 != 0)
1408 return -1;
1409 }
1410
1411 gtphub_check_restart_counter(hub, &p, ggsn);
1412 gtphub_map_restart_counter(hub, &p, ggsn, sgsn);
1413
1414 /* If the GGSN is replying to an SGSN request, the sequence nr has
1415 * already been unmapped above (sgsn_from_seq != NULL), and we need not
1416 * create a new mapping. */
1417 if (!sgsn_from_seq)
1418 gtphub_map_seq(&p, ggsn, sgsn, now);
1419
1420 osmo_sockaddr_copy(to_addr, &sgsn->sa);
1421 return received;
1422}
1423
1424static int from_sgsns_read_cb(struct osmo_fd *from_sgsns_ofd, unsigned int what)
1425{
1426 unsigned int plane_idx = from_sgsns_ofd->priv_nr;
1427 OSMO_ASSERT(plane_idx < GTPH_PLANE_N);
1428 LOG("\n\n=== reading from SGSN (%s)\n", gtphub_plane_idx_names[plane_idx]);
1429
1430 if (!(what & BSC_FD_READ))
1431 return 0;
1432
1433 struct gtphub *hub = from_sgsns_ofd->data;
1434
1435 static uint8_t buf[4096];
1436 struct osmo_sockaddr from_addr;
1437 struct osmo_sockaddr to_addr;
1438 struct osmo_fd *to_ofd;
1439 size_t len;
1440
1441 len = gtphub_read(from_sgsns_ofd, &from_addr, buf, sizeof(buf));
1442 if (len < 1)
1443 return 0;
1444
1445 len = gtphub_from_sgsns_handle_buf(hub, plane_idx, &from_addr, buf, len,
1446 gtphub_now(),
1447 &to_ofd, &to_addr);
1448 if (len < 1)
1449 return 0;
1450
1451 return gtphub_write(to_ofd, &to_addr, buf, len);
1452}
1453
1454/* Analogous to gtphub_from_ggsns_handle_buf(), see the comment there. */
1455int gtphub_from_sgsns_handle_buf(struct gtphub *hub,
1456 unsigned int plane_idx,
1457 const struct osmo_sockaddr *from_addr,
1458 uint8_t *buf,
1459 size_t received,
1460 time_t now,
1461 struct osmo_fd **to_ofd,
1462 struct osmo_sockaddr *to_addr)
1463{
1464 LOG("-> rx from SGSN %s\n", osmo_sockaddr_to_str(from_addr));
1465
1466 *to_ofd = &hub->to_ggsns[plane_idx].ofd;
1467
1468 static struct gtp_packet_desc p;
1469 gtp_decode(buf, received, plane_idx, &p);
1470
1471 if (p.rc <= 0)
1472 return -1;
1473
1474 int rc;
1475 rc = gtphub_handle_echo(&p);
1476 if (rc == 1) {
1477 /* It was en echo. Nothing left to do. */
1478 /* (*to_ofd already set above.) */
1479 osmo_sockaddr_copy(to_addr, from_addr);
1480 return 0;
1481 }
1482 if (rc < 0)
1483 return -1; /* Invalid packet. */
1484
1485 /* If an SGSN proxy is configured, check that it's indeed that proxy
1486 * talking to us. A proxy is a forced 1:1 connection, e.g. to another
1487 * gtphub, so no-one else is allowed to talk to us from that side. */
1488 struct gtphub_peer_port *sgsn = hub->sgsn_proxy[plane_idx];
1489 if (sgsn) {
1490 if (osmo_sockaddr_cmp(&sgsn->sa, from_addr) != 0) {
1491 LOGERR("Rejecting: GGSN proxy configured, but GTP packet"
1492 " received on GGSN bind is from another sender:"
1493 " proxy: %s sender: %s\n",
1494 gtphub_port_str(sgsn),
1495 osmo_sockaddr_to_str(from_addr));
1496 return -1;
1497 }
1498 }
1499
1500 if (!sgsn) {
1501 /* If any contact has been made before, we already have an
1502 * entry for this SGSN. */
1503 sgsn = gtphub_port_find_sa(&hub->to_sgsns[plane_idx], from_addr);
1504 }
1505
1506 if (!sgsn) {
1507 /* A new peer. If this is on the Ctrl plane, an SGSN may make
1508 * first contact without being known yet, so create the peer
1509 * struct for the current sender. */
1510 if (plane_idx != GTPH_PLANE_CTRL) {
1511 LOGERR("User plane peer was not announced by PDP Context, discarding: %s\n",
1512 osmo_sockaddr_to_str(from_addr));
1513 return -1;
1514 }
1515
1516 struct gsn_addr from_gsna;
1517 uint16_t from_port;
1518 if (gsn_addr_from_sockaddr(&from_gsna, &from_port, from_addr) != 0)
1519 return -1;
1520
1521 sgsn = gtphub_port_have(hub, &hub->to_sgsns[plane_idx],
1522 &from_gsna, from_port);
1523 }
1524
1525 if (!sgsn) {
1526 /* This could theoretically happen for invalid address data or somesuch. */
1527 LOGERR("Invalid SGSN peer. Dropping packet.\n");
1528 return -1;
1529 }
1530 LOG("SGSN peer: %s\n", gtphub_port_str(sgsn));
1531
1532 struct gtphub_peer_port *ggsn_from_seq;
1533 struct gtphub_peer_port *ggsn;
1534 if (gtphub_unmap(hub, &p, sgsn,
1535 hub->ggsn_proxy[plane_idx],
1536 &ggsn, &ggsn_from_seq,
1537 NULL /* not interested, got it in &ggsn already */
1538 )
1539 != 0) {
1540 return -1;
1541 }
1542
1543 /* See what our GGSN guess would be from the packet data per se. */
1544 /* TODO maybe not do this always? */
1545 struct gtphub_peer_port *ggsn_from_packet;
1546 ggsn_from_packet = gtphub_resolve_ggsn(hub, &p);
1547
1548 if (ggsn_from_packet && ggsn
1549 && (ggsn_from_packet != ggsn)) {
1550 LOGERR("GGSN implied from packet does not match unmapped"
1551 " GGSN, using unmapped GGSN:"
1552 " from packet: %s unmapped: %s\n",
1553 gtphub_port_str(ggsn_from_packet),
1554 gtphub_port_str2(ggsn));
1555 /* TODO return -1; ? */
1556 }
1557
1558 if (!ggsn)
1559 ggsn = ggsn_from_packet;
1560
1561 if (!ggsn) {
1562 LOGERR("No GGSN to send to. Dropping packet.\n");
1563 return -1;
1564 }
1565
1566 if (plane_idx == GTPH_PLANE_CTRL) {
1567 /* This may be a Create PDP Context requst. If it is, there are other
1568 * addresses in the GTP message to set up apart from the sender. */
1569 if (gtphub_handle_pdp_ctx_ies(hub, hub->to_sgsns,
1570 hub->to_ggsns, &p, now)
1571 != 0)
1572 return -1;
1573 }
1574
1575 gtphub_check_restart_counter(hub, &p, sgsn);
1576 gtphub_map_restart_counter(hub, &p, sgsn, ggsn);
1577
1578 /* If the SGSN is replying to a GGSN request, the sequence nr has
1579 * already been unmapped above (unmap_ggsn != NULL), and we need not
1580 * create a new outgoing sequence map. */
1581 if (!ggsn_from_seq)
1582 gtphub_map_seq(&p, sgsn, ggsn, now);
1583
1584 osmo_sockaddr_copy(to_addr, &ggsn->sa);
1585
1586 return received;
1587}
1588
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001589static void resolved_gssn_del_cb(struct expiring_item *expi)
1590{
1591 struct gtphub_resolved_ggsn *ggsn;
1592 ggsn = container_of(expi, struct gtphub_resolved_ggsn, expiry_entry);
1593
1594 gtphub_port_ref_count_dec(ggsn->peer);
1595 llist_del(&ggsn->entry);
1596
1597 ggsn->expiry_entry.del_cb = 0;
1598 expiring_item_del(&ggsn->expiry_entry);
1599
1600 talloc_free(ggsn);
1601}
1602
1603void gtphub_resolved_ggsn(struct gtphub *hub, const char *apn_oi_str,
1604 struct gsn_addr *resolved_addr,
1605 time_t now)
1606{
1607 struct gtphub_peer_port *pp;
1608 struct gtphub_resolved_ggsn *ggsn;
1609
1610 pp = gtphub_port_have(hub, &hub->to_ggsns[GTPH_PLANE_CTRL],
1611 resolved_addr, 2123);
1612 if (!pp) {
1613 LOGERR("Internal: Cannot create/find peer '%s'\n",
1614 gsn_addr_to_str(resolved_addr));
1615 return;
1616 }
1617
1618 ggsn = talloc_zero(osmo_gtphub_ctx, struct gtphub_resolved_ggsn);
1619 OSMO_ASSERT(ggsn);
1620
1621 ggsn->peer = pp;
1622 gtphub_port_ref_count_inc(pp);
1623
1624 strncpy(ggsn->apn_oi_str, apn_oi_str, sizeof(ggsn->apn_oi_str));
1625
1626 ggsn->expiry_entry.del_cb = resolved_gssn_del_cb;
1627 expiry_add(&hub->expire_tei_maps, &ggsn->expiry_entry, now);
1628
1629 llist_add(&ggsn->entry, &hub->resolved_ggsns);
1630}
1631
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001632static int gtphub_gc_peer_port(struct gtphub_peer_port *pp)
1633{
1634 return pp->ref_count == 0;
1635}
1636
1637static int gtphub_gc_peer_addr(struct gtphub_peer_addr *pa)
1638{
1639 struct gtphub_peer_port *pp, *npp;
1640 llist_for_each_entry_safe(pp, npp, &pa->ports, entry) {
1641 if (gtphub_gc_peer_port(pp)) {
1642 LOG("expired: peer %s\n",
1643 gtphub_port_str(pp));
1644 gtphub_peer_port_del(pp);
1645 }
1646 }
1647 return llist_empty(&pa->ports);
1648}
1649
1650static int gtphub_gc_peer(struct gtphub_peer *p)
1651{
1652 struct gtphub_peer_addr *pa, *npa;
1653 llist_for_each_entry_safe(pa, npa, &p->addresses, entry) {
1654 if (gtphub_gc_peer_addr(pa)) {
1655 gtphub_peer_addr_del(pa);
1656 }
1657 }
1658
1659 /* Note that there's a ref_count in each gtphub_peer_port instance
1660 * listed within p->addresses, referenced by TEI mappings from
1661 * hub->tei_map. As long as those don't expire, this peer will stay. */
1662
1663 LOG("gc peer %p llist_empty %d seq_map_empty %d\n", p,
1664 (int)llist_empty(&p->addresses), (int) nr_map_empty(&p->seq_map));
1665 if (! nr_map_empty(&p->seq_map)) {
1666 printf("not empty\n");
1667 struct nr_mapping *nrm;
1668 llist_for_each_entry(nrm, &p->seq_map.mappings, entry) {
1669 printf("%p %s %d -> %d\n",
1670 nrm->origin, gtphub_port_str(nrm->origin),nrm->orig, nrm->repl);
1671 }
1672 }
1673 return llist_empty(&p->addresses)
1674 && nr_map_empty(&p->seq_map);
1675}
1676
1677static void gtphub_gc_bind(struct gtphub_bind *b)
1678{
1679 struct gtphub_peer *p, *n;
1680 llist_for_each_entry_safe(p, n, &b->peers, entry) {
1681 if (gtphub_gc_peer(p)) {
1682 gtphub_peer_del(p);
1683 }
1684 }
1685}
1686
1687void gtphub_gc(struct gtphub *hub, time_t now)
1688{
1689 int expired;
1690 expired = expiry_tick(&hub->expire_seq_maps, now);
1691 expired += expiry_tick(&hub->expire_tei_maps, now);
1692
1693 /* ... */
1694
1695 if (expired) {
1696 int i;
1697 for (i = 0; i < GTPH_PLANE_N; i++) {
1698 gtphub_gc_bind(&hub->to_sgsns[i]);
1699 gtphub_gc_bind(&hub->to_ggsns[i]);
1700 }
1701 }
1702}
1703
1704static void gtphub_gc_cb(void *data)
1705{
1706 struct gtphub *hub = data;
1707 gtphub_gc(hub, gtphub_now());
1708 osmo_timer_schedule(&hub->gc_timer, GTPH_GC_TICK_SECONDS, 0);
1709}
1710
1711static void gtphub_gc_start(struct gtphub *hub)
1712{
1713 hub->gc_timer.cb = gtphub_gc_cb;
1714 hub->gc_timer.data = hub;
1715
1716 osmo_timer_schedule(&hub->gc_timer, GTPH_GC_TICK_SECONDS, 0);
1717}
1718
1719/* called by unit tests */
1720void gtphub_init(struct gtphub *hub)
1721{
1722 gtphub_zero(hub);
1723
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001724 INIT_LLIST_HEAD(&hub->resolved_ggsns);
1725
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001726 expiry_init(&hub->expire_seq_maps, GTPH_SEQ_MAPPING_EXPIRY_SECS);
1727 expiry_init(&hub->expire_tei_maps, GTPH_TEI_MAPPING_EXPIRY_MINUTES * 60);
1728
1729 int plane_idx;
1730 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1731 nr_pool_init(&hub->tei_pool[plane_idx]);
1732 nr_map_init(&hub->tei_map[plane_idx],
1733 &hub->tei_pool[plane_idx],
1734 &hub->expire_tei_maps);
1735
1736 gtphub_bind_init(&hub->to_ggsns[plane_idx]);
1737 gtphub_bind_init(&hub->to_sgsns[plane_idx]);
1738 }
1739}
1740
1741static int gtphub_make_proxy(struct gtphub *hub,
1742 struct gtphub_peer_port **pp,
1743 struct gtphub_bind *bind,
1744 const struct gtphub_cfg_addr *addr)
1745{
1746 if (!addr->addr_str)
1747 return 0;
1748
1749 struct gsn_addr gsna;
1750 if (gsn_addr_from_str(&gsna, addr->addr_str) != 0)
1751 return -1;
1752
1753 *pp = gtphub_port_have(hub, bind, &gsna, addr->port);
1754
1755 /* This is *the* proxy. Make sure it is never expired. */
1756 gtphub_port_ref_count_inc(*pp);
1757 return 0;
1758}
1759
1760int gtphub_start(struct gtphub *hub, struct gtphub_cfg *cfg)
1761{
1762 int rc;
1763
1764 gtphub_init(hub);
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001765 gtphub_ares_init(hub);
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001766
1767 int plane_idx;
1768 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1769 rc = gtphub_bind_start(&hub->to_ggsns[plane_idx],
1770 &cfg->to_ggsns[plane_idx],
1771 from_ggsns_read_cb, hub, plane_idx);
1772 if (rc) {
1773 LOGERR("Failed to bind for GGSNs (%s)\n",
1774 gtphub_plane_idx_names[plane_idx]);
1775 return rc;
1776 }
1777
1778 rc = gtphub_bind_start(&hub->to_sgsns[plane_idx],
1779 &cfg->to_sgsns[plane_idx],
1780 from_sgsns_read_cb, hub, plane_idx);
1781 if (rc) {
1782 LOGERR("Failed to bind for SGSNs (%s)\n",
1783 gtphub_plane_idx_names[plane_idx]);
1784 return rc;
1785 }
1786 }
1787
1788
1789 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1790 if (gtphub_make_proxy(hub,
1791 &hub->sgsn_proxy[plane_idx],
1792 &hub->to_sgsns[plane_idx],
1793 &cfg->sgsn_proxy[plane_idx])
1794 != 0) {
1795 LOGERR("Cannot configure SGSN proxy %s port %d.\n",
1796 cfg->sgsn_proxy[plane_idx].addr_str,
1797 (int)cfg->sgsn_proxy[plane_idx].port);
1798 return -1;
1799 }
1800 if (gtphub_make_proxy(hub,
1801 &hub->ggsn_proxy[plane_idx],
1802 &hub->to_ggsns[plane_idx],
1803 &cfg->ggsn_proxy[plane_idx])
1804 != 0) {
1805 LOGERR("Cannot configure GGSN proxy.\n");
1806 return -1;
1807 }
1808 }
1809
1810 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1811 if (hub->sgsn_proxy[plane_idx])
1812 LOG("Using SGSN %s proxy %s\n",
1813 gtphub_plane_idx_names[plane_idx],
1814 gtphub_port_str(hub->sgsn_proxy[plane_idx]));
1815 }
1816
1817 for (plane_idx = 0; plane_idx < GTPH_PLANE_N; plane_idx++) {
1818 if (hub->sgsn_proxy[plane_idx])
1819 LOG("Using GGSN %s proxy %s\n",
1820 gtphub_plane_idx_names[plane_idx],
1821 gtphub_port_str(hub->ggsn_proxy[plane_idx]));
1822 }
1823
1824 gtphub_gc_start(hub);
1825 return 0;
1826}
1827
1828static struct gtphub_peer_addr *gtphub_peer_find_addr(const struct gtphub_peer *peer,
1829 const struct gsn_addr *addr)
1830{
1831 struct gtphub_peer_addr *a;
1832 llist_for_each_entry(a, &peer->addresses, entry) {
1833 if (gsn_addr_same(&a->addr, addr))
1834 return a;
1835 }
1836 return NULL;
1837}
1838
1839static struct gtphub_peer_port *gtphub_addr_find_port(const struct gtphub_peer_addr *a,
1840 uint16_t port)
1841{
1842 OSMO_ASSERT(port);
1843 struct gtphub_peer_port *pp;
1844 llist_for_each_entry(pp, &a->ports, entry) {
1845 if (pp->port == port)
1846 return pp;
1847 }
1848 return NULL;
1849}
1850
1851static struct gtphub_peer_addr *gtphub_addr_find(const struct gtphub_bind *bind,
1852 const struct gsn_addr *addr)
1853{
1854 struct gtphub_peer *peer;
1855 llist_for_each_entry(peer, &bind->peers, entry) {
1856 struct gtphub_peer_addr *a = gtphub_peer_find_addr(peer, addr);
1857 if (a)
1858 return a;
1859 }
1860 return NULL;
1861}
1862
1863static struct gtphub_peer_port *gtphub_port_find(const struct gtphub_bind *bind,
1864 const struct gsn_addr *addr,
1865 uint16_t port)
1866{
1867 struct gtphub_peer_addr *a = gtphub_addr_find(bind, addr);
1868 if (!a)
1869 return NULL;
1870 return gtphub_addr_find_port(a, port);
1871}
1872
1873struct gtphub_peer_port *gtphub_port_find_sa(const struct gtphub_bind *bind,
1874 const struct osmo_sockaddr *addr)
1875{
1876 struct gsn_addr gsna;
1877 uint16_t port;
1878 gsn_addr_from_sockaddr(&gsna, &port, addr);
1879 return gtphub_port_find(bind, &gsna, port);
1880}
1881
1882static struct gtphub_peer *gtphub_peer_new(struct gtphub *hub,
1883 struct gtphub_bind *bind)
1884{
1885 struct gtphub_peer *peer = talloc_zero(osmo_gtphub_ctx, struct gtphub_peer);
1886 OSMO_ASSERT(peer);
1887
1888 INIT_LLIST_HEAD(&peer->addresses);
1889
1890 nr_pool_init(&peer->seq_pool);
1891 nr_map_init(&peer->seq_map, &peer->seq_pool, &hub->expire_seq_maps);
1892
1893 /* TODO use something random to pick the initial sequence nr.
1894 0x6d31 produces the ASCII character sequence 'm1', currently used in
1895 gtphub_nc_test.sh. */
1896 peer->seq_pool.last_nr = 0x6d31 - 1;
1897
1898 llist_add(&peer->entry, &bind->peers);
1899 return peer;
1900}
1901
1902static struct gtphub_peer_addr *gtphub_peer_add_addr(struct gtphub_peer *peer,
1903 const struct gsn_addr *addr)
1904{
1905 struct gtphub_peer_addr *a;
1906 a = talloc_zero(osmo_gtphub_ctx, struct gtphub_peer_addr);
1907 OSMO_ASSERT(a);
1908 a->peer = peer;
1909 gsn_addr_copy(&a->addr, addr);
1910 INIT_LLIST_HEAD(&a->ports);
1911 llist_add(&a->entry, &peer->addresses);
1912
1913 return a;
1914}
1915
1916static struct gtphub_peer_addr *gtphub_addr_have(struct gtphub *hub,
1917 struct gtphub_bind *bind,
1918 const struct gsn_addr *addr)
1919{
1920 struct gtphub_peer_addr *a = gtphub_addr_find(bind, addr);
1921 if (a)
1922 return a;
1923
1924 /* If we haven't found an address, that means we need to create an
1925 * entirely new peer for the new address. More addresses may be added
1926 * to this peer later, but not via this function. */
1927 struct gtphub_peer *peer = gtphub_peer_new(hub, bind);
1928 return gtphub_peer_add_addr(peer, addr);
1929}
1930
1931static struct gtphub_peer_port *gtphub_addr_add_port(struct gtphub_peer_addr *a,
1932 uint16_t port)
1933{
1934 struct gtphub_peer_port *pp;
1935
1936 pp = talloc_zero(osmo_gtphub_ctx, struct gtphub_peer_port);
1937 OSMO_ASSERT(pp);
1938 pp->peer_addr = a;
1939 pp->port = port;
1940
1941 if (gsn_addr_to_sockaddr(&a->addr, port, &pp->sa) != 0) {
1942 talloc_free(pp);
1943 return NULL;
1944 }
1945
1946 llist_add(&pp->entry, &a->ports);
1947
1948 LOG("New peer: %s port %d\n",
1949 gsn_addr_to_str(&a->addr),
1950 (int)port);
1951
1952 return pp;
1953}
1954
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001955struct gtphub_peer_port *gtphub_port_have(struct gtphub *hub,
1956 struct gtphub_bind *bind,
1957 const struct gsn_addr *addr,
1958 uint16_t port)
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001959{
1960 struct gtphub_peer_addr *a = gtphub_addr_have(hub, bind, addr);
1961
1962 struct gtphub_peer_port *pp = gtphub_addr_find_port(a, port);
1963 if (pp)
1964 return pp;
1965
1966 return gtphub_addr_add_port(a, port);
1967}
1968
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001969static struct gtphub_peer_port *gtphub_resolve_ggsn(struct gtphub *hub,
1970 struct gtp_packet_desc *p)
1971{
Neels Hofmeyr30f7bcb2015-11-08 20:34:47 +01001972 return gtphub_resolve_ggsn_addr(hub,
1973 get_ie_imsi_str(p->ie, 0),
1974 get_ie_apn_str(p->ie));
Neels Hofmeyrc8a614d2015-09-24 17:32:30 +02001975}
1976
1977
1978/* TODO move to osmocom/core/socket.c ? */
1979/* The caller is required to call freeaddrinfo(*result), iff zero is returned. */
1980/* use this in osmo_sock_init() to remove dup. */
1981static int _osmo_getaddrinfo(struct addrinfo **result,
1982 uint16_t family, uint16_t type, uint8_t proto,
1983 const char *host, uint16_t port)
1984{
1985 struct addrinfo hints;
1986 char portbuf[16];
1987
1988 sprintf(portbuf, "%u", port);
1989 memset(&hints, '\0', sizeof(struct addrinfo));
1990 hints.ai_family = family;
1991 if (type == SOCK_RAW) {
1992 /* Workaround for glibc, that returns EAI_SERVICE (-8) if
1993 * SOCK_RAW and IPPROTO_GRE is used.
1994 */
1995 hints.ai_socktype = SOCK_DGRAM;
1996 hints.ai_protocol = IPPROTO_UDP;
1997 } else {
1998 hints.ai_socktype = type;
1999 hints.ai_protocol = proto;
2000 }
2001
2002 return getaddrinfo(host, portbuf, &hints, result);
2003}
2004
2005/* TODO move to osmocom/core/socket.c ? */
2006int osmo_sockaddr_init(struct osmo_sockaddr *addr,
2007 uint16_t family, uint16_t type, uint8_t proto,
2008 const char *host, uint16_t port)
2009{
2010 struct addrinfo *res;
2011 int rc;
2012 rc = _osmo_getaddrinfo(&res, family, type, proto, host, port);
2013
2014 if (rc != 0) {
2015 LOGERR("getaddrinfo returned error %d\n", (int)rc);
2016 return -EINVAL;
2017 }
2018
2019 OSMO_ASSERT(res->ai_addrlen <= sizeof(addr->a));
2020 memcpy(&addr->a, res->ai_addr, res->ai_addrlen);
2021 addr->l = res->ai_addrlen;
2022 freeaddrinfo(res);
2023
2024 return 0;
2025}
2026
2027int osmo_sockaddr_to_strs(char *addr_str, size_t addr_str_len,
2028 char *port_str, size_t port_str_len,
2029 const struct osmo_sockaddr *addr,
2030 int flags)
2031{
2032 int rc;
2033
2034 if ((addr->l < 1) || (addr->l > sizeof(addr->a))) {
2035 LOGP(DGTPHUB, LOGL_ERROR, "Invalid address size: %d\n", addr->l);
2036 return -1;
2037 }
2038
2039 if (addr->l > sizeof(addr->a)) {
2040 LOGP(DGTPHUB, LOGL_ERROR, "Invalid address: too long: %d\n", addr->l);
2041 return -1;
2042 }
2043
2044 rc = getnameinfo((struct sockaddr*)&addr->a, addr->l,
2045 addr_str, addr_str_len,
2046 port_str, port_str_len,
2047 flags);
2048
2049 if (rc)
2050 LOGP(DGTPHUB, LOGL_ERROR, "Invalid address: %s: %s\n", gai_strerror(rc),
2051 osmo_hexdump((uint8_t*)&addr->a, addr->l));
2052
2053 return rc;
2054}
2055
2056const char *osmo_sockaddr_to_strb(const struct osmo_sockaddr *addr,
2057 char *buf, size_t buf_len)
2058{
2059 const int portbuf_len = 6;
2060 OSMO_ASSERT(buf_len > portbuf_len);
2061 char *portbuf = buf + buf_len - portbuf_len;
2062 buf_len -= portbuf_len;
2063 if (osmo_sockaddr_to_strs(buf, buf_len,
2064 portbuf, portbuf_len,
2065 addr,
2066 NI_NUMERICHOST | NI_NUMERICSERV))
2067 return NULL;
2068
2069 char *pos = buf + strnlen(buf, buf_len-1);
2070 size_t len = buf_len - (pos - buf);
2071
2072 snprintf(pos, len, " port %s", portbuf);
2073 buf[buf_len-1] = '\0';
2074
2075 return buf;
2076}
2077
2078const char *osmo_sockaddr_to_str(const struct osmo_sockaddr *addr)
2079{
2080 static char buf[256];
2081 const char *result = osmo_sockaddr_to_strb(addr, buf, sizeof(buf));
2082 if (! result)
2083 return "(invalid)";
2084 return result;
2085}
2086
2087int osmo_sockaddr_cmp(const struct osmo_sockaddr *a, const struct osmo_sockaddr *b)
2088{
2089 if (a == b)
2090 return 0;
2091 if (!a)
2092 return -1;
2093 if (!b)
2094 return 1;
2095 if (a->l != b->l) {
2096 /* Lengths are not the same, but determine the order. Will
2097 * anyone ever sort a list by osmo_sockaddr though...? */
2098 int cmp = memcmp(&a->a, &b->a, (a->l < b->l)? a->l : b->l);
2099 if (cmp == 0) {
2100 if (a->l < b->l)
2101 return -1;
2102 else
2103 return 1;
2104 }
2105 return cmp;
2106 }
2107 return memcmp(&a->a, &b->a, a->l);
2108}
2109
2110void osmo_sockaddr_copy(struct osmo_sockaddr *dst, const struct osmo_sockaddr *src)
2111{
2112 OSMO_ASSERT(src->l <= sizeof(dst->a));
2113 memcpy(&dst->a, &src->a, src->l);
2114 dst->l = src->l;
2115}