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>.
36 #include <sys/limits.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/sysctl.h>
44 #include <netinet/in.h>
46 #include <netipsec/ipsec.h>
48 #include <netinet/tcp.h>
49 #include <netinet/ip.h>
50 #include <arpa/telnet.h>
69 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
72 #define PORT_MAX 65535
73 #define PORT_MAX_LEN 6
74 #define UNIX_DG_TMP_SOCKET_SIZE 19
82 /* Command Line Options */
83 int dflag; /* detached, no stdin */
84 int Fflag; /* fdpass sock to stdout */
85 unsigned int iflag; /* Interval Flag */
86 int kflag; /* More than one connect */
87 int lflag; /* Bind to local port */
88 int Nflag; /* shutdown() network socket */
89 int nflag; /* Don't do name look up */
90 int FreeBSD_Oflag; /* Do not use TCP options */
91 char *Pflag; /* Proxy username */
92 char *pflag; /* Localport flag */
93 int rflag; /* Random ports flag */
94 char *sflag; /* Source Address */
95 int tflag; /* Telnet Emulation */
96 int uflag; /* UDP - Default to TCP */
97 int vflag; /* Verbosity */
98 int xflag; /* Socks proxy */
99 int zflag; /* Port Scan Flag */
100 int Dflag; /* sodebug */
101 int Iflag; /* TCP receive buffer size */
102 int Oflag; /* TCP send buffer size */
103 int Sflag; /* TCP MD5 signature option */
104 int Tflag = -1; /* IP Type of Service */
108 int family = AF_UNSPEC;
109 char *portlist[PORT_MAX+1];
110 char *unix_dg_tmp_socket;
112 void atelnet(int, unsigned char *, unsigned int);
113 void build_ports(char *);
115 int local_listen(char *, char *, struct addrinfo);
117 void fdpass(int nfd) __attribute__((noreturn));
118 int remote_connect(const char *, const char *, struct addrinfo);
119 int timeout_connect(int, const struct sockaddr *, socklen_t);
120 int socks_connect(const char *, const char *, struct addrinfo,
121 const char *, const char *, struct addrinfo, int, const char *);
123 int unix_bind(char *);
124 int unix_connect(char *);
125 int unix_listen(char *);
126 void set_common_sockopts(int, int);
127 int map_tos(char *, int *);
128 void report_connect(const struct sockaddr *, socklen_t);
130 ssize_t drainbuf(int, unsigned char *, size_t *);
131 ssize_t fillbuf(int, unsigned char *, size_t *);
134 void add_ipsec_policy(int, char *);
136 char *ipsec_policy[2];
140 main(int argc, char *argv[])
142 int ch, s, ret, socksv, ipsec_count;
144 size_t intsize = sizeof(int);
146 struct addrinfo hints;
149 struct sockaddr_storage cliaddr;
151 const char *errstr, *proxyhost = "", *proxyport = NULL;
152 struct addrinfo proxyhints;
153 char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
154 struct option longopts[] = {
155 { "no-tcpopt", no_argument, &FreeBSD_Oflag, 1 },
167 signal(SIGPIPE, SIG_IGN);
169 while ((ch = getopt_long(argc, argv,
170 "46DdEe:FhI:i:klNnoO:P:p:rSs:tT:UuV:vw:X:x:z",
171 longopts, NULL)) != -1) {
183 if (strcasecmp(optarg, "connect") == 0)
184 socksv = -1; /* HTTP proxy CONNECT */
185 else if (strcmp(optarg, "4") == 0)
186 socksv = 4; /* SOCKS v.4 */
187 else if (strcmp(optarg, "5") == 0)
188 socksv = 5; /* SOCKS v.5 */
190 errx(1, "unsupported proxy protocol");
197 ipsec_policy[ipsec_count++ % 2] = optarg;
199 errx(1, "IPsec support unavailable.");
204 ipsec_policy[0] = "in ipsec esp/transport//require";
205 ipsec_policy[1] = "out ipsec esp/transport//require";
207 errx(1, "IPsec support unavailable.");
217 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
219 errx(1, "interval %s: %s", errstr, optarg);
234 fprintf(stderr, "option -o is deprecated.\n");
255 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
256 errx(1, "Multiple FIBS not supported");
257 rtableid = (int)strtonum(optarg, 0,
258 numfibs - 1, &errstr);
260 errx(1, "rtable %s: %s", errstr, optarg);
266 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
268 errx(1, "timeout %s: %s", errstr, optarg);
273 if ((proxy = strdup(optarg)) == NULL)
283 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
285 errx(1, "TCP receive window %s: %s",
289 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
290 if (errstr != NULL) {
291 if (strcmp(errstr, "invalid") != 0)
292 errx(1, "TCP send window %s: %s",
302 if (map_tos(optarg, &Tflag))
304 if (strlen(optarg) > 1 && optarg[0] == '0' &&
306 Tflag = (int)strtol(optarg, NULL, 16);
308 Tflag = (int)strtonum(optarg, 0, 255,
310 if (Tflag < 0 || Tflag > 255 || errstr || errno)
311 errx(1, "illegal tos value %s", optarg);
320 /* Cruft to make sure options are clean, and used properly. */
321 if (argv[0] && !argv[1] && family == AF_UNIX) {
324 } else if (argv[0] && !argv[1]) {
329 } else if (argv[0] && argv[1]) {
336 errx(1, "cannot use -s and -l");
338 errx(1, "cannot use -p and -l");
340 errx(1, "cannot use -z and -l");
342 errx(1, "must use -l with -k");
344 /* Get name of temporary socket for unix datagram client */
345 if ((family == AF_UNIX) && uflag && !lflag) {
347 unix_dg_tmp_socket = sflag;
349 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
350 UNIX_DG_TMP_SOCKET_SIZE);
351 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
353 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
357 /* Initialize addrinfo structure. */
358 if (family != AF_UNIX) {
359 memset(&hints, 0, sizeof(struct addrinfo));
360 hints.ai_family = family;
361 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
362 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
364 hints.ai_flags |= AI_NUMERICHOST;
369 errx(1, "no proxy support for UDP mode");
372 errx(1, "no proxy support for listen");
374 if (family == AF_UNIX)
375 errx(1, "no proxy support for unix sockets");
377 /* XXX IPv6 transport to proxy would probably work */
378 if (family == AF_INET6)
379 errx(1, "no proxy support for IPv6");
382 errx(1, "no proxy support for local source address");
384 proxyhost = strsep(&proxy, ":");
387 memset(&proxyhints, 0, sizeof(struct addrinfo));
388 proxyhints.ai_family = family;
389 proxyhints.ai_socktype = SOCK_STREAM;
390 proxyhints.ai_protocol = IPPROTO_TCP;
392 proxyhints.ai_flags |= AI_NUMERICHOST;
399 if (family == AF_UNIX) {
403 s = unix_listen(host);
406 /* Allow only one connection at a time, but stay alive. */
408 if (family != AF_UNIX)
409 s = local_listen(host, uport, hints);
413 * For UDP and -k, don't connect the socket, let it
414 * receive datagrams from multiple socket pairs.
419 * For UDP and not -k, we will use recvfrom() initially
420 * to wait for a caller, then use the regular functions
421 * to talk to the caller.
423 else if (uflag && !kflag) {
426 struct sockaddr_storage z;
430 rv = recvfrom(s, buf, plen, MSG_PEEK,
431 (struct sockaddr *)&z, &len);
435 rv = connect(s, (struct sockaddr *)&z, len);
440 report_connect((struct sockaddr *)&z, len);
444 len = sizeof(cliaddr);
445 connfd = accept(s, (struct sockaddr *)&cliaddr,
448 /* For now, all errnos are fatal */
452 report_connect((struct sockaddr *)&cliaddr, len);
458 if (family != AF_UNIX)
461 if (connect(s, NULL, 0) < 0)
468 } else if (family == AF_UNIX) {
471 if ((s = unix_connect(host)) > 0 && !zflag) {
478 unlink(unix_dg_tmp_socket);
484 /* Construct the portlist[] array. */
487 /* Cycle through portlist, connecting to each port. */
488 for (i = 0; portlist[i] != NULL; i++) {
493 s = socks_connect(host, portlist[i], hints,
494 proxyhost, proxyport, proxyhints, socksv,
497 s = remote_connect(host, portlist[i], hints);
503 if (vflag || zflag) {
504 /* For UDP, make sure we are connected. */
506 if (udptest(s) == -1) {
512 /* Don't look up port if -n. */
517 ntohs(atoi(portlist[i])),
518 uflag ? "udp" : "tcp");
522 "Connection to %s %s port [%s/%s] "
523 "succeeded!\n", host, portlist[i],
524 uflag ? "udp" : "tcp",
525 sv ? sv->s_name : "*");
542 * Returns a unix socket bound to the given path
545 unix_bind(char *path)
547 struct sockaddr_un sun;
550 /* Create unix domain socket. */
551 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
555 memset(&sun, 0, sizeof(struct sockaddr_un));
556 sun.sun_family = AF_UNIX;
558 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
559 sizeof(sun.sun_path)) {
561 errno = ENAMETOOLONG;
565 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
574 * Returns a socket connected to a local unix socket. Returns -1 on failure.
577 unix_connect(char *path)
579 struct sockaddr_un sun;
583 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
586 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
589 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
591 memset(&sun, 0, sizeof(struct sockaddr_un));
592 sun.sun_family = AF_UNIX;
594 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
595 sizeof(sun.sun_path)) {
597 errno = ENAMETOOLONG;
600 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
610 * Create a unix domain socket, and listen on it.
613 unix_listen(char *path)
616 if ((s = unix_bind(path)) < 0)
619 if (listen(s, 5) < 0) {
628 * Returns a socket connected to a remote host. Properly binds to a local
629 * port or source address if needed. Returns -1 on failure.
632 remote_connect(const char *host, const char *port, struct addrinfo hints)
634 struct addrinfo *res, *res0;
635 int s, error, on = 1;
637 if ((error = getaddrinfo(host, port, &hints, &res)))
638 errx(1, "getaddrinfo: %s", gai_strerror(error));
642 if ((s = socket(res0->ai_family, res0->ai_socktype,
643 res0->ai_protocol)) < 0)
646 if (ipsec_policy[0] != NULL)
647 add_ipsec_policy(s, ipsec_policy[0]);
648 if (ipsec_policy[1] != NULL)
649 add_ipsec_policy(s, ipsec_policy[1]);
652 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
653 &rtableid, sizeof(rtableid)) == -1))
654 err(1, "setsockopt SO_SETFIB");
656 /* Bind to a local port or source address if specified. */
657 if (sflag || pflag) {
658 struct addrinfo ahints, *ares;
660 /* try IP_BINDANY, but don't insist */
661 setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
662 memset(&ahints, 0, sizeof(struct addrinfo));
663 ahints.ai_family = res0->ai_family;
664 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
665 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
666 ahints.ai_flags = AI_PASSIVE;
667 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
668 errx(1, "getaddrinfo: %s", gai_strerror(error));
670 if (bind(s, (struct sockaddr *)ares->ai_addr,
671 ares->ai_addrlen) < 0)
672 err(1, "bind failed");
676 set_common_sockopts(s, res0->ai_family);
678 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
681 warn("connect to %s port %s (%s) failed", host, port,
682 uflag ? "udp" : "tcp");
686 } while ((res0 = res0->ai_next) != NULL);
694 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
702 flags = fcntl(s, F_GETFL, 0);
703 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
704 err(1, "set non-blocking mode");
707 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
709 pfd.events = POLLOUT;
710 if ((ret = poll(&pfd, 1, timeout)) == 1) {
711 optlen = sizeof(optval);
712 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
713 &optval, &optlen)) == 0) {
715 ret = optval == 0 ? 0 : -1;
717 } else if (ret == 0) {
721 err(1, "poll failed");
724 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
725 err(1, "restoring flags");
732 * Returns a socket listening on a local port, binds to specified source
733 * address. Returns -1 on failure.
736 local_listen(char *host, char *port, struct addrinfo hints)
738 struct addrinfo *res, *res0;
742 /* Allow nodename to be null. */
743 hints.ai_flags |= AI_PASSIVE;
746 * In the case of binding to a wildcard address
747 * default to binding to an ipv4 address.
749 if (host == NULL && hints.ai_family == AF_UNSPEC)
750 hints.ai_family = AF_INET;
752 if ((error = getaddrinfo(host, port, &hints, &res)))
753 errx(1, "getaddrinfo: %s", gai_strerror(error));
757 if ((s = socket(res0->ai_family, res0->ai_socktype,
758 res0->ai_protocol)) < 0)
761 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
762 &rtableid, sizeof(rtableid)) == -1))
763 err(1, "setsockopt SO_SETFIB");
765 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
769 if (ipsec_policy[0] != NULL)
770 add_ipsec_policy(s, ipsec_policy[0]);
771 if (ipsec_policy[1] != NULL)
772 add_ipsec_policy(s, ipsec_policy[1]);
775 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
776 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
777 err(1, "disable TCP options");
780 set_common_sockopts(s, res0->ai_family);
782 if (bind(s, (struct sockaddr *)res0->ai_addr,
783 res0->ai_addrlen) == 0)
788 } while ((res0 = res0->ai_next) != NULL);
790 if (!uflag && s != -1) {
791 if (listen(s, 1) < 0)
802 * Loop that polls on the network file descriptor and stdin.
805 readwrite(int net_fd)
807 struct pollfd pfd[4];
808 int stdin_fd = STDIN_FILENO;
809 int stdout_fd = STDOUT_FILENO;
810 unsigned char netinbuf[BUFSIZE];
811 size_t netinbufpos = 0;
812 unsigned char stdinbuf[BUFSIZE];
813 size_t stdinbufpos = 0;
817 /* don't read from stdin if requested */
822 pfd[POLL_STDIN].fd = stdin_fd;
823 pfd[POLL_STDIN].events = POLLIN;
826 pfd[POLL_NETOUT].fd = net_fd;
827 pfd[POLL_NETOUT].events = 0;
830 pfd[POLL_NETIN].fd = net_fd;
831 pfd[POLL_NETIN].events = POLLIN;
834 pfd[POLL_STDOUT].fd = stdout_fd;
835 pfd[POLL_STDOUT].events = 0;
838 /* both inputs are gone, buffers are empty, we are done */
839 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
840 && stdinbufpos == 0 && netinbufpos == 0) {
844 /* both outputs are gone, we can't continue */
845 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
849 /* listen and net in gone, queues empty, done */
850 if (lflag && pfd[POLL_NETIN].fd == -1
851 && stdinbufpos == 0 && netinbufpos == 0) {
856 /* help says -i is for "wait between lines sent". We read and
857 * write arbitrary amounts of data, and we don't want to start
858 * scanning for newlines, so this is as good as it gets */
863 num_fds = poll(pfd, 4, timeout);
865 /* treat poll errors */
868 err(1, "polling error");
871 /* timeout happened */
875 /* treat socket error conditions */
876 for (n = 0; n < 4; n++) {
877 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
881 /* reading is possible after HUP */
882 if (pfd[POLL_STDIN].events & POLLIN &&
883 pfd[POLL_STDIN].revents & POLLHUP &&
884 ! (pfd[POLL_STDIN].revents & POLLIN))
885 pfd[POLL_STDIN].fd = -1;
887 if (pfd[POLL_NETIN].events & POLLIN &&
888 pfd[POLL_NETIN].revents & POLLHUP &&
889 ! (pfd[POLL_NETIN].revents & POLLIN))
890 pfd[POLL_NETIN].fd = -1;
892 if (pfd[POLL_NETOUT].revents & POLLHUP) {
894 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
895 pfd[POLL_NETOUT].fd = -1;
897 /* if HUP, stop watching stdout */
898 if (pfd[POLL_STDOUT].revents & POLLHUP)
899 pfd[POLL_STDOUT].fd = -1;
900 /* if no net out, stop watching stdin */
901 if (pfd[POLL_NETOUT].fd == -1)
902 pfd[POLL_STDIN].fd = -1;
903 /* if no stdout, stop watching net in */
904 if (pfd[POLL_STDOUT].fd == -1) {
905 if (pfd[POLL_NETIN].fd != -1)
906 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
907 pfd[POLL_NETIN].fd = -1;
910 /* try to read from stdin */
911 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
912 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
914 /* error or eof on stdin - remove from pfd */
915 if (ret == 0 || ret == -1)
916 pfd[POLL_STDIN].fd = -1;
917 /* read something - poll net out */
919 pfd[POLL_NETOUT].events = POLLOUT;
920 /* filled buffer - remove self from polling */
921 if (stdinbufpos == BUFSIZE)
922 pfd[POLL_STDIN].events = 0;
924 /* try to write to network */
925 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
926 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
929 pfd[POLL_NETOUT].fd = -1;
930 /* buffer empty - remove self from polling */
931 if (stdinbufpos == 0)
932 pfd[POLL_NETOUT].events = 0;
933 /* buffer no longer full - poll stdin again */
934 if (stdinbufpos < BUFSIZE)
935 pfd[POLL_STDIN].events = POLLIN;
937 /* try to read from network */
938 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
939 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
942 pfd[POLL_NETIN].fd = -1;
943 /* eof on net in - remove from pfd */
945 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
946 pfd[POLL_NETIN].fd = -1;
948 /* read something - poll stdout */
950 pfd[POLL_STDOUT].events = POLLOUT;
951 /* filled buffer - remove self from polling */
952 if (netinbufpos == BUFSIZE)
953 pfd[POLL_NETIN].events = 0;
956 atelnet(pfd[POLL_NETIN].fd, netinbuf,
959 /* try to write to stdout */
960 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
961 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
964 pfd[POLL_STDOUT].fd = -1;
965 /* buffer empty - remove self from polling */
966 if (netinbufpos == 0)
967 pfd[POLL_STDOUT].events = 0;
968 /* buffer no longer full - poll net in again */
969 if (netinbufpos < BUFSIZE)
970 pfd[POLL_NETIN].events = POLLIN;
973 /* stdin gone and queue empty? */
974 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
975 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
976 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
977 pfd[POLL_NETOUT].fd = -1;
979 /* net in gone and queue empty? */
980 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
981 pfd[POLL_STDOUT].fd = -1;
987 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
992 n = write(fd, buf, *bufpos);
993 /* don't treat EAGAIN, EINTR as error */
994 if (n == -1 && (errno == EAGAIN || errno == EINTR))
999 adjust = *bufpos - n;
1001 memmove(buf, buf + n, adjust);
1008 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1010 size_t num = BUFSIZE - *bufpos;
1013 n = read(fd, buf + *bufpos, num);
1014 /* don't treat EAGAIN, EINTR as error */
1015 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1025 * Pass the connected file descriptor to stdout and exit.
1033 char buf[CMSG_SPACE(sizeof(int))];
1035 struct cmsghdr *cmsg;
1041 /* Avoid obvious stupidity */
1042 if (isatty(STDOUT_FILENO))
1043 errx(1, "Cannot pass file descriptor to tty");
1045 bzero(&mh, sizeof(mh));
1046 bzero(&cmsgbuf, sizeof(cmsgbuf));
1047 bzero(&iov, sizeof(iov));
1049 mh.msg_control = (caddr_t)&cmsgbuf.buf;
1050 mh.msg_controllen = sizeof(cmsgbuf.buf);
1051 cmsg = CMSG_FIRSTHDR(&mh);
1052 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1053 cmsg->cmsg_level = SOL_SOCKET;
1054 cmsg->cmsg_type = SCM_RIGHTS;
1055 *(int *)CMSG_DATA(cmsg) = nfd;
1062 bzero(&pfd, sizeof(pfd));
1063 pfd.fd = STDOUT_FILENO;
1064 pfd.events = POLLOUT;
1066 r = sendmsg(STDOUT_FILENO, &mh, 0);
1068 if (errno == EAGAIN || errno == EINTR) {
1069 if (poll(&pfd, 1, -1) == -1)
1075 errx(1, "sendmsg: unexpected return value %zd", r);
1082 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1084 atelnet(int nfd, unsigned char *buf, unsigned int size)
1086 unsigned char *p, *end;
1087 unsigned char obuf[4];
1091 end = buf + size - 2;
1093 for (p = buf; p < end; p++) {
1099 if ((*p == WILL) || (*p == WONT))
1101 else if ((*p == DO) || (*p == DONT))
1108 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1109 warn("Write Error!");
1115 * Build an array of ports in portlist[], listing each port
1116 * that we should try to connect to.
1119 build_ports(char *p)
1126 if ((n = strchr(p, '-')) != NULL) {
1130 /* Make sure the ports are in order: lowest->highest. */
1131 hi = strtonum(n, 1, PORT_MAX, &errstr);
1133 errx(1, "port number %s: %s", errstr, n);
1134 lo = strtonum(p, 1, PORT_MAX, &errstr);
1136 errx(1, "port number %s: %s", errstr, p);
1144 /* Load ports sequentially. */
1145 for (cp = lo; cp <= hi; cp++) {
1146 portlist[x] = calloc(1, PORT_MAX_LEN);
1147 if (portlist[x] == NULL)
1149 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1153 /* Randomly swap ports. */
1158 for (x = 0; x <= (hi - lo); x++) {
1159 y = (arc4random() & 0xFFFF) % (hi - lo);
1161 portlist[x] = portlist[y];
1166 hi = strtonum(p, 1, PORT_MAX, &errstr);
1168 errx(1, "port number %s: %s", errstr, p);
1169 portlist[0] = strdup(p);
1170 if (portlist[0] == NULL)
1177 * Do a few writes to see if the UDP port is there.
1178 * Fails once PF state table is full.
1185 for (i = 0; i <= 3; i++) {
1186 if (write(s, "X", 1) == 1)
1195 set_common_sockopts(int s, int af)
1200 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1201 &x, sizeof(x)) == -1)
1205 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1206 &x, sizeof(x)) == -1)
1212 if (af == AF_INET6) {
1213 proto = IPPROTO_IPV6;
1214 option = IPV6_TCLASS;
1220 if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1221 err(1, "set IP ToS");
1224 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1225 &Iflag, sizeof(Iflag)) == -1)
1226 err(1, "set TCP receive buffer size");
1229 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1230 &Oflag, sizeof(Oflag)) == -1)
1231 err(1, "set TCP send buffer size");
1233 if (FreeBSD_Oflag) {
1234 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
1235 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
1236 err(1, "disable TCP options");
1241 map_tos(char *s, int *val)
1243 /* DiffServ Codepoints and other TOS mappings */
1244 const struct toskeywords {
1245 const char *keyword;
1247 } *t, toskeywords[] = {
1248 { "af11", IPTOS_DSCP_AF11 },
1249 { "af12", IPTOS_DSCP_AF12 },
1250 { "af13", IPTOS_DSCP_AF13 },
1251 { "af21", IPTOS_DSCP_AF21 },
1252 { "af22", IPTOS_DSCP_AF22 },
1253 { "af23", IPTOS_DSCP_AF23 },
1254 { "af31", IPTOS_DSCP_AF31 },
1255 { "af32", IPTOS_DSCP_AF32 },
1256 { "af33", IPTOS_DSCP_AF33 },
1257 { "af41", IPTOS_DSCP_AF41 },
1258 { "af42", IPTOS_DSCP_AF42 },
1259 { "af43", IPTOS_DSCP_AF43 },
1260 { "critical", IPTOS_PREC_CRITIC_ECP },
1261 { "cs0", IPTOS_DSCP_CS0 },
1262 { "cs1", IPTOS_DSCP_CS1 },
1263 { "cs2", IPTOS_DSCP_CS2 },
1264 { "cs3", IPTOS_DSCP_CS3 },
1265 { "cs4", IPTOS_DSCP_CS4 },
1266 { "cs5", IPTOS_DSCP_CS5 },
1267 { "cs6", IPTOS_DSCP_CS6 },
1268 { "cs7", IPTOS_DSCP_CS7 },
1269 { "ef", IPTOS_DSCP_EF },
1270 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1271 { "lowdelay", IPTOS_LOWDELAY },
1272 { "netcontrol", IPTOS_PREC_NETCONTROL },
1273 { "reliability", IPTOS_RELIABILITY },
1274 { "throughput", IPTOS_THROUGHPUT },
1278 for (t = toskeywords; t->keyword != NULL; t++) {
1279 if (strcmp(s, t->keyword) == 0) {
1289 report_connect(const struct sockaddr *sa, socklen_t salen)
1291 char remote_host[NI_MAXHOST];
1292 char remote_port[NI_MAXSERV];
1294 int flags = NI_NUMERICSERV;
1297 flags |= NI_NUMERICHOST;
1299 if ((herr = getnameinfo(sa, salen,
1300 remote_host, sizeof(remote_host),
1301 remote_port, sizeof(remote_port),
1303 if (herr == EAI_SYSTEM)
1304 err(1, "getnameinfo");
1306 errx(1, "getnameinfo: %s", gai_strerror(herr));
1310 "Connection from %s %s "
1311 "received!\n", remote_host, remote_port);
1318 fprintf(stderr, "\tCommand Summary:\n\
1321 \t-D Enable the debug socket option\n\
1322 \t-d Detach from stdin\n");
1325 \t-E Use IPsec ESP\n\
1326 \t-e policy Use specified IPsec policy\n");
1329 \t-F Pass socket fd\n\
1330 \t-h This help text\n\
1331 \t-I length TCP receive buffer length\n\
1332 \t-i secs\t Delay interval for lines sent, ports scanned\n\
1333 \t-k Keep inbound sockets open for multiple connects\n\
1334 \t-l Listen mode, for inbound connects\n\
1335 \t-N Shutdown the network socket after EOF on stdin\n\
1336 \t-n Suppress name/port resolutions\n\
1337 \t--no-tcpopt Disable TCP options\n\
1338 \t-O length TCP send buffer length\n\
1339 \t-P proxyuser\tUsername for proxy authentication\n\
1340 \t-p port\t Specify local port for remote connects\n\
1341 \t-r Randomize remote ports\n\
1342 \t-S Enable the TCP MD5 signature option\n\
1343 \t-s addr\t Local source address\n\
1344 \t-T toskeyword\tSet IP Type of Service\n\
1345 \t-t Answer TELNET negotiation\n\
1346 \t-U Use UNIX domain socket\n\
1348 \t-V rtable Specify alternate routing table\n\
1350 \t-w secs\t Timeout for connects and final net reads\n\
1351 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1352 \t-x addr[:port]\tSpecify proxy address and port\n\
1353 \t-z Zero-I/O mode [used for scanning]\n\
1354 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1356 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
1363 add_ipsec_policy(int s, char *policy)
1368 raw = ipsec_set_policy(policy, strlen(policy));
1370 errx(1, "ipsec_set_policy `%s': %s", policy,
1372 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1373 ipsec_get_policylen(raw));
1375 err(1, "ipsec policy cannot be configured");
1378 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1388 "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1390 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1392 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1393 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1394 "\t [-x proxy_address[:port]] [destination] [port]\n");