This repository has been archived by the owner on Jul 16, 2019. It is now read-only.
forked from apenwarr/netselect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
netselect.c
1527 lines (1300 loc) · 37.2 KB
/
netselect.c
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
/*
* Netselect:
* Copyright (c) 1998-2010 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/ip6.h>
#include <netinet/icmp6.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;
/*
* format of a (headerless udp) probe packet.
*/
typedef struct
{
struct udphdr udp;
u_char seq; /* sequence number of this packet */
u_char ttl; /* ttl packet left with */
struct timeval tv; /* time packet left */
} OPacket6;
/*
* format of a (icmpv6) probe packet.
*/
typedef struct
{
struct icmp6_hdr icmp6; /* icmp6 contains seq (id) and ttl (seq)
* fields already */
struct timeval tv; /* time packet left */
}__attribute__((packed)) I6Packet;
/*
* currently-known information about a host
*/
typedef struct
{
char *hostname; /* hostname as provided on command line */
char *shortname; /* hostname with any URL-type stuff removed */
struct sockaddr_storage 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 *addr,
int max_ttl);
static char *un_url(char *orig);
static char *fix_url(char *orig, struct sockaddr *addr);
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_probe6(int seq, int ttl, OPacket6 *op,
HostData *host);
static void send_icmp_probe(int seq, int ttl, IPacket *op,
HostData *host);
static void send_icmp6_probe(int seq, int ttl, I6Packet *op,
HostData *host);
static time_t deltaT(struct timeval *t1p, struct timeval *t2p);
static HostData *wait_for_reply(HostData *hosts, int numhosts,
int msec_timeout);
static HostData *packet_ok(HostData *hosts, int numhosts,
u_char *buf, int cc,
struct sockaddr_in *from);
static HostData *packet6_ok(HostData *hosts, int numhosts,
u_char *buf, int cc,
struct sockaddr_in6 *from);
static int choose_ttl(HostData *host);
static void usage();
static void results(HostData *hosts, int numhosts, int num_score);
static int host_score(HostData *host);
#define INPACKET_SIZE 512
/* global variables */
static int rcvsock; /* receive (icmp) socket file descriptor */
static int rcvsock6; /* IPv6 receive (icmp) socket file descriptor */
static int sndsock; /* send (udp) socket file descriptor */
static int sndsock6; /* IPv6 send 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;
static int addr_fam = AF_UNSPEC;
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 = 0;
int sock_v6_only = 1;
unsigned int min_tries = 10;
struct timeval now;
struct timezone tz;
OPacket udppacket; /* last output (udp) packet */
IPacket icmppacket; /* last output (icmp) packet */
OPacket6 udppacket6; /* last output (headerless udp) packet */
I6Packet icmp6packet; /* last output (icmp6) packet */
HostData *host, *hosts;
int numhosts, delay, must_continue, count, port_unreachable, other_unreachable;
int socket_errno = 0;
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
|| (rcvsock6 = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 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:Iv?46")) != 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 '4':
addr_fam = AF_INET;
break;
case '6':
addr_fam = AF_INET6;
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");
return 5;
}
if (addr_fam == AF_INET)
{
close(rcvsock6);
rcvsock6 = -1;
}
else if (addr_fam == AF_INET6)
{
close(rcvsock);
rcvsock = -1;
}
ident = (getpid() & 0xffff) | 0x8000;
if ( use_icmp )
{
memset(&icmppacket, 0, sizeof(IPacket));
icmppacket.ip.ip_tos = 0;
icmppacket.ip.ip_v = IPVERSION;
icmppacket.ip.ip_id = 0;
sndsock6 = rcvsock6;
}
else
{
memset(&udppacket, 0, sizeof(OPacket));
udppacket.ip.ip_tos = 0;
udppacket.ip.ip_v = IPVERSION;
udppacket.ip.ip_id = 0;
if (addr_fam != AF_INET)
{
struct sockaddr_in6 source;
if ((sndsock6 = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
{
perror("netselect: socket");
if (errno == EPERM) {
fprintf(stderr, "You should be root to run netselect.\n");
return 6;
}
return 5;
}
if (setsockopt(sndsock6, IPPROTO_IPV6, IPV6_V6ONLY,
&sock_v6_only, sizeof(int)) < 0)
{
perror("setsockopt with IPV6_V6ONLY");
return 1;
}
memset(&source, 0, sizeof(struct sockaddr_in6));
source.sin6_family = AF_INET6;
source.sin6_port = htons(ident);
memcpy(&source.sin6_addr, &in6addr_any, sizeof(struct in6_addr));
if (bind(sndsock6, (struct sockaddr *)&source, sizeof(source)) < 0)
{
perror("bind");
return 1;
}
}
}
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 (host->addr.ss_family == AF_INET
|| host->addr.ss_family == AF_INET6)
{
if (host->addr.ss_family == AF_INET)
{
if ( use_icmp )
send_icmp_probe(host->seq, ttl, &icmppacket, host);
else
send_probe(host->seq, ttl, &udppacket, host);
}
else
{
if ( use_icmp )
send_icmp6_probe(host->seq, ttl, &icmp6packet, host);
else
send_probe6(host->seq, ttl, &udppacket6, 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, 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));
port_unreachable = 0;
other_unreachable = 0;
if (host->code == -1)
{
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--;
}
else if (host->addr.ss_family == AF_INET)
{
switch (host->code - 1)
{
case ICMP_UNREACH_PORT:
port_unreachable = 1;
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:
other_unreachable = 1;
break;
}
}
else if (host->addr.ss_family == AF_INET6)
{
switch (host->code - 1)
{
case ICMP6_DST_UNREACH_NOPORT:
port_unreachable = 1;
break;
case ICMP6_DST_UNREACH_NOROUTE:
case ICMP6_DST_UNREACH_ADMIN:
case ICMP6_DST_UNREACH_BEYONDSCOPE:
case ICMP6_DST_UNREACH_ADDR:
other_unreachable = 1;
break;
}
}
if (port_unreachable)
{
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;
}
else if (other_unreachable)
{
if (verbose >= 3)
fprintf(stderr, "unreachable!\n");
if (!host->invalid)
validhosts--;
host->invalid = 1;
}
if (verbose >= 3)
fprintf(stderr, "\n");
}
}
if (verbose >= 1)
fprintf(stderr, "\n");
results(hosts, numhosts, num_score);
if (hosts)
{
for (count = 0; count < numhosts; count++)
{
free(hosts[count].hostname);
free(hosts[count].shortname);
}
free(hosts);
}
return 0;
}
static inline int in6_addr_cmp(struct in6_addr *a, struct in6_addr *b)
{
return memcmp(&a->s6_addr, &b->s6_addr, 16);
}
/*
* 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 *addr,
int max_ttl)
{
HostData *host;
if (addr)
{
int hcount;
sa_family_t family = ((struct sockaddr_storage *)addr)->ss_family;
struct in_addr *addr4, *haddr4;
struct in6_addr *addr6, *haddr6;
if ((family != AF_INET && family != AF_INET6)
|| (family == AF_INET && addr_fam == AF_INET6)
|| (family == AF_INET6 && addr_fam == AF_INET ))
{
if (verbose >= 1)
fprintf(stderr, "\nUnsupported address family %hu for host %s address\n",
family, hostname);
return hosts;
}
if (family == AF_INET)
addr4 = &((struct sockaddr_in *)addr)->sin_addr;
else
addr6 = &((struct sockaddr_in6 *)addr)->sin6_addr;
for (hcount = 0, host = hosts; hcount < *numhosts; hcount++, host++)
{
if (host->invalid || host->addr.ss_family != family)
continue;
if (family == AF_INET)
haddr4 = &((struct sockaddr_in *)&host->addr)->sin_addr;
else
haddr6 = &((struct sockaddr_in6 *)&host->addr)->sin6_addr;
if ((family == AF_INET && haddr4->s_addr == addr4->s_addr)
|| (family == AF_INET6 && in6_addr_cmp(haddr6, addr6) == 0))
{
if (verbose >= 1)
{
char txt[INET6_ADDRSTRLEN];
fprintf(stderr, "\nDuplicate address %s (%s, %s); keeping only under first name.\n",
inet_ntop(family,
family == AF_INET ? (void *)addr4 : (void *)addr6,
txt, sizeof(txt)),
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->shortname = un_url(hostname);
if (addr)
memcpy(&host->addr, addr, sizeof(struct sockaddr_storage));
else
host->invalid = 1;
host->hops_less_than = max_ttl;
return hosts;
}
static char *un_url(char *orig)
{
char *sptr, *eptr = NULL, *newbuf;
if ((sptr = strstr(orig, "://")) != NULL)
{
/* URL formatted, like: http://hostname:port/dir/file */
sptr += 3; /* skip :// */
if (*sptr == '[') /* v6 literal address */
{
eptr = strchr(sptr, ']');
if (eptr)
++sptr;
}
if (!eptr) eptr = strchr(sptr, ':');
if (!eptr) eptr = strchr(sptr, '/');
if (!eptr) eptr = strchr(sptr, 0);
}
else
{
if (*orig == '[')
{
/* quoted v6 literal address in non-URL format */
eptr = strchr(orig, ']');
if (eptr)
sptr = orig + 1;
}
if (!sptr && (eptr = strchr(orig, ':')) != NULL)
{
/* Could be an IPv6 address */
struct sockaddr_storage ss;
if (inet_pton(AF_INET6, orig, &ss) != 1)
{
/* FTP formatted, like: ftp.debian.org:/debian/foo */
sptr = orig;
}
}
}
if (sptr)
{
newbuf = (char *)malloc(eptr-sptr+1);
strncpy(newbuf, sptr, eptr-sptr);
newbuf[eptr-sptr] = 0;
return newbuf;
}
else /* just plain */
return strdup(orig);
}
static char *fix_url(char *orig, struct sockaddr *addr)
{
char *pree = NULL, *posts = NULL;
char addrstr[INET6_ADDRSTRLEN + 2];
void *src;
if ((pree = strstr(orig, "://")) != NULL)
{
/* URL formatted, like: http://hostname:port/dir/file */
pree += 3; /* skip :// */
if (*pree == '[') /* v6 literal address */
{
posts = strchr(pree, ']');
if (posts)
++posts;
}
if (!posts) posts = strchr(pree, ':');
if (!posts) posts = strchr(pree, '/');
if (!posts) posts = strchr(pree, 0);
}
else
{
pree = orig;
if (*pree == '[')
{
/* quoted v6 literal address in non-URL format */
posts = strchr(pree, ']');
if (posts)
++posts;
}
if (!posts)
{
struct sockaddr_storage ss;
if (inet_pton(AF_INET6, orig, &ss) != 1)
{
/* FTP formatted, like: ftp.debian.org:/debian/foo */
posts = strchr(orig, ':');
}
}
}
if (addr->sa_family == AF_INET)
src = &((struct sockaddr_in *)addr)->sin_addr;
else
src = &((struct sockaddr_in6 *)addr)->sin6_addr;
inet_ntop(addr->sa_family, src, addrstr, sizeof(addrstr));
if (posts)
{
char *newbuf;
size_t addrlen;
size_t prelen = pree - orig;
size_t postlen = strlen(posts);
/* We want to quote a v6 address in this case */
if (addr->sa_family == AF_INET6)
{
char quoted_addr[sizeof(addrstr)];
sprintf(quoted_addr, "[%s]", addrstr);
strcpy(addrstr, quoted_addr);
}
addrlen = strlen(addrstr);
newbuf = (char *)malloc(prelen + addrlen + postlen + 1);
if (prelen > 0)
strncpy(newbuf, orig, prelen);
strncpy(newbuf + prelen, addrstr, addrlen);
strncpy(newbuf + prelen + addrlen, posts, postlen);
return newbuf;
}
else /* just plain */
return strdup(addrstr);
}
/*
* 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_storage 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 addrinfo *hp, hints;
pid_t pid;
int err;
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
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = addr_fam;
hints.ai_flags = AI_ADDRCONFIG;
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 */
/* try simple IPv4 dotted-quad conversion */
if (addr_fam != AF_INET6)
{
struct sockaddr_in *addr4 = (struct sockaddr_in *) &result.addr;
addr4->sin_family = AF_INET;
addr4->sin_addr.s_addr = inet_addr(names[count]);
if (addr4->sin_addr.s_addr != INADDR_NONE)
{
write(pipes[1], &result, sizeof(result));
/* Use this as a flag to not do a lookup */
result.multi = 1;
}
}
if (result.multi == 0);
{
/* must actually do the name lookup */
char *simplename = un_url(result.hostname);
err = getaddrinfo(simplename, NULL, &hints, &hp);
free(simplename);
if (!err)
{
struct addrinfo *ptr;
int already_seen_one = 0;
result.broken = 0;
for (ptr = hp; ptr; ptr = ptr->ai_next)
{
if ((ptr->ai_family != AF_INET && ptr->ai_family != AF_INET6)
|| (ptr->ai_family == AF_INET && addr_fam == AF_INET6)
|| (ptr->ai_family == AF_INET6 && addr_fam == AF_INET))
continue;
if (already_seen_one)
result.multi = 1;
memcpy(&result.addr, ptr->ai_addr, ptr->ai_addrlen);
write(pipes[1], &result, sizeof(result));
if (!already_seen_one)
already_seen_one = 1;
}
freeaddrinfo(hp);
}
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! */
if (result.broken)
{
/* name lookup failed */
char *simplename = un_url(result.hostname);
hosts = add_host(hosts, numhosts, strdup(result.hostname),
NULL, 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,
(struct sockaddr *)&result.addr);
else
newhostname = strdup(result.hostname);
hosts = add_host(hosts, numhosts, newhostname,
(struct sockaddr *)&result.addr, max_ttl);
}
}
}
/* reap dead tasks */
while (waitpid(-1, NULL, WNOHANG) > 0)
active--;
}