-
Notifications
You must be signed in to change notification settings - Fork 0
/
edge_utils.c
2409 lines (1928 loc) · 71.7 KB
/
edge_utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* (C) 2007-18 - ntop.org and contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not see see <http://www.gnu.org/licenses/>
*
*/
#include "n2n.h"
#include "lzoconf.h"
#ifdef WIN32
#include <process.h>
/* Multicast peers discovery disabled due to https://github.com/ntop/n2n/issues/65 */
#define SKIP_MULTICAST_PEERS_DISCOVERY
#endif
#ifdef __ANDROID_NDK__
#include "android/edge_android.h"
#include <tun2tap/tun2tap.h>
#endif /* __ANDROID_NDK__ */
#define SOCKET_TIMEOUT_INTERVAL_SECS 10
#define REGISTER_SUPER_INTERVAL_DFL 20 /* sec, usually UDP NAT entries in a firewall expire after 30 seconds */
#define IFACE_UPDATE_INTERVAL (30) /* sec. How long it usually takes to get an IP lease. */
#define TRANSOP_TICK_INTERVAL (10) /* sec */
#ifdef __ANDROID_NDK__
#define ARP_PERIOD_INTERVAL (10) /* sec */
#endif
#ifdef __linux__
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#endif
#define ETH_FRAMESIZE 14
#define IP4_SRCOFFSET 12
#define IP4_DSTOFFSET 16
#define IP4_MIN_SIZE 20
#define UDP_SIZE 8
/* heap allocation for compression as per lzo example doc */
#define HEAP_ALLOC(var,size) lzo_align_t __LZO_MMODEL var [ ((size) + (sizeof(lzo_align_t) - 1)) / sizeof(lzo_align_t) ]
static HEAP_ALLOC(wrkmem, LZO1X_1_MEM_COMPRESS);
/* ************************************** */
static const char * supernode_ip(const n2n_edge_t * eee);
static void send_register(n2n_edge_t *eee, const n2n_sock_t *remote_peer, const n2n_mac_t peer_mac);
static void check_peer_registration_needed(n2n_edge_t * eee,
uint8_t from_supernode,
const n2n_mac_t mac,
const n2n_sock_t * peer);
static int edge_init_sockets(n2n_edge_t *eee, int udp_local_port, int mgmt_port, uint8_t tos);
static int edge_init_routes(n2n_edge_t *eee, n2n_route_t *routes, uint16_t num_routes);
static void edge_cleanup_routes(n2n_edge_t *eee);
static int supernode2addr(n2n_sock_t * sn, const n2n_sn_name_t addrIn);
static void check_known_peer_sock_change(n2n_edge_t * eee,
uint8_t from_supernode,
const n2n_mac_t mac,
const n2n_sock_t * peer,
time_t when);
/* ************************************** */
int edge_verify_conf(const n2n_edge_conf_t *conf) {
if(conf->community_name[0] == 0)
return(-1);
if(conf->sn_num == 0)
return(-2);
if(conf->register_interval < 1)
return(-3);
if(((conf->encrypt_key == NULL) && (conf->transop_id != N2N_TRANSFORM_ID_NULL)) ||
((conf->encrypt_key != NULL) && (conf->transop_id == N2N_TRANSFORM_ID_NULL)))
return(-4);
return(0);
}
/* ************************************** */
struct n2n_edge_stats {
uint32_t tx_p2p;
uint32_t rx_p2p;
uint32_t tx_sup;
uint32_t rx_sup;
uint32_t tx_sup_broadcast;
uint32_t rx_sup_broadcast;
};
/* ************************************** */
struct n2n_edge {
n2n_edge_conf_t conf;
/* Status */
uint8_t sn_idx; /**< Currently active supernode. */
uint8_t sn_wait; /**< Whether we are waiting for a supernode response. */
size_t sup_attempts; /**< Number of remaining attempts to this supernode. */
tuntap_dev device; /**< All about the TUNTAP device */
n2n_trans_op_t transop; /**< The transop to use when encoding */
n2n_cookie_t last_cookie; /**< Cookie sent in last REGISTER_SUPER. */
n2n_route_t *sn_route_to_clean; /**< Supernode route to clean */
/* Sockets */
n2n_sock_t supernode;
int udp_sock;
int udp_mgmt_sock; /**< socket for status info. */
#ifndef SKIP_MULTICAST_PEERS_DISCOVERY
n2n_sock_t multicast_peer; /**< Multicast peer group (for local edges) */
int udp_multicast_sock; /**< socket for local multicast registrations. */
int multicast_joined; /**< 1 if the group has been joined.*/
#endif
/* Peers */
struct peer_info * known_peers; /**< Edges we are connected to. */
struct peer_info * pending_peers; /**< Edges we have tried to register with. */
/* Timers */
time_t last_register_req; /**< Check if time to re-register with super*/
time_t last_p2p; /**< Last time p2p traffic was received. */
time_t last_sup; /**< Last time a packet arrived from supernode. */
time_t start_time; /**< For calculating uptime */
/* Statistics */
struct n2n_edge_stats stats;
};
/* ************************************** */
static const char* transop_str(enum n2n_transform tr) {
switch(tr) {
case N2N_TRANSFORM_ID_NULL: return("null");
case N2N_TRANSFORM_ID_TWOFISH: return("twofish");
case N2N_TRANSFORM_ID_AESCBC: return("AES-CBC");
default: return("invalid");
};
}
/* ************************************** */
/** Destination 01:00:5E:00:00:00 - 01:00:5E:7F:FF:FF is multicast ethernet.
*/
static int is_ethMulticast(const void * buf, size_t bufsize) {
int retval = 0;
/* Match 01:00:5E:00:00:00 - 01:00:5E:7F:FF:FF */
if(bufsize >= sizeof(ether_hdr_t)) {
/* copy to aligned memory */
ether_hdr_t eh;
memcpy(&eh, buf, sizeof(ether_hdr_t));
if((0x01 == eh.dhost[0]) &&
(0x00 == eh.dhost[1]) &&
(0x5E == eh.dhost[2]) &&
(0 == (0x80 & eh.dhost[3])))
retval = 1; /* This is an ethernet multicast packet [RFC1112]. */
}
return retval;
}
/* ************************************** */
/** Destination MAC 33:33:0:00:00:00 - 33:33:FF:FF:FF:FF is reserved for IPv6
* neighbour discovery.
*/
static int is_ip6_discovery(const void * buf, size_t bufsize) {
int retval = 0;
if(bufsize >= sizeof(ether_hdr_t)) {
/* copy to aligned memory */
ether_hdr_t eh;
memcpy(&eh, buf, sizeof(ether_hdr_t));
if((0x33 == eh.dhost[0]) && (0x33 == eh.dhost[1]))
retval = 1; /* This is an IPv6 multicast packet [RFC2464]. */
}
return retval;
}
/* ************************************** */
/** Initialise an edge to defaults.
*
* This also initialises the NULL transform operation opstruct.
*/
n2n_edge_t* edge_init(const tuntap_dev *dev, const n2n_edge_conf_t *conf, int *rv) {
n2n_transform_t transop_id = conf->transop_id;
n2n_edge_t *eee = calloc(1, sizeof(n2n_edge_t));
int rc = -1, i;
if((rc = edge_verify_conf(conf)) != 0) {
traceEvent(TRACE_ERROR, "Invalid configuration");
goto edge_init_error;
}
if(!eee) {
traceEvent(TRACE_ERROR, "Cannot allocate memory");
goto edge_init_error;
}
#ifdef WIN32
initWin32();
#endif
memcpy(&eee->conf, conf, sizeof(*conf));
memcpy(&eee->device, dev, sizeof(*dev));
eee->start_time = time(NULL);
eee->known_peers = NULL;
eee->pending_peers = NULL;
eee->sup_attempts = N2N_EDGE_SUP_ATTEMPTS;
if(lzo_init() != LZO_E_OK) {
traceEvent(TRACE_ERROR, "LZO compression error");
goto edge_init_error;
}
for(i=0; i<conf->sn_num; ++i)
traceEvent(TRACE_NORMAL, "supernode %u => %s\n", i, (conf->sn_ip_array[i]));
/* Set the active supernode */
supernode2addr(&(eee->supernode), conf->sn_ip_array[eee->sn_idx]);
/* Set active transop */
switch(transop_id) {
case N2N_TRANSFORM_ID_TWOFISH:
rc = n2n_transop_twofish_init(&eee->conf, &eee->transop);
break;
#ifdef N2N_HAVE_AES
case N2N_TRANSFORM_ID_AESCBC:
rc = n2n_transop_aes_cbc_init(&eee->conf, &eee->transop);
break;
#endif
default:
rc = n2n_transop_null_init(&eee->conf, &eee->transop);
}
if((rc < 0) || (eee->transop.fwd == NULL) || (eee->transop.transform_id != transop_id)) {
traceEvent(TRACE_ERROR, "Transop init failed");
goto edge_init_error;
}
if(eee->transop.no_encryption)
traceEvent(TRACE_WARNING, "Encryption is disabled in edge");
if(edge_init_sockets(eee, conf->local_port, conf->mgmt_port, conf->tos) < 0) {
traceEvent(TRACE_ERROR, "socket setup failed");
goto edge_init_error;
}
if(edge_init_routes(eee, conf->routes, conf->num_routes) < 0) {
traceEvent(TRACE_ERROR, "routes setup failed");
goto edge_init_error;
}
//edge_init_success:
*rv = 0;
return(eee);
edge_init_error:
if(eee)
free(eee);
*rv = rc;
return(NULL);
}
/* ************************************** */
static int find_and_remove_peer(struct peer_info **head, const n2n_mac_t mac) {
struct peer_info *peer;
HASH_FIND_PEER(*head, mac, peer);
if(peer) {
HASH_DEL(*head, peer);
free(peer);
return(1);
}
return(0);
}
/* ************************************** */
static uint32_t localhost_v4 = 0x7f000001;
static uint8_t localhost_v6[IPV6_SIZE] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
/* Exclude localhost as it may be received when an edge node runs
* in the same supernode host.
*/
static int is_valid_peer_sock(const n2n_sock_t *sock) {
if(((sock->family == AF_INET) && (*((uint32_t*)sock->addr.v4) != htonl(localhost_v4)))
|| ((sock->family == AF_INET6) && memcmp(sock->addr.v6, localhost_v6, IPV6_SIZE)))
return(1);
return(0);
}
/* ***************************************************** */
/** Resolve the supernode IP address.
*
* REVISIT: This is a really bad idea. The edge will block completely while the
* hostname resolution is performed. This could take 15 seconds.
*/
static int supernode2addr(n2n_sock_t * sn, const n2n_sn_name_t addrIn) {
n2n_sn_name_t addr;
const char *supernode_host;
int rv = 0;
memcpy(addr, addrIn, N2N_EDGE_SN_HOST_SIZE);
supernode_host = strtok(addr, ":");
if(supernode_host) {
in_addr_t sn_addr;
char *supernode_port = strtok(NULL, ":");
const struct addrinfo aihints = {0, PF_INET, 0, 0, 0, NULL, NULL, NULL};
struct addrinfo * ainfo = NULL;
int nameerr;
if(supernode_port)
sn->port = atoi(supernode_port);
else
traceEvent(TRACE_WARNING, "Bad supernode parameter (-l <host:port>) %s %s:%s",
addr, supernode_host, supernode_port);
nameerr = getaddrinfo(supernode_host, NULL, &aihints, &ainfo);
if(0 == nameerr)
{
struct sockaddr_in * saddr;
/* ainfo s the head of a linked list if non-NULL. */
if(ainfo && (PF_INET == ainfo->ai_family))
{
/* It is definitely and IPv4 address -> sockaddr_in */
saddr = (struct sockaddr_in *)ainfo->ai_addr;
memcpy(sn->addr.v4, &(saddr->sin_addr.s_addr), IPV4_SIZE);
sn->family=AF_INET;
}
else
{
/* Should only return IPv4 addresses due to aihints. */
traceEvent(TRACE_WARNING, "Failed to resolve supernode IPv4 address for %s", supernode_host);
rv = -1;
}
freeaddrinfo(ainfo); /* free everything allocated by getaddrinfo(). */
ainfo = NULL;
} else {
traceEvent(TRACE_WARNING, "Failed to resolve supernode host %s, assuming numeric", supernode_host);
sn_addr = inet_addr(supernode_host); /* uint32_t */
memcpy(sn->addr.v4, &(sn_addr), IPV4_SIZE);
sn->family=AF_INET;
rv = -2;
}
} else {
traceEvent(TRACE_WARNING, "Wrong supernode parameter (-l <host:port>)");
rv = -3;
}
return(rv);
}
/* ************************************** */
/***
*
* Register over multicast in case there is a peer on the same network listening
*/
static void register_with_local_peers(n2n_edge_t * eee) {
#ifndef SKIP_MULTICAST_PEERS_DISCOVERY
if(eee->multicast_joined && eee->conf.allow_p2p) {
/* send registration to the local multicast group */
traceEvent(TRACE_DEBUG, "Registering with multicast group %s:%u",
N2N_MULTICAST_GROUP, N2N_MULTICAST_PORT);
send_register(eee, &(eee->multicast_peer), NULL);
}
#else
traceEvent(TRACE_DEBUG, "Multicast peers discovery is disabled, skipping");
#endif
}
/* ************************************** */
/** Start the registration process.
*
* If the peer is already in pending_peers, ignore the request.
* If not in pending_peers, add it and send a REGISTER.
*
* If hdr is for a direct peer-to-peer packet, try to register back to sender
* even if the MAC is in pending_peers. This is because an incident direct
* packet indicates that peer-to-peer exchange should work so more aggressive
* registration can be permitted (once per incoming packet) as this should only
* last for a small number of packets..
*
* Called from the main loop when Rx a packet for our device mac.
*/
static void register_with_new_peer(n2n_edge_t * eee,
uint8_t from_supernode,
const n2n_mac_t mac,
const n2n_sock_t * peer) {
/* REVISIT: purge of pending_peers not yet done. */
struct peer_info * scan;
macstr_t mac_buf;
n2n_sock_str_t sockbuf;
HASH_FIND_PEER(eee->pending_peers, mac, scan);
/* NOTE: pending_peers are purged periodically with purge_expired_registrations */
if(scan == NULL) {
scan = calloc(1, sizeof(struct peer_info));
memcpy(scan->mac_addr, mac, N2N_MAC_SIZE);
scan->sock = *peer;
scan->timeout = REGISTER_SUPER_INTERVAL_DFL; /* TODO: should correspond to the peer supernode registration timeout */
scan->last_seen = time(NULL); /* Don't change this it marks the pending peer for removal. */
HASH_ADD_PEER(eee->pending_peers, scan);
traceEvent(TRACE_DEBUG, "=== new pending %s -> %s",
macaddr_str(mac_buf, scan->mac_addr),
sock_to_cstr(sockbuf, &(scan->sock)));
traceEvent(TRACE_DEBUG, "Pending peers list size=%u",
HASH_COUNT(eee->pending_peers));
/* trace Sending REGISTER */
if(from_supernode) {
/* UDP NAT hole punching through supernode. Send to peer first(punch local UDP hole)
* and then ask supernode to forward. Supernode then ask peer to ack. Some nat device
* drop and block ports with incoming UDP packet if out-come traffic does not exist.
* So we can alternatively set TTL so that the packet sent to peer never really reaches
* The register_ttl is basically nat level + 1. Set it to 1 means host like DMZ.
*/
if (eee->conf.register_ttl == 1) {
/* We are DMZ host or port is directly accessible. Just let peer to send back the ack */
#ifndef WIN32
} else if(eee->conf.register_ttl > 1) {
/* Setting register_ttl usually implies that the edge knows the internal net topology
* clearly, we can apply aggressive port prediction to support incoming Symmetric NAT
*/
int curTTL = 0;
socklen_t lenTTL = sizeof(int);
n2n_sock_t sock = scan->sock;
int alter = 16; /* TODO: set by command line or more reliable prediction method */
getsockopt(eee->udp_sock, IPPROTO_IP, IP_TTL, (void *)(char *)&curTTL, &lenTTL);
setsockopt(eee->udp_sock, IPPROTO_IP, IP_TTL,
(void *)(char *)&eee->conf.register_ttl,
sizeof(eee->conf.register_ttl));
for (; alter > 0; alter--, sock.port++)
{
send_register(eee, &sock, mac);
}
setsockopt(eee->udp_sock, IPPROTO_IP, IP_TTL, (void *)(char *)&curTTL, sizeof(curTTL));
#endif
} else { /* eee->conf.register_ttl <= 0 */
/* Normal STUN */
send_register(eee, &(scan->sock), mac);
}
send_register(eee, &(eee->supernode), mac);
} else {
/* P2P register, send directly */
send_register(eee, &(scan->sock), mac);
}
register_with_local_peers(eee);
} else
scan->sock = *peer;
}
/* ************************************** */
/** Update the last_seen time for this peer, or get registered. */
static void check_peer_registration_needed(n2n_edge_t * eee,
uint8_t from_supernode,
const n2n_mac_t mac,
const n2n_sock_t * peer) {
struct peer_info *scan;
HASH_FIND_PEER(eee->known_peers, mac, scan);
if(scan == NULL) {
/* Not in known_peers - start the REGISTER process. */
register_with_new_peer(eee, from_supernode, mac, peer);
} else {
/* Already in known_peers. */
time_t now = time(NULL);
if(!from_supernode)
scan->last_p2p = now;
if((now - scan->last_seen) > 0 /* >= 1 sec */) {
/* Don't register too often */
check_known_peer_sock_change(eee, from_supernode, mac, peer, now);
}
}
}
/* ************************************** */
/* Confirm that a pending peer is reachable directly via P2P.
*
* peer must be a pointer to an element of the pending_peers list.
*/
static void peer_set_p2p_confirmed(n2n_edge_t * eee,
const n2n_mac_t mac,
const n2n_sock_t * peer,
time_t now) {
struct peer_info *scan;
macstr_t mac_buf;
n2n_sock_str_t sockbuf;
HASH_FIND_PEER(eee->pending_peers, mac, scan);
if(scan) {
HASH_DEL(eee->pending_peers, scan);
/* Add scan to known_peers. */
HASH_ADD_PEER(eee->known_peers, scan);
scan->sock = *peer;
scan->last_p2p = now;
traceEvent(TRACE_NORMAL, "P2P connection established: %s [%s]",
macaddr_str(mac_buf, mac),
sock_to_cstr(sockbuf, peer));
traceEvent(TRACE_DEBUG, "=== new peer %s -> %s",
macaddr_str(mac_buf, scan->mac_addr),
sock_to_cstr(sockbuf, &(scan->sock)));
traceEvent(TRACE_DEBUG, "Pending peers list size=%u",
HASH_COUNT(eee->pending_peers));
traceEvent(TRACE_DEBUG, "Known peers list size=%u",
HASH_COUNT(eee->known_peers));
scan->last_seen = now;
} else
traceEvent(TRACE_DEBUG, "Failed to find sender in pending_peers.");
}
/* ************************************** */
int is_empty_ip_address(const n2n_sock_t * sock) {
const uint8_t * ptr=NULL;
size_t len=0;
size_t i;
if(AF_INET6 == sock->family)
{
ptr = sock->addr.v6;
len = 16;
}
else
{
ptr = sock->addr.v4;
len = 4;
}
for (i=0; i<len; ++i)
{
if(0 != ptr[i])
{
/* found a non-zero byte in address */
return 0;
}
}
return 1;
}
/* ************************************** */
static n2n_mac_t broadcast_mac = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
/** Check if a known peer socket has changed and possibly register again.
*/
static void check_known_peer_sock_change(n2n_edge_t * eee,
uint8_t from_supernode,
const n2n_mac_t mac,
const n2n_sock_t * peer,
time_t when) {
struct peer_info *scan;
n2n_sock_str_t sockbuf1;
n2n_sock_str_t sockbuf2; /* don't clobber sockbuf1 if writing two addresses to trace */
macstr_t mac_buf;
if(is_empty_ip_address(peer))
return;
if(!memcmp(mac, broadcast_mac, N2N_MAC_SIZE))
return;
/* Search the peer in known_peers */
HASH_FIND_PEER(eee->known_peers, mac, scan);
if(!scan)
/* Not in known_peers */
return;
if(!sock_equal(&(scan->sock), peer)) {
if(!from_supernode) {
/* This is a P2P packet */
traceEvent(TRACE_NORMAL, "Peer changed %s: %s -> %s",
macaddr_str(mac_buf, scan->mac_addr),
sock_to_cstr(sockbuf1, &(scan->sock)),
sock_to_cstr(sockbuf2, peer));
/* The peer has changed public socket. It can no longer be assumed to be reachable. */
HASH_DEL(eee->known_peers, scan);
free(scan);
register_with_new_peer(eee, from_supernode, mac, peer);
} else {
/* Don't worry about what the supernode reports, it could be seeing a different socket. */
}
} else
scan->last_seen = when;
}
/* ************************************** */
/** Send a datagram to a socket defined by a n2n_sock_t */
static ssize_t sendto_sock(int fd, const void * buf,
size_t len, const n2n_sock_t * dest) {
struct sockaddr_in peer_addr;
ssize_t sent;
fill_sockaddr((struct sockaddr *) &peer_addr,
sizeof(peer_addr),
dest);
sent = sendto(fd, buf, len, 0/*flags*/,
(struct sockaddr *)&peer_addr, sizeof(struct sockaddr_in));
if(sent < 0)
{
char * c = strerror(errno);
traceEvent(TRACE_ERROR, "sendto failed (%d) %s", errno, c);
}
else
{
traceEvent(TRACE_DEBUG, "sendto sent=%d to ", (signed int)sent);
}
return sent;
}
/* ************************************** */
/* Bind eee->udp_multicast_sock to multicast group */
static void check_join_multicast_group(n2n_edge_t *eee) {
#ifndef SKIP_MULTICAST_PEERS_DISCOVERY
if(!eee->multicast_joined) {
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr(N2N_MULTICAST_GROUP);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if(setsockopt(eee->udp_multicast_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)) < 0) {
traceEvent(TRACE_WARNING, "Failed to bind to local multicast group %s:%u [errno %u]",
N2N_MULTICAST_GROUP, N2N_MULTICAST_PORT, errno);
#ifdef WIN32
traceEvent(TRACE_ERROR, "WSAGetLastError(): %u", WSAGetLastError());
#endif
} else {
traceEvent(TRACE_NORMAL, "Successfully joined multicast group %s:%u",
N2N_MULTICAST_GROUP, N2N_MULTICAST_PORT);
eee->multicast_joined = 1;
}
}
#endif
}
/* ************************************** */
/** Send a REGISTER_SUPER packet to the current supernode. */
static void send_register_super(n2n_edge_t * eee,
const n2n_sock_t * supernode) {
uint8_t pktbuf[N2N_PKT_BUF_SIZE] = {0};
size_t idx;
/* ssize_t sent; */
n2n_common_t cmn;
n2n_REGISTER_SUPER_t reg;
n2n_sock_str_t sockbuf;
memset(&cmn, 0, sizeof(cmn));
memset(®, 0, sizeof(reg));
cmn.ttl=N2N_DEFAULT_TTL;
cmn.pc = n2n_register_super;
cmn.flags = 0;
memcpy(cmn.community, eee->conf.community_name, N2N_COMMUNITY_SIZE);
for(idx=0; idx < N2N_COOKIE_SIZE; ++idx)
eee->last_cookie[idx] = rand() % 0xff;
memcpy(reg.cookie, eee->last_cookie, N2N_COOKIE_SIZE);
reg.auth.scheme=0; /* No auth yet */
idx=0;
encode_mac(reg.edgeMac, &idx, eee->device.mac_addr);
idx=0;
encode_REGISTER_SUPER(pktbuf, &idx, &cmn, ®);
traceEvent(TRACE_DEBUG, "send REGISTER_SUPER to %s",
sock_to_cstr(sockbuf, supernode));
/* sent = */ sendto_sock(eee->udp_sock, pktbuf, idx, supernode);
}
/* ************************************** */
/** Send a QUERY_PEER packet to the current supernode. */
static void send_query_peer( n2n_edge_t * eee,
const n2n_mac_t dstMac) {
uint8_t pktbuf[N2N_PKT_BUF_SIZE];
size_t idx;
n2n_common_t cmn = {0};
n2n_QUERY_PEER_t query = {{0}};
cmn.ttl=N2N_DEFAULT_TTL;
cmn.pc = n2n_query_peer;
cmn.flags = 0;
memcpy( cmn.community, eee->conf.community_name, N2N_COMMUNITY_SIZE );
idx=0;
encode_mac( query.srcMac, &idx, eee->device.mac_addr );
idx=0;
encode_mac( query.targetMac, &idx, dstMac );
idx=0;
encode_QUERY_PEER( pktbuf, &idx, &cmn, &query );
traceEvent( TRACE_DEBUG, "send QUERY_PEER to supernode" );
sendto_sock( eee->udp_sock, pktbuf, idx, &(eee->supernode) );
}
/** Send a REGISTER packet to another edge. */
static void send_register(n2n_edge_t * eee,
const n2n_sock_t * remote_peer,
const n2n_mac_t peer_mac) {
uint8_t pktbuf[N2N_PKT_BUF_SIZE];
size_t idx;
/* ssize_t sent; */
n2n_common_t cmn;
n2n_REGISTER_t reg;
n2n_sock_str_t sockbuf;
if(!eee->conf.allow_p2p) {
traceEvent(TRACE_DEBUG, "Skipping register as P2P is disabled");
return;
}
memset(&cmn, 0, sizeof(cmn));
memset(®, 0, sizeof(reg));
cmn.ttl=N2N_DEFAULT_TTL;
cmn.pc = n2n_register;
cmn.flags = 0;
memcpy(cmn.community, eee->conf.community_name, N2N_COMMUNITY_SIZE);
idx=0;
encode_uint32(reg.cookie, &idx, 123456789);
idx=0;
encode_mac(reg.srcMac, &idx, eee->device.mac_addr);
if(peer_mac) {
/* Can be NULL for multicast registrations */
idx=0;
encode_mac(reg.dstMac, &idx, peer_mac);
}
idx=0;
encode_REGISTER(pktbuf, &idx, &cmn, ®);
traceEvent(TRACE_INFO, "Send REGISTER to %s",
sock_to_cstr(sockbuf, remote_peer));
/* sent = */ sendto_sock(eee->udp_sock, pktbuf, idx, remote_peer);
}
/* ************************************** */
/** Send a REGISTER_ACK packet to a peer edge. */
static void send_register_ack(n2n_edge_t * eee,
const n2n_sock_t * remote_peer,
const n2n_REGISTER_t * reg) {
uint8_t pktbuf[N2N_PKT_BUF_SIZE];
size_t idx;
/* ssize_t sent; */
n2n_common_t cmn;
n2n_REGISTER_ACK_t ack;
n2n_sock_str_t sockbuf;
if(!eee->conf.allow_p2p) {
traceEvent(TRACE_DEBUG, "Skipping register ACK as P2P is disabled");
return;
}
memset(&cmn, 0, sizeof(cmn));
memset(&ack, 0, sizeof(reg));
cmn.ttl=N2N_DEFAULT_TTL;
cmn.pc = n2n_register_ack;
cmn.flags = 0;
memcpy(cmn.community, eee->conf.community_name, N2N_COMMUNITY_SIZE);
memset(&ack, 0, sizeof(ack));
memcpy(ack.cookie, reg->cookie, N2N_COOKIE_SIZE);
memcpy(ack.srcMac, eee->device.mac_addr, N2N_MAC_SIZE);
memcpy(ack.dstMac, reg->srcMac, N2N_MAC_SIZE);
idx=0;
encode_REGISTER_ACK(pktbuf, &idx, &cmn, &ack);
traceEvent(TRACE_INFO, "send REGISTER_ACK %s",
sock_to_cstr(sockbuf, remote_peer));
/* sent = */ sendto_sock(eee->udp_sock, pktbuf, idx, remote_peer);
}
/* ************************************** */
/** @brief Check to see if we should re-register with the supernode.
*
* This is frequently called by the main loop.
*/
static void update_supernode_reg(n2n_edge_t * eee, time_t nowTime) {
u_int sn_idx;
if(eee->sn_wait && (nowTime > (eee->last_register_req + (eee->conf.register_interval/10)))) {
/* fall through */
traceEvent(TRACE_DEBUG, "update_supernode_reg: doing fast retry.");
} else if(nowTime < (eee->last_register_req + eee->conf.register_interval))
return; /* Too early */
check_join_multicast_group(eee);
if(0 == eee->sup_attempts) {
/* Give up on that supernode and try the next one. */
++(eee->sn_idx);
if (eee->sn_idx >= eee->conf.sn_num) {
/* Got to end of list, go back to the start. Also works for list of one entry. */
eee->sn_idx=0;
}
traceEvent(TRACE_WARNING, "Supernode not responding, now trying %s", supernode_ip(eee));
eee->sup_attempts = N2N_EDGE_SUP_ATTEMPTS;
}
else
--(eee->sup_attempts);
for(sn_idx=0; sn_idx<eee->conf.sn_num; sn_idx++) {
supernode2addr(&(eee->supernode), eee->conf.sn_ip_array[sn_idx]);
traceEvent(TRACE_INFO, "Registering with supernode [id: %u/%u][%s][attempts left %u]",
sn_idx+1, eee->conf.sn_num,
supernode_ip(eee), (unsigned int)eee->sup_attempts);
send_register_super(eee, &(eee->supernode));
}
register_with_local_peers(eee);
eee->sn_wait=1;
/* REVISIT: turn-on gratuitous ARP with config option. */
/* send_grat_arps(sock_fd, is_udp_sock); */
eee->last_register_req = nowTime;
}
/* ************************************** */
/** NOT IMPLEMENTED
*
* This would send a DEREGISTER packet to a peer edge or supernode to indicate
* the edge is going away.
*/
static void send_deregister(n2n_edge_t * eee,
n2n_sock_t * remote_peer) {
/* Marshall and send message */
}
/* ************************************** */
/** Return the IP address of the current supernode in the ring. */
static const char * supernode_ip(const n2n_edge_t * eee) {
return (eee->conf.sn_ip_array)[eee->sn_idx];
}
/* ************************************** */
/** A PACKET has arrived containing an encapsulated ethernet datagram - usually
* encrypted. */
static int handle_PACKET(n2n_edge_t * eee,
const n2n_common_t * cmn,
const n2n_PACKET_t * pkt,
const n2n_sock_t * orig_sender,
uint8_t * payload,
size_t psize) {
ssize_t data_sent_len;
uint8_t from_supernode;
uint8_t * eth_payload=NULL;
int retval = -1;
time_t now;
ether_hdr_t * eh;
ipstr_t ip_buf;
now = time(NULL);
traceEvent(TRACE_DEBUG, "handle_PACKET size %u transform %u",
(unsigned int)psize, (unsigned int)pkt->transform);
/* hexdump(payload, psize); */
from_supernode= cmn->flags & N2N_FLAGS_FROM_SUPERNODE;
if(from_supernode)
{
if(!memcmp(pkt->dstMac, broadcast_mac, 6))
++(eee->stats.rx_sup_broadcast);
++(eee->stats.rx_sup);
eee->last_sup=now;
}
else
{
++(eee->stats.rx_p2p);
eee->last_p2p=now;
}
/* Update the sender in peer table entry */
check_peer_registration_needed(eee, from_supernode, pkt->srcMac, orig_sender);
/* Handle transform. */
{
uint8_t decodebuf[N2N_PKT_BUF_SIZE];
size_t eth_size;
n2n_transform_t rx_transop_id;
rx_transop_id = (n2n_transform_t)pkt->transform;
/* optional compression is encoded in uppermost bit of transform field.
* this is an intermediate solution to maintain compatibility until some
* upcoming major release (3.0?) brings up changes in packet structure anyway
* in the course of which a dedicated compression field could be spent.
* REVISIT then. */
uint16_t rx_compression_id;
rx_compression_id = (uint16_t)rx_transop_id >> (8*sizeof((uint16_t)rx_transop_id)-N2N_COMPRESSION_ID_BITLEN);
rx_transop_id &= (1 << (8*sizeof((uint16_t)rx_transop_id)-N2N_COMPRESSION_ID_BITLEN)) -1;
if(rx_transop_id == eee->conf.transop_id) {
uint8_t is_multicast;
eth_payload = decodebuf;
eh = (ether_hdr_t*)eth_payload;
eth_size = eee->transop.rev(&eee->transop,
eth_payload, N2N_PKT_BUF_SIZE,
payload, psize, pkt->srcMac);
++(eee->transop.rx_cnt); /* stats */
/* decompress if necessary */
uint8_t * deflation_buffer = 0;
uint32_t deflated_len;
switch (rx_compression_id) {
case N2N_COMPRESSION_ID_LZO:
deflation_buffer = malloc (N2N_PKT_BUF_SIZE);
lzo1x_decompress (eth_payload, eth_size, deflation_buffer, (lzo_uint*)&deflated_len, NULL);
break;
default:
break;
}
if (rx_compression_id) {