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

1.86    ! djm         1: /* $OpenBSD: netcat.c,v 1.85 2006/01/20 00:01:20 millert 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.31      ericj      65:
1.21      ericj      66: /* Command Line Options */
1.68      tedu       67: int    dflag;                                  /* detached, no stdin */
1.21      ericj      68: int    iflag;                                  /* Interval Flag */
1.80      mcbride    69: int    jflag;                                  /* use jumbo frames if we can */
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.65      markus     83: int    Sflag;                                  /* TCP MD5 signature option */
1.83      dtucker    84: int    Tflag = -1;                             /* IP Type of Service */
1.21      ericj      85:
1.49      hugh       86: int timeout = -1;
1.21      ericj      87: int family = AF_UNSPEC;
1.63      miod       88: char *portlist[PORT_MAX+1];
1.21      ericj      89:
1.40      millert    90: void   atelnet(int, unsigned char *, unsigned int);
                     91: void   build_ports(char *);
                     92: void   help(void);
                     93: int    local_listen(char *, char *, struct addrinfo);
                     94: void   readwrite(int);
1.77      otto       95: int    remote_connect(const char *, const char *, struct addrinfo);
1.86    ! djm        96: int    socks_connect(const char *, const char *, struct addrinfo,
        !            97:            const char *, const char *, struct addrinfo, int, const char *);
1.40      millert    98: int    udptest(int);
1.42      ericj      99: int    unix_connect(char *);
                    100: int    unix_listen(char *);
