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

1.17    ! ericj       1: /* $OpenBSD: netcat.c,v 1.16 2000/09/26 17:46:40 ericj Exp $ */
1.11      ericj       2:
1.1       deraadt     3: /* Netcat 1.10 RELEASE 960320
1.7       deraadt     4:  *
                      5:  *   A damn useful little "backend" utility begun 950915 or thereabouts,
                      6:  *   as *Hobbit*'s first real stab at some sockets programming.  Something that
                      7:  *   should have and indeed may have existed ten years ago, but never became a
                      8:  *   standard Unix utility.  IMHO, "nc" could take its place right next to cat,
                      9:  *   cp, rm, mv, dd, ls, and all those other cryptic and Unix-like things.
                     10:  *
                     11:  *   Read the README for the whole story, doc, applications, etc.
                     12:  *
                     13:  *   Layout:
                     14:  *     conditional includes:
                     15:  *     includes:
                     16:  *     handy defines:
                     17:  *     globals:
                     18:  *     malloced globals:
                     19:  *     cmd-flag globals:
                     20:  *     support routines:
                     21:  *     readwrite select loop:
                     22:  *     main:
                     23:  *
                     24:  *  bluesky:
                     25:  *     parse ranges of IP address as well as ports, perhaps
                     26:  *     RAW mode!
                     27:  *     backend progs to grab a pty and look like a real telnetd?!
                     28:  *     backend progs to do various encryption modes??!?!
1.1       deraadt    29: */
                     30:
                     31:
1.7       deraadt    32: #include <sys/types.h>
                     33: #include <sys/time.h>
                     34: #include <sys/select.h>
                     35: #include <sys/socket.h>
                     36: #include <netinet/in.h>
                     37: #include <netinet/in_systm.h>
                     38: #include <netinet/ip.h>
                     39: #include <arpa/inet.h>
                     40: #include <netdb.h>             /* hostent, gethostby*, getservby* */
                     41: #include <stdio.h>
                     42: #include <string.h>
1.11      ericj      43: #include <err.h>
1.7       deraadt    44: #include <errno.h>
                     45: #include <setjmp.h>
                     46: #include <signal.h>
                     47: #include <fcntl.h>
1.13      ericj      48: #include <stdarg.h>
1.1       deraadt    49: #include <stdlib.h>
1.5       art        50: #include <unistd.h>
1.1       deraadt    51:
                     52: #define SLEAZE_PORT 31337      /* for UDP-scan RTT trick, change if ya want */
                     53: #define BIGSIZ 8192            /* big buffers */
                     54:
1.7       deraadt    55: struct host_info {
1.11      ericj      56:        char    name[MAXHOSTNAMELEN];   /* DNS name */
                     57:        char    addrs[8][24];           /* ascii-format IP addresses */
                     58:        struct  in_addr iaddrs[8];      /* in_addr.s_addr: ulong */
1.1       deraadt    59: };
                     60:
1.7       deraadt    61: struct port_info {
1.6       deraadt    62:        char    name[64];       /* name in /etc/services */
                     63:        char    anum[8];        /* ascii-format number */
1.7       deraadt    64:        u_short  num;           /* real host-order number */
1.1       deraadt    65: };
                     66:
                     67: /* globals: */
1.11      ericj      68: jmp_buf jbuf;                  /* timer jump buffer*/
1.6       deraadt    69: int     jval = 0;              /* timer crud */
                     70: int     netfd = -1;
                     71: int     ofd = 0;               /* hexdump output fd */
1.7       deraadt    72:
1.6       deraadt    73: int     gatesidx = 0;          /* LSRR hop count */
                     74: int     gatesptr = 4;          /* initial LSRR pointer, settable */
1.7       deraadt    75: u_short  Single = 1;           /* zero if scanning */
1.1       deraadt    76: unsigned int insaved = 0;      /* stdin-buffer size for multi-mode */
                     77: unsigned int wrote_out = 0;    /* total stdout bytes */
                     78: unsigned int wrote_net = 0;    /* total net bytes */
                     79: static char hexnibs[20] = "0123456789abcdef  ";
                     80:
                     81: /* will malloc up the following globals: */
1.7       deraadt    82: struct timeval timer1, timer2;
1.11      ericj      83: struct sockaddr_in    *lclend = NULL;  /* sockaddr_in structs */
1.7       deraadt    84: struct sockaddr_in    *remend = NULL;
1.11      ericj      85: struct host_info  **gates = NULL;      /* LSRR hop hinfo */
                     86: char   *optbuf = NULL;                 /* LSRR or sockopts */
                     87: char   *bigbuf_in;                     /* data buffers */
1.6       deraadt    88: char   *bigbuf_net;
1.7       deraadt    89: fd_set fds1, fds2;
1.11      ericj      90: struct port_info   *pinfo = NULL;      /* for getpinfo / getservby* */
                     91: unsigned char *stage = NULL;           /* hexdump line buffer */
1.1       deraadt    92:
                     93: /* global cmd flags: */
1.7       deraadt    94: u_short  o_alla = 0;
1.1       deraadt    95: unsigned int o_interval = 0;
1.7       deraadt    96: u_short  o_listen = 0;
                     97: u_short  o_nflag = 0;
                     98: u_short  o_wfile = 0;
                     99: u_short  o_random = 0;
                    100: u_short  o_udpmode = 0;
                    101: u_short  o_verbose = 0;
1.1       deraadt   102: unsigned int o_wait = 0;
1.7       deraadt   103: u_short  o_zero = 0;
1.1       deraadt   104:
1.11      ericj     105: /* Function Prototype's */
1.17    ! ericj     106: void   help __P(());
1.13      ericj     107: void   nlog __P((int, char *, ...));
1.17    ! ericj     108: void   usage __P((int));
1.11      ericj     109:
                    110: /*
                    111:  * support routines -- the bulk of this thing.  Placed in such an order that
                    112:  * we don't have to forward-declare anything:
                    113:  */
                    114:
                    115: /*
                    116:  * catch :
                    117:  * no-brainer interrupt handler
                    118:  */
1.6       deraadt   119: void
                    120: catch()
1.1       deraadt   121: {
1.17    ! ericj     122:        if (o_verbose)  /* normally we don't care */
1.13      ericj     123:                nlog(1, "Sent %i Rcvd %i", wrote_net, wrote_out);
                    124:        nlog(1, " punt!");
1.1       deraadt   125: }
                    126:
                    127: /* timeout and other signal handling cruft */
1.6       deraadt   128: void
                    129: tmtravel()
1.1       deraadt   130: {
1.6       deraadt   131:        signal(SIGALRM, SIG_IGN);
                    132:        alarm(0);
                    133:        if (jval == 0)
1.13      ericj     134:                nlog(1, "spurious timer interrupt!");
1.6       deraadt   135:        longjmp(jbuf, jval);
1.1       deraadt   136: }
                    137:
1.11      ericj     138: /*
                    139:  * arm :
                    140:  * set the timer.  Zero secs arg means unarm
                    141:  */
1.6       deraadt   142: void
                    143: arm(num, secs)
                    144:        unsigned int num;
                    145:        unsigned int secs;
                    146: {
1.11      ericj     147:        if (secs == 0) {
1.6       deraadt   148:                signal(SIGALRM, SIG_IGN);
                    149:                alarm(0);
                    150:                jval = 0;
1.11      ericj     151:        } else {
1.6       deraadt   152:                signal(SIGALRM, tmtravel);
                    153:                alarm(secs);
                    154:                jval = num;
1.11      ericj     155:        }
1.7       deraadt   156: }
1.1       deraadt   157:
1.11      ericj     158: /*
                    159:  * findline :
                    160:  * find the next newline in a buffer; return inclusive size of that "line",
                    161:  * or the entire buffer size, so the caller knows how much to then write().
                    162:  * Not distinguishing \n vs \r\n for the nonce; it just works as is...
                    163:  */
1.6       deraadt   164: unsigned int
                    165: findline(buf, siz)
                    166:        char   *buf;
                    167:        unsigned int siz;
                    168: {
1.11      ericj     169:        char *p;
                    170:        int x;
1.6       deraadt   171:        if (!buf)               /* various sanity checks... */
                    172:                return (0);
                    173:        if (siz > BIGSIZ)
                    174:                return (0);
                    175:        x = siz;
                    176:        for (p = buf; x > 0; x--) {
                    177:                if (*p == '\n') {
                    178:                        x = (int) (p - buf);
                    179:                        x++;    /* 'sokay if it points just past the end! */
                    180:                            return (x);
                    181:                }
                    182:                p++;
1.11      ericj     183:        }
1.6       deraadt   184:            return (siz);
1.7       deraadt   185: }
1.1       deraadt   186:
1.11      ericj     187: /*
                    188:  * comparehosts :
                    189:  * cross-check the host_info we have so far against new gethostby*() info,
                    190:  * and holler about mismatches.  Perhaps gratuitous, but it can't hurt to
                    191:  * point out when someone's DNS is fukt.  Returns 1 if mismatch, in case
                    192:  * someone else wants to do something about it.
                    193:  */
