This repository has been archived by the owner on Jan 31, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathedge.c
1832 lines (1544 loc) · 52.4 KB
/
edge.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-09 - Luca Deri <deri@ntop.org>
* Richard Andrews <andrews@ntop.org>
*
* 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/>
*
* Code contributions courtesy of:
* Don Bindner <don.bindner@gmail.com>
* Sylwester Sosnowski <syso-n2n@no-route.org>
* Wilfried "Wonka" Klaebe
*
*/
#include "minilzo.h"
#include "n2n.h"
#include <assert.h>
#include <sys/stat.h>
#ifdef __ANDROID_NDK__
#include <edge_jni/edge_jni.h>
#include <tun2tap/tun2tap.h>
#endif /* __ANDROID_NDK__ */
/** Time between logging system STATUS messages */
#define STATUS_UPDATE_INTERVAL (30 * 60) /*secs*/
#ifdef __ANDROID_NDK__
#define ARP_PERIOD_INTERVAL (10) /* sec */
#endif /* __ANDROID_NDK__ */
/* maximum length of command line arguments */
#define MAX_CMDLINE_BUFFER_LENGTH 4096
/* maximum length of a line in the configuration file */
#define MAX_CONFFILE_LINE_LENGTH 1024
#define N2N_EDGE_SN_HOST_SIZE 48
#ifdef __ANDROID_NDK__
#define N2N_EDGE_MGMT_PORT 5644
#endif /* __ANDROID_NDK__ */
struct n2n_edge
{
u_char re_resolve_supernode_ip;
struct peer_addr supernode;
char supernode_ip[N2N_EDGE_SN_HOST_SIZE];
char * community_name /*= NULL*/;
/* int sock; */
/* char is_udp_socket /\*= 1*\/; */
n2n_sock_info_t sinfo;
u_int pkt_sent /*= 0*/;
tuntap_dev device;
int allow_routing /*= 0*/;
int drop_ipv6_ndp /*= 0*/;
char * encrypt_key /* = NULL*/;
TWOFISH * enc_tf;
TWOFISH * dec_tf;
struct peer_info * known_peers /* = NULL*/;
struct peer_info * pending_peers /* = NULL*/;
time_t last_register /* = 0*/;
#ifdef __ANDROID_NDK__
int sn_wait /* = 0*/;
#endif /* #ifdef __ANDROID_NDK__ */
};
static void supernode2addr(n2n_edge_t * eee, char* addr);
static void send_packet2net(n2n_edge_t * eee,
char *decrypted_msg, size_t len);
/* ************************************** */
/* parse the configuration file */
static int readConfFile(const char * filename, char * const linebuffer) {
struct stat stats;
FILE * fd;
char * buffer = NULL;
buffer = (char *)malloc(MAX_CONFFILE_LINE_LENGTH);
if (!buffer) {
traceEvent( TRACE_ERROR, "Unable to allocate memory");
return -1;
}
if (stat(filename, &stats)) {
if (errno == ENOENT)
traceEvent(TRACE_ERROR, "parameter file %s not found/unable to access\n", filename);
else
traceEvent(TRACE_ERROR, "cannot stat file %s, errno=%d\n",filename, errno);
free(buffer);
return -1;
}
fd = fopen(filename, "rb");
if (!fd) {
traceEvent(TRACE_ERROR, "Unable to open parameter file '%s' (%d)...\n",filename,errno);
free(buffer);
return -1;
}
while(fgets(buffer, MAX_CONFFILE_LINE_LENGTH,fd)) {
char * p = NULL;
/* strip out comments */
p = strchr(buffer, '#');
if (p) *p ='\0';
/* remove \n */
p = strchr(buffer, '\n');
if (p) *p ='\0';
/* strip out heading spaces */
p = buffer;
while(*p == ' ' && *p != '\0') ++p;
if (p != buffer) strncpy(buffer,p,strlen(p)+1);
/* strip out trailing spaces */
while(strlen(buffer) && buffer[strlen(buffer)-1]==' ')
buffer[strlen(buffer)-1]= '\0';
/* check for nested @file option */
if (strchr(buffer, '@')) {
traceEvent(TRACE_ERROR, "@file in file nesting is not supported\n");
free(buffer);
return -1;
}
if ((strlen(linebuffer)+strlen(buffer)+2)< MAX_CMDLINE_BUFFER_LENGTH) {
strncat(linebuffer, " ", 1);
strncat(linebuffer, buffer, strlen(buffer));
} else {
traceEvent(TRACE_ERROR, "too many argument");
free(buffer);
return -1;
}
}
free(buffer);
fclose(fd);
return 0;
}
/* Create the argv vector */
static char ** buildargv(char * const linebuffer) {
const int INITIAL_MAXARGC = 16; /* Number of args + NULL in initial argv */
int maxargc;
int argc=0;
char ** argv;
char * buffer, * buff;
buffer = (char *)calloc(1, strlen(linebuffer)+2);
if (!buffer) {
traceEvent( TRACE_ERROR, "Unable to allocate memory");
return NULL;
}
strncpy(buffer, linebuffer,strlen(linebuffer));
maxargc = INITIAL_MAXARGC;
argv = (char **)malloc(maxargc * sizeof(char*));
if (argv == NULL) {
traceEvent( TRACE_ERROR, "Unable to allocate memory");
return NULL;
}
buff = buffer;
while(buff) {
char * p = strchr(buff,' ');
if (p) {
*p='\0';
argv[argc++] = strdup(buff);
while(*++p == ' ' && *p != '\0');
buff=p;
if (argc >= maxargc) {
maxargc *= 2;
argv = (char **)realloc(argv, maxargc * sizeof(char*));
if (argv == NULL) {
traceEvent(TRACE_ERROR, "Unable to re-allocate memory");
free(buffer);
return NULL;
}
}
} else {
argv[argc++] = strdup(buff);
break;
}
}
argv[argc] = NULL;
free(buffer);
return argv;
}
/* ************************************** */
static int edge_init(n2n_edge_t * eee) {
#ifdef WIN32
initWin32();
#endif
memset(eee, 0, sizeof(n2n_edge_t));
eee->re_resolve_supernode_ip = 0;
eee->community_name = NULL;
eee->sinfo.sock = -1;
eee->sinfo.is_udp_socket = 1;
eee->pkt_sent = 0;
eee->allow_routing = 0;
eee->drop_ipv6_ndp = 0;
eee->encrypt_key = NULL;
eee->enc_tf = NULL;
eee->dec_tf = NULL;
eee->known_peers = NULL;
eee->pending_peers = NULL;
eee->last_register = 0;
#ifdef __ANDROID_NDK__
eee->sn_wait = 0;
#endif /* #ifdef __ANDROID_NDK__ */
if(lzo_init() != LZO_E_OK) {
traceEvent(TRACE_ERROR, "LZO compression error");
return(-1);
}
return(0);
}
static int edge_init_twofish( n2n_edge_t * eee, u_int8_t *encrypt_pwd, u_int32_t encrypt_pwd_len )
{
eee->enc_tf = TwoFishInit(encrypt_pwd, encrypt_pwd_len);
eee->dec_tf = TwoFishInit(encrypt_pwd, encrypt_pwd_len);
if ( (eee->enc_tf) && (eee->dec_tf) )
{
return 0;
}
else
{
return 1;
}
}
/* ************************************** */
static void edge_deinit(n2n_edge_t * eee) {
TwoFishDestroy(eee->enc_tf);
TwoFishDestroy(eee->dec_tf);
if ( eee->sinfo.sock >=0 )
{
close( eee->sinfo.sock );
}
}
static void readFromIPSocket( n2n_edge_t * eee );
static void help() {
print_n2n_version();
printf("edge "
#ifdef __linux__
"-d <tun device> "
#endif
"-a <tun IP address> "
"-c <community> "
"-k <encrypt key> "
"-s <netmask> "
#ifndef WIN32
"[-u <uid> -g <gid>]"
"[-f]"
#endif
"[-m <MAC address>]"
"\n"
"-l <supernode host:port> "
"[-p <local port>] [-M <mtu>] "
"[-t] [-r] [-v] [-b] [-h]\n\n");
#ifdef __linux__
printf("-d <tun device> | tun device name\n");
#endif
printf("-a <tun IP address> | n2n IP address\n");
printf("-c <community> | n2n community name\n");
printf("-k <encrypt key> | Encryption key (ASCII) - also N2N_KEY=<encrypt key>\n");
printf("-s <netmask> | Edge interface netmask in dotted decimal notation (255.255.255.0)\n");
printf("-l <supernode host:port> | Supernode IP:port\n");
printf("-b | Periodically resolve supernode IP\n");
printf(" | (when supernodes are running on dynamic IPs)\n");
printf("-p <local port> | Local port used for connecting to supernode\n");
#ifndef WIN32
printf("-u <UID> | User ID (numeric) to use when privileges are dropped\n");
printf("-g <GID> | Group ID (numeric) to use when privileges are dropped\n");
printf("-f | Fork and run as a daemon. Use syslog.\n");
#endif
printf("-m <MAC address> | Choose a MAC address for the TAP interface\n"
" | eg. -m 01:02:03:04:05:06\n");
printf("-M <mtu> | Specify n2n MTU (default %d)\n", DEFAULT_MTU);
printf("-t | Use http tunneling (experimental)\n");
printf("-r | Enable packet forwarding through n2n community\n");
printf("-v | Verbose\n");
printf("\nEnvironment variables:\n");
printf(" N2N_KEY | Encryption key (ASCII)\n" );
exit(0);
}
/* *********************************************** */
static void send_register( n2n_edge_t * eee,
const struct peer_addr *remote_peer,
u_char is_ack) {
struct n2n_packet_header hdr;
char pkt[N2N_PKT_HDR_SIZE];
size_t len = sizeof(hdr);
ipstr_t ip_buf;
fill_standard_header_fields( &(eee->sinfo), &hdr, (char*)(eee->device.mac_addr));
hdr.sent_by_supernode = 0;
hdr.msg_type = (is_ack == 0) ? MSG_TYPE_REGISTER : MSG_TYPE_REGISTER_ACK;
memcpy(hdr.community_name, eee->community_name, COMMUNITY_LEN);
marshall_n2n_packet_header( (u_int8_t *)pkt, &hdr );
send_packet( &(eee->sinfo), pkt, &len, remote_peer, N2N_COMPRESSION_ENABLED );
traceEvent(TRACE_INFO, "Sent %s message to %s:%hu",
((hdr.msg_type==MSG_TYPE_REGISTER)?"MSG_TYPE_REGISTER":"MSG_TYPE_REGISTER_ACK"),
intoa(ntohl(remote_peer->addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(remote_peer->port));
}
/* *********************************************** */
static void send_deregister(n2n_edge_t * eee,
struct peer_addr *remote_peer) {
struct n2n_packet_header hdr;
char pkt[N2N_PKT_HDR_SIZE];
size_t len = sizeof(hdr);
fill_standard_header_fields( &(eee->sinfo), &hdr, (char*)(eee->device.mac_addr) );
hdr.sent_by_supernode = 0;
hdr.msg_type = MSG_TYPE_DEREGISTER;
memcpy(hdr.community_name, eee->community_name, COMMUNITY_LEN);
marshall_n2n_packet_header( (u_int8_t *)pkt, &hdr );
send_packet( &(eee->sinfo), pkt, &len, remote_peer, N2N_COMPRESSION_ENABLED);
}
/* *********************************************** */
static void update_peer_address(n2n_edge_t * eee,
const struct n2n_packet_header * hdr,
time_t when);
void trace_registrations( struct peer_info * scan );
int is_ip6_discovery( const void * buf, size_t bufsize );
void check_peer( n2n_edge_t * eee,
const struct n2n_packet_header * hdr );
void try_send_register( n2n_edge_t * eee,
const struct n2n_packet_header * hdr );
void set_peer_operational( n2n_edge_t * eee, const struct n2n_packet_header * hdr );
/** 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.
*/
void try_send_register( n2n_edge_t * eee,
const struct n2n_packet_header * hdr )
{
ipstr_t ip_buf;
/* REVISIT: purge of pending_peers not yet done. */
struct peer_info * scan = find_peer_by_mac( eee->pending_peers, hdr->src_mac );
if ( NULL == scan )
{
scan = calloc( 1, sizeof( struct peer_info ) );
memcpy(scan->mac_addr, hdr->src_mac, 6);
scan->public_ip = hdr->public_ip;
scan->last_seen = time(NULL); /* Don't change this it marks the pending peer for removal. */
peer_list_add( &(eee->pending_peers), scan );
traceEvent( TRACE_NORMAL, "Pending peers list size=%ld",
peer_list_size( eee->pending_peers ) );
traceEvent( TRACE_NORMAL, "Sending REGISTER request to %s:%hu",
intoa(ntohl(scan->public_ip.addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(scan->public_ip.port));
send_register(eee,
&(scan->public_ip),
0 /* is not ACK */ );
/* pending_peers now owns scan. */
}
else
{
/* scan already in pending_peers. */
if ( 0 == hdr->sent_by_supernode )
{
/* over-write supernode-based socket with direct socket. */
scan->public_ip = hdr->public_ip;
traceEvent( TRACE_NORMAL, "Sending additional REGISTER request to %s:%hu",
intoa(ntohl(scan->public_ip.addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(scan->public_ip.port));
send_register(eee,
&(scan->public_ip),
0 /* is not ACK */ );
}
}
}
/** Update the last_seen time for this peer, or get registered. */
void check_peer( n2n_edge_t * eee,
const struct n2n_packet_header * hdr )
{
struct peer_info * scan = find_peer_by_mac( eee->known_peers, hdr->src_mac );
if ( NULL == scan )
{
/* Not in known_peers - start the REGISTER process. */
try_send_register( eee, hdr );
}
else
{
/* Already in known_peers. */
update_peer_address( eee, hdr, time(NULL) );
}
}
/* Move the peer from the pending_peers list to the known_peers lists.
*
* peer must be a pointer to an element of the pending_peers list.
*
* Called by main loop when Rx a REGISTER_ACK.
*/
void set_peer_operational( n2n_edge_t * eee, const struct n2n_packet_header * hdr )
{
struct peer_info * prev = NULL;
struct peer_info * scan;
macstr_t mac_buf;
ipstr_t ip_buf;
scan=eee->pending_peers;
while ( NULL != scan )
{
if ( 0 != memcmp( scan->mac_addr, hdr->dst_mac, 6 ) )
{
break; /* found. */
}
prev = scan;
scan = scan->next;
}
if ( scan )
{
/* Remove scan from pending_peers. */
if ( prev )
{
prev->next = scan->next;
}
else
{
eee->pending_peers = scan->next;
}
/* Add scan to known_peers. */
scan->next = eee->known_peers;
eee->known_peers = scan;
scan->public_ip = hdr->public_ip;
traceEvent(TRACE_INFO, "=== new peer [mac=%s][socket=%s:%hu]",
macaddr_str(scan->mac_addr, mac_buf, sizeof(mac_buf)),
intoa(ntohl(scan->public_ip.addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(scan->public_ip.port));
traceEvent( TRACE_NORMAL, "Pending peers list size=%ld",
peer_list_size( eee->pending_peers ) );
traceEvent( TRACE_NORMAL, "Operational peers list size=%ld",
peer_list_size( eee->known_peers ) );
scan->last_seen = time(NULL);
}
else
{
traceEvent( TRACE_WARNING, "Failed to find sender in pending_peers." );
}
}
void trace_registrations( struct peer_info * scan )
{
macstr_t mac_buf;
ipstr_t ip_buf;
while ( scan )
{
traceEvent(TRACE_INFO, "=== peer [mac=%s][socket=%s:%hu]",
macaddr_str(scan->mac_addr, mac_buf, sizeof(mac_buf)),
intoa(ntohl(scan->public_ip.addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(scan->public_ip.port));
scan = scan->next;
}
}
u_int8_t broadcast_mac[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
/** Keep the known_peers list straight.
*
* Ignore broadcast L2 packets, and packets with invalid public_ip.
* If the dst_mac is in known_peers make sure the entry is correct:
* - if the public_ip socket has changed, erase the entry
* - if the same, update its last_seen = when
*/
static void update_peer_address(n2n_edge_t * eee,
const struct n2n_packet_header * hdr,
time_t when)
{
ipstr_t ip_buf;
struct peer_info *scan = eee->known_peers;
struct peer_info *prev = NULL; /* use to remove bad registrations. */
if ( 0 == hdr->public_ip.addr_type.v4_addr )
{
/* Not to be registered. */
return;
}
if ( 0 == memcmp( hdr->dst_mac, broadcast_mac, 6 ) )
{
/* Not to be registered. */
return;
}
while(scan != NULL)
{
if(memcmp(hdr->dst_mac, scan->mac_addr, 6) == 0)
{
break;
}
prev = scan;
scan = scan->next;
}
if ( NULL == scan )
{
/* Not in known_peers. */
return;
}
if ( 0 != memcmp( &(scan->public_ip), &(hdr->public_ip), sizeof(struct peer_addr)))
{
if ( 0 == hdr->sent_by_supernode )
{
traceEvent( TRACE_NORMAL, "Peer changed public socket, Was %s:%hu",
intoa(ntohl(hdr->public_ip.addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(hdr->public_ip.port));
/* The peer has changed public socket. It can no longer be assumed to be reachable. */
/* Remove the peer. */
if ( NULL == prev )
{
/* scan was head of list */
eee->known_peers = scan->next;
}
else
{
prev->next = scan->next;
}
free(scan);
try_send_register( eee, hdr );
}
else
{
/* Don't worry about what the supernode reports, it could be seeing a different socket. */
}
}
else
{
/* Found and unchanged. */
scan->last_seen = when;
}
}
#if defined(DUMMY_ID_00001) /* Disabled waiting for config option to enable it */
/* *********************************************** */
static char gratuitous_arp[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* Dest mac */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Src mac */
0x08, 0x06, /* ARP */
0x00, 0x01, /* Ethernet */
0x08, 0x00, /* IP */
0x06, /* Hw Size */
0x04, /* Protocol Size */
0x00, 0x01, /* ARP Request */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Src mac */
0x00, 0x00, 0x00, 0x00, /* Src IP */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Target mac */
0x00, 0x00, 0x00, 0x00 /* Target IP */
};
static int build_gratuitous_arp(char *buffer, u_short buffer_len) {
if(buffer_len < sizeof(gratuitous_arp)) return(-1);
memcpy(buffer, gratuitous_arp, sizeof(gratuitous_arp));
memcpy(&buffer[6], device.mac_addr, 6);
memcpy(&buffer[22], device.mac_addr, 6);
memcpy(&buffer[28], &device.ip_addr, 4);
/* REVISIT: BbMaj7 - use a real netmask here. This is valid only by accident
* for /24 IPv4 networks. */
buffer[31] = 0xFF; /* Use a faked broadcast address */
memcpy(&buffer[38], &device.ip_addr, 4);
return(sizeof(gratuitous_arp));
}
/** Called from update_registrations to periodically send gratuitous ARP
* broadcasts. */
static void send_grat_arps(n2n_edge_t * eee,) {
char buffer[48];
size_t len;
traceEvent(TRACE_NORMAL, "Sending gratuitous ARP...");
len = build_gratuitous_arp(buffer, sizeof(buffer));
send_packet2net(eee, buffer, len);
send_packet2net(eee, buffer, len); /* Two is better than one :-) */
}
#endif /* #if defined(DUMMY_ID_00001) */
/* *********************************************** */
/** @brief Check to see if we should re-register with our peers and the
* supernode.
*
* This is periodically called by the main loop. The list of registrations is
* not modified. Registration packets may be sent.
*/
static void update_registrations( n2n_edge_t * eee ) {
/* REVISIT: BbMaj7: have shorter timeout to REGISTER to supernode if this has
* not yet succeeded. */
if(time(NULL) < (eee->last_register+REGISTER_FREQUENCY)) return; /* Too early */
traceEvent(TRACE_NORMAL, "Registering with supernode");
if(eee->re_resolve_supernode_ip) {
supernode2addr(eee, eee->supernode_ip);
}
send_register(eee, &(eee->supernode), 0); /* Register with supernode */
/* REVISIT: turn-on gratuitous ARP with config option. */
/* send_grat_arps(sock_fd, is_udp_sock); */
#ifdef __ANDROID_NDK__
if (eee->sn_wait) {
int change = 0;
pthread_mutex_lock(&g_status->mutex);
change = g_status->running_status == EDGE_STAT_SUPERNODE_DISCONNECT ? 0 : 1;
g_status->running_status = EDGE_STAT_SUPERNODE_DISCONNECT;
pthread_mutex_unlock(&g_status->mutex);
if (change) {
g_status->report_edge_status();
}
}
eee->sn_wait = 1;
#endif /* #ifdef __ANDROID_NDK__ */
eee->last_register = time(NULL);
}
/* ***************************************************** */
static int find_peer_destination(n2n_edge_t * eee,
const u_char *mac_address,
struct peer_addr *destination) {
const struct peer_info *scan = eee->known_peers;
macstr_t mac_buf;
ipstr_t ip_buf;
int retval=0;
traceEvent(TRACE_INFO, "Searching destination peer for MAC %02X:%02X:%02X:%02X:%02X:%02X",
mac_address[0] & 0xFF, mac_address[1] & 0xFF, mac_address[2] & 0xFF,
mac_address[3] & 0xFF, mac_address[4] & 0xFF, mac_address[5] & 0xFF);
while(scan != NULL) {
traceEvent(TRACE_INFO, "Evaluating peer [MAC=%02X:%02X:%02X:%02X:%02X:%02X][ip=%s:%hu]",
scan->mac_addr[0] & 0xFF, scan->mac_addr[1] & 0xFF, scan->mac_addr[2] & 0xFF,
scan->mac_addr[3] & 0xFF, scan->mac_addr[4] & 0xFF, scan->mac_addr[5] & 0xFF,
intoa(ntohl(scan->public_ip.addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(scan->public_ip.port));
if((scan->last_seen > 0) &&
(memcmp(mac_address, scan->mac_addr, 6) == 0))
{
memcpy(destination, &scan->public_ip, sizeof(struct sockaddr_in));
retval=1;
break;
}
scan = scan->next;
}
if ( 0 == retval )
{
memcpy(destination, &(eee->supernode), sizeof(struct sockaddr_in));
}
traceEvent(TRACE_INFO, "find_peer_address(%s) -> [socket=%s:%hu]",
macaddr_str( (char *)mac_address, mac_buf, sizeof(mac_buf)),
intoa(ntohl(destination->addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(destination->port));
return retval;
}
/* *********************************************** */
static const struct option long_options[] = {
{ "community", required_argument, NULL, 'c' },
{ "supernode-list", required_argument, NULL, 'l' },
{ "tun-device", required_argument, NULL, 'd' },
{ "euid", required_argument, NULL, 'u' },
{ "egid", required_argument, NULL, 'g' },
{ "help" , no_argument, NULL, 'h' },
{ "verbose", no_argument, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
/* ***************************************************** */
/** A layer-2 packet was received at the tunnel and needs to be sent via UDP. */
static void send_packet2net(n2n_edge_t * eee,
char *decrypted_msg, size_t len) {
ipstr_t ip_buf;
char packet[2048];
int data_sent_len;
struct n2n_packet_header hdr;
struct peer_addr destination;
macstr_t mac_buf;
macstr_t mac2_buf;
struct ether_header *eh = (struct ether_header*)decrypted_msg;
/* Discard IP packets that are not originated by this hosts */
if(!(eee->allow_routing)) {
if(ntohs(eh->ether_type) == 0x0800) {
/* This is an IP packet from the local source address - not forwarded. */
#define ETH_FRAMESIZE 14
#define IP4_SRCOFFSET 12
u_int32_t dst;
memcpy( &dst, &decrypted_msg[ETH_FRAMESIZE + IP4_SRCOFFSET], sizeof(dst) );
/* The following comparison works because device.ip_addr is stored in network order */
if( dst != eee->device.ip_addr) {
/* This is a packet that needs to be routed */
traceEvent(TRACE_INFO, "Discarding routed packet [%s]",
intoa(ntohl(dst), ip_buf, sizeof(ip_buf)));
return;
} else {
/* This packet is originated by us */
/* traceEvent(TRACE_INFO, "Sending non-routed packet"); */
}
}
}
/* Encrypt "decrypted_msg" into the second half of the n2n packet. */
len = TwoFishEncryptRaw((u_int8_t *)decrypted_msg,
(u_int8_t *)&packet[N2N_PKT_HDR_SIZE], len, eee->enc_tf);
/* Add the n2n header to the start of the n2n packet. */
fill_standard_header_fields( &(eee->sinfo), &hdr, (char*)(eee->device.mac_addr) );
hdr.msg_type = MSG_TYPE_PACKET;
hdr.sent_by_supernode = 0;
memcpy(hdr.community_name, eee->community_name, COMMUNITY_LEN);
memcpy(hdr.dst_mac, decrypted_msg, 6);
marshall_n2n_packet_header( (u_int8_t *)packet, &hdr );
len += N2N_PKT_HDR_SIZE;
if(find_peer_destination(eee, eh->ether_dhost, &destination))
traceEvent(TRACE_INFO, "** Going direct [dst_mac=%s][dest=%s:%hu]",
macaddr_str((char*)eh->ether_dhost, mac_buf, sizeof(mac_buf)),
intoa(ntohl(destination.addr_type.v4_addr), ip_buf, sizeof(ip_buf)),
ntohs(destination.port));
else
traceEvent(TRACE_INFO, " Going via supernode [src_mac=%s][dst_mac=%s]",
macaddr_str((char*)eh->ether_shost, mac_buf, sizeof(mac_buf)),
macaddr_str((char*)eh->ether_dhost, mac2_buf, sizeof(mac2_buf)));
data_sent_len = reliable_sendto( &(eee->sinfo), packet, &len, &destination,
N2N_COMPRESSION_ENABLED);
if(data_sent_len != len)
traceEvent(TRACE_WARNING, "sendto() [sent=%d][attempted_to_send=%d] [%s]\n",
data_sent_len, len, strerror(errno));
else {
++(eee->pkt_sent);
traceEvent(TRACE_INFO, "Sent %d byte MSG_TYPE_PACKET ok", data_sent_len);
}
}
/* ***************************************************** */
/** Destination MAC 33:33:0:00:00:00 - 33:33:FF:FF:FF:FF is reserved for IPv6
* neighbour discovery.
*/
int is_ip6_discovery( const void * buf, size_t bufsize )
{
int retval = 0;
if ( bufsize >= sizeof(struct ether_header) )
{
struct ether_header *eh = (struct ether_header*)buf;
if ( (0x33 == eh->ether_dhost[0]) &&
(0x33 == eh->ether_dhost[1]) )
{
retval = 1; /* This is an IPv6 neighbour discovery packet. */
}
}
return retval;
}
/* ***************************************************** */
/*
* Return: 0 = ok, -1 = invalid packet
*
*/
static int check_received_packet(n2n_edge_t * eee, char *pkt,
u_int pkt_len) {
if(pkt_len == 42) {
/* ARP */
if((pkt[12] != 0x08) || (pkt[13] != 0x06)) return(0); /* No ARP */
if((pkt[20] != 0x00) || (pkt[21] != 0x02)) return(0); /* No ARP Reply */
if(memcmp(&pkt[28], &(eee->device.ip_addr), 4)) return(0); /* This is not me */
if(memcmp(eee->device.mac_addr, &pkt[22], 6) == 0) {
traceEvent(TRACE_WARNING, "Bounced packet received: supernode bug?");
return(0);
}
traceEvent(TRACE_ERROR, "Duplicate address found. Your IP is used by MAC %02X:%02X:%02X:%02X:%02X:%02X",
pkt[22+0] & 0xFF, pkt[22+1] & 0xFF, pkt[22+2] & 0xFF,
pkt[22+3] & 0xFF, pkt[22+4] & 0xFF, pkt[22+5] & 0xFF);
exit(0);
} else if(pkt_len > 32 /* IP + Ethernet */) {
/* Check if this packet is for us or if it's routed */
struct ether_header *eh = (struct ether_header*)pkt;
const struct in_addr bcast = { 0xffffffff };
if(ntohs(eh->ether_type) == 0x0800) {
/* Note: all elements of the_ip are in network order */
struct ip the_ip;
memcpy( &the_ip, pkt+sizeof(struct ether_header), sizeof(the_ip) );
if((the_ip.ip_dst.s_addr != eee->device.ip_addr)
&& ((the_ip.ip_dst.s_addr & eee->device.device_mask) != (eee->device.ip_addr & eee->device.device_mask)) /* Not a broadcast */
&& ((the_ip.ip_dst.s_addr & 0xE0000000) != (0xE0000000 /* 224.0.0.0-239.255.255.255 */)) /* Not a multicast */
&& ((the_ip.ip_dst.s_addr) != (bcast.s_addr)) /* always broadcast (RFC919) */
&& (!(eee->allow_routing)) /* routing is enabled so let it in */
)
{
/* Dropping the packet */
ipstr_t ip_buf;
ipstr_t ip_buf2;
/* This is a packet that needs to be routed */
traceEvent(TRACE_INFO, "Discarding routed packet [rcvd=%s][expected=%s]",
intoa(ntohl(the_ip.ip_dst.s_addr), ip_buf, sizeof(ip_buf)),
intoa(ntohl(eee->device.ip_addr), ip_buf2, sizeof(ip_buf2)));
} else {
/* This packet is for us */
/* traceEvent(TRACE_INFO, "Received non-routed packet"); */
return(0);
}
} else
return(0);
} else {
traceEvent(TRACE_INFO, "Packet too short (%d bytes): discarded", pkt_len);
}
return(-1);
}
/* ***************************************************** */
/** Read a single packet from the TAP interface, process it and write out the
* corresponding packet to the cooked socket.
*
* REVISIT: fails if more than one packet is waiting to be read.
*/
static void readFromTAPSocket( n2n_edge_t * eee )
{
/* tun -> remote */
u_char decrypted_msg[2048];
size_t len;
#ifdef __ANDROID_NDK__
if (uip_arp_len != 0) {
len = uip_arp_len;
memcpy(decrypted_msg, uip_arp_buf, MIN(uip_arp_len, sizeof(decrypted_msg)));
traceEvent(TRACE_NORMAL, "ARP reply packet to send");
}
else
{
#endif /* #ifdef __ANDROID_NDK__ */
len = tuntap_read(&(eee->device), decrypted_msg, sizeof(decrypted_msg));
#ifdef __ANDROID_NDK__
}
#endif /* #ifdef __ANDROID_NDK__ */
if((len <= 0) || (len > sizeof(decrypted_msg)))
traceEvent(TRACE_WARNING, "read()=%d [%d/%s]\n",
len, errno, strerror(errno));
else {
traceEvent(TRACE_INFO, "### Rx L2 Msg (%d) tun -> network", len);
if ( eee->drop_ipv6_ndp && is_ip6_discovery( decrypted_msg, len ) ) {
traceEvent(TRACE_WARNING, "Dropping unsupported IPv6 neighbour discovery packet");
} else {
send_packet2net(eee, (char*)decrypted_msg, len);
}
}
}
/* ***************************************************** */
void readFromIPSocket( n2n_edge_t * eee )
{
ipstr_t ip_buf;
macstr_t mac_buf;
char packet[2048], decrypted_msg[2048];
size_t len;
int data_sent_len;
struct peer_addr sender;
/* remote -> tun */
u_int8_t discarded_pkt;
struct n2n_packet_header hdr_storage;
len = receive_data( &(eee->sinfo), packet, sizeof(packet), &sender,
&discarded_pkt, (char*)(eee->device.mac_addr),
N2N_COMPRESSION_ENABLED, &hdr_storage);
if(len <= 0) return;