File: netselect.c

package info (click to toggle)
netselect 0.3.ds1-28
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 336 kB
  • ctags: 243
  • sloc: ansic: 1,082; sh: 625; makefile: 43
file content (1143 lines) | stat: -rw-r--r-- 28,754 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
/*
 * Netselect:
 *      Copyright (c) 1998-2001 by Avery Pennarun <apenwarr@gmail.com>
 *
 *
 * Traceroute:
 * Copyright (c) 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 * 
 * This code is derived from software contributed to Berkeley by
 * Van Jacobson.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * I expect this to only compile on Linux.  If it also works on your system,
 * hey, great!  Let me know. -- apenwarr
 */

#ifdef __EMX__
# include <io.h>
# include <fcntl.h>
# include <sys/types.h>
# include <sys/select.h>
# include <machine/endian.h>
#else
# include <endian.h>
#endif

#include <sys/param.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/udp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>

#define MAXPACKET	IP_MAXPACKET	/* max ip packet size */
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN	64
#endif

/*
 * format of a (udp) probe packet.
 */
typedef struct
{
    struct ip ip;
    struct udphdr udp;
    u_char seq;			/* sequence number of this packet */
    u_char ttl;			/* ttl packet left with */
    struct timeval tv;		/* time packet left */
} OPacket;

/*
 * format of a (icmp) probe packet.
 */
typedef struct
{
    struct ip ip;
    struct icmp icmp;
    u_char seq;			/* sequence number of this packet */
    u_char ttl;			/* ttl packet left with */
    struct timeval tv;		/* time packet left */
}__attribute__((packed)) IPacket;



/* 
 * currently-known information about a host
 */
typedef struct
{
    char *hostname;		/* hostname as provided on command line 
                                 * or host IP address if we get multiple IPs
                                 * for a name */
    char *shortname;		/* hostname with any URL-type stuff removed */
    char *dnsname;		/* DNS name of the host, matches hostname
                                 * unless a host resolves to multiple IP
                                 * addresses */
    struct sockaddr_in addr;	/* remote address */

    int invalid;		/* !=0 if we discard this host */
    int done;			/* !=0 if host testing is done */

    unsigned num_out, num_in;	/* packets sent/received successfully */
    unsigned total_lag;		/* combined lag on ALL received messages */
    int hops_less_than, hops_more_than; /* for guessing number of hops */
    
    int retries;		/* transaction in progress */
    struct timeval send_time;	/* time of transmission */
    int code;			/* ICMP error code returned */
    u_short seq;		/* sequence number sent with packet */
} HostData;


/* prototypes for functions in this file */
static HostData *add_host(HostData *host, int *numhosts,
			  char *hostname, struct sockaddr_in *addr,
                          char *dnsname, int max_ttl);
static char *un_url(char *orig);
static char *fix_url(char *orig, char *hostname);
static HostData *name_resolver(int *numhosts, int numnames, char **names,
			       int max_ttl);

static void send_probe(int seq, int ttl, OPacket *op,
		       HostData *host);
static void send_icmp_probe(int seq, int ttl, IPacket *op,
		       HostData *host);
static time_t deltaT(struct timeval *t1p, struct timeval *t2p);
static HostData *wait_for_reply(HostData *hosts, int numhosts,
				       int sock, int msec_timeout);
static HostData *packet_ok(HostData *hosts, int numhosts,
				  u_char *buf, int cc,
				  struct sockaddr_in *from);
static int choose_ttl(HostData *host);
static void usage();
static int results(HostData *hosts, int numhosts, int num_score, int use_dns);
static int host_score(HostData *host);

#define INPACKET_SIZE    512


/* global variables */
static int rcvsock;		/* receive (icmp) socket file descriptor */
static int sndsock;		/* send (udp) socket file descriptor */

static int verbose = 0;
static u_short ident;
static u_short port = 32768 + 666; /* start udp dest port for probe packets */

static int validhosts;

