[BACK]Return to netcat.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / nc

Annotation of src/usr.bin/nc/netcat.c, Revision 1.108

1.108   ! haesbaer    1: /* $OpenBSD: netcat.c,v 1.107 2012/04/01 02:58:57 deraadt Exp $ */
1.21      ericj       2: /*
                      3:  * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
1.7       deraadt     4:  *
1.21      ericj       5:  * Redistribution and use in source and binary forms, with or without
                      6:  * modification, are permitted provided that the following conditions
                      7:  * are met:
1.7       deraadt     8:  *
1.21      ericj       9:  * 1. Redistributions of source code must retain the above copyright
                     10:  *   notice, this list of conditions and the following disclaimer.
                     11:  * 2. Redistributions in binary form must reproduce the above copyright
                     12:  *   notice, this list of conditions and the following disclaimer in the
                     13:  *   documentation and/or other materials provided with the distribution.
                     14:  * 3. The name of the author may not be used to endorse or promote products
                     15:  *   derived from this software without specific prior written permission.
1.7       deraadt    16:  *
1.21      ericj      17:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     18:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     19:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     20:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     21:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     22:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     23:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     24:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     25:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     26:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     27:  */
1.1       deraadt    28:
1.24      ericj      29: /*
                     30:  * Re-written nc(1) for OpenBSD. Original implementation by
1.21      ericj      31:  * *Hobbit* <hobbit@avian.org>.
                     32:  */
1.1       deraadt    33:
1.7       deraadt    34: #include <sys/types.h>
1.21      ericj      35: #include <sys/socket.h>
1.7       deraadt    36: #include <sys/time.h>
1.42      ericj      37: #include <sys/un.h>
1.21      ericj      38:
1.7       deraadt    39: #include <netinet/in.h>
1.83      dtucker    40: #include <netinet/in_systm.h>
1.65      markus     41: #include <netinet/tcp.h>
1.83      dtucker    42: #include <netinet/ip.h>
1.21      ericj      43: #include <arpa/telnet.h>
1.29      smart      44:
1.11      ericj      45: #include <err.h>
1.7       deraadt    46: #include <errno.h>
1.21      ericj      47: #include <netdb.h>
                     48: #include <poll.h>
