Deleted Added
full compact
netcat.c (302408) netcat.c (141261)
1/* $OpenBSD: netcat.c,v 1.130 2015/07/26 19:12:28 chl Exp $ */
1/* $OpenBSD: netcat.c,v 1.76 2004/12/10 16:51:31 hshoexer 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

--- 9 unchanged lines hidden (view full) ---

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.
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

--- 9 unchanged lines hidden (view full) ---

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: stable/11/contrib/netcat/netcat.c 288303 2015-09-27 07:04:16Z delphij $
29 */
30
31/*
32 * Re-written nc(1) for OpenBSD. Original implementation by
33 * *Hobbit* <hobbit@avian.org>.
34 */
35
27 */
28
29/*
30 * Re-written nc(1) for OpenBSD. Original implementation by
31 * *Hobbit* <hobbit@avian.org>.
32 */
33
36#include <sys/limits.h>
37#include <sys/types.h>
38#include <sys/socket.h>
34#include <sys/types.h>
35#include <sys/socket.h>
39#include <sys/sysctl.h>
40#include <sys/time.h>
36#include <sys/time.h>
41#include <sys/uio.h>
42#include <sys/un.h>
43
44#include <netinet/in.h>
37#include <sys/un.h>
38
39#include <netinet/in.h>
45#ifdef IPSEC
46#include <netipsec/ipsec.h>
47#endif
48#include <netinet/tcp.h>
40#include <netinet/tcp.h>
49#include <netinet/ip.h>
50#include <arpa/telnet.h>
51
52#include <err.h>
53#include <errno.h>
41#include <arpa/telnet.h>
42
43#include <err.h>
44#include <errno.h>
54#include <getopt.h>
55#include <fcntl.h>
56#include <limits.h>
57#include <netdb.h>
58#include <poll.h>
45#include <netdb.h>
46#include <poll.h>
59#include <signal.h>
60#include <stdarg.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <unistd.h>
47#include <stdarg.h>
48#include <stdio.h>
49#include <stdlib.h>
50#include <string.h>
51#include <unistd.h>
65#include "atomicio.h"
52#include <fcntl.h>
66
67#ifndef SUN_LEN
68#define SUN_LEN(su) \
69 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
70#endif
71
72#define PORT_MAX 65535
73#define PORT_MAX_LEN 6
53
54#ifndef SUN_LEN
55#define SUN_LEN(su) \
56 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
57#endif
58
59#define PORT_MAX 65535
60#define PORT_MAX_LEN 6
74#define UNIX_DG_TMP_SOCKET_SIZE 19
75
61
76#define POLL_STDIN 0
77#define POLL_NETOUT 1
78#define POLL_NETIN 2
79#define POLL_STDOUT 3
80#define BUFSIZE 16384
81
82/* Command Line Options */
83int dflag; /* detached, no stdin */
62/* Command Line Options */
63int dflag; /* detached, no stdin */
84int Fflag; /* fdpass sock to stdout */
85unsigned int iflag; /* Interval Flag */
64int iflag; /* Interval Flag */
86int kflag; /* More than one connect */
87int lflag; /* Bind to local port */
65int kflag; /* More than one connect */
66int lflag; /* Bind to local port */
88int Nflag; /* shutdown() network socket */
89int nflag; /* Don't do name look up */
67int nflag; /* Don't do name look up */
90int FreeBSD_Oflag; /* Do not use TCP options */
91char *Pflag; /* Proxy username */
92char *pflag; /* Localport flag */
93int rflag; /* Random ports flag */
94char *sflag; /* Source Address */
95int tflag; /* Telnet Emulation */
96int uflag; /* UDP - Default to TCP */
97int vflag; /* Verbosity */
98int xflag; /* Socks proxy */
99int zflag; /* Port Scan Flag */
100int Dflag; /* sodebug */
68char *pflag; /* Localport flag */
69int rflag; /* Random ports flag */
70char *sflag; /* Source Address */
71int tflag; /* Telnet Emulation */
72int uflag; /* UDP - Default to TCP */
73int vflag; /* Verbosity */
74int xflag; /* Socks proxy */
75int zflag; /* Port Scan Flag */
76int Dflag; /* sodebug */
101int Iflag; /* TCP receive buffer size */
102int Oflag; /* TCP send buffer size */
103int Sflag; /* TCP MD5 signature option */
77int Sflag; /* TCP MD5 signature option */
104int Tflag = -1; /* IP Type of Service */
105int rtableid = -1;
106
107int timeout = -1;
108int family = AF_UNSPEC;
109char *portlist[PORT_MAX+1];
78
79int timeout = -1;
80int family = AF_UNSPEC;
81char *portlist[PORT_MAX+1];
110char *unix_dg_tmp_socket;
111
82
83ssize_t atomicio(ssize_t (*)(int, void *, size_t), int, void *, size_t);
112void atelnet(int, unsigned char *, unsigned int);
113void build_ports(char *);
114void help(void);
115int local_listen(char *, char *, struct addrinfo);
116void readwrite(int);
84void atelnet(int, unsigned char *, unsigned int);
85void build_ports(char *);
86void help(void);
87int local_listen(char *, char *, struct addrinfo);
88void readwrite(int);
117void fdpass(int nfd) __attribute__((noreturn));
118int remote_connect(const char *, const char *, struct addrinfo);
119int timeout_connect(int, const struct sockaddr *, socklen_t);
120int socks_connect(const char *, const char *, struct addrinfo,
121 const char *, const char *, struct addrinfo, int, const char *);
89int remote_connect(char *, char *, struct addrinfo);
90int socks_connect(char *, char *, struct addrinfo, char *, char *,
91 struct addrinfo, int);
122int udptest(int);
92int udptest(int);
123int unix_bind(char *);
124int unix_connect(char *);
125int unix_listen(char *);
93int unix_connect(char *);
94int unix_listen(char *);
126void set_common_sockopts(int, int);
127int map_tos(char *, int *);
128void report_connect(const struct sockaddr *, socklen_t);
129void usage(int);
95void usage(int);
130ssize_t drainbuf(int, unsigned char *, size_t *);
131ssize_t fillbuf(int, unsigned char *, size_t *);
132
96
133#ifdef IPSEC
134void add_ipsec_policy(int, char *);
135
136char *ipsec_policy[2];
137#endif
138
139int
140main(int argc, char *argv[])
141{
97int
98main(int argc, char *argv[])
99{
142 int ch, s, ret, socksv, ipsec_count;
143 int numfibs;
144 size_t intsize = sizeof(int);
145 char *host, *uport;
100 int ch, s, ret, socksv;
101 char *host, *uport, *endp;
146 struct addrinfo hints;
147 struct servent *sv;
148 socklen_t len;
149 struct sockaddr_storage cliaddr;
150 char *proxy;
102 struct addrinfo hints;
103 struct servent *sv;
104 socklen_t len;
105 struct sockaddr_storage cliaddr;
106 char *proxy;
151 const char *errstr, *proxyhost = "", *proxyport = NULL;
107 char *proxyhost = "", *proxyport = NULL;
152 struct addrinfo proxyhints;
108 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 },
156 { NULL, 0, NULL, 0 }
157 };
158
159 ret = 1;
109
110 ret = 1;
160 ipsec_count = 0;
161 s = 0;
162 socksv = 5;
163 host = NULL;
164 uport = NULL;
111 s = 0;
112 socksv = 5;
113 host = NULL;
114 uport = NULL;
115 endp = NULL;
165 sv = NULL;
166
116 sv = NULL;
117
167 signal(SIGPIPE, SIG_IGN);
168
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) {
118 while ((ch = getopt(argc, argv, "46Ddhi:klnp:rSs:tUuvw:X:x:z")) != -1) {
172 switch (ch) {
173 case '4':
174 family = AF_INET;
175 break;
176 case '6':
177 family = AF_INET6;
178 break;
179 case 'U':

--- 7 unchanged lines hidden (view full) ---

187 else if (strcmp(optarg, "5") == 0)
188 socksv = 5; /* SOCKS v.5 */
189 else
190 errx(1, "unsupported proxy protocol");
191 break;
192 case 'd':
193 dflag = 1;
194 break;
119 switch (ch) {
120 case '4':
121 family = AF_INET;
122 break;
123 case '6':
124 family = AF_INET6;
125 break;
126 case 'U':

--- 7 unchanged lines hidden (view full) ---

134 else if (strcmp(optarg, "5") == 0)
135 socksv = 5; /* SOCKS v.5 */
136 else
137 errx(1, "unsupported proxy protocol");
138 break;
139 case 'd':
140 dflag = 1;
141 break;
195 case 'e':
196#ifdef IPSEC
197 ipsec_policy[ipsec_count++ % 2] = optarg;
198#else
199 errx(1, "IPsec support unavailable.");
200#endif
201 break;
202 case 'E':
203#ifdef IPSEC
204 ipsec_policy[0] = "in ipsec esp/transport//require";
205 ipsec_policy[1] = "out ipsec esp/transport//require";
206#else
207 errx(1, "IPsec support unavailable.");
208#endif
209 break;
210 case 'F':
211 Fflag = 1;
212 break;
213 case 'h':
214 help();
215 break;
216 case 'i':
142 case 'h':
143 help();
144 break;
145 case 'i':
217 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
218 if (errstr)
219 errx(1, "interval %s: %s", errstr, optarg);
146 iflag = (int)strtoul(optarg, &endp, 10);
147 if (iflag < 0 || *endp != '\0')
148 errx(1, "interval cannot be negative");
220 break;
221 case 'k':
222 kflag = 1;
223 break;
224 case 'l':
225 lflag = 1;
226 break;
149 break;
150 case 'k':
151 kflag = 1;
152 break;
153 case 'l':
154 lflag = 1;
155 break;
227 case 'N':
228 Nflag = 1;
229 break;
230 case 'n':
231 nflag = 1;
232 break;
156 case 'n':
157 nflag = 1;
158 break;
233 case 'o':
234 fprintf(stderr, "option -o is deprecated.\n");
235 break;
236 case 'P':
237 Pflag = optarg;
238 break;
239 case 'p':
240 pflag = optarg;
241 break;
242 case 'r':
243 rflag = 1;
244 break;
245 case 's':
246 sflag = optarg;
247 break;
248 case 't':
249 tflag = 1;
250 break;
251 case 'u':
252 uflag = 1;
253 break;
159 case 'p':
160 pflag = optarg;
161 break;
162 case 'r':
163 rflag = 1;
164 break;
165 case 's':
166 sflag = optarg;
167 break;
168 case 't':
169 tflag = 1;
170 break;
171 case 'u':
172 uflag = 1;
173 break;
254 case 'V':
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);
259 if (errstr)
260 errx(1, "rtable %s: %s", errstr, optarg);
261 break;
262 case 'v':
263 vflag = 1;
264 break;
265 case 'w':
174 case 'v':
175 vflag = 1;
176 break;
177 case 'w':
266 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
267 if (errstr)
268 errx(1, "timeout %s: %s", errstr, optarg);
178 timeout = (int)strtoul(optarg, &endp, 10);
179 if (timeout < 0 || *endp != '\0')
180 errx(1, "timeout cannot be negative");
181 if (timeout >= (INT_MAX / 1000))
182 errx(1, "timeout too large");
269 timeout *= 1000;
270 break;
271 case 'x':
272 xflag = 1;
273 if ((proxy = strdup(optarg)) == NULL)
274 err(1, NULL);
275 break;
276 case 'z':
277 zflag = 1;
278 break;
279 case 'D':
280 Dflag = 1;
281 break;
183 timeout *= 1000;
184 break;
185 case 'x':
186 xflag = 1;
187 if ((proxy = strdup(optarg)) == NULL)
188 err(1, NULL);
189 break;
190 case 'z':
191 zflag = 1;
192 break;
193 case 'D':
194 Dflag = 1;
195 break;
282 case 'I':
283 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
284 if (errstr != NULL)
285 errx(1, "TCP receive window %s: %s",
286 errstr, optarg);
287 break;
288 case 'O':
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",
293 errstr, optarg);
294 }
295 break;
296 case 'S':
297 Sflag = 1;
298 break;
196 case 'S':
197 Sflag = 1;
198 break;
299 case 'T':
300 errstr = NULL;
301 errno = 0;
302 if (map_tos(optarg, &Tflag))
303 break;
304 if (strlen(optarg) > 1 && optarg[0] == '0' &&
305 optarg[1] == 'x')
306 Tflag = (int)strtol(optarg, NULL, 16);
307 else
308 Tflag = (int)strtonum(optarg, 0, 255,
309 &errstr);
310 if (Tflag < 0 || Tflag > 255 || errstr || errno)
311 errx(1, "illegal tos value %s", optarg);
312 break;
313 default:
314 usage(1);
315 }
316 }
317 argc -= optind;
318 argv += optind;
319
320 /* Cruft to make sure options are clean, and used properly. */
321 if (argv[0] && !argv[1] && family == AF_UNIX) {
199 default:
200 usage(1);
201 }
202 }
203 argc -= optind;
204 argv += optind;
205
206 /* Cruft to make sure options are clean, and used properly. */
207 if (argv[0] && !argv[1] && family == AF_UNIX) {
208 if (uflag)
209 errx(1, "cannot use -u and -U");
322 host = argv[0];
323 uport = NULL;
324 } else if (argv[0] && !argv[1]) {
325 if (!lflag)
326 usage(1);
327 uport = argv[0];
328 host = NULL;
329 } else if (argv[0] && argv[1]) {

--- 6 unchanged lines hidden (view full) ---

336 errx(1, "cannot use -s and -l");
337 if (lflag && pflag)
338 errx(1, "cannot use -p and -l");
339 if (lflag && zflag)
340 errx(1, "cannot use -z and -l");
341 if (!lflag && kflag)
342 errx(1, "must use -l with -k");
343
210 host = argv[0];
211 uport = NULL;
212 } else if (argv[0] && !argv[1]) {
213 if (!lflag)
214 usage(1);
215 uport = argv[0];
216 host = NULL;
217 } else if (argv[0] && argv[1]) {

--- 6 unchanged lines hidden (view full) ---

224 errx(1, "cannot use -s and -l");
225 if (lflag && pflag)
226 errx(1, "cannot use -p and -l");
227 if (lflag && zflag)
228 errx(1, "cannot use -z and -l");
229 if (!lflag && kflag)
230 errx(1, "must use -l with -k");
231
344 /* Get name of temporary socket for unix datagram client */
345 if ((family == AF_UNIX) && uflag && !lflag) {
346 if (sflag) {
347 unix_dg_tmp_socket = sflag;
348 } else {
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)
352 err(1, "mktemp");
353 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
354 }
355 }
356
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;
363 if (nflag)
364 hints.ai_flags |= AI_NUMERICHOST;