int main(int argc, char **argv)
{
    extern char *optarg;
    extern int optind;
    int hostcount, startcount, endcount = 0, sent_one, lag, min_lag = 100;
    int ch, seq, ttl, max_ttl = 30, num_score = 1;
    int use_icmp, use_dns, found = 0;
    unsigned int min_tries = 10;
    struct timeval now;
    struct timezone tz;
    OPacket udppacket;          /* last output (udp) packet */
    IPacket icmppacket;          /* last output (udp) packet */
    
    HostData *host, *hosts;
    int numhosts, delay, must_continue, count;
    int socket_errno = 0;

    /* we might have cap_net_raw on linux, instead print a tip if and when
       sendto fails
    if (geteuid () != 0)
        fprintf (stderr, "%s: root privileges required\n", argv[0]);
    */

    if ((rcvsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0
     || (sndsock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW )) < 0)
    {
	/* Capture errno so that command-line options can be parsed.
	   We delay reporting an error until this has happened. */
	socket_errno = errno;
    }

    /* drop root privileges as soon as possible! */
    setuid(getuid());

    seq = 0;

#ifdef __EMX__
    _response(&argc,&argv);
#endif
    while ((ch = getopt(argc, argv, "s:t:m:IDv?")) != EOF)
    {
	switch (ch)
	{
	case 's':
	    num_score = atoi(optarg);
	    break;
	    
	case 't':
	    min_tries = atoi(optarg);
	    if (min_tries < 1)
	    {
		fprintf(stderr, "netselect: number of tries must be >1.\n");
		return 1;
	    }
	    break;
	    
	case 'm':
	    max_ttl = atoi(optarg);
	    if (max_ttl <= 1)
	    {
		fprintf(stderr, "netselect: max ttl must be >1.\n");
		return 1;
	    }
	    break;

	case 'I':
            use_icmp = 1;
	    break;

	case 'D':
            use_dns = 1;
	    break;

	case 'v':
	    verbose++;
	    break;
	    
	case '?':
	default:
	    usage();
	    return 1;
	}
    }

    argc -= optind;
    argv += optind;

    if (argc < 1)
    {
	usage();
	return 1;
    }

    /* Was there an error acquiring a socket? */
    if (socket_errno)
    {
	errno = socket_errno;
	perror("netselect: socket");
	if (errno == EPERM) {
		fprintf(stderr, "You should be root to run netselect.\n");
		return 6;
	}
	return 5;
    }

    if ( use_icmp )  
    {
        memset(&icmppacket, 0, sizeof(IPacket));
        icmppacket.ip.ip_tos = 0;
        icmppacket.ip.ip_v = IPVERSION;
        icmppacket.ip.ip_id = 0;
    } 
    else 
    {
        memset(&udppacket, 0, sizeof(OPacket));
        udppacket.ip.ip_tos = 0;
        udppacket.ip.ip_v = IPVERSION;
        udppacket.ip.ip_id = 0;
    }

    ident = (getpid() & 0xffff) | 0x8000;
    
    validhosts = numhosts = 0;
    
    hosts = name_resolver(&numhosts, argc, argv, max_ttl);
    validhosts = numhosts;
    
    if (verbose >= 1)
	fprintf(stderr, "Running netselect to choose %d out of %d address%s.\n",
		num_score, numhosts, numhosts==1 ? "" : "es");
    
    /* keep going until most of the hosts have been finished */
    must_continue = numhosts;
    while (must_continue && must_continue >= numhosts/2)
    {
	gettimeofday(&now, &tz);
	
	must_continue = 0;

	/* send out a packet; if there are no interesting packets to send
	 * out, make sure we only loop once through the list of hosts.
	 * Also make sure that next time we start the loop, we pick up
	 * at the host where we left off, rather than starting over; this
	 * increases fairness.
	 */
	startcount = hostcount = endcount;
	sent_one = 0;
	do
	{
	    hostcount = (hostcount + 1) % numhosts;
	    host = &hosts[hostcount];
	    
	    if (!host->invalid && !host->done
		&& (host->num_out < min_tries
		    || deltaT(&host->send_time, &now) < 5000))
	    {
		must_continue++;
	    }
	    else if (!host->done)
	    {
		host->done = 1;
		validhosts--;
	    }

	    if (host->invalid
	      || (host->retries && deltaT(&host->send_time, &now) < 3000))
		continue;
	    
	    if (host->retries < 3  &&  host->num_out < min_tries)
	    {
		if (!sent_one)
		{
		    if (verbose >= 3 && host->retries >= 1)
			fprintf(stderr, "%-55s - TIMEOUT\n", host->shortname);
		    
		    host->send_time = now;
		    ttl = choose_ttl(host);
		    
		    host->seq = ++seq;
		    seq %= 256;
		    host->retries++;
		    
		    host->num_out++;
                    if ( use_icmp ) 
                        send_icmp_probe(host->seq, ttl, &icmppacket, host);
                    else
                        send_probe(host->seq, ttl, &udppacket, host);
		    endcount = hostcount;
		    sent_one = 1;
		}
	    }
	    else if (host->hops_less_than - host->hops_more_than > 2)
	    {
		/* sometimes we get a TIMEOUT instead of an error if
		 * the ttl is too small; just move to the next one then. */
		host->hops_more_than = choose_ttl(host);
		host->retries = 0;
	    }
	    else
	    {
		if (!host->done)
		    validhosts--;
		host->done = 1;
	    }
	} while (hostcount != startcount);
	
	delay = min_lag/2; /* transmit time must be <= min_lag / 2 */
	if ((host = wait_for_reply(hosts, numhosts, rcvsock, delay)) != NULL)
	{
	    gettimeofday(&now, &tz);
	    delay = 0;

	    if (verbose >= 3)
		fprintf(stderr, "%-35s  %5u ms  %3d hops - ", host->shortname,
		       (unsigned)deltaT(&host->send_time, &now),
		       choose_ttl(host));
	    
	    switch (host->code - 1)
	    {
	    case -2:
		if (verbose >= 3)
		    fprintf(stderr, "HIGHER");
		else if (verbose >= 1)
		    fprintf(stderr, ".");
		if (choose_ttl(host) >= host->hops_less_than)
		    host->hops_less_than = choose_ttl(host) + 1;
		host->hops_more_than = choose_ttl(host);
		host->retries = 0;
		host->num_out--;
		break;
		
	    case ICMP_UNREACH_PORT:
		if (verbose >= 3)
		    fprintf(stderr, "OK");
		else if (verbose >= 1)
		    fprintf(stderr, ".");
		host->hops_less_than = choose_ttl(host);
		host->retries = 0;
		host->num_in++;
		lag = deltaT(&host->send_time, &now);
		if (lag > 10 && lag < min_lag)
		{
		    min_lag = lag;
		    if (verbose >= 3)
			fprintf(stderr, "\nmin_lag is now %d", min_lag);
		}
		host->total_lag += lag;
		break;

	    case ICMP_UNREACH_NET:
	    case ICMP_UNREACH_HOST:
	    case ICMP_UNREACH_PROTOCOL:
	    case ICMP_UNREACH_NEEDFRAG:
	    case ICMP_UNREACH_SRCFAIL:
	    case ICMP_UNREACH_FILTER_PROHIB:
	    case ICMP_UNREACH_NET_PROHIB:	/* misuse */
	    case ICMP_UNREACH_HOST_PROHIB:
	    case ICMP_UNREACH_NET_UNKNOWN:
	    case ICMP_UNREACH_HOST_UNKNOWN:
	    case ICMP_UNREACH_ISOLATED:
	    case ICMP_UNREACH_TOSNET:
	    case ICMP_UNREACH_TOSHOST:
		if (verbose >= 3)
		    fprintf(stderr, "unreachable! (blocking probes?)\n");
		if (!host->invalid)
		    validhosts--;
		host->invalid = 1;
		break;
	    }

	    if (verbose >= 3)
		fprintf(stderr, "\n");
	}
	    
    }
    
    if (verbose >= 1)
	fprintf(stderr, "\n");
    
    found = results(hosts, numhosts, num_score, use_dns);
    
    if (hosts)
    {
	for (count = 0; count < numhosts; count++)
	{
	    free(hosts[count].hostname);
	    free(hosts[count].shortname);
	}
	free(hosts);
    }
    
    if (found == 0) 
        return 1;
    return 0;
}


