]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/netcat/netcat.c
Merge once more from ^/vendor/llvm-project/release-10.x, to get the
[FreeBSD/FreeBSD.git] / contrib / netcat / netcat.c
1 /* $OpenBSD: netcat.c,v 1.130 2015/07/26 19:12:28 chl Exp $ */
2 /*
3  * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *   notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *   notice, this list of conditions and the following disclaimer in the
13  *   documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *   derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30
31 /*
32  * Re-written nc(1) for OpenBSD. Original implementation by
33  * *Hobbit* <hobbit@avian.org>.
34  */
35
36 #include <errno.h>
37 #include <stdio.h>
38 #include <sys/arb.h>
39 #include <sys/limits.h>
40 #include <sys/types.h>
41 #include <sys/sbuf.h>
42 #include <sys/socket.h>
43 #include <sys/sysctl.h>
44 #include <sys/qmath.h>
45 #include <sys/stats.h>
46 #include <sys/time.h>
47 #include <sys/uio.h>
48 #include <sys/un.h>
49
50 #include <netinet/in.h>
51 #ifdef IPSEC
52 #include <netipsec/ipsec.h>
53 #endif
54 #include <netinet/tcp.h>
55 #include <netinet/ip.h>
56 #include <arpa/telnet.h>
57
58 #include <err.h>
59 #include <getopt.h>
60 #include <fcntl.h>
61 #include <limits.h>
62 #include <netdb.h>
63 #include <poll.h>
64 #include <signal.h>
65 #include <stdarg.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69 #include "atomicio.h"
70
71 #ifndef SUN_LEN
72 #define SUN_LEN(su) \
73         (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
74 #endif
75
76 #define PORT_MAX        65535
77 #define PORT_MAX_LEN    6
78 #define UNIX_DG_TMP_SOCKET_SIZE 19
79
80 #define POLL_STDIN 0
81 #define POLL_NETOUT 1
82 #define POLL_NETIN 2
83 #define POLL_STDOUT 3
84 #define BUFSIZE 16384
85
86 /* Command Line Options */
87 int     dflag;                                  /* detached, no stdin */
88 int     Fflag;                                  /* fdpass sock to stdout */
89 unsigned int iflag;                             /* Interval Flag */
90 int     kflag;                                  /* More than one connect */
91 int     lflag;                                  /* Bind to local port */
92 int     FreeBSD_Mflag;                          /* Measure using stats(3) */
93 int     Nflag;                                  /* shutdown() network socket */
94 int     nflag;                                  /* Don't do name look up */
95 int     FreeBSD_Oflag;                          /* Do not use TCP options */
96 char   *Pflag;                                  /* Proxy username */
97 char   *pflag;                                  /* Localport flag */
98 int     rflag;                                  /* Random ports flag */
99 char   *sflag;                                  /* Source Address */
100 int     tflag;                                  /* Telnet Emulation */
101 int     uflag;                                  /* UDP - Default to TCP */
102 int     vflag;                                  /* Verbosity */
103 int     xflag;                                  /* Socks proxy */
104 int     zflag;                                  /* Port Scan Flag */
105 int     Dflag;                                  /* sodebug */
106 int     Iflag;                                  /* TCP receive buffer size */
107 int     Oflag;                                  /* TCP send buffer size */
108 int     Sflag;                                  /* TCP MD5 signature option */
109 int     Tflag = -1;                             /* IP Type of Service */
110 int     rtableid = -1;
111
112 int timeout = -1;
113 int family = AF_UNSPEC;
114 char *portlist[PORT_MAX+1];
115 char *unix_dg_tmp_socket;
116
117 void    atelnet(int, unsigned char *, unsigned int);
118 void    build_ports(char *);
119 void    help(void);
120 int     local_listen(char *, char *, struct addrinfo);
121 void    readwrite(int);
122 void    fdpass(int nfd) __attribute__((noreturn));
123 int     remote_connect(const char *, const char *, struct addrinfo);
124 int     timeout_connect(int, const struct sockaddr *, socklen_t);
125 int     socks_connect(const char *, const char *, struct addrinfo,
126             const char *, const char *, struct addrinfo, int, const char *);
127 int     udptest(int);
128 int     unix_bind(char *);
129 int     unix_connect(char *);
130 int     unix_listen(char *);
131 void    FreeBSD_stats_setup(int);
132 void    FreeBSD_stats_print(int);
133 void    set_common_sockopts(int, int);
134 int     map_tos(char *, int *);
135 void    report_connect(const struct sockaddr *, socklen_t);
136 void    usage(int);
137 ssize_t drainbuf(int, unsigned char *, size_t *);
138 ssize_t fillbuf(int, unsigned char *, size_t *);
139
140 #ifdef IPSEC
141 void    add_ipsec_policy(int, int, char *);
142
143 char    *ipsec_policy[2];
144 #endif
145
146 int
147 main(int argc, char *argv[])
148 {
149         int ch, s, ret, socksv, ipsec_count;
150         int numfibs;
151         size_t intsize = sizeof(int);
152         char *host, *uport;
153         struct addrinfo hints;
154         struct servent *sv;
155         socklen_t len;
156         struct sockaddr_storage cliaddr;
157         char *proxy;
158         const char *errstr, *proxyhost = "", *proxyport = NULL;
159         struct addrinfo proxyhints;
160         char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
161         struct option longopts[] = {
162                 { "no-tcpopt",  no_argument,    &FreeBSD_Oflag, 1 },
163                 { NULL,         0,              NULL,           0 }
164         };
165
166         ret = 1;
167         ipsec_count = 0;
168         s = 0;
169         socksv = 5;
170         host = NULL;
171         uport = NULL;
172         sv = NULL;
173
174         signal(SIGPIPE, SIG_IGN);
175
176         while ((ch = getopt_long(argc, argv,
177             "46DdEe:FhI:i:klMNnoO:P:p:rSs:tT:UuV:vw:X:x:z",
178             longopts, NULL)) != -1) {
179                 switch (ch) {
180                 case '4':
181                         family = AF_INET;
182                         break;
183                 case '6':
184                         family = AF_INET6;
185                         break;
186                 case 'U':
187                         family = AF_UNIX;
188                         break;
189                 case 'X':
190                         if (strcasecmp(optarg, "connect") == 0)
191                                 socksv = -1; /* HTTP proxy CONNECT */
192                         else if (strcmp(optarg, "4") == 0)
193                                 socksv = 4; /* SOCKS v.4 */
194                         else if (strcmp(optarg, "5") == 0)
195                                 socksv = 5; /* SOCKS v.5 */
196                         else
197                                 errx(1, "unsupported proxy protocol");
198                         break;
199                 case 'd':
200                         dflag = 1;
201                         break;
202                 case 'e':
203 #ifdef IPSEC
204                         ipsec_policy[ipsec_count++ % 2] = optarg;
205 #else
206                         errx(1, "IPsec support unavailable.");
207 #endif
208                         break;
209                 case 'E':
210 #ifdef IPSEC
211                         ipsec_policy[0] = "in  ipsec esp/transport//require";
212                         ipsec_policy[1] = "out ipsec esp/transport//require";
213 #else
214                         errx(1, "IPsec support unavailable.");
215 #endif
216                         break;
217                 case 'F':
218                         Fflag = 1;
219                         break;
220                 case 'h':
221                         help();
222                         break;
223                 case 'i':
224                         iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
225                         if (errstr)
226                                 errx(1, "interval %s: %s", errstr, optarg);
227                         break;
228                 case 'k':
229                         kflag = 1;
230                         break;
231                 case 'l':
232                         lflag = 1;
233                         break;
234                 case 'M':
235 #ifndef WITH_STATS
236                         errx(1, "-M requires stats(3) support");
237 #else
238                         FreeBSD_Mflag = 1;
239 #endif
240                         break;
241                 case 'N':
242                         Nflag = 1;
243                         break;
244                 case 'n':
245                         nflag = 1;
246                         break;
247                 case 'o':
248                         fprintf(stderr, "option -o is deprecated.\n");
249                         break;
250                 case 'P':
251                         Pflag = optarg;
252                         break;
253                 case 'p':
254                         pflag = optarg;
255                         break;
256                 case 'r':
257                         rflag = 1;
258                         break;
259                 case 's':
260                         sflag = optarg;
261                         break;
262                 case 't':
263                         tflag = 1;
264                         break;
265                 case 'u':
266                         uflag = 1;
267                         break;
268                 case 'V':
269                         if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
270                                 errx(1, "Multiple FIBS not supported");
271                         rtableid = (int)strtonum(optarg, 0,
272                             numfibs - 1, &errstr);
273                         if (errstr)
274                                 errx(1, "rtable %s: %s", errstr, optarg);
275                         break;
276                 case 'v':
277                         vflag = 1;
278                         break;
279                 case 'w':
280                         timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
281                         if (errstr)
282                                 errx(1, "timeout %s: %s", errstr, optarg);
283                         timeout *= 1000;
284                         break;
285                 case 'x':
286                         xflag = 1;
287                         if ((proxy = strdup(optarg)) == NULL)
288                                 err(1, NULL);
289                         break;
290                 case 'z':
291                         zflag = 1;
292                         break;
293                 case 'D':
294                         Dflag = 1;
295                         break;
296                 case 'I':
297                         Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
298                         if (errstr != NULL)
299                                 errx(1, "TCP receive window %s: %s",
300                                     errstr, optarg);
301                         break;
302                 case 'O':
303                         Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
304                         if (errstr != NULL) {
305                             if (strcmp(errstr, "invalid") != 0)
306                                 errx(1, "TCP send window %s: %s",
307                                     errstr, optarg);
308                         }
309                         break;
310                 case 'S':
311                         Sflag = 1;
312                         break;
313                 case 'T':
314                         errstr = NULL;
315                         errno = 0;
316                         if (map_tos(optarg, &Tflag))
317                                 break;
318                         if (strlen(optarg) > 1 && optarg[0] == '0' &&
319                             optarg[1] == 'x')
320                                 Tflag = (int)strtol(optarg, NULL, 16);
321                         else
322                                 Tflag = (int)strtonum(optarg, 0, 255,
323                                     &errstr);
324                         if (Tflag < 0 || Tflag > 255 || errstr || errno)
325                                 errx(1, "illegal tos value %s", optarg);
326                         break;
327                 default:
328                         usage(1);
329                 }
330         }
331         argc -= optind;
332         argv += optind;
333
334         /* Cruft to make sure options are clean, and used properly. */
335         if (argv[0] && !argv[1] && family == AF_UNIX) {
336                 host = argv[0];
337                 uport = NULL;
338         } else if (argv[0] && !argv[1]) {
339                 if  (!lflag)
340                         usage(1);
341                 uport = argv[0];
342                 host = NULL;
343         } else if (argv[0] && argv[1]) {
344                 host = argv[0];
345                 uport = argv[1];
346         } else
347                 usage(1);
348
349         if (lflag && sflag)
350                 errx(1, "cannot use -s and -l");
351         if (lflag && pflag)
352                 errx(1, "cannot use -p and -l");
353         if (lflag && zflag)
354                 errx(1, "cannot use -z and -l");
355         if (!lflag && kflag)
356                 errx(1, "must use -l with -k");
357
358         /* Get name of temporary socket for unix datagram client */
359         if ((family == AF_UNIX) && uflag && !lflag) {
360                 if (sflag) {
361                         unix_dg_tmp_socket = sflag;
362                 } else {
363                         strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
364                                 UNIX_DG_TMP_SOCKET_SIZE);
365                         if (mktemp(unix_dg_tmp_socket_buf) == NULL)
366                                 err(1, "mktemp");
367                         unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
368                 }
369         }
370
371         /* Initialize addrinfo structure. */
372         if (family != AF_UNIX) {
373                 memset(&hints, 0, sizeof(struct addrinfo));
374                 hints.ai_family = family;
375                 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
376                 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
377                 if (nflag)
378                         hints.ai_flags |= AI_NUMERICHOST;
379         }
380
381         if (xflag) {
382                 if (uflag)
383                         errx(1, "no proxy support for UDP mode");
384
385                 if (lflag)
386                         errx(1, "no proxy support for listen");
387
388                 if (family == AF_UNIX)
389                         errx(1, "no proxy support for unix sockets");
390
391                 /* XXX IPv6 transport to proxy would probably work */
392                 if (family == AF_INET6)
393                         errx(1, "no proxy support for IPv6");
394
395                 if (sflag)
396                         errx(1, "no proxy support for local source address");
397
398                 proxyhost = strsep(&proxy, ":");
399                 proxyport = proxy;
400
401                 memset(&proxyhints, 0, sizeof(struct addrinfo));
402                 proxyhints.ai_family = family;
403                 proxyhints.ai_socktype = SOCK_STREAM;
404                 proxyhints.ai_protocol = IPPROTO_TCP;
405                 if (nflag)
406                         proxyhints.ai_flags |= AI_NUMERICHOST;
407         }
408
409         if (lflag) {
410                 int connfd;
411                 ret = 0;
412
413                 if (family == AF_UNIX) {
414                         if (uflag)
415                                 s = unix_bind(host);
416                         else
417                                 s = unix_listen(host);
418                 }
419
420                 /* Allow only one connection at a time, but stay alive. */
421                 for (;;) {
422                         if (family != AF_UNIX)
423                                 s = local_listen(host, uport, hints);
424                         if (s < 0)
425                                 err(1, NULL);
426                         /*
427                          * For UDP and -k, don't connect the socket, let it
428                          * receive datagrams from multiple socket pairs.
429                          */
430                         if (uflag && kflag)
431                                 readwrite(s);
432                         /*
433                          * For UDP and not -k, we will use recvfrom() initially
434                          * to wait for a caller, then use the regular functions
435                          * to talk to the caller.
436                          */
437                         else if (uflag && !kflag) {
438                                 int rv, plen;
439                                 char buf[16384];
440                                 struct sockaddr_storage z;
441
442                                 len = sizeof(z);
443                                 plen = 2048;
444                                 rv = recvfrom(s, buf, plen, MSG_PEEK,
445                                     (struct sockaddr *)&z, &len);
446                                 if (rv < 0)
447                                         err(1, "recvfrom");
448
449                                 rv = connect(s, (struct sockaddr *)&z, len);
450                                 if (rv < 0)
451                                         err(1, "connect");
452
453                                 if (vflag)
454                                         report_connect((struct sockaddr *)&z, len);
455
456                                 readwrite(s);
457                         } else {
458                                 len = sizeof(cliaddr);
459                                 connfd = accept(s, (struct sockaddr *)&cliaddr,
460                                     &len);
461                                 if (connfd == -1) {
462                                         /* For now, all errnos are fatal */
463                                         err(1, "accept");
464                                 }
465                                 if (vflag)
466                                         report_connect((struct sockaddr *)&cliaddr, len);
467
468                                 if (FreeBSD_Mflag)
469                                         FreeBSD_stats_setup(connfd);
470                                 readwrite(connfd);
471                                 close(connfd);
472                         }
473
474                         if (family != AF_UNIX)
475                                 close(s);
476                         else if (uflag) {
477                                 if (connect(s, NULL, 0) < 0)
478                                         err(1, "connect");
479                         }
480
481                         if (!kflag)
482                                 break;
483                 }
484         } else if (family == AF_UNIX) {
485                 ret = 0;
486
487                 if ((s = unix_connect(host)) > 0 && !zflag) {
488                         readwrite(s);
489                         close(s);
490                 } else
491                         ret = 1;
492
493                 if (uflag)
494                         unlink(unix_dg_tmp_socket);
495                 exit(ret);
496
497         } else {
498                 int i = 0;
499
500                 /* Construct the portlist[] array. */
501                 build_ports(uport);
502
503                 /* Cycle through portlist, connecting to each port. */
504                 for (i = 0; portlist[i] != NULL; i++) {
505                         if (s)
506                                 close(s);
507
508                         if (xflag)
509                                 s = socks_connect(host, portlist[i], hints,
510                                     proxyhost, proxyport, proxyhints, socksv,
511                                     Pflag);
512                         else
513                                 s = remote_connect(host, portlist[i], hints);
514
515                         if (s < 0)
516                                 continue;
517
518                         ret = 0;
519                         if (vflag || zflag) {
520                                 /* For UDP, make sure we are connected. */
521                                 if (uflag) {
522                                         if (udptest(s) == -1) {
523                                                 ret = 1;
524                                                 continue;
525                                         }
526                                 }
527
528                                 /* Don't look up port if -n. */
529                                 if (nflag)
530                                         sv = NULL;
531                                 else {
532                                         sv = getservbyport(
533                                             ntohs(atoi(portlist[i])),
534                                             uflag ? "udp" : "tcp");
535                                 }
536
537                                 fprintf(stderr,
538                                     "Connection to %s %s port [%s/%s] "
539                                     "succeeded!\n", host, portlist[i],
540                                     uflag ? "udp" : "tcp",
541                                     sv ? sv->s_name : "*");
542                         }
543                         if (Fflag)
544                                 fdpass(s);
545                         else if (!zflag)
546                                 readwrite(s);
547                 }
548         }
549
550         if (s)
551                 close(s);
552
553         exit(ret);
554 }
555
556 /*
557  * unix_bind()
558  * Returns a unix socket bound to the given path
559  */
560 int
561 unix_bind(char *path)
562 {
563         struct sockaddr_un sun;
564         int s;
565
566         /* Create unix domain socket. */
567         if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
568              0)) < 0)
569                 return (-1);
570
571         memset(&sun, 0, sizeof(struct sockaddr_un));
572         sun.sun_family = AF_UNIX;
573
574         if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
575             sizeof(sun.sun_path)) {
576                 close(s);
577                 errno = ENAMETOOLONG;
578                 return (-1);
579         }
580
581         if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
582                 close(s);
583                 return (-1);
584         }
585         return (s);
586 }
587
588 /*
589  * unix_connect()
590  * Returns a socket connected to a local unix socket. Returns -1 on failure.
591  */
592 int
593 unix_connect(char *path)
594 {
595         struct sockaddr_un sun;
596         int s;
597
598         if (uflag) {
599                 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
600                         return (-1);
601         } else {
602                 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
603                         return (-1);
604         }
605         (void)fcntl(s, F_SETFD, FD_CLOEXEC);
606
607         memset(&sun, 0, sizeof(struct sockaddr_un));
608         sun.sun_family = AF_UNIX;
609
610         if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
611             sizeof(sun.sun_path)) {
612                 close(s);
613                 errno = ENAMETOOLONG;
614                 return (-1);
615         }
616         if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
617                 close(s);
618                 return (-1);
619         }
620         return (s);
621
622 }
623
624 /*
625  * unix_listen()
626  * Create a unix domain socket, and listen on it.
627  */
628 int
629 unix_listen(char *path)
630 {
631         int s;
632         if ((s = unix_bind(path)) < 0)
633                 return (-1);
634
635         if (listen(s, 5) < 0) {
636                 close(s);
637                 return (-1);
638         }
639         return (s);
640 }
641
642 /*
643  * remote_connect()
644  * Returns a socket connected to a remote host. Properly binds to a local
645  * port or source address if needed. Returns -1 on failure.
646  */
647 int
648 remote_connect(const char *host, const char *port, struct addrinfo hints)
649 {
650         struct addrinfo *res, *res0;
651         int s, error, on = 1;
652
653         if ((error = getaddrinfo(host, port, &hints, &res)))
654                 errx(1, "getaddrinfo: %s", gai_strerror(error));
655
656         res0 = res;
657         do {
658                 if ((s = socket(res0->ai_family, res0->ai_socktype,
659                     res0->ai_protocol)) < 0)
660                         continue;
661
662                 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
663                     &rtableid, sizeof(rtableid)) == -1))
664                         err(1, "setsockopt SO_SETFIB");
665
666                 /* Bind to a local port or source address if specified. */
667                 if (sflag || pflag) {
668                         struct addrinfo ahints, *ares;
669
670                         /* try IP_BINDANY, but don't insist */
671                         setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
672                         memset(&ahints, 0, sizeof(struct addrinfo));
673                         ahints.ai_family = res0->ai_family;
674                         ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
675                         ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
676                         ahints.ai_flags = AI_PASSIVE;
677                         if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
678                                 errx(1, "getaddrinfo: %s", gai_strerror(error));
679
680                         if (bind(s, (struct sockaddr *)ares->ai_addr,
681                             ares->ai_addrlen) < 0)
682                                 err(1, "bind failed");
683                         freeaddrinfo(ares);
684                 }
685
686                 set_common_sockopts(s, res0->ai_family);
687
688                 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
689                         break;
690                 else if (vflag)
691                         warn("connect to %s port %s (%s) failed", host, port,
692                             uflag ? "udp" : "tcp");
693
694                 close(s);
695                 s = -1;
696         } while ((res0 = res0->ai_next) != NULL);
697
698         freeaddrinfo(res);
699
700         return (s);
701 }
702
703 int
704 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
705 {
706         struct pollfd pfd;
707         socklen_t optlen;
708         int flags, optval;
709         int ret;
710
711         if (timeout != -1) {
712                 flags = fcntl(s, F_GETFL, 0);
713                 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
714                         err(1, "set non-blocking mode");
715         }
716
717         if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
718                 pfd.fd = s;
719                 pfd.events = POLLOUT;
720                 if ((ret = poll(&pfd, 1, timeout)) == 1) {
721                         optlen = sizeof(optval);
722                         if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
723                             &optval, &optlen)) == 0) {
724                                 errno = optval;
725                                 ret = optval == 0 ? 0 : -1;
726                         }
727                 } else if (ret == 0) {
728                         errno = ETIMEDOUT;
729                         ret = -1;
730                 } else
731                         err(1, "poll failed");
732         }
733
734         if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
735                 err(1, "restoring flags");
736
737         return (ret);
738 }
739
740 /*
741  * local_listen()
742  * Returns a socket listening on a local port, binds to specified source
743  * address. Returns -1 on failure.
744  */
745 int
746 local_listen(char *host, char *port, struct addrinfo hints)
747 {
748         struct addrinfo *res, *res0;
749         int s, ret, x = 1;
750         int error;
751
752         /* Allow nodename to be null. */
753         hints.ai_flags |= AI_PASSIVE;
754
755         /*
756          * In the case of binding to a wildcard address
757          * default to binding to an ipv4 address.
758          */
759         if (host == NULL && hints.ai_family == AF_UNSPEC)
760                 hints.ai_family = AF_INET;
761
762         if ((error = getaddrinfo(host, port, &hints, &res)))
763                 errx(1, "getaddrinfo: %s", gai_strerror(error));
764
765         res0 = res;
766         do {
767                 if ((s = socket(res0->ai_family, res0->ai_socktype,
768                     res0->ai_protocol)) < 0)
769                         continue;
770
771                 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
772                     &rtableid, sizeof(rtableid)) == -1))
773                         err(1, "setsockopt SO_SETFIB");
774
775                 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
776                 if (ret == -1)
777                         err(1, NULL);
778
779                 if (FreeBSD_Oflag) {
780                         if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
781                             &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
782                                 err(1, "disable TCP options");
783                 }
784
785                 set_common_sockopts(s, res0->ai_family);
786
787                 if (bind(s, (struct sockaddr *)res0->ai_addr,
788                     res0->ai_addrlen) == 0)
789                         break;
790
791                 close(s);
792                 s = -1;
793         } while ((res0 = res0->ai_next) != NULL);
794
795         if (!uflag && s != -1) {
796                 if (listen(s, 1) < 0)
797                         err(1, "listen");
798         }
799
800         freeaddrinfo(res);
801
802         return (s);
803 }
804
805 /*
806  * readwrite()
807  * Loop that polls on the network file descriptor and stdin.
808  */
809 void
810 readwrite(int net_fd)
811 {
812         struct pollfd pfd[4];
813         int stdin_fd = STDIN_FILENO;
814         int stdout_fd = STDOUT_FILENO;
815         unsigned char netinbuf[BUFSIZE];
816         size_t netinbufpos = 0;
817         unsigned char stdinbuf[BUFSIZE];
818         size_t stdinbufpos = 0;
819         int n, num_fds;
820         int stats_printed = 0;
821         ssize_t ret;
822
823         /* don't read from stdin if requested */
824         if (dflag)
825                 stdin_fd = -1;
826
827         /* stdin */
828         pfd[POLL_STDIN].fd = stdin_fd;
829         pfd[POLL_STDIN].events = POLLIN;
830
831         /* network out */
832         pfd[POLL_NETOUT].fd = net_fd;
833         pfd[POLL_NETOUT].events = 0;
834
835         /* network in */
836         pfd[POLL_NETIN].fd = net_fd;
837         pfd[POLL_NETIN].events = POLLIN;
838
839         /* stdout */
840         pfd[POLL_STDOUT].fd = stdout_fd;
841         pfd[POLL_STDOUT].events = 0;
842
843         while (1) {
844                 /* both inputs are gone, buffers are empty, we are done */
845                 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
846                     && stdinbufpos == 0 && netinbufpos == 0) {
847                         if (FreeBSD_Mflag && !stats_printed)
848                                 FreeBSD_stats_print(net_fd);
849                         close(net_fd);
850                         return;
851                 }
852                 /* both outputs are gone, we can't continue */
853                 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
854                         if (FreeBSD_Mflag && !stats_printed)
855                                 FreeBSD_stats_print(net_fd);
856                         close(net_fd);
857                         return;
858                 }
859                 /* listen and net in gone, queues empty, done */
860                 if (lflag && pfd[POLL_NETIN].fd == -1
861                     && stdinbufpos == 0 && netinbufpos == 0) {
862                         if (FreeBSD_Mflag && !stats_printed)
863                                 FreeBSD_stats_print(net_fd);
864                         close(net_fd);
865                         return;
866                 }
867
868                 /* help says -i is for "wait between lines sent". We read and
869                  * write arbitrary amounts of data, and we don't want to start
870                  * scanning for newlines, so this is as good as it gets */
871                 if (iflag)
872                         sleep(iflag);
873
874                 /* poll */
875                 num_fds = poll(pfd, 4, timeout);
876
877                 /* treat poll errors */
878                 if (num_fds == -1) {
879                         close(net_fd);
880                         err(1, "polling error");
881                 }
882
883                 /* timeout happened */
884                 if (num_fds == 0) {
885                         if (FreeBSD_Mflag)
886                                 FreeBSD_stats_print(net_fd);
887                         return;
888                 }
889
890                 /* treat socket error conditions */
891                 for (n = 0; n < 4; n++) {
892                         if (pfd[n].revents & (POLLERR|POLLNVAL)) {
893                                 pfd[n].fd = -1;
894                         }
895                 }
896                 /* reading is possible after HUP */
897                 if (pfd[POLL_STDIN].events & POLLIN &&
898                     pfd[POLL_STDIN].revents & POLLHUP &&
899                     ! (pfd[POLL_STDIN].revents & POLLIN))
900                                 pfd[POLL_STDIN].fd = -1;
901
902                 if (pfd[POLL_NETIN].events & POLLIN &&
903                     pfd[POLL_NETIN].revents & POLLHUP &&
904                     ! (pfd[POLL_NETIN].revents & POLLIN))
905                                 pfd[POLL_NETIN].fd = -1;
906
907                 if (pfd[POLL_NETOUT].revents & POLLHUP) {
908                         if (Nflag)
909                                 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
910                         pfd[POLL_NETOUT].fd = -1;
911                 }
912                 /* if HUP, stop watching stdout */
913                 if (pfd[POLL_STDOUT].revents & POLLHUP)
914                         pfd[POLL_STDOUT].fd = -1;
915                 /* if no net out, stop watching stdin */
916                 if (pfd[POLL_NETOUT].fd == -1)
917                         pfd[POLL_STDIN].fd = -1;
918                 /* if no stdout, stop watching net in */
919                 if (pfd[POLL_STDOUT].fd == -1) {
920                         if (pfd[POLL_NETIN].fd != -1)
921                                 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
922                         pfd[POLL_NETIN].fd = -1;
923                 }
924
925                 /* try to read from stdin */
926                 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
927                         ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
928                             &stdinbufpos);
929                         /* error or eof on stdin - remove from pfd */
930                         if (ret == 0 || ret == -1)
931                                 pfd[POLL_STDIN].fd = -1;
932                         /* read something - poll net out */
933                         if (stdinbufpos > 0)
934                                 pfd[POLL_NETOUT].events = POLLOUT;
935                         /* filled buffer - remove self from polling */
936                         if (stdinbufpos == BUFSIZE)
937                                 pfd[POLL_STDIN].events = 0;
938                 }
939                 /* try to write to network */
940                 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
941                         ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
942                             &stdinbufpos);
943                         if (ret == -1)
944                                 pfd[POLL_NETOUT].fd = -1;
945                         /* buffer empty - remove self from polling */
946                         if (stdinbufpos == 0)
947                                 pfd[POLL_NETOUT].events = 0;
948                         /* buffer no longer full - poll stdin again */
949                         if (stdinbufpos < BUFSIZE)
950                                 pfd[POLL_STDIN].events = POLLIN;
951                 }
952                 /* try to read from network */
953                 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
954                         ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
955                             &netinbufpos);
956                         if (ret == -1)
957                                 pfd[POLL_NETIN].fd = -1;
958                         /* eof on net in - remove from pfd */
959                         if (ret == 0) {
960                                 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
961                                 pfd[POLL_NETIN].fd = -1;
962                         }
963                         /* read something - poll stdout */
964                         if (netinbufpos > 0)
965                                 pfd[POLL_STDOUT].events = POLLOUT;
966                         /* filled buffer - remove self from polling */
967                         if (netinbufpos == BUFSIZE)
968                                 pfd[POLL_NETIN].events = 0;
969                         /* handle telnet */
970                         if (tflag)
971                                 atelnet(pfd[POLL_NETIN].fd, netinbuf,
972                                     netinbufpos);
973                 }
974                 /* try to write to stdout */
975                 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
976                         ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
977                             &netinbufpos);
978                         if (ret == -1)
979                                 pfd[POLL_STDOUT].fd = -1;
980                         /* buffer empty - remove self from polling */
981                         if (netinbufpos == 0)
982                                 pfd[POLL_STDOUT].events = 0;
983                         /* buffer no longer full - poll net in again */
984                         if (netinbufpos < BUFSIZE)
985                                 pfd[POLL_NETIN].events = POLLIN;
986                 }
987
988                 /* stdin gone and queue empty? */
989                 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
990                         if (pfd[POLL_NETOUT].fd != -1 && Nflag) {
991                                 if (FreeBSD_Mflag) {
992                                         FreeBSD_stats_print(net_fd);
993                                         stats_printed = 1;
994                                 }
995                                 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
996                         }
997                         pfd[POLL_NETOUT].fd = -1;
998                 }
999                 /* net in gone and queue empty? */
1000                 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1001                         pfd[POLL_STDOUT].fd = -1;
1002                 }
1003         }
1004 }
1005
1006 ssize_t
1007 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
1008 {
1009         ssize_t n;
1010         ssize_t adjust;
1011
1012         n = write(fd, buf, *bufpos);
1013         /* don't treat EAGAIN, EINTR as error */
1014         if (n == -1 && (errno == EAGAIN || errno == EINTR))
1015                 n = -2;
1016         if (n <= 0)
1017                 return n;
1018         /* adjust buffer */
1019         adjust = *bufpos - n;
1020         if (adjust > 0)
1021                 memmove(buf, buf + n, adjust);
1022         *bufpos -= n;
1023         return n;
1024 }
1025
1026
1027 ssize_t
1028 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1029 {
1030         size_t num = BUFSIZE - *bufpos;
1031         ssize_t n;
1032
1033         n = read(fd, buf + *bufpos, num);
1034         /* don't treat EAGAIN, EINTR as error */
1035         if (n == -1 && (errno == EAGAIN || errno == EINTR))
1036                 n = -2;
1037         if (n <= 0)
1038                 return n;
1039         *bufpos += n;
1040         return n;
1041 }
1042
1043 /*
1044  * fdpass()
1045  * Pass the connected file descriptor to stdout and exit.
1046  */
1047 void
1048 fdpass(int nfd)
1049 {
1050         struct msghdr mh;
1051         union {
1052                 struct cmsghdr hdr;
1053                 char buf[CMSG_SPACE(sizeof(int))];
1054         } cmsgbuf;
1055         struct cmsghdr *cmsg;
1056         struct iovec iov;
1057         char c = '\0';
1058         ssize_t r;
1059         struct pollfd pfd;
1060
1061         /* Avoid obvious stupidity */
1062         if (isatty(STDOUT_FILENO))
1063                 errx(1, "Cannot pass file descriptor to tty");
1064
1065         bzero(&mh, sizeof(mh));
1066         bzero(&cmsgbuf, sizeof(cmsgbuf));
1067         bzero(&iov, sizeof(iov));
1068
1069         mh.msg_control = (caddr_t)&cmsgbuf.buf;
1070         mh.msg_controllen = sizeof(cmsgbuf.buf);
1071         cmsg = CMSG_FIRSTHDR(&mh);
1072         cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1073         cmsg->cmsg_level = SOL_SOCKET;
1074         cmsg->cmsg_type = SCM_RIGHTS;
1075         *(int *)CMSG_DATA(cmsg) = nfd;
1076
1077         iov.iov_base = &c;
1078         iov.iov_len = 1;
1079         mh.msg_iov = &iov;
1080         mh.msg_iovlen = 1;
1081
1082         bzero(&pfd, sizeof(pfd));
1083         pfd.fd = STDOUT_FILENO;
1084         pfd.events = POLLOUT;
1085         for (;;) {
1086                 r = sendmsg(STDOUT_FILENO, &mh, 0);
1087                 if (r == -1) {
1088                         if (errno == EAGAIN || errno == EINTR) {
1089                                 if (poll(&pfd, 1, -1) == -1)
1090                                         err(1, "poll");
1091                                 continue;
1092                         }
1093                         err(1, "sendmsg");
1094                 } else if (r != 1)
1095                         errx(1, "sendmsg: unexpected return value %zd", r);
1096                 else
1097                         break;
1098         }
1099         exit(0);
1100 }
1101
1102 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1103 void
1104 atelnet(int nfd, unsigned char *buf, unsigned int size)
1105 {
1106         unsigned char *p, *end;
1107         unsigned char obuf[4];
1108
1109         if (size < 3)
1110                 return;
1111         end = buf + size - 2;
1112
1113         for (p = buf; p < end; p++) {
1114                 if (*p != IAC)
1115                         continue;
1116
1117                 obuf[0] = IAC;
1118                 p++;
1119                 if ((*p == WILL) || (*p == WONT))
1120                         obuf[1] = DONT;
1121                 else if ((*p == DO) || (*p == DONT))
1122                         obuf[1] = WONT;
1123                 else
1124                         continue;
1125
1126                 p++;
1127                 obuf[2] = *p;
1128                 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1129                         warn("Write Error!");
1130         }
1131 }
1132
1133 /*
1134  * build_ports()
1135  * Build an array of ports in portlist[], listing each port
1136  * that we should try to connect to.
1137  */
1138 void
1139 build_ports(char *p)
1140 {
1141         const char *errstr;
1142         char *n;
1143         int hi, lo, cp;
1144         int x = 0;
1145
1146         if ((n = strchr(p, '-')) != NULL) {
1147                 *n = '\0';
1148                 n++;
1149
1150                 /* Make sure the ports are in order: lowest->highest. */
1151                 hi = strtonum(n, 1, PORT_MAX, &errstr);
1152                 if (errstr)
1153                         errx(1, "port number %s: %s", errstr, n);
1154                 lo = strtonum(p, 1, PORT_MAX, &errstr);
1155                 if (errstr)
1156                         errx(1, "port number %s: %s", errstr, p);
1157
1158                 if (lo > hi) {
1159                         cp = hi;
1160                         hi = lo;
1161                         lo = cp;
1162                 }
1163
1164                 /* Load ports sequentially. */
1165                 for (cp = lo; cp <= hi; cp++) {
1166                         portlist[x] = calloc(1, PORT_MAX_LEN);
1167                         if (portlist[x] == NULL)
1168                                 err(1, NULL);
1169                         snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1170                         x++;
1171                 }
1172
1173                 /* Randomly swap ports. */
1174                 if (rflag) {
1175                         int y;
1176                         char *c;
1177
1178                         for (x = 0; x <= (hi - lo); x++) {
1179                                 y = (arc4random() & 0xFFFF) % (hi - lo);
1180                                 c = portlist[x];
1181                                 portlist[x] = portlist[y];
1182                                 portlist[y] = c;
1183                         }
1184                 }
1185         } else {
1186                 hi = strtonum(p, 1, PORT_MAX, &errstr);
1187                 if (errstr)
1188                         errx(1, "port number %s: %s", errstr, p);
1189                 portlist[0] = strdup(p);
1190                 if (portlist[0] == NULL)
1191                         err(1, NULL);
1192         }
1193 }
1194
1195 /*
1196  * udptest()
1197  * Do a few writes to see if the UDP port is there.
1198  * Fails once PF state table is full.
1199  */
1200 int
1201 udptest(int s)
1202 {
1203         int i, ret;
1204
1205         for (i = 0; i <= 3; i++) {
1206                 if (write(s, "X", 1) == 1)
1207                         ret = 1;
1208                 else
1209                         ret = -1;
1210         }
1211         return (ret);
1212 }
1213
1214 void
1215 FreeBSD_stats_setup(int s)
1216 {
1217
1218         if (setsockopt(s, IPPROTO_TCP, TCP_STATS,
1219             &FreeBSD_Mflag, sizeof(FreeBSD_Mflag)) == -1) {
1220                 if (errno == EOPNOTSUPP) {
1221                         warnx("getsockopt(TCP_STATS) failed; "
1222                             "kernel built without \"options STATS\"?");
1223                 }
1224                 err(1, "enable TCP_STATS gathering");
1225         }
1226 }
1227
1228 void
1229 FreeBSD_stats_print(int s)
1230 {
1231 #ifdef WITH_STATS
1232         struct statsblob *statsb;
1233         struct sbuf *sb;
1234         socklen_t sockoptlen;
1235         int error;
1236
1237         /*
1238          * This usleep is a workaround for TCP_STATS reporting
1239          * incorrect values for TXPB.
1240          */
1241         usleep(100000);
1242
1243         sockoptlen = 2048;
1244         statsb = malloc(sockoptlen);
1245         if (statsb == NULL)
1246                 err(1, "malloc");
1247         error = getsockopt(s, IPPROTO_TCP, TCP_STATS, statsb, &sockoptlen);
1248         if (error != 0) {
1249                 if (errno == EOVERFLOW && statsb->cursz > sockoptlen) {
1250                         /* Retry with a larger size. */
1251                         sockoptlen = statsb->cursz;
1252                         statsb = realloc(statsb, sockoptlen);
1253                         if (statsb == NULL)
1254                                 err(1, "realloc");
1255                         error = getsockopt(s, IPPROTO_TCP, TCP_STATS,
1256                             statsb, &sockoptlen);
1257                 }
1258                 if (error != 0)
1259                         err(1, "getsockopt");
1260         }
1261
1262         sb = sbuf_new_auto();
1263         error = stats_blob_tostr(statsb, sb, SB_STRFMT_JSON, SB_TOSTR_META);
1264         if (error != 0)
1265                 errc(1, error, "stats_blob_tostr");
1266
1267         error = sbuf_finish(sb);
1268         if (error != 0)
1269                 err(1, "sbuf_finish");
1270
1271         fprintf(stderr, "%s\n", sbuf_data(sb));
1272 #endif
1273 }
1274
1275 void
1276 set_common_sockopts(int s, int af)
1277 {
1278         int x = 1;
1279
1280         if (Sflag) {
1281                 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1282                         &x, sizeof(x)) == -1)
1283                         err(1, NULL);
1284         }
1285         if (Dflag) {
1286                 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1287                         &x, sizeof(x)) == -1)
1288                         err(1, NULL);
1289         }
1290         if (Tflag != -1) {
1291                 int proto, option;
1292
1293                 if (af == AF_INET6) {
1294                         proto = IPPROTO_IPV6;
1295                         option = IPV6_TCLASS;
1296                 } else {
1297                         proto = IPPROTO_IP;
1298                         option = IP_TOS;
1299                 }
1300
1301                 if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1302                         err(1, "set IP ToS");
1303         }
1304         if (Iflag) {
1305                 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1306                     &Iflag, sizeof(Iflag)) == -1)
1307                         err(1, "set TCP receive buffer size");
1308         }
1309         if (Oflag) {
1310                 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1311                     &Oflag, sizeof(Oflag)) == -1)
1312                         err(1, "set TCP send buffer size");
1313         }
1314         if (FreeBSD_Oflag) {
1315                 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
1316                     &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
1317                         err(1, "disable TCP options");
1318         }
1319         if (FreeBSD_Mflag)
1320                 FreeBSD_stats_setup(s);
1321 #ifdef IPSEC
1322         if (ipsec_policy[0] != NULL)
1323                 add_ipsec_policy(s, af, ipsec_policy[0]);
1324         if (ipsec_policy[1] != NULL)
1325                 add_ipsec_policy(s, af, ipsec_policy[1]);
1326 #endif
1327 }
1328
1329 int
1330 map_tos(char *s, int *val)
1331 {
1332         /* DiffServ Codepoints and other TOS mappings */
1333         const struct toskeywords {
1334                 const char      *keyword;
1335                 int              val;
1336         } *t, toskeywords[] = {
1337                 { "af11",               IPTOS_DSCP_AF11 },
1338                 { "af12",               IPTOS_DSCP_AF12 },
1339                 { "af13",               IPTOS_DSCP_AF13 },
1340                 { "af21",               IPTOS_DSCP_AF21 },
1341                 { "af22",               IPTOS_DSCP_AF22 },
1342                 { "af23",               IPTOS_DSCP_AF23 },
1343                 { "af31",               IPTOS_DSCP_AF31 },
1344                 { "af32",               IPTOS_DSCP_AF32 },
1345                 { "af33",               IPTOS_DSCP_AF33 },
1346                 { "af41",               IPTOS_DSCP_AF41 },
1347                 { "af42",               IPTOS_DSCP_AF42 },
1348                 { "af43",               IPTOS_DSCP_AF43 },
1349                 { "critical",           IPTOS_PREC_CRITIC_ECP },
1350                 { "cs0",                IPTOS_DSCP_CS0 },
1351                 { "cs1",                IPTOS_DSCP_CS1 },
1352                 { "cs2",                IPTOS_DSCP_CS2 },
1353                 { "cs3",                IPTOS_DSCP_CS3 },
1354                 { "cs4",                IPTOS_DSCP_CS4 },
1355                 { "cs5",                IPTOS_DSCP_CS5 },
1356                 { "cs6",                IPTOS_DSCP_CS6 },
1357                 { "cs7",                IPTOS_DSCP_CS7 },
1358                 { "ef",                 IPTOS_DSCP_EF },
1359                 { "inetcontrol",        IPTOS_PREC_INTERNETCONTROL },
1360                 { "lowdelay",           IPTOS_LOWDELAY },
1361                 { "netcontrol",         IPTOS_PREC_NETCONTROL },
1362                 { "reliability",        IPTOS_RELIABILITY },
1363                 { "throughput",         IPTOS_THROUGHPUT },
1364                 { NULL,                 -1 },
1365         };
1366
1367         for (t = toskeywords; t->keyword != NULL; t++) {
1368                 if (strcmp(s, t->keyword) == 0) {
1369                         *val = t->val;
1370                         return (1);
1371                 }
1372         }
1373
1374         return (0);
1375 }
1376
1377 void
1378 report_connect(const struct sockaddr *sa, socklen_t salen)
1379 {
1380         char remote_host[NI_MAXHOST];
1381         char remote_port[NI_MAXSERV];
1382         int herr;
1383         int flags = NI_NUMERICSERV;
1384         
1385         if (nflag)
1386                 flags |= NI_NUMERICHOST;
1387         
1388         if ((herr = getnameinfo(sa, salen,
1389             remote_host, sizeof(remote_host),
1390             remote_port, sizeof(remote_port),
1391             flags)) != 0) {
1392                 if (herr == EAI_SYSTEM)
1393                         err(1, "getnameinfo");
1394                 else
1395                         errx(1, "getnameinfo: %s", gai_strerror(herr));
1396         }
1397         
1398         fprintf(stderr,
1399             "Connection from %s %s "
1400             "received!\n", remote_host, remote_port);
1401 }
1402
1403 void
1404 help(void)
1405 {
1406         usage(0);
1407         fprintf(stderr, "\tCommand Summary:\n\
1408         \t-4            Use IPv4\n\
1409         \t-6            Use IPv6\n\
1410         \t-D            Enable the debug socket option\n\
1411         \t-d            Detach from stdin\n");
1412 #ifdef IPSEC
1413         fprintf(stderr, "\
1414         \t-E            Use IPsec ESP\n\
1415         \t-e policy     Use specified IPsec policy\n");
1416 #endif
1417         fprintf(stderr, "\
1418         \t-F            Pass socket fd\n\
1419         \t-h            This help text\n\
1420         \t-I length     TCP receive buffer length\n\
1421         \t-i secs\t     Delay interval for lines sent, ports scanned\n\
1422         \t-k            Keep inbound sockets open for multiple connects\n\
1423         \t-l            Listen mode, for inbound connects\n\
1424         \t-N            Shutdown the network socket after EOF on stdin\n\
1425         \t-n            Suppress name/port resolutions\n\
1426         \t--no-tcpopt   Disable TCP options\n\
1427         \t-O length     TCP send buffer length\n\
1428         \t-P proxyuser\tUsername for proxy authentication\n\
1429         \t-p port\t     Specify local port for remote connects\n\
1430         \t-r            Randomize remote ports\n\
1431         \t-S            Enable the TCP MD5 signature option\n\
1432         \t-s addr\t     Local source address\n\
1433         \t-T toskeyword\tSet IP Type of Service\n\
1434         \t-t            Answer TELNET negotiation\n\
1435         \t-U            Use UNIX domain socket\n\
1436         \t-u            UDP mode\n\
1437         \t-V rtable     Specify alternate routing table\n\
1438         \t-v            Verbose\n\
1439         \t-w secs\t     Timeout for connects and final net reads\n\
1440         \t-X proto      Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1441         \t-x addr[:port]\tSpecify proxy address and port\n\
1442         \t-z            Zero-I/O mode [used for scanning]\n\
1443         Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1444 #ifdef IPSEC
1445         fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
1446 #endif
1447         exit(1);
1448 }
1449
1450 #ifdef IPSEC
1451 void
1452 add_ipsec_policy(int s, int af, char *policy)
1453 {
1454         char *raw;
1455         int e;
1456
1457         raw = ipsec_set_policy(policy, strlen(policy));
1458         if (raw == NULL)
1459                 errx(1, "ipsec_set_policy `%s': %s", policy,
1460                      ipsec_strerror());
1461         if (af == AF_INET)
1462                 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1463                     ipsec_get_policylen(raw));
1464         if (af == AF_INET6)
1465                 e = setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, raw,
1466                     ipsec_get_policylen(raw));
1467         if (e < 0)
1468                 err(1, "ipsec policy cannot be configured");
1469         free(raw);
1470         if (vflag)
1471                 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1472         return;
1473 }
1474 #endif /* IPSEC */
1475
1476 void
1477 usage(int ret)
1478 {
1479         fprintf(stderr,
1480 #ifdef IPSEC
1481             "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1482 #else
1483             "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1484 #endif
1485             "\t  [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1486             "\t  [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1487             "\t  [-x proxy_address[:port]] [destination] [port]\n");
1488         if (ret)
1489                 exit(1);
1490 }