1.13      ericj      49: #include <stdarg.h>
1.21      ericj      50: #include <stdio.h>
1.1       deraadt    51: #include <stdlib.h>
1.21      ericj      52: #include <string.h>
1.5       art        53: #include <unistd.h>
1.42      ericj      54: #include <fcntl.h>
1.85      millert    55: #include <limits.h>
1.79      avsm       56: #include "atomicio.h"
1.51      vincent    57:
                     58: #ifndef SUN_LEN
                     59: #define SUN_LEN(su) \
                     60:        (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
                     61: #endif
1.1       deraadt    62:
1.55      fgsch      63: #define PORT_MAX       65535
                     64: #define PORT_MAX_LEN   6
1.99      jeremy     65: #define UNIX_DG_TMP_SOCKET_SIZE        19
1.31      ericj      66:
1.21      ericj      67: /* Command Line Options */
1.68      tedu       68: int    dflag;                                  /* detached, no stdin */
1.88      ray        69: unsigned int iflag;                            /* Interval Flag */
1.21      ericj      70: int    kflag;                                  /* More than one connect */
                     71: int    lflag;                                  /* Bind to local port */
1.67      jmc        72: int    nflag;                                  /* Don't do name look up */
1.86      djm        73: char   *Pflag;                                 /* Proxy username */
1.21      ericj      74: char   *pflag;                                 /* Localport flag */
                     75: int    rflag;                                  /* Random ports flag */
                     76: char   *sflag;                                 /* Source Address */
                     77: int    tflag;                                  /* Telnet Emulation */
                     78: int    uflag;                                  /* UDP - Default to TCP */
                     79: int    vflag;                                  /* Verbosity */
1.34      jakob      80: int    xflag;                                  /* Socks proxy */
1.21      ericj      81: int    zflag;                                  /* Port Scan Flag */
1.73      markus     82: int    Dflag;                                  /* sodebug */
1.90      djm        83: int    Iflag;                                  /* TCP receive buffer size */
                     84: int    Oflag;                                  /* TCP send buffer size */
1.65      markus     85: int    Sflag;                                  /* TCP MD5 signature option */
1.83      dtucker    86: int    Tflag = -1;                             /* IP Type of Service */
1.98      guenther   87: u_int  rtableid;
1.21      ericj      88:
1.49      hugh       89: int timeout = -1;
1.21      ericj      90: int family = AF_UNSPEC;
1.63      miod       91: char *portlist[PORT_MAX+1];
1.99      jeremy     92: char *unix_dg_tmp_socket;
1.21      ericj      93:
1.40      millert    94: void   atelnet(int, unsigned char *, unsigned int);
                     95: void   build_ports(char *);
                     96: void   help(void);
                     97: int    local_listen(char *, char *, struct addrinfo);
                     98: void   readwrite(int);
1.77      otto       99: int    remote_connect(const char *, const char *, struct addrinfo);
1.103     fgsch     100: int    timeout_connect(int, const struct sockaddr *, socklen_t);
1.86      djm       101: int    socks_connect(const char *, const char *, struct addrinfo,
                    102:            const char *, const char *, struct addrinfo, int, const char *);
1.40      millert   103: int    udptest(int);
1.99      jeremy    104: int    unix_bind(char *);
1.42      ericj     105: int    unix_connect(char *);
                    106: int    unix_listen(char *);
1.84      dtucker   107: void   set_common_sockopts(int);
1.102     haesbaer  108: int    map_tos(char *, int *);
1.108   ! haesbaer  109: void   report_connect(const struct sockaddr *, socklen_t);
1.40      millert   110: void   usage(int);
1.1       deraadt   111:
1.21      ericj     112: int
1.37      jakob     113: main(int argc, char *argv[])
1.21      ericj     114: {
1.46      markus    115:        int ch, s, ret, socksv;
1.88      ray       116:        char *host, *uport;
1.21      ericj     117:        struct addrinfo hints;
1.29      smart     118:        struct servent *sv;
1.21      ericj     119:        socklen_t len;
1.76      hshoexer  120:        struct sockaddr_storage cliaddr;
1.34      jakob     121:        char *proxy;
1.88      ray       122:        const char *errstr, *proxyhost = "", *proxyport = NULL;
1.34      jakob     123:        struct addrinfo proxyhints;
1.99      jeremy    124:        char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
1.11      ericj     125:
1.29      smart     126:        ret = 1;
                    127:        s = 0;
1.46      markus    128:        socksv = 5;
1.29      smart     129:        host = NULL;
                    130:        uport = NULL;
                    131:        sv = NULL;
                    132:
1.80      mcbride   133:        while ((ch = getopt(argc, argv,
1.106     dlg       134:            "46DdhI:i:klnO:P:p:rSs:tT:UuV:vw:X:x:z")) != -1) {
1.21      ericj     135:                switch (ch) {
                    136:                case '4':
                    137:                        family = AF_INET;
                    138:                        break;
                    139:                case '6':
                    140:                        family = AF_INET6;
                    141:                        break;
1.42      ericj     142:                case 'U':
                    143:                        family = AF_UNIX;
                    144:                        break;
1.46      markus    145:                case 'X':
1.75      djm       146:                        if (strcasecmp(optarg, "connect") == 0)
                    147:                                socksv = -1; /* HTTP proxy CONNECT */
                    148:                        else if (strcmp(optarg, "4") == 0)
                    149:                                socksv = 4; /* SOCKS v.4 */
                    150:                        else if (strcmp(optarg, "5") == 0)
                    151:                                socksv = 5; /* SOCKS v.5 */
                    152:                        else
                    153:                                errx(1, "unsupported proxy protocol");
1.46      markus    154:                        break;
1.68      tedu      155:                case 'd':
                    156:                        dflag = 1;
                    157:                        break;
1.21      ericj     158:                case 'h':
                    159:                        help();
                    160:                        break;
                    161:                case 'i':
1.88      ray       162:                        iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
                    163:                        if (errstr)
                    164:                                errx(1, "interval %s: %s", errstr, optarg);
1.21      ericj     165:                        break;
                    166:                case 'k':
                    167:                        kflag = 1;
                    168:                        break;
                    169:                case 'l':
                    170:                        lflag = 1;
                    171:                        break;
                    172:                case 'n':
                    173:                        nflag = 1;
                    174:                        break;
1.86      djm       175:                case 'P':
                    176:                        Pflag = optarg;
                    177:                        break;
1.21      ericj     178:                case 'p':
                    179:                        pflag = optarg;
                    180:                        break;
                    181:                case 'r':
                    182:                        rflag = 1;
                    183:                        break;
                    184:                case 's':
                    185:                        sflag = optarg;
                    186:                        break;
                    187:                case 't':
                    188:                        tflag = 1;
                    189:                        break;
                    190:                case 'u':
                    191:                        uflag = 1;
                    192:                        break;
1.93      claudio   193:                case 'V':
1.98      guenther  194:                        rtableid = (unsigned int)strtonum(optarg, 0,
1.93      claudio   195:                            RT_TABLEID_MAX, &errstr);
                    196:                        if (errstr)
1.98      guenther  197:                                errx(1, "rtable %s: %s", errstr, optarg);
1.93      claudio   198:                        break;
1.21      ericj     199:                case 'v':
                    200:                        vflag = 1;
                    201:                        break;
1.70      deraadt   202:                case 'w':
1.88      ray       203:                        timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
                    204:                        if (errstr)
                    205:                                errx(1, "timeout %s: %s", errstr, optarg);
1.49      hugh      206:                        timeout *= 1000;
1.21      ericj     207:                        break;
1.34      jakob     208:                case 'x':
                    209:                        xflag = 1;
1.64      deraadt   210:                        if ((proxy = strdup(optarg)) == NULL)
                    211:                                err(1, NULL);
1.34      jakob     212:                        break;
1.21      ericj     213:                case 'z':
                    214:                        zflag = 1;
                    215:                        break;
1.73      markus    216:                case 'D':
                    217:                        Dflag = 1;
                    218:                        break;
1.90      djm       219:                case 'I':
                    220:                        Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
                    221:                        if (errstr != NULL)
                    222:                                errx(1, "TCP receive window %s: %s",
                    223:                                    errstr, optarg);
                    224:                        break;
                    225:                case 'O':
                    226:                        Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
                    227:                        if (errstr != NULL)
                    228:                                errx(1, "TCP send window %s: %s",
                    229:                                    errstr, optarg);
                    230:                        break;
1.65      markus    231:                case 'S':
                    232:                        Sflag = 1;
                    233:                        break;
1.83      dtucker   234:                case 'T':
1.102     haesbaer  235:                        errstr = NULL;
                    236:                        errno = 0;
                    237:                        if (map_tos(optarg, &Tflag))
                    238:                                break;
                    239:                        if (strlen(optarg) > 1 && optarg[0] == '0' &&
                    240:                            optarg[1] == 'x')
                    241:                                Tflag = (int)strtol(optarg, NULL, 16);
                    242:                        else
                    243:                                Tflag = (int)strtonum(optarg, 0, 255,
                    244:                                    &errstr);
                    245:                        if (Tflag < 0 || Tflag > 255 || errstr || errno)
                    246:                                errx(1, "illegal tos value %s", optarg);
1.83      dtucker   247:                        break;
1.21      ericj     248:                default:
                    249:                        usage(1);
                    250:                }
                    251:        }
                    252:        argc -= optind;
                    253:        argv += optind;
1.11      ericj     254:
1.21      ericj     255:        /* Cruft to make sure options are clean, and used properly. */
1.42      ericj     256:        if (argv[0] && !argv[1] && family == AF_UNIX) {
                    257:                host = argv[0];
                    258:                uport = NULL;
                    259:        } else if (argv[0] && !argv[1]) {
1.21      ericj     260:                if  (!lflag)
                    261:                        usage(1);
                    262:                uport = argv[0];
                    263:                host = NULL;
                    264:        } else if (argv[0] && argv[1]) {
                    265:                host = argv[0];
                    266:                uport = argv[1];
                    267:        } else
                    268:                usage(1);
1.1       deraadt   269:
1.21      ericj     270:        if (lflag && sflag)
                    271:                errx(1, "cannot use -s and -l");
                    272:        if (lflag && pflag)
                    273:                errx(1, "cannot use -p and -l");
                    274:        if (lflag && zflag)
1.32      ericj     275:                errx(1, "cannot use -z and -l");
1.21      ericj     276:        if (!lflag && kflag)
1.32      ericj     277:                errx(1, "must use -l with -k");
1.21      ericj     278:
1.99      jeremy    279:        /* Get name of temporary socket for unix datagram client */
                    280:        if ((family == AF_UNIX) && uflag && !lflag) {
                    281:                if (sflag) {
                    282:                        unix_dg_tmp_socket = sflag;
                    283:                } else {
                    284:                        strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
                    285:                                UNIX_DG_TMP_SOCKET_SIZE);
                    286:                        if (mktemp(unix_dg_tmp_socket_buf) == NULL)
                    287:                                err(1, "mktemp");
                    288:                        unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
                    289:                }
                    290:        }
                    291:
1.67      jmc       292:        /* Initialize addrinfo structure. */
1.42      ericj     293:        if (family != AF_UNIX) {
                    294:                memset(&hints, 0, sizeof(struct addrinfo));
                    295:                hints.ai_family = family;
                    296:                hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
                    297:                hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
                    298:                if (nflag)
                    299:                        hints.ai_flags |= AI_NUMERICHOST;
                    300:        }
1.1       deraadt   301:
1.34      jakob     302:        if (xflag) {
                    303:                if (uflag)
                    304:                        errx(1, "no proxy support for UDP mode");
                    305:
                    306:                if (lflag)
                    307:                        errx(1, "no proxy support for listen");
                    308:
1.42      ericj     309:                if (family == AF_UNIX)
                    310:                        errx(1, "no proxy support for unix sockets");
                    311:
1.34      jakob     312:                /* XXX IPv6 transport to proxy would probably work */
                    313:                if (family == AF_INET6)
                    314:                        errx(1, "no proxy support for IPv6");
                    315:
                    316:                if (sflag)
                    317:                        errx(1, "no proxy support for local source address");
                    318:
                    319:                proxyhost = strsep(&proxy, ":");
                    320:                proxyport = proxy;
                    321:
                    322:                memset(&proxyhints, 0, sizeof(struct addrinfo));
                    323:                proxyhints.ai_family = family;
                    324:                proxyhints.ai_socktype = SOCK_STREAM;
                    325:                proxyhints.ai_protocol = IPPROTO_TCP;
                    326:                if (nflag)
                    327:                        proxyhints.ai_flags |= AI_NUMERICHOST;
                    328:        }
                    329:
1.21      ericj     330:        if (lflag) {
                    331:                int connfd;
1.27      ericj     332:                ret = 0;
1.1       deraadt   333:
1.99      jeremy    334:                if (family == AF_UNIX) {
                    335:                        if (uflag)
                    336:                                s = unix_bind(host);
                    337:                        else
                    338:                                s = unix_listen(host);
                    339:                }
1.42      ericj     340:
1.67      jmc       341:                /* Allow only one connection at a time, but stay alive. */
1.21      ericj     342:                for (;;) {
1.42      ericj     343:                        if (family != AF_UNIX)
                    344:                                s = local_listen(host, uport, hints);
                    345:                        if (s < 0)
1.30      smart     346:                                err(1, NULL);
1.21      ericj     347:                        /*
                    348:                         * For UDP, we will use recvfrom() initially
                    349:                         * to wait for a caller, then use the regular
                    350:                         * functions to talk to the caller.
                    351:                         */
                    352:                        if (uflag) {
1.80      mcbride   353:                                int rv, plen;
1.97      nicm      354:                                char buf[16384];
1.21      ericj     355:                                struct sockaddr_storage z;
                    356:
                    357:                                len = sizeof(z);
1.106     dlg       358:                                plen = 2048;
1.80      mcbride   359:                                rv = recvfrom(s, buf, plen, MSG_PEEK,
1.37      jakob     360:                                    (struct sockaddr *)&z, &len);
1.23      ericj     361:                                if (rv < 0)
1.57      stevesk   362:                                        err(1, "recvfrom");
1.21      ericj     363:
1.37      jakob     364:                                rv = connect(s, (struct sockaddr *)&z, len);
1.23      ericj     365:                                if (rv < 0)
1.57      stevesk   366:                                        err(1, "connect");
1.1       deraadt   367:
1.108   ! haesbaer  368:                                if (vflag)
        !           369:                                        report_connect((struct sockaddr *)&z, len);
        !           370:
1.99      jeremy    371:                                readwrite(s);
1.21      ericj     372:                        } else {
1.78      otto      373:                                len = sizeof(cliaddr);
1.21      ericj     374:                                connfd = accept(s, (struct sockaddr *)&cliaddr,
1.37      jakob     375:                                    &len);
1.107     deraadt   376:                                if (connfd == -1)
                    377:                                        err(1, "accept");
1.108   ! haesbaer  378:
        !           379:                                if (vflag)
        !           380:                                        report_connect((struct sockaddr *)&cliaddr, len);
        !           381:
1.99      jeremy    382:                                readwrite(connfd);
                    383:                                close(connfd);
1.21      ericj     384:                        }
1.1       deraadt   385:
1.42      ericj     386:                        if (family != AF_UNIX)
                    387:                                close(s);
1.99      jeremy    388:                        else if (uflag) {
                    389:                                if (connect(s, NULL, 0) < 0)
                    390:                                        err(1, "connect");
                    391:                        }
1.27      ericj     392:
1.21      ericj     393:                        if (!kflag)
                    394:                                break;
1.11      ericj     395:                }
1.42      ericj     396:        } else if (family == AF_UNIX) {
                    397:                ret = 0;
                    398:
                    399:                if ((s = unix_connect(host)) > 0 && !zflag) {
                    400:                        readwrite(s);
                    401:                        close(s);
                    402:                } else
                    403:                        ret = 1;
                    404:
1.99      jeremy    405:                if (uflag)
                    406:                        unlink(unix_dg_tmp_socket);
1.42      ericj     407:                exit(ret);
                    408:
1.21      ericj     409:        } else {
                    410:                int i = 0;
1.6       deraadt   411:
1.67      jmc       412:                /* Construct the portlist[] array. */
1.21      ericj     413:                build_ports(uport);
1.1       deraadt   414:
1.67      jmc       415:                /* Cycle through portlist, connecting to each port. */
1.21      ericj     416:                for (i = 0; portlist[i] != NULL; i++) {
                    417:                        if (s)
                    418:                                close(s);
1.34      jakob     419:
                    420:                        if (xflag)
                    421:                                s = socks_connect(host, portlist[i], hints,
1.86      djm       422:                                    proxyhost, proxyport, proxyhints, socksv,
                    423:                                    Pflag);
1.34      jakob     424:                        else
                    425:                                s = remote_connect(host, portlist[i], hints);
                    426:
                    427:                        if (s < 0)
1.21      ericj     428:                                continue;
1.1       deraadt   429:
1.21      ericj     430:                        ret = 0;
                    431:                        if (vflag || zflag) {
1.67      jmc       432:                                /* For UDP, make sure we are connected. */
1.21      ericj     433:                                if (uflag) {
1.50      vincent   434:                                        if (udptest(s) == -1) {
1.21      ericj     435:                                                ret = 1;
                    436:                                                continue;
                    437:                                        }
                    438:                                }
1.1       deraadt   439:
1.67      jmc       440:                                /* Don't look up port if -n. */
1.21      ericj     441:                                if (nflag)
                    442:                                        sv = NULL;
                    443:                                else {
                    444:                                        sv = getservbyport(
1.37      jakob     445:                                            ntohs(atoi(portlist[i])),
                    446:                                            uflag ? "udp" : "tcp");
1.21      ericj     447:                                }
1.50      vincent   448:
1.94      mpf       449:                                fprintf(stderr,
                    450:                                    "Connection to %s %s port [%s/%s] "
                    451:                                    "succeeded!\n", host, portlist[i],
                    452:                                    uflag ? "udp" : "tcp",
1.37      jakob     453:                                    sv ? sv->s_name : "*");
1.21      ericj     454:                        }
                    455:                        if (!zflag)
                    456:                                readwrite(s);
1.7       deraadt   457:                }
1.11      ericj     458:        }
1.1       deraadt   459:
1.21      ericj     460:        if (s)
                    461:                close(s);
                    462:
                    463:        exit(ret);
1.7       deraadt   464: }
1.1       deraadt   465:
1.11      ericj     466: /*
1.99      jeremy    467:  * unix_bind()
                    468:  * Returns a unix socket bound to the given path
1.42      ericj     469:  */
                    470: int