1.6       deraadt   194: int
1.11      ericj     195: comparehosts(hinfo, hp)
                    196:        struct host_info   *hinfo;
1.6       deraadt   197:        struct hostent *hp;
                    198: {
1.11      ericj     199:        if (strcasecmp(hinfo->name, hp->h_name) != 0) {
1.13      ericj     200:                nlog(0, "DNS fwd/rev mismatch: %s != %s", hinfo->name, hp->h_name);
1.6       deraadt   201:                return (1);
                    202:        }
                    203:        return (0);
1.7       deraadt   204: }
1.1       deraadt   205:
1.11      ericj     206: /*
                    207:  * gethinfo:
                    208:  * resolve a host 8 ways from sunday; return a new host_info struct with its
                    209:  * info.  The argument can be a name or [ascii] IP address; it will try its
                    210:  * damndest to deal with it.  "numeric" governs whether we do any DNS at all,
                    211:  * and we also check o_verbose for what's appropriate work to do.
                    212:  */
1.7       deraadt   213: struct host_info   *
1.11      ericj     214: gethinfo(name, numeric)
1.6       deraadt   215:        char   *name;
1.7       deraadt   216:        u_short  numeric;
1.6       deraadt   217: {
                    218:        struct hostent *hostent;
                    219:        struct in_addr iaddr;
1.11      ericj     220:        struct host_info *hinfo = NULL;
                    221:        int x;
1.1       deraadt   222:
1.6       deraadt   223:        if (name)
1.11      ericj     224:                hinfo = (struct host_info *) calloc(1, sizeof(struct host_info));
                    225:
                    226:        if (!hinfo)
1.13      ericj     227:                nlog(1, "error obtaining host information");
1.11      ericj     228:
                    229:        strlcpy(hinfo->name, "(UNKNOWN)", sizeof(hinfo->name));
1.7       deraadt   230:        if (inet_aton(name, &iaddr) == 0) {
1.11      ericj     231:                if (numeric)
1.13      ericj     232:                        nlog(1, "Can't parse %s as an IP address", name);
1.6       deraadt   233:
1.11      ericj     234:                /*
                    235:                 * failure to look up a name is fatal,
                    236:                 * since we can't do anything with it.
                    237:                 */
1.6       deraadt   238:                hostent = gethostbyname(name);
                    239:                if (!hostent)
1.13      ericj     240:                        nlog(1, "%s: forward host lookup failed: ", name);
1.11      ericj     241:
                    242:                strlcpy(hinfo->name, hostent->h_name, MAXHOSTNAMELEN);
1.6       deraadt   243:                for (x = 0; hostent->h_addr_list[x] && (x < 8); x++) {
1.11      ericj     244:                        memcpy(&hinfo->iaddrs[x], hostent->h_addr_list[x],
1.7       deraadt   245:                            sizeof(struct in_addr));
1.11      ericj     246:                        strlcpy(hinfo->addrs[x], inet_ntoa(hinfo->iaddrs[x]),
                    247:                            sizeof(hinfo->addrs[0]));
1.7       deraadt   248:                }
1.11      ericj     249:                /* Go ahead and return if we don't want to view more */
                    250:                if (!o_verbose)
                    251:                        return (hinfo);
                    252:
                    253:                /*
                    254:                 * Do inverse lookups in separate loop based on our collected
                    255:                 * forward addrs, since gethostby* tends to crap into the same
                    256:                 * buffer over and over.
                    257:                 */
                    258:                for (x = 0; hinfo->iaddrs[x].s_addr && (x < 8); x++) {
                    259:                        hostent = gethostbyaddr((char *) &hinfo->iaddrs[x],
1.7       deraadt   260:                            sizeof(struct in_addr), AF_INET);
1.6       deraadt   261:                        if ((!hostent) || (!hostent->h_name))
1.13      ericj     262:                                nlog(0, "Warning: inverse host lookup failed for %s: ",
1.11      ericj     263:                                    hinfo->addrs[x]);
1.6       deraadt   264:                        else
1.11      ericj     265:                                (void) comparehosts(hinfo, hostent);
                    266:                }
1.6       deraadt   267:
                    268:        } else {                /* not INADDR_NONE: numeric addresses... */
1.11      ericj     269:                memcpy(hinfo->iaddrs, &iaddr, sizeof(struct in_addr));
                    270:                strlcpy(hinfo->addrs[0], inet_ntoa(iaddr), sizeof(hinfo->addrs));
                    271:                /* If all that's wanted is numeric IP, go ahead and leave */
                    272:                if (numeric)
                    273:                        return (hinfo);
                    274:
                    275:                /* Go ahead and return if we don't want to view more */
                    276:                if (!o_verbose)
                    277:                        return (hinfo);
                    278:
                    279:                hostent = gethostbyaddr((char *) &iaddr,
                    280:                                        sizeof(struct in_addr), AF_INET);
                    281:
                    282:                /*
                    283:                 * numeric or not, failure to look up a PTR is
                    284:                 * *not* considered fatal
                    285:                 */
1.6       deraadt   286:                if (!hostent)
1.13      ericj     287:                        nlog(0, "%s: inverse host lookup failed: ", name);
1.6       deraadt   288:                else {
1.11      ericj     289:                        strlcpy(hinfo->name, hostent->h_name, MAXHOSTNAMELEN);
                    290:                        hostent = gethostbyname(hinfo->name);
1.6       deraadt   291:                        if ((!hostent) || (!hostent->h_addr_list[0]))
1.13      ericj     292:                                nlog(0, "Warning: forward host lookup failed for %s: ",
1.11      ericj     293:                                    hinfo->name);
1.6       deraadt   294:                        else
1.11      ericj     295:                                (void) comparehosts(hinfo, hostent);
                    296:                }
                    297:        }
1.1       deraadt   298:
1.11      ericj     299:        /*
                    300:         * Whatever-all went down previously, we should now have a host_info
                    301:         * struct with at least one IP address in it.
                    302:         */
                    303:        return (hinfo);
1.7       deraadt   304: }
1.1       deraadt   305:
1.11      ericj     306: /*
                    307:  * getpinfo:
                    308:  * Same general idea as gethinfo-- look up a port in /etc/services, fill
                    309:  * in global port_info, but return the actual port *number*.  Pass ONE of:
                    310:  *     pstring to resolve stuff like "23" or "exec";
                    311:  *     pnum to reverse-resolve something that's already a number.
                    312:  * If o_nflag is on, fill in what we can but skip the getservby??? stuff.
                    313:  * Might as well have consistent behavior here, and it *is* faster.
                    314:  */