/* 
 * when the newly-created objects are freed, we try to free(hostname)...
 * so make sure it's already dynamically allocated when you call this
 * function!
 */
static HostData *add_host(HostData *hosts, int *numhosts,
			  char *hostname, struct sockaddr_in *addr,
			  char *dnsname, int max_ttl)
{
    HostData *host;
    
    if (addr)
    {
      int hcount;
      for (hcount = 0, host = hosts; hcount < *numhosts; hcount++, host++)
	if (host->addr.sin_addr.s_addr == addr->sin_addr.s_addr)
	{
	  if (verbose >= 1)
	    fprintf(stderr, "\nDuplicate address %s (%s, %s); keeping only under first name.\n",
		    inet_ntoa(addr->sin_addr), host->hostname, hostname);
	  return hosts;
	}
    }
    
    (*numhosts)++;
    
    if (!hosts)
	hosts = (HostData *)malloc(sizeof(HostData) * *numhosts);
    else
	hosts = (HostData *)realloc(hosts, sizeof(HostData) * *numhosts);
    
    host = &hosts[*numhosts - 1];
    
    memset(host, 0, sizeof(HostData));
    host->hostname = hostname;
    host->dnsname = dnsname;
    host->shortname = un_url(hostname);
    if (addr)
	memcpy(&host->addr, addr, sizeof(*addr));
    else
	host->invalid = 1;
    host->hops_less_than = max_ttl;
    
    return hosts;
}