1.99      jeremy    471: unix_bind(char *path)
1.42      ericj     472: {
                    473:        struct sockaddr_un sun;
                    474:        int s;
                    475:
1.99      jeremy    476:        /* Create unix domain socket. */
                    477:        if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
                    478:             0)) < 0)
1.50      vincent   479:                return (-1);
1.42      ericj     480:
                    481:        memset(&sun, 0, sizeof(struct sockaddr_un));
                    482:        sun.sun_family = AF_UNIX;
1.60      avsm      483:
                    484:        if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
                    485:            sizeof(sun.sun_path)) {
                    486:                close(s);
                    487:                errno = ENAMETOOLONG;
                    488:                return (-1);
                    489:        }
1.99      jeremy    490:
                    491:        if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
1.50      vincent   492:                close(s);
                    493:                return (-1);
1.42      ericj     494:        }
                    495:        return (s);
                    496: }
                    497:
                    498: /*
1.99      jeremy    499:  * unix_connect()
                    500:  * Returns a socket connected to a local unix socket. Returns -1 on failure.
1.42      ericj     501:  */
                    502: int
1.99      jeremy    503: unix_connect(char *path)
1.42      ericj     504: {
                    505:        struct sockaddr_un sun;
                    506:        int s;
                    507:
1.99      jeremy    508:        if (uflag) {
                    509:                if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
                    510:                        return (-1);
                    511:        } else {
                    512:                if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
                    513:                        return (-1);
                    514:        }
                    515:        (void)fcntl(s, F_SETFD, 1);
1.42      ericj     516:
1.60      avsm      517:        memset(&sun, 0, sizeof(struct sockaddr_un));
1.42      ericj     518:        sun.sun_family = AF_UNIX;
1.60      avsm      519:
                    520:        if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
                    521:            sizeof(sun.sun_path)) {
                    522:                close(s);
                    523:                errno = ENAMETOOLONG;
                    524:                return (-1);
                    525:        }
