nc_bloaty.c 30 KB

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