static char *un_url(char *orig)
{
    char *sptr, *eptr, *newbuf;
    
    if ((sptr = strstr(orig, "://")) != NULL)
    {
	/* URL formatted, like: http://hostname:port/dir/file */
	sptr += 3; /* skip :// */
	eptr = strchr(sptr, ':');
	if (!eptr) eptr = strchr(sptr, '/');
	if (!eptr) eptr = strchr(sptr, 0);
	
	newbuf = (char *)malloc(eptr-sptr+1);
	strncpy(newbuf, sptr, eptr-sptr);
	newbuf[eptr-sptr] = 0;
	return newbuf;
    }
    else if ((sptr = strchr(orig, ':')) != NULL)
    {
	/* FTP formatted, like: ftp.debian.org:/debian/foo */
	newbuf = (char *)malloc(sptr-orig+1);
	strncpy(newbuf, orig, sptr-orig);
	newbuf[sptr-orig] = 0;
	return newbuf;
    }
    else /* just plain */
	return strdup(orig);
}


static char *fix_url(char *orig, char *hostname)
{
    char *sptr, *eptr, *newbuf;
    
    if ((sptr = strstr(orig, "://")) != NULL)
    {
	/* URL formatted, like: http://hostname:port/dir/file */
	sptr += 3; /* skip :// */
	eptr = strchr(sptr, ':');
	if (!eptr) eptr = strchr(sptr, '/');
	if (!eptr) eptr = strchr(sptr, 0);
	
	newbuf = (char *)malloc(strlen(orig) + strlen(hostname) + 1);
	strncpy(newbuf, orig, sptr-orig);
	strcpy(newbuf+(sptr-orig), hostname);
	strcat(newbuf, eptr);
	return newbuf;
    }
    else if ((sptr = strchr(orig, ':')) != NULL)
    {
	/* FTP formatted, like: ftp.debian.org:/debian/foo */
	newbuf = (char *)malloc(strlen(orig) + strlen(hostname) + 1);
	strcpy(newbuf, hostname);
	strcat(newbuf, sptr);
	return newbuf;
    }
    else /* just plain */
	return strdup(hostname);
}


/*
 * Resolve all hostnames to IP addresses.  returns the number of hosts that
 * do not have name resolution errors.
 */
