blob: af23f3a2e368b1c22d5f78ea4c28f3dc5a9342e8 [file] [log] [blame]
Willy Tarreau84393aa2016-11-12 11:29:46 +01001#include <sys/resource.h>
2#include <sys/select.h>
3#include <sys/types.h>
4#include <sys/socket.h>
5#include <sys/stat.h>
6#include <sys/time.h>
7#include <sys/ioctl.h>
8#include <arpa/inet.h>
9#include <netinet/in.h>
10#include <netinet/tcp.h>
11
12#include <ctype.h>
13#include <errno.h>
14#include <fcntl.h>
15#include <netdb.h>
16#include <poll.h>
17#include <signal.h>
18#include <stdarg.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <time.h>
23#include <unistd.h>
24
25
26struct err_msg {
27 int size;
28 int len;
29 char msg[0];
30};
31
32const int zero = 0;
33const int one = 1;
34const struct linger nolinger = { .l_onoff = 1, .l_linger = 0 };
35
36#define TRASH_SIZE 65536
37static char trash[TRASH_SIZE];
38
39/* display the message and exit with the code */
40__attribute__((noreturn)) void die(int code, const char *format, ...)
41{
42 va_list args;
43
44 va_start(args, format);
45 vfprintf(stderr, format, args);
46 va_end(args);
47 exit(code);
48}
49
50/* display the usage message and exit with the code */
51__attribute__((noreturn)) void usage(int code, const char *arg0)
52{
53 die(code, "Usage: %s [<ip>:]port [action*]\n", arg0);
54}
55
56struct err_msg *alloc_err_msg(int size)
57{
58 struct err_msg *err;
59
60 err = malloc(sizeof(*err) + size);
61 if (err) {
62 err->len = 0;
63 err->size = size;
64 }
65 return err;
66}
67
68
69/* converts str in the form [[<ipv4>|<ipv6>|<hostname>]:]port to struct sockaddr_storage.
70 * Returns < 0 with err set in case of error.
71 */
72int addr_to_ss(char *str, struct sockaddr_storage *ss, struct err_msg *err)
73{
74 char *port_str;
75 int port;
76
77 memset(ss, 0, sizeof(*ss));
78
79 /* look for the addr/port delimiter, it's the last colon. If there's no
80 * colon, it's 0:<port>.
81 */
82 if ((port_str = strrchr(str, ':')) == NULL) {
83 port = atoi(str);
84 if (port <= 0 || port > 65535) {
85 err->len = snprintf(err->msg, err->size, "Missing/invalid port number: '%s'\n", str);
86 return -1;
87 }
88
89 ss->ss_family = AF_INET;
90 ((struct sockaddr_in *)ss)->sin_port = htons(port);
91 ((struct sockaddr_in *)ss)->sin_addr.s_addr = INADDR_ANY;
92 return 0;
93 }
94
95 *port_str++ = 0;
96
97 if (strrchr(str, ':') != NULL) {
98 /* IPv6 address contains ':' */
99 ss->ss_family = AF_INET6;
100 ((struct sockaddr_in6 *)ss)->sin6_port = htons(atoi(port_str));
101
102 if (!inet_pton(ss->ss_family, str, &((struct sockaddr_in6 *)ss)->sin6_addr)) {
103 err->len = snprintf(err->msg, err->size, "Invalid server address: '%s'\n", str);
104 return -1;
105 }
106 }
107 else {
108 ss->ss_family = AF_INET;
109 ((struct sockaddr_in *)ss)->sin_port = htons(atoi(port_str));
110
111 if (*str == '*' || *str == '\0') { /* INADDR_ANY */
112 ((struct sockaddr_in *)ss)->sin_addr.s_addr = INADDR_ANY;
113 return 0;
114 }
115
116 if (!inet_pton(ss->ss_family, str, &((struct sockaddr_in *)ss)->sin_addr)) {
117 struct hostent *he = gethostbyname(str);
118
119 if (he == NULL) {
120 err->len = snprintf(err->msg, err->size, "Invalid server name: '%s'\n", str);
121 return -1;
122 }
123 ((struct sockaddr_in *)ss)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
124 }
125 }
126
127 return 0;
128}
129
130/* waits up to one second on fd <fd> for events <events> (POLLIN|POLLOUT).
131 * returns poll's status.
132 */
133int wait_on_fd(int fd, int events)
134{
135 struct pollfd pollfd;
136 int ret;
137
138 do {
139 pollfd.fd = fd;
140 pollfd.events = events;
141 ret = poll(&pollfd, 1, 1000);
142 } while (ret == -1 && errno == EINTR);
143
144 return ret;
145}
146
147int tcp_set_nodelay(int sock, const char *arg)
148{
149 return setsockopt(sock, SOL_TCP, TCP_NODELAY, &one, sizeof(one));
150}
151
152int tcp_set_nolinger(int sock, const char *arg)
153{
154 return setsockopt(sock, SOL_SOCKET, SO_LINGER, (struct linger *) &nolinger, sizeof(struct linger));
155}
156
157int tcp_set_noquickack(int sock, const char *arg)
158{
159 /* warning: do not use during connect if nothing is to be sent! */
160 return setsockopt(sock, SOL_TCP, TCP_QUICKACK, &zero, sizeof(zero));
161}
162
163/* Try to listen to address <sa>. Return the fd or -1 in case of error */
164int tcp_listen(const struct sockaddr_storage *sa, const char *arg)
165{
166 int sock;
167 int backlog;
168
169 if (arg[1])
170 backlog = atoi(arg + 1);
171 else
172 backlog = 1000;
173
174 if (backlog < 0 || backlog > 65535) {
175 fprintf(stderr, "backlog must be between 0 and 65535 inclusive (was %d)\n", backlog);
176 return -1;
177 }
178
179 sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
180 if (sock < 0) {
181 perror("socket()");
182 return -1;
183 }
184
185 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
186 perror("setsockopt(SO_REUSEADDR)");
187 goto fail;
188 }
189
190#ifdef SO_REUSEPORT
191 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (char *) &one, sizeof(one)) == -1) {
192 perror("setsockopt(SO_REUSEPORT)");
193 goto fail;
194 }
195#endif
196 if (bind(sock, (struct sockaddr *)sa, sa->ss_family == AF_INET6 ?
197 sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)) == -1) {
198 perror("bind");
199 goto fail;
200 }
201
202 if (listen(sock, backlog) == -1) {
203 perror("listen");
204 goto fail;
205 }
206
207 return sock;
208 fail:
209 close(sock);
210 return -1;
211}
212
213/* accepts a socket from listening socket <sock>, and returns it (or -1 in case of error) */
214int tcp_accept(int sock, const char *arg)
215{
216 int count;
217 int newsock;
218
219 if (arg[1])
220 count = atoi(arg + 1);
221 else
222 count = 1;
223
224 if (count <= 0) {
225 fprintf(stderr, "accept count must be > 0 or unset (was %d)\n", count);
226 return -1;
227 }
228
229 do {
230 newsock = accept(sock, NULL, NULL);
231 if (newsock < 0) { // TODO: improve error handling
232 if (errno == EINTR || errno == EAGAIN || errno == ECONNABORTED)
233 continue;
234 perror("accept()");
235 break;
236 }
237
238 if (count > 1)
239 close(newsock);
240 count--;
241 } while (count > 0);
242
243 fcntl(newsock, F_SETFL, O_NONBLOCK);
244 return newsock;
245}
246
247/* Try to establish a new connection to <sa>. Return the fd or -1 in case of error */
248int tcp_connect(const struct sockaddr_storage *sa, const char *arg)
249{
250 int sock;
251
252 sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
253 if (sock < 0)
254 return -1;
255
256 if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
257 goto fail;
258
259 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1)
260 goto fail;
261
262 if (connect(sock, (const struct sockaddr *)sa, sizeof(*sa)) < 0) {
263 if (errno != EINPROGRESS)
264 goto fail;
265 }
266
267 return sock;
268 fail:
269 close(sock);
270 return -1;
271}
272
273/* receives N bytes from the socket and returns 0 (or -1 in case of error).
274 * When no arg is passed, receives anything and stops. Otherwise reads the
275 * requested amount of data. 0 means read as much as possible.
276 */
277int tcp_recv(int sock, const char *arg)
278{
279 int count = -1; // stop at first read
280 int ret;
281
282 if (arg[1]) {
283 count = atoi(arg + 1);
284 if (count < 0) {
285 fprintf(stderr, "recv count must be >= 0 or unset (was %d)\n", count);
286 return -1;
287 }
288 }
289
290 while (1) {
291 ret = recv(sock, NULL, (count > 0) ? count : INT_MAX, MSG_NOSIGNAL | MSG_TRUNC);
292 if (ret < 0) {
293 if (errno == EINTR)
294 continue;
295 if (errno != EAGAIN)
296 return -1;
297 while (!wait_on_fd(sock, POLLIN));
298 continue;
299 }
300 if (!ret)
301 break;
302
303 if (!count)
304 continue;
305 else if (count > 0)
306 count -= ret;
307
308 if (count <= 0)
309 break;
310 }
311
312 return 0;
313}
314
315/* sends N bytes to the socket and returns 0 (or -1 in case of error). If not
316 * set, sends only one block. Sending zero means try to send forever.
317 */
318int tcp_send(int sock, const char *arg)
319{
320 int count = -1; // stop after first block
321 int ret;
322
323 if (arg[1]) {
324 count = atoi(arg + 1);
325 if (count <= 0) {
326 fprintf(stderr, "send count must be >= 0 or unset (was %d)\n", count);
327 return -1;
328 }
329 }
330
331 while (1) {
332 ret = send(sock, trash,
333 (count > 0) && (count < sizeof(trash)) ? count : sizeof(trash),
334 MSG_NOSIGNAL | ((count > sizeof(trash)) ? MSG_MORE : 0));
335 if (ret < 0) {
336 if (errno == EINTR)
337 continue;
338 if (errno != EAGAIN)
339 return -1;
340 while (!wait_on_fd(sock, POLLOUT));
341 continue;
342 }
343 if (!count)
344 continue;
345 else if (count > 0)
346 count -= ret;
347
348 if (count <= 0)
349 break;
350 }
351
352 return 0;
353}
354
355/* echoes N bytes to the socket and returns 0 (or -1 in case of error). If not
356 * set, echoes only the first block. Zero means forward forever.
357 */
358int tcp_echo(int sock, const char *arg)
359{
360 int count = -1; // echo forever
361 int ret;
362 int rcvd;
363
364 if (arg[1]) {
365 count = atoi(arg + 1);
366 if (count < 0) {
367 fprintf(stderr, "send count must be >= 0 or unset (was %d)\n", count);
368 return -1;
369 }
370 }
371
372 rcvd = 0;
373 while (1) {
374 if (rcvd <= 0) {
375 /* no data pending */
376 rcvd = recv(sock, trash, (count > 0) && (count < sizeof(trash)) ? count : sizeof(trash), MSG_NOSIGNAL);
377 if (rcvd < 0) {
378 if (errno == EINTR)
379 continue;
380 if (errno != EAGAIN)
381 return -1;
382 while (!wait_on_fd(sock, POLLIN));
383 continue;
384 }
385 if (!rcvd)
386 break;
387 }
388 else {
389 /* some data still pending */
390 ret = send(sock, trash, rcvd, MSG_NOSIGNAL | ((count > rcvd) ? MSG_MORE : 0));
391 if (ret < 0) {
392 if (errno == EINTR)
393 continue;
394 if (errno != EAGAIN)
395 return -1;
396 while (!wait_on_fd(sock, POLLOUT));
397 continue;
398 }
399 rcvd -= ret;
400 if (rcvd)
401 continue;
402
403 if (!count)
404 continue;
405 else if (count > 0)
406 count -= ret;
407
408 if (count <= 0)
409 break;
410 }
411 }
412 return 0;
413}
414
415/* waits for an event on the socket, usually indicates an accept for a
416 * listening socket and a connect for an outgoing socket.
417 */
418int tcp_wait(int sock, const char *arg)
419{
420 struct pollfd pollfd;
421 int delay = -1; // wait forever
422 int ret;
423
424 if (arg[1]) {
425 delay = atoi(arg + 1);
426 if (delay < 0) {
427 fprintf(stderr, "wait time must be >= 0 or unset (was %d)\n", delay);
428 return -1;
429 }
430 }
431
432 /* FIXME: this doesn't take into account delivered signals */
433 do {
434 pollfd.fd = sock;
435 pollfd.events = POLLIN | POLLOUT;
436 ret = poll(&pollfd, 1, delay);
437 } while (ret == -1 && errno == EINTR);
438
439 return 0;
440}
441
442/* waits for the input data to be present */
443int tcp_wait_in(int sock, const char *arg)
444{
445 struct pollfd pollfd;
446 int ret;
447
448 do {
449 pollfd.fd = sock;
450 pollfd.events = POLLIN;
451 ret = poll(&pollfd, 1, 1000);
452 } while (ret == -1 && errno == EINTR);
453 return 0;
454}
455
456/* waits for the output queue to be empty */
457int tcp_wait_out(int sock, const char *arg)
458{
459 struct pollfd pollfd;
460 int ret;
461
462 do {
463 pollfd.fd = sock;
464 pollfd.events = POLLOUT;
465 ret = poll(&pollfd, 1, 1000);
466 } while (ret == -1 && errno == EINTR);
467
468 /* Now wait for data to leave the socket */
469 do {
470 if (ioctl(sock, TIOCOUTQ, &ret) < 0)
471 return -1;
472 } while (ret > 0);
473 return 0;
474}
475
476/* delays processing for <time> milliseconds, 100 by default */
477int tcp_pause(int sock, const char *arg)
478{
479 struct pollfd pollfd;
480 int delay = 100;
481 int ret;
482
483 if (arg[1]) {
484 delay = atoi(arg + 1);
485 if (delay < 0) {
486 fprintf(stderr, "wait time must be >= 0 or unset (was %d)\n", delay);
487 return -1;
488 }
489 }
490
491 usleep(delay * 1000);
492 return 0;
493}
494
495int main(int argc, char **argv)
496{
497 struct sockaddr_storage ss;
498 struct err_msg err;
499 const char *arg0;
500 int arg;
501 int sock;
502
503 arg0 = argv[0];
504 if (argc < 2)
505 usage(1, arg0);
506
507 if (addr_to_ss(argv[1], &ss, &err) < 0)
508 die(1, "%s\n", err.msg);
509
510 sock = -1;
511 for (arg = 2; arg < argc; arg++) {
512 switch (argv[arg][0]) {
513 case 'L':
514 /* silently ignore existing connections */
515 if (sock == -1)
516 sock = tcp_listen(&ss, argv[arg]);
517 if (sock < 0)
518 die(1, "Fatal: tcp_listen() failed.\n");
519 break;
520
521 case 'C':
522 /* silently ignore existing connections */
523 if (sock == -1)
524 sock = tcp_connect(&ss, argv[arg]);
525 if (sock < 0)
526 die(1, "Fatal: tcp_connect() failed.\n");
527 break;
528
529 case 'A':
530 if (sock < 0)
531 die(1, "Fatal: tcp_accept() on non-socket.\n");
532 sock = tcp_accept(sock, argv[arg]);
533 if (sock < 0)
534 die(1, "Fatal: tcp_accept() failed.\n");
535 break;
536
537 case 'T':
538 if (sock < 0)
539 die(1, "Fatal: tcp_set_nodelay() on non-socket.\n");
540 if (tcp_set_nodelay(sock, argv[arg]) < 0)
541 die(1, "Fatal: tcp_set_nodelay() failed.\n");
542 break;
543
544 case 'G':
545 if (sock < 0)
546 die(1, "Fatal: tcp_set_nolinger() on non-socket.\n");
547 if (tcp_set_nolinger(sock, argv[arg]) < 0)
548 die(1, "Fatal: tcp_set_nolinger() failed.\n");
549 break;
550
551 case 'Q':
552 if (sock < 0)
553 die(1, "Fatal: tcp_set_noquickack() on non-socket.\n");
554 if (tcp_set_noquickack(sock, argv[arg]) < 0)
555 die(1, "Fatal: tcp_set_noquickack() failed.\n");
556 break;
557
558 case 'R':
559 if (sock < 0)
560 die(1, "Fatal: tcp_recv() on non-socket.\n");
561 if (tcp_recv(sock, argv[arg]) < 0)
562 die(1, "Fatal: tcp_recv() failed.\n");
563 break;
564
565 case 'S':
566 if (sock < 0)
567 die(1, "Fatal: tcp_send() on non-socket.\n");
568 if (tcp_send(sock, argv[arg]) < 0)
569 die(1, "Fatal: tcp_send() failed.\n");
570 break;
571
572 case 'E':
573 if (sock < 0)
574 die(1, "Fatal: tcp_echo() on non-socket.\n");
575 if (tcp_echo(sock, argv[arg]) < 0)
576 die(1, "Fatal: tcp_echo() failed.\n");
577 break;
578
579 case 'P':
580 if (tcp_pause(sock, argv[arg]) < 0)
581 die(1, "Fatal: tcp_pause() failed.\n");
582 break;
583
584 case 'W':
585 if (sock < 0)
586 die(1, "Fatal: tcp_wait() on non-socket.\n");
587 if (tcp_wait(sock, argv[arg]) < 0)
588 die(1, "Fatal: tcp_wait() failed.\n");
589 break;
590
591 case 'I':
592 if (sock < 0)
593 die(1, "Fatal: tcp_wait_in() on non-socket.\n");
594 if (tcp_wait_in(sock, argv[arg]) < 0)
595 die(1, "Fatal: tcp_wait_in() failed.\n");
596 break;
597
598 case 'O':
599 if (sock < 0)
600 die(1, "Fatal: tcp_wait_out() on non-socket.\n");
601 if (tcp_wait_out(sock, argv[arg]) < 0)
602 die(1, "Fatal: tcp_wait_out() failed.\n");
603 break;
604
605 case 'K':
606 if (sock < 0 || close(sock) < 0)
607 die(1, "Fatal: close() on non-socket.\n");
608 sock = -1;
609 break;
610
611 case 'F':
612 /* ignore errors on shutdown() as they are common */
613 if (sock >= 0)
614 shutdown(sock, SHUT_WR);
615 break;
616
617 default:
618 usage(1, arg0);
619 }
620 }
621 return 0;
622}