1.84      dtucker   101: void   set_common_sockopts(int);
1.83      dtucker   102: int    parse_iptos(char *);
1.40      millert   103: void   usage(int);
1.1       deraadt   104:
1.21      ericj     105: int
1.37      jakob     106: main(int argc, char *argv[])
1.21      ericj     107: {
1.46      markus    108:        int ch, s, ret, socksv;
1.26      ericj     109:        char *host, *uport, *endp;
1.21      ericj     110:        struct addrinfo hints;
1.29      smart     111:        struct servent *sv;
1.21      ericj     112:        socklen_t len;
1.76      hshoexer  113:        struct sockaddr_storage cliaddr;
1.34      jakob     114:        char *proxy;
1.77      otto      115:        const char *proxyhost = "", *proxyport = NULL;
1.34      jakob     116:        struct addrinfo proxyhints;
1.11      ericj     117:
1.29      smart     118:        ret = 1;
                    119:        s = 0;
1.46      markus    120:        socksv = 5;
1.29      smart     121:        host = NULL;
                    122:        uport = NULL;
                    123:        endp = NULL;
                    124:        sv = NULL;
                    125:
1.80      mcbride   126:        while ((ch = getopt(argc, argv,
1.86    ! djm       127:            "46Ddhi:jklnP:p:rSs:tT:Uuvw:X:x:z")) != -1) {
1.21      ericj     128:                switch (ch) {
                    129:                case '4':
                    130:                        family = AF_INET;
                    131:                        break;
                    132:                case '6':
                    133:                        family = AF_INET6;
                    134:                        break;
1.42      ericj     135:                case 'U':
                    136:                        family = AF_UNIX;
                    137:                        break;
1.46      markus    138:                case 'X':
1.75      djm       139:                        if (strcasecmp(optarg, "connect") == 0)
                    140:                                socksv = -1; /* HTTP proxy CONNECT */
                    141:                        else if (strcmp(optarg, "4") == 0)
                    142:                                socksv = 4; /* SOCKS v.4 */
                    143:                        else if (strcmp(optarg, "5") == 0)
                    144:                                socksv = 5; /* SOCKS v.5 */
                    145:                        else
                    146:                                errx(1, "unsupported proxy protocol");
1.46      markus    147:                        break;
1.68      tedu      148:                case 'd':
                    149:                        dflag = 1;
                    150:                        break;
1.21      ericj     151:                case 'h':
                    152:                        help();
                    153:                        break;
                    154:                case 'i':
1.26      ericj     155:                        iflag = (int)strtoul(optarg, &endp, 10);
                    156:                        if (iflag < 0 || *endp != '\0')
                    157:                                errx(1, "interval cannot be negative");
1.21      ericj     158:                        break;
1.80      mcbride   159:                case 'j':
                    160:                        jflag = 1;
                    161:                        break;
1.21      ericj     162:                case 'k':
                    163:                        kflag = 1;
                    164:                        break;
                    165:                case 'l':
                    166:                        lflag = 1;
                    167:                        break;
                    168:                case 'n':
                    169:                        nflag = 1;
                    170:                        break;
1.86    ! djm       171:                case 'P':
        !           172:                        Pflag = optarg;
        !           173:                        break;
1.21      ericj     174:                case 'p':
                    175:                        pflag = optarg;
                    176:                        break;
                    177:                case 'r':
                    178:                        rflag = 1;
                    179:                        break;
                    180:                case 's':
                    181:                        sflag = optarg;
                    182:                        break;
                    183:                case 't':
                    184:                        tflag = 1;
                    185:                        break;
                    186:                case 'u':
                    187:                        uflag = 1;
                    188:                        break;
                    189:                case 'v':
                    190:                        vflag = 1;
                    191:                        break;
1.70      deraadt   192:                case 'w':
1.26      ericj     193:                        timeout = (int)strtoul(optarg, &endp, 10);
                    194:                        if (timeout < 0 || *endp != '\0')
                    195:                                errx(1, "timeout cannot be negative");
1.49      hugh      196:                        if (timeout >= (INT_MAX / 1000))
                    197:                                errx(1, "timeout too large");
                    198:                        timeout *= 1000;
1.21      ericj     199:                        break;
1.34      jakob     200:                case 'x':
                    201:                        xflag = 1;
1.64      deraadt   202:                        if ((proxy = strdup(optarg)) == NULL)
                    203:                                err(1, NULL);
1.34      jakob     204:                        break;
1.21      ericj     205:                case 'z':
                    206:                        zflag = 1;
                    207:                        break;
1.73      markus    208:                case 'D':
                    209:                        Dflag = 1;
                    210:                        break;
1.65      markus    211:                case 'S':
                    212:                        Sflag = 1;
                    213:                        break;
1.83      dtucker   214:                case 'T':
                    215:                        Tflag = parse_iptos(optarg);
                    216:                        break;
1.21      ericj     217:                default:
                    218:                        usage(1);
                    219:                }
                    220:        }
                    221:        argc -= optind;
                    222:        argv += optind;
1.11      ericj     223:
1.21      ericj     224:        /* Cruft to make sure options are clean, and used properly. */
1.42      ericj     225:        if (argv[0] && !argv[1] && family == AF_UNIX) {
                    226:                if (uflag)
                    227:                        errx(1, "cannot use -u and -U");
                    228:                host = argv[0];
                    229:                uport = NULL;
                    230:        } else if (argv[0] && !argv[1]) {
1.21      ericj     231:                if  (!lflag)
                    232:                        usage(1);
                    233:                uport = argv[0];
                    234:                host = NULL;
                    235:        } else if (argv[0] && argv[1]) {
                    236:                host = argv[0];
                    237:                uport = argv[1];
                    238:        } else
                    239:                usage(1);
1.1       deraadt   240:
1.21      ericj     241:        if (lflag && sflag)
                    242:                errx(1, "cannot use -s and -l");
                    243:        if (lflag && pflag)
                    244:                errx(1, "cannot use -p and -l");
                    245:        if (lflag && zflag)
1.32      ericj     246:                errx(1, "cannot use -z and -l");
1.21      ericj     247:        if (!lflag && kflag)
1.32      ericj     248:                errx(1, "must use -l with -k");
1.21      ericj     249:
1.67      jmc       250:        /* Initialize addrinfo structure. */
1.42      ericj     251:        if (family != AF_UNIX) {
                    252:                memset(&hints, 0, sizeof(struct addrinfo));
                    253:                hints.ai_family = family;
                    254:                hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
                    255:                hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
                    256:                if (nflag)
                    257:                        hints.ai_flags |= AI_NUMERICHOST;
                    258:        }
1.1       deraadt   259:
1.34      jakob     260:        if (xflag) {
                    261:                if (uflag)
                    262:                        errx(1, "no proxy support for UDP mode");
                    263:
                    264:                if (lflag)
                    265:                        errx(1, "no proxy support for listen");
                    266:
1.42      ericj     267:                if (family == AF_UNIX)
                    268:                        errx(1, "no proxy support for unix sockets");
                    269:
1.34      jakob     270:                /* XXX IPv6 transport to proxy would probably work */
                    271:                if (family == AF_INET6)
                    272:                        errx(1, "no proxy support for IPv6");
                    273:
                    274:                if (sflag)
                    275:                        errx(1, "no proxy support for local source address");
                    276:
                    277:                proxyhost = strsep(&proxy, ":");
                    278:                proxyport = proxy;
                    279:
                    280:                memset(&proxyhints, 0, sizeof(struct addrinfo));
                    281:                proxyhints.ai_family = family;
                    282:                proxyhints.ai_socktype = SOCK_STREAM;
                    283:                proxyhints.ai_protocol = IPPROTO_TCP;
                    284:                if (nflag)
                    285:                        proxyhints.ai_flags |= AI_NUMERICHOST;
                    286:        }
                    287:
1.21      ericj     288:        if (lflag) {
                    289:                int connfd;
1.27      ericj     290:                ret = 0;
1.1       deraadt   291:
1.42      ericj     292:                if (family == AF_UNIX)
                    293:                        s = unix_listen(host);
                    294:
1.67      jmc       295:                /* Allow only one connection at a time, but stay alive. */
1.21      ericj     296:                for (;;) {
1.42      ericj     297:                        if (family != AF_UNIX)
                    298:                                s = local_listen(host, uport, hints);
                    299:                        if (s < 0)
1.30      smart     300:                                err(1, NULL);
1.21      ericj     301:                        /*
                    302:                         * For UDP, we will use recvfrom() initially
                    303:                         * to wait for a caller, then use the regular
                    304:                         * functions to talk to the caller.
                    305:                         */
                    306:                        if (uflag) {
1.80      mcbride   307:                                int rv, plen;
                    308:                                char buf[8192];
1.21      ericj     309:                                struct sockaddr_storage z;
                    310:
                    311:                                len = sizeof(z);
1.80      mcbride   312:                                plen = jflag ? 8192 : 1024;
                    313:                                rv = recvfrom(s, buf, plen, MSG_PEEK,
1.37      jakob     314:                                    (struct sockaddr *)&z, &len);
1.23      ericj     315:                                if (rv < 0)
1.57      stevesk   316:                                        err(1, "recvfrom");
1.21      ericj     317:
1.37      jakob     318:                                rv = connect(s, (struct sockaddr *)&z, len);
1.23      ericj     319:                                if (rv < 0)
1.57      stevesk   320:                                        err(1, "connect");
1.1       deraadt   321:
1.21      ericj     322:                                connfd = s;
                    323:                        } else {
1.78      otto      324:                                len = sizeof(cliaddr);
1.21      ericj     325:                                connfd = accept(s, (struct sockaddr *)&cliaddr,
1.37      jakob     326:                                    &len);
1.21      ericj     327:                        }
1.1       deraadt   328:
1.21      ericj     329:                        readwrite(connfd);
                    330:                        close(connfd);
1.42      ericj     331:                        if (family != AF_UNIX)
                    332:                                close(s);
1.27      ericj     333:
1.21      ericj     334:                        if (!kflag)
                    335:                                break;
1.11      ericj     336:                }
1.42      ericj     337:        } else if (family == AF_UNIX) {
                    338:                ret = 0;
                    339:
                    340:                if ((s = unix_connect(host)) > 0 && !zflag) {
                    341:                        readwrite(s);
                    342:                        close(s);
                    343:                } else
                    344:                        ret = 1;
                    345:
                    346:                exit(ret);
                    347:
1.21      ericj     348:        } else {
                    349:                int i = 0;
1.6       deraadt   350:
1.67      jmc       351:                /* Construct the portlist[] array. */
1.21      ericj     352:                build_ports(uport);
1.1       deraadt   353:
1.67      jmc       354:                /* Cycle through portlist, connecting to each port. */
1.21      ericj     355:                for (i = 0; portlist[i] != NULL; i++) {
                    356:                        if (s)
                    357:                                close(s);
1.34      jakob     358:
                    359:                        if (xflag)
                    360:                                s = socks_connect(host, portlist[i], hints,
1.86    ! djm       361:                                    proxyhost, proxyport, proxyhints, socksv,
        !           362:                                    Pflag);
1.34      jakob     363:                        else
                    364:                                s = remote_connect(host, portlist[i], hints);
                    365:
                    366:                        if (s < 0)
1.21      ericj     367:                                continue;
1.1       deraadt   368:
1.21      ericj     369:                        ret = 0;
                    370:                        if (vflag || zflag) {
1.67      jmc       371:                                /* For UDP, make sure we are connected. */
1.21      ericj     372:                                if (uflag) {
1.50      vincent   373:                                        if (udptest(s) == -1) {
1.21      ericj     374:                                                ret = 1;
                    375:                                                continue;
                    376:                                        }
                    377:                                }
1.1       deraadt   378:
1.67      jmc       379:                                /* Don't look up port if -n. */
1.21      ericj     380:                                if (nflag)
                    381:                                        sv = NULL;
                    382:                                else {
                    383:                                        sv = getservbyport(
1.37      jakob     384:                                            ntohs(atoi(portlist[i])),
                    385:                                            uflag ? "udp" : "tcp");
1.21      ericj     386:                                }
1.50      vincent   387:
1.21      ericj     388:                                printf("Connection to %s %s port [%s/%s] succeeded!\n",
1.37      jakob     389:                                    host, portlist[i], uflag ? "udp" : "tcp",
                    390:                                    sv ? sv->s_name : "*");
1.21      ericj     391:                        }
                    392:                        if (!zflag)
                    393:                                readwrite(s);
1.7       deraadt   394:                }
1.11      ericj     395:        }
1.1       deraadt   396:
1.21      ericj     397:        if (s)
                    398:                close(s);
                    399:
                    400:        exit(ret);
1.7       deraadt   401: }
1.1       deraadt   402:
1.11      ericj     403: /*
1.42      ericj     404:  * unix_connect()
1.67      jmc       405:  * Returns a socket connected to a local unix socket. Returns -1 on failure.
1.42      ericj     406:  */
                    407: int
                    408: unix_connect(char *path)
                    409: {
                    410:        struct sockaddr_un sun;
                    411:        int s;
                    412:
                    413:        if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
1.50      vincent   414:                return (-1);
1.42      ericj     415:        (void)fcntl(s, F_SETFD, 1);
                    416:
                    417:        memset(&sun, 0, sizeof(struct sockaddr_un));
                    418:        sun.sun_family = AF_UNIX;
1.60      avsm      419:
                    420:        if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
                    421:            sizeof(sun.sun_path)) {
                    422:                close(s);
                    423:                errno = ENAMETOOLONG;
                    424:                return (-1);
                    425:        }
