forked from nmap/nmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_net.cc
2004 lines (1683 loc) · 68.4 KB
/
utils_net.cc
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
/***************************************************************************
* utils_net.cc -- Miscellaneous network-related functions that perform *
* various tasks. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2016 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS *
* AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, *
* modify, and redistribute this software under certain conditions. If *
* you wish to embed Nmap technology into proprietary software, we sell *
* alternative licenses (contact [email protected]). Dozens of software *
* vendors already license Nmap technology such as host discovery, port *
* scanning, OS detection, version detection, and the Nmap Scripting *
* Engine. *
* *
* Note that the GPL places important restrictions on "derivative works", *
* yet it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we interpret that term as broadly as copyright law *
* allows. For example, we consider an application to constitute a *
* derivative work for the purpose of this license if it does any of the *
* following with any software or content covered by this license *
* ("Covered Software"): *
* *
* o Integrates source code from Covered Software. *
* *
* o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
* or nmap-service-probes. *
* *
* o Is designed specifically to execute Covered Software and parse the *
* results (as opposed to typical shell or execution-menu apps, which will *
* execute anything you tell them to). *
* *
* o Includes Covered Software in a proprietary executable installer. The *
* installers produced by InstallShield are an example of this. Including *
* Nmap with other software in compressed or archival form does not *
* trigger this provision, provided appropriate open source decompression *
* or de-archiving software is widely available for no charge. For the *
* purposes of this license, an installer is considered to include Covered *
* Software even if it actually retrieves a copy of Covered Software from *
* another source during runtime (such as by downloading it from the *
* Internet). *
* *
* o Links (statically or dynamically) to a library which does any of the *
* above. *
* *
* o Executes a helper program, module, or script to do any of the above. *
* *
* This list is not exclusive, but is meant to clarify our interpretation *
* of derived works with some common examples. Other people may interpret *
* the plain GPL differently, so we consider this a special exception to *
* the GPL that we apply to Covered Software. Works which meet any of *
* these conditions must conform to all of the terms of this license, *
* particularly including the GPL Section 3 requirements of providing *
* source code and allowing free redistribution of the work as a whole. *
* *
* As another special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. *
* *
* Any redistribution of Covered Software, including any derived works, *
* must obey and carry forward all of the terms of this license, including *
* obeying all GPL rules and restrictions. For example, source code of *
* the whole work must be provided and free redistribution must be *
* allowed. All GPL references to "this License", are to be treated as *
* including the terms and conditions of this license text as well. *
* *
* Because this license imposes special exceptions to the GPL, Covered *
* Work may not be combined (even as part of a larger work) with plain GPL *
* software. The terms, conditions, and exceptions of this license must *
* be included as well. This license is incompatible with some other open *
* source licenses as well. In some cases we can relicense portions of *
* Nmap or grant special permissions to use it in other open source *
* software. Please contact [email protected] with any such requests. *
* Similarly, we don't incorporate incompatible open source software into *
* Covered Software without special permission from the copyright holders. *
* *
* If you have any questions about the licensing restrictions on using *
* Nmap in other works, are happy to help. As mentioned above, we also *
* offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates. They also fund the *
* continued development of Nmap. Please email [email protected] for further *
* information. *
* *
* If you have received a written license agreement or contract for *
* Covered Software stating terms other than these, you may choose to use *
* and redistribute Covered Software under those terms instead of these. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes. *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to the [email protected] mailing list for possible incorporation into the *
* main distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, or checking them into the Nmap *
* source code repository, it is understood (unless you specify otherwise) *
* that you are offering the Nmap Project (Insecure.Com LLC) the *
* unlimited, non-exclusive right to reuse, modify, and relicense the *
* code. Nmap will always be available Open Source, but this is important *
* because the inability to relicense code has caused devastating problems *
* for other Free Software projects (such as KDE and NASM). We also *
* occasionally relicense the code to third parties as discussed above. *
* If you wish to specify special license conditions of your *
* contributions, just say so when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
* license file for more details (it's in a COPYING file included with *
* Nmap, and also available from https://svn.nmap.org/nmap/COPYING) *
* *
***************************************************************************/
#include "nping.h"
#include "utils.h"
#include "utils_net.h"
#include "NpingOps.h"
#include "global_structures.h"
#include "output.h"
#include "nbase.h"
#include "pcap.h"
#include "dnet.h"
#include <vector>
extern NpingOps o;
int atoIP(const char *hostname, struct in_addr *dst){
struct sockaddr_in i;
unsigned int stlen=0;
if ( resolve(hostname, 0, (sockaddr_storage*)&i, (size_t *)&stlen , PF_INET) != 0 )
return OP_FAILURE;
*dst=i.sin_addr;
return OP_SUCCESS;
} /* End of atoIP */
int atoIP(const char *hostname, struct sockaddr_storage *ss, int family){
size_t stlen=0;
if(ss==NULL || hostname==NULL)
return OP_FAILURE;
if(family!=AF_INET && family!=AF_INET6)
return OP_FAILURE;
if ( resolve(hostname, 0, ss, &stlen , family) != 0 )
return OP_FAILURE;
return OP_SUCCESS;
} /* End of atoIP */
/** @warning The string is returned in a statically allocated buffer, which
* subsequent calls will overwrite.*/
char *IPtoa(u32 i){
static char buffer[24];
char *aux=NULL;
memset(buffer, 0, 24);
struct in_addr myip;
myip.s_addr=i;
aux=inet_ntoa(myip);
/* Get our own copy of the data so only subsequent calls to IPtoa overwrite
* the returned buffer (not subsequent calls to inet_ntoa() made by other
* methods. */
if(aux!=NULL){
strncpy(buffer, aux, 23);
return buffer;
}
else
return NULL;
} /* End of IPtoa() */
/** @warning The string is returned in a statically allocated buffer, which
* subsequent calls will overwrite.*/
char *IPtoa(struct sockaddr_storage *ss){
struct sockaddr_in *s4=(struct sockaddr_in *)ss;
struct sockaddr_in6 *s6=(struct sockaddr_in6 *)ss;
static char ipstring[256];
memset(ipstring, 0, 256);
if( ss==NULL ){
snprintf(ipstring,256, "[[NULL address supplied to IPtoa()]]");
return ipstring;
}
if(s6->sin6_family==AF_INET6){
inet_ntop(AF_INET6, &s6->sin6_addr, ipstring, sizeof(ipstring));
}else if( s4->sin_family == AF_INET ) {
inet_ntop(AF_INET, &s4->sin_addr, ipstring, sizeof(ipstring));
}else{
snprintf(ipstring,256,"[[Unknown address family sockaddr supplied to IPtoa()]]");
}
return ipstring;
} /* End of IPtoa() */
char *IPtoa(struct sockaddr_storage ss){
return IPtoa(&ss);
} /* End of IPtoa() */
char *IPtoa(struct sockaddr_storage *ss, int family){
if(ss==NULL){
return NULL;
}else if(family==AF_INET){
struct sockaddr_in *s4=(struct sockaddr_in *)ss;
return IPtoa(s4->sin_addr);
}else if(family==AF_INET6){
struct sockaddr_in6 *s6=(struct sockaddr_in6 *)ss;
return IPtoa(s6->sin6_addr);
}else{
return NULL;
}
} /* End of IPtoa() */
/** @warning The string is returned in a statically allocated buffer, which
* subsequent calls will overwrite.*/
char *IPtoa(struct in_addr addr){
static char ipstring[256];
memset(ipstring, 0, 256);
inet_ntop(AF_INET, &addr, ipstring, sizeof(ipstring));
return ipstring;
} /* End of IPtoa() */
/** @warning The string is returned in a statically allocated buffer, which
* subsequent calls will overwrite.*/
char *IPtoa(struct in6_addr addr){
static char ipstring[256];
memset(ipstring, 0, 256);
inet_ntop(AF_INET6, &addr, ipstring, sizeof(ipstring));
return ipstring;
} /* End of IPtoa() */
/** @warning The string is returned in a statically allocated buffer, which
* subsequent calls will overwrite.*/
char *IPtoa(u8 *ipv6addr){
static char ipstring[256];
memset(ipstring, 0, 256);
struct in6_addr s6;
memcpy(s6.s6_addr, ipv6addr, 16);
inet_ntop(AF_INET6, &s6, ipstring, sizeof(ipstring));
return ipstring;
} /* End of IPtoa() */
/** Returns true if supplied value corresponds to a valid RFC compliant ICMP
* type. Otherwise it returns false. */
bool isICMPType(u8 type){
switch (type){
case 0:
case 3:
case 4:
case 5:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 30:
return true;
break;
default:
return false;
break;
}
return false;
} /* End of isICMPType() */
u16 sockaddr2port(struct sockaddr_storage ss){
return sockaddr2port(&ss);
}
u16 sockaddr2port(struct sockaddr_storage *ss){
assert(ss!=NULL);
if(ss->ss_family==AF_INET)
return sockaddr2port( (struct sockaddr_in *)ss );
else if( ss->ss_family==AF_INET6){
return sockaddr2port( (struct sockaddr_in6 *)ss );
}else{
return 0;
}
}
u16 sockaddr2port(struct sockaddr_in *s4){
assert(s4!=NULL);
return ntohs(s4->sin_port);
}
u16 sockaddr2port(struct sockaddr_in6 *s6){
assert(s6!=NULL);
return ntohs(s6->sin6_port);
}
/* Sets the address family member of the supplied sockaddr. */
int setsockaddrfamily(struct sockaddr_storage *ss, int family){
struct sockaddr_in *s4=(struct sockaddr_in *)ss;
s4->sin_family=family;
return OP_SUCCESS;
} /* End of setsockaddrfamily() */
/* Sets the special INADDR_ANY or in6addr_an constant on the sin_family or
* sin6_addr member of the supplied sockaddr. Note that for this to work,
* the supplied sockaddr_storage MUST have a correct address family set
* already (sin_family or sin6_family). */
int setsockaddrany(struct sockaddr_storage *ss){
struct sockaddr_in *s4=(struct sockaddr_in *)ss;
struct sockaddr_in6 *s6=(struct sockaddr_in6 *)ss;
if(s4->sin_family==AF_INET)
s4->sin_addr.s_addr=INADDR_ANY;
else if(s6->sin6_family==AF_INET6)
s6->sin6_addr=in6addr_any;
else
return OP_FAILURE;
return OP_SUCCESS;
} /* End of setsockaddrany() */
/** Returns true if supplied value corresponds to a valid RFC compliant ICMP
* Code. Otherwise it returns false.
* @warning The fact that a given value matches a standard code does not
* mean the code is correct because it depends on the type being used */
bool isICMPCode(u8 code){
/* Correct as of 25 June 09.
* http://www.iana.org/assignments/icmp-parameters */
if( code<=16 )
return true;
else
return false;
} /* End of isICMPType() */
/** Returns true if supplied value corresponds to a valid RFC compliant ICMP
* Code for the supplied type
* @warning The fact that a given value matches a standard code does not
* mean the code is correct because it depends on the type being used */
bool isICMPCode(u8 code, u8 type){
/* Correct as of 25 June 09.
* http://www.iana.org/assignments/icmp-parameters */
switch (type){
case 0: /* Echo Reply */
if(code==0) return true;
break;
case 3: /* Destination Unreachable */
if(code<=15) return true;
break;
case 4: /* Source Quench */
if(code==0) return true;
break;
case 5: /* Redirect */
if(code<=3) return true;
break;
case 6: /* Alternate Address for Host */
if(code==0) return true;
break;
case 8: /* Echo */
if(code==0) return true;
break;
case 9: /* Router Advertisement */
if(code==0 || code==16) return true;
break;
case 10: /* Router Selection */
if(code==0) return true;
break;
case 11: /* Time Exceeded */
if(code==0 || code==1) return true;
break;
case 12: /* Parameter Problem */
if(code<=2) return true;
break;
case 13: /* Timestamp */
if(code==0) return true;
break;
case 14: /* Timestamp Reply */
if(code==0) return true;
break;
case 15: /* Information Request */
if(code==0) return true;
break;
case 16: /* Information Reply */
if(code==0) return true;
break;
case 17: /* Address Mask Request */
if(code==0) return true;
break;
case 18: /* Address Mask Reply */
if(code==0) return true;
break;
case 30: /* Traceroute */
return true;
break;
case 40: /* Experimental ICMP Security Failures Messages [RFC 2521] */
if(code<=5) return true;
break;
default:
return false;
break;
}
return false;
} /* End of isICMPType() */
/* This function fills buffer "dstbuff" with a printable string that
* represents the supplied packet. When sending IPv6 packet at raw TCP
* level, the caller may specify source and/or destination address so they
* also get included in the returned information. However, this is optional
* and is safe to pass NULL values. */
int getPacketStrInfo(const char *proto, const u8 *packet, u32 len, u8 *dstbuff,
u32 dstlen, struct sockaddr_storage *ss_src, struct sockaddr_storage *ss_dst){
char *b=NULL;
int detail;
if ( dstbuff == NULL || dstlen < 512 )
nping_fatal(QT_3,"safe_ippackethdrinfo() Invalid values supplied.");
if(o.getVerbosity()>=VB_2)
detail=HIGH_DETAIL;
else if (o.getVerbosity()==VB_1)
detail=MEDIUM_DETAIL;
else
detail=LOW_DETAIL;
if( !strcasecmp(proto, "IP") || !strcasecmp(proto, "IPv4") || !strcasecmp(proto, "IPv6")){
b=(char *)ippackethdrinfo(packet, len, detail);
strncpy((char*)dstbuff, b, dstlen);
dstbuff[dstlen-1]=0; /* Just to be sure, NULL-terminate the last position*/
}else if( !strcasecmp(proto, "ARP") || !strcasecmp(proto, "RARP") ){
return arppackethdrinfo(packet, len, dstbuff, dstlen);
}else if( !strcasecmp(proto, "IPv6_NO_HEADER") || o.ipv6UsingSocket() ){
if( o.getMode()==TCP )
return tcppackethdrinfo(packet, len, dstbuff, dstlen, detail, ss_src, ss_dst);
else if ( o.getMode()==UDP )
return udppackethdrinfo(packet, len, dstbuff, dstlen, detail, ss_src, ss_dst);
else
nping_fatal(QT_3, "getPacketStrInfo(): Unable to determinate transport layer protocol");
}else{
nping_fatal(QT_3, "getPacketStrInfo(): Unknown protocol");
}
return OP_SUCCESS;
} /* getPacketStrInfo() */
/* Same as previous one but passes NULL sockaddr values automatically. */
int getPacketStrInfo(const char *proto, const u8 *packet, u32 len, u8 *dstbuff, u32 dstlen){
return getPacketStrInfo(proto,packet,len,dstbuff,dstlen,NULL,NULL);
} /* getPacketStrInfo() */
/** This function converts a port ranges specification into an array of u16
* integers that represent each of the specified ports. It allocates space
* for the port lists and stores the pointer in the supplied "list" parameter.
* Also, the number of ports in the array is returned through the supplied
* "count" pointer.
* @warning the caller is the one responsible for free()ing the allocated
* list of ports.
*/
int nping_getpts_simple(const char *origexpr, u16 **list, int *count) {
u8 *porttbl;
int portwarning = 0;
int i, j;
/* Allocate array to hold 2^16 ports */
porttbl = (u8 *) safe_zalloc(65536);
/* Get the ports but do not allow changing the type with T:, U:, or P:. */
getpts_aux(origexpr, 0, porttbl, &portwarning);
/* Count how many are set. */
*count = 0;
for (i = 0; i <= 65535; i++) {
if (porttbl[i])
(*count)++;
}
if (*count == 0){
free(porttbl);
return OP_FAILURE;
}
*list = (unsigned short *) safe_zalloc(*count * sizeof(u16));
/* Fill in the list. */
for (i = 0, j = 0; i <= 65535; i++) {
if (porttbl[i])
(*list)[j++] = i;
}
free(porttbl);
return OP_SUCCESS;
} /* End of nping_getpts_simple() */
/** Determines the net iface that should be used when sending packets
* to "destination".
* @return OP_SUCCESS on success and OP_FAILUIRE in case of error.
* @warning "*dev" must be able to hold at least 16 bytes */
int getNetworkInterfaceName(u32 destination, char *dev){
struct route_nfo rnfo;
struct sockaddr_in dst, src;
bool result=false;
if(dev==NULL)
nping_fatal(QT_3, "getNetworkInterfaceName(): NULL value supplied.");
memset(&rnfo, 0, sizeof(struct route_nfo) );
memset(&dst, 0, sizeof(struct sockaddr_in) );
memset(&src, 0, sizeof(struct sockaddr_in) );
dst.sin_addr.s_addr = destination;
dst.sin_family = AF_INET;
result=route_dst((struct sockaddr_storage *)&dst, &rnfo, NULL, NULL);
if( result == false )
return OP_FAILURE;
strncpy( dev, rnfo.ii.devname, 16 );
return OP_SUCCESS;
} /* End of getSourceAddress() */
/** Determines the net iface that should be used when sending packets
* to "destination".
* @return OP_SUCCESS on success and OP_FAILUIRE in case of error.
* @warning "*dev" must be able to hold at least 16 bytes */
int getNetworkInterfaceName(struct sockaddr_storage *dst, char *dev){
struct route_nfo rnfo;
struct sockaddr_storage src;
bool result=false;
if(dev==NULL)
nping_fatal(QT_3, "getNetworkInterfaceName(): NULL value supplied.");
memset(&rnfo, 0, sizeof(struct route_nfo) );
memset(&src, 0, sizeof(struct sockaddr_in) );
result=route_dst(dst, &rnfo, NULL, NULL);
if( result == false )
return OP_FAILURE;
strncpy( dev, rnfo.ii.devname, 16 );
return OP_SUCCESS;
} /* End of getSourceAddress() */
typedef struct cached_host{
char hostname[MAX_CACHED_HOSTNAME_LEN];
struct sockaddr_storage ss;
size_t sslen;
}cached_host_t;
int resolveCached(char *host, struct sockaddr_storage *ss, size_t *sslen, int pf) {
static cached_host_t archive[MAX_CACHED_HOSTS];
static int cached_count=0;
static int current_index=0; /* Used when we reach the end of the array and we do circular buffer */
int result=0;
//static int way=1;
static int misses=0, hits=0;
/* Used for debug. When called with NULL,0x1337, print stats */
if(host==NULL && pf == 1337){
nping_print(DBG_4, "resolveCached(): MISSES: %d, HITS: %d\n", misses, hits);
return OP_SUCCESS;
}
if( ss==NULL || sslen==NULL || host==NULL)
nping_fatal(QT_3, "resolveCached(): NULL values supplied");
/* First we check if we have the host already cached */
for(int i=0; i<MAX_CACHED_HOSTS && i<cached_count; i++){
if( !strcasecmp( archive[i].hostname , host ) ){ /* Cache hit */
*sslen=archive[i].sslen;
memcpy(ss, &(archive[i].ss) , *sslen);
hits++;
nping_print(DBG_4, "resolveCached(): Cache hit %d for %s\n", hits, host);
return OP_SUCCESS;
}
}
/* Cache miss */
misses++;
nping_print(DBG_4, "resolveCached(): Cache miss %d for %s\n", misses, host);
if( (result=resolve(host, 0, ss, sslen, pf)) == 0 ){
/* Increment count */
if( cached_count < MAX_CACHED_HOSTS )
cached_count++;
/* Store info */
memset(&(archive[current_index]), 0, sizeof(cached_host_t) );
strncpy(archive[current_index].hostname, host, MAX_CACHED_HOSTNAME_LEN);
archive[current_index].sslen = *sslen;
memcpy(&(archive[current_index].ss), ss, *sslen);
/* I run some tests to see what is the best approach when the cache
* is full. The thing is that in Nping, we are likely to call
* this function over and over with specifying the same hosts. Deleting
* the oldest entry results in 100% cache misses. I also tried to start
* overwriting entries first backwards and then upwards. That showed
* much better results. However, if we simply overwrite the last
* cache entry over an over we get the best results. */
if( current_index < MAX_CACHED_HOSTS-1 )
current_index++;
return 0;
///* Watch out for the overflow. If cache is full, */
//if( cached_count == MAX_CACHED_HOSTS ){
//if( way%2==1 ){
//if( current_index > 0 )
//current_index--;
//else{
//current_index=1;
//way++;
//}
//}
//else{
//if( current_index < MAX_CACHED_HOSTS-1 )
//current_index++;
//else{
//current_index=MAX_CACHED_HOSTS-2;
//way++;
//}
//}
//}
//else
//current_index++;
//return OP_SUCCESS;
}else{
nping_warning(QT_2, "Error resolving %s\n",host);
return OP_FAILURE;
}
} /* End of resolveCached() */
typedef struct gethostbyname_cached{
char hostname[MAX_CACHED_HOSTNAME_LEN];
struct hostent *h;
}gethostbynamecached_t;
struct hostent *gethostbynameCached(char *host){
static gethostbynamecached_t archive[MAX_CACHED_HOSTS];
static int cached_count=0;
static int current_index=0;
struct hostent *result=NULL;
static int misses=0, hits=0;
int i=0;
if( host==NULL)
nping_fatal(QT_3, "gethostbynameCached(): NULL values supplied");
/* First we check if we have the host already cached */
for(i=0; i<MAX_CACHED_HOSTS && i<cached_count; i++){
if( !strcasecmp( archive[i].hostname , host ) ){ /* Cache hit */
hits++;
nping_print(DBG_4, "gethostbynameCached(): Cache hit %d for %s", hits, host);
return archive[i].h;
}
}
/* Cache miss */
misses++;
nping_print(DBG_4, "gethostbynameCached(): Cache miss %d for %s", misses, host);
if( (result=gethostbyname(host) ) != NULL ){
/* Increment cache entry count */
if( cached_count < MAX_CACHED_HOSTS )
cached_count++;
/* If we've reached the max number of cached hosts, free the
* hostent entry that is in the last slot so we can insert a new
* one in its place */
if ( current_index==MAX_CACHED_HOSTS-1 && archive[current_index].h != NULL )
hostentfree( archive[current_index].h );
/* Store the hostent entry in the cache */
memset(&(archive[current_index]), 0, sizeof(gethostbynamecached_t) );
strncpy(archive[current_index].hostname, host, MAX_CACHED_HOSTNAME_LEN);
archive[current_index].h = hostentcpy( result );
/* Return the entry that we've just added */
if( current_index < MAX_CACHED_HOSTS-1 ){
current_index++;
return archive[current_index-1].h;
}
else{
return archive[current_index].h;
}
}else{
return NULL;
}
} /* End of resolveCached() */
struct hostent *hostentcpy(struct hostent *src){
struct hostent *st=NULL;
int aliases=0;
int addrs=0;
if( src == NULL )
return NULL;
st=(struct hostent *)safe_zalloc( sizeof(struct hostent) );
/* Copy host name */
if( src->h_name!= NULL )
st->h_name = strdup( src->h_name );
/* Copy aliases */
if( src->h_aliases != NULL ){
while( src->h_aliases[aliases] ) /* Fist count how many*/
aliases++;
st->h_aliases = (char **)safe_zalloc( aliases * sizeof(char*) ); /* Allocate array */
for( int i=0; i<aliases; i++) /* Copy all entries */
st->h_aliases[i] = strdup( src->h_aliases[i] );
}
/* Copy address type an length */
st->h_addrtype=src->h_addrtype;
st->h_length=src->h_length;
/* Copy list of addresses */
if( src->h_addr_list != NULL ){
while( src->h_addr_list[addrs] ) /* Fist count how many*/
addrs++;
st->h_addr_list = (char **)safe_zalloc( addrs * sizeof(char*) ); /* Allocate array */
for( int j=0; j<addrs; j++) /* Copy all entries */
st->h_addr_list[j] = strdup( src->h_addr_list[j] );
/* Create dummy synonym for h_addr_list[0]*/
st->h_addr=st->h_addr_list[0];
}
return st;
} /* End of hostentcpy() */
/** Free a hostend structure.
* @warning This function can ONLY be used with hostent structs returned by
* hostentcpy. Do NOT attempt to use this on a hostent returned by
* gethostbyname() because the structure may contain pointers to statically
* allocated memory regions.*/
int hostentfree(struct hostent *src){
int aliases=0;
int addrs=0;
if( src == NULL )
return OP_SUCCESS;
/* Free host name */
if ( src->h_name != NULL )
free( src->h_name );
/* Free aliases */
if( src->h_aliases != NULL ){
while( src->h_aliases[aliases] ){
free(src->h_aliases[aliases]);
aliases++;
}
free(src->h_aliases);
}
/* Free list of addresses */
if( src->h_addr_list != NULL ){
while( src->h_addr_list[addrs] ){
addrs++;
free( src->h_addr_list[addrs] );
}
free( src->h_addr_list );
}
/* Finally free the base hostent struct */
free( src );
return OP_SUCCESS;
} /* End of hostentfree() */
/** Receives a MAC address as a string of format 00:13:01:e6:c7:ae or
* 00-13-01-e6-c7-ae and stores in targetbuff the 6 corresponding bytes.
* The "txt" parameter may take the special value "rand" or "random",
* in which case, 6 random bytes will be stored in "targetbuff".
* @return OP_SUCCESS on success and OP_FAILURE in case of error.
* Buffer targetbuff is NOT modified if "txt" does not have the proper
* format */
int parseMAC(const char *txt, u8 *targetbuff){
u8 mac_data[6];
char tmphex[3];
int i=0, j=0;
if( txt==NULL || targetbuff==NULL )
return OP_FAILURE;
/* Set up a random MAC if user requested so. */
if( meansRandom(txt) ){
get_random_bytes(targetbuff, 6);
return OP_SUCCESS;
/* Or set it to FF:FF:FF:FF:FF:FF if user chose broadcast */
}else if( !strcasecmp(optarg, "broadcast") || !strcasecmp(optarg, "bcast") ){
memset(targetbuff, 0xFF, 6);
return OP_SUCCESS;
}
/* Array should look like 00:13:01:e6:c7:ae or 00-13-01-e6-c7-ae
Array positions: 01234567890123456 01234567890123456 */
if( strlen(txt)!=17 )
return OP_FAILURE;
/* Check MAC has the correct ':' or '-' characters */
if( (txt[2]!=':' && txt[2]!='-') || (txt[5]!=':' && txt[5]!='-') ||
(txt[8]!=':' && txt[8]!='-') || (txt[11]!=':' && txt[11]!='-') ||
(txt[14]!=':' && txt[14]!='-') )
return OP_FAILURE;
/* Convert txt into actual bytes */
for(i=0, j=0; i<6; i++, j+=3 ){
if( !isxdigit(txt[j]) || !isxdigit(txt[j+1]) )
return OP_FAILURE;
tmphex[0] = txt[j];
tmphex[1] = txt[j+1];
tmphex[2] = '\0';
mac_data[i] = (u8) strtol(tmphex, NULL, 16);
}
memcpy(targetbuff, mac_data, 6);
return OP_SUCCESS;
} /* End of parseMAC() */
char *MACtoa(u8 *mac){
static char macinfo[24];
memset(macinfo, 0, 24);
sprintf(macinfo,"%02X:%02X:%02X:%02X:%02X:%02X",
mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
return macinfo;
} /* End of MACtoa() */
/* Returns a buffer of ASCII information about an ARP/RARP packet that may look
like "ARP who has 192.168.10.1? Tell 192.168.10.98"
Since this is a static buffer, don't use threads or call twice
within (say) printf(). And certainly don't try to free() it! The
returned buffer is NUL-terminated */
const char *arppackethdrinfo(const u8 *packet, u32 len, int detail){
static char protoinfo[512];
if (packet==NULL)
nping_fatal(QT_3, "arppackethdrinfo(): NULL value supplied");
if( len < 28 )
return "BOGUS! Packet too short.";
u16 *htype = (u16 *)packet;
u16 *ptype = (u16 *)(packet+2);
u8 *hlen = (u8 *)(packet+4);
u8 *plen = (u8 *)(packet+5);
u16 *op = (u16 *)(packet+6);
u8 *sMAC= (u8 *)(packet+8);
u32 *sIP = (u32 *)(packet+14);
u8 *tMAC = (u8 *)(packet+18);
u32 *tIP = (u32 *)(packet+24);
if( ntohs(*op) == 1 ){ /* ARP Request */
sprintf(protoinfo, "ARP who has %s? ", IPtoa(*tIP));
sprintf(protoinfo+strlen(protoinfo),"Tell %s", IPtoa(*sIP) );
}
else if( ntohs(*op) == 2 ){ /* ARP Reply */
sprintf(protoinfo, "ARP reply %s ", IPtoa(*sIP));
sprintf(protoinfo+strlen(protoinfo),"is at %s", MACtoa(sMAC) );
}
else if( ntohs(*op) == 3 ){ /* RARP Request */
sprintf(protoinfo, "RARP who is %s? Tell %s", MACtoa(tMAC), MACtoa(sMAC) );
}
else if( ntohs(*op) ==4 ){ /* RARP Reply */
sprintf(protoinfo, "RARP reply: %s is at %s", MACtoa(tMAC), IPtoa(*tIP) );
}
else{
sprintf(protoinfo, "HTYPE:%04X PTYPE:%04X HLEN:%d PLEN:%d OP:%04X SMAC:%s SIP:%s DMAC:%s DIP:%s",
*htype, *ptype, *hlen, *plen, *op, MACtoa(sMAC), IPtoa(*sIP), MACtoa(tMAC), IPtoa(*tIP));
}
return protoinfo;
} /* End of arppackethdrinfo() */
int arppackethdrinfo(const u8 *packet, u32 len, u8 *dstbuff, u32 dstlen){
char *b=NULL;
int detail=0;
if ( dstbuff == NULL || dstlen < 512 )
nping_fatal(QT_3,"safe_arppackethdrinfo() Invalid values supplied.");
/* Determine level of detail in packet output from current verbosity level */
if(o.getVerbosity()>=VB_2)
detail=HIGH_DETAIL;
else if (o.getVerbosity()==VB_1)
detail=MEDIUM_DETAIL;
else
detail=LOW_DETAIL;
b=(char *)arppackethdrinfo(packet, len, detail);
strncpy((char*)dstbuff, b, dstlen);
dstbuff[dstlen-1]=0; /* Just to be sure, NULL-terminate the last position*/
return OP_SUCCESS;
} /* End of arppackethdrinfo() */
int tcppackethdrinfo(const u8 *packet, size_t len, u8 *dstbuff, size_t dstlen,
int detail, struct sockaddr_storage *src, struct sockaddr_storage *dst){
struct tcp_hdr *tcp=NULL; ; /* TCP header structure. */
char *p = NULL; /* Aux pointer. */
static char protoinfo[1024] = ""; /* Stores final info string. */
char tflags[10];
char tcpinfo[64] = "";
char buf[32];
char tcpoptinfo[256] = "";
struct sockaddr_in *s4=(struct sockaddr_in *)src;
struct sockaddr_in6 *s6=(struct sockaddr_in6 *)src;
struct sockaddr_in *d4=(struct sockaddr_in *)dst;
struct sockaddr_in6 *d6=(struct sockaddr_in6 *)dst;
char srcipstring[128];
char dstipstring[128];
assert(packet);
assert(dstbuff);
assert(len>=20);
tcp=(struct tcp_hdr *)packet;
/* Ensure we end up with a valid detail number */
if( detail!=LOW_DETAIL && detail!=MEDIUM_DETAIL && detail!=HIGH_DETAIL)
detail=LOW_DETAIL;
/* Determine target IP address */
if(src!=NULL){
if( s4->sin_family==AF_INET ){
inet_ntop(AF_INET, &s4->sin_addr, srcipstring, sizeof(srcipstring));
}
else if( s6->sin6_family==AF_INET6){
inet_ntop(AF_INET6, &s6->sin6_addr, srcipstring, sizeof(srcipstring));
}else{
sprintf(dstipstring, "unknown_addr_family");
}
}else{
sprintf(srcipstring, "this_host");
}
/* Determine source IP address */
if(dst!=NULL){
if( d4->sin_family==AF_INET ){
inet_ntop(AF_INET, &d4->sin_addr, dstipstring, sizeof(dstipstring));
}
else if( d6->sin6_family==AF_INET6){
inet_ntop(AF_INET6, &d6->sin6_addr, dstipstring, sizeof(dstipstring));
}else{
sprintf(dstipstring, "unknown_addr_family");
}
}else{
sprintf(dstipstring, "unknown_host");