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