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