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