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