Correct return type check
[tunudptotcp] / main.cpp
1 #include <fcntl.h>
2 #include <string.h>
3 #include <stropts.h>
4 #include <stdio.h>
5 #include <unistd.h>
6 #include <sys/socket.h>
7 #include <sys/ioctl.h>
8 #include <netinet/in.h>
9 #include <errno.h>
10 #include <arpa/inet.h>
11 #include <stdint.h>
12 #include <linux/if.h>
13 #include <linux/if_tun.h>
14 #include <assert.h>
15
16 #include <atomic>
17 #include <chrono>
18 #include <thread>
19
20 #if __has_include(<sys/random.h>)
21 #include <sys/random.h>
22 #else
23 int getrandom(void* buf, size_t len, unsigned int flags) {
24         FILE* f = fopen("/dev/urandom", "r");
25         int res = fread(buf, len, 1, f);
26         fclose(f);
27         return res;
28 }
29 #endif
30
31
32 static int tun_alloc(char *dev, int queues, int *fds)
33 {
34         struct ifreq ifr;
35         int fd, err, i;
36
37         if (!dev)
38                 return -1;
39
40         memset(&ifr, 0, sizeof(ifr));
41
42         /* Flags: IFF_TUN   - TUN device (no Ethernet headers) 
43         *         IFF_TAP   - TAP device  
44         *
45         *         IFF_NO_PI - Do not provide packet information  
46         */ 
47         ifr.ifr_flags = IFF_TUN | IFF_NO_PI | IFF_MULTI_QUEUE;
48         strncpy(ifr.ifr_name, dev, IFNAMSIZ);
49
50         for (i = 0; i < queues; i++) {
51                 if((fd = open("/dev/net/tun", O_RDWR)) < 0)
52                         goto err;
53                 err = ioctl(fd, TUNSETIFF, (void *) &ifr);
54                 if (err) {
55                         close(fd);
56                         goto err;
57                 }
58                 fds[i] = fd;
59         }
60         return 0;
61 err:
62         for (--i; i >= 0; i--)
63                 close(fds[i]);
64         return err;
65 }
66
67 static int check_ip_header(const unsigned char* buf, ssize_t buf_len, uint8_t expected_type) {
68         if (buf_len < 20) {
69                 // < size than IPv4?
70                 return -1;
71         }
72
73         if ((buf[0] & 0xf0) != (4 << 4)) {
74                 // Only support IPv4
75                 return -1;
76         }
77
78         uint8_t num_words = buf[0] & 0xf;
79         int header_size = num_words * 4;
80         if (header_size < 20) {
81                 fprintf(stderr, "Invalid IPv4 IHL size (%d)\n", header_size);
82                 return -1;
83         }
84
85         if ((((uint16_t)buf[2]) << 8 | buf[3]) != buf_len) {
86                 //fprintf(stderr, "Packet len %u != %ld\n", ((uint16_t)buf[2]) << 8 | buf[3], buf_len);
87                 return -1;
88         }
89
90         if (buf[9] != expected_type) {
91                 fprintf(stderr, "Packet type %u, not %u\n", buf[9], expected_type);
92                 return -1;
93         }
94
95         return header_size;
96 }
97
98 void print_packet(const unsigned char* buf, ssize_t buf_len) {
99         for (ssize_t i = 0; i < buf_len; ) {
100                 for (int j = 0; i < buf_len && j < 20; i++, j++)
101                         fprintf(stderr, "%02x", buf[i]);
102                 fprintf(stderr, "\n");
103         }
104 }
105
106 static uint32_t data_checksum(const unsigned char* buf, size_t len) {
107         uint32_t sum = 0;
108
109         while (len > 1)
110         {
111                 sum += *buf++;
112                 sum += (*buf++) << 8;
113                 if (sum & 0x80000000)
114                         sum = (sum & 0xFFFF) + (sum >> 16);
115                 len -= 2;
116         }
117
118         if (len & 1)
119                 sum += *buf;
120
121         return sum;
122 }
123
124 static uint16_t finalize_data_checksum(uint32_t sum) {
125         while (sum >> 16)
126                 sum = (sum & 0xFFFF) + (sum >> 16);
127
128         return (uint16_t)(~sum);
129 }
130
131 static uint16_t tcp_checksum(const unsigned char* buff, size_t len, in_addr_t src_addr, in_addr_t dest_addr)
132 {
133         uint16_t *ip_src = (uint16_t*)&src_addr, *ip_dst = (uint16_t*)&dest_addr;
134         uint32_t sum = data_checksum(buff, len);
135
136         sum += *(ip_src++);
137         sum += *ip_src;
138         sum += *(ip_dst++);
139         sum += *ip_dst;
140         sum += htons(IPPROTO_TCP);
141         sum += htons(len);
142
143         return finalize_data_checksum(sum);
144 }
145
146 static std::atomic<uint32_t> highest_recvd_seq(0), cur_seq(0);
147 static std::atomic<uint16_t> local_port(0);
148 static uint16_t remote_port;
149 static bool are_server;
150
151 static void build_tcp_header(unsigned char* buf, uint32_t len, int syn, int synack, in_addr_t src_addr, in_addr_t dest_addr) {
152         buf[0 ] = local_port >> 8;         // src port
153         buf[1 ] = local_port;              // src port
154         buf[2 ] = remote_port >> 8;        // dst port
155         buf[3 ] = remote_port;             // dst port
156
157         uint32_t seq = cur_seq.fetch_add((syn || synack) ? 1 : len, std::memory_order_acq_rel);
158         buf[4 ] = seq >> (8 * 3);          // SEQ
159         buf[5 ] = seq >> (8 * 2);          // SEQ
160         buf[6 ] = seq >> (8 * 1);          // SEQ
161         buf[7 ] = seq >> (8 * 0);          // SEQ
162
163         uint32_t their_seq = highest_recvd_seq.load(std::memory_order_relaxed);
164         buf[8 ] = their_seq >> (8 * 3);    // ACK
165         buf[9 ] = their_seq >> (8 * 2);    // ACK
166         buf[10] = their_seq >> (8 * 1);    // ACK
167         buf[11] = their_seq >> (8 * 0);    // ACK
168
169         bool longpkt = syn || synack;
170         buf[12] = (longpkt ? 6 : 5) << 4;  // data offset
171         if (syn)
172                 buf[13] = 1 << 1;              // SYN
173         else if (synack)
174                 buf[13] = (1 << 1) | (1 << 4); // SYN + ACK
175         else if (len == 0)
176                 buf[13] = 1 << 4;              // ACK
177         else
178                 buf[13] = 3 << 3;              // PSH + ACK
179         buf[14] = 0xff;                    // Window Size
180         buf[15] = 0xff;                    // Window Size
181
182         buf[16] = 0x00;                    // Checksum
183         buf[17] = 0x00;                    // Checksum
184         buf[18] = 0x00;                    // URG Pointer
185         buf[19] = 0x00;                    // URG Pointer
186
187         if (longpkt) {
188         buf[20] = 0x01;                    // NOP
189         buf[21] = 0x03;                    // Window Scale
190         buf[22] = 0x03;                    // Window Scale Option Length
191         buf[23] = 0x0e;                    // 1GB Window Size (0xffff << 0x0e)
192         }
193
194         uint16_t checksum = tcp_checksum(buf, len + 20 + (longpkt ? 4 : 0), src_addr, dest_addr);
195         buf[16] = checksum;                // Checksum
196         buf[17] = checksum >> 8;           // Checksum
197 }
198
199 static void build_ip_header(unsigned char* buf, uint32_t len, uint8_t proto, const in_addr_t& src_addr, const in_addr_t& dest_addr) {
200         buf[0 ] = (4 << 4) | 5;    // IPv4 + IHL of 5 (20 bytes)
201         buf[1 ] = 0;               // DSCP 0 + ECN 0
202         buf[2 ] = (len + 20) >> 8; // Length
203         buf[3 ] = (len + 20);      // Length
204         memset(buf + 4, 0, 4);     // Identification and Fragment 0s
205         buf[6 ] = 1 << 6;          // DF bit
206         buf[8 ] = 255;             // TTL
207         buf[9 ] = proto;           // Protocol Number
208         buf[10] = 0;               // Checksum
209         buf[11] = 0;               // Checksum
210
211         memcpy(buf + 12, &src_addr, 4);
212         memcpy(buf + 16, &dest_addr, 4);
213
214         uint16_t checksum = finalize_data_checksum(data_checksum(buf, 20));
215         buf[10] = checksum;
216         buf[11] = checksum >> 8;
217 }
218
219
220 const signed char p_util_hexdigit[256] =
221 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
222   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
223   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
224   0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
225   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
226   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
227   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
228   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
229   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
230   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
231   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
232   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
233   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
234   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
235   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
236   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
237
238 uint32_t hex_to_num(const char* buf) {
239         const char* pbegin = buf;
240         while (p_util_hexdigit[*buf] != -1)
241                 buf++;
242         buf--;
243         uint32_t res = 0;
244         unsigned char* p1 = (unsigned char*)&res;
245         unsigned char* pend = p1 + 4;
246         while (buf >= pbegin && p1 < pend) {
247                 *p1 = p_util_hexdigit[*buf--];
248                 if (buf >= pbegin) {
249                         *p1 |= ((unsigned char)p_util_hexdigit[*buf--] << 4);
250                         p1++;
251                 }
252         }
253
254         return res;
255 }
256
257 #define TUN_IF_COUNT 4
258 static int fdr;
259 static int fd[TUN_IF_COUNT];
260 static struct sockaddr_in dest;
261 static in_addr_t src, tun_src, tun_dest, ipip_src, ipip_dest;
262 static const uint64_t tcp_init_magic = 0x1badcafedeadbeefULL;
263
264 #define PENDING_MESSAGES_BUFF_SIZE (0x3000)
265 #define PACKET_READ_SIZE 1500
266 #define THREAD_POLL_SLEEP_MICS 50
267 struct MessageQueue {
268         std::tuple<sockaddr_in, std::array<unsigned char, PACKET_READ_SIZE>, ssize_t> messagesPendingRingBuff[PENDING_MESSAGES_BUFF_SIZE];
269         std::atomic<uint16_t> nextPendingMessage, nextUndefinedMessage;
270         MessageQueue() : nextPendingMessage(0), nextUndefinedMessage(0) {}
271         MessageQueue(MessageQueue&& q) =delete;
272         MessageQueue(MessageQueue& q) =delete;
273 };
274
275 static MessageQueue tcp_to_tun_queue;
276 static std::chrono::steady_clock::time_point last_ack_recv;
277
278 static void tcp_to_tun() {
279         unsigned char buf[1500];
280         struct sockaddr_in pkt_src;
281         memset(&pkt_src, 0, sizeof(pkt_src));
282
283         while (1) {
284                 socklen_t hostsz = sizeof(pkt_src);
285                 ssize_t nread = recvfrom(fdr, buf, sizeof(buf), 0, (struct sockaddr*)&pkt_src, &hostsz);
286                 if (nread < 0) {
287                         fprintf (stderr, "Failed to read tcp raw sock\n");
288                         exit(-1);
289                 }
290
291                 if (tcp_to_tun_queue.nextPendingMessage == (tcp_to_tun_queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE)
292                         continue;
293
294                 auto& new_msg = tcp_to_tun_queue.messagesPendingRingBuff[tcp_to_tun_queue.nextUndefinedMessage];
295                 std::get<0>(new_msg) = pkt_src;
296                 memcpy(std::get<1>(new_msg).data(), buf, nread);
297                 std::get<2>(new_msg) = nread;
298
299                 tcp_to_tun_queue.nextUndefinedMessage = (tcp_to_tun_queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE;
300         }
301 }
302
303 static void tcp_to_tun_queue_process() {
304         do {
305                 while (tcp_to_tun_queue.nextUndefinedMessage == tcp_to_tun_queue.nextPendingMessage) {
306                         std::this_thread::sleep_for(std::chrono::microseconds(THREAD_POLL_SLEEP_MICS));
307                 }
308
309                 auto& msg = tcp_to_tun_queue.messagesPendingRingBuff[tcp_to_tun_queue.nextPendingMessage];
310
311                 const sockaddr_in& pkt_src = std::get<0>(msg);
312                 unsigned char* buf = std::get<1>(msg).data();
313                 ssize_t nread = std::get<2>(msg);
314
315                 int header_size = check_ip_header(buf, nread, 0x06); // Only support TCP
316                 if (header_size < 0)
317                         continue;
318
319                 if (nread - header_size < 20) {
320                         fprintf(stderr, "Short TCP packet\n");
321                         continue;
322                 }
323
324                 unsigned char* tcp_buf = buf + header_size;
325
326                 if (((tcp_buf[2] << 8) | tcp_buf[3]) != local_port) continue;
327
328                 bool syn = tcp_buf[13] & (1 << 1);
329                 bool ack = tcp_buf[13] & (1 << 4);
330
331                 if (are_server && syn && !ack) {
332                         // We're a server and just got a client
333                         if (tcp_buf[4 ] != uint8_t(tcp_init_magic >> (7 * 8)) ||
334                             tcp_buf[5 ] != uint8_t(tcp_init_magic >> (6 * 8)) ||
335                             tcp_buf[6 ] != uint8_t(tcp_init_magic >> (5 * 8)) ||
336                             tcp_buf[7 ] != uint8_t(tcp_init_magic >> (4 * 8)) ||
337                             tcp_buf[8 ] != uint8_t(tcp_init_magic >> (3 * 8)) ||
338                             tcp_buf[9 ] != uint8_t(tcp_init_magic >> (2 * 8)) ||
339                             tcp_buf[10] != uint8_t(tcp_init_magic >> (1 * 8)) ||
340                             tcp_buf[11] != uint8_t(tcp_init_magic >> (0 * 8)))
341                                 continue;
342
343                         fprintf(stderr, "Got SYN, sending SYNACK\n");
344                         remote_port = (tcp_buf[0] << 8) | tcp_buf[1];
345                         dest = pkt_src;
346                 }
347
348                 if (((tcp_buf[0] << 8) | tcp_buf[1]) != remote_port) continue;
349                 if (pkt_src.sin_addr.s_addr != dest.sin_addr.s_addr) continue;
350
351                 uint8_t num_words = (tcp_buf[12] & 0xf0) >> 4;
352                 int tcp_header_size = num_words * 4;
353                 if (tcp_header_size < 20) {
354                         fprintf(stderr, "Invalid TCP header size (%d)\n", tcp_header_size);
355                         continue;
356                 }
357
358                 highest_recvd_seq = ((((uint32_t)tcp_buf[4]) << (8 * 3)) |
359                                      (((uint32_t)tcp_buf[5]) << (8 * 2)) |
360                                      (((uint32_t)tcp_buf[6]) << (8 * 1)) |
361                                      (((uint32_t)tcp_buf[7]) << (8 * 0))) +
362                                      (syn ? 1 : nread - header_size - tcp_header_size);
363
364                 if (ack)
365                         last_ack_recv = std::chrono::steady_clock::now();
366
367                 if (are_server && syn && !ack) {
368                         build_tcp_header(tcp_buf, 0, 0, 1, src, dest.sin_addr.s_addr);
369
370                         ssize_t res = sendto(fdr, tcp_buf, 20 + 4, 0, (struct sockaddr*)&dest, sizeof(dest));
371                         if (res < 0) {
372                                 int err = errno;
373                                 fprintf(stderr, "Failed to send SYNACK with err %d (%s)\n", err, strerror(err));
374                         }
375                 } else if (!syn) {
376                         tcp_buf += tcp_header_size - 20;
377
378                         // Replace TCP with IPv4 header
379                         //build_ip_header(tcp_buf, nread - tcp_header_size - header_size, 0x01, ipip_dest, ipip_src); // ICMP
380                         build_ip_header(tcp_buf, nread - tcp_header_size - header_size, 0x11, ipip_dest, ipip_src); // UDP
381                         // Add IPIP header
382                         build_ip_header(tcp_buf - 20, nread - tcp_header_size - header_size + 20, 0x04, tun_dest, tun_src);
383
384                         write(fd[0], tcp_buf - 20, nread - tcp_header_size - header_size + 40);
385                 }
386         } while ((tcp_to_tun_queue.nextPendingMessage = (tcp_to_tun_queue.nextPendingMessage + 1) % PENDING_MESSAGES_BUFF_SIZE) || true);
387 }
388
389 static std::atomic_int tun_if_thread(0), tun_if_process_thread(0);
390 static std::atomic_bool pause_tun_read_reinit_tcp(false);
391 static MessageQueue tun_to_tcp_queue[TUN_IF_COUNT];
392
393 static void tun_to_tcp() {
394         unsigned char buf[PACKET_READ_SIZE];
395
396         int thread = tun_if_thread.fetch_add(1);
397         MessageQueue& queue = tun_to_tcp_queue[thread];
398
399         while (1) {
400                 ssize_t nread = read(fd[thread], buf, sizeof(buf));
401                 if (pause_tun_read_reinit_tcp)
402                         continue;
403
404                 if (nread < 0) {
405                         fprintf (stderr, "Failed to read tun if\n");
406                         continue;
407                 }
408
409                 if (queue.nextPendingMessage == (queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE)
410                         continue;
411
412                 auto& new_msg = queue.messagesPendingRingBuff[queue.nextUndefinedMessage];
413                 memcpy(std::get<1>(new_msg).data(), buf, nread);
414                 std::get<2>(new_msg) = nread;
415
416                 queue.nextUndefinedMessage = (queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE;
417         }
418 }
419
420 static void tun_to_tcp_queue_process() {
421         int thread = tun_if_process_thread.fetch_add(1);
422         MessageQueue& queue = tun_to_tcp_queue[thread];
423
424         do {
425                 while (queue.nextUndefinedMessage == queue.nextPendingMessage) {
426                         std::this_thread::sleep_for(std::chrono::microseconds(THREAD_POLL_SLEEP_MICS));
427                 }
428                 if (pause_tun_read_reinit_tcp)
429                         continue;
430
431                 auto& msg = queue.messagesPendingRingBuff[queue.nextPendingMessage];
432
433                 unsigned char* buf = std::get<1>(msg).data();
434                 ssize_t nread = std::get<2>(msg);
435
436                 int header_size = check_ip_header(buf, nread, 0x04); // Only support IPIP
437                 if (header_size < 0)
438                         continue;
439
440                 int internal_header_size = check_ip_header(buf + header_size, nread - header_size, 0x11); // Only support UDP
441                 //int internal_header_size = check_ip_header(buf + header_size, nread - header_size, 0x01); // Only support ICMP
442                 if (internal_header_size < 0)
443                         continue;
444
445                 if (internal_header_size + header_size + 8 > nread) {
446                         fprintf(stderr, "Short UDP-in-IPIP packet\n");
447                         continue;
448                 }
449
450                 size_t tcp_start_offset = header_size + internal_header_size - 20;
451                 build_tcp_header(buf + tcp_start_offset, nread - tcp_start_offset - 20, 0, 0, src, dest.sin_addr.s_addr);
452
453                 ssize_t res = sendto(fdr, buf + tcp_start_offset, nread - tcp_start_offset, 0, (struct sockaddr*)&dest, sizeof(dest));
454                 if (res < 0) {
455                         int err = errno;
456                         fprintf(stderr, "Failed to send with err %d (%s)\n", err, strerror(err));
457                 }
458
459         } while ((queue.nextPendingMessage = (queue.nextPendingMessage + 1) % PENDING_MESSAGES_BUFF_SIZE) || true);
460 }
461
462 int do_init() {
463         //
464         // Send SYN and SYN/ACK
465         //
466
467         if (!are_server) {
468                 if (local_port) // Doing a re-init
469                         pause_tun_read_reinit_tcp = true;
470
471                 uint16_t local_port_tmp = 0;
472                 while (local_port_tmp < 1024)
473                         assert(getrandom(&local_port_tmp, sizeof(local_port_tmp), 0) == sizeof(local_port_tmp));
474
475                 local_port = local_port_tmp;
476         }
477
478         uint32_t starting_ack = 0, starting_seq = 0;
479         memcpy(&starting_ack, &tcp_init_magic, 4);
480         memcpy(&starting_seq, ((const unsigned char*)&tcp_init_magic) + 4, 4);
481         highest_recvd_seq = starting_ack;
482         cur_seq = starting_seq;
483
484         if (!pause_tun_read_reinit_tcp) { // Not doing a re-init
485                 std::thread t(&tcp_to_tun);
486                 std::thread t2(&tcp_to_tun_queue_process);
487                 t.detach();
488                 t2.detach();
489         }
490
491         unsigned char buf[1500];
492         if (!are_server) {
493                 build_tcp_header(buf, 0, 1, 0, src, dest.sin_addr.s_addr);
494                 ssize_t res = sendto(fdr, buf, 20 + 4, 0, (struct sockaddr*)&dest, sizeof(dest));
495                 if (res < 0) {
496                         int err = errno;
497                         fprintf(stderr, "Failed to send initial SYN with err %d (%s)\n", err, strerror(err));
498                         return -1;
499                 }
500         }
501
502         int i;
503         for (i = 0; i < 1000 && highest_recvd_seq == starting_ack; i++)
504                 std::this_thread::sleep_for(std::chrono::milliseconds(10));
505         if (i == 1000) // Will come back in 10 seconds
506                 return 0;
507
508         if (!are_server) {
509                 fprintf(stderr, "Got SYNACK, sending ACK and starting tun listen\n");
510
511                 build_tcp_header(buf, 0, 0, 0, src, dest.sin_addr.s_addr);
512                 ssize_t res = sendto(fdr, buf, 20, 0, (struct sockaddr*)&dest, sizeof(dest));
513                 if (res < 0) {
514                         int err = errno;
515                         fprintf(stderr, "Failed to send initial ACK with err %d (%s)\n", err, strerror(err));
516                         return -1;
517                 }
518         }
519
520         if (pause_tun_read_reinit_tcp) {
521                 pause_tun_read_reinit_tcp = false;
522         } else {
523                 for (int i = 0; i < TUN_IF_COUNT; i++) {
524                         std::thread t3(&tun_to_tcp);
525                         std::thread t4(&tun_to_tcp_queue_process);
526                         t3.detach();
527                         t4.detach();
528                 }
529         }
530
531         return 0;
532 }
533
534 int main(int argc, char* argv[]) {
535         assert(argc > 1 && "Need tun name");
536         assert(argc > 2 && "Need tun remote host");
537         assert(argc > 3 && "Need tun local host");
538         assert(argc > 4 && "Need ipip remote host");
539         assert(argc > 5 && "Need ipip local host");
540         assert(argc > 6 && "Need server port");
541         assert(argc > 7 && "Need mode (client or server)");
542         assert(argc > 8 && "Need src host");
543         if (std::string(argv[7]) == std::string("client"))
544                 assert(argc > 9 && "Need dest host");
545
546         assert(std::string(argv[7]) == std::string("client") || std::string(argv[7]) == std::string("server"));
547         are_server = (std::string(argv[7]) == std::string("server"));
548
549         //
550         // Parse args into variables
551         //
552
553         char tun_name[IFNAMSIZ];
554
555         memset(tun_name, 0, sizeof(tun_name));
556         strcpy(tun_name, argv[1]);
557
558         tun_dest = inet_addr(argv[2]);
559         tun_src = inet_addr(argv[3]);
560
561         ipip_dest = inet_addr(argv[4]);
562         ipip_src = inet_addr(argv[5]);
563
564         if (are_server) {
565                 local_port = atoi(argv[6]);
566                 remote_port = 0;
567         } else {
568                 // Get local port in do_init() so that we pick a new one on reload
569                 remote_port = atoi(argv[6]);
570         }
571
572         src = inet_addr(argv[8]);
573
574         memset(&dest, 0, sizeof(dest));
575         if (!are_server) {
576                 dest.sin_family = AF_INET;
577                 dest.sin_addr.s_addr = inet_addr(argv[9]);
578         }
579
580         //
581         // Create tun and bind to sockets...
582         //
583
584         if (tun_alloc(tun_name, TUN_IF_COUNT, fd) != 0) {
585                 fprintf(stderr, "Failed to alloc tun if\n");
586                 return -1;
587         }
588
589         fdr = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
590         if (fdr < 0) {
591                 fprintf(stderr, "Failed to get raw socket\n");
592                 return -1;
593         }
594
595         int res = do_init();
596         if (res)
597                 return res;
598
599         while (true) {
600                 std::this_thread::sleep_for(std::chrono::seconds(15));
601                 if (!are_server && last_ack_recv < std::chrono::steady_clock::now() - std::chrono::seconds(15)) {
602                         res = do_init();
603                         if (res)
604                                 return res;
605                 }
606         }
607 }