--- 26 unchanged lines hidden (view full) ---

391 if (nflag)
392 proxyhints.ai_flags |= AI_NUMERICHOST;
393 }
394
395 if (lflag) {
396 int connfd;
397 ret = 0;
398
232 /* Initialize addrinfo structure. */
233 if (family != AF_UNIX) {
234 memset(&hints, 0, sizeof(struct addrinfo));
235 hints.ai_family = family;
236 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
237 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
238 if (nflag)
239 hints.ai_flags |= AI_NUMERICHOST;

--- 26 unchanged lines hidden (view full) ---

266 if (nflag)
267 proxyhints.ai_flags |= AI_NUMERICHOST;
268 }
269
270 if (lflag) {
271 int connfd;
272 ret = 0;
273
399 if (family == AF_UNIX) {
400 if (uflag)
401 s = unix_bind(host);
402 else
403 s = unix_listen(host);
404 }
274 if (family == AF_UNIX)
275 s = unix_listen(host);
405
406 /* Allow only one connection at a time, but stay alive. */
407 for (;;) {
408 if (family != AF_UNIX)
409 s = local_listen(host, uport, hints);
410 if (s < 0)
411 err(1, NULL);
412 /*
276
277 /* Allow only one connection at a time, but stay alive. */
278 for (;;) {
279 if (family != AF_UNIX)
280 s = local_listen(host, uport, hints);
281 if (s < 0)
282 err(1, NULL);
283 /*
413 * For UDP and -k, don't connect the socket, let it
414 * receive datagrams from multiple socket pairs.
284 * For UDP, we will use recvfrom() initially
285 * to wait for a caller, then use the regular
286 * functions to talk to the caller.
415 */
287 */
416 if (uflag && kflag)
417 readwrite(s);
418 /*
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.
422 */
423 else if (uflag && !kflag) {
424 int rv, plen;
425 char buf[16384];
288 if (uflag) {
289 int rv;
290 char buf[1024];
426 struct sockaddr_storage z;
427
428 len = sizeof(z);
291 struct sockaddr_storage z;
292
293 len = sizeof(z);
429 plen = 2048;
430 rv = recvfrom(s, buf, plen, MSG_PEEK,
294 rv = recvfrom(s, buf, sizeof(buf), MSG_PEEK,
431 (struct sockaddr *)&z, &len);
432 if (rv < 0)
433 err(1, "recvfrom");
434
435 rv = connect(s, (struct sockaddr *)&z, len);
436 if (rv < 0)
437 err(1, "connect");
438
295 (struct sockaddr *)&z, &len);
296 if (rv < 0)
297 err(1, "recvfrom");
298
299 rv = connect(s, (struct sockaddr *)&z, len);
300 if (rv < 0)
301 err(1, "connect");
302
439 if (vflag)
440 report_connect((struct sockaddr *)&z, len);
441
442 readwrite(s);
303 connfd = s;
443 } else {
304 } else {
444 len = sizeof(cliaddr);
445 connfd = accept(s, (struct sockaddr *)&cliaddr,
446 &len);
305 connfd = accept(s, (struct sockaddr *)&cliaddr,
306 &len);
447 if (connfd == -1) {
448 /* For now, all errnos are fatal */
449 err(1, "accept");
450 }
451 if (vflag)
452 report_connect((struct sockaddr *)&cliaddr, len);
453
454 readwrite(connfd);
455 close(connfd);
456 }
457
307 }
308
309 readwrite(connfd);
310 close(connfd);
458 if (family != AF_UNIX)
459 close(s);
311 if (family != AF_UNIX)
312 close(s);
460 else if (uflag) {
461 if (connect(s, NULL, 0) < 0)
462 err(1, "connect");
463 }
464
465 if (!kflag)
466 break;
467 }
468 } else if (family == AF_UNIX) {
469 ret = 0;
470
471 if ((s = unix_connect(host)) > 0 && !zflag) {
472 readwrite(s);
473 close(s);
474 } else
475 ret = 1;
476
313
314 if (!kflag)
315 break;
316 }
317 } else if (family == AF_UNIX) {
318 ret = 0;
319
320 if ((s = unix_connect(host)) > 0 && !zflag) {
321 readwrite(s);
322 close(s);
323 } else
324 ret = 1;
325
477 if (uflag)
478 unlink(unix_dg_tmp_socket);
479 exit(ret);
480
481 } else {
482 int i = 0;
483
484 /* Construct the portlist[] array. */
485 build_ports(uport);
486
487 /* Cycle through portlist, connecting to each port. */
488 for (i = 0; portlist[i] != NULL; i++) {
489 if (s)
490 close(s);
491
492 if (xflag)
493 s = socks_connect(host, portlist[i], hints,
326 exit(ret);
327
328 } else {
329 int i = 0;
330
331 /* Construct the portlist[] array. */
332 build_ports(uport);
333
334 /* Cycle through portlist, connecting to each port. */
335 for (i = 0; portlist[i] != NULL; i++) {
336 if (s)
337 close(s);
338
339 if (xflag)
340 s = socks_connect(host, portlist[i], hints,
494 proxyhost, proxyport, proxyhints, socksv,
495 Pflag);
341 proxyhost, proxyport, proxyhints, socksv);
496 else
497 s = remote_connect(host, portlist[i], hints);
498
499 if (s < 0)
500 continue;
501
502 ret = 0;
503 if (vflag || zflag) {

--- 9 unchanged lines hidden (view full) ---

513 if (nflag)
514 sv = NULL;
515 else {
516 sv = getservbyport(
517 ntohs(atoi(portlist[i])),
518 uflag ? "udp" : "tcp");
519 }
520
342 else
343 s = remote_connect(host, portlist[i], hints);
344
345 if (s < 0)
346 continue;
347
348 ret = 0;
349 if (vflag || zflag) {

--- 9 unchanged lines hidden (view full) ---

359 if (nflag)
360 sv = NULL;
361 else {
362 sv = getservbyport(
363 ntohs(atoi(portlist[i])),
364 uflag ? "udp" : "tcp");
365 }
366
521 fprintf(stderr,
522 "Connection to %s %s port [%s/%s] "
523 "succeeded!\n", host, portlist[i],
524 uflag ? "udp" : "tcp",
367 printf("Connection to %s %s port [%s/%s] succeeded!\n",
368 host, portlist[i], uflag ? "udp" : "tcp",
525 sv ? sv->s_name : "*");
526 }
369 sv ? sv->s_name : "*");
370 }
527 if (Fflag)
528 fdpass(s);
529 else if (!zflag)
371 if (!zflag)
530 readwrite(s);
531 }
532 }
533
534 if (s)
535 close(s);
536
537 exit(ret);
538}
539
540/*
372 readwrite(s);
373 }
374 }
375
376 if (s)
377 close(s);
378
379 exit(ret);
380}
381
382/*
541 * unix_bind()
542 * Returns a unix socket bound to the given path
383 * unix_connect()
384 * Returns a socket connected to a local unix socket. Returns -1 on failure.
543 */
544int
385 */
386int
545unix_bind(char *path)
387unix_connect(char *path)
546{
547 struct sockaddr_un sun;
548 int s;
549
388{
389 struct sockaddr_un sun;
390 int s;
391
550 /* Create unix domain socket. */
551 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
552 0)) < 0)
392 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
553 return (-1);
393 return (-1);
394 (void)fcntl(s, F_SETFD, 1);
554
555 memset(&sun, 0, sizeof(struct sockaddr_un));
556 sun.sun_family = AF_UNIX;
557
558 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
559 sizeof(sun.sun_path)) {
560 close(s);
561 errno = ENAMETOOLONG;
562 return (-1);
563 }
395
396 memset(&sun, 0, sizeof(struct sockaddr_un));
397 sun.sun_family = AF_UNIX;
398
399 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
400 sizeof(sun.sun_path)) {
401 close(s);
402 errno = ENAMETOOLONG;
403 return (-1);
404 }
564
565 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
405 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
566 close(s);
567 return (-1);
568 }
569 return (s);
406 close(s);
407 return (-1);
408 }
409 return (s);
410
570}
571
572/*
411}
412
413/*
573 * unix_connect()
574 * Returns a socket connected to a local unix socket. Returns -1 on failure.
414 * unix_listen()
415 * Create a unix domain socket, and listen on it.
575 */
576int
416 */
417int
577unix_connect(char *path)
418unix_listen(char *path)
578{
579 struct sockaddr_un sun;
580 int s;
581
419{
420 struct sockaddr_un sun;
421 int s;
422
582 if (uflag) {
583 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
584 return (-1);
585 } else {
586 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
587 return (-1);
588 }
589 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
423 /* Create unix domain socket. */
424 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
425 return (-1);
590
591 memset(&sun, 0, sizeof(struct sockaddr_un));
592 sun.sun_family = AF_UNIX;
593
594 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
595 sizeof(sun.sun_path)) {
596 close(s);
597 errno = ENAMETOOLONG;
598 return (-1);
599 }
426
427 memset(&sun, 0, sizeof(struct sockaddr_un));
428 sun.sun_family = AF_UNIX;
429
430 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
431 sizeof(sun.sun_path)) {
432 close(s);
433 errno = ENAMETOOLONG;
434 return (-1);
435 }
600 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
436
437 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
601 close(s);
602 return (-1);
603 }
438 close(s);
439 return (-1);
440 }
604 return (s);
605
441
606}
607
608/*
609 * unix_listen()
610 * Create a unix domain socket, and listen on it.
611 */
612int
613unix_listen(char *path)
614{
615 int s;
616 if ((s = unix_bind(path)) < 0)
617 return (-1);
618
619 if (listen(s, 5) < 0) {
620 close(s);
621 return (-1);
622 }
623 return (s);
624}
625
626/*
627 * remote_connect()
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.
630 */
631int
442 if (listen(s, 5) < 0) {
443 close(s);
444 return (-1);
445 }
446 return (s);
447}
448
449/*
450 * remote_connect()
451 * Returns a socket connected to a remote host. Properly binds to a local
452 * port or source address if needed. Returns -1 on failure.
453 */
454int
632remote_connect(const char *host, const char *port, struct addrinfo hints)
455remote_connect(char *host, char *port, struct addrinfo hints)
633{
634 struct addrinfo *res, *res0;
456{
457 struct addrinfo *res, *res0;
635 int s, error, on = 1;
458 int s, error, x = 1;
636
637 if ((error = getaddrinfo(host, port, &hints, &res)))
638 errx(1, "getaddrinfo: %s", gai_strerror(error));
639
640 res0 = res;
641 do {
642 if ((s = socket(res0->ai_family, res0->ai_socktype,
643 res0->ai_protocol)) < 0)
644 continue;
459
460 if ((error = getaddrinfo(host, port, &hints, &res)))
461 errx(1, "getaddrinfo: %s", gai_strerror(error));
462
463 res0 = res;
464 do {
465 if ((s = socket(res0->ai_family, res0->ai_socktype,
466 res0->ai_protocol)) < 0)
467 continue;
645#ifdef IPSEC
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]);
650#endif
651
468
652 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
653 &rtableid, sizeof(rtableid)) == -1))
654 err(1, "setsockopt SO_SETFIB");
655
656 /* Bind to a local port or source address if specified. */
657 if (sflag || pflag) {
658 struct addrinfo ahints, *ares;
659
469 /* Bind to a local port or source address if specified. */
470 if (sflag || pflag) {
471 struct addrinfo ahints, *ares;
472
660 /* try IP_BINDANY, but don't insist */
661 setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
473 if (!(sflag && pflag)) {
474 if (!sflag)
475 sflag = NULL;
476 else
477 pflag = NULL;
478 }
479
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));
669
670 if (bind(s, (struct sockaddr *)ares->ai_addr,
671 ares->ai_addrlen) < 0)
480 memset(&ahints, 0, sizeof(struct addrinfo));
481 ahints.ai_family = res0->ai_family;
482 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
483 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
484 ahints.ai_flags = AI_PASSIVE;
485 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
486 errx(1, "getaddrinfo: %s", gai_strerror(error));
487
488 if (bind(s, (struct sockaddr *)ares->ai_addr,
489 ares->ai_addrlen) < 0)
672 err(1, "bind failed");
490 errx(1, "bind failed: %s", strerror(errno));
673 freeaddrinfo(ares);
674 }
491 freeaddrinfo(ares);
492 }
493 if (Sflag) {
494 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
495 &x, sizeof(x)) == -1)
496 err(1, NULL);
497 }
498 if (Dflag) {
499 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
500 &x, sizeof(x)) == -1)
501 err(1, NULL);
502 }
675
503
676 set_common_sockopts(s, res0->ai_family);
677
678 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
504 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
679 break;
680 else if (vflag)
681 warn("connect to %s port %s (%s) failed", host, port,
682 uflag ? "udp" : "tcp");
683
684 close(s);
685 s = -1;
686 } while ((res0 = res0->ai_next) != NULL);
687
688 freeaddrinfo(res);
689
690 return (s);
691}
692
505 break;
506 else if (vflag)
507 warn("connect to %s port %s (%s) failed", host, port,
508 uflag ? "udp" : "tcp");
509
510 close(s);
511 s = -1;
512 } while ((res0 = res0->ai_next) != NULL);
513
514 freeaddrinfo(res);
515
516 return (s);
517}
518
693int
694timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
695{
696 struct pollfd pfd;
697 socklen_t optlen;
698 int flags, optval;
699 int ret;
700
701 if (timeout != -1) {
702 flags = fcntl(s, F_GETFL, 0);
703 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
704 err(1, "set non-blocking mode");
705 }
706
707 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
708 pfd.fd = s;
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) {
714 errno = optval;
715 ret = optval == 0 ? 0 : -1;
716 }
717 } else if (ret == 0) {
718 errno = ETIMEDOUT;
719 ret = -1;
720 } else
721 err(1, "poll failed");
722 }
723
724 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
725 err(1, "restoring flags");
726
727 return (ret);
728}
729
730/*
731 * local_listen()
732 * Returns a socket listening on a local port, binds to specified source
733 * address. Returns -1 on failure.
734 */
735int
736local_listen(char *host, char *port, struct addrinfo hints)
737{

--- 12 unchanged lines hidden (view full) ---

750 hints.ai_family = AF_INET;
751
752 if ((error = getaddrinfo(host, port, &hints, &res)))
753 errx(1, "getaddrinfo: %s", gai_strerror(error));
754
755 res0 = res;
756 do {
757 if ((s = socket(res0->ai_family, res0->ai_socktype,
519/*
520 * local_listen()
521 * Returns a socket listening on a local port, binds to specified source
522 * address. Returns -1 on failure.
523 */
524int
525local_listen(char *host, char *port, struct addrinfo hints)
526{

--- 12 unchanged lines hidden (view full) ---

539 hints.ai_family = AF_INET;
540
541 if ((error = getaddrinfo(host, port, &hints, &res)))
542 errx(1, "getaddrinfo: %s", gai_strerror(error));
543
544 res0 = res;
545 do {
546 if ((s = socket(res0->ai_family, res0->ai_socktype,
758 res0->ai_protocol)) < 0)
547 res0->ai_protocol)) == 0)
759 continue;
760
548 continue;
549
761 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
762 &rtableid, sizeof(rtableid)) == -1))
763 err(1, "setsockopt SO_SETFIB");
764
765 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
766 if (ret == -1)
767 err(1, NULL);
550 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
551 if (ret == -1)
552 err(1, NULL);
768#ifdef IPSEC
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]);
773#endif
774 if (FreeBSD_Oflag) {
775 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
776 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
777 err(1, "disable TCP options");
553 if (Sflag) {
554 ret = setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
555 &x, sizeof(x));
556 if (ret == -1)
557 err(1, NULL);
778 }
558 }
559 if (Dflag) {
560 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
561 &x, sizeof(x)) == -1)
562 err(1, NULL);
563 }
779
564
780 set_common_sockopts(s, res0->ai_family);
781
782 if (bind(s, (struct sockaddr *)res0->ai_addr,
783 res0->ai_addrlen) == 0)
784 break;
785
786 close(s);
787 s = -1;
788 } while ((res0 = res0->ai_next) != NULL);
789