1.99      jeremy    526:        if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
1.42      ericj     527:                close(s);
                    528:                return (-1);
                    529:        }
1.99      jeremy    530:        return (s);
                    531:
                    532: }
                    533:
                    534: /*
                    535:  * unix_listen()
                    536:  * Create a unix domain socket, and listen on it.
                    537:  */
                    538: int
                    539: unix_listen(char *path)
                    540: {
                    541:        int s;
                    542:        if ((s = unix_bind(path)) < 0)
                    543:                return (-1);
1.42      ericj     544:
                    545:        if (listen(s, 5) < 0) {
                    546:                close(s);
                    547:                return (-1);
                    548:        }
                    549:        return (s);
                    550: }
                    551:
                    552: /*
1.21      ericj     553:  * remote_connect()
1.67      jmc       554:  * Returns a socket connected to a remote host. Properly binds to a local
                    555:  * port or source address if needed. Returns -1 on failure.
1.11      ericj     556:  */
1.21      ericj     557: int
1.77      otto      558: remote_connect(const char *host, const char *port, struct addrinfo hints)
1.21      ericj     559: {
                    560:        struct addrinfo *res, *res0;
1.91      markus    561:        int s, error, on = 1;
1.21      ericj     562:
                    563:        if ((error = getaddrinfo(host, port, &hints, &res)))
1.56      stevesk   564:                errx(1, "getaddrinfo: %s", gai_strerror(error));
1.21      ericj     565:
                    566:        res0 = res;
                    567:        do {
                    568:                if ((s = socket(res0->ai_family, res0->ai_socktype,
1.37      jakob     569:                    res0->ai_protocol)) < 0)
1.21      ericj     570:                        continue;
                    571:
1.98      guenther  572:                if (rtableid) {
1.101     mikeb     573:                        if (setsockopt(s, SOL_SOCKET, SO_RTABLE, &rtableid,
1.98      guenther  574:                            sizeof(rtableid)) == -1)
                    575:                                err(1, "setsockopt SO_RTABLE");
1.93      claudio   576:                }
                    577:
1.67      jmc       578:                /* Bind to a local port or source address if specified. */
1.21      ericj     579:                if (sflag || pflag) {
                    580:                        struct addrinfo ahints, *ares;
1.6       deraadt   581:
1.91      markus    582:                        /* try SO_BINDANY, but don't insist */
                    583:                        setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
1.21      ericj     584:                        memset(&ahints, 0, sizeof(struct addrinfo));
                    585:                        ahints.ai_family = res0->ai_family;
                    586:                        ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
                    587:                        ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
1.25      ericj     588:                        ahints.ai_flags = AI_PASSIVE;
1.38      jakob     589:                        if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
1.56      stevesk   590:                                errx(1, "getaddrinfo: %s", gai_strerror(error));
1.21      ericj     591:
                    592:                        if (bind(s, (struct sockaddr *)ares->ai_addr,
1.62      millert   593:                            ares->ai_addrlen) < 0)
1.21      ericj     594:                                errx(1, "bind failed: %s", strerror(errno));
                    595:                        freeaddrinfo(ares);
1.6       deraadt   596:                }
1.81      marius    597:
                    598:                set_common_sockopts(s);
1.6       deraadt   599:
1.103     fgsch     600:                if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
1.6       deraadt   601:                        break;
1.71      mcbride   602:                else if (vflag)
                    603:                        warn("connect to %s port %s (%s) failed", host, port,
                    604:                            uflag ? "udp" : "tcp");
1.34      jakob     605:
1.21      ericj     606:                close(s);
                    607:                s = -1;
                    608:        } while ((res0 = res0->ai_next) != NULL);
                    609:
                    610:        freeaddrinfo(res);
1.1       deraadt   611:
1.21      ericj     612:        return (s);
1.103     fgsch     613: }
                    614:
                    615: int
                    616: timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
                    617: {
                    618:        struct pollfd pfd;
                    619:        socklen_t optlen;
                    620:        int flags, optval;
                    621:        int ret;
                    622:
                    623:        if (timeout != -1) {
                    624:                flags = fcntl(s, F_GETFL, 0);
                    625:                if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
                    626:                        err(1, "set non-blocking mode");
                    627:        }
                    628:
                    629:        if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
                    630:                pfd.fd = s;
                    631:                pfd.events = POLLOUT;
                    632:                if ((ret = poll(&pfd, 1, timeout)) == 1) {
                    633:                        optlen = sizeof(optval);
                    634:                        if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
                    635:                            &optval, &optlen)) == 0) {
                    636:                                errno = optval;
                    637:                                ret = optval == 0 ? 0 : -1;
                    638:                        }
                    639:                } else if (ret == 0) {
                    640:                        errno = ETIMEDOUT;
                    641:                        ret = -1;
                    642:                } else
                    643:                        err(1, "poll failed");
                    644:        }
                    645:
                    646:        if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
                    647:                err(1, "restoring flags");
                    648:
                    649:        return (ret);
