nat_traversal.c 10.5 KB
Newer Older
Jason Fong's avatar
Jason Fong committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>  
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>

#include "nat_traversal.h"

#define MAX_PORT 65535
#define MIN_PORT 1025
#define NUM_OF_PORTS 700

#define MSG_BUF_SIZE 512

// file scope variables
static int nums[MAX_PORT - MIN_PORT];

Fong's avatar
Fong committed
25
26
static int send_to_punch_server(client* c) {
    int n = send(c->sfd, c->buf, c->msg_buf - c->buf, 0);
Jason Fong's avatar
Jason Fong committed
27
28
29
30
31
32
33
34
    c->msg_buf= c->buf;

    return n;
}

static int get_peer_info(client* cli, uint32_t peer_id, struct peer_info *peer) {
    cli->msg_buf = encode16(cli->msg_buf, GetPeerInfo);
    cli->msg_buf = encode32(cli->msg_buf, peer_id);
Fong's avatar
Fong committed
35
    if (-1 == send_to_punch_server(cli)) {
Jason Fong's avatar
Jason Fong committed
36
37
38
        return -1;
    }

Fong's avatar
Fong committed
39
40
    int n_bytes = recv(cli->sfd, (void*)peer, sizeof(struct peer_info), 0);
    if (n_bytes <= 0) {
Jason Fong's avatar
Jason Fong committed
41
        return -1;
Fong's avatar
Fong committed
42
43
44
45
46
47
    } else if (n_bytes == 1) {
        // offline
        return 1;
    } else {
        peer->port = ntohs(peer->port);
        peer->type = ntohs(peer->type);
Jason Fong's avatar
Jason Fong committed
48

Fong's avatar
Fong committed
49
50
        return 0;
    }
Jason Fong's avatar
Jason Fong committed
51
52
53
54
55
56
57
58
59
60
61
62
}

static int send_dummy_udp_packet(int fd, struct sockaddr_in addr) {
    char dummy = 'c';

    struct timeval tv = {5, 0};
    setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv, sizeof(tv));
    
    return sendto(fd, &dummy, 1, 0, (struct sockaddr *)&addr, sizeof(addr));
}


Fong's avatar
Fong committed
63
static int punch_hole(struct sockaddr_in peer_addr, int ttl) {
Jason Fong's avatar
Jason Fong committed
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
    int hole = socket(AF_INET, SOCK_DGRAM, 0);
    if (hole != -1) {

        // no need to choose local port for now, let OS do that
        /*struct sockaddr_in local_addr;
          local_addr.sin_family = AF_INET;
          local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
          local_addr.sin_port = htons(DEFAULT_LOCAL_PORT + 1); 
          if (bind(hole, (struct sockaddr *)&local_addr, sizeof(local_addr))) {
              if (errno == EADDRINUSE) {
                  printf("addr in use, try another port\n");
                  return -1; 
              }   
          } */

        /* TODO we can use traceroute to get the number of hops to the peer
         * to make sure this packet woudn't reach the peer but get through the NAT of itself
         */
        setsockopt(hole, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));

        // send short ttl packets to avoid triggering flooding protection of NAT in front of peer
        if (send_dummy_udp_packet(hole, peer_addr) < 0) {
            return -1;
        }
    }

    return hole;
}

static int wait_for_peer(int* socks, int sock_num, struct timeval *timeout) {
    fd_set fds;  
    int max_fd = 0;
    FD_ZERO(&fds);

    int i;
    for (i = 0; i < sock_num; ++i) {
        FD_SET(socks[i], &fds);
        if (socks[i] > max_fd) {
            max_fd = socks[i];
        }
    }
    int ret = select(max_fd + 1, &fds, NULL, NULL, timeout);

    int index = -1;
    if (ret > 0) {
        for (i = 0; i < sock_num; ++i) {
            if (FD_ISSET(socks[i], &fds)) {
                index = i;
                break;
            }
        }
    } else {
        // timeout or error
    }

    // one of the fds is ready, close others
    if (index != -1) {
        for (i = 0; i < sock_num; ++i) {
            if (index != i) {
                close(socks[i]);
            }
        }

        return socks[index];
    }

    return -1;
}

static void shuffle(int *num, int len) {
    srand(time(NULL));

    // Fisher-Yates shuffle algorithm
    int i, r, temp;
    for (i = len - 1; i > 0; i--) {
        r = rand() % i;

        temp = num[i];
        num[i] = num[r];
        num[r] = temp;
    }
}

