blob: 8594a67a6131e345dd7aba4569f195f393b0a831 [file] [log] [blame]
Denis Vlasenko29fe7262007-04-05 20:26:28 +00001/* Based on netcat 1.10 RELEASE 960320 written by hobbit@avian.org.
2 * Released into public domain by the author.
3 *
Denis Vlasenko7cff01e2008-02-02 16:23:43 +00004 * Copyright (C) 2007 Denys Vlasenko.
Denis Vlasenko29fe7262007-04-05 20:26:28 +00005 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02006 * Licensed under GPLv2, see file LICENSE in this source tree.
Denis Vlasenko29fe7262007-04-05 20:26:28 +00007 */
8
9/* Author's comments from nc 1.10:
10 * =====================
11 * Netcat is entirely my own creation, although plenty of other code was used as
12 * examples. It is freely given away to the Internet community in the hope that
13 * it will be useful, with no restrictions except giving credit where it is due.
14 * No GPLs, Berkeley copyrights or any of that nonsense. The author assumes NO
15 * responsibility for how anyone uses it. If netcat makes you rich somehow and
16 * you're feeling generous, mail me a check. If you are affiliated in any way
17 * with Microsoft Network, get a life. Always ski in control. Comments,
18 * questions, and patches to hobbit@avian.org.
19 * ...
20 * Netcat and the associated package is a product of Avian Research, and is freely
21 * available in full source form with no restrictions save an obligation to give
22 * credit where due.
23 * ...
24 * A damn useful little "backend" utility begun 950915 or thereabouts,
25 * as *Hobbit*'s first real stab at some sockets programming. Something that
26 * should have and indeed may have existed ten years ago, but never became a
27 * standard Unix utility. IMHO, "nc" could take its place right next to cat,
28 * cp, rm, mv, dd, ls, and all those other cryptic and Unix-like things.
29 * =====================
30 *
31 * Much of author's comments are still retained in the code.
32 *
33 * Functionality removed (rationale):
34 * - miltiple-port ranges, randomized port scanning (use nmap)
35 * - telnet support (use telnet)
36 * - source routing
37 * - multiple DNS checks
38 * Functionalty which is different from nc 1.10:
Denys Vlasenko7d1201c2010-06-28 04:17:06 +020039 * - PROG in '-e PROG' can have ARGS (and options).
Denis Vlasenko29fe7262007-04-05 20:26:28 +000040 * Because of this -e option must be last.
Denys Vlasenko7d1201c2010-06-28 04:17:06 +020041//TODO: remove -e incompatibility?
42 * - we don't redirect stderr to the network socket for the -e PROG.
43 * (PROG can do it itself if needed, but sometimes it is NOT wanted!)
Denis Vlasenko19507f02007-04-06 10:41:05 +000044 * - numeric addresses are printed in (), not [] (IPv6 looks better),
45 * port numbers are inside (): (1.2.3.4:5678)
46 * - network read errors are reported on verbose levels > 1
47 * (nc 1.10 treats them as EOF)
48 * - TCP connects from wrong ip/ports (if peer ip:port is specified
49 * on the command line, but accept() says that it came from different addr)
Denys Vlasenko7d1201c2010-06-28 04:17:06 +020050 * are closed, but we don't exit - we continue to listen/accept.
Denis Vlasenko29fe7262007-04-05 20:26:28 +000051 */
52
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000053/* done in nc.c: #include "libbb.h" */
Denis Vlasenko29fe7262007-04-05 20:26:28 +000054
Denys Vlasenko77cc2c52010-06-27 04:22:02 +020055//usage:#if ENABLE_NC_110_COMPAT
56//usage:
57//usage:#define nc_trivial_usage
58//usage: "[OPTIONS] HOST PORT - connect"
59//usage: IF_NC_SERVER("\n"
Denys Vlasenko3b2acb72010-10-09 21:10:32 +020060//usage: "nc [OPTIONS] -l -p PORT [HOST] [PORT] - listen"
61//usage: )
Denys Vlasenko77cc2c52010-06-27 04:22:02 +020062//usage:#define nc_full_usage "\n\n"
63//usage: "Options:"
64//usage: "\n -e PROG Run PROG after connect (must be last)"
65//usage: IF_NC_SERVER(
66//usage: "\n -l Listen mode, for inbound connects"
67//usage: )
68//usage: "\n -p PORT Local port"
69//usage: "\n -s ADDR Local address"
70//usage: "\n -w SEC Timeout for connects and final net reads"
71//usage: IF_NC_EXTRA(
72//usage: "\n -i SEC Delay interval for lines sent" /* ", ports scanned" */
73//usage: )
74//usage: "\n -n Don't do DNS resolution"
75//usage: "\n -u UDP mode"
76//usage: "\n -v Verbose"
77//usage: IF_NC_EXTRA(
78//usage: "\n -o FILE Hex dump traffic"
79//usage: "\n -z Zero-I/O mode (scanning)"
80//usage: )
81//usage:#endif
82
83/* "\n -r Randomize local and remote ports" */
84/* "\n -g gateway Source-routing hop point[s], up to 8" */
85/* "\n -G num Source-routing pointer: 4, 8, 12, ..." */
86/* "\nport numbers can be individual or ranges: lo-hi [inclusive]" */
87
88/* -e PROG can take ARGS too: "nc ... -e ls -l", but we don't document it
89 * in help text: nc 1.10 does not allow that. We don't want to entice
90 * users to use this incompatibility */
91
Denis Vlasenko19507f02007-04-06 10:41:05 +000092enum {
93 SLEAZE_PORT = 31337, /* for UDP-scan RTT trick, change if ya want */
94 BIGSIZ = 8192, /* big buffers */
95
96 netfd = 3,
97 ofd = 4,
98};
Denis Vlasenko29fe7262007-04-05 20:26:28 +000099
100struct globals {
Denis Vlasenko19507f02007-04-06 10:41:05 +0000101 /* global cmd flags: */
102 unsigned o_verbose;
103 unsigned o_wait;
104#if ENABLE_NC_EXTRA
105 unsigned o_interval;
106#endif
107
108 /*int netfd;*/
109 /*int ofd;*/ /* hexdump output fd */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000110#if ENABLE_LFS
111#define SENT_N_RECV_M "sent %llu, rcvd %llu\n"
112 unsigned long long wrote_out; /* total stdout bytes */
113 unsigned long long wrote_net; /* total net bytes */
114#else
Denis Vlasenko19507f02007-04-06 10:41:05 +0000115#define SENT_N_RECV_M "sent %u, rcvd %u\n"
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000116 unsigned wrote_out; /* total stdout bytes */
117 unsigned wrote_net; /* total net bytes */
118#endif
Bernhard Reutner-Fischera985d302008-02-11 11:44:38 +0000119 /* ouraddr is never NULL and goes through three states as we progress:
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000120 1 - local address before bind (IP/port possibly zero)
121 2 - local address after bind (port is nonzero)
122 3 - local address after connect??/recv/accept (IP and port are nonzero) */
123 struct len_and_sockaddr *ouraddr;
124 /* themaddr is NULL if no peer hostname[:port] specified on command line */
125 struct len_and_sockaddr *themaddr;
126 /* remend is set after connect/recv/accept to the actual ip:port of peer */
127 struct len_and_sockaddr remend;
128
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000129 jmp_buf jbuf; /* timer crud */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000130
131 /* will malloc up the following globals: */
132 fd_set ding1; /* for select loop */
133 fd_set ding2;
134 char bigbuf_in[BIGSIZ]; /* data buffers */
135 char bigbuf_net[BIGSIZ];
136};
137
138#define G (*ptr_to_globals)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000139#define wrote_out (G.wrote_out )
140#define wrote_net (G.wrote_net )
141#define ouraddr (G.ouraddr )
142#define themaddr (G.themaddr )
143#define remend (G.remend )
144#define jbuf (G.jbuf )
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000145#define ding1 (G.ding1 )
146#define ding2 (G.ding2 )
147#define bigbuf_in (G.bigbuf_in )
148#define bigbuf_net (G.bigbuf_net)
149#define o_verbose (G.o_verbose )
150#define o_wait (G.o_wait )
151#if ENABLE_NC_EXTRA
152#define o_interval (G.o_interval)
153#else
154#define o_interval 0
155#endif
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000156#define INIT_G() do { \
157 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
158} while (0)
159
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000160
161/* Must match getopt32 call! */
162enum {
163 OPT_h = (1 << 0),
164 OPT_n = (1 << 1),
165 OPT_p = (1 << 2),
166 OPT_s = (1 << 3),
167 OPT_u = (1 << 4),
168 OPT_v = (1 << 5),
169 OPT_w = (1 << 6),
170 OPT_l = (1 << 7) * ENABLE_NC_SERVER,
171 OPT_i = (1 << (7+ENABLE_NC_SERVER)) * ENABLE_NC_EXTRA,
172 OPT_o = (1 << (8+ENABLE_NC_SERVER)) * ENABLE_NC_EXTRA,
173 OPT_z = (1 << (9+ENABLE_NC_SERVER)) * ENABLE_NC_EXTRA,
174};
175
176#define o_nflag (option_mask32 & OPT_n)
177#define o_udpmode (option_mask32 & OPT_u)
Denis Vlasenko19507f02007-04-06 10:41:05 +0000178#if ENABLE_NC_SERVER
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000179#define o_listen (option_mask32 & OPT_l)
Denis Vlasenko19507f02007-04-06 10:41:05 +0000180#else
181#define o_listen 0
182#endif
183#if ENABLE_NC_EXTRA
184#define o_ofile (option_mask32 & OPT_o)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000185#define o_zero (option_mask32 & OPT_z)
186#else
Denis Vlasenko19507f02007-04-06 10:41:05 +0000187#define o_ofile 0
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000188#define o_zero 0
189#endif
190
Denis Vlasenko19507f02007-04-06 10:41:05 +0000191/* Debug: squirt whatever message and sleep a bit so we can see it go by. */
192/* Beware: writes to stdOUT... */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000193#if 0
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100194#define Debug(...) do { printf(__VA_ARGS__); printf("\n"); fflush_all(); sleep(1); } while (0)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000195#else
Denis Vlasenko51742f42007-04-12 00:32:05 +0000196#define Debug(...) do { } while (0)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000197#endif
198
Denis Vlasenko51742f42007-04-12 00:32:05 +0000199#define holler_error(...) do { if (o_verbose) bb_error_msg(__VA_ARGS__); } while (0)
200#define holler_perror(...) do { if (o_verbose) bb_perror_msg(__VA_ARGS__); } while (0)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000201
202/* catch: no-brainer interrupt handler */
203static void catch(int sig)
204{
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000205 if (o_verbose > 1) /* normally we don't care */
206 fprintf(stderr, SENT_N_RECV_M, wrote_net, wrote_out);
207 fprintf(stderr, "punt!\n");
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000208 kill_myself_with_sig(sig);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000209}
210
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000211/* unarm */
212static void unarm(void)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000213{
214 signal(SIGALRM, SIG_IGN);
215 alarm(0);
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000216}
217
218/* timeout and other signal handling cruft */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000219static void tmtravel(int sig UNUSED_PARAM)
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000220{
221 unarm();
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000222 longjmp(jbuf, 1);
223}
224
225/* arm: set the timer. */
226static void arm(unsigned secs)
227{
228 signal(SIGALRM, tmtravel);
229 alarm(secs);
230}
231
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000232/* findline:
233 find the next newline in a buffer; return inclusive size of that "line",
234 or the entire buffer size, so the caller knows how much to then write().
235 Not distinguishing \n vs \r\n for the nonce; it just works as is... */
236static unsigned findline(char *buf, unsigned siz)
237{
238 char * p;
239 int x;
240 if (!buf) /* various sanity checks... */
241 return 0;
242 if (siz > BIGSIZ)
243 return 0;
244 x = siz;
245 for (p = buf; x > 0; x--) {
246 if (*p == '\n') {
247 x = (int) (p - buf);
248 x++; /* 'sokay if it points just past the end! */
Denis Vlasenko19507f02007-04-06 10:41:05 +0000249Debug("findline returning %d", x);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000250 return x;
251 }
252 p++;
253 } /* for */
Denis Vlasenko19507f02007-04-06 10:41:05 +0000254Debug("findline returning whole thing: %d", siz);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000255 return siz;
256} /* findline */
257
258/* doexec:
259 fiddle all the file descriptors around, and hand off to another prog. Sort
260 of like a one-off "poor man's inetd". This is the only section of code
261 that would be security-critical, which is why it's ifdefed out by default.
262 Use at your own hairy risk; if you leave shells lying around behind open
263 listening ports you deserve to lose!! */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000264static int doexec(char **proggie) NORETURN;
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000265static int doexec(char **proggie)
266{
267 xmove_fd(netfd, 0);
268 dup2(0, 1);
269 /* dup2(0, 2); - do we *really* want this? NO!
270 * exec'ed prog can do it yourself, if needed */
271 execvp(proggie[0], proggie);
Denys Vlasenko41ddd9f2010-06-25 01:46:53 +0200272 bb_perror_msg_and_die("can't execute '%s'", proggie[0]);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000273}
274
275/* connect_w_timeout:
276 return an fd for one of
277 an open outbound TCP connection, a UDP stub-socket thingie, or
278 an unconnected TCP or UDP socket to listen on.
279 Examines various global o_blah flags to figure out what to do.
280 lad can be NULL, then socket is not bound to any local ip[:port] */
281static int connect_w_timeout(int fd)
282{
283 int rr;
284
285 /* wrap connect inside a timer, and hit it */
286 arm(o_wait);
287 if (setjmp(jbuf) == 0) {
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000288 rr = connect(fd, &themaddr->u.sa, themaddr->len);
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000289 unarm();
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000290 } else { /* setjmp: connect failed... */
291 rr = -1;
292 errno = ETIMEDOUT; /* fake it */
293 }
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000294 return rr;
295}
296
297/* dolisten:
298 listens for
299 incoming and returns an open connection *from* someplace. If we were
300 given host/port args, any connections from elsewhere are rejected. This
301 in conjunction with local-address binding should limit things nicely... */
302static void dolisten(void)
303{
304 int rr;
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000305
306 if (!o_udpmode)
307 xlisten(netfd, 1); /* TCP: gotta listen() before we can get */
308
309 /* Various things that follow temporarily trash bigbuf_net, which might contain
310 a copy of any recvfrom()ed packet, but we'll read() another copy later. */
311
312 /* I can't believe I have to do all this to get my own goddamn bound address
313 and port number. It should just get filled in during bind() or something.
314 All this is only useful if we didn't say -p for listening, since if we
315 said -p we *know* what port we're listening on. At any rate we won't bother
316 with it all unless we wanted to see it, although listening quietly on a
317 random unknown port is probably not very useful without "netstat". */
318 if (o_verbose) {
319 char *addr;
Denis Vlasenkoa771e7c2009-04-21 23:48:38 +0000320 getsockname(netfd, &ouraddr->u.sa, &ouraddr->len);
321 //if (rr < 0)
322 // bb_perror_msg_and_die("getsockname after bind");
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000323 addr = xmalloc_sockaddr2dotted(&ouraddr->u.sa);
Denis Vlasenko19507f02007-04-06 10:41:05 +0000324 fprintf(stderr, "listening on %s ...\n", addr);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000325 free(addr);
326 }
327
328 if (o_udpmode) {
329 /* UDP is a speeeeecial case -- we have to do I/O *and* get the calling
330 party's particulars all at once, listen() and accept() don't apply.
331 At least in the BSD universe, however, recvfrom/PEEK is enough to tell
332 us something came in, and we can set things up so straight read/write
333 actually does work after all. Yow. YMMV on strange platforms! */
334
335 /* I'm not completely clear on how this works -- BSD seems to make UDP
336 just magically work in a connect()ed context, but we'll undoubtedly run
337 into systems this deal doesn't work on. For now, we apparently have to
338 issue a connect() on our just-tickled socket so we can write() back.
339 Again, why the fuck doesn't it just get filled in and taken care of?!
340 This hack is anything but optimal. Basically, if you want your listener
341 to also be able to send data back, you need this connect() line, which
342 also has the side effect that now anything from a different source or even a
343 different port on the other end won't show up and will cause ICMP errors.
344 I guess that's what they meant by "connect".
345 Let's try to remember what the "U" is *really* for, eh? */
346
347 /* If peer address is specified, connect to it */
Denis Vlasenko19507f02007-04-06 10:41:05 +0000348 remend.len = LSA_SIZEOF_SA;
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000349 if (themaddr) {
350 remend = *themaddr;
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000351 xconnect(netfd, &themaddr->u.sa, themaddr->len);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000352 }
Denis Vlasenko19507f02007-04-06 10:41:05 +0000353 /* peek first packet and remember peer addr */
354 arm(o_wait); /* might as well timeout this, too */
355 if (setjmp(jbuf) == 0) { /* do timeout for initial connect */
356 /* (*ouraddr) is prefilled with "default" address */
357 /* and here we block... */
358 rr = recv_from_to(netfd, NULL, 0, MSG_PEEK, /*was bigbuf_net, BIGSIZ*/
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000359 &remend.u.sa, &ouraddr->u.sa, ouraddr->len);
Denis Vlasenko19507f02007-04-06 10:41:05 +0000360 if (rr < 0)
361 bb_perror_msg_and_die("recvfrom");
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000362 unarm();
Denis Vlasenko19507f02007-04-06 10:41:05 +0000363 } else
364 bb_error_msg_and_die("timeout");
Denis Vlasenko19507f02007-04-06 10:41:05 +0000365/* Now we learned *to which IP* peer has connected, and we want to anchor
366our socket on it, so that our outbound packets will have correct local IP.
367Unfortunately, bind() on already bound socket will fail now (EINVAL):
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000368 xbind(netfd, &ouraddr->u.sa, ouraddr->len);
Denis Vlasenko19507f02007-04-06 10:41:05 +0000369Need to read the packet, save data, close this socket and
370create new one, and bind() it. TODO */
371 if (!themaddr)
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000372 xconnect(netfd, &remend.u.sa, ouraddr->len);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000373 } else {
374 /* TCP */
375 arm(o_wait); /* wrap this in a timer, too; 0 = forever */
376 if (setjmp(jbuf) == 0) {
Denis Vlasenko19507f02007-04-06 10:41:05 +0000377 again:
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000378 remend.len = LSA_SIZEOF_SA;
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000379 rr = accept(netfd, &remend.u.sa, &remend.len);
Denis Vlasenko19507f02007-04-06 10:41:05 +0000380 if (rr < 0)
381 bb_perror_msg_and_die("accept");
Denys Vlasenko866710a2010-01-08 16:09:45 +0100382 if (themaddr) {
383 int sv_port, port, r;
384
385 sv_port = get_nport(&remend.u.sa); /* save */
386 port = get_nport(&themaddr->u.sa);
387 if (port == 0) {
388 /* "nc -nl -p LPORT RHOST" (w/o RPORT!):
389 * we should accept any remote port */
390 set_nport(&remend, 0); /* blot out remote port# */
Denis Vlasenko19507f02007-04-06 10:41:05 +0000391 }
Denys Vlasenko866710a2010-01-08 16:09:45 +0100392 r = memcmp(&remend.u.sa, &themaddr->u.sa, remend.len);
393 set_nport(&remend, sv_port); /* restore */
394 if (r != 0) {
395 /* nc 1.10 bails out instead, and its error message
396 * is not suppressed by o_verbose */
397 if (o_verbose) {
398 char *remaddr = xmalloc_sockaddr2dotted(&remend.u.sa);
399 bb_error_msg("connect from wrong ip/port %s ignored", remaddr);
400 free(remaddr);
401 }
402 close(rr);
403 goto again;
404 }
Denis Vlasenko19507f02007-04-06 10:41:05 +0000405 }
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000406 unarm();
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000407 } else
408 bb_error_msg_and_die("timeout");
Denis Vlasenko19507f02007-04-06 10:41:05 +0000409 xmove_fd(rr, netfd); /* dump the old socket, here's our new one */
410 /* find out what address the connection was *to* on our end, in case we're
411 doing a listen-on-any on a multihomed machine. This allows one to
412 offer different services via different alias addresses, such as the
413 "virtual web site" hack. */
Denis Vlasenkoa771e7c2009-04-21 23:48:38 +0000414 getsockname(netfd, &ouraddr->u.sa, &ouraddr->len);
415 //if (rr < 0)
416 // bb_perror_msg_and_die("getsockname after accept");
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000417 }
Denis Vlasenko19507f02007-04-06 10:41:05 +0000418
419 if (o_verbose) {
420 char *lcladdr, *remaddr, *remhostname;
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000421
422#if ENABLE_NC_EXTRA && defined(IP_OPTIONS)
423 /* If we can, look for any IP options. Useful for testing the receiving end of
424 such things, and is a good exercise in dealing with it. We do this before
425 the connect message, to ensure that the connect msg is uniformly the LAST
426 thing to emerge after all the intervening crud. Doesn't work for UDP on
427 any machines I've tested, but feel free to surprise me. */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000428 char optbuf[40];
Denis Vlasenkoc4f12f52008-05-12 14:35:56 +0000429 socklen_t x = sizeof(optbuf);
Denis Vlasenko19507f02007-04-06 10:41:05 +0000430
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000431 rr = getsockopt(netfd, IPPROTO_IP, IP_OPTIONS, optbuf, &x);
Denis Vlasenkof6b46852009-04-25 13:16:53 +0000432 if (rr >= 0 && x) { /* we've got options, lessee em... */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000433 bin2hex(bigbuf_net, optbuf, x);
434 bigbuf_net[2*x] = '\0';
435 fprintf(stderr, "IP options: %s\n", bigbuf_net);
436 }
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000437#endif
438
439 /* now check out who it is. We don't care about mismatched DNS names here,
440 but any ADDR and PORT we specified had better fucking well match the caller.
441 Converting from addr to inet_ntoa and back again is a bit of a kludge, but
442 gethostpoop wants a string and there's much gnarlier code out there already,
443 so I don't feel bad.
444 The *real* question is why BFD sockets wasn't designed to allow listens for
445 connections *from* specific hosts/ports, instead of requiring the caller to
446 accept the connection and then reject undesireable ones by closing.
447 In other words, we need a TCP MSG_PEEK. */
448 /* bbox: removed most of it */
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000449 lcladdr = xmalloc_sockaddr2dotted(&ouraddr->u.sa);
450 remaddr = xmalloc_sockaddr2dotted(&remend.u.sa);
451 remhostname = o_nflag ? remaddr : xmalloc_sockaddr2host(&remend.u.sa);
Denis Vlasenko19507f02007-04-06 10:41:05 +0000452 fprintf(stderr, "connect to %s from %s (%s)\n",
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000453 lcladdr, remhostname, remaddr);
454 free(lcladdr);
455 free(remaddr);
456 if (!o_nflag)
457 free(remhostname);
458 }
459}
460
461/* udptest:
462 fire a couple of packets at a UDP target port, just to see if it's really
463 there. On BSD kernels, ICMP host/port-unreachable errors get delivered to
464 our socket as ECONNREFUSED write errors. On SV kernels, we lose; we'll have
465 to collect and analyze raw ICMP ourselves a la satan's probe_udp_ports
466 backend. Guess where one could swipe the appropriate code from...
467
468 Use the time delay between writes if given, otherwise use the "tcp ping"
469 trick for getting the RTT. [I got that idea from pluvius, and warped it.]
470 Return either the original fd, or clean up and return -1. */
Denis Vlasenko19507f02007-04-06 10:41:05 +0000471#if ENABLE_NC_EXTRA
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000472static int udptest(void)
473{
474 int rr;
475
476 rr = write(netfd, bigbuf_in, 1);
477 if (rr != 1)
478 bb_perror_msg("udptest first write");
479
480 if (o_wait)
Denis Vlasenko19507f02007-04-06 10:41:05 +0000481 sleep(o_wait); // can be interrupted! while (t) nanosleep(&t)?
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000482 else {
483 /* use the tcp-ping trick: try connecting to a normally refused port, which
484 causes us to block for the time that SYN gets there and RST gets back.
485 Not completely reliable, but it *does* mostly work. */
486 /* Set a temporary connect timeout, so packet filtration doesnt cause
487 us to hang forever, and hit it */
488 o_wait = 5; /* enough that we'll notice?? */
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000489 rr = xsocket(ouraddr->u.sa.sa_family, SOCK_STREAM, 0);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000490 set_nport(themaddr, htons(SLEAZE_PORT));
491 connect_w_timeout(rr);
Denis Vlasenko19507f02007-04-06 10:41:05 +0000492 /* don't need to restore themaddr's port, it's not used anymore */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000493 close(rr);
Denis Vlasenko19507f02007-04-06 10:41:05 +0000494 o_wait = 0; /* restore */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000495 }
496
497 rr = write(netfd, bigbuf_in, 1);
498 return (rr != 1); /* if rr == 1, return 0 (success) */
499}
Denis Vlasenko19507f02007-04-06 10:41:05 +0000500#else
501int udptest(void);
502#endif
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000503
504/* oprint:
505 Hexdump bytes shoveled either way to a running logfile, in the format:
506 D offset - - - - --- 16 bytes --- - - - - # .... ascii .....
507 where "which" sets the direction indicator, D:
508 0 -- sent to network, or ">"
509 1 -- rcvd and printed to stdout, or "<"
510 and "buf" and "n" are data-block and length. If the current block generates
511 a partial line, so be it; we *want* that lockstep indication of who sent
512 what when. Adapted from dgaudet's original example -- but must be ripping
513 *fast*, since we don't want to be too disk-bound... */
Denis Vlasenko19507f02007-04-06 10:41:05 +0000514#if ENABLE_NC_EXTRA
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000515static void oprint(int direction, unsigned char *p, unsigned bc)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000516{
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000517 unsigned obc; /* current "global" offset */
518 unsigned x;
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000519 unsigned char *op; /* out hexdump ptr */
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000520 unsigned char *ap; /* out asc-dump ptr */
Denis Vlasenko19507f02007-04-06 10:41:05 +0000521 unsigned char stage[100];
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000522
Denis Vlasenko19507f02007-04-06 10:41:05 +0000523 if (bc == 0)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000524 return;
525
Denis Vlasenko19507f02007-04-06 10:41:05 +0000526 obc = wrote_net; /* use the globals! */
527 if (direction == '<')
528 obc = wrote_out;
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000529 stage[0] = direction;
530 stage[59] = '#'; /* preload separator */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000531 stage[60] = ' ';
532
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000533 do { /* for chunk-o-data ... */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000534 x = 16;
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000535 if (bc < 16) {
536 /* memset(&stage[bc*3 + 11], ' ', 16*3 - bc*3); */
537 memset(&stage[11], ' ', 16*3);
538 x = bc;
539 }
Denis Vlasenkoc4f12f52008-05-12 14:35:56 +0000540 sprintf((char *)&stage[1], " %8.8x ", obc); /* xxx: still slow? */
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000541 bc -= x; /* fix current count */
542 obc += x; /* fix current offset */
543 op = &stage[11]; /* where hex starts */
544 ap = &stage[61]; /* where ascii starts */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000545
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000546 do { /* for line of dump, however long ... */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000547 *op++ = 0x20 | bb_hexdigits_upcase[*p >> 4];
548 *op++ = 0x20 | bb_hexdigits_upcase[*p & 0x0f];
549 *op++ = ' ';
550 if ((*p > 31) && (*p < 127))
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000551 *ap = *p; /* printing */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000552 else
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000553 *ap = '.'; /* nonprinting, loose def */
554 ap++;
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000555 p++;
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000556 } while (--x);
557 *ap++ = '\n'; /* finish the line */
558 xwrite(ofd, stage, ap - stage);
559 } while (bc);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000560}
Denis Vlasenko19507f02007-04-06 10:41:05 +0000561#else
Denis Vlasenko828e2a92007-07-13 12:37:31 +0000562void oprint(int direction, unsigned char *p, unsigned bc);
Denis Vlasenko19507f02007-04-06 10:41:05 +0000563#endif
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000564
565/* readwrite:
566 handle stdin/stdout/network I/O. Bwahaha!! -- the select loop from hell.
567 In this instance, return what might become our exit status. */
568static int readwrite(void)
569{
570 int rr;
571 char *zp = zp; /* gcc */ /* stdin buf ptr */
572 char *np = np; /* net-in buf ptr */
573 unsigned rzleft;
574 unsigned rnleft;
575 unsigned netretry; /* net-read retry counter */
576 unsigned wretry; /* net-write sanity counter */
577 unsigned wfirst; /* one-shot flag to skip first net read */
578
579 /* if you don't have all this FD_* macro hair in sys/types.h, you'll have to
580 either find it or do your own bit-bashing: *ding1 |= (1 << fd), etc... */
581 FD_SET(netfd, &ding1); /* global: the net is open */
582 netretry = 2;
583 wfirst = 0;
584 rzleft = rnleft = 0;
585 if (o_interval)
586 sleep(o_interval); /* pause *before* sending stuff, too */
587
588 errno = 0; /* clear from sleep, close, whatever */
589 /* and now the big ol' select shoveling loop ... */
590 while (FD_ISSET(netfd, &ding1)) { /* i.e. till the *net* closes! */
591 wretry = 8200; /* more than we'll ever hafta write */
592 if (wfirst) { /* any saved stdin buffer? */
593 wfirst = 0; /* clear flag for the duration */
594 goto shovel; /* and go handle it first */
595 }
596 ding2 = ding1; /* FD_COPY ain't portable... */
597 /* some systems, notably linux, crap into their select timers on return, so
598 we create a expendable copy and give *that* to select. */
599 if (o_wait) {
600 struct timeval tmp_timer;
601 tmp_timer.tv_sec = o_wait;
602 tmp_timer.tv_usec = 0;
Denis Vlasenko19507f02007-04-06 10:41:05 +0000603 /* highest possible fd is netfd (3) */
604 rr = select(netfd+1, &ding2, NULL, NULL, &tmp_timer);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000605 } else
Denis Vlasenko19507f02007-04-06 10:41:05 +0000606 rr = select(netfd+1, &ding2, NULL, NULL, NULL);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000607 if (rr < 0 && errno != EINTR) { /* might have gotten ^Zed, etc */
608 holler_perror("select");
609 close(netfd);
610 return 1;
611 }
612 /* if we have a timeout AND stdin is closed AND we haven't heard anything
613 from the net during that time, assume it's dead and close it too. */
614 if (rr == 0) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +0000615 if (!FD_ISSET(STDIN_FILENO, &ding1))
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000616 netretry--; /* we actually try a coupla times. */
617 if (!netretry) {
618 if (o_verbose > 1) /* normally we don't care */
619 fprintf(stderr, "net timeout\n");
620 close(netfd);
621 return 0; /* not an error! */
622 }
623 } /* select timeout */
624 /* xxx: should we check the exception fds too? The read fds seem to give
625 us the right info, and none of the examples I found bothered. */
626
627 /* Ding!! Something arrived, go check all the incoming hoppers, net first */
628 if (FD_ISSET(netfd, &ding2)) { /* net: ding! */
629 rr = read(netfd, bigbuf_net, BIGSIZ);
630 if (rr <= 0) {
Denis Vlasenko19507f02007-04-06 10:41:05 +0000631 if (rr < 0 && o_verbose > 1) {
632 /* nc 1.10 doesn't do this */
633 bb_perror_msg("net read");
634 }
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000635 FD_CLR(netfd, &ding1); /* net closed, we'll finish up... */
636 rzleft = 0; /* can't write anymore: broken pipe */
637 } else {
638 rnleft = rr;
639 np = bigbuf_net;
640 }
Denis Vlasenko19507f02007-04-06 10:41:05 +0000641Debug("got %d from the net, errno %d", rr, errno);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000642 } /* net:ding */
643
644 /* if we're in "slowly" mode there's probably still stuff in the stdin
645 buffer, so don't read unless we really need MORE INPUT! MORE INPUT! */
646 if (rzleft)
647 goto shovel;
648
649 /* okay, suck more stdin */
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +0000650 if (FD_ISSET(STDIN_FILENO, &ding2)) { /* stdin: ding! */
651 rr = read(STDIN_FILENO, bigbuf_in, BIGSIZ);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000652 /* Considered making reads here smaller for UDP mode, but 8192-byte
653 mobygrams are kinda fun and exercise the reassembler. */
654 if (rr <= 0) { /* at end, or fukt, or ... */
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +0000655 FD_CLR(STDIN_FILENO, &ding1); /* disable and close stdin */
Denis Vlasenkof6b46852009-04-25 13:16:53 +0000656 close(STDIN_FILENO);
657// Does it make sense to shutdown(net_fd, SHUT_WR)
658// to let other side know that we won't write anything anymore?
659// (and what about keeping compat if we do that?)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000660 } else {
661 rzleft = rr;
662 zp = bigbuf_in;
663 }
664 } /* stdin:ding */
665 shovel:
666 /* now that we've dingdonged all our thingdings, send off the results.
667 Geez, why does this look an awful lot like the big loop in "rsh"? ...
668 not sure if the order of this matters, but write net -> stdout first. */
669
670 /* sanity check. Works because they're both unsigned... */
671 if ((rzleft > 8200) || (rnleft > 8200)) {
672 holler_error("bogus buffers: %u, %u", rzleft, rnleft);
673 rzleft = rnleft = 0;
674 }
675 /* net write retries sometimes happen on UDP connections */
676 if (!wretry) { /* is something hung? */
677 holler_error("too many output retries");
678 return 1;
679 }
680 if (rnleft) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +0000681 rr = write(STDOUT_FILENO, np, rnleft);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000682 if (rr > 0) {
Denis Vlasenkoc4f12f52008-05-12 14:35:56 +0000683 if (o_ofile) /* log the stdout */
684 oprint('<', (unsigned char *)np, rr);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000685 np += rr; /* fix up ptrs and whatnot */
686 rnleft -= rr; /* will get sanity-checked above */
687 wrote_out += rr; /* global count */
688 }
Denis Vlasenko19507f02007-04-06 10:41:05 +0000689Debug("wrote %d to stdout, errno %d", rr, errno);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000690 } /* rnleft */
691 if (rzleft) {
692 if (o_interval) /* in "slowly" mode ?? */
693 rr = findline(zp, rzleft);
694 else
695 rr = rzleft;
696 rr = write(netfd, zp, rr); /* one line, or the whole buffer */
697 if (rr > 0) {
Denis Vlasenkoc4f12f52008-05-12 14:35:56 +0000698 if (o_ofile) /* log what got sent */
699 oprint('>', (unsigned char *)zp, rr);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000700 zp += rr;
701 rzleft -= rr;
702 wrote_net += rr; /* global count */
703 }
Denis Vlasenko19507f02007-04-06 10:41:05 +0000704Debug("wrote %d to net, errno %d", rr, errno);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000705 } /* rzleft */
706 if (o_interval) { /* cycle between slow lines, or ... */
707 sleep(o_interval);
708 errno = 0; /* clear from sleep */
709 continue; /* ...with hairy select loop... */
710 }
711 if ((rzleft) || (rnleft)) { /* shovel that shit till they ain't */
712 wretry--; /* none left, and get another load */
713 goto shovel;
714 }
715 } /* while ding1:netfd is open */
716
717 /* XXX: maybe want a more graceful shutdown() here, or screw around with
718 linger times?? I suspect that I don't need to since I'm always doing
719 blocking reads and writes and my own manual "last ditch" efforts to read
720 the net again after a timeout. I haven't seen any screwups yet, but it's
721 not like my test network is particularly busy... */
722 close(netfd);
723 return 0;
724} /* readwrite */
725
726/* main: now we pull it all together... */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +0000727int nc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denys Vlasenko2ec91ae2010-01-04 14:15:38 +0100728int nc_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000729{
Denis Vlasenko1d426652008-03-17 09:09:09 +0000730 char *str_p, *str_s;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000731 IF_NC_EXTRA(char *str_i, *str_o;)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000732 char *themdotted = themdotted; /* gcc */
733 char **proggie;
734 int x;
735 unsigned o_lport = 0;
736
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000737 INIT_G();
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000738
739 /* catch a signal or two for cleanup */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000740 bb_signals(0
741 + (1 << SIGINT)
742 + (1 << SIGQUIT)
743 + (1 << SIGTERM)
744 , catch);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000745 /* and suppress others... */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000746 bb_signals(0
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000747#ifdef SIGURG
Denis Vlasenko25591c32008-02-16 22:58:56 +0000748 + (1 << SIGURG)
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000749#endif
Denis Vlasenko25591c32008-02-16 22:58:56 +0000750 + (1 << SIGPIPE) /* important! */
751 , SIG_IGN);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000752
753 proggie = argv;
754 while (*++proggie) {
755 if (strcmp(*proggie, "-e") == 0) {
756 *proggie = NULL;
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000757 proggie++;
758 goto e_found;
759 }
760 }
761 proggie = NULL;
762 e_found:
Denis Vlasenko4b924f32007-05-30 00:29:55 +0000763
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000764 // -g -G -t -r deleted, unimplemented -a deleted too
Denis Vlasenko1d426652008-03-17 09:09:09 +0000765 opt_complementary = "?2:vv:w+"; /* max 2 params; -v is a counter; -w N */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000766 getopt32(argv, "hnp:s:uvw:" IF_NC_SERVER("l")
767 IF_NC_EXTRA("i:o:z"),
Denis Vlasenko1d426652008-03-17 09:09:09 +0000768 &str_p, &str_s, &o_wait
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000769 IF_NC_EXTRA(, &str_i, &str_o, &o_verbose));
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000770 argv += optind;
771#if ENABLE_NC_EXTRA
772 if (option_mask32 & OPT_i) /* line-interval time */
773 o_interval = xatou_range(str_i, 1, 0xffff);
774#endif
775 //if (option_mask32 & OPT_l) /* listen mode */
776 //if (option_mask32 & OPT_n) /* numeric-only, no DNS lookups */
777 //if (option_mask32 & OPT_o) /* hexdump log */
778 if (option_mask32 & OPT_p) { /* local source port */
779 o_lport = bb_lookup_port(str_p, o_udpmode ? "udp" : "tcp", 0);
780 if (!o_lport)
781 bb_error_msg_and_die("bad local port '%s'", str_p);
782 }
783 //if (option_mask32 & OPT_r) /* randomize various things */
784 //if (option_mask32 & OPT_u) /* use UDP */
785 //if (option_mask32 & OPT_v) /* verbose */
Denis Vlasenko1d426652008-03-17 09:09:09 +0000786 //if (option_mask32 & OPT_w) /* wait time */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000787 //if (option_mask32 & OPT_z) /* little or no data xfer */
788
Denis Vlasenko19507f02007-04-06 10:41:05 +0000789 /* We manage our fd's so that they are never 0,1,2 */
790 /*bb_sanitize_stdio(); - not needed */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000791
Denis Vlasenko5c51a7c2007-06-05 20:08:11 +0000792 if (argv[0]) {
793 themaddr = xhost2sockaddr(argv[0],
794 argv[1]
795 ? bb_lookup_port(argv[1], o_udpmode ? "udp" : "tcp", 0)
796 : 0);
797 }
798
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000799 /* create & bind network socket */
Denis Vlasenko19507f02007-04-06 10:41:05 +0000800 x = (o_udpmode ? SOCK_DGRAM : SOCK_STREAM);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000801 if (option_mask32 & OPT_s) { /* local address */
Denis Vlasenko19507f02007-04-06 10:41:05 +0000802 /* if o_lport is still 0, then we will use random port */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000803 ouraddr = xhost2sockaddr(str_s, o_lport);
Denis Vlasenko4cf1d082008-03-12 23:13:50 +0000804#ifdef BLOAT
805 /* prevent spurious "UDP listen needs !0 port" */
806 o_lport = get_nport(ouraddr);
807 o_lport = ntohs(o_lport);
808#endif
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000809 x = xsocket(ouraddr->u.sa.sa_family, x, 0);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000810 } else {
Denis Vlasenko5c51a7c2007-06-05 20:08:11 +0000811 /* We try IPv6, then IPv4, unless addr family is
812 * implicitly set by way of remote addr/port spec */
813 x = xsocket_type(&ouraddr,
Denis Vlasenko4e6d5112008-03-12 22:14:34 +0000814 (themaddr ? themaddr->u.sa.sa_family : AF_UNSPEC),
Denis Vlasenko5c51a7c2007-06-05 20:08:11 +0000815 x);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000816 if (o_lport)
817 set_nport(ouraddr, htons(o_lport));
818 }
Denis Vlasenko19507f02007-04-06 10:41:05 +0000819 xmove_fd(x, netfd);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000820 setsockopt_reuseaddr(netfd);
821 if (o_udpmode)
822 socket_want_pktinfo(netfd);
Denis Vlasenkof6b46852009-04-25 13:16:53 +0000823 if (!ENABLE_FEATURE_UNIX_LOCAL
824 || o_listen
825 || ouraddr->u.sa.sa_family != AF_UNIX
826 ) {
827 xbind(netfd, &ouraddr->u.sa, ouraddr->len);
828 }
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000829#if 0
830 setsockopt(netfd, SOL_SOCKET, SO_RCVBUF, &o_rcvbuf, sizeof o_rcvbuf);
831 setsockopt(netfd, SOL_SOCKET, SO_SNDBUF, &o_sndbuf, sizeof o_sndbuf);
832#endif
833
Denis Vlasenko4cf1d082008-03-12 23:13:50 +0000834#ifdef BLOAT
Denis Vlasenko19507f02007-04-06 10:41:05 +0000835 if (OPT_l && (option_mask32 & (OPT_u|OPT_l)) == (OPT_u|OPT_l)) {
836 /* apparently UDP can listen ON "port 0",
837 but that's not useful */
838 if (!o_lport)
839 bb_error_msg_and_die("UDP listen needs nonzero -p port");
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000840 }
Denis Vlasenko4cf1d082008-03-12 23:13:50 +0000841#endif
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000842
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +0000843 FD_SET(STDIN_FILENO, &ding1); /* stdin *is* initially open */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000844 if (proggie) {
845 close(0); /* won't need stdin */
846 option_mask32 &= ~OPT_o; /* -o with -e is meaningless! */
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000847 }
Denis Vlasenko19507f02007-04-06 10:41:05 +0000848#if ENABLE_NC_EXTRA
849 if (o_ofile)
850 xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), ofd);
851#endif
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000852
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000853 if (o_listen) {
854 dolisten();
855 /* dolisten does its own connect reporting */
856 if (proggie) /* -e given? */
857 doexec(proggie);
858 x = readwrite(); /* it even works with UDP! */
859 } else {
860 /* Outbound connects. Now we're more picky about args... */
861 if (!themaddr)
Denys Vlasenkob103fb12010-09-07 18:41:56 +0200862 bb_show_usage();
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000863
864 remend = *themaddr;
865 if (o_verbose)
Denis Vlasenko7cff01e2008-02-02 16:23:43 +0000866 themdotted = xmalloc_sockaddr2dotted(&themaddr->u.sa);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000867
868 x = connect_w_timeout(netfd);
869 if (o_zero && x == 0 && o_udpmode) /* if UDP scanning... */
870 x = udptest();
871 if (x == 0) { /* Yow, are we OPEN YET?! */
872 if (o_verbose)
Denis Vlasenko19507f02007-04-06 10:41:05 +0000873 fprintf(stderr, "%s (%s) open\n", argv[0], themdotted);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000874 if (proggie) /* exec is valid for outbound, too */
875 doexec(proggie);
876 if (!o_zero)
877 x = readwrite();
878 } else { /* connect or udptest wasn't successful */
879 x = 1; /* exit status */
880 /* if we're scanning at a "one -v" verbosity level, don't print refusals.
881 Give it another -v if you want to see everything. */
882 if (o_verbose > 1 || (o_verbose && errno != ECONNREFUSED))
Denis Vlasenko19507f02007-04-06 10:41:05 +0000883 bb_perror_msg("%s (%s)", argv[0], themdotted);
Denis Vlasenko29fe7262007-04-05 20:26:28 +0000884 }
885 }
886 if (o_verbose > 1) /* normally we don't care */
887 fprintf(stderr, SENT_N_RECV_M, wrote_net, wrote_out);
888 return x;
889}