static HostData *name_resolver(int *numhosts, int numnames, char **names,
			       int max_ttl)
{
    struct {
	char *hostname;
	int broken, multi;
	struct sockaddr_in addr;
    } result;
    
    HostData *hosts = NULL;
    int closed = 0, active = 0, count = 0, max_active = 24;
    int pipes[2];
    time_t start = time(NULL);
    fd_set rfd, wfd, efd;
    struct timeval tv;
    struct hostent *hp;
    pid_t pid;
    
    if (pipe(pipes))
    {
	perror("netselect pipe");
	validhosts = 0;
    }
    
#ifdef __EMX__
    /* OS/2 uses ASCII mode by default for pipes... */
    setmode(pipes[0],O_BINARY);
    setmode(pipes[1],O_BINARY);
#endif
    
    while (time(NULL) < start + 20)
    {
	if (verbose >= 1)
	{
	    fprintf(stderr, "       \rnetselect: %d (%d active) "
		            "nameserver request(s)...",
		    numnames - count + active, active);
	}

	/* launch new name lookups if we aren't already doing too many */
	while (active < max_active && count < numnames)
	{
	    pid = fork();
	    
	    if (pid == 0) /* child process */
	    {
		alarm(20);
		
		result.hostname = names[count];
		result.multi = result.broken = 0;
		
		/* child task -- actually do name lookup */
		result.addr.sin_family = AF_INET;
		result.addr.sin_addr.s_addr = inet_addr(names[count]);
		
		if (result.addr.sin_addr.s_addr != INADDR_NONE)
		{
		    write(pipes[1], &result, sizeof(result));
		}
		else
		{
		    /* must actually do the name lookup */
		    char *simplename = un_url(result.hostname);
		    hp = gethostbyname(simplename);
		    free(simplename);
		    
		    if (hp)
		    {
			if (hp->h_addrtype != AF_INET 
			    || hp->h_length != sizeof(struct in_addr))
			{
			    result.broken = 1;
			    write(pipes[1], &result, sizeof(result));
			}
			else
			{
			    char **ptr = hp->h_addr_list;
			    
			    result.broken = 0;
			    if (ptr[1])
				result.multi = 1;
			    result.addr.sin_family = AF_INET;
			    
			    while (*ptr)
			    {
				memcpy(&result.addr.sin_addr,
				       *ptr, hp->h_length);
				write(pipes[1], &result, sizeof(result));
				ptr++;
			    }
			}
		    }
		    else
		    {
			result.broken = 1;
			write(pipes[1], &result, sizeof(result));
		    }
		}
		
		_exit(result.broken ? 1 : 0);
	    }
	    else if (pid < 0)
	    {
		/* trouble forking */
		max_active = active-1;
		if (max_active < 1)
		    max_active = 1;
		break;
	    }
	    else
	    {
		/* successful launch */
		active++;
		count++;
		start = time(NULL);
	    }
	} /* end of launcher section */
	
	/* the parent closes the "write" side of the pipe as soon as it
	 * doesn't need any more children; then we know all the children
	 * are dead if selecting on the "read" pipe returns an error.
	 */
	if (!closed && !active)
	{
	    close(pipes[1]);
	    closed = 1;
	}
	
	/* read results from our subtasks */
	tv.tv_sec = active ? 1 : 0;
	tv.tv_usec = 0;
	
	FD_ZERO(&rfd);
	FD_ZERO(&wfd);
	FD_ZERO(&efd);
	FD_SET(pipes[0], &rfd);
	
	if (select(pipes[0] + 1, &rfd, &wfd, &efd, &tv) > 0)
	{
	    if (read(pipes[0], &result, sizeof(result)) != sizeof(result))
	    {
		if (closed && errno == ECHILD)
		    break; /* done resolving */
		else
		    perror("netselect readpipe");
	    }
	    else
	    {
		/* got some kind of result back! */
                char *dnsname = strdup(result.hostname);
		if (result.broken)
		{
		    /* name lookup failed */
		    char *simplename = un_url(result.hostname);
		    
		    hosts = add_host(hosts, numhosts, strdup(result.hostname),
				     NULL, dnsname, max_ttl);
		    if (verbose >= 1)
			fprintf(stderr, "\r%60s\r", "");
		    fprintf(stderr, "netselect: unknown host %s\n", simplename);
		    validhosts--;
		    
		    free(simplename);
		}
		else
		{
		    /* name lookup successful */
		    char *newhostname;
		    
		    if (result.multi)
			newhostname = fix_url(result.hostname,
					      inet_ntoa(result.addr.sin_addr));
		    else
			newhostname = strdup(result.hostname);
		    
		    hosts = add_host(hosts, numhosts, newhostname,
				     &result.addr, dnsname, max_ttl);
		}
	    }
	}
	
	/* reap dead tasks */
	while (waitpid(-1, NULL, WNOHANG) > 0)
	    active--;
    }
    
    if (verbose >= 1)
    {
	fprintf(stderr, 
		"\r                            "
		"                            \r");
    }
    
    /* reap any remaining tasks */
    while (waitpid(-1, NULL, WNOHANG) > 0)
	active--;
    
    close(pipes[0]);
    close(pipes[1]);
    
    return hosts;
}


