Don't assume sa.sa_family is a short int.
[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 verbose;
42 static bool readonly;
43 static bool writeonly;
44 static int in = 0;
45 static int out = 1;
46
47 static bool send_data(void *handle, uint8_t type, const void *data, size_t len) {
48         char hex[len * 2 + 1];
49         bin2hex(data, hex, len);
50         if(verbose)
51                 fprintf(stderr, "Sending %d bytes of data:\n%s\n", (int)len, hex);
52         const int *sock = handle;
53         if(send(*sock, data, len, 0) != len)
54                 return false;
55         return true;
56 }
57
58 static bool receive_record(void *handle, uint8_t type, const void *data, uint16_t len) {
59         if(verbose)
60                 fprintf(stderr, "Received type %d record of %hu bytes:\n", type, len);
61         if(!writeonly)
62                 write(out, data, len);
63         return true;
64 }
65
66 static struct option const long_options[] = {
67         {"datagram", no_argument, NULL, 'd'},
68         {"quit", no_argument, NULL, 'q'},
69         {"readonly", no_argument, NULL, 'r'},
70         {"writeonly", no_argument, NULL, 'w'},
71         {"packet-loss", required_argument, NULL, 'L'},
72         {"replay-window", required_argument, NULL, 'W'},
73         {"verbose", required_argument, NULL, 'v'},
74         {"help", no_argument, NULL, 1},
75         {NULL, 0, NULL, 0}
76 };
77
78 const char *program_name;
79
80 static void usage() {
81         fprintf(stderr, "Usage: %s [options] my_ed25519_key_file his_ed25519_key_file [host] port\n\n", program_name);
82         fprintf(stderr, "Valid options are:\n"
83                         "  -d, --datagram          Enable datagram mode.\n"
84                         "  -q, --quit              Quit when EOF occurs on stdin.\n"
85                         "  -r, --readonly          Only send data from the socket to stdout.\n"
86 #ifdef HAVE_LINUX
87                         "  -t, --tun               Use a tun device instead of stdio.\n"
88 #endif
89                         "  -w, --writeonly         Only send data from stdin to the socket.\n"
90                         "  -L, --packet-loss RATE  Fake packet loss of RATE percent.\n"
91                         "  -R, --replay-window N   Set replay window to N bytes.\n"
92                         "  -v, --verbose           Display debug messages.\n"
93                         "\n");
94         fprintf(stderr, "Report bugs to tinc@tinc-vpn.org.\n");
95 }
96
97 int main(int argc, char *argv[]) {
98         program_name = argv[0];
99         bool initiator = false;
100         bool datagram = false;
101 #ifdef HAVE_LINUX
102         bool tun = false;
103 #endif
104         int packetloss = 0;
105         int r;
106         int option_index = 0;
107         ecdsa_t *mykey = NULL, *hiskey = NULL;
108         bool quit = false;
109
110         while((r = getopt_long(argc, argv, "dqrtwL:W:v", long_options, &option_index)) != EOF) {
111                 switch (r) {
112                         case 0:   /* long option */
113                                 break;
114
115                         case 'd': /* datagram mode */
116                                 datagram = true;
117                                 break;
118
119                         case 'q': /* close connection on EOF from stdin */
120                                 quit = true;
121                                 break;
122
123                         case 'r': /* read only */
124                                 readonly = true;
125                                 break;
126
127                         case 't': /* read only */
128 #ifdef HAVE_LINUX
129                                 tun = true;
130 #else
131                                 fprintf(stderr, "--tun is only supported on Linux.\n");
132                                 usage();
133                                 return 1;
134 #endif
135                                 break;
136
137                         case 'w': /* write only */
138                                 writeonly = true;
139                                 break;
140
141                         case 'L': /* packet loss rate */
142                                 packetloss = atoi(optarg);
143                                 break;
144
145                         case 'W': /* replay window size */
146                                 sptps_replaywin = atoi(optarg);
147                                 break;
148
149                         case 'v': /* be verbose */
150                                 verbose = true;
151                                 break;
152
153                         case '?': /* wrong options */
154                                 usage();
155                                 return 1;
156
157                         case 1: /* help */
158                                 usage();
159                                 return 0;
160
161                         default:
162                                 break;
163                 }
164         }
165
166         argc -= optind - 1;
167         argv += optind - 1;
168
169         if(argc < 4 || argc > 5) {
170                 fprintf(stderr, "Wrong number of arguments.\n");
171                 usage();
172                 return 1;
173         }
174
175         if(argc > 4)
176                 initiator = true;
177
178         srand(time(NULL));
179
180 #ifdef HAVE_LINUX
181         if(tun) {
182                 in = out = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
183                 if(in < 0) {
184                         fprintf(stderr, "Could not open tun device: %s\n", strerror(errno));
185                         return 1;
186                 }
187                 struct ifreq ifr = {
188                         .ifr_flags = IFF_TUN
189                 };
190                 if(ioctl(in, TUNSETIFF, &ifr)) {
191                         fprintf(stderr, "Could not configure tun interface: %s\n", strerror(errno));
192                         return 1;
193                 }
194                 ifr.ifr_name[IFNAMSIZ - 1] = 0;
195                 fprintf(stderr, "Using tun interface %s\n", ifr.ifr_name);
196         }
197 #endif
198
199 #ifdef HAVE_MINGW
200         static struct WSAData wsa_state;
201         if(WSAStartup(MAKEWORD(2, 2), &wsa_state))
202                 return 1;
203 #endif
204
205         struct addrinfo *ai, hint;
206         memset(&hint, 0, sizeof hint);
207
208         hint.ai_family = AF_UNSPEC;
209         hint.ai_socktype = datagram ? SOCK_DGRAM : SOCK_STREAM;
210         hint.ai_protocol = datagram ? IPPROTO_UDP : IPPROTO_TCP;
211         hint.ai_flags = initiator ? 0 : AI_PASSIVE;
212
213         if(getaddrinfo(initiator ? argv[3] : NULL, initiator ? argv[4] : argv[3], &hint, &ai) || !ai) {
214                 fprintf(stderr, "getaddrinfo() failed: %s\n", sockstrerror(sockerrno));
215                 return 1;
216         }
217
218         int sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
219         if(sock < 0) {
220                 fprintf(stderr, "Could not create socket: %s\n", sockstrerror(sockerrno));
221                 return 1;
222         }
223
224         int one = 1;
225         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof one);
226
227         if(initiator) {
228                 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
229                         fprintf(stderr, "Could not connect to peer: %s\n", sockstrerror(sockerrno));
230                         return 1;
231                 }
232                 fprintf(stderr, "Connected\n");
233         } else {
234                 if(bind(sock, ai->ai_addr, ai->ai_addrlen)) {
235                         fprintf(stderr, "Could not bind socket: %s\n", sockstrerror(sockerrno));
236                         return 1;
237                 }
238
239                 if(!datagram) {
240                         if(listen(sock, 1)) {
241                                 fprintf(stderr, "Could not listen on socket: %s\n", sockstrerror(sockerrno));
242                                 return 1;
243                         }
244                         fprintf(stderr, "Listening...\n");
245
246                         sock = accept(sock, NULL, NULL);
247                         if(sock < 0) {
248                                 fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
249                                 return 1;
250                         }
251                 } else {
252                         fprintf(stderr, "Listening...\n");
253
254                         char buf[65536];
255                         struct sockaddr addr;
256                         socklen_t addrlen = sizeof addr;
257
258                         if(recvfrom(sock, buf, sizeof buf, MSG_PEEK, &addr, &addrlen) <= 0) {
259                                 fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
260                                 return 1;
261                         }
262
263                         if(connect(sock, &addr, addrlen)) {
264                                 fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
265                                 return 1;
266                         }
267                 }
268
269                 fprintf(stderr, "Connected\n");
270         }
271
272         crypto_init();
273
274         FILE *fp = fopen(argv[1], "r");
275         if(!fp) {
276                 fprintf(stderr, "Could not open %s: %s\n", argv[1], strerror(errno));
277                 return 1;
278         }
279         if(!(mykey = ecdsa_read_pem_private_key(fp)))
280                 return 1;
281         fclose(fp);
282
283         fp = fopen(argv[2], "r");
284         if(!fp) {
285                 fprintf(stderr, "Could not open %s: %s\n", argv[2], strerror(errno));
286                 return 1;
287         }
288         if(!(hiskey = ecdsa_read_pem_public_key(fp)))
289                 return 1;
290         fclose(fp);
291
292         if(verbose)
293                 fprintf(stderr, "Keys loaded\n");
294
295         sptps_t s;
296         if(!sptps_start(&s, &sock, initiator, datagram, mykey, hiskey, "sptps_test", 10, send_data, receive_record))
297                 return 1;
298
299         while(true) {
300                 if(writeonly && readonly)
301                         break;
302
303                 char buf[65535] = "";
304
305                 fd_set fds;
306                 FD_ZERO(&fds);
307 #ifndef HAVE_MINGW
308                 if(!readonly && s.instate)
309                         FD_SET(in, &fds);
310 #endif
311                 FD_SET(sock, &fds);
312                 if(select(sock + 1, &fds, NULL, NULL, NULL) <= 0)
313                         return 1;
314
315                 if(FD_ISSET(in, &fds)) {
316                         ssize_t len = read(in, buf, sizeof buf);
317                         if(len < 0) {
318                                 fprintf(stderr, "Could not read from stdin: %s\n", strerror(errno));
319                                 return 1;
320                         }
321                         if(len == 0) {
322                                 if(quit)
323                                         break;
324                                 readonly = true;
325                                 continue;
326                         }
327                         if(buf[0] == '#')
328                                 s.outseqno = atoi(buf + 1);
329                         if(buf[0] == '^')
330                                 sptps_send_record(&s, SPTPS_HANDSHAKE, NULL, 0);
331                         else if(buf[0] == '$') {
332                                 sptps_force_kex(&s);
333                                 if(len > 1)
334                                         sptps_send_record(&s, 0, buf, len);
335                         } else
336                         if(!sptps_send_record(&s, buf[0] == '!' ? 1 : 0, buf, (len == 1 && buf[0] == '\n') ? 0 : buf[0] == '*' ? sizeof buf : len))
337                                 return 1;
338                 }
339
340                 if(FD_ISSET(sock, &fds)) {
341                         ssize_t len = recv(sock, buf, sizeof buf, 0);
342                         if(len < 0) {
343                                 fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
344                                 return 1;
345                         }
346                         if(len == 0) {
347                                 fprintf(stderr, "Connection terminated by peer.\n");
348                                 break;
349                         }
350                         if(verbose) {
351                                 char hex[len * 2 + 1];
352                                 bin2hex(buf, hex, len);
353                                 fprintf(stderr, "Received %d bytes of data:\n%s\n", (int)len, hex);
354                         }
355                         if(packetloss && (rand() % 100) < packetloss) {
356                                 if(verbose)
357                                         fprintf(stderr, "Dropped.\n");
358                                 continue;
359                         }
360                         char *bufp = buf;
361                         while(len) {
362                                 size_t done = sptps_receive_data(&s, bufp, len);
363                                 if(!done) {
364                                         if(!datagram)
365                                                 return 1;
366                                 } else {
367                                         break;
368                                 }
369
370                                 bufp += done;
371                                 len -= done;
372                         }
373                 }
374         }
375
376         if(!sptps_stop(&s))
377                 return 1;
378
379         return 0;
380 }