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