]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - contrib/netcat/netcat.c
MFC r231852,232127:
[FreeBSD/stable/8.git] / contrib / netcat / netcat.c
1 /* $OpenBSD: netcat.c,v 1.100 2011/01/09 22:16:46 jeremy 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 <sys/limits.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/sysctl.h>
40 #include <sys/time.h>
41 #include <sys/un.h>
42
43 #include <netinet/in.h>
44 #include <netinet/in_systm.h>
45 #ifdef IPSEC
46 #include <netipsec/ipsec.h>
47 #endif
48 #include <netinet/tcp.h>
49 #include <netinet/ip.h>
50 #include <arpa/telnet.h>
51
52 #include <err.h>
53 #include <errno.h>
54 #include <getopt.h>
55 #include <netdb.h>
56 #include <poll.h>
57 #include <stdarg.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 #include <fcntl.h>
63 #include <limits.h>
64 #include "atomicio.h"
65
66 #ifndef SUN_LEN
67 #define SUN_LEN(su) \
68         (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
69 #endif
70
71 #define PORT_MAX        65535
72 #define PORT_MAX_LEN    6
73 #define UNIX_DG_TMP_SOCKET_SIZE 19
74
75 /* Command Line Options */
76 int     dflag;                                  /* detached, no stdin */
77 unsigned int iflag;                             /* Interval Flag */
78 int     jflag;                                  /* use jumbo frames if we can */
79 int     kflag;                                  /* More than one connect */
80 int     lflag;                                  /* Bind to local port */
81 int     nflag;                                  /* Don't do name look up */
82 int     FreeBSD_Oflag;                          /* Do not use TCP options */
83 char   *Pflag;                                  /* Proxy username */
84 char   *pflag;                                  /* Localport flag */
85 int     rflag;                                  /* Random ports flag */
86 char   *sflag;                                  /* Source Address */
87 int     tflag;                                  /* Telnet Emulation */
88 int     uflag;                                  /* UDP - Default to TCP */
89 int     vflag;                                  /* Verbosity */
90 int     xflag;                                  /* Socks proxy */
91 int     zflag;                                  /* Port Scan Flag */
92 int     Dflag;                                  /* sodebug */
93 int     Iflag;                                  /* TCP receive buffer size */
94 int     Oflag;                                  /* TCP send buffer size */
95 int     Sflag;                                  /* TCP MD5 signature option */
96 int     Tflag = -1;                             /* IP Type of Service */
97 u_int   rtableid;
98
99 int timeout = -1;
100 int family = AF_UNSPEC;
101 char *portlist[PORT_MAX+1];
102 char *unix_dg_tmp_socket;
103
104 void    atelnet(int, unsigned char *, unsigned int);
105 void    build_ports(char *);
106 void    help(void);
107 int     local_listen(char *, char *, struct addrinfo);
108 void    readwrite(int);
109 int     remote_connect(const char *, const char *, struct addrinfo);
110 int     socks_connect(const char *, const char *, struct addrinfo,
111             const char *, const char *, struct addrinfo, int, const char *);
112 int     udptest(int);
113 int     unix_bind(char *);
114 int     unix_connect(char *);
115 int     unix_listen(char *);
116 void    set_common_sockopts(int);
117 int     parse_iptos(char *);
118 void    usage(int);
119
120 #ifdef IPSEC
121 void    add_ipsec_policy(int, char *);
122
123 char    *ipsec_policy[2];
124 #endif
125
126 int
127 main(int argc, char *argv[])
128 {
129         int ch, s, ret, socksv, ipsec_count;
130         int numfibs;
131         size_t intsize = sizeof(int);
132         char *host, *uport;
133         struct addrinfo hints;
134         struct servent *sv;
135         socklen_t len;
136         struct sockaddr_storage cliaddr;
137         char *proxy;
138         const char *errstr, *proxyhost = "", *proxyport = NULL;
139         struct addrinfo proxyhints;
140         char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
141         struct option longopts[] = {
142                 { "no-tcpopt",  no_argument,    &FreeBSD_Oflag, 1 },
143                 { NULL,         0,              NULL,           0 }
144         };
145
146         ret = 1;
147         ipsec_count = 0;
148         s = 0;
149         socksv = 5;
150         host = NULL;
151         uport = NULL;
152         sv = NULL;
153
154         while ((ch = getopt_long(argc, argv,
155             "46DdEe:hI:i:jklnoO:P:p:rSs:tT:UuV:vw:X:x:z",
156             longopts, NULL)) != -1) {
157                 switch (ch) {
158                 case '4':
159                         family = AF_INET;
160                         break;
161                 case '6':
162                         family = AF_INET6;
163                         break;
164                 case 'U':
165                         family = AF_UNIX;
166                         break;
167                 case 'X':
168                         if (strcasecmp(optarg, "connect") == 0)
169                                 socksv = -1; /* HTTP proxy CONNECT */
170                         else if (strcmp(optarg, "4") == 0)
171                                 socksv = 4; /* SOCKS v.4 */
172                         else if (strcmp(optarg, "5") == 0)
173                                 socksv = 5; /* SOCKS v.5 */
174                         else
175                                 errx(1, "unsupported proxy protocol");
176                         break;
177                 case 'd':
178                         dflag = 1;
179                         break;
180                 case 'e':
181 #ifdef IPSEC
182                         ipsec_policy[ipsec_count++ % 2] = optarg;
183 #else
184                         errx(1, "IPsec support unavailable.");
185 #endif
186                         break;
187                 case 'E':
188 #ifdef IPSEC
189                         ipsec_policy[0] = "in  ipsec esp/transport//require";
190                         ipsec_policy[1] = "out ipsec esp/transport//require";
191 #else
192                         errx(1, "IPsec support unavailable.");
193 #endif
194                         break;
195                 case 'h':
196                         help();
197                         break;
198                 case 'i':
199                         iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
200                         if (errstr)
201                                 errx(1, "interval %s: %s", errstr, optarg);
202                         break;
203 #ifdef SO_JUMBO
204                 case 'j':
205                         jflag = 1;
206                         break;
207 #endif
208                 case 'k':
209                         kflag = 1;
210                         break;
211                 case 'l':
212                         lflag = 1;
213                         break;
214                 case 'n':
215                         nflag = 1;
216                         break;
217                 case 'o':
218                         fprintf(stderr, "option -o is deprecated.\n");
219                         break;
220                 case 'P':
221                         Pflag = optarg;
222                         break;
223                 case 'p':
224                         pflag = optarg;
225                         break;
226                 case 'r':
227                         rflag = 1;
228                         break;
229                 case 's':
230                         sflag = optarg;
231                         break;
232                 case 't':
233                         tflag = 1;
234                         break;
235                 case 'u':
236                         uflag = 1;
237                         break;
238                 case 'V':
239                         if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
240                                 errx(1, "Multiple FIBS not supported");
241                         rtableid = (unsigned int)strtonum(optarg, 0,
242                             numfibs - 1, &errstr);
243                         if (errstr)
244                                 errx(1, "rtable %s: %s", errstr, optarg);
245                         break;
246                 case 'v':
247                         vflag = 1;
248                         break;
249                 case 'w':
250                         timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
251                         if (errstr)
252                                 errx(1, "timeout %s: %s", errstr, optarg);
253                         timeout *= 1000;
254                         break;
255                 case 'x':
256                         xflag = 1;
257                         if ((proxy = strdup(optarg)) == NULL)
258                                 err(1, NULL);
259                         break;
260                 case 'z':
261                         zflag = 1;
262                         break;
263                 case 'D':
264                         Dflag = 1;
265                         break;
266                 case 'I':
267                         Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
268                         if (errstr != NULL)
269                                 errx(1, "TCP receive window %s: %s",
270                                     errstr, optarg);
271                         break;
272                 case 'O':
273                         Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
274                         if (errstr != NULL) {
275                             if (strcmp(errstr, "invalid") != 0)
276                                 errx(1, "TCP send window %s: %s",
277                                     errstr, optarg);
278                         }
279                         break;
280                 case 'S':
281                         Sflag = 1;
282                         break;
283                 case 'T':
284                         Tflag = parse_iptos(optarg);
285                         break;
286                 default:
287                         usage(1);
288                 }
289         }
290         argc -= optind;
291         argv += optind;
292
293         /* Cruft to make sure options are clean, and used properly. */
294         if (argv[0] && !argv[1] && family == AF_UNIX) {
295                 host = argv[0];
296                 uport = NULL;
297         } else if (argv[0] && !argv[1]) {
298                 if  (!lflag)
299                         usage(1);
300                 uport = argv[0];
301                 host = NULL;
302         } else if (argv[0] && argv[1]) {
303                 host = argv[0];
304                 uport = argv[1];
305         } else
306                 usage(1);
307
308         if (lflag && sflag)
309                 errx(1, "cannot use -s and -l");
310         if (lflag && pflag)
311                 errx(1, "cannot use -p and -l");
312         if (lflag && zflag)
313                 errx(1, "cannot use -z and -l");
314         if (!lflag && kflag)
315                 errx(1, "must use -l with -k");
316
317         /* Get name of temporary socket for unix datagram client */
318         if ((family == AF_UNIX) && uflag && !lflag) {
319                 if (sflag) {
320                         unix_dg_tmp_socket = sflag;
321                 } else {
322                         strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
323                                 UNIX_DG_TMP_SOCKET_SIZE);
324                         if (mktemp(unix_dg_tmp_socket_buf) == NULL)
325                                 err(1, "mktemp");
326                         unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
327                 }
328         }
329
330         /* Initialize addrinfo structure. */
331         if (family != AF_UNIX) {
332                 memset(&hints, 0, sizeof(struct addrinfo));
333                 hints.ai_family = family;
334                 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
335                 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
336                 if (nflag)
337                         hints.ai_flags |= AI_NUMERICHOST;
338         }
339
340         if (xflag) {
341                 if (uflag)
342                         errx(1, "no proxy support for UDP mode");
343
344                 if (lflag)
345                         errx(1, "no proxy support for listen");
346
347                 if (family == AF_UNIX)
348                         errx(1, "no proxy support for unix sockets");
349
350                 /* XXX IPv6 transport to proxy would probably work */
351                 if (family == AF_INET6)
352                         errx(1, "no proxy support for IPv6");
353
354                 if (sflag)
355                         errx(1, "no proxy support for local source address");
356
357                 proxyhost = strsep(&proxy, ":");
358                 proxyport = proxy;
359
360                 memset(&proxyhints, 0, sizeof(struct addrinfo));
361                 proxyhints.ai_family = family;
362                 proxyhints.ai_socktype = SOCK_STREAM;
363                 proxyhints.ai_protocol = IPPROTO_TCP;
364                 if (nflag)
365                         proxyhints.ai_flags |= AI_NUMERICHOST;
366         }
367
368         if (lflag) {
369                 int connfd;
370                 ret = 0;
371
372                 if (family == AF_UNIX) {
373                         if (uflag)
374                                 s = unix_bind(host);
375                         else
376                                 s = unix_listen(host);
377                 }
378
379                 /* Allow only one connection at a time, but stay alive. */
380                 for (;;) {
381                         if (family != AF_UNIX)
382                                 s = local_listen(host, uport, hints);
383                         if (s < 0)
384                                 err(1, NULL);
385                         /*
386                          * For UDP, we will use recvfrom() initially
387                          * to wait for a caller, then use the regular
388                          * functions to talk to the caller.
389                          */
390                         if (uflag) {
391                                 int rv, plen;
392                                 char buf[16384];
393                                 struct sockaddr_storage z;
394
395                                 len = sizeof(z);
396                                 plen = jflag ? 16384 : 2048;
397                                 rv = recvfrom(s, buf, plen, MSG_PEEK,
398                                     (struct sockaddr *)&z, &len);
399                                 if (rv < 0)
400                                         err(1, "recvfrom");
401
402                                 rv = connect(s, (struct sockaddr *)&z, len);
403                                 if (rv < 0)
404                                         err(1, "connect");
405
406                                 readwrite(s);
407                         } else {
408                                 len = sizeof(cliaddr);
409                                 connfd = accept(s, (struct sockaddr *)&cliaddr,
410                                     &len);
411                                 readwrite(connfd);
412                                 close(connfd);
413                         }
414
415                         if (family != AF_UNIX)
416                                 close(s);
417                         else if (uflag) {
418                                 if (connect(s, NULL, 0) < 0)
419                                         err(1, "connect");
420                         }
421
422                         if (!kflag)
423                                 break;
424                 }
425         } else if (family == AF_UNIX) {
426                 ret = 0;
427
428                 if ((s = unix_connect(host)) > 0 && !zflag) {
429                         readwrite(s);
430                         close(s);
431                 } else
432                         ret = 1;
433
434                 if (uflag)
435                         unlink(unix_dg_tmp_socket);
436                 exit(ret);
437
438         } else {
439                 int i = 0;
440
441                 /* Construct the portlist[] array. */
442                 build_ports(uport);
443
444                 /* Cycle through portlist, connecting to each port. */
445                 for (i = 0; portlist[i] != NULL; i++) {
446                         if (s)
447                                 close(s);
448
449                         if (xflag)
450                                 s = socks_connect(host, portlist[i], hints,
451                                     proxyhost, proxyport, proxyhints, socksv,
452                                     Pflag);
453                         else
454                                 s = remote_connect(host, portlist[i], hints);
455
456                         if (s < 0)
457                                 continue;
458
459                         ret = 0;
460                         if (vflag || zflag) {
461                                 /* For UDP, make sure we are connected. */
462                                 if (uflag) {
463                                         if (udptest(s) == -1) {
464                                                 ret = 1;
465                                                 continue;
466                                         }
467                                 }
468
469                                 /* Don't look up port if -n. */
470                                 if (nflag)
471                                         sv = NULL;
472                                 else {
473                                         sv = getservbyport(
474                                             ntohs(atoi(portlist[i])),
475                                             uflag ? "udp" : "tcp");
476                                 }
477
478                                 fprintf(stderr,
479                                     "Connection to %s %s port [%s/%s] "
480                                     "succeeded!\n", host, portlist[i],
481                                     uflag ? "udp" : "tcp",
482                                     sv ? sv->s_name : "*");
483                         }
484                         if (!zflag)
485                                 readwrite(s);
486                 }
487         }
488
489         if (s)
490                 close(s);
491
492         exit(ret);
493 }
494
495 /*
496  * unix_bind()
497  * Returns a unix socket bound to the given path
498  */
499 int
500 unix_bind(char *path)
501 {
502         struct sockaddr_un sun;
503         int s;
504
505         /* Create unix domain socket. */
506         if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
507              0)) < 0)
508                 return (-1);
509
510         memset(&sun, 0, sizeof(struct sockaddr_un));
511         sun.sun_family = AF_UNIX;
512
513         if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
514             sizeof(sun.sun_path)) {
515                 close(s);
516                 errno = ENAMETOOLONG;
517                 return (-1);
518         }
519
520         if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
521                 close(s);
522                 return (-1);
523         }
524         return (s);
525 }
526
527 /*
528  * unix_connect()
529  * Returns a socket connected to a local unix socket. Returns -1 on failure.
530  */
531 int
532 unix_connect(char *path)
533 {
534         struct sockaddr_un sun;
535         int s;
536
537         if (uflag) {
538                 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
539                         return (-1);
540         } else {
541                 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
542                         return (-1);
543         }
544         (void)fcntl(s, F_SETFD, 1);
545
546         memset(&sun, 0, sizeof(struct sockaddr_un));
547         sun.sun_family = AF_UNIX;
548
549         if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
550             sizeof(sun.sun_path)) {
551                 close(s);
552                 errno = ENAMETOOLONG;
553                 return (-1);
554         }
555         if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
556                 close(s);
557                 return (-1);
558         }
559         return (s);
560
561 }
562
563 /*
564  * unix_listen()
565  * Create a unix domain socket, and listen on it.
566  */
567 int
568 unix_listen(char *path)
569 {
570         int s;
571         if ((s = unix_bind(path)) < 0)
572                 return (-1);
573
574         if (listen(s, 5) < 0) {
575                 close(s);
576                 return (-1);
577         }
578         return (s);
579 }
580
581 /*
582  * remote_connect()
583  * Returns a socket connected to a remote host. Properly binds to a local
584  * port or source address if needed. Returns -1 on failure.
585  */
586 int
587 remote_connect(const char *host, const char *port, struct addrinfo hints)
588 {
589         struct addrinfo *res, *res0;
590         int s, error, on = 1;
591
592         if ((error = getaddrinfo(host, port, &hints, &res)))
593                 errx(1, "getaddrinfo: %s", gai_strerror(error));
594
595         res0 = res;
596         do {
597                 if ((s = socket(res0->ai_family, res0->ai_socktype,
598                     res0->ai_protocol)) < 0)
599                         continue;
600 #ifdef IPSEC
601                 if (ipsec_policy[0] != NULL)
602                         add_ipsec_policy(s, ipsec_policy[0]);
603                 if (ipsec_policy[1] != NULL)
604                         add_ipsec_policy(s, ipsec_policy[1]);
605 #endif
606
607                 if (rtableid) {
608                         if (setsockopt(s, SOL_SOCKET, SO_SETFIB, &rtableid,
609                             sizeof(rtableid)) == -1)
610                                 err(1, "setsockopt(.., SO_SETFIB, %u, ..)",
611                                     rtableid);
612                 }
613
614                 /* Bind to a local port or source address if specified. */
615                 if (sflag || pflag) {
616                         struct addrinfo ahints, *ares;
617
618                         /* try IP_BINDANY, but don't insist */
619                         setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
620                         memset(&ahints, 0, sizeof(struct addrinfo));
621                         ahints.ai_family = res0->ai_family;
622                         ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
623                         ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
624                         ahints.ai_flags = AI_PASSIVE;
625                         if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
626                                 errx(1, "getaddrinfo: %s", gai_strerror(error));
627
628                         if (bind(s, (struct sockaddr *)ares->ai_addr,
629                             ares->ai_addrlen) < 0)
630                                 errx(1, "bind failed: %s", strerror(errno));
631                         freeaddrinfo(ares);
632                 }
633
634                 set_common_sockopts(s);
635
636                 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
637                         break;
638                 else if (vflag)
639                         warn("connect to %s port %s (%s) failed", host, port,
640                             uflag ? "udp" : "tcp");
641
642                 close(s);
643                 s = -1;
644         } while ((res0 = res0->ai_next) != NULL);
645
646         freeaddrinfo(res);
647
648         return (s);
649 }
650
651 /*
652  * local_listen()
653  * Returns a socket listening on a local port, binds to specified source
654  * address. Returns -1 on failure.
655  */
656 int
657 local_listen(char *host, char *port, struct addrinfo hints)
658 {
659         struct addrinfo *res, *res0;
660         int s, ret, x = 1;
661         int error;
662
663         /* Allow nodename to be null. */
664         hints.ai_flags |= AI_PASSIVE;
665
666         /*
667          * In the case of binding to a wildcard address
668          * default to binding to an ipv4 address.
669          */
670         if (host == NULL && hints.ai_family == AF_UNSPEC)
671                 hints.ai_family = AF_INET;
672
673         if ((error = getaddrinfo(host, port, &hints, &res)))
674                 errx(1, "getaddrinfo: %s", gai_strerror(error));
675
676         res0 = res;
677         do {
678                 if ((s = socket(res0->ai_family, res0->ai_socktype,
679                     res0->ai_protocol)) < 0)
680                         continue;
681
682                 if (rtableid) {
683                         ret = setsockopt(s, SOL_SOCKET, SO_SETFIB, &rtableid,
684                             sizeof(rtableid));
685                         if (ret == -1)
686                                 err(1, "setsockopt(.., SO_SETFIB, %u, ..)",
687                                     rtableid);
688                 }
689
690                 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
691                 if (ret == -1)
692                         err(1, NULL);
693 #ifdef IPSEC
694                 if (ipsec_policy[0] != NULL)
695                         add_ipsec_policy(s, ipsec_policy[0]);
696                 if (ipsec_policy[1] != NULL)
697                         add_ipsec_policy(s, ipsec_policy[1]);
698 #endif
699                 if (FreeBSD_Oflag) {
700                         if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
701                             &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
702                                 err(1, "disable TCP options");
703                 }
704
705                 if (bind(s, (struct sockaddr *)res0->ai_addr,
706                     res0->ai_addrlen) == 0)
707                         break;
708
709                 close(s);
710                 s = -1;
711         } while ((res0 = res0->ai_next) != NULL);
712
713         if (!uflag && s != -1) {
714                 if (listen(s, 1) < 0)
715                         err(1, "listen");
716         }
717
718         freeaddrinfo(res);
719
720         return (s);
721 }
722
723 /*
724  * readwrite()
725  * Loop that polls on the network file descriptor and stdin.
726  */
727 void
728 readwrite(int nfd)
729 {
730         struct pollfd pfd[2];
731         unsigned char buf[16384];
732         int n, wfd = fileno(stdin);
733         int lfd = fileno(stdout);
734         int plen;
735
736         plen = jflag ? 16384 : 2048;
737
738         /* Setup Network FD */
739         pfd[0].fd = nfd;
740         pfd[0].events = POLLIN;
741
742         /* Set up STDIN FD. */
743         pfd[1].fd = wfd;
744         pfd[1].events = POLLIN;
745
746         while (pfd[0].fd != -1) {
747                 if (iflag)
748                         sleep(iflag);
749
750                 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
751                         close(nfd);
752                         err(1, "Polling Error");
753                 }
754
755                 if (n == 0)
756                         return;
757
758                 if (pfd[0].revents & POLLIN) {
759                         if ((n = read(nfd, buf, plen)) < 0)
760                                 return;
761                         else if (n == 0) {
762                                 shutdown(nfd, SHUT_RD);
763                                 pfd[0].fd = -1;
764                                 pfd[0].events = 0;
765                         } else {
766                                 if (tflag)
767                                         atelnet(nfd, buf, n);
768                                 if (atomicio(vwrite, lfd, buf, n) != n)
769                                         return;
770                         }
771                 }
772
773                 if (!dflag && pfd[1].revents & POLLIN) {
774                         if ((n = read(wfd, buf, plen)) < 0)
775                                 return;
776                         else if (n == 0) {
777                                 shutdown(nfd, SHUT_WR);
778                                 pfd[1].fd = -1;
779                                 pfd[1].events = 0;
780                         } else {
781                                 if (atomicio(vwrite, nfd, buf, n) != n)
782                                         return;
783                         }
784                 }
785         }
786 }
787
788 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
789 void
790 atelnet(int nfd, unsigned char *buf, unsigned int size)
791 {
792         unsigned char *p, *end;
793         unsigned char obuf[4];
794
795         if (size < 3)
796                 return;
797         end = buf + size - 2;
798
799         for (p = buf; p < end; p++) {
800                 if (*p != IAC)
801                         continue;
802
803                 obuf[0] = IAC;
804                 p++;
805                 if ((*p == WILL) || (*p == WONT))
806                         obuf[1] = DONT;
807                 else if ((*p == DO) || (*p == DONT))
808                         obuf[1] = WONT;
809                 else
810                         continue;
811
812                 p++;
813                 obuf[2] = *p;
814                 if (atomicio(vwrite, nfd, obuf, 3) != 3)
815                         warn("Write Error!");
816         }
817 }
818
819 /*
820  * build_ports()
821  * Build an array or ports in portlist[], listing each port
822  * that we should try to connect to.
823  */
824 void
825 build_ports(char *p)
826 {
827         const char *errstr;
828         char *n;
829         int hi, lo, cp;
830         int x = 0;
831
832         if ((n = strchr(p, '-')) != NULL) {
833                 if (lflag)
834                         errx(1, "Cannot use -l with multiple ports!");
835
836                 *n = '\0';
837                 n++;
838
839                 /* Make sure the ports are in order: lowest->highest. */
840                 hi = strtonum(n, 1, PORT_MAX, &errstr);
841                 if (errstr)
842                         errx(1, "port number %s: %s", errstr, n);
843                 lo = strtonum(p, 1, PORT_MAX, &errstr);
844                 if (errstr)
845                         errx(1, "port number %s: %s", errstr, p);
846
847                 if (lo > hi) {
848                         cp = hi;
849                         hi = lo;
850                         lo = cp;
851                 }
852
853                 /* Load ports sequentially. */
854                 for (cp = lo; cp <= hi; cp++) {
855                         portlist[x] = calloc(1, PORT_MAX_LEN);
856                         if (portlist[x] == NULL)
857                                 err(1, NULL);
858                         snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
859                         x++;
860                 }
861
862                 /* Randomly swap ports. */
863                 if (rflag) {
864                         int y;
865                         char *c;
866
867                         for (x = 0; x <= (hi - lo); x++) {
868                                 y = (arc4random() & 0xFFFF) % (hi - lo);
869                                 c = portlist[x];
870                                 portlist[x] = portlist[y];
871                                 portlist[y] = c;
872                         }
873                 }
874         } else {
875                 hi = strtonum(p, 1, PORT_MAX, &errstr);
876                 if (errstr)
877                         errx(1, "port number %s: %s", errstr, p);
878                 portlist[0] = strdup(p);
879                 if (portlist[0] == NULL)
880                         err(1, NULL);
881         }
882 }
883
884 /*
885  * udptest()
886  * Do a few writes to see if the UDP port is there.
887  * XXX - Better way of doing this? Doesn't work for IPv6.
888  * Also fails after around 100 ports checked.
889  */
890 int
891 udptest(int s)
892 {
893         int i, ret;
894
895         for (i = 0; i <= 3; i++) {
896                 if (write(s, "X", 1) == 1)
897                         ret = 1;
898                 else
899                         ret = -1;
900         }
901         return (ret);
902 }
903
904 void
905 set_common_sockopts(int s)
906 {
907         int x = 1;
908
909         if (Sflag) {
910                 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
911                         &x, sizeof(x)) == -1)
912                         err(1, NULL);
913         }
914         if (Dflag) {
915                 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
916                         &x, sizeof(x)) == -1)
917                         err(1, NULL);
918         }
919 #ifdef SO_JUMBO
920         if (jflag) {
921                 if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
922                         &x, sizeof(x)) == -1)
923                         err(1, NULL);
924         }
925 #endif
926         if (Tflag != -1) {
927                 if (setsockopt(s, IPPROTO_IP, IP_TOS,
928                     &Tflag, sizeof(Tflag)) == -1)
929                         err(1, "set IP ToS");
930         }
931         if (Iflag) {
932                 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
933                     &Iflag, sizeof(Iflag)) == -1)
934                         err(1, "set TCP receive buffer size");
935         }
936         if (Oflag) {
937                 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
938                     &Oflag, sizeof(Oflag)) == -1)
939                         err(1, "set TCP send buffer size");
940         }
941         if (FreeBSD_Oflag) {
942                 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
943                     &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
944                         err(1, "disable TCP options");
945         }
946 }
947
948 int
949 parse_iptos(char *s)
950 {
951         int tos = -1;
952
953         if (strcmp(s, "lowdelay") == 0)
954                 return (IPTOS_LOWDELAY);
955         if (strcmp(s, "throughput") == 0)
956                 return (IPTOS_THROUGHPUT);
957         if (strcmp(s, "reliability") == 0)
958                 return (IPTOS_RELIABILITY);
959
960         if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
961                 errx(1, "invalid IP Type of Service");
962         return (tos);
963 }
964
965 void
966 help(void)
967 {
968         usage(0);
969         fprintf(stderr, "\tCommand Summary:\n\
970         \t-4            Use IPv4\n\
971         \t-6            Use IPv6\n\
972         \t-D            Enable the debug socket option\n\
973         \t-d            Detach from stdin\n");
974 #ifdef IPSEC
975         fprintf(stderr, "\
976         \t-E            Use IPsec ESP\n\
977         \t-e policy     Use specified IPsec policy\n");
978 #endif
979         fprintf(stderr, "\
980         \t-h            This help text\n\
981         \t-I length     TCP receive buffer length\n\
982         \t-i secs\t     Delay interval for lines sent, ports scanned\n\
983         \t-k            Keep inbound sockets open for multiple connects\n\
984         \t-l            Listen mode, for inbound connects\n\
985         \t-n            Suppress name/port resolutions\n\
986         \t--no-tcpopt   Disable TCP options\n\
987         \t-O length     TCP send buffer length\n\
988         \t-P proxyuser\tUsername for proxy authentication\n\
989         \t-p port\t     Specify local port for remote connects\n\
990         \t-r            Randomize remote ports\n\
991         \t-S            Enable the TCP MD5 signature option\n\
992         \t-s addr\t     Local source address\n\
993         \t-T ToS\t      Set IP Type of Service\n\
994         \t-t            Answer TELNET negotiation\n\
995         \t-U            Use UNIX domain socket\n\
996         \t-u            UDP mode\n\
997         \t-V rtable     Specify alternate routing table\n\
998         \t-v            Verbose\n\
999         \t-w secs\t     Timeout for connects and final net reads\n\
1000         \t-X proto      Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1001         \t-x addr[:port]\tSpecify proxy address and port\n\
1002         \t-z            Zero-I/O mode [used for scanning]\n\
1003         Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1004 #ifdef IPSEC
1005         fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
1006 #endif
1007         exit(1);
1008 }
1009
1010 #ifdef IPSEC
1011 void
1012 add_ipsec_policy(int s, char *policy)
1013 {
1014         char *raw;
1015         int e;
1016
1017         raw = ipsec_set_policy(policy, strlen(policy));
1018         if (raw == NULL)
1019                 errx(1, "ipsec_set_policy `%s': %s", policy,
1020                      ipsec_strerror());
1021         e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1022                         ipsec_get_policylen(raw));
1023         if (e < 0)
1024                 err(1, "ipsec policy cannot be configured");
1025         free(raw);
1026         if (vflag)
1027                 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1028         return;
1029 }
1030 #endif /* IPSEC */
1031
1032 void
1033 usage(int ret)
1034 {
1035         fprintf(stderr,
1036 #ifdef IPSEC
1037             "usage: nc [-46DdEhklnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1038 #else
1039             "usage: nc [-46DdhklnrStUuvz] [-I length] [-i interval] [-O length]\n"
1040 #endif
1041             "\t  [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1042             "\t  [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1043             "\t  [-x proxy_address[:port]] [destination] [port]\n");
1044         if (ret)
1045                 exit(1);
1046 }