nc: code shrinkage, bugfixes. -50 bytes code size
[oweals/busybox.git] / networking / nc_bloaty.c
1 /* Based on netcat 1.10 RELEASE 960320 written by hobbit@avian.org.
2  * Released into public domain by the author.
3  *
4  * Copyright (C) 2007 Denis Vlasenko.
5  *
6  * Licensed under GPLv2, see file LICENSE in this tarball for details.
7  */
8
9 /* Author's comments from nc 1.10:
10  * =====================
11  * Netcat is entirely my own creation, although plenty of other code was used as
12  * examples.  It is freely given away to the Internet community in the hope that
13  * it will be useful, with no restrictions except giving credit where it is due.
14  * No GPLs, Berkeley copyrights or any of that nonsense.  The author assumes NO
15  * responsibility for how anyone uses it.  If netcat makes you rich somehow and
16  * you're feeling generous, mail me a check.  If you are affiliated in any way
17  * with Microsoft Network, get a life.  Always ski in control.  Comments,
18  * questions, and patches to hobbit@avian.org.
19  * ...
20  * Netcat and the associated package is a product of Avian Research, and is freely
21  * available in full source form with no restrictions save an obligation to give
22  * credit where due.
23  * ...
24  * A damn useful little "backend" utility begun 950915 or thereabouts,
25  * as *Hobbit*'s first real stab at some sockets programming.  Something that
26  * should have and indeed may have existed ten years ago, but never became a
27  * standard Unix utility.  IMHO, "nc" could take its place right next to cat,
28  * cp, rm, mv, dd, ls, and all those other cryptic and Unix-like things.
29  * =====================
30  *
31  * Much of author's comments are still retained in the code.
32  *
33  * Functionality removed (rationale):
34  * - miltiple-port ranges, randomized port scanning (use nmap)
35  * - telnet support (use telnet)
36  * - source routing
37  * - multiple DNS checks
38  * Functionalty which is different from nc 1.10:
39  * - Prog in '-e prog' can have prog's parameters and options.
40  *   Because of this -e option must be last.
41  * - nc doesn't redirect stderr to the network socket for the -e prog.
42  * - numeric addresses are printed in (), not [] (IPv6 looks better),
43  *   port numbers are inside (): (1.2.3.4:5678)
44  * - network read errors are reported on verbose levels > 1
45  *   (nc 1.10 treats them as EOF)
46  * - TCP connects from wrong ip/ports (if peer ip:port is specified
47  *   on the command line, but accept() says that it came from different addr)
48  *   are closed, but nc doesn't exit - continues to listen/accept.
49  */
50
51 /* done in nc.c: #include "busybox.h" */
52
53 enum {
54         SLEAZE_PORT = 31337,               /* for UDP-scan RTT trick, change if ya want */
55         BIGSIZ = 8192,                     /* big buffers */
56
57         netfd = 3,
58         ofd = 4,
59 };
60
61 struct globals {
62         /* global cmd flags: */
63         unsigned o_verbose;
64         unsigned o_wait;
65 #if ENABLE_NC_EXTRA
66         unsigned o_interval;
67 #endif
68
69         /*int netfd;*/
70         /*int ofd;*/                     /* hexdump output fd */
71 #if ENABLE_LFS
72 #define SENT_N_RECV_M "sent %llu, rcvd %llu\n"
73         unsigned long long wrote_out;          /* total stdout bytes */
74         unsigned long long wrote_net;          /* total net bytes */
75 #else
76 #define SENT_N_RECV_M "sent %u, rcvd %u\n"
77         unsigned wrote_out;          /* total stdout bytes */
78         unsigned wrote_net;          /* total net bytes */
79 #endif
80         /* ouraddr is never NULL and goes thru three states as we progress:
81          1 - local address before bind (IP/port possibly zero)
82          2 - local address after bind (port is nonzero)
83          3 - local address after connect??/recv/accept (IP and port are nonzero) */
84         struct len_and_sockaddr *ouraddr;
85         /* themaddr is NULL if no peer hostname[:port] specified on command line */
86         struct len_and_sockaddr *themaddr;
87         /* remend is set after connect/recv/accept to the actual ip:port of peer */
88         struct len_and_sockaddr remend;
89
90         jmp_buf jbuf;                /* timer crud */
91
92         /* will malloc up the following globals: */
93         fd_set ding1;                /* for select loop */
94         fd_set ding2;
95         char bigbuf_in[BIGSIZ];      /* data buffers */
96         char bigbuf_net[BIGSIZ];
97 };
98
99 #define G (*ptr_to_globals)
100
101 #define wrote_out  (G.wrote_out )
102 #define wrote_net  (G.wrote_net )
103 #define ouraddr    (G.ouraddr   )
104 #define themaddr   (G.themaddr  )
105 #define remend     (G.remend    )
106 #define jbuf       (G.jbuf      )
107 #define ding1      (G.ding1     )
108 #define ding2      (G.ding2     )
109 #define bigbuf_in  (G.bigbuf_in )
110 #define bigbuf_net (G.bigbuf_net)
111 #define o_verbose  (G.o_verbose )
112 #define o_wait     (G.o_wait    )
113 #if ENABLE_NC_EXTRA
114 #define o_interval (G.o_interval)
115 #else
116 #define o_interval 0
117 #endif
118
119 /* Must match getopt32 call! */
120 enum {
121         OPT_h = (1 << 0),
122         OPT_n = (1 << 1),
123         OPT_p = (1 << 2),
124         OPT_s = (1 << 3),
125         OPT_u = (1 << 4),
126         OPT_v = (1 << 5),
127         OPT_w = (1 << 6),
128         OPT_l = (1 << 7) * ENABLE_NC_SERVER,
129         OPT_i = (1 << (7+ENABLE_NC_SERVER)) * ENABLE_NC_EXTRA,
130         OPT_o = (1 << (8+ENABLE_NC_SERVER)) * ENABLE_NC_EXTRA,
131         OPT_z = (1 << (9+ENABLE_NC_SERVER)) * ENABLE_NC_EXTRA,
132 };
133
134 #define o_nflag   (option_mask32 & OPT_n)
135 #define o_udpmode (option_mask32 & OPT_u)
136 #if ENABLE_NC_SERVER
137 #define o_listen  (option_mask32 & OPT_l)
138 #else
139 #define o_listen  0
140 #endif
141 #if ENABLE_NC_EXTRA
142 #define o_ofile   (option_mask32 & OPT_o)
143 #define o_zero    (option_mask32 & OPT_z)
144 #else
145 #define o_ofile   0
146 #define o_zero    0
147 #endif
148
149 /* Debug: squirt whatever message and sleep a bit so we can see it go by. */
150 /* Beware: writes to stdOUT... */
151 #if 0
152 #define Debug(...) do { printf(__VA_ARGS__); printf("\n"); fflush(stdout); sleep(1); } while(0)
153 #else
154 #define Debug(...) do { } while(0)
155 #endif
156
157 #define holler_error(...)  do { if (o_verbose) bb_error_msg(__VA_ARGS__); } while(0)
158 #define holler_perror(...) do { if (o_verbose) bb_perror_msg(__VA_ARGS__); } while(0)
159
160 /* catch: no-brainer interrupt handler */
161 static void catch(int sig)
162 {
163         errno = 0;
164         if (o_verbose > 1)                /* normally we don't care */
165                 fprintf(stderr, SENT_N_RECV_M, wrote_net, wrote_out);
166         fprintf(stderr, "punt!\n");
167         exit(1);
168 }
169
170 /* timeout and other signal handling cruft */
171 static void tmtravel(int sig)
172 {
173         signal(SIGALRM, SIG_IGN);
174         alarm(0);
175         longjmp(jbuf, 1);
176 }
177
178 /* arm: set the timer.  */
179 static void arm(unsigned secs)
180 {
181         signal(SIGALRM, tmtravel);
182         alarm(secs);
183 }
184
185 /* unarm  */
186 static void unarm(void)
187 {
188         signal(SIGALRM, SIG_IGN);
189         alarm(0);
190 }
191
192 /* findline:
193  find the next newline in a buffer; return inclusive size of that "line",
194  or the entire buffer size, so the caller knows how much to then write().
195  Not distinguishing \n vs \r\n for the nonce; it just works as is... */
196 static unsigned findline(char *buf, unsigned siz)
197 {
198         char * p;
199         int x;
200         if (!buf)                        /* various sanity checks... */
201                 return 0;
202         if (siz > BIGSIZ)
203                 return 0;
204         x = siz;
205         for (p = buf; x > 0; x--) {
206                 if (*p == '\n') {
207                         x = (int) (p - buf);
208                         x++;                        /* 'sokay if it points just past the end! */
209 Debug("findline returning %d", x);
210                         return x;
211                 }
212                 p++;
213         } /* for */
214 Debug("findline returning whole thing: %d", siz);
215         return siz;
216 } /* findline */
217
218 /* doexec:
219  fiddle all the file descriptors around, and hand off to another prog.  Sort
220  of like a one-off "poor man's inetd".  This is the only section of code
221  that would be security-critical, which is why it's ifdefed out by default.
222  Use at your own hairy risk; if you leave shells lying around behind open
223  listening ports you deserve to lose!! */
224 static int doexec(char **proggie) ATTRIBUTE_NORETURN;
225 static int doexec(char **proggie)
226 {
227         xmove_fd(netfd, 0);
228         dup2(0, 1);
229         /* dup2(0, 2); - do we *really* want this? NO!
230          * exec'ed prog can do it yourself, if needed */
231         execvp(proggie[0], proggie);
232         bb_perror_msg_and_die("exec");
233 }
234
235 /* connect_w_timeout:
236  return an fd for one of
237  an open outbound TCP connection, a UDP stub-socket thingie, or
238  an unconnected TCP or UDP socket to listen on.
239  Examines various global o_blah flags to figure out what to do.
240  lad can be NULL, then socket is not bound to any local ip[:port] */
241 static int connect_w_timeout(int fd)
242 {
243         int rr;
244
245         /* wrap connect inside a timer, and hit it */
246         arm(o_wait);
247         if (setjmp(jbuf) == 0) {
248                 rr = connect(fd, &themaddr->sa, themaddr->len);
249         } else { /* setjmp: connect failed... */
250                 rr = -1;
251                 errno = ETIMEDOUT; /* fake it */
252         }
253         unarm();
254         return rr;
255 }
256
257 /* dolisten:
258  listens for
259  incoming and returns an open connection *from* someplace.  If we were
260  given host/port args, any connections from elsewhere are rejected.  This
261  in conjunction with local-address binding should limit things nicely... */
262 static void dolisten(void)
263 {
264         int rr;
265
266         if (!o_udpmode)
267                 xlisten(netfd, 1); /* TCP: gotta listen() before we can get */
268
269         /* Various things that follow temporarily trash bigbuf_net, which might contain
270          a copy of any recvfrom()ed packet, but we'll read() another copy later. */
271
272         /* I can't believe I have to do all this to get my own goddamn bound address
273          and port number.  It should just get filled in during bind() or something.
274          All this is only useful if we didn't say -p for listening, since if we
275          said -p we *know* what port we're listening on.  At any rate we won't bother
276          with it all unless we wanted to see it, although listening quietly on a
277          random unknown port is probably not very useful without "netstat". */
278         if (o_verbose) {
279                 char *addr;
280                 rr = getsockname(netfd, &ouraddr->sa, &ouraddr->len);
281                 if (rr < 0)
282                         bb_perror_msg_and_die("getsockname after bind");
283                 addr = xmalloc_sockaddr2dotted(&ouraddr->sa, ouraddr->len);
284                 fprintf(stderr, "listening on %s ...\n", addr);
285                 free(addr);
286         }
287
288         if (o_udpmode) {
289                 /* UDP is a speeeeecial case -- we have to do I/O *and* get the calling
290                  party's particulars all at once, listen() and accept() don't apply.
291                  At least in the BSD universe, however, recvfrom/PEEK is enough to tell
292                  us something came in, and we can set things up so straight read/write
293                  actually does work after all.  Yow.  YMMV on strange platforms!  */
294
295                 /* I'm not completely clear on how this works -- BSD seems to make UDP
296                  just magically work in a connect()ed context, but we'll undoubtedly run
297                  into systems this deal doesn't work on.  For now, we apparently have to
298                  issue a connect() on our just-tickled socket so we can write() back.
299                  Again, why the fuck doesn't it just get filled in and taken care of?!
300                  This hack is anything but optimal.  Basically, if you want your listener
301                  to also be able to send data back, you need this connect() line, which
302                  also has the side effect that now anything from a different source or even a
303                  different port on the other end won't show up and will cause ICMP errors.
304                  I guess that's what they meant by "connect".
305                  Let's try to remember what the "U" is *really* for, eh? */
306
307                 /* If peer address is specified, connect to it */
308                 remend.len = LSA_SIZEOF_SA;
309                 if (themaddr) {
310                         remend = *themaddr;
311                         xconnect(netfd, &themaddr->sa, themaddr->len);
312                 }
313                 /* peek first packet and remember peer addr */
314                 arm(o_wait);                /* might as well timeout this, too */
315                 if (setjmp(jbuf) == 0) {       /* do timeout for initial connect */
316                         /* (*ouraddr) is prefilled with "default" address */
317                         /* and here we block... */
318                         rr = recv_from_to(netfd, NULL, 0, MSG_PEEK, /*was bigbuf_net, BIGSIZ*/
319                                 &remend.sa, &ouraddr->sa, ouraddr->len);
320                         if (rr < 0)
321                                 bb_perror_msg_and_die("recvfrom");
322                 } else
323                         bb_error_msg_and_die("timeout");
324                 unarm();
325 /* Now we learned *to which IP* peer has connected, and we want to anchor
326 our socket on it, so that our outbound packets will have correct local IP.
327 Unfortunately, bind() on already bound socket will fail now (EINVAL):
328         xbind(netfd, &ouraddr->sa, ouraddr->len);
329 Need to read the packet, save data, close this socket and
330 create new one, and bind() it. TODO */
331                 if (!themaddr)
332                         xconnect(netfd, &remend.sa, ouraddr->len);
333         } else {
334                 /* TCP */
335                 arm(o_wait); /* wrap this in a timer, too; 0 = forever */
336                 if (setjmp(jbuf) == 0) {
337  again:
338                         remend.len = LSA_SIZEOF_SA;
339                         rr = accept(netfd, &remend.sa, &remend.len);
340                         if (rr < 0)
341                                 bb_perror_msg_and_die("accept");
342                         if (themaddr && memcmp(&remend.sa, &themaddr->sa, remend.len) != 0) {
343                                 /* nc 1.10 bails out instead, and its error message
344                                  * is not suppressed by o_verbose */
345                                 if (o_verbose) {
346                                         char *remaddr = xmalloc_sockaddr2dotted(&remend.sa, remend.len);
347                                         bb_error_msg("connect from wrong ip/port %s ignored", remaddr);
348                                         free(remaddr);
349                                 }
350                                 close(rr);
351                                 goto again;
352                         }
353                         
354                 } else
355                         bb_error_msg_and_die("timeout");
356                 unarm();
357                 xmove_fd(rr, netfd); /* dump the old socket, here's our new one */
358                 /* find out what address the connection was *to* on our end, in case we're
359                  doing a listen-on-any on a multihomed machine.  This allows one to
360                  offer different services via different alias addresses, such as the
361                  "virtual web site" hack. */
362                 rr = getsockname(netfd, &ouraddr->sa, &ouraddr->len);
363                 if (rr < 0)
364                         bb_perror_msg_and_die("getsockname after accept");
365         }
366
367         if (o_verbose) {
368                 char *lcladdr, *remaddr, *remhostname;
369
370 #if ENABLE_NC_EXTRA && defined(IP_OPTIONS)
371         /* If we can, look for any IP options.  Useful for testing the receiving end of
372          such things, and is a good exercise in dealing with it.  We do this before
373          the connect message, to ensure that the connect msg is uniformly the LAST
374          thing to emerge after all the intervening crud.  Doesn't work for UDP on
375          any machines I've tested, but feel free to surprise me. */
376                 char optbuf[40];
377                 int x = sizeof(optbuf);
378
379                 rr = getsockopt(netfd, IPPROTO_IP, IP_OPTIONS, optbuf, &x);
380                 if (rr < 0)
381                         bb_perror_msg("getsockopt failed");
382                 else if (x) {    /* we've got options, lessee em... */
383                         bin2hex(bigbuf_net, optbuf, x);
384                         bigbuf_net[2*x] = '\0';
385                         fprintf(stderr, "IP options: %s\n", bigbuf_net);
386                 }
387 #endif
388
389         /* now check out who it is.  We don't care about mismatched DNS names here,
390          but any ADDR and PORT we specified had better fucking well match the caller.
391          Converting from addr to inet_ntoa and back again is a bit of a kludge, but
392          gethostpoop wants a string and there's much gnarlier code out there already,
393          so I don't feel bad.
394          The *real* question is why BFD sockets wasn't designed to allow listens for
395          connections *from* specific hosts/ports, instead of requiring the caller to
396          accept the connection and then reject undesireable ones by closing.
397          In other words, we need a TCP MSG_PEEK. */
398         /* bbox: removed most of it */
399                 lcladdr = xmalloc_sockaddr2dotted(&ouraddr->sa, ouraddr->len);
400                 remaddr = xmalloc_sockaddr2dotted(&remend.sa, remend.len);
401                 remhostname = o_nflag ? remaddr : xmalloc_sockaddr2host(&remend.sa, remend.len);
402                 fprintf(stderr, "connect to %s from %s (%s)\n",
403                                 lcladdr, remhostname, remaddr);
404                 free(lcladdr);
405                 free(remaddr);
406                 if (!o_nflag)
407                         free(remhostname);
408         }
409 }
410
411 /* udptest:
412  fire a couple of packets at a UDP target port, just to see if it's really
413  there.  On BSD kernels, ICMP host/port-unreachable errors get delivered to
414  our socket as ECONNREFUSED write errors.  On SV kernels, we lose; we'll have
415  to collect and analyze raw ICMP ourselves a la satan's probe_udp_ports
416  backend.  Guess where one could swipe the appropriate code from...
417
418  Use the time delay between writes if given, otherwise use the "tcp ping"
419  trick for getting the RTT.  [I got that idea from pluvius, and warped it.]
420  Return either the original fd, or clean up and return -1. */
421 #if ENABLE_NC_EXTRA
422 static int udptest(void)
423 {
424         int rr;
425
426         rr = write(netfd, bigbuf_in, 1);
427         if (rr != 1)
428                 bb_perror_msg("udptest first write");
429
430         if (o_wait)
431                 sleep(o_wait); // can be interrupted! while (t) nanosleep(&t)?
432         else {
433         /* use the tcp-ping trick: try connecting to a normally refused port, which
434          causes us to block for the time that SYN gets there and RST gets back.
435          Not completely reliable, but it *does* mostly work. */
436         /* Set a temporary connect timeout, so packet filtration doesnt cause
437          us to hang forever, and hit it */
438                 o_wait = 5;                     /* enough that we'll notice?? */
439                 rr = xsocket(ouraddr->sa.sa_family, SOCK_STREAM, 0);
440                 set_nport(themaddr, htons(SLEAZE_PORT));
441                 connect_w_timeout(rr);
442                 /* don't need to restore themaddr's port, it's not used anymore */
443                 close(rr);
444                 o_wait = 0; /* restore */
445         }
446
447         rr = write(netfd, bigbuf_in, 1);
448         return (rr != 1); /* if rr == 1, return 0 (success) */
449 }
450 #else
451 int udptest(void);
452 #endif
453
454 /* oprint:
455  Hexdump bytes shoveled either way to a running logfile, in the format:
456  D offset       -  - - - --- 16 bytes --- - - -  -     # .... ascii .....
457  where "which" sets the direction indicator, D:
458  0 -- sent to network, or ">"
459  1 -- rcvd and printed to stdout, or "<"
460  and "buf" and "n" are data-block and length.  If the current block generates
461  a partial line, so be it; we *want* that lockstep indication of who sent
462  what when.  Adapted from dgaudet's original example -- but must be ripping
463  *fast*, since we don't want to be too disk-bound... */
464 #if ENABLE_NC_EXTRA
465 static void oprint(int direction, unsigned char *p, int bc)
466 {
467         int obc;                /* current "global" offset */
468         int soc;                /* stage write count */
469         unsigned char *op;      /* out hexdump ptr */
470         unsigned char *a;       /* out asc-dump ptr */
471         int x;
472         unsigned char stage[100];
473
474         if (bc == 0)
475                 return;
476
477         op = stage;
478         obc = wrote_net; /* use the globals! */
479         if (direction == '<')
480                 obc = wrote_out;
481         *op++ = direction;
482         *op = ' ';
483         stage[59] = '#';                /* preload separator */
484         stage[60] = ' ';
485
486         while (bc) {                        /* for chunk-o-data ... */
487                 x = 16;
488                 soc = 78;                        /* len of whole formatted line */
489                 if (bc < x) {
490                         soc = soc - 16 + bc;        /* fiddle for however much is left */
491                         x = (bc * 3) + 11;        /* 2 digits + space per, after D & offset */
492                         op = &stage[x];
493                         x = 16 - bc;
494                         while (x) {
495                                 *op++ = ' ';                /* preload filler spaces */
496                                 *op++ = ' ';
497                                 *op++ = ' ';
498                                 x--;
499                         }
500                         x = bc;                        /* re-fix current linecount */
501                 } /* if bc < x */
502
503                 bc -= x;                        /* fix wrt current line size */
504                 sprintf(&stage[2], "%8.8x ", obc);                /* xxx: still slow? */
505                 obc += x;                        /* fix current offset */
506                 op = &stage[11];                /* where hex starts */
507                 a = &stage[61];                /* where ascii starts */
508
509                 while (x) {  /* for line of dump, however long ... */
510                         *op++ = 0x20 | bb_hexdigits_upcase[*p >> 4];
511                         *op++ = 0x20 | bb_hexdigits_upcase[*p & 0x0f];
512                         *op++ = ' ';
513                         if ((*p > 31) && (*p < 127))
514                                 *a = *p;                /* printing */
515                         else
516                                 *a = '.';                /* nonprinting, loose def */
517                         a++;
518                         p++;
519                         x--;
520                 } /* while x */
521                 *a = '\n';                        /* finish the line */
522                 xwrite(ofd, stage, soc);
523         } /* while bc */
524 }
525 #else
526 void oprint(int direction, unsigned char *p, int bc);
527 #endif
528
529 /* readwrite:
530  handle stdin/stdout/network I/O.  Bwahaha!! -- the select loop from hell.
531  In this instance, return what might become our exit status. */
532 static int readwrite(void)
533 {
534         int rr;
535         char *zp = zp; /* gcc */  /* stdin buf ptr */
536         char *np = np;            /* net-in buf ptr */
537         unsigned rzleft;
538         unsigned rnleft;
539         unsigned netretry;              /* net-read retry counter */
540         unsigned wretry;                /* net-write sanity counter */
541         unsigned wfirst;                /* one-shot flag to skip first net read */
542
543         /* if you don't have all this FD_* macro hair in sys/types.h, you'll have to
544          either find it or do your own bit-bashing: *ding1 |= (1 << fd), etc... */
545         FD_SET(netfd, &ding1);                /* global: the net is open */
546         netretry = 2;
547         wfirst = 0;
548         rzleft = rnleft = 0;
549         if (o_interval)
550                 sleep(o_interval);                /* pause *before* sending stuff, too */
551
552         errno = 0;                        /* clear from sleep, close, whatever */
553         /* and now the big ol' select shoveling loop ... */
554         while (FD_ISSET(netfd, &ding1)) {        /* i.e. till the *net* closes! */
555                 wretry = 8200;                        /* more than we'll ever hafta write */
556                 if (wfirst) {                        /* any saved stdin buffer? */
557                         wfirst = 0;                        /* clear flag for the duration */
558                         goto shovel;                        /* and go handle it first */
559                 }
560                 ding2 = ding1;                        /* FD_COPY ain't portable... */
561         /* some systems, notably linux, crap into their select timers on return, so
562          we create a expendable copy and give *that* to select.  */
563                 if (o_wait) {
564                         struct timeval tmp_timer;
565                         tmp_timer.tv_sec = o_wait;
566                         tmp_timer.tv_usec = 0;
567                 /* highest possible fd is netfd (3) */
568                         rr = select(netfd+1, &ding2, NULL, NULL, &tmp_timer);
569                 } else
570                         rr = select(netfd+1, &ding2, NULL, NULL, NULL);
571                 if (rr < 0 && errno != EINTR) {                /* might have gotten ^Zed, etc */
572                         holler_perror("select");
573                         close(netfd);
574                         return 1;
575                 }
576         /* if we have a timeout AND stdin is closed AND we haven't heard anything
577          from the net during that time, assume it's dead and close it too. */
578                 if (rr == 0) {
579                         if (!FD_ISSET(0, &ding1))
580                                 netretry--;                        /* we actually try a coupla times. */
581                         if (!netretry) {
582                                 if (o_verbose > 1)                /* normally we don't care */
583                                         fprintf(stderr, "net timeout\n");
584                                 close(netfd);
585                                 return 0;                        /* not an error! */
586                         }
587                 } /* select timeout */
588         /* xxx: should we check the exception fds too?  The read fds seem to give
589          us the right info, and none of the examples I found bothered. */
590
591         /* Ding!!  Something arrived, go check all the incoming hoppers, net first */
592                 if (FD_ISSET(netfd, &ding2)) {                /* net: ding! */
593                         rr = read(netfd, bigbuf_net, BIGSIZ);
594                         if (rr <= 0) {
595                                 if (rr < 0 && o_verbose > 1) {
596                                         /* nc 1.10 doesn't do this */
597                                         bb_perror_msg("net read");
598                                 }
599                                 FD_CLR(netfd, &ding1);                /* net closed, we'll finish up... */
600                                 rzleft = 0;                        /* can't write anymore: broken pipe */
601                         } else {
602                                 rnleft = rr;
603                                 np = bigbuf_net;
604                         }
605 Debug("got %d from the net, errno %d", rr, errno);
606                 } /* net:ding */
607
608         /* if we're in "slowly" mode there's probably still stuff in the stdin
609          buffer, so don't read unless we really need MORE INPUT!  MORE INPUT! */
610                 if (rzleft)
611                         goto shovel;
612
613         /* okay, suck more stdin */
614                 if (FD_ISSET(0, &ding2)) {                /* stdin: ding! */
615                         rr = read(0, bigbuf_in, BIGSIZ);
616         /* Considered making reads here smaller for UDP mode, but 8192-byte
617          mobygrams are kinda fun and exercise the reassembler. */
618                         if (rr <= 0) {                        /* at end, or fukt, or ... */
619                                 FD_CLR(0, &ding1);                /* disable and close stdin */
620                                 close(0);
621                         } else {
622                                 rzleft = rr;
623                                 zp = bigbuf_in;
624                         }
625                 } /* stdin:ding */
626  shovel:
627         /* now that we've dingdonged all our thingdings, send off the results.
628          Geez, why does this look an awful lot like the big loop in "rsh"? ...
629          not sure if the order of this matters, but write net -> stdout first. */
630
631         /* sanity check.  Works because they're both unsigned... */
632                 if ((rzleft > 8200) || (rnleft > 8200)) {
633                         holler_error("bogus buffers: %u, %u", rzleft, rnleft);
634                         rzleft = rnleft = 0;
635                 }
636         /* net write retries sometimes happen on UDP connections */
637                 if (!wretry) {                        /* is something hung? */
638                         holler_error("too many output retries");
639                         return 1;
640                 }
641                 if (rnleft) {
642                         rr = write(1, np, rnleft);
643                         if (rr > 0) {
644                                 if (o_ofile)
645                                         oprint('<', np, rr);                /* log the stdout */
646                                 np += rr;                        /* fix up ptrs and whatnot */
647                                 rnleft -= rr;                        /* will get sanity-checked above */
648                                 wrote_out += rr;                /* global count */
649                         }
650 Debug("wrote %d to stdout, errno %d", rr, errno);
651                 } /* rnleft */
652                 if (rzleft) {
653                         if (o_interval)                        /* in "slowly" mode ?? */
654                                 rr = findline(zp, rzleft);
655                         else
656                                 rr = rzleft;
657                         rr = write(netfd, zp, rr);        /* one line, or the whole buffer */
658                         if (rr > 0) {
659                                 if (o_ofile)
660                                         oprint('>', zp, rr);                /* log what got sent */
661                                 zp += rr;
662                                 rzleft -= rr;
663                                 wrote_net += rr;                /* global count */
664                         }
665 Debug("wrote %d to net, errno %d", rr, errno);
666                 } /* rzleft */
667                 if (o_interval) {                        /* cycle between slow lines, or ... */
668                         sleep(o_interval);
669                         errno = 0;                        /* clear from sleep */
670                         continue;                        /* ...with hairy select loop... */
671                 }
672                 if ((rzleft) || (rnleft)) {                /* shovel that shit till they ain't */
673                         wretry--;                        /* none left, and get another load */
674                         goto shovel;
675                 }
676         } /* while ding1:netfd is open */
677
678         /* XXX: maybe want a more graceful shutdown() here, or screw around with
679          linger times??  I suspect that I don't need to since I'm always doing
680          blocking reads and writes and my own manual "last ditch" efforts to read
681          the net again after a timeout.  I haven't seen any screwups yet, but it's
682          not like my test network is particularly busy... */
683         close(netfd);
684         return 0;
685 } /* readwrite */
686
687 /* main: now we pull it all together... */
688 int nc_main(int argc, char **argv);
689 int nc_main(int argc, char **argv)
690 {
691         char *str_p, *str_s, *str_w;
692         USE_NC_EXTRA(char *str_i, *str_o;)
693         char *themdotted = themdotted; /* gcc */
694         char **proggie;
695         int x;
696         unsigned o_lport = 0;
697
698         /* I was in this barbershop quartet in Skokie IL ... */
699         /* round up the usual suspects, i.e. malloc up all the stuff we need */
700         PTR_TO_GLOBALS = xzalloc(sizeof(G));
701
702         /* catch a signal or two for cleanup */
703         signal(SIGINT, catch);
704         signal(SIGQUIT, catch);
705         signal(SIGTERM, catch);
706         /* and suppress others... */
707 #ifdef SIGURG
708         signal(SIGURG, SIG_IGN);
709 #endif
710         signal(SIGPIPE, SIG_IGN); /* important! */
711
712         proggie = argv;
713         while (*++proggie) {
714                 if (strcmp(*proggie, "-e") == 0) {
715                         *proggie = NULL;
716                         argc = proggie - argv;
717                         proggie++;
718                         goto e_found;
719                 }
720         }
721         proggie = NULL;
722  e_found:
723                 
724         // -g -G -t -r deleted, unimplemented -a deleted too
725         opt_complementary = "?2:vv"; /* max 2 params, -v is a counter */
726         getopt32(argc, argv, "hnp:s:uvw:" USE_NC_SERVER("l")
727                         USE_NC_EXTRA("i:o:z"),
728                         &str_p, &str_s, &str_w
729                         USE_NC_EXTRA(, &str_i, &str_o, &o_verbose));
730         argv += optind;
731 #if ENABLE_NC_EXTRA
732         if (option_mask32 & OPT_i) /* line-interval time */
733                 o_interval = xatou_range(str_i, 1, 0xffff);
734 #endif
735         //if (option_mask32 & OPT_l) /* listen mode */
736         //if (option_mask32 & OPT_n) /* numeric-only, no DNS lookups */
737         //if (option_mask32 & OPT_o) /* hexdump log */
738         if (option_mask32 & OPT_p) { /* local source port */
739                 o_lport = bb_lookup_port(str_p, o_udpmode ? "udp" : "tcp", 0);
740                 if (!o_lport)
741                         bb_error_msg_and_die("bad local port '%s'", str_p);
742         }
743         //if (option_mask32 & OPT_r) /* randomize various things */
744         //if (option_mask32 & OPT_u) /* use UDP */
745         //if (option_mask32 & OPT_v) /* verbose */
746         if (option_mask32 & OPT_w) { /* wait time */
747                 o_wait = xatoi_u(str_w);
748         }
749         //if (option_mask32 & OPT_z) /* little or no data xfer */
750
751         /* We manage our fd's so that they are never 0,1,2 */
752         /*bb_sanitize_stdio(); - not needed */
753
754         /* create & bind network socket */
755         x = (o_udpmode ? SOCK_DGRAM : SOCK_STREAM);
756         if (option_mask32 & OPT_s) { /* local address */
757                 /* if o_lport is still 0, then we will use random port */
758                 ouraddr = xhost2sockaddr(str_s, o_lport);
759                 x = xsocket(ouraddr->sa.sa_family, x, 0);
760         } else {
761                 x = xsocket_type(&ouraddr, x);
762                 if (o_lport)
763                         set_nport(ouraddr, htons(o_lport));
764         }
765         xmove_fd(x, netfd);
766         setsockopt_reuseaddr(netfd);
767         if (o_udpmode)
768                 socket_want_pktinfo(netfd);
769         xbind(netfd, &ouraddr->sa, ouraddr->len);
770 #if 0
771         setsockopt(netfd, SOL_SOCKET, SO_RCVBUF, &o_rcvbuf, sizeof o_rcvbuf);
772         setsockopt(netfd, SOL_SOCKET, SO_SNDBUF, &o_sndbuf, sizeof o_sndbuf);
773 #endif
774
775         if (OPT_l && (option_mask32 & (OPT_u|OPT_l)) == (OPT_u|OPT_l)) {
776                 /* apparently UDP can listen ON "port 0",
777                  but that's not useful */
778                 if (!o_lport)
779                         bb_error_msg_and_die("UDP listen needs nonzero -p port");
780         }
781
782         FD_SET(0, &ding1);                        /* stdin *is* initially open */
783         if (proggie) {
784                 close(0); /* won't need stdin */
785                 option_mask32 &= ~OPT_o; /* -o with -e is meaningless! */
786         }
787 #if ENABLE_NC_EXTRA
788         if (o_ofile)
789                 xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), ofd);
790 #endif
791
792         if (argv[0]) {
793                 themaddr = xhost2sockaddr(argv[0],
794                         argv[1]
795                         ? bb_lookup_port(argv[1], o_udpmode ? "udp" : "tcp", 0)
796                         : 0);
797 ///what if sa_family won't match??
798         }
799
800         if (o_listen) {
801                 dolisten();
802                 /* dolisten does its own connect reporting */
803                 if (proggie) /* -e given? */
804                         doexec(proggie);
805                 x = readwrite(); /* it even works with UDP! */
806         } else {
807                 /* Outbound connects.  Now we're more picky about args... */
808                 if (!themaddr)
809                         bb_error_msg_and_die("no destination");
810
811                 remend = *themaddr;
812                 if (o_verbose)
813                         themdotted = xmalloc_sockaddr2dotted(&themaddr->sa, themaddr->len);
814
815                 x = connect_w_timeout(netfd);
816                 if (o_zero && x == 0 && o_udpmode)        /* if UDP scanning... */
817                         x = udptest();
818                 if (x == 0) {                        /* Yow, are we OPEN YET?! */
819                         if (o_verbose)
820                                 fprintf(stderr, "%s (%s) open\n", argv[0], themdotted);
821                         if (proggie)                        /* exec is valid for outbound, too */
822                                 doexec(proggie);
823                         if (!o_zero)
824                                 x = readwrite();
825                 } else { /* connect or udptest wasn't successful */
826                         x = 1;                                /* exit status */
827                         /* if we're scanning at a "one -v" verbosity level, don't print refusals.
828                          Give it another -v if you want to see everything. */
829                         if (o_verbose > 1 || (o_verbose && errno != ECONNREFUSED))
830                                 bb_perror_msg("%s (%s)", argv[0], themdotted);
831                 }
832         }
833         if (o_verbose > 1)                /* normally we don't care */
834                 fprintf(stderr, SENT_N_RECV_M, wrote_net, wrote_out);
835         return x;
836 }