]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/netcat/netcat.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.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 (setfib(rtableid) == -1)
609                                 err(1, "setfib");
610                 }
611
612                 /* Bind to a local port or source address if specified. */
613                 if (sflag || pflag) {
614                         struct addrinfo ahints, *ares;
615
616                         /* try IP_BINDANY, but don't insist */
617                         setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
618                         memset(&ahints, 0, sizeof(struct addrinfo));
619                         ahints.ai_family = res0->ai_family;
620                         ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
621                         ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
622                         ahints.ai_flags = AI_PASSIVE;
623                         if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
624                                 errx(1, "getaddrinfo: %s", gai_strerror(error));
625
626                         if (bind(s, (struct sockaddr *)ares->ai_addr,
627                             ares->ai_addrlen) < 0)
628                                 errx(1, "bind failed: %s", strerror(errno));
629                         freeaddrinfo(ares);
630                 }
631
632                 set_common_sockopts(s);
633
634                 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
635                         break;
636                 else if (vflag)
637                         warn("connect to %s port %s (%s) failed", host, port,
638                             uflag ? "udp" : "tcp");
639
640                 close(s);
641                 s = -1;
642         } while ((res0 = res0->ai_next) != NULL);
643
644         freeaddrinfo(res);
645
646         return (s);
647 }
648
649 /*
650  * local_listen()
651  * Returns a socket listening on a local port, binds to specified source
652  * address. Returns -1 on failure.
653  */
654 int
655 local_listen(char *host, char *port, struct addrinfo hints)
656 {
657         struct addrinfo *res, *res0;
658         int s, ret, x = 1;
659         int error;
660
661         /* Allow nodename to be null. */
662         hints.ai_flags |= AI_PASSIVE;
663
664         /*
665          * In the case of binding to a wildcard address
666          * default to binding to an ipv4 address.
667          */
668         if (host == NULL && hints.ai_family == AF_UNSPEC)
669                 hints.ai_family = AF_INET;
670
671         if ((error = getaddrinfo(host, port, &hints, &res)))
672                 errx(1, "getaddrinfo: %s", gai_strerror(error));
673
674         res0 = res;
675         do {
676                 if ((s = socket(res0->ai_family, res0->ai_socktype,
677                     res0->ai_protocol)) < 0)
678                         continue;
679
680                 if (rtableid) {
681                         if (setfib(rtableid) == -1)
682                                 err(1, "setfib");
683                 }
684
685                 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
686                 if (ret == -1)
687                         err(1, NULL);
688 #ifdef IPSEC
689                 if (ipsec_policy[0] != NULL)
690                         add_ipsec_policy(s, ipsec_policy[0]);
691                 if (ipsec_policy[1] != NULL)
692                         add_ipsec_policy(s, ipsec_policy[1]);
693 #endif
694                 if (FreeBSD_Oflag) {
695                         if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
696                             &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
697                                 err(1, "disable TCP options");
698                 }
699
700                 if (bind(s, (struct sockaddr *)res0->ai_addr,
701                     res0->ai_addrlen) == 0)
702                         break;
703
704                 close(s);
705                 s = -1;
706         } while ((res0 = res0->ai_next) != NULL);
707
708         if (!uflag && s != -1) {
709                 if (listen(s, 1) < 0)
710                         err(1, "listen");
711         }
712
713         freeaddrinfo(res);
714
715         return (s);
716 }
717
718 /*
719  * readwrite()
720  * Loop that polls on the network file descriptor and stdin.
721  */
722 void
723 readwrite(int nfd)
724 {
725         struct pollfd pfd[2];
726         unsigned char buf[16384];
727         int n, wfd = fileno(stdin);
728         int lfd = fileno(stdout);
729         int plen;
730
731         plen = jflag ? 16384 : 2048;
732
733         /* Setup Network FD */
734         pfd[0].fd = nfd;
735         pfd[0].events = POLLIN;
736
737         /* Set up STDIN FD. */
738         pfd[1].fd = wfd;
739         pfd[1].events = POLLIN;
740
741         while (pfd[0].fd != -1) {
742                 if (iflag)
743                         sleep(iflag);
744
745                 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
746                         close(nfd);
747                         err(1, "Polling Error");
748                 }
749
750                 if (n == 0)
751                         return;
752
753                 if (pfd[0].revents & POLLIN) {
754                         if ((n = read(nfd, buf, plen)) < 0)
755                                 return;
756                         else if (n == 0) {
757                                 shutdown(nfd, SHUT_RD);
758                                 pfd[0].fd = -1;
759                                 pfd[0].events = 0;
760                         } else {
761                                 if (tflag)
762                                         atelnet(nfd, buf, n);
763                                 if (atomicio(vwrite, lfd, buf, n) != n)
764                                         return;
765                         }
766                 }
767
768                 if (!dflag && pfd[1].revents & POLLIN) {
769                         if ((n = read(wfd, buf, plen)) < 0)
770                                 return;
771                         else if (n == 0) {
772                                 shutdown(nfd, SHUT_WR);
773                                 pfd[1].fd = -1;
774                                 pfd[1].events = 0;
775                         } else {
776                                 if (atomicio(vwrite, nfd, buf, n) != n)
777                                         return;
778                         }
779                 }
780         }
781 }
782
783 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
784 void
785 atelnet(int nfd, unsigned char *buf, unsigned int size)
786 {
787         unsigned char *p, *end;
788         unsigned char obuf[4];
789
790         if (size < 3)
791                 return;
792         end = buf + size - 2;
793
794         for (p = buf; p < end; p++) {
795                 if (*p != IAC)
796                         continue;
797
798                 obuf[0] = IAC;
799                 p++;
800                 if ((*p == WILL) || (*p == WONT))
801                         obuf[1] = DONT;
802                 else if ((*p == DO) || (*p == DONT))
803                         obuf[1] = WONT;
804                 else
805                         continue;
806
807                 p++;
808                 obuf[2] = *p;
809                 if (atomicio(vwrite, nfd, obuf, 3) != 3)
810                         warn("Write Error!");
811         }
812 }
813
814 /*
815  * build_ports()
816  * Build an array or ports in portlist[], listing each port
817  * that we should try to connect to.
818  */
819 void
820 build_ports(char *p)
821 {
822         const char *errstr;
823         char *n;
824         int hi, lo, cp;
825         int x = 0;
826
827         if ((n = strchr(p, '-')) != NULL) {
828                 if (lflag)
829                         errx(1, "Cannot use -l with multiple ports!");
830
831                 *n = '\0';
832                 n++;
833
834                 /* Make sure the ports are in order: lowest->highest. */
835                 hi = strtonum(n, 1, PORT_MAX, &errstr);
836                 if (errstr)
837                         errx(1, "port number %s: %s", errstr, n);
838                 lo = strtonum(p, 1, PORT_MAX, &errstr);
839                 if (errstr)
840                         errx(1, "port number %s: %s", errstr, p);
841
842                 if (lo > hi) {
843                         cp = hi;
844                         hi = lo;
845                         lo = cp;
846                 }
847
848                 /* Load ports sequentially. */
849                 for (cp = lo; cp <= hi; cp++) {
850                         portlist[x] = calloc(1, PORT_MAX_LEN);
851                         if (portlist[x] == NULL)
852                                 err(1, NULL);
853                         snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
854                         x++;
855                 }
856
857                 /* Randomly swap ports. */
858                 if (rflag) {
859                         int y;
860                         char *c;
861
862                         for (x = 0; x <= (hi - lo); x++) {
863                                 y = (arc4random() & 0xFFFF) % (hi - lo);
864                                 c = portlist[x];
865                                 portlist[x] = portlist[y];
866                                 portlist[y] = c;
867                         }
868                 }
869         } else {
870                 hi = strtonum(p, 1, PORT_MAX, &errstr);
871                 if (errstr)
872                         errx(1, "port number %s: %s", errstr, p);
873                 portlist[0] = strdup(p);
874                 if (portlist[0] == NULL)
875                         err(1, NULL);
876         }
877 }
878
879 /*
880  * udptest()
881  * Do a few writes to see if the UDP port is there.
882  * XXX - Better way of doing this? Doesn't work for IPv6.
883  * Also fails after around 100 ports checked.
884  */
885 int
886 udptest(int s)
887 {
888         int i, ret;
889
890         for (i = 0; i <= 3; i++) {
891                 if (write(s, "X", 1) == 1)
892                         ret = 1;
893                 else
894                         ret = -1;
895         }
896         return (ret);
897 }
898
899 void
900 set_common_sockopts(int s)
901 {
902         int x = 1;
903
904         if (Sflag) {
905                 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
906                         &x, sizeof(x)) == -1)
907                         err(1, NULL);
908         }
909         if (Dflag) {
910                 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
911                         &x, sizeof(x)) == -1)
912                         err(1, NULL);
913         }
914 #ifdef SO_JUMBO
915         if (jflag) {
916                 if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
917                         &x, sizeof(x)) == -1)
918                         err(1, NULL);
919         }
920 #endif
921         if (Tflag != -1) {
922                 if (setsockopt(s, IPPROTO_IP, IP_TOS,
923                     &Tflag, sizeof(Tflag)) == -1)
924                         err(1, "set IP ToS");
925         }
926         if (Iflag) {
927                 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
928                     &Iflag, sizeof(Iflag)) == -1)
929                         err(1, "set TCP receive buffer size");
930         }
931         if (Oflag) {
932                 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
933                     &Oflag, sizeof(Oflag)) == -1)
934                         err(1, "set TCP send buffer size");
935         }
936         if (FreeBSD_Oflag) {
937                 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
938                     &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
939                         err(1, "disable TCP options");
940         }
941 }
942
943 int
944 parse_iptos(char *s)
945 {
946         int tos = -1;
947
948         if (strcmp(s, "lowdelay") == 0)
949                 return (IPTOS_LOWDELAY);
950         if (strcmp(s, "throughput") == 0)
951                 return (IPTOS_THROUGHPUT);
952         if (strcmp(s, "reliability") == 0)
953                 return (IPTOS_RELIABILITY);
954
955         if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
956                 errx(1, "invalid IP Type of Service");
957         return (tos);
958 }
959
960 void
961 help(void)
962 {
963         usage(0);
964         fprintf(stderr, "\tCommand Summary:\n\
965         \t-4            Use IPv4\n\
966         \t-6            Use IPv6\n\
967         \t-D            Enable the debug socket option\n\
968         \t-d            Detach from stdin\n");
969 #ifdef IPSEC
970         fprintf(stderr, "\
971         \t-E            Use IPsec ESP\n\
972         \t-e policy     Use specified IPsec policy\n");
973 #endif
974         fprintf(stderr, "\
975         \t-h            This help text\n\
976         \t-I length     TCP receive buffer length\n\
977         \t-i secs\t     Delay interval for lines sent, ports scanned\n\
978         \t-k            Keep inbound sockets open for multiple connects\n\
979         \t-l            Listen mode, for inbound connects\n\
980         \t-n            Suppress name/port resolutions\n\
981         \t--no-tcpopt   Disable TCP options\n\
982         \t-O length     TCP send buffer length\n\
983         \t-P proxyuser\tUsername for proxy authentication\n\
984         \t-p port\t     Specify local port for remote connects\n\
985         \t-r            Randomize remote ports\n\
986         \t-S            Enable the TCP MD5 signature option\n\
987         \t-s addr\t     Local source address\n\
988         \t-T ToS\t      Set IP Type of Service\n\
989         \t-t            Answer TELNET negotiation\n\
990         \t-U            Use UNIX domain socket\n\
991         \t-u            UDP mode\n\
992         \t-V rtable     Specify alternate routing table\n\
993         \t-v            Verbose\n\
994         \t-w secs\t     Timeout for connects and final net reads\n\
995         \t-X proto      Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
996         \t-x addr[:port]\tSpecify proxy address and port\n\
997         \t-z            Zero-I/O mode [used for scanning]\n\
998         Port numbers can be individual or ranges: lo-hi [inclusive]\n");
999 #ifdef IPSEC
1000         fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
1001 #endif
1002         exit(1);
1003 }
1004
1005 #ifdef IPSEC
1006 void
1007 add_ipsec_policy(int s, char *policy)
1008 {
1009         char *raw;
1010         int e;
1011
1012         raw = ipsec_set_policy(policy, strlen(policy));
1013         if (raw == NULL)
1014                 errx(1, "ipsec_set_policy `%s': %s", policy,
1015                      ipsec_strerror());
1016         e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1017                         ipsec_get_policylen(raw));
1018         if (e < 0)
1019                 err(1, "ipsec policy cannot be configured");
1020         free(raw);
1021         if (vflag)
1022                 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1023         return;
1024 }
1025 #endif /* IPSEC */
1026
1027 void
1028 usage(int ret)
1029 {
1030         fprintf(stderr,
1031 #ifdef IPSEC
1032             "usage: nc [-46DdEhklnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1033 #else
1034             "usage: nc [-46DdhklnrStUuvz] [-I length] [-i interval] [-O length]\n"
1035 #endif
1036             "\t  [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1037             "\t  [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1038             "\t  [-x proxy_address[:port]] [destination] [port]\n");
1039         if (ret)
1040                 exit(1);
1041 }