--- 7 unchanged lines hidden (view full) ---

797 return (s);
798}
799
800/*
801 * readwrite()
802 * Loop that polls on the network file descriptor and stdin.
803 */
804void
565 if (bind(s, (struct sockaddr *)res0->ai_addr,
566 res0->ai_addrlen) == 0)
567 break;
568
569 close(s);
570 s = -1;
571 } while ((res0 = res0->ai_next) != NULL);
572

--- 7 unchanged lines hidden (view full) ---

580 return (s);
581}
582
583/*
584 * readwrite()
585 * Loop that polls on the network file descriptor and stdin.
586 */
587void
805readwrite(int net_fd)
588readwrite(int nfd)
806{
589{
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;
814 int n, num_fds;
815 ssize_t ret;
590 struct pollfd pfd[2];
591 unsigned char buf[BUFSIZ];
592 int wfd = fileno(stdin), n;
593 int lfd = fileno(stdout);
816
594
817 /* don't read from stdin if requested */
818 if (dflag)
819 stdin_fd = -1;
595 /* Setup Network FD */
596 pfd[0].fd = nfd;
597 pfd[0].events = POLLIN;
820
598
821 /* stdin */
822 pfd[POLL_STDIN].fd = stdin_fd;
823 pfd[POLL_STDIN].events = POLLIN;
599 /* Set up STDIN FD. */
600 pfd[1].fd = wfd;
601 pfd[1].events = POLLIN;
824
602
825 /* network out */
826 pfd[POLL_NETOUT].fd = net_fd;
827 pfd[POLL_NETOUT].events = 0;
828
829 /* network in */
830 pfd[POLL_NETIN].fd = net_fd;
831 pfd[POLL_NETIN].events = POLLIN;
832
833 /* stdout */
834 pfd[POLL_STDOUT].fd = stdout_fd;
835 pfd[POLL_STDOUT].events = 0;
836
837 while (1) {
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) {
841 close(net_fd);
842 return;
843 }
844 /* both outputs are gone, we can't continue */
845 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
846 close(net_fd);
847 return;
848 }
849 /* listen and net in gone, queues empty, done */
850 if (lflag && pfd[POLL_NETIN].fd == -1
851 && stdinbufpos == 0 && netinbufpos == 0) {
852 close(net_fd);
853 return;
854 }
855
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 */
603 while (pfd[0].fd != -1) {
859 if (iflag)
860 sleep(iflag);
861
604 if (iflag)
605 sleep(iflag);
606
862 /* poll */
863 num_fds = poll(pfd, 4, timeout);
864
865 /* treat poll errors */
866 if (num_fds == -1) {
867 close(net_fd);
868 err(1, "polling error");
607 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
608 close(nfd);
609 err(1, "Polling Error");
869 }
870
610 }
611
871 /* timeout happened */
872 if (num_fds == 0)
612 if (n == 0)
873 return;
874
613 return;
614
875 /* treat socket error conditions */
876 for (n = 0; n < 4; n++) {
877 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
878 pfd[n].fd = -1;
615 if (pfd[0].revents & POLLIN) {
616 if ((n = read(nfd, buf, sizeof(buf))) < 0)
617 return;
618 else if (n == 0) {
619 shutdown(nfd, SHUT_RD);
620 pfd[0].fd = -1;
621 pfd[0].events = 0;
622 } else {
623 if (tflag)
624 atelnet(nfd, buf, n);
625 if (atomicio((ssize_t (*)(int, void *, size_t))write,
626 lfd, buf, n) != n)
627 return;
879 }
880 }
628 }
629 }
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;
886
630
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;
891
892 if (pfd[POLL_NETOUT].revents & POLLHUP) {
893 if (Nflag)
894 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
895 pfd[POLL_NETOUT].fd = -1;
896 }
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;
908 }
909
910 /* try to read from stdin */
911 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
912 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
913 &stdinbufpos);
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 */
918 if (stdinbufpos > 0)
919 pfd[POLL_NETOUT].events = POLLOUT;
920 /* filled buffer - remove self from polling */
921 if (stdinbufpos == BUFSIZE)
922 pfd[POLL_STDIN].events = 0;
923 }
924 /* try to write to network */
925 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
926 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
927 &stdinbufpos);
928 if (ret == -1)
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;
936 }
937 /* try to read from network */
938 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
939 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
940 &netinbufpos);
941 if (ret == -1)
942 pfd[POLL_NETIN].fd = -1;
943 /* eof on net in - remove from pfd */
944 if (ret == 0) {
945 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
946 pfd[POLL_NETIN].fd = -1;
631 if (!dflag && pfd[1].revents & POLLIN) {
632 if ((n = read(wfd, buf, sizeof(buf))) < 0)
633 return;
634 else if (n == 0) {
635 shutdown(nfd, SHUT_WR);
636 pfd[1].fd = -1;
637 pfd[1].events = 0;
638 } else {
639 if (atomicio((ssize_t (*)(int, void *, size_t))write,
640 nfd, buf, n) != n)
641 return;
947 }
642 }
948 /* read something - poll stdout */
949 if (netinbufpos > 0)
950 pfd[POLL_STDOUT].events = POLLOUT;
951 /* filled buffer - remove self from polling */
952 if (netinbufpos == BUFSIZE)
953 pfd[POLL_NETIN].events = 0;
954 /* handle telnet */
955 if (tflag)
956 atelnet(pfd[POLL_NETIN].fd, netinbuf,
957 netinbufpos);
958 }
643 }
959 /* try to write to stdout */
960 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
961 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
962 &netinbufpos);
963 if (ret == -1)
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;
971 }
972
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;
978 }
979 /* net in gone and queue empty? */
980 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
981 pfd[POLL_STDOUT].fd = -1;
982 }
983 }
984}
985
644 }
645}
646
986ssize_t
987drainbuf(int fd, unsigned char *buf, size_t *bufpos)
988{
989 ssize_t n;
990 ssize_t adjust;
991
992 n = write(fd, buf, *bufpos);
993 /* don't treat EAGAIN, EINTR as error */
994 if (n == -1 && (errno == EAGAIN || errno == EINTR))
995 n = -2;
996 if (n <= 0)
997 return n;
998 /* adjust buffer */
999 adjust = *bufpos - n;
1000 if (adjust > 0)
1001 memmove(buf, buf + n, adjust);
1002 *bufpos -= n;
1003 return n;
1004}
1005
1006
1007ssize_t
1008fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1009{
1010 size_t num = BUFSIZE - *bufpos;
1011 ssize_t n;
1012
1013 n = read(fd, buf + *bufpos, num);
1014 /* don't treat EAGAIN, EINTR as error */
1015 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1016 n = -2;
1017 if (n <= 0)
1018 return n;
1019 *bufpos += n;
1020 return n;
1021}
1022
1023/*
1024 * fdpass()
1025 * Pass the connected file descriptor to stdout and exit.
1026 */
1027void
1028fdpass(int nfd)
1029{
1030 struct msghdr mh;
1031 union {
1032 struct cmsghdr hdr;
1033 char buf[CMSG_SPACE(sizeof(int))];
1034 } cmsgbuf;
1035 struct cmsghdr *cmsg;
1036 struct iovec iov;
1037 char c = '\0';
1038 ssize_t r;
1039 struct pollfd pfd;
1040
1041 /* Avoid obvious stupidity */
1042 if (isatty(STDOUT_FILENO))
1043 errx(1, "Cannot pass file descriptor to tty");
1044
1045 bzero(&mh, sizeof(mh));
1046 bzero(&cmsgbuf, sizeof(cmsgbuf));
1047 bzero(&iov, sizeof(iov));
1048
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;
1056
1057 iov.iov_base = &c;
1058 iov.iov_len = 1;
1059 mh.msg_iov = &iov;
1060 mh.msg_iovlen = 1;
1061
1062 bzero(&pfd, sizeof(pfd));
1063 pfd.fd = STDOUT_FILENO;
1064 pfd.events = POLLOUT;
1065 for (;;) {
1066 r = sendmsg(STDOUT_FILENO, &mh, 0);
1067 if (r == -1) {
1068 if (errno == EAGAIN || errno == EINTR) {
1069 if (poll(&pfd, 1, -1) == -1)
1070 err(1, "poll");
1071 continue;
1072 }
1073 err(1, "sendmsg");
1074 } else if (r != 1)
1075 errx(1, "sendmsg: unexpected return value %zd", r);
1076 else
1077 break;
1078 }
1079 exit(0);
1080}
1081
1082/* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1083void
1084atelnet(int nfd, unsigned char *buf, unsigned int size)
1085{
1086 unsigned char *p, *end;
1087 unsigned char obuf[4];
1088
647/* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
648void
649atelnet(int nfd, unsigned char *buf, unsigned int size)
650{
651 unsigned char *p, *end;
652 unsigned char obuf[4];
653
1089 if (size < 3)
1090 return;
1091 end = buf + size - 2;
654 end = buf + size;
655 obuf[0] = '\0';
1092
1093 for (p = buf; p < end; p++) {
1094 if (*p != IAC)
656
657 for (p = buf; p < end; p++) {
658 if (*p != IAC)
1095 continue;
659 break;
1096
1097 obuf[0] = IAC;
1098 p++;
1099 if ((*p == WILL) || (*p == WONT))
1100 obuf[1] = DONT;
660
661 obuf[0] = IAC;
662 p++;
663 if ((*p == WILL) || (*p == WONT))
664 obuf[1] = DONT;
1101 else if ((*p == DO) || (*p == DONT))
665 if ((*p == DO) || (*p == DONT))
1102 obuf[1] = WONT;
666 obuf[1] = WONT;
1103 else
1104 continue;
1105
1106 p++;
1107 obuf[2] = *p;
1108 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1109 warn("Write Error!");
667 if (obuf) {
668 p++;
669 obuf[2] = *p;
670 obuf[3] = '\0';
671 if (atomicio((ssize_t (*)(int, void *, size_t))write,
672 nfd, obuf, 3) != 3)
673 warnx("Write Error!");
674 obuf[0] = '\0';
675 }
1110 }
1111}
1112
1113/*
1114 * build_ports()
676 }
677}
678
679/*
680 * build_ports()
1115 * Build an array of ports in portlist[], listing each port
681 * Build an array or ports in portlist[], listing each port
1116 * that we should try to connect to.
1117 */
1118void
1119build_ports(char *p)
1120{
682 * that we should try to connect to.
683 */
684void
685build_ports(char *p)
686{
1121 const char *errstr;
1122 char *n;
687 char *n, *endp;
1123 int hi, lo, cp;
1124 int x = 0;
1125
1126 if ((n = strchr(p, '-')) != NULL) {
688 int hi, lo, cp;
689 int x = 0;
690
691 if ((n = strchr(p, '-')) != NULL) {
692 if (lflag)
693 errx(1, "Cannot use -l with multiple ports!");
694
1127 *n = '\0';
1128 n++;
1129
1130 /* Make sure the ports are in order: lowest->highest. */
695 *n = '\0';
696 n++;
697
698 /* Make sure the ports are in order: lowest->highest. */
1131 hi = strtonum(n, 1, PORT_MAX, &errstr);
1132 if (errstr)
1133 errx(1, "port number %s: %s", errstr, n);
1134 lo = strtonum(p, 1, PORT_MAX, &errstr);
1135 if (errstr)
1136 errx(1, "port number %s: %s", errstr, p);
699 hi = (int)strtoul(n, &endp, 10);
700 if (hi <= 0 || hi > PORT_MAX || *endp != '\0')
701 errx(1, "port range not valid");
702 lo = (int)strtoul(p, &endp, 10);
703 if (lo <= 0 || lo > PORT_MAX || *endp != '\0')
704 errx(1, "port range not valid");
1137
1138 if (lo > hi) {
1139 cp = hi;
1140 hi = lo;
1141 lo = cp;
1142 }
1143
1144 /* Load ports sequentially. */

--- 13 unchanged lines hidden (view full) ---

1158 for (x = 0; x <= (hi - lo); x++) {
1159 y = (arc4random() & 0xFFFF) % (hi - lo);
1160 c = portlist[x];
1161 portlist[x] = portlist[y];
1162 portlist[y] = c;
1163 }
1164 }
1165 } else {
705
706 if (lo > hi) {
707 cp = hi;
708 hi = lo;
709 lo = cp;
710 }
711
712 /* Load ports sequentially. */

--- 13 unchanged lines hidden (view full) ---

726 for (x = 0; x <= (hi - lo); x++) {
727 y = (arc4random() & 0xFFFF) % (hi - lo);
728 c = portlist[x];
729 portlist[x] = portlist[y];
730 portlist[y] = c;
731 }
732 }
733 } else {
1166 hi = strtonum(p, 1, PORT_MAX, &errstr);
1167 if (errstr)
1168 errx(1, "port number %s: %s", errstr, p);
1169 portlist[0] = strdup(p);
734 hi = (int)strtoul(p, &endp, 10);
735 if (hi <= 0 || hi > PORT_MAX || *endp != '\0')
736 errx(1, "port range not valid");
737 portlist[0] = calloc(1, PORT_MAX_LEN);
1170 if (portlist[0] == NULL)
1171 err(1, NULL);
738 if (portlist[0] == NULL)
739 err(1, NULL);
740 portlist[0] = p;
1172 }
1173}
1174
1175/*
1176 * udptest()
1177 * Do a few writes to see if the UDP port is there.
741 }
742}
743
744/*
745 * udptest()
746 * Do a few writes to see if the UDP port is there.
1178 * Fails once PF state table is full.
747 * XXX - Better way of doing this? Doesn't work for IPv6.
748 * Also fails after around 100 ports checked.
1179 */
1180int
1181udptest(int s)
1182{
1183 int i, ret;
1184
1185 for (i = 0; i <= 3; i++) {
1186 if (write(s, "X", 1) == 1)
1187 ret = 1;
1188 else
1189 ret = -1;
1190 }
1191 return (ret);
1192}
1193
1194void
749 */
750int
751udptest(int s)
752{
753 int i, ret;
754
755 for (i = 0; i <= 3; i++) {
756 if (write(s, "X", 1) == 1)
757 ret = 1;
758 else
759 ret = -1;
760 }
761 return (ret);
762}
763
764void
1195set_common_sockopts(int s, int af)
1196{
1197 int x = 1;
1198
1199 if (Sflag) {
1200 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1201 &x, sizeof(x)) == -1)
1202 err(1, NULL);
1203 }
1204 if (Dflag) {
1205 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1206 &x, sizeof(x)) == -1)
1207 err(1, NULL);
1208 }
1209 if (Tflag != -1) {
1210 int proto, option;
1211
1212 if (af == AF_INET6) {
1213 proto = IPPROTO_IPV6;
1214 option = IPV6_TCLASS;
1215 } else {
1216 proto = IPPROTO_IP;
1217 option = IP_TOS;
1218 }
1219
1220 if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1221 err(1, "set IP ToS");
1222 }
1223 if (Iflag) {
1224 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1225 &Iflag, sizeof(Iflag)) == -1)
1226 err(1, "set TCP receive buffer size");
1227 }
1228 if (Oflag) {
1229 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1230 &Oflag, sizeof(Oflag)) == -1)
1231 err(1, "set TCP send buffer size");
1232 }
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");
1237 }
1238}
1239
1240int
1241map_tos(char *s, int *val)
1242{
1243 /* DiffServ Codepoints and other TOS mappings */
1244 const struct toskeywords {
1245 const char *keyword;
1246 int val;
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 },
1275 { NULL, -1 },
1276 };
1277
1278 for (t = toskeywords; t->keyword != NULL; t++) {
1279 if (strcmp(s, t->keyword) == 0) {
1280 *val = t->val;
1281 return (1);
1282 }
1283 }
1284
1285 return (0);
1286}
1287
1288void
1289report_connect(const struct sockaddr *sa, socklen_t salen)
1290{
1291 char remote_host[NI_MAXHOST];
1292 char remote_port[NI_MAXSERV];
1293 int herr;
1294 int flags = NI_NUMERICSERV;
1295
1296 if (nflag)
1297 flags |= NI_NUMERICHOST;
1298
1299 if ((herr = getnameinfo(sa, salen,
1300 remote_host, sizeof(remote_host),
1301 remote_port, sizeof(remote_port),
1302 flags)) != 0) {
1303 if (herr == EAI_SYSTEM)
1304 err(1, "getnameinfo");
1305 else
1306 errx(1, "getnameinfo: %s", gai_strerror(herr));
1307 }
1308
1309 fprintf(stderr,
1310 "Connection from %s %s "
1311 "received!\n", remote_host, remote_port);
1312}
1313
1314void
1315help(void)
1316{
1317 usage(0);
1318 fprintf(stderr, "\tCommand Summary:\n\
1319 \t-4 Use IPv4\n\
1320 \t-6 Use IPv6\n\
1321 \t-D Enable the debug socket option\n\
765help(void)
766{
767 usage(0);
768 fprintf(stderr, "\tCommand Summary:\n\
769 \t-4 Use IPv4\n\
770 \t-6 Use IPv6\n\
771 \t-D Enable the debug socket option\n\
1322 \t-d Detach from stdin\n");
1323#ifdef IPSEC
1324 fprintf(stderr, "\
1325 \t-E Use IPsec ESP\n\
1326 \t-e policy Use specified IPsec policy\n");
1327#endif
1328 fprintf(stderr, "\
1329 \t-F Pass socket fd\n\
772 \t-d Detach from stdin\n\
1330 \t-h This help text\n\
773 \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\
774 \t-i secs\t Delay interval for lines sent, ports scanned\n\
775 \t-k Keep inbound sockets open for multiple connects\n\
776 \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\
777 \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\
778 \t-p port\t Specify local port for remote connects\n\
779 \t-r Randomize remote ports\n\
780 \t-S Enable the TCP MD5 signature option\n\
781 \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\
1347 \t-u UDP mode\n\
782 \t-t Answer TELNET negotiation\n\
783 \t-U Use UNIX domain socket\n\
784 \t-u UDP mode\n\
1348 \t-V rtable Specify alternate routing table\n\
1349 \t-v Verbose\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");
785 \t-v Verbose\n\
786 \t-w secs\t Timeout for connects and final net reads\n\
787 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
788 \t-x addr[:port]\tSpecify proxy address and port\n\
789 \t-z Zero-I/O mode [used for scanning]\n\
790 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1355#ifdef IPSEC
1356 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
1357#endif
1358 exit(1);
1359}
1360
791 exit(1);
792}
793
1361#ifdef IPSEC
1362void
794void
1363add_ipsec_policy(int s, char *policy)
1364{
1365 char *raw;
1366 int e;
1367
1368 raw = ipsec_set_policy(policy, strlen(policy));
1369 if (raw == NULL)
1370 errx(1, "ipsec_set_policy `%s': %s", policy,
1371 ipsec_strerror());
1372 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1373 ipsec_get_policylen(raw));
1374 if (e < 0)
1375 err(1, "ipsec policy cannot be configured");
1376 free(raw);
1377 if (vflag)
1378 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1379 return;
1380}
1381#endif /* IPSEC */
1382
1383void
1384usage(int ret)
1385{
795usage(int ret)
796{
1386 fprintf(stderr,
1387#ifdef IPSEC
1388 "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1389#else
1390 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1391#endif
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");
797 fprintf(stderr, "usage: nc [-46DdhklnrStUuvz] [-i interval] [-p source_port]\n");
798 fprintf(stderr, "\t [-s source_ip_address] [-w timeout] [-X proxy_version]\n");
799 fprintf(stderr, "\t [-x proxy_address[:port]] [hostname] [port[s]]\n");
1395 if (ret)
1396 exit(1);
1397}
800 if (ret)
801 exit(1);
802}