1.7       deraadt   650: }
1.1       deraadt   651:
1.11      ericj     652: /*
1.21      ericj     653:  * local_listen()
1.67      jmc       654:  * Returns a socket listening on a local port, binds to specified source
                    655:  * address. Returns -1 on failure.
1.11      ericj     656:  */
1.21      ericj     657: int
1.37      jakob     658: local_listen(char *host, char *port, struct addrinfo hints)
1.21      ericj     659: {
                    660:        struct addrinfo *res, *res0;
                    661:        int s, ret, x = 1;
                    662:        int error;
1.6       deraadt   663:
1.67      jmc       664:        /* Allow nodename to be null. */
1.21      ericj     665:        hints.ai_flags |= AI_PASSIVE;
1.7       deraadt   666:
1.21      ericj     667:        /*
                    668:         * In the case of binding to a wildcard address
                    669:         * default to binding to an ipv4 address.
                    670:         */
                    671:        if (host == NULL && hints.ai_family == AF_UNSPEC)
                    672:                hints.ai_family = AF_INET;
1.1       deraadt   673:
1.21      ericj     674:        if ((error = getaddrinfo(host, port, &hints, &res)))
1.70      deraadt   675:                errx(1, "getaddrinfo: %s", gai_strerror(error));
1.14      ericj     676:
1.21      ericj     677:        res0 = res;
                    678:        do {
                    679:                if ((s = socket(res0->ai_family, res0->ai_socktype,
1.82      marius    680:                    res0->ai_protocol)) < 0)
1.21      ericj     681:                        continue;
1.1       deraadt   682:
1.98      guenther  683:                if (rtableid) {
                    684:                        if (setsockopt(s, IPPROTO_IP, SO_RTABLE, &rtableid,
                    685:                            sizeof(rtableid)) == -1)
                    686:                                err(1, "setsockopt SO_RTABLE");
1.93      claudio   687:                }
                    688:
1.21      ericj     689:                ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
                    690:                if (ret == -1)
1.30      smart     691:                        err(1, NULL);
1.81      marius    692:
                    693:                set_common_sockopts(s);
1.1       deraadt   694:
1.21      ericj     695:                if (bind(s, (struct sockaddr *)res0->ai_addr,
1.37      jakob     696:                    res0->ai_addrlen) == 0)
1.21      ericj     697:                        break;
1.1       deraadt   698:
1.21      ericj     699:                close(s);
                    700:                s = -1;
                    701:        } while ((res0 = res0->ai_next) != NULL);
1.1       deraadt   702:
1.47      ericj     703:        if (!uflag && s != -1) {
1.21      ericj     704:                if (listen(s, 1) < 0)
1.57      stevesk   705:                        err(1, "listen");
1.12      ericj     706:        }
1.1       deraadt   707:
1.21      ericj     708:        freeaddrinfo(res);
1.1       deraadt   709:
1.21      ericj     710:        return (s);
1.7       deraadt   711: }
                    712:
1.11      ericj     713: /*
1.21      ericj     714:  * readwrite()
                    715:  * Loop that polls on the network file descriptor and stdin.
1.11      ericj     716:  */
1.21      ericj     717: void
1.37      jakob     718: readwrite(int nfd)
1.6       deraadt   719: {
1.52      vincent   720:        struct pollfd pfd[2];
1.97      nicm      721:        unsigned char buf[16384];
1.79      avsm      722:        int n, wfd = fileno(stdin);
1.21      ericj     723:        int lfd = fileno(stdout);
1.80      mcbride   724:        int plen;
                    725:
1.106     dlg       726:        plen = 2048;
1.21      ericj     727:
                    728:        /* Setup Network FD */
                    729:        pfd[0].fd = nfd;
                    730:        pfd[0].events = POLLIN;
                    731:
1.67      jmc       732:        /* Set up STDIN FD. */
1.21      ericj     733:        pfd[1].fd = wfd;
                    734:        pfd[1].events = POLLIN;
                    735:
1.54      aaron     736:        while (pfd[0].fd != -1) {
1.21      ericj     737:                if (iflag)
                    738:                        sleep(iflag);
                    739:
1.68      tedu      740:                if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
1.21      ericj     741:                        close(nfd);
1.52      vincent   742:                        err(1, "Polling Error");
1.21      ericj     743:                }
1.49      hugh      744:
                    745:                if (n == 0)
                    746:                        return;
1.21      ericj     747:
                    748:                if (pfd[0].revents & POLLIN) {
1.80      mcbride   749:                        if ((n = read(nfd, buf, plen)) < 0)
1.21      ericj     750:                                return;
1.52      vincent   751:                        else if (n == 0) {
                    752:                                shutdown(nfd, SHUT_RD);
                    753:                                pfd[0].fd = -1;
                    754:                                pfd[0].events = 0;
1.21      ericj     755:                        } else {
                    756:                                if (tflag)
                    757:                                        atelnet(nfd, buf, n);
1.79      avsm      758:                                if (atomicio(vwrite, lfd, buf, n) != n)
1.21      ericj     759:                                        return;
1.6       deraadt   760:                        }
1.21      ericj     761:                }
                    762:
1.68      tedu      763:                if (!dflag && pfd[1].revents & POLLIN) {
1.80      mcbride   764:                        if ((n = read(wfd, buf, plen)) < 0)
1.21      ericj     765:                                return;
1.52      vincent   766:                        else if (n == 0) {
                    767:                                shutdown(nfd, SHUT_WR);
                    768:                                pfd[1].fd = -1;
                    769:                                pfd[1].events = 0;
                    770:                        } else {
1.79      avsm      771:                                if (atomicio(vwrite, nfd, buf, n) != n)
1.21      ericj     772:                                        return;
1.50      vincent   773:                        }
1.21      ericj     774:                }
1.11      ericj     775:        }
1.7       deraadt   776: }
1.50      vincent   777:
1.67      jmc       778: /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1.21      ericj     779: void
1.37      jakob     780: atelnet(int nfd, unsigned char *buf, unsigned int size)
1.6       deraadt   781: {
1.24      ericj     782:        unsigned char *p, *end;
                    783:        unsigned char obuf[4];
                    784:
1.95      nicm      785:        if (size < 3)
                    786:                return;
                    787:        end = buf + size - 2;
1.24      ericj     788:
                    789:        for (p = buf; p < end; p++) {
1.21      ericj     790:                if (*p != IAC)
1.95      nicm      791:                        continue;
1.24      ericj     792:
1.25      ericj     793:                obuf[0] = IAC;
1.24      ericj     794:                p++;
1.50      vincent   795:                if ((*p == WILL) || (*p == WONT))
1.24      ericj     796:                        obuf[1] = DONT;
1.95      nicm      797:                else if ((*p == DO) || (*p == DONT))
1.24      ericj     798:                        obuf[1] = WONT;
1.95      nicm      799:                else
                    800:                        continue;
                    801:
                    802:                p++;
                    803:                obuf[2] = *p;
                    804:                if (atomicio(vwrite, nfd, obuf, 3) != 3)
                    805:                        warn("Write Error!");
1.11      ericj     806:        }
1.7       deraadt   807: }
                    808:
1.11      ericj     809: /*
1.21      ericj     810:  * build_ports()
1.105     lum       811:  * Build an array of ports in portlist[], listing each port
1.67      jmc       812:  * that we should try to connect to.
1.11      ericj     813:  */
1.21      ericj     814: void
1.37      jakob     815: build_ports(char *p)
1.6       deraadt   816: {
1.88      ray       817:        const char *errstr;
                    818:        char *n;
1.21      ericj     819:        int hi, lo, cp;
                    820:        int x = 0;
                    821:
                    822:        if ((n = strchr(p, '-')) != NULL) {
                    823:                *n = '\0';
                    824:                n++;
                    825:
1.67      jmc       826:                /* Make sure the ports are in order: lowest->highest. */
1.88      ray       827:                hi = strtonum(n, 1, PORT_MAX, &errstr);
                    828:                if (errstr)
                    829:                        errx(1, "port number %s: %s", errstr, n);
                    830:                lo = strtonum(p, 1, PORT_MAX, &errstr);
                    831:                if (errstr)
                    832:                        errx(1, "port number %s: %s", errstr, p);
1.21      ericj     833:
                    834:                if (lo > hi) {
                    835:                        cp = hi;
                    836:                        hi = lo;
                    837:                        lo = cp;
                    838:                }
                    839:
1.67      jmc       840:                /* Load ports sequentially. */
1.21      ericj     841:                for (cp = lo; cp <= hi; cp++) {
1.55      fgsch     842:                        portlist[x] = calloc(1, PORT_MAX_LEN);
                    843:                        if (portlist[x] == NULL)
                    844:                                err(1, NULL);
                    845:                        snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1.21      ericj     846:                        x++;
                    847:                }
                    848:
1.67      jmc       849:                /* Randomly swap ports. */
1.21      ericj     850:                if (rflag) {
                    851:                        int y;
                    852:                        char *c;
                    853:
                    854:                        for (x = 0; x <= (hi - lo); x++) {
                    855:                                y = (arc4random() & 0xFFFF) % (hi - lo);
                    856:                                c = portlist[x];
                    857:                                portlist[x] = portlist[y];
                    858:                                portlist[y] = c;
1.6       deraadt   859:                        }
1.11      ericj     860:                }
1.21      ericj     861:        } else {
1.88      ray       862:                hi = strtonum(p, 1, PORT_MAX, &errstr);
                    863:                if (errstr)
                    864:                        errx(1, "port number %s: %s", errstr, p);
1.96      nicm      865:                portlist[0] = strdup(p);
1.55      fgsch     866:                if (portlist[0] == NULL)
                    867:                        err(1, NULL);
1.11      ericj     868:        }
1.13      ericj     869: }
                    870:
                    871: /*
1.21      ericj     872:  * udptest()
                    873:  * Do a few writes to see if the UDP port is there.
1.105     lum       874:  * Fails once PF state table is full.
1.13      ericj     875:  */
1.21      ericj     876: int
1.37      jakob     877: udptest(int s)
1.13      ericj     878: {
1.74      deraadt   879:        int i, ret;
1.13      ericj     880:
1.52      vincent   881:        for (i = 0; i <= 3; i++) {
1.74      deraadt   882:                if (write(s, "X", 1) == 1)
1.21      ericj     883:                        ret = 1;
1.14      ericj     884:                else
1.21      ericj     885:                        ret = -1;
1.14      ericj     886:        }
1.21      ericj     887:        return (ret);
1.81      marius    888: }
                    889:
1.84      dtucker   890: void
1.81      marius    891: set_common_sockopts(int s)
                    892: {
                    893:        int x = 1;
                    894:
                    895:        if (Sflag) {
                    896:                if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
                    897:                        &x, sizeof(x)) == -1)
                    898:                        err(1, NULL);
                    899:        }
                    900:        if (Dflag) {
                    901:                if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
                    902:                        &x, sizeof(x)) == -1)
                    903:                        err(1, NULL);
                    904:        }
1.83      dtucker   905:        if (Tflag != -1) {
                    906:                if (setsockopt(s, IPPROTO_IP, IP_TOS,
                    907:                    &Tflag, sizeof(Tflag)) == -1)
                    908:                        err(1, "set IP ToS");
                    909:        }
1.90      djm       910:        if (Iflag) {
                    911:                if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
                    912:                    &Iflag, sizeof(Iflag)) == -1)
                    913:                        err(1, "set TCP receive buffer size");
                    914:        }
                    915:        if (Oflag) {
                    916:                if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
                    917:                    &Oflag, sizeof(Oflag)) == -1)
                    918:                        err(1, "set TCP send buffer size");
                    919:        }
1.83      dtucker   920: }
                    921:
                    922: int