1.50      vincent   426:        if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
                    427:                close(s);
                    428:                return (-1);
1.42      ericj     429:        }
                    430:        return (s);
1.50      vincent   431:
1.42      ericj     432: }
                    433:
                    434: /*
                    435:  * unix_listen()
1.67      jmc       436:  * Create a unix domain socket, and listen on it.
1.42      ericj     437:  */
                    438: int
                    439: unix_listen(char *path)
                    440: {
                    441:        struct sockaddr_un sun;
                    442:        int s;
                    443:
1.67      jmc       444:        /* Create unix domain socket. */
1.42      ericj     445:        if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
                    446:                return (-1);
                    447:
1.60      avsm      448:        memset(&sun, 0, sizeof(struct sockaddr_un));
1.42      ericj     449:        sun.sun_family = AF_UNIX;
1.60      avsm      450:
                    451:        if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
                    452:            sizeof(sun.sun_path)) {
                    453:                close(s);
                    454:                errno = ENAMETOOLONG;
                    455:                return (-1);
                    456:        }
                    457:
1.50      vincent   458:        if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
1.42      ericj     459:                close(s);
                    460:                return (-1);
                    461:        }
                    462:
                    463:        if (listen(s, 5) < 0) {
                    464:                close(s);
                    465:                return (-1);
                    466:        }
                    467:        return (s);
                    468: }
                    469:
                    470: /*
1.21      ericj     471:  * remote_connect()
1.67      jmc       472:  * Returns a socket connected to a remote host. Properly binds to a local
                    473:  * port or source address if needed. Returns -1 on failure.
1.11      ericj     474:  */
1.21      ericj     475: int
1.77      otto      476: remote_connect(const char *host, const char *port, struct addrinfo hints)
1.21      ericj     477: {
                    478:        struct addrinfo *res, *res0;
1.81      marius    479:        int s, error;
1.21      ericj     480:
                    481:        if ((error = getaddrinfo(host, port, &hints, &res)))
1.56      stevesk   482:                errx(1, "getaddrinfo: %s", gai_strerror(error));
1.21      ericj     483:
                    484:        res0 = res;
                    485:        do {
                    486:                if ((s = socket(res0->ai_family, res0->ai_socktype,
1.37      jakob     487:                    res0->ai_protocol)) < 0)
1.21      ericj     488:                        continue;
                    489:
1.67      jmc       490:                /* Bind to a local port or source address if specified. */
1.21      ericj     491:                if (sflag || pflag) {
                    492:                        struct addrinfo ahints, *ares;
                    493:
                    494:                        if (!(sflag && pflag)) {
                    495:                                if (!sflag)
                    496:                                        sflag = NULL;
                    497:                                else
                    498:                                        pflag = NULL;
                    499:                        }
1.6       deraadt   500:
1.21      ericj     501:                        memset(&ahints, 0, sizeof(struct addrinfo));
                    502:                        ahints.ai_family = res0->ai_family;
                    503:                        ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
                    504:                        ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
1.25      ericj     505:                        ahints.ai_flags = AI_PASSIVE;
1.38      jakob     506:                        if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
1.56      stevesk   507:                                errx(1, "getaddrinfo: %s", gai_strerror(error));
1.21      ericj     508:
                    509:                        if (bind(s, (struct sockaddr *)ares->ai_addr,
1.62      millert   510:                            ares->ai_addrlen) < 0)
1.21      ericj     511:                                errx(1, "bind failed: %s", strerror(errno));
                    512:                        freeaddrinfo(ares);
1.6       deraadt   513:                }
1.81      marius    514:
                    515:                set_common_sockopts(s);
1.6       deraadt   516:
1.21      ericj     517:                if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
1.6       deraadt   518:                        break;
1.71      mcbride   519:                else if (vflag)
                    520:                        warn("connect to %s port %s (%s) failed", host, port,
                    521:                            uflag ? "udp" : "tcp");
1.34      jakob     522:
1.21      ericj     523:                close(s);
                    524:                s = -1;
                    525:        } while ((res0 = res0->ai_next) != NULL);
                    526:
                    527:        freeaddrinfo(res);
1.1       deraadt   528:
1.21      ericj     529:        return (s);
1.7       deraadt   530: }
1.1       deraadt   531:
1.11      ericj     532: /*
1.21      ericj     533:  * local_listen()
1.67      jmc       534:  * Returns a socket listening on a local port, binds to specified source
                    535:  * address. Returns -1 on failure.
1.11      ericj     536:  */
1.21      ericj     537: int
1.37      jakob     538: local_listen(char *host, char *port, struct addrinfo hints)
1.21      ericj     539: {
                    540:        struct addrinfo *res, *res0;
                    541:        int s, ret, x = 1;
                    542:        int error;
1.6       deraadt   543:
1.67      jmc       544:        /* Allow nodename to be null. */
1.21      ericj     545:        hints.ai_flags |= AI_PASSIVE;
1.7       deraadt   546:
1.21      ericj     547:        /*
                    548:         * In the case of binding to a wildcard address
                    549:         * default to binding to an ipv4 address.
                    550:         */
                    551:        if (host == NULL && hints.ai_family == AF_UNSPEC)
                    552:                hints.ai_family = AF_INET;
1.1       deraadt   553:
1.21      ericj     554:        if ((error = getaddrinfo(host, port, &hints, &res)))
1.70      deraadt   555:                errx(1, "getaddrinfo: %s", gai_strerror(error));
1.14      ericj     556:
1.21      ericj     557:        res0 = res;
                    558:        do {
                    559:                if ((s = socket(res0->ai_family, res0->ai_socktype,
1.82      marius    560:                    res0->ai_protocol)) < 0)
1.21      ericj     561:                        continue;
1.1       deraadt   562:
1.21      ericj     563:                ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
                    564:                if (ret == -1)
1.30      smart     565:                        err(1, NULL);
1.81      marius    566:
                    567:                set_common_sockopts(s);
1.1       deraadt   568:
1.21      ericj     569:                if (bind(s, (struct sockaddr *)res0->ai_addr,
1.37      jakob     570:                    res0->ai_addrlen) == 0)
1.21      ericj     571:                        break;
1.1       deraadt   572:
1.21      ericj     573:                close(s);
                    574:                s = -1;
                    575:        } while ((res0 = res0->ai_next) != NULL);
1.1       deraadt   576:
1.47      ericj     577:        if (!uflag && s != -1) {
1.21      ericj     578:                if (listen(s, 1) < 0)
1.57      stevesk   579:                        err(1, "listen");
1.12      ericj     580:        }
1.1       deraadt   581:
1.21      ericj     582:        freeaddrinfo(res);
1.1       deraadt   583:
1.21      ericj     584:        return (s);
1.7       deraadt   585: }
                    586:
1.11      ericj     587: /*
1.21      ericj     588:  * readwrite()
                    589:  * Loop that polls on the network file descriptor and stdin.
1.11      ericj     590:  */
1.21      ericj     591: void
1.37      jakob     592: readwrite(int nfd)
1.6       deraadt   593: {
1.52      vincent   594:        struct pollfd pfd[2];
1.80      mcbride   595:        unsigned char buf[8192];
1.79      avsm      596:        int n, wfd = fileno(stdin);
1.21      ericj     597:        int lfd = fileno(stdout);
1.80      mcbride   598:        int plen;
                    599:
                    600:        plen = jflag ? 8192 : 1024;
1.21      ericj     601:
                    602:        /* Setup Network FD */
                    603:        pfd[0].fd = nfd;
                    604:        pfd[0].events = POLLIN;
                    605:
1.67      jmc       606:        /* Set up STDIN FD. */
1.21      ericj     607:        pfd[1].fd = wfd;
                    608:        pfd[1].events = POLLIN;
                    609:
1.54      aaron     610:        while (pfd[0].fd != -1) {
1.21      ericj     611:                if (iflag)
                    612:                        sleep(iflag);
                    613:
1.68      tedu      614:                if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
1.21      ericj     615:                        close(nfd);
1.52      vincent   616:                        err(1, "Polling Error");
1.21      ericj     617:                }
1.49      hugh      618:
                    619:                if (n == 0)
                    620:                        return;
1.21      ericj     621:
                    622:                if (pfd[0].revents & POLLIN) {
1.80      mcbride   623:                        if ((n = read(nfd, buf, plen)) < 0)
1.21      ericj     624:                                return;
1.52      vincent   625:                        else if (n == 0) {
                    626:                                shutdown(nfd, SHUT_RD);
                    627:                                pfd[0].fd = -1;
                    628:                                pfd[0].events = 0;
1.21      ericj     629:                        } else {
                    630:                                if (tflag)
                    631:                                        atelnet(nfd, buf, n);
1.79      avsm      632:                                if (atomicio(vwrite, lfd, buf, n) != n)
1.21      ericj     633:                                        return;
1.6       deraadt   634:                        }
1.21      ericj     635:                }
                    636:
1.68      tedu      637:                if (!dflag && pfd[1].revents & POLLIN) {
1.80      mcbride   638:                        if ((n = read(wfd, buf, plen)) < 0)
1.21      ericj     639:                                return;
1.52      vincent   640:                        else if (n == 0) {
                    641:                                shutdown(nfd, SHUT_WR);
                    642:                                pfd[1].fd = -1;
                    643:                                pfd[1].events = 0;
                    644:                        } else {
1.79      avsm      645:                                if (atomicio(vwrite, nfd, buf, n) != n)
1.21      ericj     646:                                        return;
1.50      vincent   647:                        }
1.21      ericj     648:                }
1.11      ericj     649:        }
1.7       deraadt   650: }
1.50      vincent   651:
1.67      jmc       652: /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1.21      ericj     653: void
1.37      jakob     654: atelnet(int nfd, unsigned char *buf, unsigned int size)
1.6       deraadt   655: {
1.24      ericj     656:        unsigned char *p, *end;
                    657:        unsigned char obuf[4];
                    658:
                    659:        end = buf + size;
                    660:        obuf[0] = '\0';
                    661:
                    662:        for (p = buf; p < end; p++) {
1.21      ericj     663:                if (*p != IAC)
1.24      ericj     664:                        break;
                    665:
1.25      ericj     666:                obuf[0] = IAC;
1.24      ericj     667:                p++;
1.50      vincent   668:                if ((*p == WILL) || (*p == WONT))
1.24      ericj     669:                        obuf[1] = DONT;
1.50      vincent   670:                if ((*p == DO) || (*p == DONT))
1.24      ericj     671:                        obuf[1] = WONT;
                    672:                if (obuf) {
                    673:                        p++;
1.11      ericj     674:                        obuf[2] = *p;
1.24      ericj     675:                        obuf[3] = '\0';
1.79      avsm      676:                        if (atomicio(vwrite, nfd, obuf, 3) != 3)
                    677:                                warn("Write Error!");
1.24      ericj     678:                        obuf[0] = '\0';
1.11      ericj     679:                }
                    680:        }
1.7       deraadt   681: }
                    682:
