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 int FreeBSD_sctp; /* Use SCTP */
97 int FreeBSD_crlf; /* Convert LF to CRLF */
98 char *Pflag; /* Proxy username */
99 char *pflag; /* Localport flag */
100 int rflag; /* Random ports flag */
101 char *sflag; /* Source Address */
102 int tflag; /* Telnet Emulation */
103 int uflag; /* UDP - Default to TCP */
104 int vflag; /* Verbosity */
105 int xflag; /* Socks proxy */
106 int zflag; /* Port Scan Flag */
107 int Dflag; /* sodebug */
108 int Iflag; /* TCP receive buffer size */
109 int Oflag; /* TCP send buffer size */
110 int Sflag; /* TCP MD5 signature option */
111 int Tflag = -1; /* IP Type of Service */
115 int family = AF_UNSPEC;
117 char *portlist[PORT_MAX+1];
118 char *unix_dg_tmp_socket;
120 void atelnet(int, unsigned char *, unsigned int);
121 void build_ports(char *);
123 int local_listen(char *, char *, struct addrinfo);
125 void fdpass(int nfd) __attribute__((noreturn));
126 int remote_connect(const char *, const char *, struct addrinfo);
127 int timeout_connect(int, const struct sockaddr *, socklen_t);
128 int socks_connect(const char *, const char *, struct addrinfo,
129 const char *, const char *, struct addrinfo, int, const char *);
131 int unix_bind(char *);
132 int unix_connect(char *);
133 int unix_listen(char *);
134 void FreeBSD_stats_setup(int);
135 void FreeBSD_stats_print(int);
136 void set_common_sockopts(int, int);
137 int map_tos(char *, int *);
138 void report_connect(const struct sockaddr *, socklen_t);
140 ssize_t write_wrapper(int, const void *, size_t);
141 ssize_t drainbuf(int, unsigned char *, size_t *, int);
142 ssize_t fillbuf(int, unsigned char *, size_t *);
145 void add_ipsec_policy(int, int, char *);
147 char *ipsec_policy[2];
151 FREEBSD_TUN = CHAR_MAX, /* avoid collision with return values from getopt */
155 main(int argc, char *argv[])
157 int ch, s, ret, socksv, ipsec_count;
159 size_t intsize = sizeof(int);
161 struct addrinfo hints;
164 struct sockaddr_storage cliaddr;
166 const char *errstr, *proxyhost = "", *proxyport = NULL, *tundev = NULL;
167 struct addrinfo proxyhints;
168 char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
169 struct option longopts[] = {
170 { "crlf", no_argument, &FreeBSD_crlf, 1 },
171 { "no-tcpopt", no_argument, &FreeBSD_Oflag, 1 },
172 { "sctp", no_argument, &FreeBSD_sctp, 1 },
173 { "tun", required_argument, NULL, FREEBSD_TUN },
185 signal(SIGPIPE, SIG_IGN);
187 while ((ch = getopt_long(argc, argv,
188 "46DdEe:FhI:i:klMNnoO:P:p:rSs:tT:UuV:vw:X:x:z",
189 longopts, NULL)) != -1) {
201 if (strcasecmp(optarg, "connect") == 0)
202 socksv = -1; /* HTTP proxy CONNECT */
203 else if (strcmp(optarg, "4") == 0)
204 socksv = 4; /* SOCKS v.4 */
205 else if (strcmp(optarg, "5") == 0)
206 socksv = 5; /* SOCKS v.5 */
208 errx(1, "unsupported proxy protocol");
215 ipsec_policy[ipsec_count++ % 2] = optarg;
217 errx(1, "IPsec support unavailable.");
222 ipsec_policy[0] = "in ipsec esp/transport//require";
223 ipsec_policy[1] = "out ipsec esp/transport//require";
225 errx(1, "IPsec support unavailable.");
235 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
237 errx(1, "interval %s: %s", errstr, optarg);
247 errx(1, "-M requires stats(3) support");
259 fprintf(stderr, "option -o is deprecated.\n");
280 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
281 errx(1, "Multiple FIBS not supported");
282 rtableid = (int)strtonum(optarg, 0,
283 numfibs - 1, &errstr);
285 errx(1, "rtable %s: %s", errstr, optarg);
291 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
293 errx(1, "timeout %s: %s", errstr, optarg);
298 if ((proxy = strdup(optarg)) == NULL)
308 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
310 errx(1, "TCP receive window %s: %s",
314 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
315 if (errstr != NULL) {
316 if (strcmp(errstr, "invalid") != 0)
317 errx(1, "TCP send window %s: %s",
327 if (map_tos(optarg, &Tflag))
329 if (strlen(optarg) > 1 && optarg[0] == '0' &&
331 Tflag = (int)strtol(optarg, NULL, 16);
333 Tflag = (int)strtonum(optarg, 0, 255,
335 if (Tflag < 0 || Tflag > 255 || errstr || errno)
336 errx(1, "illegal tos value %s", optarg);
351 /* Cruft to make sure options are clean, and used properly. */
352 if (argv[0] && !argv[1] && family == AF_UNIX) {
355 } else if (argv[0] && !argv[1]) {
360 } else if (argv[0] && argv[1]) {
367 errx(1, "cannot use -s and -l");
369 errx(1, "cannot use -p and -l");
371 errx(1, "cannot use -z and -l");
373 errx(1, "must use -l with -k");
376 errx(1, "cannot use -u and --sctp");
377 if (family == AF_UNIX)
378 errx(1, "cannot use -U and --sctp");
380 if (tundev != NULL) {
382 errx(1, "must use --tun with -u");
383 tun_fd = open(tundev, O_RDWR);
385 errx(1, "unable to open tun device %s", tundev);
388 /* Get name of temporary socket for unix datagram client */
389 if ((family == AF_UNIX) && uflag && !lflag) {
391 unix_dg_tmp_socket = sflag;
393 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
394 UNIX_DG_TMP_SOCKET_SIZE);
395 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
397 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
401 /* Initialize addrinfo structure. */
402 if (family != AF_UNIX) {
403 memset(&hints, 0, sizeof(struct addrinfo));
404 hints.ai_family = family;
405 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
406 hints.ai_protocol = uflag ? IPPROTO_UDP :
407 FreeBSD_sctp ? IPPROTO_SCTP : IPPROTO_TCP;
409 hints.ai_flags |= AI_NUMERICHOST;
414 errx(1, "no proxy support for UDP mode");
417 errx(1, "no proxy support for SCTP mode");
420 errx(1, "no proxy support for listen");
422 if (family == AF_UNIX)
423 errx(1, "no proxy support for unix sockets");
425 /* XXX IPv6 transport to proxy would probably work */
426 if (family == AF_INET6)
427 errx(1, "no proxy support for IPv6");
430 errx(1, "no proxy support for local source address");
432 proxyhost = strsep(&proxy, ":");
435 memset(&proxyhints, 0, sizeof(struct addrinfo));
436 proxyhints.ai_family = family;
437 proxyhints.ai_socktype = SOCK_STREAM;
438 proxyhints.ai_protocol = IPPROTO_TCP;
440 proxyhints.ai_flags |= AI_NUMERICHOST;
447 if (family == AF_UNIX) {
451 s = unix_listen(host);
454 /* Allow only one connection at a time, but stay alive. */
456 if (family != AF_UNIX)
457 s = local_listen(host, uport, hints);
461 * For UDP and -k, don't connect the socket, let it
462 * receive datagrams from multiple socket pairs.
467 * For UDP and not -k, we will use recvfrom() initially
468 * to wait for a caller, then use the regular functions
469 * to talk to the caller.
471 else if (uflag && !kflag) {
474 struct sockaddr_storage z;
478 rv = recvfrom(s, buf, plen, MSG_PEEK,
479 (struct sockaddr *)&z, &len);
483 rv = connect(s, (struct sockaddr *)&z, len);
488 report_connect((struct sockaddr *)&z, len);
492 len = sizeof(cliaddr);
493 connfd = accept(s, (struct sockaddr *)&cliaddr,
496 /* For now, all errnos are fatal */
500 report_connect((struct sockaddr *)&cliaddr, len);
503 FreeBSD_stats_setup(connfd);
508 if (family != AF_UNIX)
511 if (connect(s, NULL, 0) < 0)
518 } else if (family == AF_UNIX) {
521 if ((s = unix_connect(host)) > 0 && !zflag) {
528 unlink(unix_dg_tmp_socket);
534 /* Construct the portlist[] array. */
537 /* Cycle through portlist, connecting to each port. */
538 for (i = 0; portlist[i] != NULL; i++) {
543 s = socks_connect(host, portlist[i], hints,
544 proxyhost, proxyport, proxyhints, socksv,
547 s = remote_connect(host, portlist[i], hints);
553 if (vflag || zflag) {
554 /* For UDP, make sure we are connected. */
556 if (udptest(s) == -1) {
562 /* Don't look up port if -n. */
567 ntohs(atoi(portlist[i])),
568 uflag ? "udp" : "tcp");
572 "Connection to %s %s port [%s/%s] "
573 "succeeded!\n", host, portlist[i],
574 uflag ? "udp" : "tcp",
575 sv ? sv->s_name : "*");
594 * Returns a unix socket bound to the given path
597 unix_bind(char *path)
599 struct sockaddr_un sun;
602 /* Create unix domain socket. */
603 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
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;
617 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
626 * Returns a socket connected to a local unix socket. Returns -1 on failure.
629 unix_connect(char *path)
631 struct sockaddr_un sun;
635 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
638 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
641 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
643 memset(&sun, 0, sizeof(struct sockaddr_un));
644 sun.sun_family = AF_UNIX;
646 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
647 sizeof(sun.sun_path)) {
649 errno = ENAMETOOLONG;
652 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
662 * Create a unix domain socket, and listen on it.
665 unix_listen(char *path)
668 if ((s = unix_bind(path)) < 0)
671 if (listen(s, 5) < 0) {
680 * Returns a socket connected to a remote host. Properly binds to a local
681 * port or source address if needed. Returns -1 on failure.
684 remote_connect(const char *host, const char *port, struct addrinfo hints)
686 struct addrinfo *res, *res0;
687 int s, error, on = 1;
689 if ((error = getaddrinfo(host, port, &hints, &res)))
690 errx(1, "getaddrinfo: %s", gai_strerror(error));
694 if ((s = socket(res0->ai_family, res0->ai_socktype,
695 res0->ai_protocol)) < 0)
698 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
699 &rtableid, sizeof(rtableid)) == -1))
700 err(1, "setsockopt SO_SETFIB");
702 /* Bind to a local port or source address if specified. */
703 if (sflag || pflag) {
704 struct addrinfo ahints, *ares;
706 /* try IP_BINDANY, but don't insist */
707 setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
708 memset(&ahints, 0, sizeof(struct addrinfo));
709 ahints.ai_family = res0->ai_family;
710 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
711 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
712 ahints.ai_flags = AI_PASSIVE;
713 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
714 errx(1, "getaddrinfo: %s", gai_strerror(error));
716 if (bind(s, (struct sockaddr *)ares->ai_addr,
717 ares->ai_addrlen) < 0)
718 err(1, "bind failed");
722 set_common_sockopts(s, res0->ai_family);
724 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
727 warn("connect to %s port %s (%s) failed", host, port,
728 uflag ? "udp" : "tcp");
732 } while ((res0 = res0->ai_next) != NULL);
740 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
748 flags = fcntl(s, F_GETFL, 0);
749 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
750 err(1, "set non-blocking mode");
753 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
755 pfd.events = POLLOUT;
756 if ((ret = poll(&pfd, 1, timeout)) == 1) {
757 optlen = sizeof(optval);
758 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
759 &optval, &optlen)) == 0) {
761 ret = optval == 0 ? 0 : -1;
763 } else if (ret == 0) {
767 err(1, "poll failed");
770 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
771 err(1, "restoring flags");
778 * Returns a socket listening on a local port, binds to specified source
779 * address. Returns -1 on failure.
782 local_listen(char *host, char *port, struct addrinfo hints)
784 struct addrinfo *res, *res0;
788 /* Allow nodename to be null. */
789 hints.ai_flags |= AI_PASSIVE;
792 * In the case of binding to a wildcard address
793 * default to binding to an ipv4 address.
795 if (host == NULL && hints.ai_family == AF_UNSPEC)
796 hints.ai_family = AF_INET;
798 if ((error = getaddrinfo(host, port, &hints, &res)))
799 errx(1, "getaddrinfo: %s", gai_strerror(error));
803 if ((s = socket(res0->ai_family, res0->ai_socktype,
804 res0->ai_protocol)) < 0)
807 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
808 &rtableid, sizeof(rtableid)) == -1))
809 err(1, "setsockopt SO_SETFIB");
811 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
816 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
817 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
818 err(1, "disable TCP options");
821 set_common_sockopts(s, res0->ai_family);
823 if (bind(s, (struct sockaddr *)res0->ai_addr,
824 res0->ai_addrlen) == 0)
829 } while ((res0 = res0->ai_next) != NULL);
831 if (!uflag && s != -1) {
832 if (listen(s, 1) < 0)
843 * Loop that polls on the network file descriptor and stdin.
846 readwrite(int net_fd)
848 struct pollfd pfd[4];
849 int stdin_fd = STDIN_FILENO;
850 int stdout_fd = STDOUT_FILENO;
851 unsigned char netinbuf[BUFSIZE];
852 size_t netinbufpos = 0;
853 unsigned char stdinbuf[BUFSIZE];
854 size_t stdinbufpos = 0;
856 int stats_printed = 0;
859 /* don't read from stdin if requested */
864 pfd[POLL_STDIN].fd = (tun_fd != -1) ? tun_fd : stdin_fd;
865 pfd[POLL_STDIN].events = POLLIN;
868 pfd[POLL_NETOUT].fd = net_fd;
869 pfd[POLL_NETOUT].events = 0;
872 pfd[POLL_NETIN].fd = net_fd;
873 pfd[POLL_NETIN].events = POLLIN;
876 pfd[POLL_STDOUT].fd = (tun_fd != -1) ? tun_fd : stdout_fd;
877 pfd[POLL_STDOUT].events = 0;
880 /* both inputs are gone, buffers are empty, we are done */
881 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
882 && stdinbufpos == 0 && netinbufpos == 0) {
883 if (FreeBSD_Mflag && !stats_printed)
884 FreeBSD_stats_print(net_fd);
888 /* both outputs are gone, we can't continue */
889 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
890 if (FreeBSD_Mflag && !stats_printed)
891 FreeBSD_stats_print(net_fd);
895 /* listen and net in gone, queues empty, done */
896 if (lflag && pfd[POLL_NETIN].fd == -1
897 && stdinbufpos == 0 && netinbufpos == 0) {
898 if (FreeBSD_Mflag && !stats_printed)
899 FreeBSD_stats_print(net_fd);
904 /* help says -i is for "wait between lines sent". We read and
905 * write arbitrary amounts of data, and we don't want to start
906 * scanning for newlines, so this is as good as it gets */
911 num_fds = poll(pfd, 4, timeout);
913 /* treat poll errors */
916 err(1, "polling error");
919 /* timeout happened */
922 FreeBSD_stats_print(net_fd);
926 /* treat socket error conditions */
927 for (n = 0; n < 4; n++) {
928 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
932 /* reading is possible after HUP */
933 if (pfd[POLL_STDIN].events & POLLIN &&
934 pfd[POLL_STDIN].revents & POLLHUP &&
935 ! (pfd[POLL_STDIN].revents & POLLIN))
936 pfd[POLL_STDIN].fd = -1;
938 if (pfd[POLL_NETIN].events & POLLIN &&
939 pfd[POLL_NETIN].revents & POLLHUP &&
940 ! (pfd[POLL_NETIN].revents & POLLIN))
941 pfd[POLL_NETIN].fd = -1;
943 if (pfd[POLL_NETOUT].revents & POLLHUP) {
945 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
946 pfd[POLL_NETOUT].fd = -1;
948 /* if HUP, stop watching stdout */
949 if (pfd[POLL_STDOUT].revents & POLLHUP)
950 pfd[POLL_STDOUT].fd = -1;
951 /* if no net out, stop watching stdin */
952 if (pfd[POLL_NETOUT].fd == -1)
953 pfd[POLL_STDIN].fd = -1;
954 /* if no stdout, stop watching net in */
955 if (pfd[POLL_STDOUT].fd == -1) {
956 if (pfd[POLL_NETIN].fd != -1)
957 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
958 pfd[POLL_NETIN].fd = -1;
961 /* try to read from stdin */
962 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
963 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
965 /* error or eof on stdin - remove from pfd */
966 if (ret == 0 || ret == -1)
967 pfd[POLL_STDIN].fd = -1;
968 /* read something - poll net out */
970 pfd[POLL_NETOUT].events = POLLOUT;
971 /* filled buffer - remove self from polling */
972 if (stdinbufpos == BUFSIZE)
973 pfd[POLL_STDIN].events = 0;
975 /* try to write to network */
976 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
977 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
978 &stdinbufpos, FreeBSD_crlf);
980 pfd[POLL_NETOUT].fd = -1;
981 /* buffer empty - remove self from polling */
982 if (stdinbufpos == 0)
983 pfd[POLL_NETOUT].events = 0;
984 /* buffer no longer full - poll stdin again */
985 if (stdinbufpos < BUFSIZE)
986 pfd[POLL_STDIN].events = POLLIN;
988 /* try to read from network */
989 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
990 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
993 pfd[POLL_NETIN].fd = -1;
994 /* eof on net in - remove from pfd */
996 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
997 pfd[POLL_NETIN].fd = -1;
999 /* read something - poll stdout */
1000 if (netinbufpos > 0)
1001 pfd[POLL_STDOUT].events = POLLOUT;
1002 /* filled buffer - remove self from polling */
1003 if (netinbufpos == BUFSIZE)
1004 pfd[POLL_NETIN].events = 0;
1007 atelnet(pfd[POLL_NETIN].fd, netinbuf,
1010 /* try to write to stdout */
1011 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
1012 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
1015 pfd[POLL_STDOUT].fd = -1;
1016 /* buffer empty - remove self from polling */
1017 if (netinbufpos == 0)
1018 pfd[POLL_STDOUT].events = 0;
1019 /* buffer no longer full - poll net in again */
1020 if (netinbufpos < BUFSIZE)
1021 pfd[POLL_NETIN].events = POLLIN;
1024 /* stdin gone and queue empty? */
1025 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
1026 if (pfd[POLL_NETOUT].fd != -1 && Nflag) {
1027 if (FreeBSD_Mflag) {
1028 FreeBSD_stats_print(net_fd);
1031 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1033 pfd[POLL_NETOUT].fd = -1;
1035 /* net in gone and queue empty? */
1036 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1037 pfd[POLL_STDOUT].fd = -1;
1043 write_wrapper(int fd, const void *buf, size_t buflen)
1045 ssize_t n = write(fd, buf, buflen);
1046 /* don't treat EAGAIN, EINTR as error */
1047 return (n == -1 && (errno == EAGAIN || errno == EINTR)) ? -2 : n;
1051 drainbuf(int fd, unsigned char *buf, size_t *bufpos, int crlf)
1053 ssize_t n = *bufpos, n2 = 0;
1055 unsigned char *lf = NULL;
1058 lf = memchr(buf, '\n', *bufpos);
1059 if (lf && (lf == buf || *(lf - 1) != '\r'))
1066 n = write_wrapper(fd, buf, n);
1072 n2 = write_wrapper(fd, "\r\n", 2);
1079 adjust = *bufpos - n;
1081 memmove(buf, buf + n, adjust);
1088 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1090 size_t num = BUFSIZE - *bufpos;
1093 n = read(fd, buf + *bufpos, num);
1094 /* don't treat EAGAIN, EINTR as error */
1095 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1105 * Pass the connected file descriptor to stdout and exit.
1113 char buf[CMSG_SPACE(sizeof(int))];
1115 struct cmsghdr *cmsg;
1121 /* Avoid obvious stupidity */
1122 if (isatty(STDOUT_FILENO))
1123 errx(1, "Cannot pass file descriptor to tty");
1125 bzero(&mh, sizeof(mh));
1126 bzero(&cmsgbuf, sizeof(cmsgbuf));
1127 bzero(&iov, sizeof(iov));
1129 mh.msg_control = (caddr_t)&cmsgbuf.buf;
1130 mh.msg_controllen = sizeof(cmsgbuf.buf);
1131 cmsg = CMSG_FIRSTHDR(&mh);
1132 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1133 cmsg->cmsg_level = SOL_SOCKET;
1134 cmsg->cmsg_type = SCM_RIGHTS;
1135 *(int *)CMSG_DATA(cmsg) = nfd;
1142 bzero(&pfd, sizeof(pfd));
1143 pfd.fd = STDOUT_FILENO;
1144 pfd.events = POLLOUT;
1146 r = sendmsg(STDOUT_FILENO, &mh, 0);
1148 if (errno == EAGAIN || errno == EINTR) {
1149 if (poll(&pfd, 1, -1) == -1)
1155 errx(1, "sendmsg: unexpected return value %zd", r);
1162 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1164 atelnet(int nfd, unsigned char *buf, unsigned int size)
1166 unsigned char *p, *end;
1167 unsigned char obuf[4];
1171 end = buf + size - 2;
1173 for (p = buf; p < end; p++) {
1179 if ((*p == WILL) || (*p == WONT))
1181 else if ((*p == DO) || (*p == DONT))
1188 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1189 warn("Write Error!");
1195 * Build an array of ports in portlist[], listing each port
1196 * that we should try to connect to.
1199 build_ports(char *p)
1206 if ((n = strchr(p, '-')) != NULL) {
1210 /* Make sure the ports are in order: lowest->highest. */
1211 hi = strtonum(n, 1, PORT_MAX, &errstr);
1213 errx(1, "port number %s: %s", errstr, n);
1214 lo = strtonum(p, 1, PORT_MAX, &errstr);
1216 errx(1, "port number %s: %s", errstr, p);
1224 /* Load ports sequentially. */
1225 for (cp = lo; cp <= hi; cp++) {
1226 portlist[x] = calloc(1, PORT_MAX_LEN);
1227 if (portlist[x] == NULL)
1229 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1233 /* Randomly swap ports. */
1238 for (x = 0; x <= (hi - lo); x++) {
1239 y = (arc4random() & 0xFFFF) % (hi - lo);
1241 portlist[x] = portlist[y];
1246 hi = strtonum(p, 1, PORT_MAX, &errstr);
1248 errx(1, "port number %s: %s", errstr, p);
1249 portlist[0] = strdup(p);
1250 if (portlist[0] == NULL)
1257 * Do a few writes to see if the UDP port is there.
1258 * Fails once PF state table is full.
1265 for (i = 0; i <= 3; i++) {
1266 if (write(s, "X", 1) == 1)
1275 FreeBSD_stats_setup(int s)
1278 if (setsockopt(s, IPPROTO_TCP, TCP_STATS,
1279 &FreeBSD_Mflag, sizeof(FreeBSD_Mflag)) == -1) {
1280 if (errno == EOPNOTSUPP) {
1281 warnx("getsockopt(TCP_STATS) failed; "
1282 "kernel built without \"options STATS\"?");
1284 err(1, "enable TCP_STATS gathering");
1289 FreeBSD_stats_print(int s)
1292 struct statsblob *statsb;
1294 socklen_t sockoptlen;
1298 * This usleep is a workaround for TCP_STATS reporting
1299 * incorrect values for TXPB.
1304 statsb = malloc(sockoptlen);
1307 error = getsockopt(s, IPPROTO_TCP, TCP_STATS, statsb, &sockoptlen);
1309 if (errno == EOVERFLOW && statsb->cursz > sockoptlen) {
1310 /* Retry with a larger size. */
1311 sockoptlen = statsb->cursz;
1312 statsb = realloc(statsb, sockoptlen);
1315 error = getsockopt(s, IPPROTO_TCP, TCP_STATS,
1316 statsb, &sockoptlen);
1319 err(1, "getsockopt");
1322 sb = sbuf_new_auto();
1323 error = stats_blob_tostr(statsb, sb, SB_STRFMT_JSON, SB_TOSTR_META);
1325 errc(1, error, "stats_blob_tostr");
1327 error = sbuf_finish(sb);
1329 err(1, "sbuf_finish");
1331 fprintf(stderr, "%s\n", sbuf_data(sb));
1336 set_common_sockopts(int s, int af)
1341 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1342 &x, sizeof(x)) == -1)
1346 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1347 &x, sizeof(x)) == -1)
1353 if (af == AF_INET6) {
1354 proto = IPPROTO_IPV6;
1355 option = IPV6_TCLASS;
1361 if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1362 err(1, "set IP ToS");
1365 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1366 &Iflag, sizeof(Iflag)) == -1)
1367 err(1, "set TCP receive buffer size");
1370 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1371 &Oflag, sizeof(Oflag)) == -1)
1372 err(1, "set TCP send buffer size");
1374 if (FreeBSD_Oflag) {
1375 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
1376 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
1377 err(1, "disable TCP options");
1380 FreeBSD_stats_setup(s);
1382 if (ipsec_policy[0] != NULL)
1383 add_ipsec_policy(s, af, ipsec_policy[0]);
1384 if (ipsec_policy[1] != NULL)
1385 add_ipsec_policy(s, af, ipsec_policy[1]);
1390 map_tos(char *s, int *val)
1392 /* DiffServ Codepoints and other TOS mappings */
1393 const struct toskeywords {
1394 const char *keyword;
1396 } *t, toskeywords[] = {
1397 { "af11", IPTOS_DSCP_AF11 },
1398 { "af12", IPTOS_DSCP_AF12 },
1399 { "af13", IPTOS_DSCP_AF13 },
1400 { "af21", IPTOS_DSCP_AF21 },
1401 { "af22", IPTOS_DSCP_AF22 },
1402 { "af23", IPTOS_DSCP_AF23 },
1403 { "af31", IPTOS_DSCP_AF31 },
1404 { "af32", IPTOS_DSCP_AF32 },
1405 { "af33", IPTOS_DSCP_AF33 },
1406 { "af41", IPTOS_DSCP_AF41 },
1407 { "af42", IPTOS_DSCP_AF42 },
1408 { "af43", IPTOS_DSCP_AF43 },
1409 { "critical", IPTOS_PREC_CRITIC_ECP },
1410 { "cs0", IPTOS_DSCP_CS0 },
1411 { "cs1", IPTOS_DSCP_CS1 },
1412 { "cs2", IPTOS_DSCP_CS2 },
1413 { "cs3", IPTOS_DSCP_CS3 },
1414 { "cs4", IPTOS_DSCP_CS4 },
1415 { "cs5", IPTOS_DSCP_CS5 },
1416 { "cs6", IPTOS_DSCP_CS6 },
1417 { "cs7", IPTOS_DSCP_CS7 },
1418 { "ef", IPTOS_DSCP_EF },
1419 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1420 { "lowdelay", IPTOS_LOWDELAY },
1421 { "netcontrol", IPTOS_PREC_NETCONTROL },
1422 { "reliability", IPTOS_RELIABILITY },
1423 { "throughput", IPTOS_THROUGHPUT },
1427 for (t = toskeywords; t->keyword != NULL; t++) {
1428 if (strcmp(s, t->keyword) == 0) {
1438 report_connect(const struct sockaddr *sa, socklen_t salen)
1440 char remote_host[NI_MAXHOST];
1441 char remote_port[NI_MAXSERV];
1443 int flags = NI_NUMERICSERV;
1446 flags |= NI_NUMERICHOST;
1448 if ((herr = getnameinfo(sa, salen,
1449 remote_host, sizeof(remote_host),
1450 remote_port, sizeof(remote_port),
1452 if (herr == EAI_SYSTEM)
1453 err(1, "getnameinfo");
1455 errx(1, "getnameinfo: %s", gai_strerror(herr));
1459 "Connection from %s %s "
1460 "received!\n", remote_host, remote_port);
1467 fprintf(stderr, "\tCommand Summary:\n\
1470 \t--crlf Convert LF into CRLF when sending data over the network\n\
1471 \t-D Enable the debug socket option\n\
1472 \t-d Detach from stdin\n");
1475 \t-E Use IPsec ESP\n\
1476 \t-e policy Use specified IPsec policy\n");
1479 \t-F Pass socket fd\n\
1480 \t-h This help text\n\
1481 \t-I length TCP receive buffer length\n\
1482 \t-i secs\t Delay interval for lines sent, ports scanned\n\
1483 \t-k Keep inbound sockets open for multiple connects\n\
1484 \t-l Listen mode, for inbound connects\n\
1485 \t-N Shutdown the network socket after EOF on stdin\n\
1486 \t-n Suppress name/port resolutions\n\
1487 \t--no-tcpopt Disable TCP options\n\
1488 \t--sctp\t SCTP mode\n\
1489 \t--tun tundev Use tun device rather than stdio\n\
1490 \t-O length TCP send buffer length\n\
1491 \t-P proxyuser\tUsername for proxy authentication\n\
1492 \t-p port\t Specify local port for remote connects\n\
1493 \t-r Randomize remote ports\n\
1494 \t-S Enable the TCP MD5 signature option\n\
1495 \t-s addr\t Local source address\n\
1496 \t-T toskeyword\tSet IP Type of Service\n\
1497 \t-t Answer TELNET negotiation\n\
1498 \t-U Use UNIX domain socket\n\
1500 \t-V rtable Specify alternate routing table\n\
1502 \t-w secs\t Timeout for connects and final net reads\n\
1503 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1504 \t-x addr[:port]\tSpecify proxy address and port\n\
1505 \t-z Zero-I/O mode [used for scanning]\n\
1506 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1508 fprintf(stderr, "\tSee ipsec_set_policy(3) for -e argument format\n");
1515 add_ipsec_policy(int s, int af, char *policy)
1520 raw = ipsec_set_policy(policy, strlen(policy));
1522 errx(1, "ipsec_set_policy `%s': %s", policy,
1525 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1526 ipsec_get_policylen(raw));
1528 e = setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, raw,
1529 ipsec_get_policylen(raw));
1531 err(1, "ipsec policy cannot be configured");
1534 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1544 "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1546 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1548 "\t [--no-tcpopt] [--sctp]\n"
1549 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1550 "\t [--tun tundev] [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1551 "\t [-x proxy_address[:port]] [destination] [port]\n");