1.7       deraadt   315: u_short
1.11      ericj     316: getpinfo(pstring, pnum)
1.6       deraadt   317:        char   *pstring;
                    318:        unsigned int pnum;
                    319: {
                    320:        struct servent *servent;
1.11      ericj     321:        int x;
                    322:        int y;
1.1       deraadt   323:
1.11      ericj     324:        pinfo->name[0] = '?';/* fast preload */
                    325:        pinfo->name[1] = '\0';
                    326:
                    327:        /*
                    328:         * case 1: reverse-lookup of a number; placed first since this case
                    329:         * is much more frequent if we're scanning.
                    330:         */
1.6       deraadt   331:        if (pnum) {
1.11      ericj     332:                /* Can't be both */
                    333:                if (pstring)
1.6       deraadt   334:                        return (0);
1.11      ericj     335:
1.6       deraadt   336:                x = pnum;
                    337:                if (o_nflag)    /* go faster, skip getservbyblah */
                    338:                        goto gp_finish;
                    339:                y = htons(x);   /* gotta do this -- see Fig.1 below */
1.17    ! ericj     340:                servent = getservbyport(y, o_udpmode ? "udp" : "tcp");
1.6       deraadt   341:                if (servent) {
                    342:                        y = ntohs(servent->s_port);
1.17    ! ericj     343:                        if (x != y)
1.13      ericj     344:                                nlog(0, "Warning: port-bynum mismatch, %d != %d", x, y);
1.11      ericj     345:                        strlcpy(pinfo->name, servent->s_name,
                    346:                            sizeof(pinfo->name));
1.7       deraadt   347:                }
1.6       deraadt   348:                goto gp_finish;
1.11      ericj     349:        }
                    350:        /*
                    351:         * case 2: resolve a string, but we still give preference to numbers
1.6       deraadt   352:         * instead of trying to resolve conflicts.  None of the entries in *my*
                    353:         * extensive /etc/services begins with a digit, so this should "always
                    354:         * work" unless you're at 3com and have some company-internal services
1.11      ericj     355:         * defined.
                    356:         */
1.6       deraadt   357:        if (pstring) {
1.11      ericj     358:                /* Can't be both */
                    359:                if (pnum)
1.6       deraadt   360:                        return (0);
1.11      ericj     361:
1.6       deraadt   362:                x = atoi(pstring);
                    363:                if (x)
1.11      ericj     364:                        return (getpinfo(NULL, x));     /* recurse for
1.6       deraadt   365:                                                         * numeric-string-arg */
1.17    ! ericj     366:                if (o_nflag)
1.6       deraadt   367:                        return (0);
1.17    ! ericj     368:                servent = getservbyname(pstring, o_udpmode ? "udp" : "tcp");
1.6       deraadt   369:                if (servent) {
1.11      ericj     370:                        strlcpy(pinfo->name, servent->s_name,
                    371:                            sizeof(pinfo->name));
1.6       deraadt   372:                        x = ntohs(servent->s_port);
                    373:                        goto gp_finish;
                    374:                }               /* if servent */
                    375:        }                       /* if pstring */
                    376:        return (0);             /* catches any problems so far */
1.1       deraadt   377:
                    378: gp_finish:
1.11      ericj     379:        /*
                    380:         * Fall here whether or not we have a valid servent at this point, with
                    381:         * x containing our [host-order and therefore useful, dammit] port number.
                    382:         */
                    383:        sprintf(pinfo->anum, "%d", x);  /* always load any numeric
1.6       deraadt   384:                                                 * specs! */
1.11      ericj     385:        pinfo->num = (x & 0xffff);      /* u_short, remember... */
                    386:        return (pinfo->num);
1.7       deraadt   387: }
1.1       deraadt   388:
1.11      ericj     389: /*
                    390:  * nextport :
                    391:  * Come up with the next port to try, be it random or whatever.  "block" is
                    392:  * a ptr to randports array, whose bytes [so far] carry these meanings:
                    393:  *     0       ignore
                    394:  *     1       to be tested
                    395:  *     2       tested [which is set as we find them here]
                    396:  * returns a u_short random port, or 0 if all the t-b-t ones are used up.
                    397:  */
1.7       deraadt   398: u_short
1.6       deraadt   399: nextport(block)
                    400:        char   *block;
                    401: {
1.11      ericj     402:        unsigned int x;
                    403:        unsigned int y;
1.6       deraadt   404:
1.11      ericj     405:        y = 70000;                      /* high safety count for rnd-tries */
1.6       deraadt   406:        while (y > 0) {
1.16      ericj     407:                x = (arc4random() & 0xffff);
1.6       deraadt   408:                if (block[x] == 1) {    /* try to find a not-done one... */
                    409:                        block[x] = 2;
                    410:                        break;
                    411:                }
1.11      ericj     412:                x = 0;
1.6       deraadt   413:                y--;
1.11      ericj     414:        }
1.6       deraadt   415:        if (x)
                    416:                return (x);
                    417:
                    418:        y = 65535;              /* no random one, try linear downsearch */
                    419:        while (y > 0) {         /* if they're all used, we *must* be sure! */
                    420:                if (block[y] == 1) {
                    421:                        block[y] = 2;
                    422:                        break;
                    423:                }
                    424:                y--;
1.11      ericj     425:        }
1.6       deraadt   426:        if (y)
                    427:                return (y);     /* at least one left */
1.1       deraadt   428:
1.11      ericj     429:        return (0);
1.7       deraadt   430: }
1.1       deraadt   431:
1.11      ericj     432: /*
                    433:  * loadports :
                    434:  * set "to be tested" indications in BLOCK, from LO to HI.  Almost too small
                    435:  * to be a separate routine, but makes main() a little cleaner.
                    436:  */
1.6       deraadt   437: void
                    438: loadports(block, lo, hi)
                    439:        char   *block;
1.7       deraadt   440:        u_short  lo;
                    441:        u_short  hi;
1.6       deraadt   442: {
1.7       deraadt   443:        u_short  x;
1.6       deraadt   444:
                    445:        if (!block)
1.13      ericj     446:                nlog(1, "loadports: no block?!");
1.6       deraadt   447:        if ((!lo) || (!hi))
1.13      ericj     448:                nlog(1, "loadports: bogus values %d, %d", lo, hi);
1.6       deraadt   449:        x = hi;
                    450:        while (lo <= x) {
                    451:                block[x] = 1;
                    452:                x--;
                    453:        }
1.7       deraadt   454: }
                    455:
1.1       deraadt   456:
1.11      ericj     457: /*
                    458:  * doconnect :
                    459:  * do all the socket stuff, and return an fd for one of
                    460:  *     an open outbound TCP connection
                    461:  *     a UDP stub-socket thingie
                    462:  * with appropriate socket options set up if we wanted source-routing, or
                    463:  *     an unconnected TCP or UDP socket to listen on.
                    464:  * Examines various global o_blah flags to figure out what-all to do.
                    465:  */
1.6       deraadt   466: int
                    467: doconnect(rad, rp, lad, lp)
1.7       deraadt   468:        struct in_addr     *rad;
                    469:        u_short  rp;
                    470:        struct in_addr     *lad;
                    471:        u_short  lp;
