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