static void send_probe(int seq, int ttl, OPacket *op, HostData *host)
{
    struct ip *ip = &op->ip;
    struct udphdr *up = &op->udp;
    struct timezone tz;
    int i;

    op->ip.ip_dst = host->addr.sin_addr;
    op->seq = seq;
    op->ttl = ttl;
    gettimeofday(&op->tv, &tz);

    ip->ip_off = 0;
    ip->ip_hl = sizeof(*ip) >> 2;
    ip->ip_p = IPPROTO_UDP;
    ip->ip_len = 0; /* kernel fills this in */
    ip->ip_ttl = ttl;
    ip->ip_v = IPVERSION;
    ip->ip_id = htons(ident + seq);

    up->uh_sport = htons(ident);
    up->uh_dport = htons(port + seq);
    up->uh_ulen = htons((u_short)(sizeof(OPacket) - sizeof(struct ip)));
    up->uh_sum = 0;
    
    if (verbose >= 4)
    	fprintf(stderr, "%-35s(UDP)>>\n", host->shortname);

    i = sendto(sndsock, op, sizeof(OPacket), 0,
	       (struct sockaddr *)&host->addr, sizeof(host->addr));
    if (i < 0 || i != sizeof(OPacket))
    {
	if (i < 0)
	{
	    switch (errno)
	    {
	    case ENETDOWN:
	    case ENETUNREACH:
	    case EHOSTDOWN:
	    case EHOSTUNREACH:
		if (verbose >= 3)
		    fprintf(stderr, "unreachable or down!\n");
		if (!host->invalid)
		    validhosts--;
		host->invalid = 1;
		break;
		
	    default:
		perror("sendto");
	    }
	}
	fflush(stdout);
    }
}

uint16_t
checksum (uint16_t *header, size_t len)
{
    uint32_t sum = 0;
    int i;

    for (i = 0; i < len / sizeof (uint16_t); i++)
        sum += ntohs (header[i]);

    return htons (~((sum >> 16) + (sum & 0xffff)));
}

