source: branches/stable/mindi-busybox/networking/nc_bloaty.c @ 1770

Last change on this file since 1770 was 1770, checked in by Bruno Cornec, 13 years ago
  • Better output for mindi-busybox revision
  • Remove dummy file created on NFS - report from Arnaud Tiger <arnaud.tiger_at_hp.com>
  • strace useful for debug
  • fix new versions for pb (2.0.0 for mindi and 1.7.2 for mindi-busybox)
  • fix build process for mindi-busybox + options used in that version (dd for label-partitions-as-necessary)
  • fix typo in label-partitions-as-necessary which doesn't seem to work
  • Update to busybox 1.7.2
  • perl is now required at restore time to support uuid swap partitions (and will be used for many other thigs

in the future for sure)

  • next mindi version will be 2.0.0 due to all the changes made in it (udev may break working distros)
  • small optimization in mindi on keyboard handling (one single find instead of multiple)
  • better interaction for USB device when launching mindi manually
  • attempt to automatically guess block disk size for ramdisk
  • fix typos in bkphw
  • Fix the remaining problem with UUID support for swap partitions
  • Updates mondoarchive man page for USB support
  • Adds preliminary Hardware support to mindi (Proliant SSSTK)
  • Tries to add udev support also for rhel4
  • Fix UUID support which was still broken.
  • Be conservative in test for the start-nfs script
  • Update config file for mindi-busybox for 1.7.2 migration
  • Try to run around a busybox bug (1.2.2 pb on inexistant links)
  • Add build content for mindi-busybox in pb
  • Remove distributions content for mindi-busybox
  • Fix a warning on inexistant raidtab
  • Solve problem on tmpfs in restore init (Problem of inexistant symlink and busybox)
  • Create MONDO_CACHE and use it everywhere + creation at start
  • Really never try to eject a USB device
  • Fix a issue with &> usage (replaced with 1> and 2>)
  • Adds magic file to depllist in order to have file working + ldd which helps for debugging issues
  • tty modes correct to avoid sh error messages
  • Use ext3 normally and not ext2 instead
  • USB device should be corrected after reading (take 1st part)
  • Adds a mount_USB_here function derived from mount_CDROM_here
  • usb detection place before /dev detection in device name at restore time
  • Fix when restoring from USB: media is asked in interactive mode
  • Adds USB support for mondorestore
  • mount_cdrom => mount_media
  • elilo.efi is now searched throughout /boot/efi and not in a fixed place as there is no standard
  • untar-and-softlink => untar (+ interface change)
  • suppress useless softlinks creation/removal in boot process
  • avoids udevd messages on groups
  • Increase # of disks to 99 as in mindi at restore time (should be a conf file parameter)
  • skip existing big file creation
  • seems to work correctly for USB mindi boot
  • Adds group and tty link to udev conf
  • Always load usb-torage (even 2.6) to initiate USB bus discovery
  • Better printing of messages
  • Attempt to fix a bug in supporting OpenSusE 10.3 kernel for initramfs (mindi may now use multiple regex for kernel initrd detection)
  • Links were not correctly done as non relative for modules in mindi
  • exclusion of modules denied now works
  • Also create modules in their ordinary place, so that classical modprobe works + copy modules.dep
  • Fix bugs for DENY_MODS handling
  • Add device /dev/console for udev
  • ide-generic should now really be excluded
  • Fix a bug in major number for tty
  • If udev then adds modprobe/insmod to rootfs
  • tty0 is also cretaed with udev
  • ide-generic put rather in DENY_MODS
  • udevd remove from deplist s handled in mindi directly
  • better default for mindi when using --usb
  • Handles dynamically linked busybox (in case we want to use it soon ;-)
  • Adds fixed devices to create for udev
  • ide-generic should not be part of the initrd when using libata v2
  • support a dynamically linked udev (case on Ubuntu 7.10 and Mandriva 2008.0 so should be quite generic) This will give incitation to move to dyn. linked binaries in the initrd which will help for other tasks (ia6 4)
  • Improvement in udev support (do not use cl options not available in busybox)
  • Udev in mindi
    • auto creation of the right links at boot time with udev-links.conf(from Mandriva 2008.0)
    • rework startup of udev as current makes kernel crash (from Mandriva 2008.0)
    • add support for 64 bits udev
  • Try to render MyInsmod? silent at boot time
  • Adds udev support (mandatory for newest distributions to avoid remapping of devices in a different way as on the original system)
  • We also need vaft format support for USB boot
  • Adds libusual support (Ubuntu 7.10 needs it for USB)
  • Improve Ubuntu/Debian? keyboard detection and support
  • pbinit adapted to new pb (0.8.10). Filtering of docs done in it
  • Suppress some mondo warnings and errors on USB again
  • Tries to fix lack of files in deb mindi package
  • Verify should now work for USB devices
  • More log/mesages improvement for USB support
  • - Supress g_erase_tmpdir_and_scratchdir
  • Improve some log messages for USB support
  • Try to improve install in mindi to avoid issues with isolinux.cfg not installed vene if in the pkg :-(
  • Improve mindi-busybox build
  • In conformity with pb 0.8.9
  • Add support for Ubuntu 7.10 in build process
  • Add USB Key button to Menu UI (CD streamer removed)
  • Attempt to fix error messages on tmp/scratch files at the end by removing those dir at the latest possible.
  • Fix a bug linked to the size of the -E param which could be used (Arnaud Tiger/René? Ribaud).
  • Integrate ~/.pbrc content into mondorescue.pb (required project-builder >= 0.8.7)
  • Put mondorescue in conformity with new pb filtering rules
  • Add USB support at restore time (no test done yet). New start-usb script PB varibale added where useful
  • Unmounting USB device before removal of temporary scratchdir
  • Stil refining USB copy back to mondo (one command was not executed)
  • No need to have the image subdor in the csratchdir when USB.
  • umount the USB partition before attempting to use it
  • Remove useless copy from mindi to mondo at end of USB handling

(risky merge, we are raising the limits of 2 diverging branches. The status of stable is not completely sure as such. Will need lots of tests, but it's not yet done :-()
(merge -r1692:1769 $SVN_M/branches/2.2.5)

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