Fong's avatar
Fong committed
147
static int connect_to_symmetric_nat(client* c, uint32_t peer_id, struct peer_info remote_peer) {
Jason Fong's avatar
Jason Fong committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    // TODO choose port prediction strategy

    /* 
	* according to birthday paradox, probability that port randomly chosen from [1024, 65535] 
	* will collide with another one chosen by the same way is 
	* p(n) = 1-(64511!/(64511^n*64511!))
	* where '!' is the factorial operator, n is the number of ports chosen.
	* P(100)=0.073898
	* P(200)=0.265667
	* P(300)=0.501578
	* P(400)=0.710488
	* P(500)=0.856122
	* P(600)=0.938839
    * but symmetric NAT has port sensitive filter for incoming packet
    * which makes the probalility decline dramatically. 
    * Moreover, symmetric NATs don't really allocate ports randomly.
	*/	
    struct sockaddr_in peer_addr;

    peer_addr.sin_family = AF_INET;
Fong's avatar
Fong committed
168
    peer_addr.sin_addr.s_addr = inet_addr(remote_peer.ip);
Jason Fong's avatar
Jason Fong committed
169
170
171
172
173
174
175

    int *holes = malloc(NUM_OF_PORTS * sizeof(int));
    shuffle(nums, MAX_PORT - MIN_PORT + 1);

    int i = 0;
    for (; i < NUM_OF_PORTS;) {
        uint16_t port = nums[i];
Fong's avatar
Fong committed
176
        if (port != remote_peer.port) { // exclude the used one
Jason Fong's avatar
Jason Fong committed
177
178
            peer_addr.sin_port = htons(port);

Fong's avatar
Fong committed
179
            if ((holes[i] = punch_hole(peer_addr, c->ttl)) < 0) {
Jason Fong's avatar
Jason Fong committed
180
                // NAT in front of us wound't tolerate too many ports used by one application
Fong's avatar
Fong committed
181
                verbose_log("%s, NAT flooding protection triggered, try %d times\n", strerror(errno), i);
Jason Fong's avatar
Jason Fong committed
182
183
184
185
186
187
188
189
190
191
                break;
            }

            ++i;
        } else {
            nums[i] = nums[1000];
            continue;
        }
    }

Fong's avatar
Fong committed
192
    // hole punched, notify remote peer via punch server
Jason Fong's avatar
Jason Fong committed
193
194
    c->msg_buf = encode16(c->msg_buf, NotifyPeer);
    c->msg_buf = encode32(c->msg_buf, peer_id);
Fong's avatar
Fong committed
195
    send_to_punch_server(c);
Jason Fong's avatar
Jason Fong committed
196
197
198
199
200
201
202
203
204
205

    struct timeval timeout={10, 0};
    int fd = wait_for_peer(holes, i, &timeout);
    if (fd > 0) {
        on_connected(fd);
    } else {
        int j = 0;
        for (; j < i; ++j) {
            close(holes[j]);
        }
Fong's avatar
Fong committed
206
        printf("timout, not connected\n");
Jason Fong's avatar
Jason Fong committed
207
208
209
210
211
212
213
214
215
216
217
218
    }

    return 0;
}