1.6       deraadt   472: {
1.14      ericj     473:        int nnetfd = 0;
1.11      ericj     474:        int rr;
1.6       deraadt   475:        int     x, y;
1.1       deraadt   476:
1.11      ericj     477:        /* grab a socket; set opts */
1.14      ericj     478:        while (nnetfd == 0) {
                    479:                if (o_udpmode)
                    480:                        nnetfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
                    481:                else
                    482:                        nnetfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                    483:                if (nnetfd < 0)
                    484:                        nlog(1, "Can't get socket");
                    485:        }
                    486:
1.6       deraadt   487:        x = 1;
                    488:        rr = setsockopt(nnetfd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
                    489:        if (rr == -1)
1.13      ericj     490:                nlog(1, NULL);
1.6       deraadt   491:
                    492:        /* fill in all the right sockaddr crud */
                    493:        lclend->sin_family = AF_INET;
                    494:        remend->sin_family = AF_INET;
1.1       deraadt   495:
1.11      ericj     496:        /* if lad/lp, do appropriate binding */
1.6       deraadt   497:        if (lad)
1.7       deraadt   498:                memcpy(&lclend->sin_addr.s_addr, lad, sizeof(struct in_addr));
1.6       deraadt   499:        if (lp)
                    500:                lclend->sin_port = htons(lp);
1.11      ericj     501:
1.6       deraadt   502:        rr = 0;
                    503:        if (lad || lp) {
                    504:                x = (int) lp;
1.11      ericj     505:                /* try a few times for the local bind, a la ftp-data-port... */
1.6       deraadt   506:                for (y = 4; y > 0; y--) {
1.7       deraadt   507:                        rr = bind(nnetfd, (struct sockaddr *) lclend,
                    508:                            sizeof(struct sockaddr_in));
1.6       deraadt   509:                        if (rr == 0)
                    510:                                break;
                    511:                        if (errno != EADDRINUSE)
                    512:                                break;
                    513:                        else {
1.13      ericj     514:                                nlog(0, "retrying local %s:%d", inet_ntoa(lclend->sin_addr), lp);
1.6       deraadt   515:                                sleep(2);
1.11      ericj     516:                        }
                    517:                }
                    518:        }
1.6       deraadt   519:        if (rr)
1.13      ericj     520:                nlog(1, "Can't grab %s:%d with bind",
1.6       deraadt   521:                    inet_ntoa(lclend->sin_addr), lp);
1.1       deraadt   522:
1.6       deraadt   523:        if (o_listen)
                    524:                return (nnetfd);/* thanks, that's all for today */
1.1       deraadt   525:
1.7       deraadt   526:        memcpy(&remend->sin_addr.s_addr, rad, sizeof(struct in_addr));
1.6       deraadt   527:        remend->sin_port = htons(rp);
1.1       deraadt   528:
1.6       deraadt   529:        /* wrap connect inside a timer, and hit it */
                    530:        arm(1, o_wait);
                    531:        if (setjmp(jbuf) == 0) {
1.11      ericj     532:                rr = connect(nnetfd, (struct sockaddr *) remend,
                    533:                                                sizeof(struct sockaddr));
                    534:        } else {
1.6       deraadt   535:                rr = -1;
1.11      ericj     536:                errno = ETIMEDOUT;
1.6       deraadt   537:        }
                    538:        arm(0, 0);
                    539:        if (rr == 0)
                    540:                return (nnetfd);
1.11      ericj     541:        close(nnetfd);
1.6       deraadt   542:        return (-1);
1.7       deraadt   543: }
1.1       deraadt   544:
1.11      ericj     545: /*
                    546:  * dolisten :
                    547:  * just like doconnect, and in fact calls a hunk of doconnect, but listens for
                    548:  * incoming and returns an open connection *from* someplace.  If we were
                    549:  * given host/port args, any connections from elsewhere are rejected.  This
                    550:  * in conjunction with local-address binding should limit things nicely.
                    551:  */
1.6       deraadt   552: int
                    553: dolisten(rad, rp, lad, lp)
1.7       deraadt   554:        struct in_addr     *rad;
                    555:        u_short  rp;
                    556:        struct in_addr     *lad;
                    557:        u_short  lp;
1.6       deraadt   558: {
1.11      ericj     559:        int nnetfd;
                    560:        int rr;
1.7       deraadt   561:        struct host_info   *whozis = NULL;
1.6       deraadt   562:        int     x;
                    563:        char   *cp;
1.7       deraadt   564:        u_short  z;
1.1       deraadt   565:
1.11      ericj     566:        /*
                    567:         * Pass everything off to doconnect,
                    568:         * who in o_listen mode just gets a socket
                    569:         */
1.6       deraadt   570:        nnetfd = doconnect(rad, rp, lad, lp);
                    571:        if (nnetfd <= 0)
                    572:                return (-1);
1.11      ericj     573:        if (o_udpmode) {
                    574:                if (!lp)
1.13      ericj     575:                        nlog(1, "UDP listen needs -p arg");
1.6       deraadt   576:        } else {
1.11      ericj     577:                rr = listen(nnetfd, 1);
                    578:                if (rr < 0)
1.13      ericj     579:                        nlog(1, "error listening");
1.6       deraadt   580:        }
1.1       deraadt   581:
1.6       deraadt   582:        if (o_verbose) {
1.11      ericj     583:                x = sizeof(struct sockaddr);
1.7       deraadt   584:                rr = getsockname(nnetfd, (struct sockaddr *) lclend, &x);
1.6       deraadt   585:                if (rr < 0)
1.13      ericj     586:                        nlog(0, "local getsockname failed");
1.6       deraadt   587:                strcpy(bigbuf_net, "listening on [");   /* buffer reuse... */
                    588:                if (lclend->sin_addr.s_addr)
                    589:                        strcat(bigbuf_net, inet_ntoa(lclend->sin_addr));
                    590:                else
                    591:                        strcat(bigbuf_net, "any");
1.15      ericj     592:                strcat(bigbuf_net, "] ...");
1.6       deraadt   593:                z = ntohs(lclend->sin_port);
1.13      ericj     594:                nlog(0, "%s %d", bigbuf_net, z);
1.6       deraadt   595:        }                       /* verbose -- whew!! */
1.11      ericj     596:        /*
                    597:         * UDP is a speeeeecial case -- we have to do I/O *and* get the
1.6       deraadt   598:         * calling party's particulars all at once, listen() and accept()
                    599:         * don't apply. At least in the BSD universe, however, recvfrom/PEEK
                    600:         * is enough to tell us something came in, and we can set things up so
                    601:         * straight read/write actually does work after all.  Yow.  YMMV on
1.11      ericj     602:         * strange platforms!
                    603:         */
1.6       deraadt   604:        if (o_udpmode) {
1.7       deraadt   605:                x = sizeof(struct sockaddr);    /* retval for recvfrom */
1.6       deraadt   606:                arm(2, o_wait); /* might as well timeout this, too */
                    607:                if (setjmp(jbuf) == 0) {        /* do timeout for initial
                    608:                                                 * connect */
1.11      ericj     609:                        rr = recvfrom(nnetfd, bigbuf_net, BIGSIZ, MSG_PEEK,
                    610:                                        (struct sockaddr *)remend, &x);
1.6       deraadt   611:                } else
1.11      ericj     612:                        goto dol_tmo;
1.6       deraadt   613:                arm(0, 0);
1.11      ericj     614:                rr = connect(nnetfd, (struct sockaddr *)remend,
                    615:                                                sizeof(struct sockaddr));
1.6       deraadt   616:                goto whoisit;
1.11      ericj     617:        }
1.6       deraadt   618:        /* fall here for TCP */
1.11      ericj     619:        x = sizeof(struct sockaddr);
                    620:        arm(2, o_wait);
1.6       deraadt   621:        if (setjmp(jbuf) == 0) {
1.7       deraadt   622:                rr = accept(nnetfd, (struct sockaddr *) remend, &x);
1.6       deraadt   623:        } else
1.11      ericj     624:                goto dol_tmo;
1.6       deraadt   625:        arm(0, 0);
                    626:        close(nnetfd);          /* dump the old socket */
                    627:        nnetfd = rr;            /* here's our new one */
1.1       deraadt   628:
                    629: whoisit:
1.6       deraadt   630:        if (rr < 0)
                    631:                goto dol_err;   /* bail out if any errors so far */
1.1       deraadt   632:
1.11      ericj     633:        /*
                    634:         * Find out what address the connection was *to* on
                    635:         * our end, in case we're doing a listen-on-any on
                    636:         * a multihomed machine. This allows one to offer
                    637:         * different services via different alias addresses,
                    638:         * such as the "virtual web site" hack.
                    639:         */
1.6       deraadt   640:        memset(bigbuf_net, 0, 64);
                    641:        cp = &bigbuf_net[32];
1.7       deraadt   642:        x = sizeof(struct sockaddr);
                    643:        rr = getsockname(nnetfd, (struct sockaddr *) lclend, &x);
1.17    ! ericj     644:        if (rr < 0)
1.13      ericj     645:                nlog(0, "post-rcv getsockname failed");
1.6       deraadt   646:        strcpy(cp, inet_ntoa(lclend->sin_addr));
1.1       deraadt   647:
1.6       deraadt   648:        z = ntohs(remend->sin_port);
                    649:        strcpy(bigbuf_net, inet_ntoa(remend->sin_addr));
1.11      ericj     650:        whozis = gethinfo(bigbuf_net, o_nflag);
                    651:        x = 0;
1.6       deraadt   652:        if (rad)                /* xxx: fix to go down the *list* if we have
                    653:                                 * one? */
1.7       deraadt   654:                if (memcmp(rad, whozis->iaddrs, sizeof(struct sockaddr)))
1.6       deraadt   655:                        x = 1;
1.11      ericj     656:        if (rp) {
1.6       deraadt   657:                if (z != rp)
                    658:                        x = 1;
1.11      ericj     659:        }
                    660:        if (x) {
1.13      ericj     661:                nlog(1, "invalid connection to [%s] from %s [%s] %d",
1.6       deraadt   662:                    cp, whozis->name, whozis->addrs[0], z);
1.11      ericj     663:        }
1.12      ericj     664:        if (o_verbose) {
1.13      ericj     665:                nlog(0, "connect to [%s] from %s [%s] %d",
1.12      ericj     666:                        cp, whozis->name, whozis->addrs[0], z);
                    667:        }
1.11      ericj     668:        return (nnetfd);
1.1       deraadt   669:
                    670: dol_tmo:
1.11      ericj     671:        errno = ETIMEDOUT;
1.1       deraadt   672: dol_err:
1.6       deraadt   673:        close(nnetfd);
                    674:        return (-1);
1.7       deraadt   675: }
1.1       deraadt   676:
1.11      ericj     677: /*
                    678:  * udptest :
                    679:  * fire a couple of packets at a UDP target port, just to see if it's really
                    680:  * there.  On BSD kernels, ICMP host/port-unreachable errors get delivered to
                    681:  * our socket as ECONNREFUSED write errors.  On SV kernels, we lose; we'll have
                    682:  * to collect and analyze raw ICMP ourselves a la satan's probe_udp_ports
                    683:  * backend.  Guess where one could swipe the appropriate code from...
                    684:  *
                    685:  * Use the time delay between writes if given, otherwise use the "tcp ping"
                    686:  * trick for getting the RTT.  [I got that idea from pluvius, and warped it.]
                    687:  * Return either the original fd, or clean up and return -1.
                    688:  */
1.6       deraadt   689: udptest(fd, where)
                    690:        int     fd;
1.7       deraadt   691:        struct in_addr     *where;
1.6       deraadt   692: {
1.11      ericj     693:        int rr;
1.6       deraadt   694:
                    695:        rr = write(fd, bigbuf_in, 1);
1.17    ! ericj     696:        if (rr != 1)
        !           697:                nlog(0, "udptest first write failed: ");
1.6       deraadt   698:        if (o_wait)
                    699:                sleep(o_wait);
                    700:        else {
1.11      ericj     701:                o_udpmode = 0;
                    702:                o_wait = 5;
1.6       deraadt   703:                rr = doconnect(where, SLEAZE_PORT, 0, 0);
                    704:                if (rr > 0)
1.11      ericj     705:                        close(rr);
                    706:                o_wait = 0;
                    707:                o_udpmode++;
                    708:        }
1.6       deraadt   709:        rr = write(fd, bigbuf_in, 1);
1.11      ericj     710:        if (rr == 1)
1.6       deraadt   711:                return (fd);
1.11      ericj     712:        close(fd);
1.6       deraadt   713:        return (-1);
1.7       deraadt   714: }
                    715:
1.11      ericj     716: /*
1.17    ! ericj     717:  * oprint :
1.11      ericj     718:  * Hexdump bytes shoveled either way to a running logfile, in the format:
                    719:  * D offset       -  - - - --- 16 bytes --- - - -  -     # .... ascii .....
                    720:  * where "which" sets the direction indicator, D:
                    721:  * 0 -- sent to network, or ">"
                    722:  * 1 -- rcvd and printed to stdout, or "<"
                    723:  * and "buf" and "n" are data-block and length.  If the current block generates
                    724:  * a partial line, so be it; we *want* that lockstep indication of who sent
                    725:  * what when.  Adapted from dgaudet's original example -- but must be ripping
                    726:  * *fast*, since we don't want to be too disk-bound.
                    727:  */
1.6       deraadt   728: void
                    729: oprint(which, buf, n)
                    730:        int     which;
                    731:        char   *buf;
                    732:        int     n;
                    733: {
                    734:        int     bc;             /* in buffer count */
                    735:        int     obc;            /* current "global" offset */
                    736:        int     soc;            /* stage write count */
1.11      ericj     737:        unsigned char *p;       /* main buf ptr; m.b. unsigned here */
                    738:        unsigned char *op;      /* out hexdump ptr */
                    739:        unsigned char *a;       /* out asc-dump ptr */
                    740:        int x;
                    741:        unsigned int y;
1.6       deraadt   742:
                    743:        if (!ofd)
1.13      ericj     744:                nlog(1, "oprint called with no open fd?!");
1.6       deraadt   745:        if (n == 0)
                    746:                return;
                    747:
                    748:        op = stage;
                    749:        if (which) {
                    750:                *op = '<';
                    751:                obc = wrote_out;/* use the globals! */
                    752:        } else {
                    753:                *op = '>';
                    754:                obc = wrote_net;
                    755:        }
                    756:        op++;                   /* preload "direction" */
                    757:        *op = ' ';
                    758:        p = (unsigned char *) buf;
                    759:        bc = n;
                    760:        stage[59] = '#';        /* preload separator */
                    761:        stage[60] = ' ';
                    762:
                    763:        while (bc) {            /* for chunk-o-data ... */
                    764:                x = 16;
                    765:                soc = 78;       /* len of whole formatted line */
                    766:                if (bc < x) {
                    767:                        soc = soc - 16 + bc;    /* fiddle for however much is
                    768:                                                 * left */
                    769:                        x = (bc * 3) + 11;      /* 2 digits + space per, after
                    770:                                                 * D & offset */
                    771:                        op = &stage[x];
                    772:                        x = 16 - bc;
                    773:                        while (x) {
                    774:                                *op++ = ' ';    /* preload filler spaces */
                    775:                                *op++ = ' ';
                    776:                                *op++ = ' ';
                    777:                                x--;
                    778:                        }
                    779:                        x = bc; /* re-fix current linecount */
                    780:                }               /* if bc < x */
                    781:                bc -= x;        /* fix wrt current line size */
                    782:                sprintf(&stage[2], "%8.8x ", obc);      /* xxx: still slow? */
                    783:                obc += x;       /* fix current offset */
                    784:                op = &stage[11];/* where hex starts */
                    785:                a = &stage[61]; /* where ascii starts */
                    786:
                    787:                while (x) {     /* for line of dump, however long ... */
                    788:                        y = (int) (*p >> 4);    /* hi half */
                    789:                        *op = hexnibs[y];
                    790:                        op++;
                    791:                        y = (int) (*p & 0x0f);  /* lo half */
                    792:                        *op = hexnibs[y];
                    793:                        op++;
                    794:                        *op = ' ';
                    795:                        op++;
                    796:                        if ((*p > 31) && (*p < 127))
                    797:                                *a = *p;        /* printing */
                    798:                        else
                    799:                                *a = '.';       /* nonprinting, loose def */
                    800:                        a++;
                    801:                        p++;
                    802:                        x--;
                    803:                }               /* while x */
                    804:                *a = '\n';      /* finish the line */
                    805:                x = write(ofd, stage, soc);
                    806:                if (x < 0)
1.13      ericj     807:                        nlog(1, "ofd write err");
1.11      ericj     808:        }
1.7       deraadt   809: }
                    810:
1.1       deraadt   811: #ifdef TELNET
1.7       deraadt   812: u_short  o_tn = 0;             /* global -t option */
1.1       deraadt   813:
1.11      ericj     814: /*
                    815:  *  atelnet :
                    816:  * Answer anything that looks like telnet negotiation with don't/won't.
                    817:  * This doesn't modify any data buffers, update the global output count,
                    818:  * or show up in a hexdump -- it just shits into the outgoing stream.
                    819:  * Idea and codebase from Mudge@l0pht.com.
                    820:  */
1.6       deraadt   821: void
                    822: atelnet(buf, size)
                    823:        unsigned char *buf;     /* has to be unsigned here! */
                    824:        unsigned int size;
                    825: {
                    826:        static unsigned char obuf[4];   /* tiny thing to build responses into */
1.11      ericj     827:        int x;
                    828:        unsigned char y;
                    829:        unsigned char *p;
1.6       deraadt   830:
                    831:        y = 0;
                    832:        p = buf;
                    833:        x = size;
                    834:        while (x > 0) {
                    835:                if (*p != 255)  /* IAC? */
                    836:                        goto notiac;
                    837:                obuf[0] = 255;
                    838:                p++;
                    839:                x--;
                    840:                if ((*p == 251) || (*p == 252)) /* WILL or WONT */
                    841:                        y = 254;/* -> DONT */
                    842:                if ((*p == 253) || (*p == 254)) /* DO or DONT */
                    843:                        y = 252;/* -> WONT */
                    844:                if (y) {
                    845:                        obuf[1] = y;
                    846:                        p++;
                    847:                        x--;
1.11      ericj     848:                        obuf[2] = *p;
1.6       deraadt   849:                        (void) write(netfd, obuf, 3);
1.11      ericj     850:                        /*
                    851:                         * if one wanted to bump wrote_net or do
                    852:                         * a hexdump line, here's the place.
                    853:                         */
1.6       deraadt   854:                        y = 0;
1.11      ericj     855:                }
1.1       deraadt   856: notiac:
1.6       deraadt   857:                p++;
                    858:                x--;
1.11      ericj     859:        }
1.7       deraadt   860: }
1.11      ericj     861: #endif /* TELNET */
1.7       deraadt   862:
1.11      ericj     863: /*
                    864:  *  readwrite :
                    865:  * handle stdin/stdout/network I/O.  Bwahaha!! -- the select loop from hell.
                    866:  * In this instance, return what might become our exit status.
                    867:  */
1.6       deraadt   868: int
                    869: readwrite(fd)
                    870:        int     fd;
                    871: {
1.11      ericj     872:        int rr;
                    873:        char *zp;       /* stdin buf ptr */
                    874:        char *np;       /* net-in buf ptr */
1.6       deraadt   875:        unsigned int rzleft;
                    876:        unsigned int rnleft;
1.7       deraadt   877:        u_short  netretry;      /* net-read retry counter */
1.11      ericj     878:        u_short  wretry;        /* net-write sanity counter */
                    879:        u_short  wfirst;        /* one-shot flag to skip first net read */
1.1       deraadt   880:
1.11      ericj     881:        /*
                    882:         * if you don't have all this FD_* macro hair in sys/types.h,
                    883:         * you'll have to either find it or do your own bit-bashing:
                    884:         * *ds1 |= (1 << fd), etc.
                    885:         */
1.6       deraadt   886:        if (fd > FD_SETSIZE) {
1.13      ericj     887:                nlog(0, "Preposterous fd value %d", fd);
1.6       deraadt   888:                return (1);
                    889:        }
1.11      ericj     890:        FD_SET(fd, &fds1);
1.6       deraadt   891:        netretry = 2;
                    892:        wfirst = 0;
                    893:        rzleft = rnleft = 0;
                    894:        if (insaved) {
                    895:                rzleft = insaved;       /* preload multi-mode fakeouts */
                    896:                zp = bigbuf_in;
                    897:                wfirst = 1;
1.11      ericj     898:                /* If not scanning, this is a one-off first */
                    899:                if (Single)
                    900:                        insaved = 0;
1.6       deraadt   901:                else {
1.11      ericj     902:                        FD_CLR(0, &fds1);
                    903:                        close(0);
                    904:                }
                    905:        }
1.6       deraadt   906:        if (o_interval)
1.11      ericj     907:                sleep(o_interval);
1.1       deraadt   908:
1.7       deraadt   909:        while (FD_ISSET(fd, &fds1)) {   /* i.e. till the *net* closes! */
1.9       art       910:                struct timeval *tv;
                    911:
1.11      ericj     912:                wretry = 8200;          /* more than we'll ever hafta write */
                    913:                if (wfirst) {           /* any saved stdin buffer? */
1.6       deraadt   914:                        wfirst = 0;     /* clear flag for the duration */
                    915:                        goto shovel;    /* and go handle it first */
                    916:                }
1.7       deraadt   917:                fds2 = fds1;
1.9       art       918:                if (timer1.tv_sec > 0 || timer1.tv_usec > 0) {
                    919:                        memcpy(&timer2, &timer1, sizeof(struct timeval));
                    920:                        tv = &timer2;
                    921:                } else
                    922:                        tv = NULL;
                    923:                rr = select(getdtablesize(), &fds2, 0, 0, tv);
1.6       deraadt   924:                if (rr < 0) {
1.11      ericj     925:                        if (errno != EINTR) {
1.13      ericj     926:                                nlog(0, "Select Failure");
1.6       deraadt   927:                                close(fd);
                    928:                                return (1);
                    929:                        }
1.11      ericj     930:                }
1.6       deraadt   931:                /* if we have a timeout AND stdin is closed AND we haven't
                    932:                 * heard anything from the net during that time, assume it's
                    933:                 * dead and close it too. */
                    934:                if (rr == 0) {
1.7       deraadt   935:                        if (!FD_ISSET(0, &fds1))
1.6       deraadt   936:                                netretry--;     /* we actually try a coupla
                    937:                                                 * times. */
                    938:                        if (!netretry) {
1.12      ericj     939:                                if (o_verbose)  /* normally we don't
1.6       deraadt   940:                                                         * care */
1.13      ericj     941:                                        nlog(0, "net timeout");
1.6       deraadt   942:                                close(fd);
                    943:                                return (0);     /* not an error! */
                    944:                        }
                    945:                }               /* select timeout */
1.11      ericj     946:                /* XXX: should we check the exception fds too?  The read fds
1.6       deraadt   947:                 * seem to give us the right info, and none of the examples I
                    948:                 * found bothered. */
                    949:                /* Ding!!  Something arrived, go check all the incoming
                    950:                 * hoppers, net first */
1.7       deraadt   951:                if (FD_ISSET(fd, &fds2)) {      /* net: ding! */
1.6       deraadt   952:                        rr = read(fd, bigbuf_net, BIGSIZ);
                    953:                        if (rr <= 0) {
1.7       deraadt   954:                                FD_CLR(fd, &fds1);      /* net closed, we'll
1.6       deraadt   955:                                                         * finish up... */
                    956:                                rzleft = 0;     /* can't write anymore: broken
                    957:                                                 * pipe */
                    958:                        } else {
                    959:                                rnleft = rr;
                    960:                                np = bigbuf_net;
1.1       deraadt   961: #ifdef TELNET
1.6       deraadt   962:                                if (o_tn)
                    963:                                        atelnet(np, rr);        /* fake out telnet stuff */
1.11      ericj     964: #endif /* TELNET */
                    965:                        }
                    966:                }
1.6       deraadt   967:                /* if we're in "slowly" mode there's probably still stuff in
                    968:                 * the stdin buffer, so don't read unless we really need MORE
                    969:                 * INPUT!  MORE INPUT! */
                    970:                if (rzleft)
                    971:                        goto shovel;
1.1       deraadt   972:
1.11      ericj     973:                if (FD_ISSET(0, &fds2)) {
1.6       deraadt   974:                        rr = read(0, bigbuf_in, BIGSIZ);
1.11      ericj     975:                        if (rr <= 0) {
                    976:                                FD_CLR(0, &fds1);       /* disable and close */
1.6       deraadt   977:                                close(0);
                    978:                        } else {
                    979:                                rzleft = rr;
                    980:                                zp = bigbuf_in;
1.11      ericj     981:                                if (!Single) {
                    982:                                        insaved = rr;
                    983:                                        FD_CLR(0, &fds1);
                    984:                                        close(0);
                    985:                                }
                    986:                        }
                    987:                }
1.1       deraadt   988: shovel:
1.11      ericj     989:                /* sanity check.  Works because they're both unsigned... */
1.6       deraadt   990:                if ((rzleft > 8200) || (rnleft > 8200)) {
                    991:                        rzleft = rnleft = 0;
                    992:                }
1.11      ericj     993:                /* net write retries sometimes happen on UDP connections */
1.6       deraadt   994:                if (!wretry) {  /* is something hung? */
1.13      ericj     995:                        nlog(0, "too many output retries");
1.6       deraadt   996:                        return (1);
                    997:                }
                    998:                if (rnleft) {
                    999:                        rr = write(1, np, rnleft);
                   1000:                        if (rr > 0) {
                   1001:                                if (o_wfile)
1.11      ericj    1002:                                        oprint(1, np, rr);
                   1003:                                np += rr;
                   1004:                                rnleft -= rr;
1.6       deraadt  1005:                                wrote_out += rr;        /* global count */
                   1006:                        }
1.11      ericj    1007:                }
1.6       deraadt  1008:                if (rzleft) {
1.11      ericj    1009:                        if (o_interval)
1.6       deraadt  1010:                                rr = findline(zp, rzleft);
                   1011:                        else
                   1012:                                rr = rzleft;
1.11      ericj    1013:                        rr = write(fd, zp, rr);
1.6       deraadt  1014:                        if (rr > 0) {
                   1015:                                if (o_wfile)
1.11      ericj    1016:                                        oprint(0, zp, rr);
1.6       deraadt  1017:                                zp += rr;
                   1018:                                rzleft -= rr;
1.11      ericj    1019:                                wrote_net += rr;
1.6       deraadt  1020:                        }
1.11      ericj    1021:                }
                   1022:                if (o_interval) {
1.6       deraadt  1023:                        sleep(o_interval);
1.11      ericj    1024:                        continue;
1.6       deraadt  1025:                }
1.11      ericj    1026:                if ((rzleft) || (rnleft)) {
                   1027:                        wretry--;
1.6       deraadt  1028:                        goto shovel;
                   1029:                }
1.11      ericj    1030:        }
1.1       deraadt  1031:
1.6       deraadt  1032:        close(fd);
                   1033:        return (0);
1.7       deraadt  1034: }
1.1       deraadt  1035:
                   1036: /* main :
                   1037:    now we pull it all together... */
1.16      ericj    1038: int
1.6       deraadt  1039: main(argc, argv)
                   1040:        int     argc;
                   1041:        char  **argv;
1.1       deraadt  1042: {
1.11      ericj    1043:        int x, ch;
                   1044:        char *cp;
1.7       deraadt  1045:        struct host_info   *gp;
                   1046:        struct host_info   *whereto = NULL;
                   1047:        struct host_info   *wherefrom = NULL;
                   1048:        struct in_addr     *ouraddr = NULL;
                   1049:        struct in_addr     *themaddr = NULL;
                   1050:        u_short  o_lport = 0;
                   1051:        u_short  ourport = 0;
                   1052:        u_short  loport = 0;    /* for scanning stuff */
                   1053:        u_short  hiport = 0;
                   1054:        u_short  curport = 0;
1.6       deraadt  1055:        char   *randports = NULL;
1.1       deraadt  1056:
1.6       deraadt  1057:        res_init();
1.17    ! ericj    1058:
1.7       deraadt  1059:        lclend = (struct sockaddr_in *) calloc(1, sizeof(struct sockaddr));
                   1060:        remend = (struct sockaddr_in *) calloc(1, sizeof(struct sockaddr));
                   1061:        bigbuf_in = calloc(1, BIGSIZ);
                   1062:        bigbuf_net = calloc(1, BIGSIZ);
1.11      ericj    1063:        pinfo= (struct port_info *) calloc(1, sizeof(struct port_info));
1.6       deraadt  1064:
                   1065:        gatesptr = 4;
1.1       deraadt  1066:
1.11      ericj    1067:        /*
                   1068:         * We want to catch a few of these signals.
                   1069:         * Others we disgard.
                   1070:         */
1.6       deraadt  1071:        signal(SIGINT, catch);
                   1072:        signal(SIGQUIT, catch);
                   1073:        signal(SIGTERM, catch);
                   1074:        signal(SIGURG, SIG_IGN);
                   1075:        signal(SIGPIPE, SIG_IGN);       /* important! */
1.1       deraadt  1076:
1.11      ericj    1077:        /*
                   1078:         * If no args given at all, get 'em from stdin, construct an argv,
                   1079:         * and hand anything left over to readwrite().
                   1080:         */
1.6       deraadt  1081:        if (argc == 1) {
1.16      ericj    1082:                /* Loop until we get a command to try */
                   1083:                for (;;) {
                   1084:                        cp = argv[0];
                   1085:                        argv = (char **) calloc(1, 128 * sizeof(char *));
                   1086:                        argv[0] = cp;   /* leave old prog name intact */
                   1087:                        cp = calloc(1, BIGSIZ);
                   1088:                        argv[1] = cp;   /* head of new arg block */
                   1089:                        fprintf(stderr, "Cmd line: ");
                   1090:                        fflush(stderr); /* I dont care if it's unbuffered or not! */
                   1091:                        insaved = read(0, cp, BIGSIZ-1); /* we're gonna fake fgets()
                   1092:                                                          * here */
                   1093:                        cp[BIGSIZ-1] = '\0';
                   1094:                        if (*cp != '\n' && *cp != '\t')
                   1095:                                break;
                   1096:                }
1.6       deraadt  1097:                if (insaved <= 0)
1.13      ericj    1098:                        nlog(1, "wrong");
1.6       deraadt  1099:                x = findline(cp, insaved);
                   1100:                if (x)
                   1101:                        insaved -= x;   /* remaining chunk size to be sent */
                   1102:                if (insaved)    /* which might be zero... */
                   1103:                        memcpy(bigbuf_in, &cp[x], insaved);
                   1104:                cp = strchr(argv[1], '\n');
                   1105:                if (cp)
                   1106:                        *cp = '\0';
                   1107:                cp = strchr(argv[1], '\r');     /* look for ^M too */
                   1108:                if (cp)
                   1109:                        *cp = '\0';
1.1       deraadt  1110:
1.11      ericj    1111:                /*
                   1112:                 * Find and stash pointers to remaining new "args"
                   1113:                 */
1.6       deraadt  1114:                cp = argv[1];
                   1115:                cp++;           /* skip past first char */
                   1116:                x = 2;          /* we know argv 0 and 1 already */
                   1117:                for (; *cp != '\0'; cp++) {
                   1118:                        if (*cp == ' ') {
                   1119:                                *cp = '\0';     /* smash all spaces */
                   1120:                                continue;
                   1121:                        } else {
                   1122:                                if (*(cp - 1) == '\0') {
                   1123:                                        argv[x] = cp;
                   1124:                                        x++;
                   1125:                                }
                   1126:                        }       /* if space */
                   1127:                }               /* for cp */
                   1128:                argc = x;
1.11      ericj    1129:        }
                   1130:
                   1131:        while ((ch = getopt(argc, argv, "g:G:hi:lno:p:rs:tuvw:z")) != -1) {
                   1132:                switch (ch) {
                   1133:                case 'G':                       /* srcrt gateways pointer val */
1.6       deraadt  1134:                        x = atoi(optarg);
1.11      ericj    1135:                        /* Mask of bits */
                   1136:                        if ((x) && (x == (x & 0x1c)))
1.6       deraadt  1137:                                gatesptr = x;
                   1138:                        else
1.13      ericj    1139:                                nlog(1, "invalid hop pointer %d, must be multiple of 4 <= 28", x);
1.6       deraadt  1140:                        break;
1.11      ericj    1141:                case 'g':                       /* srcroute hop[s] */
1.6       deraadt  1142:                        if (gatesidx > 8)
1.13      ericj    1143:                                nlog(1, "Too many -g hops!");
1.11      ericj    1144:                        if (gates == NULL)
                   1145:                                gates = (struct host_info **) calloc(1,
                   1146:                                                sizeof(struct host_info *) * 10);
                   1147:                        gp = gethinfo(optarg, o_nflag);
1.6       deraadt  1148:                        if (gp)
                   1149:                                gates[gatesidx] = gp;
                   1150:                        gatesidx++;
                   1151:                        break;
                   1152:                case 'h':
1.11      ericj    1153:                        help();
                   1154:                        break;
                   1155:                case 'i':                       /* line-interval time */
1.6       deraadt  1156:                        o_interval = atoi(optarg) & 0xffff;
                   1157:                        if (!o_interval)
1.13      ericj    1158:                                nlog(1, "invalid interval time %s", optarg);
1.6       deraadt  1159:                        break;
1.11      ericj    1160:                case 'l':                       /* listen mode */
1.6       deraadt  1161:                        o_listen++;
                   1162:                        break;
1.11      ericj    1163:                case 'n':                       /* numeric-only, no DNS lookups */
1.6       deraadt  1164:                        o_nflag++;
                   1165:                        break;
1.11      ericj    1166:                case 'o':                       /* hexdump log */
1.6       deraadt  1167:                        stage = (unsigned char *) optarg;
                   1168:                        o_wfile++;
                   1169:                        break;
1.11      ericj    1170:                case 'p':                       /* local source port */
                   1171:                        o_lport = getpinfo(optarg, 0);
1.6       deraadt  1172:                        if (o_lport == 0)
1.13      ericj    1173:                                nlog(1, "invalid local port %s", optarg);
1.6       deraadt  1174:                        break;
1.11      ericj    1175:                case 'r':                       /* randomize various things */
1.6       deraadt  1176:                        o_random++;
                   1177:                        break;
1.11      ericj    1178:                /*
                   1179:                 * Do a full lookup [since everything else goes through the same
                   1180:                 * mill], unless -n was previously specified. In fact, careful
                   1181:                 * placement of -n can be useful, so we'll still pass o_nflag
                   1182:                 * here instead of forcing numeric.
                   1183:                 */
                   1184:                case 's':                       /* local source address */
                   1185:                        wherefrom = gethinfo(optarg, o_nflag);
1.6       deraadt  1186:                        ouraddr = &wherefrom->iaddrs[0];
                   1187:                        break;
1.1       deraadt  1188: #ifdef TELNET
1.11      ericj    1189:                case 't':                       /* do telnet fakeout */
1.6       deraadt  1190:                        o_tn++;
                   1191:                        break;
1.11      ericj    1192: #endif
                   1193:                case 'u':                       /* use UDP */
1.6       deraadt  1194:                        o_udpmode++;
                   1195:                        break;
1.11      ericj    1196:                case 'v':                       /* verbose */
1.6       deraadt  1197:                        o_verbose++;
                   1198:                        break;
1.11      ericj    1199:                case 'w':                       /* wait time */
1.6       deraadt  1200:                        o_wait = atoi(optarg);
                   1201:                        if (o_wait <= 0)
1.13      ericj    1202:                                nlog(1, "invalid wait-time %s", optarg);
1.7       deraadt  1203:                        timer1.tv_sec = o_wait;
                   1204:                        timer1.tv_usec = 0;
1.6       deraadt  1205:                        break;
1.11      ericj    1206:                case 'z':                       /* little or no data xfer */
1.6       deraadt  1207:                        o_zero++;
                   1208:                        break;
                   1209:                default:
1.11      ericj    1210:                        usage(1);
                   1211:                }
                   1212:        }
1.1       deraadt  1213:
1.11      ericj    1214:        /* other misc initialization */
1.17    ! ericj    1215:        FD_SET(0, &fds1);       /* stdin *is* initially open */
1.6       deraadt  1216:        if (o_random) {
1.11      ericj    1217:                randports = calloc(1, 65536);   /* big flag array for ports */
1.6       deraadt  1218:        }
                   1219:        if (o_wfile) {
                   1220:                ofd = open(stage, O_WRONLY | O_CREAT | O_TRUNC, 0664);
                   1221:                if (ofd <= 0)   /* must be > extant 0/1/2 */
1.17    ! ericj    1222:                        nlog(1, "%s: ", stage);
1.7       deraadt  1223:                stage = (unsigned char *) calloc(1, 100);
1.6       deraadt  1224:        }
1.11      ericj    1225:        /* optind is now index of first non -x arg */
                   1226:        if (argv[optind])
                   1227:                whereto = gethinfo(argv[optind], o_nflag);
1.6       deraadt  1228:        if (whereto && whereto->iaddrs)
                   1229:                themaddr = &whereto->iaddrs[0];
                   1230:        if (themaddr)
                   1231:                optind++;       /* skip past valid host lookup */
1.1       deraadt  1232:
1.11      ericj    1233:        /*
                   1234:         * Handle listen mode here, and exit afterward.  Only does one connect;
                   1235:         * this is arguably the right thing to do.  A "persistent listen-and-fork"
                   1236:         * mode a la inetd has been thought about, but not implemented.  A tiny
                   1237:         * wrapper script can handle such things.
                   1238:         */
1.6       deraadt  1239:        if (o_listen) {
1.11      ericj    1240:                curport = 0;
                   1241:                if (argv[optind]) {
                   1242:                        curport = getpinfo(argv[optind], 0);
                   1243:                        if (curport == 0)
1.13      ericj    1244:                                nlog(1, "invalid port %s", argv[optind]);
1.11      ericj    1245:                }
1.6       deraadt  1246:                netfd = dolisten(themaddr, curport, ouraddr, o_lport);
                   1247:                if (netfd > 0) {
1.11      ericj    1248:                        x = readwrite(netfd);
1.12      ericj    1249:                        if (o_verbose)
1.13      ericj    1250:                                nlog(0, "Sent %i Rcvd %i", wrote_net, wrote_out);
1.11      ericj    1251:                        exit(x);
                   1252:                } else
1.13      ericj    1253:                        nlog(1, "no connection");
1.11      ericj    1254:        }
1.6       deraadt  1255:        /* fall thru to outbound connects.  Now we're more picky about args... */
                   1256:        if (!themaddr)
1.13      ericj    1257:                nlog(1, "no destination");
1.6       deraadt  1258:        if (argv[optind] == NULL)
1.13      ericj    1259:                nlog(1, "no port[s] to connect to");
1.11      ericj    1260:        if (argv[optind + 1])
                   1261:                Single = 0;
                   1262:        ourport = o_lport;
                   1263:
1.6       deraadt  1264:        while (argv[optind]) {
                   1265:                hiport = loport = 0;
1.17    ! ericj    1266:                if (cp = strchr(argv[optind], '-')) {
1.6       deraadt  1267:                        *cp = '\0';
                   1268:                        cp++;
1.11      ericj    1269:                        hiport = getpinfo(cp, 0);
1.6       deraadt  1270:                        if (hiport == 0)
1.13      ericj    1271:                                nlog(1, "invalid port %s", cp);
1.17    ! ericj    1272:                }
1.11      ericj    1273:                loport = getpinfo(argv[optind], 0);
1.6       deraadt  1274:                if (loport == 0)
1.13      ericj    1275:                        nlog(1, "invalid port %s", argv[optind]);
1.16      ericj    1276:                if (hiport > loport) {
                   1277:                        Single = 0;
                   1278:                        if (o_random) {
1.6       deraadt  1279:                                loadports(randports, loport, hiport);
                   1280:                                curport = nextport(randports);
1.11      ericj    1281:                        } else
                   1282:                                curport = hiport;
1.17    ! ericj    1283:                } else
1.6       deraadt  1284:                        curport = loport;
1.11      ericj    1285:                    /*
                   1286:                     * Now start connecting to these things.
                   1287:                     * curport is already preloaded.
                   1288:                     */
1.6       deraadt  1289:                    while (loport <= curport) {
1.11      ericj    1290:                        curport = getpinfo(NULL, curport);
1.6       deraadt  1291:                        netfd = doconnect(themaddr, curport, ouraddr, ourport);
1.11      ericj    1292:                        if (netfd > 0)
                   1293:                                if (o_zero && o_udpmode)
1.6       deraadt  1294:                                        netfd = udptest(netfd, themaddr);
1.11      ericj    1295:                        if (netfd > 0) {
                   1296:                                x = 0;
                   1297:                                if (o_verbose) {
1.13      ericj    1298:                                        nlog(0, "%s [%s] %d (%s) open",
1.11      ericj    1299:                                                whereto->name,
                   1300:                                                whereto->addrs[0], curport,
                   1301:                                                pinfo->name);
                   1302:                                }
1.6       deraadt  1303:                                if (!o_zero)
1.11      ericj    1304:                                        x = readwrite(netfd);
                   1305:                        } else {
                   1306:                                x = 1;
1.17    ! ericj    1307:                                if ((Single || (o_verbose))
1.11      ericj    1308:                                   || (errno != ECONNREFUSED)) {
1.13      ericj    1309:                                        nlog(0, "%s [%s] %d (%s)",
                   1310:                                             whereto->name, whereto->addrs[0],
                   1311:                                             curport, pinfo->name);
1.11      ericj    1312:                                }
                   1313:                        }
                   1314:                        close(netfd);
1.6       deraadt  1315:                        if (o_interval)
1.11      ericj    1316:                                sleep(o_interval);
1.6       deraadt  1317:                        if (o_random)
                   1318:                                curport = nextport(randports);
                   1319:                        else
1.11      ericj    1320:                                curport--;
1.17    ! ericj    1321:                    }
1.6       deraadt  1322:                optind++;
1.11      ericj    1323:        }
1.6       deraadt  1324:
1.13      ericj    1325:        nlog(0, "Sent %i Rcvd %i", wrote_net, wrote_out);
1.6       deraadt  1326:        if (Single)
1.11      ericj    1327:                exit(x);
                   1328:        exit(0);
1.13      ericj    1329: }
                   1330:
                   1331: /*
                   1332:  * nlog:
                   1333:  * dual purpose function, does both warn() and err()
                   1334:  * and pays attention to o_verbose.
                   1335:  */
                   1336: void
                   1337: nlog(doexit, fmt)
1.14      ericj    1338:        char *fmt;
1.13      ericj    1339: {
1.14      ericj    1340:        va_list args;
1.13      ericj    1341:
1.14      ericj    1342:        if (o_verbose || doexit) {
                   1343:                va_start(args, fmt);
                   1344:                vfprintf(stderr, fmt, args);
                   1345:                if (h_errno)
1.13      ericj    1346:                         herror(NULL);
1.17    ! ericj    1347:                else if (errno)
        !          1348:                        fprintf(stderr, "%s\n", strerror(errno));
1.14      ericj    1349:                else
                   1350:                        putc('\n', stderr);
1.16      ericj    1351:                va_end(args);
1.14      ericj    1352:        }
1.13      ericj    1353:
1.14      ericj    1354:        if (doexit)
                   1355:                exit(1);
1.17    ! ericj    1356:
        !          1357:        h_errno = errno = 0;
1.7       deraadt  1358: }
1.1       deraadt  1359:
1.11      ericj    1360: void
                   1361: usage(doexit)
1.1       deraadt  1362: {
1.11      ericj    1363:        fprintf(stderr, "netcat - [v1.10]\n");
                   1364:        fprintf(stderr, "nc [-lnrtuvz] [-e command] [-g intermediates]\n");
                   1365:        fprintf(stderr, "   [-G hopcount] [-i interval] [-o filename] [-p source port]\n");
                   1366:        fprintf(stderr, "   [-s ip address] [-w timeout] [hostname] [port[s...]]\n");
                   1367:        if (doexit)
                   1368:                exit(1);
                   1369: }
                   1370:
                   1371: void
                   1372: help()
                   1373: {
                   1374:        usage(0);
                   1375:        fprintf(stderr, "\tCommand Summary:\n\
                   1376:         \t-g gateway   source-routing hop point[s], up to 8\n\
                   1377:         \t-G num\t     source-routing pointer: 4, 8, 12, ...\n\
                   1378:         \t-h           this help text\n\
                   1379:         \t-i secs\t    delay interval for lines sent, ports scanned\n\
                   1380:         \t-l           listen mode, for inbound connects\n\
                   1381:         \t-n           numeric-only IP addresses, no DNS\n\
                   1382:         \t-o file\t    hex dump of traffic\n\
                   1383:         \t-r           randomize local and remote ports\n\
                   1384:         \t-s addr\t    local source address\n");
1.1       deraadt  1385: #ifdef TELNET
1.11      ericj    1386:         fprintf(stderr, "\t\t-t                answer TELNET negotiation\n");
1.1       deraadt  1387: #endif
1.11      ericj    1388:         fprintf(stderr, "\t\t-u                UDP mode\n\
                   1389:         \t-v           verbose [use twice to be more verbose]\n\
                   1390:         \t-w secs\t    timeout for connects and final net reads\n\
                   1391:         \t-z           zero-I/O mode [used for scanning]\n\
                   1392:         Port numbers can be individual or ranges: lo-hi [inclusive]\n");
                   1393:        exit(1);
1.7       deraadt  1394: }