1.102     haesbaer  923: map_tos(char *s, int *val)
1.83      dtucker   924: {
1.102     haesbaer  925:        /* DiffServ Codepoints and other TOS mappings */
                    926:        const struct toskeywords {
                    927:                const char      *keyword;
                    928:                int              val;
                    929:        } *t, toskeywords[] = {
                    930:                { "af11",               IPTOS_DSCP_AF11 },
                    931:                { "af12",               IPTOS_DSCP_AF12 },
                    932:                { "af13",               IPTOS_DSCP_AF13 },
                    933:                { "af21",               IPTOS_DSCP_AF21 },
                    934:                { "af22",               IPTOS_DSCP_AF22 },
                    935:                { "af23",               IPTOS_DSCP_AF23 },
                    936:                { "af31",               IPTOS_DSCP_AF31 },
                    937:                { "af32",               IPTOS_DSCP_AF32 },
                    938:                { "af33",               IPTOS_DSCP_AF33 },
                    939:                { "af41",               IPTOS_DSCP_AF41 },
                    940:                { "af42",               IPTOS_DSCP_AF42 },
                    941:                { "af43",               IPTOS_DSCP_AF43 },
                    942:                { "critical",           IPTOS_PREC_CRITIC_ECP },
                    943:                { "cs0",                IPTOS_DSCP_CS0 },
                    944:                { "cs1",                IPTOS_DSCP_CS1 },
                    945:                { "cs2",                IPTOS_DSCP_CS2 },
                    946:                { "cs3",                IPTOS_DSCP_CS3 },
                    947:                { "cs4",                IPTOS_DSCP_CS4 },
                    948:                { "cs5",                IPTOS_DSCP_CS5 },
                    949:                { "cs6",                IPTOS_DSCP_CS6 },
                    950:                { "cs7",                IPTOS_DSCP_CS7 },
                    951:                { "ef",                 IPTOS_DSCP_EF },
                    952:                { "inetcontrol",        IPTOS_PREC_INTERNETCONTROL },
                    953:                { "lowdelay",           IPTOS_LOWDELAY },
                    954:                { "netcontrol",         IPTOS_PREC_NETCONTROL },
                    955:                { "reliability",        IPTOS_RELIABILITY },
                    956:                { "throughput",         IPTOS_THROUGHPUT },
                    957:                { NULL,                 -1 },
                    958:        };
                    959:
                    960:        for (t = toskeywords; t->keyword != NULL; t++) {
                    961:                if (strcmp(s, t->keyword) == 0) {
                    962:                        *val = t->val;
                    963:                        return (1);
                    964:                }
                    965:        }
1.83      dtucker   966:
1.102     haesbaer  967:        return (0);
1.108   ! haesbaer  968: }
        !           969:
        !           970: void
        !           971: report_connect(const struct sockaddr *sa, socklen_t salen)
        !           972: {
        !           973:        char remote_host[NI_MAXHOST];
        !           974:        char remote_port[NI_MAXSERV];
        !           975:        int herr;
        !           976:        int flags = NI_NUMERICSERV;
        !           977:
        !           978:        if (nflag)
        !           979:                flags |= NI_NUMERICHOST;
        !           980:
        !           981:        if ((herr = getnameinfo(sa, salen,
        !           982:            remote_host, sizeof(remote_host),
        !           983:            remote_port, sizeof(remote_port),
        !           984:            flags)) != 0) {
        !           985:                if (herr == EAI_SYSTEM)
        !           986:                        err(1, "getnameinfo");
        !           987:                else
        !           988:                        errx(1, "getnameinfo: %s", gai_strerror(herr));
        !           989:        }
        !           990:
        !           991:        fprintf(stderr,
        !           992:            "Connection from %s %s "
        !           993:            "received!\n", remote_host, remote_port);
1.7       deraadt   994: }
1.1       deraadt   995:
1.11      ericj     996: void
1.58      deraadt   997: help(void)
1.1       deraadt   998: {
1.21      ericj     999:        usage(0);
                   1000:        fprintf(stderr, "\tCommand Summary:\n\
                   1001:        \t-4            Use IPv4\n\
                   1002:        \t-6            Use IPv6\n\
1.73      markus   1003:        \t-D            Enable the debug socket option\n\
1.69      tedu     1004:        \t-d            Detach from stdin\n\
1.21      ericj    1005:        \t-h            This help text\n\
1.90      djm      1006:        \t-I length     TCP receive buffer length\n\
1.21      ericj    1007:        \t-i secs\t     Delay interval for lines sent, ports scanned\n\
                   1008:        \t-k            Keep inbound sockets open for multiple connects\n\
                   1009:        \t-l            Listen mode, for inbound connects\n\
1.22      jasoni   1010:        \t-n            Suppress name/port resolutions\n\
1.90      djm      1011:        \t-O length     TCP send buffer length\n\
1.86      djm      1012:        \t-P proxyuser\tUsername for proxy authentication\n\
1.36      jakob    1013:        \t-p port\t     Specify local port for remote connects\n\
1.21      ericj    1014:        \t-r            Randomize remote ports\n\
1.67      jmc      1015:        \t-S            Enable the TCP MD5 signature option\n\
1.21      ericj    1016:        \t-s addr\t     Local source address\n\
1.102     haesbaer 1017:        \t-T toskeyword\tSet IP Type of Service\n\
1.21      ericj    1018:        \t-t            Answer TELNET negotiation\n\
1.67      jmc      1019:        \t-U            Use UNIX domain socket\n\
1.21      ericj    1020:        \t-u            UDP mode\n\
1.98      guenther 1021:        \t-V rtable     Specify alternate routing table\n\
1.21      ericj    1022:        \t-v            Verbose\n\
                   1023:        \t-w secs\t     Timeout for connects and final net reads\n\
1.75      djm      1024:        \t-X proto      Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
                   1025:        \t-x addr[:port]\tSpecify proxy address and port\n\
1.21      ericj    1026:        \t-z            Zero-I/O mode [used for scanning]\n\
                   1027:        Port numbers can be individual or ranges: lo-hi [inclusive]\n");
                   1028:        exit(1);
1.11      ericj    1029: }
                   1030:
                   1031: void
1.37      jakob    1032: usage(int ret)
1.11      ericj    1033: {
1.92      sobrado  1034:        fprintf(stderr,
                   1035:            "usage: nc [-46DdhklnrStUuvz] [-I length] [-i interval] [-O length]\n"
1.100     jeremy   1036:            "\t  [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1.98      guenther 1037:            "\t  [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1.100     jeremy   1038:            "\t  [-x proxy_address[:port]] [destination] [port]\n");
1.21      ericj    1039:        if (ret)
                   1040:                exit(1);
1.7       deraadt  1041: }