static void send_icmp_probe(int seq, int ttl, IPacket *op, HostData *host)
{
    struct ip *ip = &op->ip;
    struct icmp *icmp = &op->icmp;
    struct timezone tz;
    int i;

    op->ip.ip_dst = host->addr.sin_addr;
    op->seq = seq;
    op->ttl = ttl;
    gettimeofday(&op->tv, &tz);

    ip->ip_off = 0;
    ip->ip_hl = sizeof(*ip) >> 2;
    ip->ip_p = IPPROTO_ICMP;
    ip->ip_len = 0; /* kernel fills this in */
    ip->ip_ttl = ttl;
    ip->ip_v = IPVERSION;
    ip->ip_id = htons(ident + seq);

    icmp->icmp_type= ICMP_ECHO;
    icmp->icmp_code = 0;
    icmp->icmp_cksum = 0;
    icmp->icmp_id = htons (ident);
    icmp->icmp_seq = htons (seq); 
    icmp->icmp_cksum = checksum((void *)icmp, sizeof(IPacket) - sizeof(struct ip)); 

    if (verbose >= 4)
    	fprintf(stderr, "%-35s(ICMP)>>\n", host->shortname);
    if (verbose >= 5)
        fprintf(stderr, "ICMP sequence: %i, identifier: %i\n", icmp->icmp_seq, icmp->icmp_id);

    i = sendto(sndsock, op, sizeof(IPacket), 0,
	       (struct sockaddr *)&host->addr, sizeof(host->addr));
    if (i < 0 || i != sizeof(IPacket))
    {
	if (i < 0)
	{
	    switch (errno)
	    {
	    case ENETDOWN:
	    case ENETUNREACH:
	    case EHOSTDOWN:
	    case EHOSTUNREACH:
		if (verbose >= 3)
		    fprintf(stderr, "unreachable or down!\n");
		if (!host->invalid)
		    validhosts--;
		host->invalid = 1;
		break;
		
	    default:
		perror("sendto");
	    }
	}
	fflush(stdout);
    }
}


static time_t deltaT(struct timeval *t1p, struct timeval *t2p)
{
    return (t2p->tv_sec - t1p->tv_sec) * 1000
	 + (t2p->tv_usec - t1p->tv_usec) / 1000;
}


static HostData *wait_for_reply(HostData *hosts, int numhosts,
				       int sock, int msec_timeout)
{
    fd_set fds;
    struct timeval wait, start_time;
    struct timezone tz;
    u_char inpacket[INPACKET_SIZE];
    struct sockaddr_in from;
    int cc = 0;
    time_t msec_used;
    HostData *host;
    
#if !defined(__GLIBC__)
    int fromlen = sizeof(from);
#else				/* __GLIBC__ */
    socklen_t fromlen = sizeof(from);
#endif				/* __GLIBC__ */

    FD_ZERO(&fds);
    FD_SET(sock, &fds);
    
    gettimeofday(&start_time, &tz);

    for (;;)
    {
	gettimeofday(&wait, &tz);
	msec_used = deltaT(&start_time, &wait);
	if (msec_used > msec_timeout)
	    break;	       /* timed out */
	
	wait.tv_usec = (msec_timeout - msec_used) * 1000;
	wait.tv_sec = 0;
	
	if (select(sock + 1, &fds, NULL, NULL, &wait) > 0)
	{
	    cc = recvfrom(rcvsock, inpacket, INPACKET_SIZE, 0,
			  (struct sockaddr *) &from, &fromlen);
	    if (cc > 0)
	    {
		if ((host = packet_ok(hosts, numhosts, inpacket, cc, &from))
		            != NULL)
		    return host;
	    }
	}
    }
    
    return NULL;
}


static HostData *packet_ok(HostData *hosts, int numhosts,
				  u_char * buf, int cc,
				  struct sockaddr_in *from)
{
    u_char type, code;
    int hlen;
    struct ip *ip;
    struct icmp *icp;
    HostData *host;
    int hcount;

    ip = (struct ip *) buf;
    hlen = ip->ip_hl << 2;
    if (cc < hlen + ICMP_MINLEN)
	return 0;
    cc -= hlen;
    icp = (struct icmp *) (buf + hlen);

    type = icp->icmp_type;
    code = icp->icmp_code;

    if (verbose >= 5)
        fprintf(stderr, "Received ICMP type: %i, code: %i, from %s\n", type, code, inet_ntoa(ip->ip_src) );

