forked from gozfree/gear-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibstun.c
1321 lines (1138 loc) · 35.6 KB
/
libstun.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
/*****************************************************************************
* Copyright (C) 2014-2015
* file: libstun.cc
* author: gozfree <[email protected]>
* created: 2015-08-05 00:14
* updated: 2015-08-05 00:14
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#ifndef __ANDROID__
#include <ifaddrs.h>
#endif
#include <fcntl.h>
#include <netdb.h>
#include <resolv.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <arpa/nameser.h>
#include <netinet/in.h>
#include <net/if.h>
#include "libstun.h"
#define STUN_PORT (3478)
#define STUN_MAX_STRING (256)
#define STUN_MAX_UNKNOWN_ATTRIBUTES (8)
#define STUN_MAX_MESSAGE_SIZE (2048)
static stun_addr g_stun_srv;
static const int INVALID_SOCKET = -1;
static const int SOCKET_ERROR = -1;
// define some basic types
/// define a structure to hold a stun address
static const uint8_t IPv4Family = 0x01;
static const uint8_t IPv6Family = 0x02;
// define flags
static const uint32_t ChangeIpFlag = 0x04;
static const uint32_t ChangePortFlag = 0x02;
// define stun attribute
#define MappedAddress 0x0001
#define ResponseAddress 0x0002
#define ChangeRequest 0x0003
#define SourceAddress 0x0004
#define ChangedAddress 0x0005
#define Username 0x0006
#define Password 0x0007
#define MessageIntegrity 0x0008
#define ErrorCode 0x0009
#define UnknownAttribute 0x000A
#define ReflectedFrom 0x000B
#define XorMappedAddress 0x8020
#define XorOnly 0x0021
#define ServerName 0x8022
#define SecondaryAddress 0x8050 // Non standard extention
// define types for a stun message
#define BindRequestMsg 0x0001
#define BindResponseMsg 0x0101
#define BindErrorResponseMsg 0x0111
#define SharedSecretRequestMsg 0x0002
#define SharedSecretResponseMsg 0x0102
#define SharedSecretErrorResponseMsg 0x0112
typedef struct {
unsigned char octet[16];
} uint128_t;
typedef struct {
uint16_t msgType;
uint16_t msgLength;
uint128_t id;
} StunMsgHdr;
typedef struct {
uint16_t type;
uint16_t length;
} StunAtrHdr;
typedef struct {
uint8_t pad;
uint8_t family;
stun_addr ipv4;
} StunAtrAddress4;
typedef struct {
uint32_t value;
} StunAtrChangeRequest;
typedef struct {
uint16_t pad; // all 0
uint8_t errorClass;
uint8_t number;
char reason[STUN_MAX_STRING];
uint16_t sizeReason;
} StunAtrError;
typedef struct {
uint16_t attrType[STUN_MAX_UNKNOWN_ATTRIBUTES];
uint16_t numAttributes;
} StunAtrUnknown;
typedef struct {
char value[STUN_MAX_STRING];
uint16_t sizeValue;
} StunAtrString;
typedef struct {
char hash[20];
} StunAtrIntegrity;
typedef struct {
StunMsgHdr msgHdr;
int hasMappedAddress;
StunAtrAddress4 mappedAddress;
int hasResponseAddress;
StunAtrAddress4 responseAddress;
int hasChangeRequest;
StunAtrChangeRequest changeRequest;
int hasSourceAddress;
StunAtrAddress4 sourceAddress;
int hasChangedAddress;
StunAtrAddress4 changedAddress;
int hasUsername;
StunAtrString username;
int hasPassword;
StunAtrString password;
int hasMessageIntegrity;
StunAtrIntegrity messageIntegrity;
int hasErrorCode;
StunAtrError errorCode;
int hasUnknownAttributes;
StunAtrUnknown unknownAttributes;
int hasReflectedFrom;
StunAtrAddress4 reflectedFrom;
int hasXorMappedAddress;
StunAtrAddress4 xorMappedAddress;
int xorOnly;
int hasServerName;
StunAtrString serverName;
int hasSecondaryAddress;
StunAtrAddress4 secondaryAddress;
} StunMessage;
// Define enum with different types of NAT
typedef enum {
StunTypeUnknown = 0,
StunTypeFailure,
StunTypeOpen,
StunTypeBlocked,
StunTypeConeNat,
StunTypeRestrictedNat,
StunTypePortRestrictedNat,
StunTypeSymNat,
StunTypeSymFirewall,
} NatType;
static void computeHmac(char *hmac, const char *input,
int length, const char *key, int sizeKey)
{
strncpy(hmac, "hmac-not-implemented", 20);
}
static int openPort(unsigned short port, unsigned int interfaceIp)
{
int fd;
int reuse;
fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (fd == INVALID_SOCKET) {
printf("Could not create a UDP socket: %d", errno);
return INVALID_SOCKET;
}
reuse = 1;
if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
(void *)&reuse, sizeof(reuse))) {
printf("setsockopt: errno = %d\n", errno);
}
struct sockaddr_in addr;
memset((char *)&(addr), 0, sizeof((addr)));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if ((interfaceIp != 0) && (interfaceIp != 0x100007f)) {
addr.sin_addr.s_addr = htonl(interfaceIp);
}
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
int e = errno;
switch (e) {
case 0:
printf("Could not bind socket\n");
break;
case EADDRINUSE:
printf("Port %d for receiving UDP is in use\n", port);
break;
case EADDRNOTAVAIL:
break;
default:
printf("Could not bind UDP receive port errno:%d\n", e);
break;
}
return INVALID_SOCKET;
}
return fd;
}
static int getMessage(int fd, char *buf, int *len, unsigned int *srcIp,
unsigned short *srcPort)
{
int originalSize = *len;
struct sockaddr_in from;
int fromLen = sizeof(from);
// int flag = MSG_DONTWAIT;
int flag = 0;
*len = recvfrom(fd, buf, originalSize, flag,
(struct sockaddr *)&from, (socklen_t *)&fromLen);
if (*len == SOCKET_ERROR) {
int err = errno;
switch (err) {
case ENOTSOCK:
fprintf(stderr, "Error fd not a socket\n");
break;
case ECONNRESET:
fprintf(stderr, "Error connection reset - host not reachable\n");
break;
default:
fprintf(stderr, "socket Error=%d\n", err);
}
return 0;
}
if (*len < 0) {
fprintf(stderr, "socket closed? negative len\n");
return 0;
}
if (*len == 0) {
fprintf(stderr, "socket closed? zero len\n");
return 0;
}
*srcPort = ntohs(from.sin_port);
*srcIp = ntohl(from.sin_addr.s_addr);
if ((*len) + 1 >= originalSize) {
return 0;
}
buf[*len] = 0;
return 1;
}
static int sendMessage(int fd, char *buf, int l, unsigned int dstIp,
unsigned short dstPort)
{
int verbose = 0;
int s;
if (dstPort == 0) {
// sending on a connected port
s = send(fd, buf, l, 0);
} else {
struct sockaddr_in to;
int toLen = sizeof(to);
memset(&to, 0, toLen);
to.sin_family = AF_INET;
to.sin_port = htons(dstPort);
to.sin_addr.s_addr = htonl(dstIp);
s = sendto(fd, buf, l, 0, (struct sockaddr *) & to, toLen);
}
if (s == SOCKET_ERROR) {
int e = errno;
switch (e) {
case ECONNREFUSED:
case EHOSTDOWN:
case EHOSTUNREACH:
// quietly ignore this
break;
case EAFNOSUPPORT:
fprintf(stderr, "err EAFNOSUPPORT in send\n");
break;
default:
fprintf(stderr, "err %d %s in send\n", e, strerror(e));
break;
}
return 0;
}
if (s == 0) {
fprintf(stderr, "no data sent in send\n");
return 0;
}
if (s != l) {
if (verbose) {
fprintf(stderr, "only %d out of %d bytes sent\n", s, l);
}
return 0;
}
return 1;
}
static int stunParseAtrAddr(char *body, unsigned int hdrLen,
StunAtrAddress4 *result)
{
if (hdrLen != 8) {
fprintf(stderr, "hdrLen wrong for Address\n");
return 0;
}
result->pad = *body++;
result->family = *body++;
if (result->family == IPv4Family) {
uint16_t nport;
memcpy(&nport, body, 2);
body += 2;
result->ipv4.port = ntohs(nport);
uint32_t naddr;
memcpy(&naddr, body, 4);
body += 4;
result->ipv4.addr = ntohl(naddr);
return 1;
} else if (result->family == IPv6Family) {
fprintf(stderr, "ipv6 not supported\n");
} else {
fprintf(stderr, "bad address family: %d\n", result->family);
}
return 0;
}
static int stunParseAtrChangeRequest(char *body,
unsigned int hdrLen, StunAtrChangeRequest *result)
{
if (hdrLen != 4) {
printf("hdr length = %u expecting %zu\n", hdrLen, sizeof(*result));
printf("Incorrect size for ChangeRequest\n");
return 0;
} else {
memcpy(&result->value, body, 4);
result->value = ntohl(result->value);
return 1;
}
}
static int stunParseAtrError(char *body, unsigned int hdrLen,
StunAtrError *result)
{
if (hdrLen >= sizeof(*result)) {
fprintf(stderr, "head on Error too large\n");
return 0;
} else {
memcpy(&result->pad, body, 2);
body += 2;
result->pad = ntohs(result->pad);
result->errorClass = *body++;
result->number = *body++;
result->sizeReason = hdrLen - 4;
memcpy(&result->reason, body, result->sizeReason);
result->reason[result->sizeReason] = 0;
return 1;
}
}
static int stunParseAtrUnknown(char *body, unsigned int hdrLen,
StunAtrUnknown *result)
{
int i;
if (hdrLen >= sizeof(*result)) {
return 0;
} else {
if (hdrLen % 4 != 0)
return 0;
result->numAttributes = hdrLen / 4;
for (i = 0; i < result->numAttributes; i++) {
memcpy(&result->attrType[i], body, 2);
body += 2;
result->attrType[i] = ntohs(result->attrType[i]);
}
return 1;
}
}
static int stunParseAtrString(char *body, unsigned int hdrLen,
StunAtrString *result)
{
if (hdrLen >= STUN_MAX_STRING) {
fprintf(stderr, "String is too large\n");
return 0;
} else {
if (hdrLen % 4 != 0) {
fprintf(stderr, "Bad length string %d\n", hdrLen);
return 0;
}
result->sizeValue = hdrLen;
memcpy(&result->value, body, hdrLen);
result->value[hdrLen] = 0;
return 1;
}
}
static int stunParseAtrIntegrity(char *body, unsigned int hdrLen,
StunAtrIntegrity *result)
{
if (hdrLen != 20) {
fprintf(stderr, "MessageIntegrity must be 20 bytes\n");
return 0;
} else {
memcpy(&result->hash, body, hdrLen);
return 1;
}
}
static int stunParseMessage(char *buf, unsigned int bufLen, StunMessage *msg)
{
memset(msg, 0, sizeof(*msg));
if (sizeof(StunMsgHdr) > bufLen) {
fprintf(stderr, "Bad message\n");
return 0;
}
memcpy(&msg->msgHdr, buf, sizeof(StunMsgHdr));
msg->msgHdr.msgType = ntohs(msg->msgHdr.msgType);
msg->msgHdr.msgLength = ntohs(msg->msgHdr.msgLength);
if (msg->msgHdr.msgLength + sizeof(StunMsgHdr) != bufLen) {
printf("Message header length doesn't match message size: %d - %d\n",
msg->msgHdr.msgLength, bufLen);
return 0;
}
char *body = buf + sizeof(StunMsgHdr);
unsigned int size = msg->msgHdr.msgLength;
while (size > 0) {
// !jf! should check that there are enough bytes left in the buffer
StunAtrHdr *attr = (StunAtrHdr *)body;
unsigned int attrLen = ntohs(attr->length);
int atrType = ntohs(attr->type);
if (attrLen + 4 > size) {
printf("claims attribute is larger than size of"
" message \"(attribute type= %d \")\n", atrType);
return 0;
}
body += 4; // skip the length and type in attribute header
size -= 4;
switch (atrType) {
case MappedAddress:
msg->hasMappedAddress = 1;
if (stunParseAtrAddr(body, attrLen, &msg->mappedAddress) == 0) {
fprintf(stderr, "problem parsing MappedAddress\n");
return 0;
}
break;
case ResponseAddress:
msg->hasResponseAddress = 1;
if (stunParseAtrAddr(body, attrLen, &msg->responseAddress) ==
0) {
fprintf(stderr, "problem parsing ResponseAddress\n");
return 0;
}
break;
case ChangeRequest:
msg->hasChangeRequest = 1;
if (stunParseAtrChangeRequest(body, attrLen,
&msg->changeRequest) == 0) {
fprintf(stderr, "problem parsing ChangeRequest\n");
return 0;
}
break;
case SourceAddress:
msg->hasSourceAddress = 1;
if (stunParseAtrAddr(body, attrLen, &msg->sourceAddress) == 0) {
fprintf(stderr, "problem parsing SourceAddress\n");
return 0;
}
break;
case ChangedAddress:
msg->hasChangedAddress = 1;
if (stunParseAtrAddr(body, attrLen, &msg->changedAddress) == 0) {
fprintf(stderr, "problem parsing ChangedAddress\n");
return 0;
}
break;
case Username:
msg->hasUsername = 1;
if (stunParseAtrString(body, attrLen, &msg->username) == 0) {
fprintf(stderr, "problem parsing Username\n");
return 0;
}
break;
case Password:
msg->hasPassword = 1;
if (stunParseAtrString(body, attrLen, &msg->password) == 0) {
fprintf(stderr, "problem parsing Password\n");
return 0;
}
break;
case MessageIntegrity:
msg->hasMessageIntegrity = 1;
if (stunParseAtrIntegrity(body, attrLen,
&msg->messageIntegrity) == 0) {
fprintf(stderr, "problem parsing MessageIntegrity\n");
return 0;
}
// read the current HMAC
// look up the password given the user of given the transaction id
// compute the HMAC on the buffer
// decide if they match or not
break;
case ErrorCode:
msg->hasErrorCode = 1;
if (stunParseAtrError(body, attrLen, &msg->errorCode) == 0) {
fprintf(stderr, "problem parsing ErrorCode\n");
return 0;
}
break;
case UnknownAttribute:
msg->hasUnknownAttributes = 1;
if (stunParseAtrUnknown(body, attrLen,
&msg->unknownAttributes) == 0) {
fprintf(stderr, "problem parsing UnknownAttribute\n");
return 0;
}
break;
case ReflectedFrom:
msg->hasReflectedFrom = 1;
if (stunParseAtrAddr(body, attrLen, &msg->reflectedFrom) == 0) {
fprintf(stderr, "problem parsing ReflectedFrom\n");
return 0;
}
break;
case XorMappedAddress:
msg->hasXorMappedAddress = 1;
if (stunParseAtrAddr(body, attrLen, &msg->xorMappedAddress) == 0) {
fprintf(stderr, "problem parsing XorMappedAddress\n");
return 0;
}
break;
case XorOnly:
msg->xorOnly = 1;
break;
case ServerName:
msg->hasServerName = 1;
if (stunParseAtrString(body, attrLen, &msg->serverName) == 0) {
fprintf(stderr, "problem parsing ServerName\n");
return 0;
}
break;
case SecondaryAddress:
msg->hasSecondaryAddress = 1;
if (stunParseAtrAddr(body, attrLen, &msg->secondaryAddress) == 0) {
fprintf(stderr, "problem parsing secondaryAddress\n");
return 0;
}
break;
default:
fprintf(stderr, "Unknown attribute: %d\n", atrType);
if (atrType <= 0x7FFF) {
return 0;
}
break;
}
body += attrLen;
size -= attrLen;
}
return 1;
}
static char *encode16(char *buf, uint16_t data)
{
uint16_t ndata = htons(data);
memcpy(buf, (void *)(&ndata), sizeof(uint16_t));
return buf + sizeof(uint16_t);
}
static char *encode32(char *buf, uint32_t data)
{
uint32_t ndata = htonl(data);
memcpy(buf, (void *)(&ndata), sizeof(uint32_t));
return buf + sizeof(uint32_t);
}
static char *encode(char *buf, const char *data, unsigned int length)
{
memcpy(buf, data, length);
return buf + length;
}
static char *encodeAtrAddress4(char *ptr, uint16_t type,
const StunAtrAddress4 *atr)
{
ptr = encode16(ptr, type);
ptr = encode16(ptr, 8);
*ptr++ = atr->pad;
*ptr++ = IPv4Family;
ptr = encode16(ptr, atr->ipv4.port);
ptr = encode32(ptr, atr->ipv4.addr);
return ptr;
}
static char *encodeAtrChangeRequest(char *ptr, const StunAtrChangeRequest *atr)
{
ptr = encode16(ptr, ChangeRequest);
ptr = encode16(ptr, 4);
ptr = encode32(ptr, atr->value);
return ptr;
}
static char *encodeAtrError(char *ptr, const StunAtrError *atr)
{
ptr = encode16(ptr, ErrorCode);
ptr = encode16(ptr, 6 + atr->sizeReason);
ptr = encode16(ptr, atr->pad);
*ptr++ = atr->errorClass;
*ptr++ = atr->number;
ptr = encode(ptr, atr->reason, atr->sizeReason);
return ptr;
}
static char *encodeAtrUnknown(char *ptr, const StunAtrUnknown *atr)
{
int i;
ptr = encode16(ptr, UnknownAttribute);
ptr = encode16(ptr, 2 + 2 * atr->numAttributes);
for (i = 0; i < atr->numAttributes; i++) {
ptr = encode16(ptr, atr->attrType[i]);
}
return ptr;
}
static char *encodeXorOnly(char *ptr)
{
ptr = encode16(ptr, XorOnly);
return ptr;
}
static char *encodeAtrString(char *ptr, uint16_t type, const StunAtrString *atr)
{
assert(atr->sizeValue % 4 == 0);
ptr = encode16(ptr, type);
ptr = encode16(ptr, atr->sizeValue);
ptr = encode(ptr, atr->value, atr->sizeValue);
return ptr;
}
static char *encodeAtrIntegrity(char *ptr, const StunAtrIntegrity *atr)
{
ptr = encode16(ptr, MessageIntegrity);
ptr = encode16(ptr, 20);
ptr = encode(ptr, atr->hash, sizeof(atr->hash));
return ptr;
}
static unsigned int stunEncodeMessage(const StunMessage *msg,
char *buf,
unsigned int bufLen,
const StunAtrString *password)
{
assert(bufLen >= sizeof(StunMsgHdr));
char *ptr = buf;
ptr = encode16(ptr, msg->msgHdr.msgType);
char *lengthp = ptr;
ptr = encode16(ptr, 0);
ptr =
encode(ptr, (const char *)(msg->msgHdr.id.octet),
sizeof(msg->msgHdr.id));
if (msg->hasMappedAddress) {
ptr = encodeAtrAddress4(ptr, MappedAddress, &msg->mappedAddress);
}
if (msg->hasResponseAddress) {
ptr = encodeAtrAddress4(ptr, ResponseAddress, &msg->responseAddress);
}
if (msg->hasChangeRequest) {
ptr = encodeAtrChangeRequest(ptr, &msg->changeRequest);
}
if (msg->hasSourceAddress) {
ptr = encodeAtrAddress4(ptr, SourceAddress, &msg->sourceAddress);
}
if (msg->hasChangedAddress) {
ptr = encodeAtrAddress4(ptr, ChangedAddress, &msg->changedAddress);
}
if (msg->hasUsername) {
ptr = encodeAtrString(ptr, Username, &msg->username);
}
if (msg->hasPassword) {
ptr = encodeAtrString(ptr, Password, &msg->password);
}
if (msg->hasErrorCode) {
ptr = encodeAtrError(ptr, &msg->errorCode);
}
if (msg->hasUnknownAttributes) {
ptr = encodeAtrUnknown(ptr, &msg->unknownAttributes);
}
if (msg->hasReflectedFrom) {
ptr = encodeAtrAddress4(ptr, ReflectedFrom, &msg->reflectedFrom);
}
if (msg->hasXorMappedAddress) {
ptr = encodeAtrAddress4(ptr, XorMappedAddress, &msg->xorMappedAddress);
}
if (msg->xorOnly) {
ptr = encodeXorOnly(ptr);
}
if (msg->hasServerName) {
ptr = encodeAtrString(ptr, ServerName, &msg->serverName);
}
if (msg->hasSecondaryAddress) {
ptr = encodeAtrAddress4(ptr, SecondaryAddress, &msg->secondaryAddress);
}
if (password->sizeValue > 0) {
StunAtrIntegrity integrity;
computeHmac(integrity.hash, buf, (int)(ptr - buf), password->value,
password->sizeValue);
ptr = encodeAtrIntegrity(ptr, &integrity);
}
encode16(lengthp, (uint16_t)(ptr - buf - sizeof(StunMsgHdr)));
return (int)(ptr - buf);
}
static int stunRand(void)
{
// return 32 bits of random stuff
assert(sizeof(int) == 4);
static int init = 0;
if (!init) {
init = 1;
uint64_t tick;
#if defined(__GNUC__) || ( defined(__i686__) || defined(__i386__) )
asm("rdtsc":"=A"(tick));
#elif defined(__MACH__) || defined(__linux)
int fd = open("/dev/random", O_RDONLY);
read(fd, &tick, sizeof(tick));
close(fd);
#else
#error Need some way to seed the random number generator
#endif
int seed = (int)(tick);
srandom(seed);
}
return random();
}
/// return a random number to use as a port
static int stunRandomPort(void)
{
int min = 0x4000;
int max = 0x7FFF;
int ret = stunRand();
ret = ret | min;
ret = ret & max;
return ret;
}
static int stunParseHostName(char *peerName,
uint32_t *ip, uint16_t *portVal, uint16_t defaultPort)
{
struct in_addr sin_addr;
char host[512];
strncpy(host, peerName, 512);
host[512 - 1] = '\0';
char *port = NULL;
int portNum = defaultPort;
// pull out the port part if present.
char *sep = strchr(host, ':');
if (sep == NULL) {
portNum = defaultPort;
} else {
*sep = '\0';
port = sep + 1;
// set port part
char *endPtr = NULL;
portNum = strtol(port, &endPtr, 10);
if (endPtr != NULL) {
if (*endPtr != '\0') {
portNum = defaultPort;
}
}
}
if (portNum < 1024)
return 0;
if (portNum >= 0xFFFF)
return 0;
// figure out the host part
struct hostent *h;
h = gethostbyname(host);
if (h == NULL) {
fprintf(stderr, "error was %d\n", errno);
*ip = ntohl(0x7F000001L);
return 0;
} else {
sin_addr = *(struct in_addr *)h->h_addr;
*ip = ntohl(sin_addr.s_addr);
}
*portVal = portNum;
return 1;
}
static int stunParseServerName(char *name, stun_addr *addr)
{
// TODO - put in DNS SRV stuff.
int ret = stunParseHostName(name, &addr->addr, &addr->port, STUN_PORT);
if (ret != 1) {
addr->port = 0xFFFF;
}
return ret;
}
static void stunBuildReqSimple(StunMessage * msg,
const StunAtrString *username,
int changePort, int changeIp, unsigned int id)
{
int i;
memset(msg, 0, sizeof(*msg));
msg->msgHdr.msgType = BindRequestMsg;
for (i = 0; i < 16; i += 4) {
int r = stunRand();
msg->msgHdr.id.octet[i + 0] = r >> 0;
msg->msgHdr.id.octet[i + 1] = r >> 8;
msg->msgHdr.id.octet[i + 2] = r >> 16;
msg->msgHdr.id.octet[i + 3] = r >> 24;
}
if (id != 0) {
msg->msgHdr.id.octet[0] = id;
}
msg->hasChangeRequest = 1;
msg->changeRequest.value = (changeIp ? ChangeIpFlag : 0) |
(changePort ? ChangePortFlag : 0);
if (username->sizeValue > 0) {
msg->hasUsername = 1;
msg->username = *username;
}
}
static void stunSendTest(int myFd, stun_addr *dest,
const StunAtrString *username, const StunAtrString *password,
int testNum)
{
int changePort = 0;
int changeIP = 0;
//int discard = 0;
switch (testNum) {
case 1:
case 10:
case 11:
break;
case 2:
//changePort=1;
changeIP = 1;
break;
case 3:
changePort = 1;
break;
case 4:
changeIP = 1;
break;
case 5:
//discard = 1;
break;
default:
fprintf(stderr, "Test %d is unkown\n", testNum);
assert(0);
break;
}
StunMessage req;
memset(&req, 0, sizeof(StunMessage));
stunBuildReqSimple(&req, username, changePort, changeIP, testNum);
char buf[STUN_MAX_MESSAGE_SIZE];
int len = STUN_MAX_MESSAGE_SIZE;
len = stunEncodeMessage(&req, buf, len, password);
sendMessage(myFd, buf, len, dest->addr, dest->port);
// add some delay so the packets don't get sent too quickly
//usleep(10 * 1000);
}
static NatType stunNatType(stun_addr *dest,
int * preservePort, // if set, is return for if NAT preservers ports or not
int * hairpin, // if set, is the return for if NAT will hairpin packets
int port, // port to use for the test, 0 to choose random port
stun_addr * sAddr // NIC to use
)
{
int i;
if (hairpin) {
*hairpin = 0;
}
if (port == 0) {
port = stunRandomPort();
}
uint32_t interfaceIp = 0;
if (sAddr) {
interfaceIp = sAddr->addr;
}
int myFd1 = openPort(port, interfaceIp);
int myFd2 = openPort(port + 1, interfaceIp);
if ((myFd1 == INVALID_SOCKET) || (myFd2 == INVALID_SOCKET)) {
fprintf(stderr, "Some problem opening port/interface to send on\n");
return StunTypeFailure;
}
assert(myFd1 != INVALID_SOCKET);
assert(myFd2 != INVALID_SOCKET);
int respTestI = 0;
int isNat = 1;
//stun_addr testIchangedAddr;
stun_addr testImappedAddr;
int respTestI2 = 0;
int mappedIpSame = 1;
stun_addr testI2mappedAddr;
stun_addr testI2dest = *dest;
int respTestII = 0;
int respTestIII = 0;
int respTestHairpin = 0;
int respTestPreservePort = 0;
memset(&testImappedAddr, 0, sizeof(testImappedAddr));
StunAtrString username;
StunAtrString password;
username.sizeValue = 0;