nc_bloaty.c 31 KB

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