// run in another thread
static void* server_notify_handler(void* data) {
    int server_sock = *(int*)data;
    struct peer_info peer;

    // wait for notification 
    printf("waiting for notification...\n");
219
220
221
222
    for (; ;) {
        if (recv(server_sock, &peer, sizeof peer, 0) > 0) {
            break;
        }
Jason Fong's avatar
Jason Fong committed
223
    }
Fong's avatar
Fong committed
224

Jason Fong's avatar
Jason Fong committed
225
226
227
    peer.port = ntohs(peer.port);
    peer.type = ntohs(peer.type);

Fong's avatar
Fong committed
228
    printf("recved command, ready to connect to %s:%d\n", peer.ip, peer.port);
Jason Fong's avatar
Jason Fong committed
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

    struct sockaddr_in peer_addr;

    peer_addr.sin_family = AF_INET;
    peer_addr.sin_addr.s_addr = inet_addr(peer.ip);

    int sock_array[NUM_OF_PORTS];
    int i = 0;

    shuffle(nums, MAX_PORT - MIN_PORT + 1);
    // send probe packets, check if connected with peer, if yes, stop probing
    for (; i < NUM_OF_PORTS;) {
        if (nums[i] == peer.port) {
            nums[i] = nums[1000]; // TODO
            continue;
        }
        if ((sock_array[i] = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
            printf("failed to create socket, send %d probe packets\n", i);
            break;
        }

        peer_addr.sin_port = htons(nums[i]);

        // let OS choose available ports
        if (send_dummy_udp_packet(sock_array[i], peer_addr) < 0) {
            printf("may trigger flooding protection\n");
            break;
        }

        /* add socket to FD_SET and check if connected
        * set both fields of the timeval structure to zero 
        * to make select() return immediately
        */
        struct timeval tv = {0, 0};
        int fd = wait_for_peer(sock_array, ++i, &tv);
        if (fd > 0) {
            // connected
            on_connected(fd);

            // TODO
            return NULL;
        }
    }

    struct timeval tv = {10, 0};
    int fd = wait_for_peer(sock_array, i, &tv);
    if (fd > 0) {
        on_connected(fd);
    } else {
        int j = 0;
        for (j = 0; j < i; ++j) {
            close(sock_array[j]);
        }
    }

    // TODO wait for next notification

    return NULL;
}

Fong's avatar
Fong committed
289
int enroll(struct peer_info self, struct sockaddr_in punch_server, client* c) {
Jason Fong's avatar
Jason Fong committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
    int i, temp;
    for (i = 0, temp = MIN_PORT; temp <= MAX_PORT; i++, temp++) {
        nums[i] = temp;
    }

    int server_sock = socket(AF_INET, SOCK_STREAM, 0);

    if (connect(server_sock, (struct sockaddr *)&punch_server, sizeof(punch_server)) < 0) {
        printf("failed to connect to punch server\n");

        return -1;
    }

    c->sfd = server_sock;
    c->msg_buf = c->buf;
    c->msg_buf = encode16(c->msg_buf, Enroll);
    c->msg_buf = encode(c->msg_buf, self.ip, 16);
    c->msg_buf = encode16(c->msg_buf, self.port);
    c->msg_buf = encode16(c->msg_buf, self.type);

Fong's avatar
Fong committed
310
    if (-1 == send_to_punch_server(c)) {
Jason Fong's avatar
Jason Fong committed
311
312
313
        return -1;
    }

Fong's avatar
Fong committed
314
315
    // wait for server reply to get own ID
    uint32_t peer_id = 0;
316
317
318
319
    struct timeval tv;
    tv.tv_sec = 5;
    tv.tv_usec = 0;
    setsockopt(server_sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
Fong's avatar
Fong committed
320
    int n = recv(server_sock, &peer_id, sizeof(uint32_t), 0);
321
    if (n != sizeof(uint32_t)) {
Fong's avatar
Fong committed
322
323
324
        return -1;
    }

Fong's avatar
Fong committed
325
    c->id = ntohl(peer_id);
Fong's avatar
Fong committed
326

Fong's avatar
Fong committed
327
328
329
    return 0;
}

Fong's avatar
Fong committed
330
pthread_t wait_for_command(int* server_sock)
Fong's avatar
Fong committed
331
332
{
    // wait for command from punch server in another thread
Jason Fong's avatar
Jason Fong committed
333
    pthread_t thread_id;
Fong's avatar
Fong committed
334
    pthread_create(&thread_id, NULL, server_notify_handler, (void*)server_sock);
Jason Fong's avatar
Jason Fong committed
335

Fong's avatar
Fong committed
336
    return thread_id;
Jason Fong's avatar
Jason Fong committed
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
}

void on_connected(int sock) {
    char buf[MSG_BUF_SIZE] = {0};
    struct sockaddr_in remote_addr;
    socklen_t fromlen = sizeof remote_addr;
    recvfrom(sock, buf, MSG_BUF_SIZE, 0, (struct sockaddr *)&remote_addr, &fromlen);

    printf("connected with peer from %s:%d\n", inet_ntoa(remote_addr.sin_addr), ntohs(remote_addr.sin_port));
    printf("recv %s\n", buf);

    // restore the ttl
    int ttl = 64;
    setsockopt(sock, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
    sendto(sock, "hello, peer", strlen("hello, peer"), 0, (struct sockaddr *)&remote_addr, sizeof(remote_addr));
}

int connect_to_peer(client* cli, uint32_t peer_id) {
    struct peer_info peer;
Fong's avatar
Fong committed
356
357
358
359
    int n = get_peer_info(cli, peer_id, &peer);
    if (n) {
        verbose_log("get_peer_info() return %d\n", n);
        printf("failed to get info of remote peer\n");
Jason Fong's avatar
Jason Fong committed
360
361
362
363

        return -1;
    }

Fong's avatar
Fong committed
364
365
    printf("peer %d: %s:%d, nat type: %s\n", peer_id, peer.ip, peer.port, get_nat_desc(peer.type));

Jason Fong's avatar
Jason Fong committed
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
    // choose less restricted peer as initiator
    switch(peer.type) {
        case OpenInternet:
            // todo
            break;
        case FullCone:
            break;
        case RestricNAT:
            // todo
            break;
        case RestricPortNAT:
            // todo 
            break;
        case SymmetricNAT:
            if (cli->type == SymmetricNAT) {
                connect_to_symmetric_nat(cli, peer_id, peer);
            }
            else {
                // todo
            }
            break;
        default:
            printf("unknown nat type\n");
            return -1;
            // log
    }

    return 0;
}