Added comments and unfold deep "if"-construct in timeout_handler
[tinc] / src / sptps_test.c
1 /*
2     sptps_test.c -- Simple Peer-to-Peer Security test program
3     Copyright (C) 2011-2014 Guus Sliepen <guus@tinc-vpn.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #ifdef HAVE_LINUX
23 #include <linux/if_tun.h>
24 #endif
25
26 #include <getopt.h>
27
28 #include "crypto.h"
29 #include "ecdsa.h"
30 #include "sptps.h"
31 #include "utils.h"
32
33 // Symbols necessary to link with logger.o
34 bool send_request(void *c, const char *msg, ...) { return false; }
35 struct list_t *connection_list = NULL;
36 bool send_meta(void *c, const char *msg , int len) { return false; }
37 char *logfilename = NULL;
38 bool do_detach = false;
39 struct timeval now;
40
41 static bool special;
42 static bool verbose;
43 static bool readonly;
44 static bool writeonly;
45 static int in = 0;
46 static int out = 1;
47
48 static bool send_data(void *handle, uint8_t type, const void *data, size_t len) {
49         char hex[len * 2 + 1];
50         bin2hex(data, hex, len);
51         if(verbose)
52                 fprintf(stderr, "Sending %d bytes of data:\n%s\n", (int)len, hex);
53         const int *sock = handle;
54         if(send(*sock, data, len, 0) != len)
55                 return false;
56         return true;
57 }
58
59 static bool receive_record(void *handle, uint8_t type, const void *data, uint16_t len) {
60         if(verbose)
61                 fprintf(stderr, "Received type %d record of %hu bytes:\n", type, len);
62         if(!writeonly)
63                 write(out, data, len);
64         return true;
65 }
66
67 static struct option const long_options[] = {
68         {"datagram", no_argument, NULL, 'd'},
69         {"quit", no_argument, NULL, 'q'},
70         {"readonly", no_argument, NULL, 'r'},
71         {"writeonly", no_argument, NULL, 'w'},
72         {"packet-loss", required_argument, NULL, 'L'},
73         {"replay-window", required_argument, NULL, 'W'},
74         {"special", no_argument, NULL, 's'},
75         {"verbose", required_argument, NULL, 'v'},
76         {"help", no_argument, NULL, 1},
77         {NULL, 0, NULL, 0}
78 };
79
80 const char *program_name;
81
82 static void usage() {
83         fprintf(stderr, "Usage: %s [options] my_ed25519_key_file his_ed25519_key_file [host] port\n\n", program_name);
84         fprintf(stderr, "Valid options are:\n"
85                         "  -d, --datagram          Enable datagram mode.\n"
86                         "  -q, --quit              Quit when EOF occurs on stdin.\n"
87                         "  -r, --readonly          Only send data from the socket to stdout.\n"
88 #ifdef HAVE_LINUX
89                         "  -t, --tun               Use a tun device instead of stdio.\n"
90 #endif
91                         "  -w, --writeonly         Only send data from stdin to the socket.\n"
92                         "  -L, --packet-loss RATE  Fake packet loss of RATE percent.\n"
93                         "  -R, --replay-window N   Set replay window to N bytes.\n"
94                         "  -s, --special           Enable special handling of lines starting with #, ^ and $.\n"
95                         "  -v, --verbose           Display debug messages.\n"
96                         "\n");
97         fprintf(stderr, "Report bugs to tinc@tinc-vpn.org.\n");
98 }
99
100 int main(int argc, char *argv[]) {
101         program_name = argv[0];
102         bool initiator = false;
103         bool datagram = false;
104 #ifdef HAVE_LINUX
105         bool tun = false;
106 #endif
107         int packetloss = 0;
108         int r;
109         int option_index = 0;
110         ecdsa_t *mykey = NULL, *hiskey = NULL;
111         bool quit = false;
112
113         while((r = getopt_long(argc, argv, "dqrstwL:W:v", long_options, &option_index)) != EOF) {
114                 switch (r) {
115                         case 0:   /* long option */
116                                 break;
117
118                         case 'd': /* datagram mode */
119                                 datagram = true;
120                                 break;
121
122                         case 'q': /* close connection on EOF from stdin */
123                                 quit = true;
124                                 break;
125
126                         case 'r': /* read only */
127                                 readonly = true;
128                                 break;
129
130                         case 't': /* read only */
131 #ifdef HAVE_LINUX
132                                 tun = true;
133 #else
134                                 fprintf(stderr, "--tun is only supported on Linux.\n");
135                                 usage();
136                                 return 1;
137 #endif
138                                 break;
139
140                         case 'w': /* write only */
141                                 writeonly = true;
142                                 break;
143
144                         case 'L': /* packet loss rate */
145                                 packetloss = atoi(optarg);
146                                 break;
147
148                         case 'W': /* replay window size */
149                                 sptps_replaywin = atoi(optarg);
150                                 break;
151
152                         case 'v': /* be verbose */
153                                 verbose = true;
154                                 break;
155
156                         case 's': /* special character handling */
157                                 special = true;
158                                 break;
159
160                         case '?': /* wrong options */
161                                 usage();
162                                 return 1;
163
164                         case 1: /* help */
165                                 usage();
166                                 return 0;
167
168                         default:
169                                 break;
170                 }
171         }
172
173         argc -= optind - 1;
174         argv += optind - 1;
175
176         if(argc < 4 || argc > 5) {
177                 fprintf(stderr, "Wrong number of arguments.\n");
178                 usage();
179                 return 1;
180         }
181
182         if(argc > 4)
183                 initiator = true;
184
185         srand(time(NULL));
186
187 #ifdef HAVE_LINUX
188         if(tun) {
189                 in = out = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
190                 if(in < 0) {
191                         fprintf(stderr, "Could not open tun device: %s\n", strerror(errno));
192                         return 1;
193                 }
194                 struct ifreq ifr = {
195                         .ifr_flags = IFF_TUN
196                 };
197                 if(ioctl(in, TUNSETIFF, &ifr)) {
198                         fprintf(stderr, "Could not configure tun interface: %s\n", strerror(errno));
199                         return 1;
200                 }
201                 ifr.ifr_name[IFNAMSIZ - 1] = 0;
202                 fprintf(stderr, "Using tun interface %s\n", ifr.ifr_name);
203         }
204 #endif
205
206 #ifdef HAVE_MINGW
207         static struct WSAData wsa_state;
208         if(WSAStartup(MAKEWORD(2, 2), &wsa_state))
209                 return 1;
210 #endif
211
212         struct addrinfo *ai, hint;
213         memset(&hint, 0, sizeof hint);
214
215         hint.ai_family = AF_UNSPEC;
216         hint.ai_socktype = datagram ? SOCK_DGRAM : SOCK_STREAM;
217         hint.ai_protocol = datagram ? IPPROTO_UDP : IPPROTO_TCP;
218         hint.ai_flags = initiator ? 0 : AI_PASSIVE;
219
220         if(getaddrinfo(initiator ? argv[3] : NULL, initiator ? argv[4] : argv[3], &hint, &ai) || !ai) {
221                 fprintf(stderr, "getaddrinfo() failed: %s\n", sockstrerror(sockerrno));
222                 return 1;
223         }
224
225         int sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
226         if(sock < 0) {
227                 fprintf(stderr, "Could not create socket: %s\n", sockstrerror(sockerrno));
228                 return 1;
229         }
230
231         int one = 1;
232         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof one);
233
234         if(initiator) {
235                 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
236                         fprintf(stderr, "Could not connect to peer: %s\n", sockstrerror(sockerrno));
237                         return 1;
238                 }
239                 fprintf(stderr, "Connected\n");
240         } else {
241                 if(bind(sock, ai->ai_addr, ai->ai_addrlen)) {
242                         fprintf(stderr, "Could not bind socket: %s\n", sockstrerror(sockerrno));
243                         return 1;
244                 }
245
246                 if(!datagram) {
247                         if(listen(sock, 1)) {
248                                 fprintf(stderr, "Could not listen on socket: %s\n", sockstrerror(sockerrno));
249                                 return 1;
250                         }
251                         fprintf(stderr, "Listening...\n");
252
253                         sock = accept(sock, NULL, NULL);
254                         if(sock < 0) {
255                                 fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
256                                 return 1;
257                         }
258                 } else {
259                         fprintf(stderr, "Listening...\n");
260
261                         char buf[65536];
262                         struct sockaddr addr;
263                         socklen_t addrlen = sizeof addr;
264
265                         if(recvfrom(sock, buf, sizeof buf, MSG_PEEK, &addr, &addrlen) <= 0) {
266                                 fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
267                                 return 1;
268                         }
269
270                         if(connect(sock, &addr, addrlen)) {
271                                 fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
272                                 return 1;
273                         }
274                 }
275
276                 fprintf(stderr, "Connected\n");
277         }
278
279         crypto_init();
280
281         FILE *fp = fopen(argv[1], "r");
282         if(!fp) {
283                 fprintf(stderr, "Could not open %s: %s\n", argv[1], strerror(errno));
284                 return 1;
285         }
286         if(!(mykey = ecdsa_read_pem_private_key(fp)))
287                 return 1;
288         fclose(fp);
289
290         fp = fopen(argv[2], "r");
291         if(!fp) {
292                 fprintf(stderr, "Could not open %s: %s\n", argv[2], strerror(errno));
293                 return 1;
294         }
295         if(!(hiskey = ecdsa_read_pem_public_key(fp)))
296                 return 1;
297         fclose(fp);
298
299         if(verbose)
300                 fprintf(stderr, "Keys loaded\n");
301
302         sptps_t s;
303         if(!sptps_start(&s, &sock, initiator, datagram, mykey, hiskey, "sptps_test", 10, send_data, receive_record))
304                 return 1;
305
306         while(true) {
307                 if(writeonly && readonly)
308                         break;
309
310                 char buf[65535] = "";
311
312                 fd_set fds;
313                 FD_ZERO(&fds);
314 #ifndef HAVE_MINGW
315                 if(!readonly && s.instate)
316                         FD_SET(in, &fds);
317 #endif
318                 FD_SET(sock, &fds);
319                 if(select(sock + 1, &fds, NULL, NULL, NULL) <= 0)
320                         return 1;
321
322                 if(FD_ISSET(in, &fds)) {
323                         ssize_t len = read(in, buf, sizeof buf);
324                         if(len < 0) {
325                                 fprintf(stderr, "Could not read from stdin: %s\n", strerror(errno));
326                                 return 1;
327                         }
328                         if(len == 0) {
329                                 if(quit)
330                                         break;
331                                 readonly = true;
332                                 continue;
333                         }
334                         if(special && buf[0] == '#')
335                                 s.outseqno = atoi(buf + 1);
336                         if(special && buf[0] == '^')
337                                 sptps_send_record(&s, SPTPS_HANDSHAKE, NULL, 0);
338                         else if(special && buf[0] == '$') {
339                                 sptps_force_kex(&s);
340                                 if(len > 1)
341                                         sptps_send_record(&s, 0, buf, len);
342                         } else
343                         if(!sptps_send_record(&s, buf[0] == '!' ? 1 : 0, buf, (len == 1 && buf[0] == '\n') ? 0 : buf[0] == '*' ? sizeof buf : len))
344                                 return 1;
345                 }
346
347                 if(FD_ISSET(sock, &fds)) {
348                         ssize_t len = recv(sock, buf, sizeof buf, 0);
349                         if(len < 0) {
350                                 fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
351                                 return 1;
352                         }
353                         if(len == 0) {
354                                 fprintf(stderr, "Connection terminated by peer.\n");
355                                 break;
356                         }
357                         if(verbose) {
358                                 char hex[len * 2 + 1];
359                                 bin2hex(buf, hex, len);
360                                 fprintf(stderr, "Received %d bytes of data:\n%s\n", (int)len, hex);
361                         }
362                         if(packetloss && (rand() % 100) < packetloss) {
363                                 if(verbose)
364                                         fprintf(stderr, "Dropped.\n");
365                                 continue;
366                         }
367                         char *bufp = buf;
368                         while(len) {
369                                 size_t done = sptps_receive_data(&s, bufp, len);
370                                 if(!done) {
371                                         if(!datagram)
372                                                 return 1;
373                                 } else {
374                                         break;
375                                 }
376
377                                 bufp += done;
378                                 len -= done;
379                         }
380                 }
381         }
382
383         if(!sptps_stop(&s))
384                 return 1;
385
386         return 0;
387 }