nc_bloaty.c 28 KB

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