    if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS)
	|| type == ICMP_UNREACH || type == ICMP_ECHOREPLY )
    {
	struct ip *hip;
	struct udphdr *up;

	hip = &icp->icmp_ip;
	hlen = hip->ip_hl << 2;
	up = (struct udphdr *) ((u_char *) hip + hlen);

	
	for (hcount = 0, host = hosts; hcount < numhosts; hcount++, host++)
	{
	    if (host->invalid) continue;

            /* Valid ICMP echo reply packet */
            if ( type == ICMP_ECHOREPLY &&
                 ip->ip_src.s_addr == host->addr.sin_addr.s_addr &&
                 icp->icmp_id == htons(ident) && 
                 icp->icmp_seq == htons(host->seq) )
            {
		host->code = ICMP_UNREACH_PORT + 1; /* Behave like if a UDP packet was received even though we used ICMP */
		return host;
            }
            /* Time exceeded reply to an ICMP echo request */
            if ( type == ICMP_TIMXCEED &&
                 hip->ip_dst.s_addr == host->addr.sin_addr.s_addr &&
                 hip->ip_id == htons(ident+host->seq) )
            {
		host->code = -1; 
		return host;
            }
	    
            /* Valid reply to an UDP probe packet */
	    if (hlen + 12 <= cc && hip->ip_p == IPPROTO_UDP &&
		up->uh_sport == htons(ident) &&
		up->uh_dport == htons(port + host->seq) &&
		hip->ip_dst.s_addr == host->addr.sin_addr.s_addr)
	    {
		host->code = (type == ICMP_TIMXCEED ? -1 : code + 1);
		return host;
	    }
	}
    }

    if (verbose >= 3)
        fprintf(stderr, "received an unknown packet!\n"); 
    return NULL;
}


static int choose_ttl(HostData *host)
{
    if (!host || host->invalid)
	return 0;

    /* converge upwards to hops_less_than -- manages rounding errors */
    return host->hops_less_than 
	      - (host->hops_less_than - host->hops_more_than)/2;
}


static void usage(void)
{
    fprintf(stderr,
	    "Usage: netselect [-v|-vv|-vvv] [-I] [-m max_ttl] [-s servers] "
	    "[-t min_tries] host ...\n");
}


static int results(HostData *hosts, int numhosts, int num_score, int use_dns)
{
    int count, lowest_score, score, found_hosts = 0;
    int desired_hosts = num_score;
    HostData *host, *lowest_host;
    
    if (verbose >= 3)
	fprintf(stderr, "\n");
    
    if (verbose >= 2)
    {
	for (count = 0, host = hosts; count < numhosts; count++, host++)
	{
	    if (!host->num_in || !host->num_out)
		fprintf(stderr,"%-35s  %5u ms  %2d hops  %3d%% ok\n",
		       host->hostname, 9999, host->hops_less_than, 0);
	    else
		fprintf(stderr,"%-35s  %5u ms  %2d hops  %3d%% ok (%2d/%2d) [%5d]\n",
		       host->hostname, host->total_lag / host->num_in,
		       host->hops_less_than,
		       host->num_in * 100 / host->num_out,
		       host->num_in, host->num_out, host_score(host));
	}
    }
    
    while (num_score)
    {
	lowest_score = 99999;
	lowest_host = NULL;
	
	for (host = hosts, count = 0; count < numhosts; count++, host++)
	{
	    if (host->invalid) continue;
	    
	    score = host_score(host);
	    if (score < lowest_score)
	    {
		lowest_score = score;
		lowest_host = host;
	    }
	}
	
	if (!lowest_host)
	    break;
	    
        found_hosts++;
        if (use_dns) {
    	    printf("%5d %s\n", lowest_score, lowest_host->dnsname);
        } else {
    	    printf("%5d %s\n", lowest_score, lowest_host->hostname);
        }
	lowest_host->invalid = 1; /* skip this one next time */
	
	if (num_score > 0)
	    num_score--;
    }

    /* Complain if we did not get as many hosts as we were asked for */
    if (found_hosts < desired_hosts)  {
        if ( found_hosts == 0 ) {
            fprintf(stderr,"Did not found any valid hosts (you requested %2d)\n",  desired_hosts);
        } else {
            fprintf(stderr,"Only found %2d hosts out of %2d requested.\n", found_hosts, desired_hosts);
        }
    }

    return found_hosts;
}


static int host_score(HostData *host)
{
    int score;
    
    if (!host->num_in || host->invalid)
	return 99999; /* rotten score */

    score = host->total_lag * host->num_out / host->num_in / host->num_in;
    score = score + (score * host->hops_less_than / 10);
    
    return score;
}