1 /* $OpenBSD: netcat.c,v 1.130 2015/07/26 19:12:28 chl Exp $ */
3 * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
32 * Re-written nc(1) for OpenBSD. Original implementation by
33 * *Hobbit* <hobbit@avian.org>.
39 #include <sys/limits.h>
40 #include <sys/types.h>
42 #include <sys/socket.h>
43 #include <sys/sysctl.h>
44 #include <sys/qmath.h>
45 #include <sys/stats.h>
50 #include <netinet/in.h>
52 #include <netipsec/ipsec.h>
54 #include <netinet/tcp.h>
55 #include <netinet/ip.h>
56 #include <arpa/telnet.h>
73 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
76 #define PORT_MAX 65535
77 #define PORT_MAX_LEN 6
78 #define UNIX_DG_TMP_SOCKET_SIZE 19
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 */
113 int family = AF_UNSPEC;
114 char *portlist[PORT_MAX+1];
115 char *unix_dg_tmp_socket;
117 void atelnet(int, unsigned char *, unsigned int);
118 void build_ports(char *);
120 int local_listen(char *, char *, struct addrinfo);
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 *);
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);
137 ssize_t drainbuf(int, unsigned char *, size_t *);
138 ssize_t fillbuf(int, unsigned char *, size_t *);
141 void add_ipsec_policy(int, int, char *);
143 char *ipsec_policy[2];
147 main(int argc, char *argv[])
149 int ch, s, ret, socksv, ipsec_count;
151 size_t intsize = sizeof(int);
153 struct addrinfo hints;
156 struct sockaddr_storage cliaddr;
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 },
174 signal(SIGPIPE, SIG_IGN);
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) {
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 */
197 errx(1, "unsupported proxy protocol");
204 ipsec_policy[ipsec_count++ % 2] = optarg;
206 errx(1, "IPsec support unavailable.");
211 ipsec_policy[0] = "in ipsec esp/transport//require";
212 ipsec_policy[1] = "out ipsec esp/transport//require";
214 errx(1, "IPsec support unavailable.");
224 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
226 errx(1, "interval %s: %s", errstr, optarg);
236 errx(1, "-M requires stats(3) support");
248 fprintf(stderr, "option -o is deprecated.\n");
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);
274 errx(1, "rtable %s: %s", errstr, optarg);
280 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
282 errx(1, "timeout %s: %s", errstr, optarg);
287 if ((proxy = strdup(optarg)) == NULL)
297 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
299 errx(1, "TCP receive window %s: %s",
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",
316 if (map_tos(optarg, &Tflag))
318 if (strlen(optarg) > 1 && optarg[0] == '0' &&
320 Tflag = (int)strtol(optarg, NULL, 16);
322 Tflag = (int)strtonum(optarg, 0, 255,
324 if (Tflag < 0 || Tflag > 255 || errstr || errno)
325 errx(1, "illegal tos value %s", optarg);
334 /* Cruft to make sure options are clean, and used properly. */
335 if (argv[0] && !argv[1] && family == AF_UNIX) {
338 } else if (argv[0] && !argv[1]) {
343 } else if (argv[0] && argv[1]) {
350 errx(1, "cannot use -s and -l");
352 errx(1, "cannot use -p and -l");
354 errx(1, "cannot use -z and -l");
356 errx(1, "must use -l with -k");
358 /* Get name of temporary socket for unix datagram client */
359 if ((family == AF_UNIX) && uflag && !lflag) {
361 unix_dg_tmp_socket = sflag;
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)
367 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
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;
378 hints.ai_flags |= AI_NUMERICHOST;
383 errx(1, "no proxy support for UDP mode");
386 errx(1, "no proxy support for listen");
388 if (family == AF_UNIX)
389 errx(1, "no proxy support for unix sockets");
391 /* XXX IPv6 transport to proxy would probably work */
392 if (family == AF_INET6)
393 errx(1, "no proxy support for IPv6");
396 errx(1, "no proxy support for local source address");
398 proxyhost = strsep(&proxy, ":");
401 memset(&proxyhints, 0, sizeof(struct addrinfo));
402 proxyhints.ai_family = family;
403 proxyhints.ai_socktype = SOCK_STREAM;
404 proxyhints.ai_protocol = IPPROTO_TCP;
406 proxyhints.ai_flags |= AI_NUMERICHOST;
413 if (family == AF_UNIX) {
417 s = unix_listen(host);
420 /* Allow only one connection at a time, but stay alive. */
422 if (family != AF_UNIX)
423 s = local_listen(host, uport, hints);
427 * For UDP and -k, don't connect the socket, let it
428 * receive datagrams from multiple socket pairs.
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.
437 else if (uflag && !kflag) {
440 struct sockaddr_storage z;
444 rv = recvfrom(s, buf, plen, MSG_PEEK,
445 (struct sockaddr *)&z, &len);
449 rv = connect(s, (struct sockaddr *)&z, len);
454 report_connect((struct sockaddr *)&z, len);
458 len = sizeof(cliaddr);
459 connfd = accept(s, (struct sockaddr *)&cliaddr,
462 /* For now, all errnos are fatal */
466 report_connect((struct sockaddr *)&cliaddr, len);
469 FreeBSD_stats_setup(connfd);
474 if (family != AF_UNIX)
477 if (connect(s, NULL, 0) < 0)
484 } else if (family == AF_UNIX) {
487 if ((s = unix_connect(host)) > 0 && !zflag) {
494 unlink(unix_dg_tmp_socket);
500 /* Construct the portlist[] array. */
503 /* Cycle through portlist, connecting to each port. */
504 for (i = 0; portlist[i] != NULL; i++) {
509 s = socks_connect(host, portlist[i], hints,
510 proxyhost, proxyport, proxyhints, socksv,
513 s = remote_connect(host, portlist[i], hints);
519 if (vflag || zflag) {
520 /* For UDP, make sure we are connected. */
522 if (udptest(s) == -1) {
528 /* Don't look up port if -n. */
533 ntohs(atoi(portlist[i])),
534 uflag ? "udp" : "tcp");
538 "Connection to %s %s port [%s/%s] "
539 "succeeded!\n", host, portlist[i],
540 uflag ? "udp" : "tcp",
541 sv ? sv->s_name : "*");
558 * Returns a unix socket bound to the given path
561 unix_bind(char *path)
563 struct sockaddr_un sun;
566 /* Create unix domain socket. */
567 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
571 memset(&sun, 0, sizeof(struct sockaddr_un));
572 sun.sun_family = AF_UNIX;
574 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
575 sizeof(sun.sun_path)) {
577 errno = ENAMETOOLONG;
581 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
590 * Returns a socket connected to a local unix socket. Returns -1 on failure.
593 unix_connect(char *path)
595 struct sockaddr_un sun;
599 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
602 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
605 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
607 memset(&sun, 0, sizeof(struct sockaddr_un));
608 sun.sun_family = AF_UNIX;
610 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
611 sizeof(sun.sun_path)) {
613 errno = ENAMETOOLONG;
616 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
626 * Create a unix domain socket, and listen on it.
629 unix_listen(char *path)
632 if ((s = unix_bind(path)) < 0)
635 if (listen(s, 5) < 0) {
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.
648 remote_connect(const char *host, const char *port, struct addrinfo hints)
650 struct addrinfo *res, *res0;
651 int s, error, on = 1;
653 if ((error = getaddrinfo(host, port, &hints, &res)))
654 errx(1, "getaddrinfo: %s", gai_strerror(error));
658 if ((s = socket(res0->ai_family, res0->ai_socktype,
659 res0->ai_protocol)) < 0)
662 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
663 &rtableid, sizeof(rtableid)) == -1))
664 err(1, "setsockopt SO_SETFIB");
666 /* Bind to a local port or source address if specified. */
667 if (sflag || pflag) {
668 struct addrinfo ahints, *ares;
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));
680 if (bind(s, (struct sockaddr *)ares->ai_addr,
681 ares->ai_addrlen) < 0)
682 err(1, "bind failed");
686 set_common_sockopts(s, res0->ai_family);
688 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
691 warn("connect to %s port %s (%s) failed", host, port,
692 uflag ? "udp" : "tcp");
696 } while ((res0 = res0->ai_next) != NULL);
704 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
712 flags = fcntl(s, F_GETFL, 0);
713 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
714 err(1, "set non-blocking mode");
717 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
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) {
725 ret = optval == 0 ? 0 : -1;
727 } else if (ret == 0) {
731 err(1, "poll failed");
734 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
735 err(1, "restoring flags");
742 * Returns a socket listening on a local port, binds to specified source
743 * address. Returns -1 on failure.
746 local_listen(char *host, char *port, struct addrinfo hints)
748 struct addrinfo *res, *res0;
752 /* Allow nodename to be null. */
753 hints.ai_flags |= AI_PASSIVE;
756 * In the case of binding to a wildcard address
757 * default to binding to an ipv4 address.
759 if (host == NULL && hints.ai_family == AF_UNSPEC)
760 hints.ai_family = AF_INET;
762 if ((error = getaddrinfo(host, port, &hints, &res)))
763 errx(1, "getaddrinfo: %s", gai_strerror(error));
767 if ((s = socket(res0->ai_family, res0->ai_socktype,
768 res0->ai_protocol)) < 0)
771 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
772 &rtableid, sizeof(rtableid)) == -1))
773 err(1, "setsockopt SO_SETFIB");
775 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
780 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
781 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
782 err(1, "disable TCP options");
785 set_common_sockopts(s, res0->ai_family);
787 if (bind(s, (struct sockaddr *)res0->ai_addr,
788 res0->ai_addrlen) == 0)
793 } while ((res0 = res0->ai_next) != NULL);
795 if (!uflag && s != -1) {
796 if (listen(s, 1) < 0)
807 * Loop that polls on the network file descriptor and stdin.
810 readwrite(int net_fd)
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;
820 int stats_printed = 0;
823 /* don't read from stdin if requested */
828 pfd[POLL_STDIN].fd = stdin_fd;
829 pfd[POLL_STDIN].events = POLLIN;
832 pfd[POLL_NETOUT].fd = net_fd;
833 pfd[POLL_NETOUT].events = 0;
836 pfd[POLL_NETIN].fd = net_fd;
837 pfd[POLL_NETIN].events = POLLIN;
840 pfd[POLL_STDOUT].fd = stdout_fd;
841 pfd[POLL_STDOUT].events = 0;
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);
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);
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);
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 */
875 num_fds = poll(pfd, 4, timeout);
877 /* treat poll errors */
880 err(1, "polling error");
883 /* timeout happened */
886 FreeBSD_stats_print(net_fd);
890 /* treat socket error conditions */
891 for (n = 0; n < 4; n++) {
892 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
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;
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;
907 if (pfd[POLL_NETOUT].revents & POLLHUP) {
909 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
910 pfd[POLL_NETOUT].fd = -1;
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;
925 /* try to read from stdin */
926 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
927 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
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 */
934 pfd[POLL_NETOUT].events = POLLOUT;
935 /* filled buffer - remove self from polling */
936 if (stdinbufpos == BUFSIZE)
937 pfd[POLL_STDIN].events = 0;
939 /* try to write to network */
940 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
941 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
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;
952 /* try to read from network */
953 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
954 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
957 pfd[POLL_NETIN].fd = -1;
958 /* eof on net in - remove from pfd */
960 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
961 pfd[POLL_NETIN].fd = -1;
963 /* read something - poll stdout */
965 pfd[POLL_STDOUT].events = POLLOUT;
966 /* filled buffer - remove self from polling */
967 if (netinbufpos == BUFSIZE)
968 pfd[POLL_NETIN].events = 0;
971 atelnet(pfd[POLL_NETIN].fd, netinbuf,
974 /* try to write to stdout */
975 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
976 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
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;
988 /* stdin gone and queue empty? */
989 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
990 if (pfd[POLL_NETOUT].fd != -1 && Nflag) {
992 FreeBSD_stats_print(net_fd);
995 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
997 pfd[POLL_NETOUT].fd = -1;
999 /* net in gone and queue empty? */
1000 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1001 pfd[POLL_STDOUT].fd = -1;
1007 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
1012 n = write(fd, buf, *bufpos);
1013 /* don't treat EAGAIN, EINTR as error */
1014 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1019 adjust = *bufpos - n;
1021 memmove(buf, buf + n, adjust);
1028 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1030 size_t num = BUFSIZE - *bufpos;
1033 n = read(fd, buf + *bufpos, num);
1034 /* don't treat EAGAIN, EINTR as error */
1035 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1045 * Pass the connected file descriptor to stdout and exit.
1053 char buf[CMSG_SPACE(sizeof(int))];
1055 struct cmsghdr *cmsg;
1061 /* Avoid obvious stupidity */
1062 if (isatty(STDOUT_FILENO))
1063 errx(1, "Cannot pass file descriptor to tty");
1065 bzero(&mh, sizeof(mh));
1066 bzero(&cmsgbuf, sizeof(cmsgbuf));
1067 bzero(&iov, sizeof(iov));
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;
1082 bzero(&pfd, sizeof(pfd));
1083 pfd.fd = STDOUT_FILENO;
1084 pfd.events = POLLOUT;
1086 r = sendmsg(STDOUT_FILENO, &mh, 0);
1088 if (errno == EAGAIN || errno == EINTR) {
1089 if (poll(&pfd, 1, -1) == -1)
1095 errx(1, "sendmsg: unexpected return value %zd", r);
1102 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1104 atelnet(int nfd, unsigned char *buf, unsigned int size)
1106 unsigned char *p, *end;
1107 unsigned char obuf[4];
1111 end = buf + size - 2;
1113 for (p = buf; p < end; p++) {
1119 if ((*p == WILL) || (*p == WONT))
1121 else if ((*p == DO) || (*p == DONT))
1128 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1129 warn("Write Error!");
1135 * Build an array of ports in portlist[], listing each port
1136 * that we should try to connect to.
1139 build_ports(char *p)
1146 if ((n = strchr(p, '-')) != NULL) {
1150 /* Make sure the ports are in order: lowest->highest. */
1151 hi = strtonum(n, 1, PORT_MAX, &errstr);
1153 errx(1, "port number %s: %s", errstr, n);
1154 lo = strtonum(p, 1, PORT_MAX, &errstr);
1156 errx(1, "port number %s: %s", errstr, p);
1164 /* Load ports sequentially. */
1165 for (cp = lo; cp <= hi; cp++) {
1166 portlist[x] = calloc(1, PORT_MAX_LEN);
1167 if (portlist[x] == NULL)
1169 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1173 /* Randomly swap ports. */
1178 for (x = 0; x <= (hi - lo); x++) {
1179 y = (arc4random() & 0xFFFF) % (hi - lo);
1181 portlist[x] = portlist[y];
1186 hi = strtonum(p, 1, PORT_MAX, &errstr);
1188 errx(1, "port number %s: %s", errstr, p);
1189 portlist[0] = strdup(p);
1190 if (portlist[0] == NULL)
1197 * Do a few writes to see if the UDP port is there.
1198 * Fails once PF state table is full.
1205 for (i = 0; i <= 3; i++) {
1206 if (write(s, "X", 1) == 1)
1215 FreeBSD_stats_setup(int s)
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\"?");
1224 err(1, "enable TCP_STATS gathering");
1229 FreeBSD_stats_print(int s)
1232 struct statsblob *statsb;
1234 socklen_t sockoptlen;
1238 * This usleep is a workaround for TCP_STATS reporting
1239 * incorrect values for TXPB.
1244 statsb = malloc(sockoptlen);
1247 error = getsockopt(s, IPPROTO_TCP, TCP_STATS, statsb, &sockoptlen);
1249 if (errno == EOVERFLOW && statsb->cursz > sockoptlen) {
1250 /* Retry with a larger size. */
1251 sockoptlen = statsb->cursz;
1252 statsb = realloc(statsb, sockoptlen);
1255 error = getsockopt(s, IPPROTO_TCP, TCP_STATS,
1256 statsb, &sockoptlen);
1259 err(1, "getsockopt");
1262 sb = sbuf_new_auto();
1263 error = stats_blob_tostr(statsb, sb, SB_STRFMT_JSON, SB_TOSTR_META);
1265 errc(1, error, "stats_blob_tostr");
1267 error = sbuf_finish(sb);
1269 err(1, "sbuf_finish");
1271 fprintf(stderr, "%s\n", sbuf_data(sb));
1276 set_common_sockopts(int s, int af)
1281 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1282 &x, sizeof(x)) == -1)
1286 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1287 &x, sizeof(x)) == -1)
1293 if (af == AF_INET6) {
1294 proto = IPPROTO_IPV6;
1295 option = IPV6_TCLASS;
1301 if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1302 err(1, "set IP ToS");
1305 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1306 &Iflag, sizeof(Iflag)) == -1)
1307 err(1, "set TCP receive buffer size");
1310 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1311 &Oflag, sizeof(Oflag)) == -1)
1312 err(1, "set TCP send buffer size");
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");
1320 FreeBSD_stats_setup(s);
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]);
1330 map_tos(char *s, int *val)
1332 /* DiffServ Codepoints and other TOS mappings */
1333 const struct toskeywords {
1334 const char *keyword;
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 },
1367 for (t = toskeywords; t->keyword != NULL; t++) {
1368 if (strcmp(s, t->keyword) == 0) {
1378 report_connect(const struct sockaddr *sa, socklen_t salen)
1380 char remote_host[NI_MAXHOST];
1381 char remote_port[NI_MAXSERV];
1383 int flags = NI_NUMERICSERV;
1386 flags |= NI_NUMERICHOST;
1388 if ((herr = getnameinfo(sa, salen,
1389 remote_host, sizeof(remote_host),
1390 remote_port, sizeof(remote_port),
1392 if (herr == EAI_SYSTEM)
1393 err(1, "getnameinfo");
1395 errx(1, "getnameinfo: %s", gai_strerror(herr));
1399 "Connection from %s %s "
1400 "received!\n", remote_host, remote_port);
1407 fprintf(stderr, "\tCommand Summary:\n\
1410 \t-D Enable the debug socket option\n\
1411 \t-d Detach from stdin\n");
1414 \t-E Use IPsec ESP\n\
1415 \t-e policy Use specified IPsec policy\n");
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\
1437 \t-V rtable Specify alternate routing table\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");
1445 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
1452 add_ipsec_policy(int s, int af, char *policy)
1457 raw = ipsec_set_policy(policy, strlen(policy));
1459 errx(1, "ipsec_set_policy `%s': %s", policy,
1462 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1463 ipsec_get_policylen(raw));
1465 e = setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, raw,
1466 ipsec_get_policylen(raw));
1468 err(1, "ipsec policy cannot be configured");
1471 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1481 "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1483 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
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");