python3: update to 3.11.10
[openadk.git] / package / netcat-openbsd / src / netcat.c
blobbd7344fb46c2e09604dec537cca657e02f7af671
1 /* $OpenBSD: netcat.c,v 1.217 2020/02/12 14:46:36 schwarze Exp $ */
2 /*
3 * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
4 * Copyright (c) 2015 Bob Beck. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 * Re-written nc(1) for OpenBSD. Original implementation by
32 * *Hobbit* <hobbit@avian.org>.
35 #define _GNU_SOURCE
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/uio.h>
40 #include <sys/un.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <netinet/ip.h>
45 #include <arpa/telnet.h>
46 #ifdef __linux__
47 # include <linux/in6.h>
48 #endif
49 #if defined(TCP_MD5SIG_EXT) && defined(TCP_MD5SIG_MAXKEYLEN)
50 # include <bsd/readpassphrase.h>
51 #endif
53 #ifndef IPTOS_LOWDELAY
54 # define IPTOS_LOWDELAY 0x10
55 # define IPTOS_THROUGHPUT 0x08
56 # define IPTOS_RELIABILITY 0x04
57 # define IPTOS_LOWCOST 0x02
58 # define IPTOS_MINCOST IPTOS_LOWCOST
59 #endif /* IPTOS_LOWDELAY */
61 # ifndef IPTOS_DSCP_AF11
62 # define IPTOS_DSCP_AF11 0x28
63 # define IPTOS_DSCP_AF12 0x30
64 # define IPTOS_DSCP_AF13 0x38
65 # define IPTOS_DSCP_AF21 0x48
66 # define IPTOS_DSCP_AF22 0x50
67 # define IPTOS_DSCP_AF23 0x58
68 # define IPTOS_DSCP_AF31 0x68
69 # define IPTOS_DSCP_AF32 0x70
70 # define IPTOS_DSCP_AF33 0x78
71 # define IPTOS_DSCP_AF41 0x88
72 # define IPTOS_DSCP_AF42 0x90
73 # define IPTOS_DSCP_AF43 0x98
74 # define IPTOS_DSCP_EF 0xb8
75 #endif /* IPTOS_DSCP_AF11 */
77 #ifndef IPTOS_DSCP_CS0
78 # define IPTOS_DSCP_CS0 0x00
79 # define IPTOS_DSCP_CS1 0x20
80 # define IPTOS_DSCP_CS2 0x40
81 # define IPTOS_DSCP_CS3 0x60
82 # define IPTOS_DSCP_CS4 0x80
83 # define IPTOS_DSCP_CS5 0xa0
84 # define IPTOS_DSCP_CS6 0xc0
85 # define IPTOS_DSCP_CS7 0xe0
86 #endif /* IPTOS_DSCP_CS0 */
88 #ifndef IPTOS_DSCP_EF
89 # define IPTOS_DSCP_EF 0xb8
90 #endif /* IPTOS_DSCP_EF */
93 #include <ctype.h>
94 #include <err.h>
95 #include <errno.h>
96 #include <fcntl.h>
97 #include <limits.h>
98 #include <netdb.h>
99 #include <poll.h>
100 #include <signal.h>
101 #include <stddef.h>
102 #include <stdarg.h>
103 #include <stdio.h>
104 #include <stdlib.h>
105 #include <string.h>
106 #include <time.h>
107 #ifdef TLS
108 # include <tls.h>
109 #endif
110 #include <unistd.h>
111 #include <bsd/stdlib.h>
112 #include <bsd/string.h>
114 #include "atomicio.h"
116 #define PORT_MAX 65535
117 #define UNIX_DG_TMP_SOCKET_SIZE 19
119 #define POLL_STDIN 0
120 #define POLL_NETOUT 1
121 #define POLL_NETIN 2
122 #define POLL_STDOUT 3
123 #define BUFSIZE 16384
125 #ifdef TLS
126 # define TLS_NOVERIFY (1 << 1)
127 # define TLS_NONAME (1 << 2)
128 # define TLS_CCERT (1 << 3)
129 # define TLS_MUSTSTAPLE (1 << 4)
130 #endif
132 #define CONNECTION_SUCCESS 0
133 #define CONNECTION_FAILED 1
134 #define CONNECTION_TIMEOUT 2
136 #define UDP_SCAN_TIMEOUT 3 /* Seconds */
138 /* Command Line Options */
139 int bflag; /* Allow Broadcast */
140 int dflag; /* detached, no stdin */
141 int Fflag; /* fdpass sock to stdout */
142 unsigned int iflag; /* Interval Flag */
143 int kflag; /* More than one connect */
144 int lflag; /* Bind to local port */
145 int Nflag; /* shutdown() network socket */
146 int nflag; /* Don't do name look up */
147 char *Pflag; /* Proxy username */
148 char *pflag; /* Localport flag */
149 int qflag = -1; /* Quit after some secs */
150 int rflag; /* Random ports flag */
151 char *sflag; /* Source Address */
152 int tflag; /* Telnet Emulation */
153 int uflag; /* UDP - Default to TCP */
154 int dccpflag; /* DCCP - Default to TCP */
155 int vflag; /* Verbosity */
156 int xflag; /* Socks proxy */
157 int zflag; /* Port Scan Flag */
158 int Dflag; /* sodebug */
159 int Iflag; /* TCP receive buffer size */
160 int Oflag; /* TCP send buffer size */
161 int Sflag; /* TCP MD5 signature option */
162 int Tflag = -1; /* IP Type of Service */
163 int rtableid = -1;
165 # if defined(TLS)
166 int usetls; /* use TLS */
167 const char *Cflag; /* Public cert file */
168 const char *Kflag; /* Private key file */
169 const char *oflag; /* OCSP stapling file */
170 const char *Rflag; /* Root CA file */
171 int tls_cachanged; /* Using non-default CA file */
172 int TLSopt; /* TLS options */
173 char *tls_expectname; /* required name in peer cert */
174 char *tls_expecthash; /* required hash of peer cert */
175 char *tls_ciphers; /* TLS ciphers */
176 char *tls_protocols; /* TLS protocols */
177 FILE *Zflag; /* file to save peer cert */
178 # else
179 int Cflag = 0; /* CRLF line-ending */
180 # endif
182 # if defined(TCP_MD5SIG_EXT) && defined(TCP_MD5SIG_MAXKEYLEN)
183 char Sflag_password[TCP_MD5SIG_MAXKEYLEN];
184 # endif
185 int recvcount, recvlimit;
186 int timeout = -1;
187 int family = AF_UNSPEC;
188 char *portlist[PORT_MAX+1];
189 char *unix_dg_tmp_socket;
190 int ttl = -1;
191 int minttl = -1;
193 void atelnet(int, unsigned char *, unsigned int);
194 int strtoport(char *portstr, int udp);
195 void build_ports(char **);
196 void help(void) __attribute__((noreturn));
197 int local_listen(const char *, const char *, struct addrinfo);
198 # if defined(TLS)
199 void readwrite(int, struct tls *);
200 # else
201 void readwrite(int);
202 # endif
203 void fdpass(int nfd) __attribute__((noreturn));
204 int remote_connect(const char *, const char *, struct addrinfo, char *);
205 # if defined(TLS)
206 int timeout_tls(int, struct tls *, int (*)(struct tls *));
207 # endif
208 int timeout_connect(int, const struct sockaddr *, socklen_t);
209 int socks_connect(const char *, const char *, struct addrinfo,
210 const char *, const char *, struct addrinfo, int, const char *);
211 int udptest(int);
212 int unix_bind(char *, int);
213 int unix_connect(char *);
214 int unix_listen(char *);
215 void set_common_sockopts(int, const struct sockaddr *);
216 int process_tos_opt(char *, int *);
217 # if defined(TLS)
218 int process_tls_opt(char *, int *);
219 void save_peer_cert(struct tls *_tls_ctx, FILE *_fp);
220 # endif
221 void report_sock(const char *, const struct sockaddr *, socklen_t, char *);
222 # if defined(TLS)
223 void report_tls(struct tls *tls_ctx, char * host);
224 # endif
225 void usage(int);
226 # if defined(TLS)
227 ssize_t drainbuf(int, unsigned char *, size_t *, struct tls *);
228 ssize_t fillbuf(int, unsigned char *, size_t *, struct tls *);
229 void tls_setup_client(struct tls *, int, char *);
230 struct tls *tls_setup_server(struct tls *, int, char *);
231 # else
232 ssize_t drainbuf(int, unsigned char *, size_t *, int);
233 ssize_t fillbuf(int, unsigned char *, size_t *);
234 # endif
236 char *proto_name(int uflag, int dccpflag);
237 static int connect_with_timeout(int fd, const struct sockaddr *sa,
238 socklen_t salen, int ctimeout);
240 static void quit();
243 main(int argc, char *argv[])
245 int ch, s = -1, ret, socksv;
246 char *host, **uport;
247 char ipaddr[NI_MAXHOST];
248 struct addrinfo hints;
249 struct servent *sv;
250 socklen_t len;
251 union {
252 struct sockaddr_storage storage;
253 struct sockaddr_un forunix;
254 } cliaddr;
255 char *proxy = NULL, *proxyport = NULL;
256 const char *errstr;
257 struct addrinfo proxyhints;
258 char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
259 # if defined(TLS)
260 struct tls_config *tls_cfg = NULL;
261 struct tls *tls_ctx = NULL;
262 # endif
263 uint32_t protocols;
265 ret = 1;
266 socksv = 5;
267 host = NULL;
268 uport = NULL;
269 sv = NULL;
270 # if defined(TLS)
271 Rflag = tls_default_ca_cert_file();
272 # endif
274 signal(SIGPIPE, SIG_IGN);
276 while ((ch = getopt(argc, argv,
277 # if defined(TLS)
278 "46bC:cDde:FH:hI:i:K:klM:m:NnO:o:P:p:q:R:rSs:T:tUuV:vW:w:X:x:Z:z"))
279 # else
280 "46bCDdFhI:i:klM:m:NnO:P:p:q:rSs:T:tUuV:vW:w:X:x:Zz"))
281 # endif
282 != -1) {
283 switch (ch) {
284 case '4':
285 family = AF_INET;
286 break;
287 case '6':
288 family = AF_INET6;
289 break;
290 case 'b':
291 # if defined(SO_BROADCAST)
292 bflag = 1;
293 # else
294 errx(1, "no broadcast frame support available");
295 # endif
296 break;
297 case 'U':
298 family = AF_UNIX;
299 break;
300 case 'X':
301 if (strcasecmp(optarg, "connect") == 0)
302 socksv = -1; /* HTTP proxy CONNECT */
303 else if (strcmp(optarg, "4") == 0)
304 socksv = 4; /* SOCKS v.4 */
305 else if (strcmp(optarg, "5") == 0)
306 socksv = 5; /* SOCKS v.5 */
307 else
308 errx(1, "unsupported proxy protocol");
309 break;
310 # if defined(TLS)
311 case 'C':
312 Cflag = optarg;
313 break;
314 case 'c':
315 usetls = 1;
316 break;
317 # else
318 case 'C':
319 Cflag = 1;
320 break;
321 # endif
322 case 'd':
323 dflag = 1;
324 break;
325 # if defined(TLS)
326 case 'e':
327 tls_expectname = optarg;
328 break;
329 # endif
330 case 'F':
331 Fflag = 1;
332 break;
333 # if defined(TLS)
334 case 'H':
335 tls_expecthash = optarg;
336 break;
337 # endif
338 case 'h':
339 help();
340 break;
341 case 'i':
342 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
343 if (errstr)
344 errx(1, "interval %s: %s", errstr, optarg);
345 break;
346 # if defined(TLS)
347 case 'K':
348 Kflag = optarg;
349 break;
350 # endif
351 case 'k':
352 kflag = 1;
353 break;
354 case 'l':
355 lflag = 1;
356 break;
357 case 'M':
358 ttl = strtonum(optarg, 0, 255, &errstr);
359 if (errstr)
360 errx(1, "ttl is %s", errstr);
361 break;
362 case 'm':
363 minttl = strtonum(optarg, 0, 255, &errstr);
364 if (errstr)
365 errx(1, "minttl is %s", errstr);
366 break;
367 case 'N':
368 Nflag = 1;
369 break;
370 case 'n':
371 nflag = 1;
372 break;
373 case 'P':
374 Pflag = optarg;
375 break;
376 case 'p':
377 pflag = optarg;
378 break;
379 case 'q':
380 qflag = strtonum(optarg, INT_MIN, INT_MAX, &errstr);
381 if (errstr)
382 errx(1, "quit timer %s: %s", errstr, optarg);
383 if (qflag >= 0)
384 Nflag = 1;
385 break;
386 # if defined(TLS)
387 case 'R':
388 tls_cachanged = 1;
389 Rflag = optarg;
390 break;
391 # endif
392 case 'r':
393 rflag = 1;
394 break;
395 case 's':
396 sflag = optarg;
397 break;
398 case 't':
399 tflag = 1;
400 break;
401 case 'u':
402 uflag = 1;
403 break;
404 case 'Z':
405 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
406 dccpflag = 1;
407 # else
408 errx(1, "no DCCP support available");
409 # endif
410 break;
411 case 'V':
412 # if defined(RT_TABLEID_MAX)
413 rtableid = (int)strtonum(optarg, 0,
414 RT_TABLEID_MAX, &errstr);
415 if (errstr)
416 errx(1, "rtable %s: %s", errstr, optarg);
417 # else
418 errx(1, "no alternate routing table support available");
419 # endif
420 break;
421 case 'v':
422 vflag = 1;
423 break;
424 case 'W':
425 recvlimit = strtonum(optarg, 1, INT_MAX, &errstr);
426 if (errstr)
427 errx(1, "receive limit %s: %s", errstr, optarg);
428 break;
429 case 'w':
430 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
431 if (errstr)
432 errx(1, "timeout %s: %s", errstr, optarg);
433 timeout *= 1000;
434 break;
435 case 'x':
436 xflag = 1;
437 if ((proxy = strdup(optarg)) == NULL)
438 err(1, NULL);
439 break;
440 # if defined(TLS)
441 case 'Z':
442 if (strcmp(optarg, "-") == 0)
443 Zflag = stderr;
444 else if ((Zflag = fopen(optarg, "w")) == NULL)
445 err(1, "can't open %s", optarg);
446 break;
447 # endif
448 case 'z':
449 zflag = 1;
450 break;
451 case 'D':
452 Dflag = 1;
453 break;
454 case 'I':
455 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
456 if (errstr != NULL)
457 errx(1, "TCP receive window %s: %s",
458 errstr, optarg);
459 break;
460 case 'O':
461 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
462 if (errstr != NULL)
463 errx(1, "TCP send window %s: %s",
464 errstr, optarg);
465 break;
466 # if defined(TLS)
467 case 'o':
468 oflag = optarg;
469 break;
470 # endif
471 case 'S':
472 # if defined(TCP_MD5SIG_EXT) && defined(TCP_MD5SIG_MAXKEYLEN)
473 if (readpassphrase("TCP MD5SIG password: ",
474 Sflag_password, TCP_MD5SIG_MAXKEYLEN, RPP_REQUIRE_TTY) == NULL)
475 errx(1, "Unable to read TCP MD5SIG password");
476 Sflag = 1;
477 # else
478 errx(1, "no TCP MD5 signature support available");
479 # endif
480 break;
481 case 'T':
482 errstr = NULL;
483 errno = 0;
484 # if defined(TLS)
485 if (process_tls_opt(optarg, &TLSopt))
486 break;
487 # endif
488 if (process_tos_opt(optarg, &Tflag))
489 break;
490 if (strlen(optarg) > 1 && optarg[0] == '0' &&
491 optarg[1] == 'x')
492 Tflag = (int)strtol(optarg, NULL, 16);
493 else
494 Tflag = (int)strtonum(optarg, 0, 255,
495 &errstr);
496 if (Tflag < 0 || Tflag > 255 || errstr || errno)
497 # if defined(TLS)
498 errx(1, "illegal tos/tls value %s", optarg);
499 # else
500 errx(1, "illegal tos value %s", optarg);
501 # endif
502 break;
503 default:
504 usage(1);
507 argc -= optind;
508 argv += optind;
510 # if defined(RT_TABLEID_MAX)
511 if (rtableid >= 0)
512 if (setrtable(rtableid) == -1)
513 err(1, "setrtable");
514 # endif
516 /* Cruft to make sure options are clean, and used properly. */
517 if (argc == 0 && lflag) {
518 uport = &pflag;
519 host = sflag;
520 } else if (argc == 1 && !pflag &&
521 /* `nc -l 12345` or `nc -U bar` or `nc -uU -s foo bar` */
522 (!sflag || (family == AF_UNIX && uflag && !lflag))) {
523 if (family == AF_UNIX) {
524 host = argv[0];
525 uport = NULL;
526 } else if (lflag) {
527 host = NULL;
528 uport = argv;
530 } else if (argc >= 2) {
531 if (lflag && (pflag || sflag || argc > 2))
532 usage(1); /* conflict */
533 host = argv[0];
534 uport = &argv[1];
535 } else
536 usage(1);
538 if (family == AF_UNIX) {
539 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
540 if (dccpflag)
541 errx(1, "cannot use -Z and -U");
542 # endif
543 if (uport && *uport)
544 errx(1, "cannot use port with -U");
545 if (!host)
546 errx(1, "missing socket pathname");
547 } else if (!uport || !*uport)
548 errx(1, "missing port number");
550 if (lflag && zflag)
551 errx(1, "cannot use -z and -l");
553 # if defined(TLS)
554 if (usetls) {
555 if (Cflag && unveil(Cflag, "r") == -1)
556 err(1, "unveil");
557 if (unveil(Rflag, "r") == -1)
558 err(1, "unveil");
559 if (Kflag && unveil(Kflag, "r") == -1)
560 err(1, "unveil");
561 if (oflag && unveil(oflag, "r") == -1)
562 err(1, "unveil");
563 } else if (family == AF_UNIX && uflag && lflag && !kflag) {
565 * After recvfrom(2) from client, the server connects
566 * to the client socket. As the client path is determined
567 * during runtime, we cannot unveil(2).
569 } else {
570 if (family == AF_UNIX) {
571 if (unveil(host, "rwc") == -1)
572 err(1, "unveil");
573 if (uflag && !kflag) {
574 if (sflag) {
575 if (unveil(sflag, "rwc") == -1)
576 err(1, "unveil");
577 } else {
578 if (unveil("/tmp", "rwc") == -1)
579 err(1, "unveil");
582 } else {
583 /* no filesystem visibility */
584 if (unveil("/", "") == -1)
585 err(1, "unveil");
588 # endif
590 if (!lflag && kflag)
591 errx(1, "must use -l with -k");
592 # if defined(TLS)
593 if (uflag && usetls)
594 errx(1, "cannot use -c and -u");
595 if ((family == AF_UNIX) && usetls)
596 errx(1, "cannot use -c and -U");
597 # endif
598 if ((family == AF_UNIX) && Fflag)
599 errx(1, "cannot use -F and -U");
600 # if defined(TLS)
601 if (Fflag && usetls)
602 errx(1, "cannot use -c and -F");
603 if (TLSopt && !usetls)
604 errx(1, "you must specify -c to use TLS options");
605 if (Cflag && !usetls)
606 errx(1, "you must specify -c to use -C");
607 if (Kflag && !usetls)
608 errx(1, "you must specify -c to use -K");
609 if (Zflag && !usetls)
610 errx(1, "you must specify -c to use -Z");
611 if (oflag && !Cflag)
612 errx(1, "you must specify -C to use -o");
613 if (tls_cachanged && !usetls)
614 errx(1, "you must specify -c to use -R");
615 if (tls_expecthash && !usetls)
616 errx(1, "you must specify -c to use -H");
617 if (tls_expectname && !usetls)
618 errx(1, "you must specify -c to use -e");
619 # endif
621 /* Get name of temporary socket for unix datagram client */
622 if ((family == AF_UNIX) && uflag && !lflag) {
623 if (sflag) {
624 unix_dg_tmp_socket = sflag;
625 } else {
626 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
627 UNIX_DG_TMP_SOCKET_SIZE);
628 if (mkstemp(unix_dg_tmp_socket_buf) == -1)
629 err(1, "mkstemp");
630 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
634 /* Initialize addrinfo structure. */
635 if (family != AF_UNIX) {
636 memset(&hints, 0, sizeof(struct addrinfo));
637 hints.ai_family = family;
638 if (uflag) {
639 hints.ai_socktype = SOCK_DGRAM;
640 hints.ai_protocol = IPPROTO_UDP;
642 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
643 else if (dccpflag) {
644 hints.ai_socktype = SOCK_DCCP;
645 hints.ai_protocol = IPPROTO_DCCP;
647 # endif
648 else {
649 hints.ai_socktype = SOCK_STREAM;
650 hints.ai_protocol = IPPROTO_TCP;
652 if (nflag)
653 hints.ai_flags |= AI_NUMERICHOST;
656 if (xflag) {
657 if (uflag)
658 errx(1, "no proxy support for UDP mode");
659 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
660 if (dccpflag)
661 errx(1, "no proxy support for DCCP mode");
662 # endif
663 if (lflag)
664 errx(1, "no proxy support for listen");
666 if (family == AF_UNIX)
667 errx(1, "no proxy support for unix sockets");
669 if (sflag)
670 errx(1, "no proxy support for local source address");
672 if (*proxy == '[') {
673 ++proxy;
674 proxyport = strchr(proxy, ']');
675 if (proxyport == NULL)
676 errx(1, "missing closing bracket in proxy");
677 *proxyport++ = '\0';
678 if (*proxyport == '\0')
679 /* Use default proxy port. */
680 proxyport = NULL;
681 else {
682 if (*proxyport == ':')
683 ++proxyport;
684 else
685 errx(1, "garbage proxy port delimiter");
687 } else {
688 proxyport = strrchr(proxy, ':');
689 if (proxyport != NULL)
690 *proxyport++ = '\0';
693 memset(&proxyhints, 0, sizeof(struct addrinfo));
694 proxyhints.ai_family = family;
695 proxyhints.ai_socktype = SOCK_STREAM;
696 proxyhints.ai_protocol = IPPROTO_TCP;
697 if (nflag)
698 proxyhints.ai_flags |= AI_NUMERICHOST;
701 # if defined(TLS)
702 if (usetls) {
703 if ((tls_cfg = tls_config_new()) == NULL)
704 errx(1, "unable to allocate TLS config");
705 if (Rflag && tls_config_set_ca_file(tls_cfg, Rflag) == -1)
706 errx(1, "%s", tls_config_error(tls_cfg));
707 if (Cflag && tls_config_set_cert_file(tls_cfg, Cflag) == -1)
708 errx(1, "%s", tls_config_error(tls_cfg));
709 if (Kflag && tls_config_set_key_file(tls_cfg, Kflag) == -1)
710 errx(1, "%s", tls_config_error(tls_cfg));
711 if (oflag && tls_config_set_ocsp_staple_file(tls_cfg, oflag) == -1)
712 errx(1, "%s", tls_config_error(tls_cfg));
713 if (tls_config_parse_protocols(&protocols, tls_protocols) == -1)
714 errx(1, "invalid TLS protocols `%s'", tls_protocols);
715 if (tls_config_set_protocols(tls_cfg, protocols) == -1)
716 errx(1, "%s", tls_config_error(tls_cfg));
717 if (tls_config_set_ciphers(tls_cfg, tls_ciphers) == -1)
718 errx(1, "%s", tls_config_error(tls_cfg));
719 if (!lflag && (TLSopt & TLS_CCERT))
720 errx(1, "clientcert is only valid with -l");
721 if (TLSopt & TLS_NONAME)
722 tls_config_insecure_noverifyname(tls_cfg);
723 if (TLSopt & TLS_NOVERIFY) {
724 if (tls_expecthash != NULL)
725 errx(1, "-H and -T noverify may not be used "
726 "together");
727 tls_config_insecure_noverifycert(tls_cfg);
729 if (TLSopt & TLS_MUSTSTAPLE)
730 tls_config_ocsp_require_stapling(tls_cfg);
732 if (Pflag) {
733 if (pledge("stdio inet dns tty", NULL) == -1)
734 err(1, "pledge");
735 } else if (pledge("stdio inet dns", NULL) == -1)
736 err(1, "pledge");
738 # endif
739 if (lflag) {
740 ret = 0;
742 if (family == AF_UNIX) {
743 if (uflag)
744 s = unix_bind(host, 0);
745 else
746 s = unix_listen(host);
747 } else
748 s = local_listen(host, *uport, hints);
749 if (s < 0)
750 err(1, NULL);
752 # if defined(TLS)
753 if (usetls) {
754 tls_config_verify_client_optional(tls_cfg);
755 if ((tls_ctx = tls_server()) == NULL)
756 errx(1, "tls server creation failed");
757 if (tls_configure(tls_ctx, tls_cfg) == -1)
758 errx(1, "tls configuration failed (%s)",
759 tls_error(tls_ctx));
761 # endif
762 /* Allow only one connection at a time, but stay alive. */
763 for (;;) {
764 if (uflag && kflag) {
766 * For UDP and -k, don't connect the socket,
767 * let it receive datagrams from multiple
768 * socket pairs.
770 # if defined(TLS)
771 readwrite(s, NULL);
772 # else
773 readwrite(s);
774 # endif
775 } else if (uflag && !kflag) {
777 * For UDP and not -k, we will use recvfrom()
778 * initially to wait for a caller, then use
779 * the regular functions to talk to the caller.
781 int rv;
782 char buf[2048];
783 struct sockaddr_storage z;
785 len = sizeof(z);
786 rv = recvfrom(s, buf, sizeof(buf), MSG_PEEK,
787 (struct sockaddr *)&z, &len);
788 if (rv == -1)
789 err(1, "recvfrom");
791 rv = connect(s, (struct sockaddr *)&z, len);
792 if (rv == -1)
793 err(1, "connect");
795 if (vflag)
796 report_sock("Connection received",
797 (struct sockaddr *)&z, len,
798 family == AF_UNIX ? host : NULL);
800 # if defined(TLS)
801 readwrite(s, NULL);
802 } else {
803 struct tls *tls_cctx = NULL;
804 # else
805 readwrite(s);
806 } else {
807 # endif
808 int connfd;
810 len = sizeof(cliaddr);
811 connfd = accept4(s, (struct sockaddr *)&cliaddr,
812 &len, SOCK_NONBLOCK);
813 if (connfd == -1) {
814 /* For now, all errnos are fatal */
815 err(1, "accept");
817 if (vflag)
818 report_sock("Connection received",
819 (struct sockaddr *)&cliaddr, len,
820 family == AF_UNIX ? host : NULL);
821 # if defined(TLS)
822 if ((usetls) &&
823 (tls_cctx = tls_setup_server(tls_ctx, connfd, host)))
824 readwrite(connfd, tls_cctx);
825 if (!usetls)
826 readwrite(connfd, NULL);
827 if (tls_cctx)
828 timeout_tls(s, tls_cctx, tls_close);
829 close(connfd);
830 tls_free(tls_cctx);
831 # else
832 readwrite(connfd);
833 close(connfd);
834 # endif
836 if (family == AF_UNIX && uflag) {
837 if (connect(s, NULL, 0) == -1)
838 err(1, "connect");
841 if (!kflag) {
842 if (s != -1)
843 close(s);
844 break;
847 } else if (family == AF_UNIX) {
848 ret = 0;
850 if ((s = unix_connect(host)) > 0) {
851 if (!zflag)
852 # if defined(TLS)
853 readwrite(s, NULL);
854 # else
855 readwrite(s);
856 # endif
857 close(s);
858 } else {
859 warn("%s", host);
860 ret = 1;
863 if (uflag)
864 unlink(unix_dg_tmp_socket);
865 return ret;
867 } else {
868 int i = 0;
870 /* Construct the portlist[] array. */
871 build_ports(uport);
873 /* Cycle through portlist, connecting to each port. */
874 for (s = -1, i = 0; portlist[i] != NULL; i++) {
875 if (s != -1)
876 close(s);
877 # if defined(TLS)
878 tls_free(tls_ctx);
879 tls_ctx = NULL;
881 if (usetls) {
882 if ((tls_ctx = tls_client()) == NULL)
883 errx(1, "tls client creation failed");
884 if (tls_configure(tls_ctx, tls_cfg) == -1)
885 errx(1, "tls configuration failed (%s)",
886 tls_error(tls_ctx));
888 # endif
889 if (xflag)
890 s = socks_connect(host, portlist[i], hints,
891 proxy, proxyport, proxyhints, socksv,
892 Pflag);
893 else
894 s = remote_connect(host, portlist[i], hints,
895 ipaddr);
897 if (s == -1)
898 continue;
900 ret = 0;
901 if (vflag) {
902 /* For UDP, make sure we are connected. */
903 if (uflag) {
904 if (udptest(s) == -1) {
905 ret = 1;
906 continue;
910 char *proto = proto_name(uflag, dccpflag);
911 /* Don't look up port if -n. */
912 if (nflag)
913 sv = NULL;
914 else {
915 sv = getservbyport(
916 ntohs(atoi(portlist[i])),
917 proto);
920 fprintf(stderr, "Connection to %s", host);
923 * if we aren't connecting thru a proxy and
924 * there is something to report, print IP
926 if (!nflag && !xflag
927 && (strcmp(host, ipaddr) != 0))
928 fprintf(stderr, " (%s)", ipaddr);
930 fprintf(stderr, " %s port [%s/%s] succeeded!\n",
931 portlist[i], proto,
932 sv ? sv->s_name : "*");
934 if (Fflag)
935 fdpass(s);
936 # if defined(TLS)
937 else {
938 if (usetls)
939 tls_setup_client(tls_ctx, s, host);
940 if (!zflag)
941 readwrite(s, tls_ctx);
942 if (tls_ctx)
943 timeout_tls(s, tls_ctx, tls_close);
945 # else
946 else if (!zflag)
947 readwrite(s);
948 # endif
952 if (s != -1)
953 close(s);
954 # if defined(TLS)
955 tls_free(tls_ctx);
956 tls_config_free(tls_cfg);
957 # endif
959 return ret;
963 * unix_bind()
964 * Returns a unix socket bound to the given path
967 unix_bind(char *path, int flags)
969 struct sockaddr_un s_un;
970 int s, save_errno;
972 /* Create unix domain socket. */
973 if ((s = socket(AF_UNIX, flags | (uflag ? SOCK_DGRAM : SOCK_STREAM),
974 0)) == -1)
975 return -1;
977 unlink(path);
979 memset(&s_un, 0, sizeof(struct sockaddr_un));
980 s_un.sun_family = AF_UNIX;
982 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
983 sizeof(s_un.sun_path)) {
984 close(s);
985 errno = ENAMETOOLONG;
986 return -1;
989 if (bind(s, (struct sockaddr *)&s_un, sizeof(s_un)) == -1) {
990 save_errno = errno;
991 close(s);
992 errno = save_errno;
993 return -1;
995 if (vflag)
996 report_sock("Bound", NULL, 0, path);
998 return s;
1001 # if defined(TLS)
1003 timeout_tls(int s, struct tls *tls_ctx, int (*func)(struct tls *))
1005 struct pollfd pfd;
1006 int ret;
1008 while ((ret = (*func)(tls_ctx)) != 0) {
1009 if (ret == TLS_WANT_POLLIN)
1010 pfd.events = POLLIN;
1011 else if (ret == TLS_WANT_POLLOUT)
1012 pfd.events = POLLOUT;
1013 else
1014 break;
1015 pfd.fd = s;
1016 if ((ret = poll(&pfd, 1, timeout)) == 1)
1017 continue;
1018 else if (ret == 0) {
1019 errno = ETIMEDOUT;
1020 ret = -1;
1021 break;
1022 } else
1023 err(1, "poll failed");
1026 return ret;
1029 void
1030 tls_setup_client(struct tls *tls_ctx, int s, char *host)
1032 const char *errstr;
1034 if (tls_connect_socket(tls_ctx, s,
1035 tls_expectname ? tls_expectname : host) == -1) {
1036 errx(1, "tls connection failed (%s)",
1037 tls_error(tls_ctx));
1039 if (timeout_tls(s, tls_ctx, tls_handshake) == -1) {
1040 if ((errstr = tls_error(tls_ctx)) == NULL)
1041 errstr = strerror(errno);
1042 errx(1, "tls handshake failed (%s)", errstr);
1044 if (vflag)
1045 report_tls(tls_ctx, host);
1046 if (tls_expecthash && (tls_peer_cert_hash(tls_ctx) == NULL ||
1047 strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0))
1048 errx(1, "peer certificate is not %s", tls_expecthash);
1049 if (Zflag) {
1050 save_peer_cert(tls_ctx, Zflag);
1051 if (Zflag != stderr && (fclose(Zflag) != 0))
1052 err(1, "fclose failed saving peer cert");
1056 struct tls *
1057 tls_setup_server(struct tls *tls_ctx, int connfd, char *host)
1059 struct tls *tls_cctx;
1060 const char *errstr;
1062 if (tls_accept_socket(tls_ctx, &tls_cctx, connfd) == -1) {
1063 warnx("tls accept failed (%s)", tls_error(tls_ctx));
1064 } else if (timeout_tls(connfd, tls_cctx, tls_handshake) == -1) {
1065 if ((errstr = tls_error(tls_cctx)) == NULL)
1066 errstr = strerror(errno);
1067 warnx("tls handshake failed (%s)", errstr);
1068 } else {
1069 int gotcert = tls_peer_cert_provided(tls_cctx);
1071 if (vflag && gotcert)
1072 report_tls(tls_cctx, host);
1073 if ((TLSopt & TLS_CCERT) && !gotcert)
1074 warnx("No client certificate provided");
1075 else if (gotcert && tls_expecthash &&
1076 (tls_peer_cert_hash(tls_cctx) == NULL ||
1077 strcmp(tls_expecthash, tls_peer_cert_hash(tls_cctx)) != 0))
1078 warnx("peer certificate is not %s", tls_expecthash);
1079 else if (gotcert && tls_expectname &&
1080 (!tls_peer_cert_contains_name(tls_cctx, tls_expectname)))
1081 warnx("name (%s) not found in client cert",
1082 tls_expectname);
1083 else {
1084 return tls_cctx;
1087 return NULL;
1089 # endif
1092 * unix_connect()
1093 * Returns a socket connected to a local unix socket. Returns -1 on failure.
1096 unix_connect(char *path)
1098 struct sockaddr_un s_un;
1099 int s, save_errno;
1101 if (uflag) {
1102 if ((s = unix_bind(unix_dg_tmp_socket, SOCK_CLOEXEC)) == -1)
1103 return -1;
1104 } else {
1105 if ((s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1) {
1106 errx(1, "create unix socket failed");
1107 return -1;
1111 memset(&s_un, 0, sizeof(struct sockaddr_un));
1112 s_un.sun_family = AF_UNIX;
1114 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
1115 sizeof(s_un.sun_path)) {
1116 close(s);
1117 errno = ENAMETOOLONG;
1118 warn("unix connect abandoned");
1119 return -1;
1121 if (connect(s, (struct sockaddr *)&s_un, sizeof(s_un)) == -1) {
1122 save_errno = errno;
1123 warn("unix connect failed");
1124 close(s);
1125 errno = save_errno;
1126 return -1;
1128 return s;
1133 * unix_listen()
1134 * Create a unix domain socket, and listen on it.
1137 unix_listen(char *path)
1139 int s;
1141 if ((s = unix_bind(path, 0)) == -1)
1142 return -1;
1143 if (listen(s, 5) == -1) {
1144 close(s);
1145 return -1;
1147 if (vflag)
1148 report_sock("Listening", NULL, 0, path);
1150 return s;
1153 char *proto_name(int uflag, int dccpflag) {
1155 char *proto = NULL;
1156 if (uflag) {
1157 proto = "udp";
1159 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
1160 else if (dccpflag) {
1161 proto = "dccp";
1163 # endif
1164 else {
1165 proto = "tcp";
1168 return proto;
1172 * remote_connect()
1173 * Returns a socket connected to a remote host. Properly binds to a local
1174 * port or source address if needed. Returns -1 on failure.
1177 remote_connect(const char *host, const char *port, struct addrinfo hints,
1178 char *ipaddr)
1180 struct addrinfo *res, *res0;
1181 int s = -1, error, herr, on = 1, save_errno;
1183 if ((error = getaddrinfo(host, port, &hints, &res0)))
1184 errx(1, "getaddrinfo for host \"%s\" port %s: %s", host,
1185 port, gai_strerror(error));
1187 for (res = res0; res; res = res->ai_next) {
1188 if ((s = socket(res->ai_family, res->ai_socktype |
1189 SOCK_NONBLOCK, res->ai_protocol)) == -1)
1190 continue;
1192 /* Bind to a local port or source address if specified. */
1193 if (sflag || pflag) {
1194 struct addrinfo ahints, *ares;
1196 # if defined (SO_BINDANY)
1197 /* try SO_BINDANY, but don't insist */
1198 setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
1199 # endif
1200 memset(&ahints, 0, sizeof(struct addrinfo));
1201 ahints.ai_family = res->ai_family;
1202 if (uflag) {
1203 ahints.ai_socktype = SOCK_DGRAM;
1204 ahints.ai_protocol = IPPROTO_UDP;
1207 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
1208 else if (dccpflag) {
1209 hints.ai_socktype = SOCK_DCCP;
1210 hints.ai_protocol = IPPROTO_DCCP;
1212 # endif
1213 else {
1214 ahints.ai_socktype = SOCK_STREAM;
1215 ahints.ai_protocol = IPPROTO_TCP;
1217 ahints.ai_flags = AI_PASSIVE;
1218 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
1219 errx(1, "getaddrinfo: %s", gai_strerror(error));
1221 if (bind(s, (struct sockaddr *)ares->ai_addr,
1222 ares->ai_addrlen) == -1)
1223 err(1, "bind failed");
1224 freeaddrinfo(ares);
1227 set_common_sockopts(s, res->ai_addr);
1229 if (ipaddr != NULL) {
1230 herr = getnameinfo(res->ai_addr, res->ai_addrlen,
1231 ipaddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1232 switch (herr) {
1233 case 0:
1234 break;
1235 case EAI_SYSTEM:
1236 err(1, "getnameinfo");
1237 default:
1238 errx(1, "getnameinfo: %s", gai_strerror(herr));
1242 if ((error = connect_with_timeout(s, res->ai_addr, res->ai_addrlen,
1243 timeout)) == CONNECTION_SUCCESS)
1244 break;
1246 char *proto = proto_name(uflag, dccpflag);
1248 if (vflag) {
1249 /* only print IP if there is something to report */
1250 if (nflag || ipaddr == NULL ||
1251 (strncmp(host, ipaddr, NI_MAXHOST) == 0))
1252 warn("connect to %s port %s (%s) %s", host,
1253 port, proto,
1254 error == CONNECTION_TIMEOUT ? "timed out" : "failed");
1255 else
1256 warn("connect to %s (%s) port %s (%s) %s",
1257 host, ipaddr, port, proto,
1258 error == CONNECTION_TIMEOUT ? "timed out" : "failed");
1261 save_errno = errno;
1262 close(s);
1263 errno = save_errno;
1264 s = -1;
1267 freeaddrinfo(res0);
1269 return s;
1273 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
1275 struct pollfd pfd;
1276 socklen_t optlen;
1277 int optval;
1278 int ret;
1280 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
1281 pfd.fd = s;
1282 pfd.events = POLLOUT;
1283 if ((ret = poll(&pfd, 1, timeout)) == 1) {
1284 optlen = sizeof(optval);
1285 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
1286 &optval, &optlen)) == 0) {
1287 errno = optval;
1288 ret = optval == 0 ? 0 : -1;
1290 } else if (ret == 0) {
1291 errno = ETIMEDOUT;
1292 ret = -1;
1293 } else
1294 err(1, "poll failed");
1297 return ret;
1300 static int connect_with_timeout(int fd, const struct sockaddr *sa,
1301 socklen_t salen, int ctimeout)
1303 int err;
1304 struct timeval tv, *tvp = NULL;
1305 fd_set connect_fdset;
1306 socklen_t len;
1307 int orig_flags;
1309 orig_flags = fcntl(fd, F_GETFL, 0);
1310 if (fcntl(fd, F_SETFL, orig_flags | O_NONBLOCK) < 0 ) {
1311 warn("can't set O_NONBLOCK - timeout not available");
1312 if (connect(fd, sa, salen) == 0)
1313 return CONNECTION_SUCCESS;
1314 else
1315 return CONNECTION_FAILED;
1318 /* set connect timeout */
1319 if (ctimeout > 0) {
1320 tv.tv_sec = (time_t)ctimeout/1000;
1321 tv.tv_usec = 0;
1322 tvp = &tv;
1325 /* attempt the connection */
1326 err = connect(fd, sa, salen);
1327 if (err != 0 && errno == EINPROGRESS) {
1328 /* connection is proceeding
1329 * it is complete (or failed) when select returns */
1331 /* initialize connect_fdset */
1332 FD_ZERO(&connect_fdset);
1333 FD_SET(fd, &connect_fdset);
1335 /* call select */
1336 do {
1337 err = select(fd + 1, NULL, &connect_fdset,
1338 NULL, tvp);
1339 } while (err < 0 && errno == EINTR);
1341 /* select error */
1342 if (err < 0)
1343 errx(1,"select error: %s", strerror(errno));
1344 /* we have reached a timeout */
1345 if (err == 0)
1346 return CONNECTION_TIMEOUT;
1347 /* select returned successfully, but we must test socket
1348 * error for result */
1349 len = sizeof(err);
1350 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0)
1351 errx(1, "getsockopt error: %s", strerror(errno));
1352 /* setup errno according to the result returned by
1353 * getsockopt */
1354 if (err != 0)
1355 errno = err;
1358 /* return aborted if an error occured, and valid otherwise */
1359 fcntl(fd, F_SETFL, orig_flags);
1360 return (err != 0)? CONNECTION_FAILED : CONNECTION_SUCCESS;
1364 * local_listen()
1365 * Returns a socket listening on a local port, binds to specified source
1366 * address. Returns -1 on failure.
1369 local_listen(const char *host, const char *port, struct addrinfo hints)
1371 struct addrinfo *res, *res0;
1372 int s = -1, ret, x = 1, save_errno;
1373 int error;
1375 /* Allow nodename to be null. */
1376 hints.ai_flags |= AI_PASSIVE;
1379 * In the case of binding to a wildcard address
1380 * default to binding to an ipv4 address.
1382 if (host == NULL && hints.ai_family == AF_UNSPEC)
1383 hints.ai_family = AF_INET;
1385 if ((error = getaddrinfo(host, port, &hints, &res0)))
1386 errx(1, "getaddrinfo: %s", gai_strerror(error));
1388 for (res = res0; res; res = res->ai_next) {
1389 if ((s = socket(res->ai_family, res->ai_socktype,
1390 res->ai_protocol)) == -1)
1391 continue;
1393 ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1394 if (ret == -1)
1395 err(1, NULL);
1397 # if defined(SO_REUSEPORT)
1398 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
1399 if (ret == -1)
1400 err(1, NULL);
1401 # endif
1403 set_common_sockopts(s, res->ai_addr);
1405 if (bind(s, (struct sockaddr *)res->ai_addr,
1406 res->ai_addrlen) == 0)
1407 break;
1409 save_errno = errno;
1410 close(s);
1411 errno = save_errno;
1412 s = -1;
1415 if (!uflag && s != -1) {
1416 if (listen(s, 1) == -1)
1417 err(1, "listen");
1419 if (vflag && s != -1) {
1420 struct sockaddr_storage ss;
1421 socklen_t len;
1423 len = sizeof(ss);
1424 if (getsockname(s, (struct sockaddr *)&ss, &len) == -1)
1425 err(1, "getsockname");
1426 report_sock(uflag ? "Bound" : "Listening",
1427 (struct sockaddr *)&ss, len, NULL);
1430 freeaddrinfo(res0);
1432 return s;
1436 * readwrite()
1437 * Loop that polls on the network file descriptor and stdin.
1439 void
1440 # if defined(TLS)
1441 readwrite(int net_fd, struct tls *tls_ctx)
1442 # else
1443 readwrite(int net_fd)
1444 # endif
1446 struct pollfd pfd[4];
1447 int stdin_fd = STDIN_FILENO;
1448 int stdout_fd = STDOUT_FILENO;
1449 unsigned char netinbuf[BUFSIZE];
1450 size_t netinbufpos = 0;
1451 unsigned char stdinbuf[BUFSIZE];
1452 size_t stdinbufpos = 0;
1453 int n, num_fds;
1454 ssize_t ret;
1456 /* don't read from stdin if requested */
1457 if (dflag)
1458 stdin_fd = -1;
1460 /* stdin */
1461 pfd[POLL_STDIN].fd = stdin_fd;
1462 pfd[POLL_STDIN].events = POLLIN;
1464 /* network out */
1465 pfd[POLL_NETOUT].fd = net_fd;
1466 pfd[POLL_NETOUT].events = 0;
1468 /* network in */
1469 pfd[POLL_NETIN].fd = net_fd;
1470 pfd[POLL_NETIN].events = POLLIN;
1472 /* stdout */
1473 pfd[POLL_STDOUT].fd = stdout_fd;
1474 pfd[POLL_STDOUT].events = 0;
1476 while (1) {
1477 /* both inputs are gone, buffers are empty, we are done */
1478 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1 &&
1479 stdinbufpos == 0 && netinbufpos == 0) {
1480 if (qflag <= 0)
1481 return;
1482 goto delay_exit;
1484 /* both outputs are gone, we can't continue */
1485 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
1486 if (qflag <= 0)
1487 return;
1488 goto delay_exit;
1490 /* listen and net in gone, queues empty, done */
1491 if (lflag && pfd[POLL_NETIN].fd == -1 &&
1492 stdinbufpos == 0 && netinbufpos == 0) {
1493 if (qflag <= 0)
1494 return;
1495 delay_exit:
1496 close(net_fd);
1497 signal(SIGALRM, quit);
1498 alarm(qflag);
1501 /* poll */
1502 num_fds = poll(pfd, 4, timeout);
1504 /* treat poll errors */
1505 if (num_fds == -1)
1506 err(1, "polling error");
1508 /* timeout happened */
1509 if (num_fds == 0)
1510 return;
1512 /* treat socket error conditions */
1513 for (n = 0; n < 4; n++) {
1514 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
1515 pfd[n].fd = -1;
1518 /* reading is possible after HUP */
1519 if (pfd[POLL_STDIN].events & POLLIN &&
1520 pfd[POLL_STDIN].revents & POLLHUP &&
1521 !(pfd[POLL_STDIN].revents & POLLIN))
1522 pfd[POLL_STDIN].fd = -1;
1524 if (pfd[POLL_NETIN].events & POLLIN &&
1525 pfd[POLL_NETIN].revents & POLLHUP &&
1526 !(pfd[POLL_NETIN].revents & POLLIN))
1527 pfd[POLL_NETIN].fd = -1;
1529 if (pfd[POLL_NETOUT].revents & POLLHUP) {
1530 if (Nflag)
1531 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1532 pfd[POLL_NETOUT].fd = -1;
1534 /* if HUP, stop watching stdout */
1535 if (pfd[POLL_STDOUT].revents & POLLHUP)
1536 pfd[POLL_STDOUT].fd = -1;
1537 /* if no net out, stop watching stdin */
1538 if (pfd[POLL_NETOUT].fd == -1)
1539 pfd[POLL_STDIN].fd = -1;
1540 /* if no stdout, stop watching net in */
1541 if (pfd[POLL_STDOUT].fd == -1) {
1542 if (pfd[POLL_NETIN].fd != -1)
1543 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1544 pfd[POLL_NETIN].fd = -1;
1547 /* try to read from stdin */
1548 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
1549 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
1550 # if defined(TLS)
1551 &stdinbufpos, NULL);
1552 if (ret == TLS_WANT_POLLIN)
1553 pfd[POLL_STDIN].events = POLLIN;
1554 else if (ret == TLS_WANT_POLLOUT)
1555 pfd[POLL_STDIN].events = POLLOUT;
1556 else
1557 # else
1558 &stdinbufpos);
1559 # endif
1560 if (ret == 0 || ret == -1)
1561 pfd[POLL_STDIN].fd = -1;
1562 /* read something - poll net out */
1563 if (stdinbufpos > 0)
1564 pfd[POLL_NETOUT].events = POLLOUT;
1565 /* filled buffer - remove self from polling */
1566 if (stdinbufpos == BUFSIZE)
1567 pfd[POLL_STDIN].events = 0;
1569 /* try to write to network */
1570 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
1571 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
1572 # if defined(TLS)
1573 &stdinbufpos, tls_ctx);
1574 if (ret == TLS_WANT_POLLIN)
1575 pfd[POLL_NETOUT].events = POLLIN;
1576 else if (ret == TLS_WANT_POLLOUT)
1577 pfd[POLL_NETOUT].events = POLLOUT;
1578 else
1579 # else
1580 &stdinbufpos, (iflag || Cflag) ? 1 : 0);
1581 # endif
1582 if (ret == -1)
1583 pfd[POLL_NETOUT].fd = -1;
1584 /* buffer empty - remove self from polling */
1585 if (stdinbufpos == 0)
1586 pfd[POLL_NETOUT].events = 0;
1587 /* buffer no longer full - poll stdin again */
1588 if (stdinbufpos < BUFSIZE)
1589 pfd[POLL_STDIN].events = POLLIN;
1591 /* try to read from network */
1592 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
1593 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
1594 # if defined(TLS)
1595 &netinbufpos, tls_ctx);
1596 if (ret == TLS_WANT_POLLIN)
1597 pfd[POLL_NETIN].events = POLLIN;
1598 else if (ret == TLS_WANT_POLLOUT)
1599 pfd[POLL_NETIN].events = POLLOUT;
1600 else
1601 # else
1602 &netinbufpos);
1603 # endif
1604 if (ret == -1)
1605 pfd[POLL_NETIN].fd = -1;
1606 /* eof on net in - remove from pfd */
1607 if (ret == 0) {
1608 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1609 pfd[POLL_NETIN].fd = -1;
1611 if (recvlimit > 0 && ++recvcount >= recvlimit) {
1612 if (pfd[POLL_NETIN].fd != -1)
1613 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1614 pfd[POLL_NETIN].fd = -1;
1615 pfd[POLL_STDIN].fd = -1;
1617 /* read something - poll stdout */
1618 if (netinbufpos > 0)
1619 pfd[POLL_STDOUT].events = POLLOUT;
1620 /* filled buffer - remove self from polling */
1621 if (netinbufpos == BUFSIZE)
1622 pfd[POLL_NETIN].events = 0;
1623 /* handle telnet */
1624 if (tflag)
1625 atelnet(pfd[POLL_NETIN].fd, netinbuf,
1626 netinbufpos);
1628 /* try to write to stdout */
1629 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
1630 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
1631 # if defined(TLS)
1632 &netinbufpos, NULL);
1633 if (ret == TLS_WANT_POLLIN)
1634 pfd[POLL_STDOUT].events = POLLIN;
1635 else if (ret == TLS_WANT_POLLOUT)
1636 pfd[POLL_STDOUT].events = POLLOUT;
1637 else
1638 # else
1639 &netinbufpos, 0);
1640 # endif
1641 if (ret == -1)
1642 pfd[POLL_STDOUT].fd = -1;
1643 /* buffer empty - remove self from polling */
1644 if (netinbufpos == 0)
1645 pfd[POLL_STDOUT].events = 0;
1646 /* buffer no longer full - poll net in again */
1647 if (netinbufpos < BUFSIZE)
1648 pfd[POLL_NETIN].events = POLLIN;
1651 /* stdin gone and queue empty? */
1652 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
1653 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
1654 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1655 pfd[POLL_NETOUT].fd = -1;
1656 /* #817050: handle UDP sockets and kflag */
1657 if ((lflag || uflag) && pfd[POLL_NETIN].fd != -1 &&
1658 qflag >= 0 && netinbufpos == 0) {
1659 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1660 pfd[POLL_NETIN].fd = -1;
1661 kflag = 0;
1664 /* net in gone and queue empty? */
1665 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1666 pfd[POLL_STDOUT].fd = -1;
1671 ssize_t
1672 drainbuf(int fd, unsigned char *buf, size_t *bufpos, int oneline)
1674 ssize_t n, r;
1675 ssize_t adjust;
1676 unsigned char *lf = NULL;
1678 if (oneline)
1679 lf = memchr(buf, '\n', *bufpos);
1680 if (lf == NULL) {
1681 n = *bufpos;
1682 oneline = 0;
1684 else if (Cflag && (lf == buf || buf[lf - buf - 1] != '\r')) {
1685 n = lf - buf;
1686 oneline = 2;
1688 else
1689 n = lf - buf + 1;
1690 if (n > 0)
1691 n = write(fd, buf, n);
1693 /* don't treat EAGAIN, EINTR as error */
1694 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1695 n = -2;
1696 if (oneline == 2 && n >= 0)
1697 n++;
1698 if (n <= 0)
1699 return n;
1701 if (oneline == 2 && (r = atomicio(vwrite, fd, "\r\n", 2)) != 2)
1702 err(1, "write failed (%zu/2)", r);
1703 if (oneline > 0 && iflag)
1704 sleep(iflag);
1706 /* adjust buffer */
1707 adjust = *bufpos - n;
1708 if (adjust > 0)
1709 memmove(buf, buf + n, adjust);
1710 *bufpos -= n;
1711 return n;
1714 ssize_t
1715 # if defined(TLS)
1716 fillbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1717 # else
1718 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1719 # endif
1721 size_t num = BUFSIZE - *bufpos;
1722 ssize_t n;
1724 # if defined(TLS)
1725 if (tls) {
1726 n = tls_read(tls, buf + *bufpos, num);
1727 if (n == -1)
1728 errx(1, "tls read failed (%s)", tls_error(tls));
1729 } else {
1730 # endif
1731 n = read(fd, buf + *bufpos, num);
1732 /* don't treat EAGAIN, EINTR as error */
1733 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1734 # if defined(TLS)
1735 n = TLS_WANT_POLLIN;
1737 # else
1738 n = -2;
1739 # endif
1740 if (n <= 0)
1741 return n;
1742 *bufpos += n;
1743 return n;
1747 * fdpass()
1748 * Pass the connected file descriptor to stdout and exit.
1750 void
1751 fdpass(int nfd)
1753 struct msghdr mh;
1754 union {
1755 struct cmsghdr hdr;
1756 char buf[CMSG_SPACE(sizeof(int))];
1757 } cmsgbuf;
1758 struct cmsghdr *cmsg;
1759 struct iovec iov;
1760 char c = '\0';
1761 ssize_t r;
1762 struct pollfd pfd;
1764 /* Avoid obvious stupidity */
1765 if (isatty(STDOUT_FILENO))
1766 errx(1, "Cannot pass file descriptor to tty");
1768 memset(&mh, 0, sizeof(mh));
1769 memset(&cmsgbuf, 0, sizeof(cmsgbuf));
1770 memset(&iov, 0, sizeof(iov));
1772 mh.msg_control = (caddr_t)&cmsgbuf.buf;
1773 mh.msg_controllen = sizeof(cmsgbuf.buf);
1774 cmsg = CMSG_FIRSTHDR(&mh);
1775 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1776 cmsg->cmsg_level = SOL_SOCKET;
1777 cmsg->cmsg_type = SCM_RIGHTS;
1778 *(int *)CMSG_DATA(cmsg) = nfd;
1780 iov.iov_base = &c;
1781 iov.iov_len = 1;
1782 mh.msg_iov = &iov;
1783 mh.msg_iovlen = 1;
1785 memset(&pfd, 0, sizeof(pfd));
1786 pfd.fd = STDOUT_FILENO;
1787 pfd.events = POLLOUT;
1788 for (;;) {
1789 r = sendmsg(STDOUT_FILENO, &mh, 0);
1790 if (r == -1) {
1791 if (errno == EAGAIN || errno == EINTR) {
1792 if (poll(&pfd, 1, -1) == -1)
1793 err(1, "poll");
1794 continue;
1796 err(1, "sendmsg");
1797 } else if (r != 1)
1798 errx(1, "sendmsg: unexpected return value %zd", r);
1799 else
1800 break;
1802 exit(0);
1805 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1806 void
1807 atelnet(int nfd, unsigned char *buf, unsigned int size)
1809 unsigned char *p, *end;
1810 unsigned char obuf[4];
1812 if (size < 3)
1813 return;
1814 end = buf + size - 2;
1816 for (p = buf; p < end; p++) {
1817 if (*p != IAC)
1818 continue;
1820 obuf[0] = IAC;
1821 p++;
1822 if ((*p == WILL) || (*p == WONT))
1823 obuf[1] = DONT;
1824 else if ((*p == DO) || (*p == DONT))
1825 obuf[1] = WONT;
1826 else
1827 continue;
1829 p++;
1830 obuf[2] = *p;
1831 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1832 warn("Write Error!");
1838 strtoport(char *portstr, int udp)
1840 struct servent *entry;
1841 const char *errstr;
1842 char *proto;
1843 int port = -1;
1845 proto = udp ? "udp" : "tcp";
1847 port = strtonum(portstr, 1, PORT_MAX, &errstr);
1848 if (errstr == NULL)
1849 return port;
1850 if (errno != EINVAL)
1851 errx(1, "port number %s: %s", errstr, portstr);
1852 if ((entry = getservbyname(portstr, proto)) == NULL)
1853 errx(1, "service \"%s\" unknown", portstr);
1854 return ntohs(entry->s_port);
1858 * build_ports()
1859 * Build an array of ports in portlist[], listing each port
1860 * that we should try to connect to.
1862 void
1863 build_ports(char **p)
1865 struct servent *sv;
1866 char *n;
1867 int hi, lo, cp;
1868 int x = 0;
1869 int i;
1871 char *proto = proto_name(uflag, dccpflag);
1872 for (i = 0; p[i] != NULL; i++) {
1873 sv = getservbyname(p[i], proto);
1874 if (sv) {
1875 if (asprintf(&portlist[x], "%d", ntohs(sv->s_port)) < 0)
1876 err(1, "asprintf");
1877 x++;
1878 } else if (isdigit((unsigned char)*p[i]) && (n = strchr(p[i], '-')) != NULL) {
1879 *n = '\0';
1880 n++;
1882 /* Make sure the ports are in order: lowest->highest. */
1883 hi = strtoport(n, uflag);
1884 lo = strtoport(p[i], uflag);
1885 if (lo > hi) {
1886 cp = hi;
1887 hi = lo;
1888 lo = cp;
1891 /* Load ports sequentially. */
1892 for (cp = lo; cp <= hi; cp++) {
1893 if (asprintf(&portlist[x], "%d", cp) == -1)
1894 err(1, "asprintf");
1895 x++;
1897 } else {
1898 hi = strtoport(p[i], uflag);
1899 if (asprintf(&portlist[x], "%d", hi) < 0)
1900 err(1, "asprintf");
1901 x++;
1906 * Initialize portlist with a random permutation using
1907 * Fisher–Yates shuffle.
1909 if (rflag) {
1910 for (i = x-1; i > 0; i--) {
1911 cp = arc4random_uniform(i+1);
1912 if (cp != i) {
1913 n = portlist[i];
1914 portlist[i] = portlist[cp];
1915 portlist[cp] = n;
1922 * udptest()
1923 * Do a few writes to see if the UDP port is there.
1924 * Fails once PF state table is full.
1927 udptest(int s)
1929 int i, t;
1931 if ((write(s, "X", 1) != 1) ||
1932 ((write(s, "X", 1) != 1) && (errno == ECONNREFUSED)))
1933 return -1;
1935 /* Give the remote host some time to reply. */
1936 for (i = 0, t = (timeout == -1) ? UDP_SCAN_TIMEOUT : (timeout / 1000);
1937 i < t; i++) {
1938 sleep(1);
1939 if ((write(s, "X", 1) != 1) && (errno == ECONNREFUSED))
1940 return -1;
1942 return 1;
1945 void
1946 set_common_sockopts(int s, const struct sockaddr* sa)
1948 int x = 1;
1949 int af = sa->sa_family;
1951 # if defined(SO_BROADCAST)
1952 if (bflag) {
1953 /* allow datagram sockets to send packets to a broadcast address
1954 * (this option has no effect on stream-oriented sockets) */
1955 if (setsockopt(s, SOL_SOCKET, SO_BROADCAST,
1956 &x, sizeof(x)) == -1)
1957 err(1, NULL);
1959 # endif
1960 # if defined(TCP_MD5SIG_EXT) && defined(TCP_MD5SIG_MAXKEYLEN)
1961 if (Sflag) {
1962 struct tcp_md5sig sig;
1963 memset(&sig, 0, sizeof(sig));
1964 memcpy(&sig.tcpm_addr, sa, sizeof(struct sockaddr_storage));
1965 sig.tcpm_keylen = TCP_MD5SIG_MAXKEYLEN < strlen(Sflag_password)
1966 ? TCP_MD5SIG_MAXKEYLEN
1967 : strlen(Sflag_password);
1968 memcpy(sig.tcpm_key, Sflag_password, sig.tcpm_keylen);
1969 sig.tcpm_flags = TCP_MD5SIG_FLAG_PREFIX;
1970 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG_EXT,
1971 &sig, sizeof(sig)) == -1)
1972 err(1, NULL);
1974 # endif
1975 if (Dflag) {
1976 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1977 &x, sizeof(x)) == -1)
1978 err(1, NULL);
1980 if (Tflag != -1) {
1981 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1982 IP_TOS, &Tflag, sizeof(Tflag)) == -1)
1983 err(1, "set IP ToS");
1985 #if defined(IPV6_TCLASS)
1986 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1987 IPV6_TCLASS, &Tflag, sizeof(Tflag)) == -1)
1988 err(1, "set IPv6 traffic class");
1989 #else
1990 else if (af == AF_INET6)
1991 errx(1, "can't set IPv6 traffic class (unavailable)");
1992 #endif
1994 if (Iflag) {
1995 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1996 &Iflag, sizeof(Iflag)) == -1)
1997 err(1, "set TCP receive buffer size");
1999 if (Oflag) {
2000 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
2001 &Oflag, sizeof(Oflag)) == -1)
2002 err(1, "set TCP send buffer size");
2005 if (ttl != -1) {
2006 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
2007 IP_TTL, &ttl, sizeof(ttl)))
2008 err(1, "set IP TTL");
2010 #if defined(IPV6_UNICAST_HOPS)
2011 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
2012 IPV6_UNICAST_HOPS, &ttl, sizeof(ttl)))
2013 err(1, "set IPv6 unicast hops");
2014 #else
2015 else if (af == AF_INET6)
2016 errx(1, "can't set IPv6 unicast hops (unavailable)");
2017 #endif
2020 if (minttl != -1) {
2021 #if defined(IP_MINTTL)
2022 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
2023 IP_MINTTL, &minttl, sizeof(minttl)))
2024 err(1, "set IP min TTL");
2025 #else
2026 if (af == AF_INET)
2027 errx(1, "can't set IP min TTL (unavailable)");
2028 #endif
2030 #if defined(IPV6_MINHOPCOUNT)
2031 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
2032 IPV6_MINHOPCOUNT, &minttl, sizeof(minttl)))
2033 err(1, "set IPv6 min hop count");
2034 #else
2035 else if (af == AF_INET6)
2036 errx(1, "can't set IPv6 min hop count (unavailable)");
2037 #endif
2042 process_tos_opt(char *s, int *val)
2044 /* DiffServ Codepoints and other TOS mappings */
2045 const struct toskeywords {
2046 const char *keyword;
2047 int val;
2048 } *t, toskeywords[] = {
2049 { "af11", IPTOS_DSCP_AF11 },
2050 { "af12", IPTOS_DSCP_AF12 },
2051 { "af13", IPTOS_DSCP_AF13 },
2052 { "af21", IPTOS_DSCP_AF21 },
2053 { "af22", IPTOS_DSCP_AF22 },
2054 { "af23", IPTOS_DSCP_AF23 },
2055 { "af31", IPTOS_DSCP_AF31 },
2056 { "af32", IPTOS_DSCP_AF32 },
2057 { "af33", IPTOS_DSCP_AF33 },
2058 { "af41", IPTOS_DSCP_AF41 },
2059 { "af42", IPTOS_DSCP_AF42 },
2060 { "af43", IPTOS_DSCP_AF43 },
2061 { "critical", IPTOS_PREC_CRITIC_ECP },
2062 { "cs0", IPTOS_DSCP_CS0 },
2063 { "cs1", IPTOS_DSCP_CS1 },
2064 { "cs2", IPTOS_DSCP_CS2 },
2065 { "cs3", IPTOS_DSCP_CS3 },
2066 { "cs4", IPTOS_DSCP_CS4 },
2067 { "cs5", IPTOS_DSCP_CS5 },
2068 { "cs6", IPTOS_DSCP_CS6 },
2069 { "cs7", IPTOS_DSCP_CS7 },
2070 { "ef", IPTOS_DSCP_EF },
2071 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
2072 { "lowcost", IPTOS_LOWCOST },
2073 { "lowdelay", IPTOS_LOWDELAY },
2074 { "netcontrol", IPTOS_PREC_NETCONTROL },
2075 { "reliability", IPTOS_RELIABILITY },
2076 { "throughput", IPTOS_THROUGHPUT },
2077 { NULL, -1 },
2080 for (t = toskeywords; t->keyword != NULL; t++) {
2081 if (strcmp(s, t->keyword) == 0) {
2082 *val = t->val;
2083 return 1;
2087 return 0;
2090 # if defined(TLS)
2092 process_tls_opt(char *s, int *flags)
2094 size_t len;
2095 char *v;
2097 const struct tlskeywords {
2098 const char *keyword;
2099 int flag;
2100 char **value;
2101 } *t, tlskeywords[] = {
2102 { "ciphers", -1, &tls_ciphers },
2103 { "clientcert", TLS_CCERT, NULL },
2104 { "muststaple", TLS_MUSTSTAPLE, NULL },
2105 { "noverify", TLS_NOVERIFY, NULL },
2106 { "noname", TLS_NONAME, NULL },
2107 { "protocols", -1, &tls_protocols },
2108 { NULL, -1, NULL },
2111 len = strlen(s);
2112 if ((v = strchr(s, '=')) != NULL) {
2113 len = v - s;
2114 v++;
2117 for (t = tlskeywords; t->keyword != NULL; t++) {
2118 if (strlen(t->keyword) == len &&
2119 strncmp(s, t->keyword, len) == 0) {
2120 if (t->value != NULL) {
2121 if (v == NULL)
2122 errx(1, "invalid tls value `%s'", s);
2123 *t->value = v;
2124 } else {
2125 *flags |= t->flag;
2127 return 1;
2130 return 0;
2133 void
2134 save_peer_cert(struct tls *tls_ctx, FILE *fp)
2136 const char *pem;
2137 size_t plen;
2139 if ((pem = tls_peer_cert_chain_pem(tls_ctx, &plen)) == NULL)
2140 errx(1, "Can't get peer certificate");
2141 if (fprintf(fp, "%.*s", (int)plen, pem) < 0)
2142 err(1, "unable to save peer cert");
2143 if (fflush(fp) != 0)
2144 err(1, "unable to flush peer cert");
2147 void
2148 report_tls(struct tls * tls_ctx, char * host)
2150 time_t t;
2151 const char *ocsp_url;
2153 fprintf(stderr, "TLS handshake negotiated %s/%s with host %s\n",
2154 tls_conn_version(tls_ctx), tls_conn_cipher(tls_ctx), host);
2155 fprintf(stderr, "Peer name: %s\n",
2156 tls_expectname ? tls_expectname : host);
2157 if (tls_peer_cert_subject(tls_ctx))
2158 fprintf(stderr, "Subject: %s\n",
2159 tls_peer_cert_subject(tls_ctx));
2160 if (tls_peer_cert_issuer(tls_ctx))
2161 fprintf(stderr, "Issuer: %s\n",
2162 tls_peer_cert_issuer(tls_ctx));
2163 if ((t = tls_peer_cert_notbefore(tls_ctx)) != -1)
2164 fprintf(stderr, "Valid From: %s", ctime(&t));
2165 if ((t = tls_peer_cert_notafter(tls_ctx)) != -1)
2166 fprintf(stderr, "Valid Until: %s", ctime(&t));
2167 if (tls_peer_cert_hash(tls_ctx))
2168 fprintf(stderr, "Cert Hash: %s\n",
2169 tls_peer_cert_hash(tls_ctx));
2170 ocsp_url = tls_peer_ocsp_url(tls_ctx);
2171 if (ocsp_url != NULL)
2172 fprintf(stderr, "OCSP URL: %s\n", ocsp_url);
2173 switch (tls_peer_ocsp_response_status(tls_ctx)) {
2174 case TLS_OCSP_RESPONSE_SUCCESSFUL:
2175 fprintf(stderr, "OCSP Stapling: %s\n",
2176 tls_peer_ocsp_result(tls_ctx) == NULL ? "" :
2177 tls_peer_ocsp_result(tls_ctx));
2178 fprintf(stderr,
2179 " response_status=%d cert_status=%d crl_reason=%d\n",
2180 tls_peer_ocsp_response_status(tls_ctx),
2181 tls_peer_ocsp_cert_status(tls_ctx),
2182 tls_peer_ocsp_crl_reason(tls_ctx));
2183 t = tls_peer_ocsp_this_update(tls_ctx);
2184 fprintf(stderr, " this update: %s",
2185 t != -1 ? ctime(&t) : "\n");
2186 t = tls_peer_ocsp_next_update(tls_ctx);
2187 fprintf(stderr, " next update: %s",
2188 t != -1 ? ctime(&t) : "\n");
2189 t = tls_peer_ocsp_revocation_time(tls_ctx);
2190 fprintf(stderr, " revocation: %s",
2191 t != -1 ? ctime(&t) : "\n");
2192 break;
2193 case -1:
2194 break;
2195 default:
2196 fprintf(stderr, "OCSP Stapling: failure - response_status %d (%s)\n",
2197 tls_peer_ocsp_response_status(tls_ctx),
2198 tls_peer_ocsp_result(tls_ctx) == NULL ? "" :
2199 tls_peer_ocsp_result(tls_ctx));
2200 break;
2204 # endif
2206 void
2207 report_sock(const char *msg, const struct sockaddr *sa, socklen_t salen,
2208 char *path)
2210 char host[NI_MAXHOST], port[NI_MAXSERV];
2211 int herr;
2212 int flags = NI_NUMERICSERV;
2214 if (path != NULL) {
2215 fprintf(stderr, "%s on %s\n", msg, path);
2216 return;
2219 if (nflag)
2220 flags |= NI_NUMERICHOST;
2222 herr = getnameinfo(sa, salen, host, sizeof(host), port, sizeof(port),
2223 flags);
2224 switch (herr) {
2225 case 0:
2226 break;
2227 case EAI_SYSTEM:
2228 warn("getnameinfo");
2229 return;
2230 default:
2231 warnx("getnameinfo: %s", gai_strerror(herr));
2232 return;
2235 fprintf(stderr, "%s on %s %s\n", msg, host, port);
2238 void
2239 help(void)
2241 # if defined(DEBIAN_VERSION)
2242 fprintf(stderr, "OpenBSD netcat (Debian patchlevel " DEBIAN_VERSION ")\n");
2243 # endif
2244 usage(0);
2245 fprintf(stderr, "\tCommand Summary:\n\
2246 \t-4 Use IPv4\n\
2247 \t-6 Use IPv6\n\
2248 \t-b Allow broadcast\n\
2249 \t-C Send CRLF as line-ending\n\
2250 \t-D Enable the debug socket option\n\
2251 \t-d Detach from stdin\n\
2252 \t-F Pass socket fd\n\
2253 \t-h This help text\n\
2254 \t-I length TCP receive buffer length\n\
2255 \t-i interval Delay interval for lines sent, ports scanned\n\
2256 \t-k Keep inbound sockets open for multiple connects\n\
2257 \t-l Listen mode, for inbound connects\n\
2258 \t-M ttl Outgoing TTL / Hop Limit\n\
2259 \t-m minttl Minimum incoming TTL / Hop Limit\n\
2260 \t-N Shutdown the network socket after EOF on stdin\n\
2261 \t-n Suppress name/port resolutions\n\
2262 \t-O length TCP send buffer length\n\
2263 \t-P proxyuser\tUsername for proxy authentication\n\
2264 \t-p port\t Specify local port for remote connects\n\
2265 \t-q secs\t quit after EOF on stdin and delay of secs\n\
2266 \t-r Randomize remote ports\n\
2267 \t-S Enable the TCP MD5 signature option\n\
2268 \t-s sourceaddr Local source address\n\
2269 \t-T keyword TOS value\n\
2270 \t-t Answer TELNET negotiation\n\
2271 \t-U Use UNIX domain socket\n\
2272 \t-u UDP mode\n\
2273 \t-V rtable Specify alternate routing table\n\
2274 \t-v Verbose\n\
2275 \t-W recvlimit Terminate after receiving a number of packets\n\
2276 \t-w timeout Timeout for connects and final net reads\n\
2277 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
2278 \t-x addr[:port]\tSpecify proxy address and port\n\
2279 \t-Z DCCP mode\n\
2280 \t-z Zero-I/O mode [used for scanning]\n\
2281 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
2282 exit(0);
2285 void
2286 usage(int ret)
2288 fprintf(stderr,
2289 "usage: nc [-46CDdFhklNnrStUuvZz] [-I length] [-i interval] [-M ttl]\n"
2290 "\t [-m minttl] [-O length] [-P proxy_username] [-p source_port]\n"
2291 "\t [-q seconds] [-s sourceaddr] [-T keyword] [-V rtable] [-W recvlimit]\n"
2292 "\t [-w timeout] [-X proxy_protocol] [-x proxy_address[:port]]\n"
2293 "\t [destination] [port]\n");
2294 if (ret)
2295 exit(1);
2299 * quit()
2300 * handler for a "-q" timeout (exit 0 instead of 1)
2302 static void quit()
2304 exit(0);