1.11      ericj     683: /*
1.21      ericj     684:  * build_ports()
                    685:  * Build an array or ports in portlist[], listing each port
1.67      jmc       686:  * that we should try to connect to.
1.11      ericj     687:  */
1.21      ericj     688: void
1.37      jakob     689: build_ports(char *p)
1.6       deraadt   690: {
1.26      ericj     691:        char *n, *endp;
1.21      ericj     692:        int hi, lo, cp;
                    693:        int x = 0;
                    694:
                    695:        if ((n = strchr(p, '-')) != NULL) {
                    696:                if (lflag)
                    697:                        errx(1, "Cannot use -l with multiple ports!");
                    698:
                    699:                *n = '\0';
                    700:                n++;
                    701:
1.67      jmc       702:                /* Make sure the ports are in order: lowest->highest. */
1.26      ericj     703:                hi = (int)strtoul(n, &endp, 10);
1.31      ericj     704:                if (hi <= 0 || hi > PORT_MAX || *endp != '\0')
1.26      ericj     705:                        errx(1, "port range not valid");
                    706:                lo = (int)strtoul(p, &endp, 10);
1.31      ericj     707:                if (lo <= 0 || lo > PORT_MAX || *endp != '\0')
1.26      ericj     708:                        errx(1, "port range not valid");
1.21      ericj     709:
                    710:                if (lo > hi) {
                    711:                        cp = hi;
                    712:                        hi = lo;
                    713:                        lo = cp;
                    714:                }
                    715:
1.67      jmc       716:                /* Load ports sequentially. */
1.21      ericj     717:                for (cp = lo; cp <= hi; cp++) {
1.55      fgsch     718:                        portlist[x] = calloc(1, PORT_MAX_LEN);
                    719:                        if (portlist[x] == NULL)
                    720:                                err(1, NULL);
                    721:                        snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1.21      ericj     722:                        x++;
                    723:                }
                    724:
1.67      jmc       725:                /* Randomly swap ports. */
1.21      ericj     726:                if (rflag) {
                    727:                        int y;
                    728:                        char *c;
                    729:
                    730:                        for (x = 0; x <= (hi - lo); x++) {
                    731:                                y = (arc4random() & 0xFFFF) % (hi - lo);
                    732:                                c = portlist[x];
                    733:                                portlist[x] = portlist[y];
                    734:                                portlist[y] = c;
1.6       deraadt   735:                        }
1.11      ericj     736:                }
1.21      ericj     737:        } else {
1.26      ericj     738:                hi = (int)strtoul(p, &endp, 10);
1.31      ericj     739:                if (hi <= 0 || hi > PORT_MAX || *endp != '\0')
1.26      ericj     740:                        errx(1, "port range not valid");
1.55      fgsch     741:                portlist[0] = calloc(1, PORT_MAX_LEN);
                    742:                if (portlist[0] == NULL)
                    743:                        err(1, NULL);
1.21      ericj     744:                portlist[0] = p;
1.11      ericj     745:        }
1.13      ericj     746: }
                    747:
                    748: /*
1.21      ericj     749:  * udptest()
                    750:  * Do a few writes to see if the UDP port is there.
1.67      jmc       751:  * XXX - Better way of doing this? Doesn't work for IPv6.
1.21      ericj     752:  * Also fails after around 100 ports checked.
1.13      ericj     753:  */
1.21      ericj     754: int
1.37      jakob     755: udptest(int s)
1.13      ericj     756: {
1.74      deraadt   757:        int i, ret;
1.13      ericj     758:
1.52      vincent   759:        for (i = 0; i <= 3; i++) {
1.74      deraadt   760:                if (write(s, "X", 1) == 1)
1.21      ericj     761:                        ret = 1;
1.14      ericj     762:                else
1.21      ericj     763:                        ret = -1;
1.14      ericj     764:        }
1.21      ericj     765:        return (ret);
1.81      marius    766: }
                    767:
1.84      dtucker   768: void
1.81      marius    769: set_common_sockopts(int s)
                    770: {
                    771:        int x = 1;
                    772:
                    773:        if (Sflag) {
                    774:                if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
                    775:                        &x, sizeof(x)) == -1)
                    776:                        err(1, NULL);
                    777:        }
                    778:        if (Dflag) {
                    779:                if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
                    780:                        &x, sizeof(x)) == -1)
                    781:                        err(1, NULL);
                    782:        }
                    783:        if (jflag) {
                    784:                if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
                    785:                        &x, sizeof(x)) == -1)
                    786:                        err(1, NULL);
                    787:        }
1.83      dtucker   788:        if (Tflag != -1) {
                    789:                if (setsockopt(s, IPPROTO_IP, IP_TOS,
                    790:                    &Tflag, sizeof(Tflag)) == -1)
                    791:                        err(1, "set IP ToS");
                    792:        }
                    793: }
                    794:
                    795: int
                    796: parse_iptos(char *s)
                    797: {
                    798:        int tos = -1;
                    799:
                    800:        if (strcmp(s, "lowdelay") == 0)
                    801:                return (IPTOS_LOWDELAY);
                    802:        if (strcmp(s, "throughput") == 0)
                    803:                return (IPTOS_THROUGHPUT);
                    804:        if (strcmp(s, "reliability") == 0)
                    805:                return (IPTOS_RELIABILITY);
                    806:
                    807:        if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
                    808:                errx(1, "invalid IP Type of Service");
                    809:        return (tos);
1.7       deraadt   810: }
1.1       deraadt   811:
1.11      ericj     812: void
1.58      deraadt   813: help(void)
1.1       deraadt   814: {
1.21      ericj     815:        usage(0);
                    816:        fprintf(stderr, "\tCommand Summary:\n\
                    817:        \t-4            Use IPv4\n\
                    818:        \t-6            Use IPv6\n\
1.73      markus    819:        \t-D            Enable the debug socket option\n\
1.69      tedu      820:        \t-d            Detach from stdin\n\
1.21      ericj     821:        \t-h            This help text\n\
                    822:        \t-i secs\t     Delay interval for lines sent, ports scanned\n\
                    823:        \t-k            Keep inbound sockets open for multiple connects\n\
                    824:        \t-l            Listen mode, for inbound connects\n\
1.22      jasoni    825:        \t-n            Suppress name/port resolutions\n\
1.86    ! djm       826:        \t-P proxyuser\tUsername for proxy authentication\n\
1.36      jakob     827:        \t-p port\t     Specify local port for remote connects\n\
1.21      ericj     828:        \t-r            Randomize remote ports\n\
1.67      jmc       829:        \t-S            Enable the TCP MD5 signature option\n\
1.21      ericj     830:        \t-s addr\t     Local source address\n\
1.83      dtucker   831:        \t-T ToS\t      Set IP Type of Service\n\
1.21      ericj     832:        \t-t            Answer TELNET negotiation\n\
1.67      jmc       833:        \t-U            Use UNIX domain socket\n\
1.21      ericj     834:        \t-u            UDP mode\n\
                    835:        \t-v            Verbose\n\
                    836:        \t-w secs\t     Timeout for connects and final net reads\n\
1.75      djm       837:        \t-X proto      Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
                    838:        \t-x addr[:port]\tSpecify proxy address and port\n\
1.21      ericj     839:        \t-z            Zero-I/O mode [used for scanning]\n\
                    840:        Port numbers can be individual or ranges: lo-hi [inclusive]\n");
                    841:        exit(1);
1.11      ericj     842: }
                    843:
                    844: void
1.37      jakob     845: usage(int ret)
1.11      ericj     846: {
1.73      markus    847:        fprintf(stderr, "usage: nc [-46DdhklnrStUuvz] [-i interval] [-p source_port]\n");
1.83      dtucker   848:        fprintf(stderr, "\t  [-s source_ip_address] [-T ToS] [-w timeout] [-X proxy_version]\n");
1.72      jmc       849:        fprintf(stderr, "\t  [-x proxy_address[:port]] [hostname] [port[s]]\n");
1.21      ericj     850:        if (ret)
                    851:                exit(1);
1.7       deraadt   852: }