home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / nmap254b.zip / tcpip.c < prev    next >
C/C++ Source or Header  |  2002-02-25  |  52KB  |  1,680 lines

  1.  
  2. /***********************************************************************/
  3. /* tcpip.c -- Various functions relating to low level TCP/IP handling, */
  4. /* including sending raw packets, routing, printing packets, reading   */
  5. /* from libpcap, etc.                                                  */
  6. /*                                                                     */
  7. /***********************************************************************/
  8. /*  The Nmap Security Scanner is (C) 1995-2001 Insecure.Com LLC. This  */
  9. /*  program is free software; you can redistribute it and/or modify    */
  10. /*  it under the terms of the GNU General Public License as published  */
  11. /*  by the Free Software Foundation; Version 2.  This guarantees your  */
  12. /*  right to use, modify, and redistribute this software under certain */
  13. /*  conditions.  If this license is unacceptable to you, we may be     */
  14. /*  willing to sell alternative licenses (contact sales@insecure.com). */
  15. /*                                                                     */
  16. /*  If you received these files with a written license agreement       */
  17. /*  stating terms other than the (GPL) terms above, then that          */
  18. /*  alternative license agreement takes precendence over this comment. */
  19. /*                                                                     */
  20. /*  Source is provided to this software because we believe users have  */
  21. /*  a right to know exactly what a program is going to do before they  */
  22. /*  run it.  This also allows you to audit the software for security   */
  23. /*  holes (none have been found so far).                               */
  24. /*                                                                     */
  25. /*  Source code also allows you to port Nmap to new platforms, fix     */
  26. /*  bugs, and add new features.  You are highly encouraged to send     */
  27. /*  your changes to fyodor@insecure.org for possible incorporation     */
  28. /*  into the main distribution.  By sending these changes to Fyodor or */
  29. /*  one the insecure.org development mailing lists, it is assumed that */
  30. /*  you are offering Fyodor the unlimited, non-exclusive right to      */
  31. /*  reuse, modify, and relicense the code.  This is important because  */
  32. /*  the inability to relicense code has caused devastating problems    */
  33. /*  for other Free Software projects (such as KDE and NASM).  Nmap     */
  34. /*  will always be available Open Source.  If you wish to specify      */
  35. /*  special license conditions of your contributions, just say so      */
  36. /*  when you send them.                                                */
  37. /*                                                                     */
  38. /*  This program is distributed in the hope that it will be useful,    */
  39. /*  but WITHOUT ANY WARRANTY; without even the implied warranty of     */
  40. /*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  */
  41. /*  General Public License for more details (                          */
  42. /*  http://www.gnu.org/copyleft/gpl.html ).                            */
  43. /*                                                                     */
  44. /***********************************************************************/
  45.  
  46. /* $Id: tcpip.c,v 1.74 2001/10/05 16:24:53 fyodor Exp $ */
  47.  
  48.  
  49. #include "tcpip.h"
  50.  
  51. #if HAVE_SYS_TIME_H
  52. #include <sys/time.h>
  53. #endif
  54.  
  55. #if HAVE_SYS_RESOURCE_H
  56. #include <sys/resource.h>
  57. #endif
  58.  
  59. #if HAVE_UNISTD_H
  60. /* #include <sys/unistd.h> */
  61. #include <unistd.h>
  62. #endif
  63.  
  64. extern struct ops o;
  65.  
  66. /*  predefined filters -- I need to kill these globals at some pont. */
  67. extern unsigned long flt_dsthost, flt_srchost, flt_baseport;
  68.  
  69. #ifndef WIN32 /* Already defined in wintcpip.c for now */
  70. void sethdrinclude(int sd) {
  71. #ifdef IP_HDRINCL
  72. int one = 1;
  73. setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (const char *) &one, sizeof(one));
  74. #endif
  75. }
  76. #endif /* WIN32 */
  77.  
  78. /* Tests whether a packet sent to  IP is LIKELY to route 
  79.  through the kernel localhost interface */
  80. #ifndef WIN32 /* This next group of functions are already defined in 
  81.                  wintcpip.c for now */
  82. int islocalhost(struct in_addr *addr) {
  83. char dev[128];
  84.   /* If it is 0.0.0.0 or starts with 127.0.0.1 then it is 
  85.      probably localhost */
  86.   if ((addr->s_addr & htonl(0xFF000000)) == htonl(0x7F000000))
  87.     return 1;
  88.  
  89.   if (!addr->s_addr)
  90.     return 1;
  91.  
  92.   /* If it is the same addy as a local interface, then it is
  93.      probably localhost */
  94.  
  95.   if (ipaddr2devname(dev, addr) != -1)
  96.     return 1;
  97.  
  98.   /* OK, so to a first approximation, this addy is probably not
  99.      localhost */
  100.   return 0;
  101. }
  102.  
  103.  
  104. /* Calls pcap_open_live and spits out an error (and quits) if the call faile.
  105.    So a valid pcap_t will always be returned. */
  106. pcap_t *my_pcap_open_live(char *device, int snaplen, int promisc, int to_ms) 
  107. {
  108.   char err0r[PCAP_ERRBUF_SIZE];
  109.   pcap_t *pt;
  110.   if (!((pt = pcap_open_live(device, snaplen, promisc, to_ms, err0r)))) {
  111.     fatal("pcap_open_live: %s\nThere are several possible reasons for this, depending on your operating system:\n"
  112.           "LINUX: If you are getting Socket type not supported, try modprobe af_packet or recompile your kernel with SOCK_PACKET enabled.\n"
  113.           "*BSD:  If you are getting device not configured, you need to recompile your kernel with Berkeley Packet Filter support.  If you are getting No such file or directory, try creating the device (eg cd /dev; MAKEDEV <device>; or use mknod).\n"
  114.           "SOLARIS:  If you are trying to scan localhost and getting '/dev/lo0: No such file or directory', complain to Sun.  I don't think Solaris can support advanced localhost scans.  You can probably use \"-P0 -sT localhost\" though.\n\n", err0r);
  115.   }
  116.   return pt;
  117. }
  118.  
  119. /* Standard BSD internet checksum routine */
  120. unsigned short in_cksum(u16 *ptr,int nbytes) {
  121.  
  122. register u32 sum;
  123. u16 oddbyte;
  124. register u16 answer;
  125.  
  126. /*
  127.  * Our algorithm is simple, using a 32-bit accumulator (sum),
  128.  * we add sequential 16-bit words to it, and at the end, fold back
  129.  * all the carry bits from the top 16 bits into the lower 16 bits.
  130.  */
  131.  
  132. sum = 0;
  133. while (nbytes > 1)  {
  134. sum += *ptr++;
  135. nbytes -= 2;
  136. }
  137.  
  138. /* mop up an odd byte, if necessary */
  139. if (nbytes == 1) {
  140. oddbyte = 0;            /* make sure top half is zero */
  141. *((u_char *) &oddbyte) = *(u_char *)ptr;   /* one byte only */
  142. sum += oddbyte;
  143. }
  144.  
  145. /*
  146.  * Add back carry outs from top 16 bits to low 16 bits.
  147.  */
  148.  
  149. sum  = (sum >> 16) + (sum & 0xffff);    /* add high-16 to low-16 */
  150. sum += (sum >> 16);                     /* add carry */
  151. answer = ~sum;          /* ones-complement, then truncate to 16 bits */
  152. return(answer);
  153. }
  154.  
  155.  
  156.  
  157.  
  158. /* Tries to resolve given hostname and stores
  159.    result in ip .  returns 0 if hostname cannot
  160.    be resolved */
  161. int resolve(char *hostname, struct in_addr *ip) {
  162.   struct hostent *h;
  163.  
  164.   if (!hostname || !*hostname)
  165.     fatal("NULL or zero-length hostname passed to resolve()");
  166.  
  167.   if (inet_aton(hostname, ip))
  168.     return 1; /* damn, that was easy ;) */
  169.   if ((h = gethostbyname(hostname))) {
  170.     memcpy(ip, h->h_addr_list[0], sizeof(struct in_addr));
  171.     return 1;
  172.   }
  173.   return 0;
  174. }
  175.  
  176. int send_tcp_raw_decoys( int sd, struct in_addr *victim, u16 sport, 
  177.              u16 dport, u32 seq, u32 ack, u8 flags, u16 window, 
  178.                          u8 *options, int optlen, u8 *data, u16 datalen) 
  179. {
  180.   int decoy;
  181.  
  182.   for(decoy = 0; decoy < o.numdecoys; decoy++) 
  183.     if (send_tcp_raw(sd, &o.decoys[decoy], victim, sport, dport, seq, ack,
  184.              flags, window, options, optlen, data, datalen) == -1)
  185.       return -1;
  186.  
  187.   return 0;
  188. }
  189.  
  190.  
  191. int send_tcp_raw( int sd, struct in_addr *source, struct in_addr *victim, 
  192.           u16 sport, u16 dport, u32 seq, u32 ack, u8 flags,
  193.           u16 window, u8 *options, int optlen, char *data, 
  194.           u16 datalen) 
  195. {
  196.  
  197. struct pseudo_header { 
  198.   /*for computing TCP checksum, see TCP/IP Illustrated p. 145 */
  199.   u32 s_addy;
  200.   u32 d_addr;
  201.   u8 zer0;
  202.   u8 protocol;
  203.   u16 length;
  204. };
  205. u8 *packet = (u8 *) safe_malloc(sizeof(struct ip) + sizeof(struct tcphdr) + optlen + datalen);
  206. struct ip *ip = (struct ip *) packet;
  207. struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct ip));
  208. struct pseudo_header *pseudo =  (struct pseudo_header *) (packet + sizeof(struct ip) - sizeof(struct pseudo_header)); 
  209. static int myttl = 0;
  210.  
  211.  /*With these placement we get data and some field alignment so we aren't
  212.    wasting too much in computing the checksum */
  213. int res = -1;
  214. struct sockaddr_in sock;
  215. char myname[MAXHOSTNAMELEN + 1];
  216. struct hostent *myhostent = NULL;
  217. int source_malloced = 0;
  218.  
  219. /* check that required fields are there and not too silly */
  220. /* We used to check that sport and dport were nonzer0, but scr3w that! */
  221. if ( !victim || sd < 0) {
  222.   fprintf(stderr, "send_tcp_raw: One or more of your parameters suck!\n");
  223.   free(packet);
  224.   return -1;
  225. }
  226.  
  227. if (optlen % 4) {
  228.   fatal("send_tcp_raw called with an option length argument of %d which is illegal because it is not divisible by 4", optlen);
  229. }
  230.  
  231.  
  232. if (!myttl) myttl = (get_random_uint() % 23) + 37;
  233.  
  234. /* It was a tough decision whether to do this here for every packet
  235.    or let the calling function deal with it.  In the end I grudgingly decided
  236.    to do it here and potentially waste a couple microseconds... */
  237. sethdrinclude(sd); 
  238.  
  239. /* if they didn't give a source address, fill in our first address */
  240. if (!source) {
  241.   source_malloced = 1;
  242.   source = (struct in_addr *) safe_malloc(sizeof(struct in_addr));
  243.   if (gethostname(myname, MAXHOSTNAMELEN) || 
  244.       !(myhostent = gethostbyname(myname)))
  245.        fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  246.   memcpy(source, myhostent->h_addr_list[0], sizeof(struct in_addr));
  247. #if ( TCPIP_DEBUGGING )
  248.     printf("We skillfully deduced that your address is %s\n", 
  249.        inet_ntoa(*source));
  250. #endif
  251. }
  252.  
  253.  
  254. /*do we even have to fill out this damn thing?  This is a raw packet, 
  255.   after all */
  256. sock.sin_family = AF_INET;
  257. sock.sin_port = htons(dport);
  258. sock.sin_addr.s_addr = victim->s_addr;
  259.  
  260.  
  261. bzero((char *) packet, sizeof(struct ip) + sizeof(struct tcphdr));
  262.  
  263. pseudo->s_addy = source->s_addr;
  264. pseudo->d_addr = victim->s_addr;
  265. pseudo->protocol = IPPROTO_TCP;
  266. pseudo->length = htons(sizeof(struct tcphdr) + optlen + datalen);
  267.  
  268. tcp->th_sport = htons(sport);
  269. tcp->th_dport = htons(dport);
  270. if (seq) {
  271.   tcp->th_seq = htonl(seq);
  272. }
  273. else if (flags & TH_SYN) {
  274.   get_random_bytes(&(tcp->th_seq), 4);
  275. }
  276.  
  277. if (ack)
  278.   tcp->th_ack = htonl(ack);
  279. /*else if (flags & TH_ACK)
  280.   tcp->th_ack = rand() + rand();*/
  281.  
  282. tcp->th_off = 5 + (optlen /4) /*words*/;
  283. tcp->th_flags = flags;
  284.  
  285. if (window)
  286.   tcp->th_win = htons(window);
  287. else tcp->th_win = htons(1024 * (myttl % 4 + 1)); /* Who cares */
  288.  
  289.  /* We should probably copy the data over too */
  290.  if (data && datalen)
  291.    memcpy(packet + sizeof(struct ip) + sizeof(struct tcphdr) + optlen, data, datalen);
  292.  /* And the options */
  293.  if (optlen) {
  294.    memcpy(packet + sizeof(struct ip) + sizeof(struct tcphdr), options, optlen);
  295.  }
  296.  
  297. #if STUPID_SOLARIS_CHECKSUM_BUG
  298.  tcp->th_sum = sizeof(struct tcphdr) + optlen + datalen; 
  299. #else
  300. tcp->th_sum = in_cksum((unsigned short *)pseudo, sizeof(struct tcphdr) + 
  301.                optlen + sizeof(struct pseudo_header) + datalen);
  302. #endif
  303. /* Now for the ip header */
  304.  
  305. bzero(packet, sizeof(struct ip)); 
  306. ip->ip_v = 4;
  307. ip->ip_hl = 5;
  308. ip->ip_len = BSDFIX(sizeof(struct ip) + sizeof(struct tcphdr) + optlen + datalen);
  309. get_random_bytes(&(ip->ip_id), 2);
  310. ip->ip_ttl = myttl;
  311. ip->ip_p = IPPROTO_TCP;
  312. ip->ip_src.s_addr = source->s_addr;
  313. ip->ip_dst.s_addr= victim->s_addr;
  314. #if HAVE_IP_IP_SUM
  315. ip->ip_sum = in_cksum((unsigned short *)ip, sizeof(struct ip));
  316. #endif
  317.  
  318. if (TCPIP_DEBUGGING > 1) {
  319.   log_write(LOG_STDOUT, "Raw TCP packet creation completed!  Here it is:\n");
  320.   readtcppacket(packet,BSDUFIX(ip->ip_len));
  321. }
  322.  
  323. res = Sendto("send_tcp_raw", sd, packet, BSDUFIX(ip->ip_len), 0,
  324.          (struct sockaddr *)&sock,  (int)sizeof(struct sockaddr_in));
  325.  
  326. if (source_malloced) free(source);
  327. free(packet);
  328. return res;
  329. }
  330.  
  331. int Sendto(char *functionname, int sd, const unsigned char *packet, int len, 
  332.        unsigned int flags, struct sockaddr *to, int tolen) {
  333.  
  334. struct sockaddr_in *sin = (struct sockaddr_in *) to;
  335. int res;
  336. int retries = 0;
  337. int sleeptime = 0;
  338.  
  339. do {
  340.   if (TCPIP_DEBUGGING > 1) {  
  341.     log_write(LOG_STDOUT, "trying sendto(%d, packet, %d, 0, %s, %d)",
  342.        sd, len, inet_ntoa(sin->sin_addr), tolen);
  343.   }
  344.   if ((res = sendto(sd, (const char *) packet, len, flags, to, tolen)) == -1) {
  345.     error("sendto in %s: sendto(%d, packet, %d, 0, %s, %d) => %s",
  346.       functionname, sd, len, inet_ntoa(sin->sin_addr), tolen,
  347.       strerror(errno));
  348.     if (retries > 2 || errno == EPERM) 
  349.       return -1;
  350.     sleeptime = 15 * (1 << (2 * retries));
  351.     error("Sleeping %d seconds then retrying", sleeptime);
  352.     fflush(stderr);
  353.     sleep(sleeptime);
  354.   }
  355.   retries++;
  356. } while( res == -1);
  357.  
  358. if (TCPIP_DEBUGGING > 1)
  359.   log_write(LOG_STDOUT, "successfully sent %d bytes of raw_tcp!\n", res);
  360.  
  361. return res;
  362. }
  363.  
  364. /* A simple function I wrote to help in debugging, shows the important fields
  365.    of a TCP packet*/
  366. int readtcppacket(unsigned char *packet, int readdata) {
  367.  
  368. struct ip *ip = (struct ip *) packet;
  369. struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct ip));
  370. unsigned char *data = packet +  sizeof(struct ip) + sizeof(struct tcphdr);
  371. int tot_len;
  372. struct in_addr bullshit, bullshit2;
  373. char sourcehost[16];
  374. int i;
  375. int realfrag = 0;
  376.  
  377. if (!packet) {
  378.   fprintf(stderr, "readtcppacket: packet is NULL!\n");
  379.   return -1;
  380.     }
  381.  
  382. bullshit.s_addr = ip->ip_src.s_addr; bullshit2.s_addr = ip->ip_dst.s_addr;
  383. /* this is gay */
  384. realfrag = BSDFIX(ntohs(ip->ip_off) & 8191 /* 2^13 - 1 */);
  385. tot_len = BSDFIX(ip->ip_len);
  386. strncpy(sourcehost, inet_ntoa(bullshit), 16);
  387. i =  4 * (ntohs(ip->ip_hl) + ntohs(tcp->th_off));
  388. if (ip->ip_p== IPPROTO_TCP) {
  389.   if (realfrag) 
  390.     printf("Packet is fragmented, offset field: %u\n", realfrag);
  391.   else {
  392.     printf("TCP packet: %s:%d -> %s:%d (total: %d bytes)\n", sourcehost, 
  393.        ntohs(tcp->th_sport), inet_ntoa(bullshit2), 
  394.        ntohs(tcp->th_dport), tot_len);
  395.     printf("Flags: ");
  396.     if (!tcp->th_flags) printf("(none)");
  397.     if (tcp->th_flags & TH_RST) printf("RST ");
  398.     if (tcp->th_flags & TH_SYN) printf("SYN ");
  399.     if (tcp->th_flags & TH_ACK) printf("ACK ");
  400.     if (tcp->th_flags & TH_PUSH) printf("PSH ");
  401.     if (tcp->th_flags & TH_FIN) printf("FIN ");
  402.     if (tcp->th_flags & TH_URG) printf("URG ");
  403.     printf("\n");
  404.  
  405.     printf("ipid: %hu ttl: %hu ", ntohs(ip->ip_id), ip->ip_ttl);
  406.  
  407.     if (tcp->th_flags & (TH_SYN | TH_ACK)) printf("Seq: %u\tAck: %u\n", 
  408.                           (unsigned int) ntohl(tcp->th_seq), (unsigned int) ntohl(tcp->th_ack));
  409.     else if (tcp->th_flags & TH_SYN) printf("Seq: %u\n", (unsigned int) ntohl(tcp->th_seq));
  410.     else if (tcp->th_flags & TH_ACK) printf("Ack: %u\n", (unsigned int) ntohl(tcp->th_ack));
  411.   }
  412. }
  413. if (readdata && i < tot_len) {
  414. printf("Data portion:\n");
  415. while(i < tot_len)  printf("%2X%c", data[i], (++i%16)? ' ' : '\n');
  416. printf("\n");
  417. }
  418. return 0;
  419. }
  420.  
  421. /* A simple function I wrote to help in debugging, shows the important fields
  422.    of a UDP packet*/
  423. int readudppacket(unsigned char *packet, int readdata) {
  424.  
  425. struct ip *ip = (struct ip *) packet;
  426. udphdr_bsd *udp = (udphdr_bsd *) (packet + sizeof(struct ip));
  427. unsigned char *data = packet +  sizeof(struct ip) + sizeof(udphdr_bsd);
  428. int tot_len;
  429. struct in_addr bullshit, bullshit2;
  430. char sourcehost[16];
  431. int i;
  432. int realfrag = 0;
  433.  
  434. if (!packet) {
  435.   fprintf(stderr, "readudppacket: packet is NULL!\n");
  436.   return -1;
  437.     }
  438.  
  439. bullshit.s_addr = ip->ip_src.s_addr; bullshit2.s_addr = ip->ip_dst.s_addr;
  440. /* this is gay */
  441. realfrag = BSDFIX(ntohs(ip->ip_off) & 8191 /* 2^13 - 1 */);
  442. tot_len = BSDFIX(ip->ip_len);
  443. strncpy(sourcehost, inet_ntoa(bullshit), 16);
  444. i =  4 * (ntohs(ip->ip_hl)) + 8;
  445. if (ip->ip_p== IPPROTO_UDP) {
  446.   if (realfrag) 
  447.     printf("Packet is fragmented, offset field: %u\n", realfrag);
  448.   else {
  449.     printf("UDP packet: %s:%d -> %s:%d (total: %d bytes)\n", sourcehost, 
  450.        ntohs(udp->uh_sport), inet_ntoa(bullshit2), 
  451.        ntohs(udp->uh_dport), tot_len);
  452.  
  453.     printf("ttl: %hu ", ip->ip_ttl);
  454.   }
  455. }
  456.  if (readdata && i < tot_len) {
  457.    printf("Data portion:\n");
  458.    while(i < tot_len)  printf("%2X%c", data[i], (++i%16)? ' ' : '\n');
  459.    printf("\n");
  460.  }
  461.  return 0;
  462. }
  463.  
  464. int send_udp_raw_decoys( int sd, struct in_addr *victim, u16 sport, 
  465.              u16 dport, u8 *data, u16 datalen) {
  466.   int decoy;
  467.   
  468.   for(decoy = 0; decoy < o.numdecoys; decoy++) 
  469.     if (send_udp_raw(sd, &o.decoys[decoy], victim, sport, dport, data, 
  470.              datalen) == -1)
  471.       return -1;
  472.  
  473.   return 0;
  474. }
  475.  
  476.  
  477.  
  478. int send_udp_raw( int sd, struct in_addr *source, struct in_addr *victim, 
  479.           u16 sport, u16 dport, u8 *data, u16 datalen) 
  480. {
  481.  
  482. unsigned char *packet = (unsigned char *) safe_malloc(sizeof(struct ip) + sizeof(udphdr_bsd) + datalen);
  483. struct ip *ip = (struct ip *) packet;
  484. udphdr_bsd *udp = (udphdr_bsd *) (packet + sizeof(struct ip));
  485. static int myttl = 0;
  486.  
  487. int res;
  488. struct sockaddr_in sock;
  489. char myname[MAXHOSTNAMELEN + 1];
  490. struct hostent *myhostent = NULL;
  491. int source_malloced = 0;
  492. struct pseudo_udp_hdr {
  493.   struct in_addr source;
  494.   struct in_addr dest;        
  495.   u8 zero;
  496.   u8 proto;        
  497.   u16 length;
  498. } *pseudo = (struct pseudo_udp_hdr *) ((char *)udp - 12) ;
  499.  
  500. /* check that required fields are there and not too silly */
  501. if ( !victim || !sport || !dport || sd < 0) {
  502.   fprintf(stderr, "send_udp_raw: One or more of your parameters suck!\n");
  503.   free(packet);
  504.   return -1;
  505. }
  506.  
  507.  
  508. if (!myttl) myttl = (get_random_uint() % 23) + 37;
  509.  
  510. /* It was a tough decision whether to do this here for every packet
  511.    or let the calling function deal with it.  In the end I grudgingly decided
  512.    to do it here and potentially waste a couple microseconds... */
  513. sethdrinclude(sd); 
  514.  
  515. /* if they didn't give a source address, fill in our first address */
  516. if (!source) {
  517.   source_malloced = 1;
  518.   source = (struct in_addr *) safe_malloc(sizeof(struct in_addr));
  519.   if (gethostname(myname, MAXHOSTNAMELEN) || 
  520.       !(myhostent = gethostbyname(myname)))
  521.     fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  522.   memcpy(source, myhostent->h_addr_list[0], sizeof(struct in_addr));
  523. #if ( TCPIP_DEBUGGING )
  524.     printf("We skillfully deduced that your address is %s\n", 
  525.        inet_ntoa(*source));
  526. #endif
  527. }
  528.  
  529.  
  530. /*do we even have to fill out this damn thing?  This is a raw packet, 
  531.   after all */
  532. sock.sin_family = AF_INET;
  533. sock.sin_port = htons(dport);
  534. sock.sin_addr.s_addr = victim->s_addr;
  535.  
  536.  
  537. bzero((char *) packet, sizeof(struct ip) + sizeof(udphdr_bsd));
  538.  
  539. udp->uh_sport = htons(sport);
  540. udp->uh_dport = htons(dport);
  541. udp->uh_ulen = htons(8 + datalen);
  542.  
  543.  /* We should probably copy the data over too */
  544. if (data)
  545.   memcpy(packet + sizeof(struct ip) + sizeof(udphdr_bsd), data, datalen);
  546.  
  547. /* Now the psuedo header for checksuming */
  548. pseudo->source.s_addr = source->s_addr;
  549. pseudo->dest.s_addr = victim->s_addr;
  550. pseudo->proto = IPPROTO_UDP;
  551. pseudo->length = htons(sizeof(udphdr_bsd) + datalen);
  552.  
  553. /* OK, now we should be able to compute a valid checksum */
  554. #if STUPID_SOLARIS_CHECKSUM_BUG
  555.  udp->uh_sum = sizeof(struct udphdr) + datalen;
  556. #else
  557. udp->uh_sum = in_cksum((unsigned short *)pseudo, 20 /* pseudo + UDP headers */ + datalen);
  558. #endif
  559.  
  560. /* Goodbye, pseudo header! */
  561. bzero(pseudo, 12);
  562.  
  563. /* Now for the ip header */
  564. ip->ip_v = 4;
  565. ip->ip_hl = 5;
  566. ip->ip_len = BSDFIX(sizeof(struct ip) + sizeof(udphdr_bsd) + datalen);
  567. get_random_bytes(&(ip->ip_id), 2);
  568. ip->ip_ttl = myttl;
  569. ip->ip_p = IPPROTO_UDP;
  570. ip->ip_src.s_addr = source->s_addr;
  571. ip->ip_dst.s_addr= victim->s_addr;
  572. #if HAVE_IP_IP_SUM
  573. ip->ip_sum = in_cksum((unsigned short *)ip, sizeof(struct ip));
  574. #endif
  575.  
  576. if (TCPIP_DEBUGGING > 1) {
  577.   printf("Raw UDP packet creation completed!  Here it is:\n");
  578.   readudppacket(packet,1);
  579. }
  580.  
  581. res = Sendto("send_udp_raw", sd, packet, BSDUFIX(ip->ip_len), 0,
  582.          (struct sockaddr *)&sock,  (int)sizeof(struct sockaddr_in));
  583.  
  584. if (source_malloced) free(source);
  585. free(packet);
  586. return res;
  587. }
  588.  
  589. int send_small_fragz_decoys(int sd, struct in_addr *victim, u32 seq, 
  590.                 u16 sport, u16 dport, int flags) {
  591.   int decoy;
  592.  
  593.   for(decoy = 0; decoy < o.numdecoys; decoy++) 
  594.     if (send_small_fragz(sd, &o.decoys[decoy], victim, seq, sport, 
  595.                 dport, 
  596.                 flags) == -1)
  597.       return -1;
  598.  
  599.   return 0;
  600. }
  601.  
  602. /* Much of this is swiped from my send_tcp_raw function above, which 
  603.    doesn't support fragmentation */
  604. int send_small_fragz(int sd, struct in_addr *source, struct in_addr *victim,
  605.              u32 seq, u16 sport, u16 dport, int flags)
  606.  {
  607.  
  608. struct pseudo_header { 
  609. /*for computing TCP checksum, see TCP/IP Illustrated p. 145 */
  610.   u32 s_addy;
  611.   u32 d_addr;
  612.   u8 zer0;
  613.   u8 protocol;
  614.   u16 length;
  615. };
  616. /*In this placement we get data and some field alignment so we aren't wasting
  617.   too much to compute the TCP checksum.*/
  618.  
  619. unsigned char packet[sizeof(struct ip) + sizeof(struct tcphdr) + 100];
  620. struct ip *ip = (struct ip *) packet;
  621. struct tcphdr *tcp = (struct tcphdr *) (packet + sizeof(struct ip));
  622. struct pseudo_header *pseudo = (struct pseudo_header *) (packet + sizeof(struct ip) - sizeof(struct pseudo_header)); 
  623. unsigned char *frag2 = packet + sizeof(struct ip) + 16;
  624. struct ip *ip2 = (struct ip *) (frag2 - sizeof(struct ip));
  625. static int myttl = 0;
  626. int res;
  627. struct sockaddr_in sock;
  628. int id;
  629.  
  630. if (!myttl)  myttl = (time(NULL) % 14) + 51;
  631.  
  632. /* It was a tough decision whether to do this here for every packet
  633.    or let the calling function deal with it.  In the end I grudgingly decided
  634.    to do it here and potentially waste a couple microseconds... */
  635. sethdrinclude(sd);
  636.  
  637.  
  638. /*Why do we have to fill out this damn thing? This is a raw packet, after all */
  639. sock.sin_family = AF_INET;
  640. sock.sin_port = htons(dport);
  641.  
  642. sock.sin_addr.s_addr = victim->s_addr;
  643.  
  644. bzero((char *)packet, sizeof(struct ip) + sizeof(struct tcphdr));
  645.  
  646. pseudo->s_addy = source->s_addr;
  647. pseudo->d_addr = victim->s_addr;
  648. pseudo->protocol = IPPROTO_TCP;
  649. pseudo->length = htons(sizeof(struct tcphdr));
  650.  
  651. tcp->th_sport = htons(sport);
  652. tcp->th_dport = htons(dport);
  653. tcp->th_seq = (seq)? htonl(seq) : get_random_uint();
  654.  
  655. tcp->th_off = 5 /*words*/;
  656. tcp->th_flags = flags;
  657.  
  658. tcp->th_win = htons(2048); /* Who cares */
  659.  
  660. tcp->th_sum = in_cksum((unsigned short *)pseudo, 
  661.                sizeof(struct tcphdr) + sizeof(struct pseudo_header));
  662.  
  663. /* Now for the ip header of frag1 */
  664.  
  665. bzero((char *) packet, sizeof(struct ip)); 
  666. ip->ip_v = 4;
  667. ip->ip_hl = 5;
  668. /*RFC 791 allows 8 octet frags, but I get "operation not permitted" (EPERM)
  669.   when I try that.  */
  670. ip->ip_len = BSDFIX(sizeof(struct ip) + 16);
  671. id = ip->ip_id = get_random_uint();
  672. ip->ip_off = BSDFIX(MORE_FRAGMENTS);
  673. ip->ip_ttl = myttl;
  674. ip->ip_p = IPPROTO_TCP;
  675. ip->ip_src.s_addr = source->s_addr;
  676. ip->ip_dst.s_addr = victim->s_addr;
  677.  
  678. #if HAVE_IP_IP_SUM
  679. ip->ip_sum= in_cksum((unsigned short *)ip, sizeof(struct ip));
  680. #endif
  681. if (o.debugging > 1) {
  682.   log_write(LOG_STDOUT, "Raw TCP packet fragment #1 creation completed!  Here it is:\n");
  683.   hdump(packet,20);
  684. }
  685. if (o.debugging > 1) 
  686.   log_write(LOG_STDOUT, "\nTrying sendto(%d , packet, %d, 0 , %s , %d)\n",
  687.      sd, ntohs(ip->ip_len), inet_ntoa(*victim),
  688.      (int) sizeof(struct sockaddr_in));
  689. /* Lets save this and send it AFTER we send the second one, just to be
  690.    cute ;) */
  691.  
  692. if ((res = sendto(sd, (const char *) packet,sizeof(struct ip) + 16 , 0, 
  693.           (struct sockaddr *)&sock, sizeof(struct sockaddr_in))) == -1)
  694.   {
  695.     perror("sendto in send_syn_fragz");
  696.     return -1;
  697.   }
  698. if (o.debugging > 1) log_write(LOG_STDOUT, "successfully sent %d bytes of raw_tcp!\n", res);
  699.  
  700. /* Create the second fragment */
  701.  
  702. bzero((char *) ip2, sizeof(struct ip));
  703. ip2->ip_v= 4;
  704. ip2->ip_hl = 5;
  705. ip2->ip_len = BSDFIX(sizeof(struct ip) + 4); /* the rest of our TCP packet */
  706. ip2->ip_id = id;
  707. ip2->ip_off = BSDFIX(2);
  708. ip2->ip_ttl = myttl;
  709. ip2->ip_p = IPPROTO_TCP;
  710. ip2->ip_src.s_addr = source->s_addr;
  711. ip2->ip_dst.s_addr = victim->s_addr;
  712.  
  713. #if HAVE_IP_IP_SUM
  714. ip2->ip_sum = in_cksum((unsigned short *)ip2, sizeof(struct ip));
  715. #endif
  716. if (o.debugging > 1) {
  717.   log_write(LOG_STDOUT, "Raw TCP packet fragment creation completed!  Here it is:\n");
  718.   hdump(packet,20);
  719. }
  720. if (o.debugging > 1) 
  721.  
  722.   log_write(LOG_STDOUT, "\nTrying sendto(%d , ip2, %d, 0 , %s , %d)\n", sd, 
  723.      ntohs(ip2->ip_len), inet_ntoa(*victim), (int) sizeof(struct sockaddr_in));
  724. if ((res = sendto(sd, (const char *)ip2,sizeof(struct ip) + 4 , 0, 
  725.           (struct sockaddr *)&sock, (int) sizeof(struct sockaddr_in))) == -1)
  726.   {
  727.     perror("sendto in send_tcp_raw frag #2");
  728.     return -1;
  729.   }
  730.  
  731. return 1;
  732. }
  733.  
  734. int send_ip_raw_decoys( int sd, struct in_addr *victim, u8 proto,
  735.             u8 *data, u16 datalen) {
  736.  
  737.   int decoy;
  738.  
  739.   for(decoy = 0; decoy < o.numdecoys; decoy++) 
  740.     if (send_ip_raw(sd, &o.decoys[decoy], victim, proto, data, 
  741.                datalen) == -1)
  742.       return -1;
  743.  
  744.   return 0;
  745.  
  746.  
  747. }
  748.  
  749. int send_ip_raw( int sd, struct in_addr *source, struct in_addr *victim, 
  750.          u8 proto, u8 *data, u16 datalen) 
  751. {
  752.  
  753. unsigned char *packet = (unsigned char *) safe_malloc(sizeof(struct ip) + datalen);
  754. struct ip *ip = (struct ip *) packet;
  755. static int myttl = 0;
  756.  
  757. int res = -1;
  758. struct sockaddr_in sock;
  759. char myname[MAXHOSTNAMELEN + 1];
  760. struct hostent *myhostent = NULL;
  761. int source_malloced = 0;
  762.  
  763. /* check that required fields are there and not too silly */
  764. if ( !victim || sd < 0) {
  765.   fprintf(stderr, "send_ip_raw: One or more of your parameters suck!\n");
  766.   free(packet);
  767.   return -1;
  768. }
  769.  
  770. if (!myttl) myttl = (get_random_uint() % 23) + 37;
  771.  
  772. /* It was a tough decision whether to do this here for every packet
  773.    or let the calling function deal with it.  In the end I grudgingly decided
  774.    to do it here and potentially waste a couple microseconds... */
  775. sethdrinclude(sd); 
  776.  
  777. /* if they didn't give a source address, fill in our first address */
  778. if (!source) {
  779.   source_malloced = 1;
  780.   source = (struct in_addr *) safe_malloc(sizeof(struct in_addr));
  781.   if (gethostname(myname, MAXHOSTNAMELEN) || 
  782.       !(myhostent = gethostbyname(myname)))
  783.     fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  784.   memcpy(source, myhostent->h_addr_list[0], sizeof(struct in_addr));
  785. #if ( TCPIP_DEBUGGING )
  786.     printf("We skillfully deduced that your address is %s\n", 
  787.        inet_ntoa(*source));
  788. #endif
  789. }
  790.  
  791.  
  792. /*do we even have to fill out this damn thing?  This is a raw packet, 
  793.   after all */
  794. sock.sin_family = AF_INET;
  795. sock.sin_port = 0;
  796. sock.sin_addr.s_addr = victim->s_addr;
  797.  
  798.  
  799. bzero((char *) packet, sizeof(struct ip));
  800.  
  801. /* Now for the ip header */
  802.  
  803. ip->ip_v = 4;
  804. ip->ip_hl = 5;
  805. ip->ip_len = BSDFIX(sizeof(struct ip) + datalen);
  806. get_random_bytes(&(ip->ip_id), 2);
  807. ip->ip_ttl = myttl;
  808. ip->ip_p = proto;
  809. ip->ip_src.s_addr = source->s_addr;
  810. ip->ip_dst.s_addr= victim->s_addr;
  811. #if HAVE_IP_IP_SUM
  812. ip->ip_sum = in_cksum((unsigned short *)ip, sizeof(struct ip));
  813. #endif
  814.  
  815.  /* We should probably copy the data over too */
  816.  if (data)
  817.    memcpy(packet + sizeof(struct ip), data, datalen);
  818.  
  819. if (TCPIP_DEBUGGING > 1) {
  820.   printf("Raw IP packet creation completed!  Here it is:\n");
  821.   hdump(packet, BSDUFIX(ip->ip_len));
  822. }
  823.  
  824.  
  825. res = Sendto("send_ip_raw", sd, packet, BSDUFIX(ip->ip_len), 0,
  826.          (struct sockaddr *)&sock,  (int)sizeof(struct sockaddr_in));
  827.  
  828. if (source_malloced) free(source);
  829. free(packet); 
  830. return res;
  831. }
  832.  
  833. int unblock_socket(int sd) {
  834. int options;
  835. /*Unblock our socket to prevent recvfrom from blocking forever
  836.   on certain target ports. */
  837. options = O_NONBLOCK | fcntl(sd, F_GETFL);
  838. fcntl(sd, F_SETFL, options);
  839. return 1;
  840. }
  841.  
  842.  
  843. /* Get the source address and interface name */
  844. #if 0
  845. char *getsourceif(struct in_addr *src, struct in_addr *dst) {
  846. int sd, sd2;
  847. u16 p1;
  848. struct sockaddr_in sock;
  849. int socklen = sizeof(struct sockaddr_in);
  850. struct sockaddr sa;
  851. int sasize = sizeof(struct sockaddr);
  852. int ports, res;
  853. u8 buf[65536];
  854. struct timeval tv;
  855. unsigned int start;
  856. int data_offset, ihl, *intptr;
  857. int done = 0;
  858.  
  859.   /* Get us some unreserved port numbers */
  860.   get_random_bytes(&p1, 2);
  861.   if (p1 < 5000) p1 += 5000;
  862.  
  863.   if (!getuid()) {
  864.     if ((sd2 = socket(AF_INET, SOCK_PACKET, htons(ETH_P_ALL))) == -1)
  865.       {perror("Linux Packet Socket troubles"); return 0;}
  866.     unblock_socket(sd2);
  867.     if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
  868.       {perror("Socket troubles"); return 0;}
  869.     sock.sin_family = AF_INET;
  870.     sock.sin_addr = *dst;
  871.     sock.sin_port = htons(p1);
  872.     if (connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in)) == -1)
  873.       { perror("UDP connect()");
  874.       close(sd);
  875.       close(sd2);
  876.       return NULL;
  877.       }
  878.     if (getsockname(sd, (SA *)&sock, &socklen) == -1) {
  879.       perror("getsockname");
  880.       close(sd);
  881.       close(sd2);
  882.       return NULL;
  883.     }
  884.     ports = (ntohs(sock.sin_port) << 16) + p1;
  885. #if ( TCPIP_DEBUGGING )
  886.       printf("ports is %X\n", ports);
  887. #endif
  888.     if (send(sd, "", 0, 0) == -1)
  889.     fatal("Could not send UDP packet");
  890.     start = time(NULL);
  891.     do {
  892.       tv.tv_sec = 2;
  893.       tv.tv_usec = 0;
  894.       res = recvfrom(sd2, buf, 65535, 0, &sa, &sasize);
  895.       if (res < 0) {
  896.     if (errno != EWOULDBLOCK)
  897.       perror("recvfrom");
  898.       }
  899.       if (res > 0) {
  900. #if ( TCPIP_DEBUGGING )
  901.     printf("Got packet!\n");
  902.     printf("sa.sa_data: %s\n", sa.sa_data);
  903.     printf("Hex dump of packet (len %d):\n", res);
  904.     hdump(buf, res);
  905. #endif
  906.     data_offset = get_link_offset(sa.sa_data);
  907.     ihl = (*(buf + data_offset) & 0xf) * 4;
  908.     /* If it is big enough and it is IPv4 */
  909.     if (res >=  data_offset + ihl + 4 &&
  910.         (*(buf + data_offset) & 0x40)) {
  911.       intptr = (int *)  ((char *) buf + data_offset + ihl);
  912.       if (*intptr == ntohl(ports)) {
  913.         intptr = (int *) ((char *) buf + data_offset + 12);
  914. #if ( TCPIP_DEBUGGING )
  915.         printf("We've found our packet [krad]\n");
  916. #endif
  917.         memcpy(src, buf + data_offset + 12, 4);
  918.         close(sd);
  919.         close(sd2);
  920.         return strdup(sa.sa_data);
  921.       }
  922.     }
  923.       }        
  924.     } while(!done && time(NULL) - start < 2);
  925.     close(sd);
  926.     close(sd2);
  927.   }
  928.  
  929. return NULL;
  930. }
  931. #endif /* 0 */
  932. #endif /* WIN32 */
  933.  
  934. int getsourceip(struct in_addr *src, struct in_addr *dst) {
  935.   int sd;
  936.   struct sockaddr_in sock;
  937.   NET_SIZE_T socklen = sizeof(struct sockaddr_in);
  938.   u16 p1;
  939.  
  940.   get_random_bytes(&p1, sizeof(p1));
  941.   if (p1 < 5000) p1 += 5000;
  942.  
  943.   if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
  944.     {perror("Socket troubles"); return 0;}
  945.   sock.sin_family = AF_INET;
  946.   sock.sin_addr = *dst;
  947.   sock.sin_port = htons(p1);
  948.   if (connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in)) == -1)
  949.     { perror("UDP connect()");
  950.     close(sd);
  951.     return 0;
  952.     }
  953.   bzero(&sock, sizeof(struct sockaddr_in));
  954.   if (getsockname(sd, (SA *)&sock, &socklen) == -1) {
  955.     perror("getsockname");
  956.     close(sd);
  957.     return 0;
  958.   }
  959.  
  960.   src->s_addr = sock.sin_addr.s_addr;
  961.   close(sd);
  962.   return 1; /* Calling function responsible for checking validity */
  963. }
  964.  
  965. #if 0
  966. int get_link_offset(char *device) {
  967. int sd;
  968. struct ifreq ifr;
  969. sd = socket(AF_INET, SOCK_DGRAM, 0);
  970. memset(&ifr, 0, sizeof(ifr));
  971. strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  972. #if (defined(SIOCGIFHWADDR) && defined(ARPHRD_ETHER) && 
  973.      defined(ARPHRD_METRICOM) && defined(ARPHRD_SLIP) && defined(ARPHRD_CSLIP)
  974.      && defined(ARPHRD_SLIP6) && defined(ARPHRD_PPP) && 
  975.      defined(ARPHRD_LOOPBACK) )
  976. if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0 ) {
  977.   fatal("Can't obtain link offset.  What kind of interface are you using?");
  978.   }
  979. close(sd);
  980. switch (ifr.ifr_hwaddr.sa_family) {
  981. case ARPHRD_ETHER:  /* These two are standard ethernet */
  982. case ARPHRD_METRICOM:
  983.   return 14;
  984.   break;
  985. case ARPHRD_SLIP:
  986. case ARPHRD_CSLIP:
  987. case ARPHRD_SLIP6:
  988. case ARPHRD_CSLIP6:
  989. case ARPHRD_PPP:
  990.   return 0;
  991.   break;
  992. case ARPHRD_LOOPBACK:  /* Loopback interface (obviously) */
  993.   return 14;
  994.   break;
  995. default:
  996.   fatal("Unknown link layer device: %d", ifr.ifr_hwaddr.sa_family);
  997. }
  998. #else
  999. printf("get_link_offset called even though your host doesn't support it.  Assuming Ethernet or Loopback connection (wild guess)\n");
  1000. return 14;
  1001. #endif
  1002. /* Not reached */
  1003. exit(1);
  1004. }
  1005. #endif
  1006.  
  1007. /* Read an IP packet using libpcap .  We return the packet and take
  1008.    a pcap descripter and a pointer to the packet length (which we set
  1009.    in the function. If you want a maximum length returned, you
  1010.    should specify that in pcap_open_live() */
  1011.  
  1012. /* to_usec is the timeout period in microseconds -- use 0 to skip the
  1013.    test and -1 to block forever.  Note that we don't interrupt pcap, so
  1014.    low values (and 0) degenerate to the timeout specified 
  1015.    in pcap_open_live()
  1016.  */
  1017.  
  1018. #ifndef WIN32 /* Windows version of next few funcstions is currently 
  1019.                  in wintcpip.c.  Should be merged at some point. */
  1020. char *readip_pcap(pcap_t *pd, unsigned int *len, long to_usec) {
  1021. int offset = -1;
  1022. struct pcap_pkthdr head;
  1023. char *p;
  1024. int datalink;
  1025. int timedout = 0;
  1026. struct timeval tv_start, tv_end;
  1027. static char *alignedbuf = NULL;
  1028. static int alignedbufsz=0;
  1029.  
  1030. if (!pd) fatal("NULL packet device passed to readip_pcap");
  1031.  
  1032. /* New packet capture device, need to recompute offset */
  1033.  if ( (datalink = pcap_datalink(pd)) < 0)
  1034.    fatal("Cannot obtain datalink information: %s", pcap_geterr(pd));
  1035.  switch(datalink) {
  1036.  case DLT_EN10MB: offset = 14; break;
  1037.  case DLT_IEEE802: offset = 22; break;
  1038. #ifdef DLT_LOOP
  1039.  case DLT_LOOP:
  1040. #endif
  1041.  case DLT_NULL: offset = 4; break;
  1042.  case DLT_SLIP:
  1043. #ifdef DLT_SLIP_BSDOS
  1044.  case DLT_SLIP_BSDOS:
  1045. #endif
  1046. #if (FREEBSD || OPENBSD || NETBSD || BSDI)
  1047.    offset = 16;
  1048. #else
  1049.    offset = 24; /* Anyone use this??? */
  1050. #endif
  1051.    break;
  1052.  case DLT_PPP: 
  1053. #ifdef DLT_PPP_BSDOS
  1054.  case DLT_PPP_BSDOS:
  1055. #endif
  1056. #ifdef DLT_PPP_SERIAL
  1057.  case DLT_PPP_SERIAL:
  1058. #endif
  1059. #ifdef DLT_PPP_ETHER
  1060.  case DLT_PPP_ETHER:
  1061. #endif
  1062. #if (FREEBSD || OPENBSD || NETBSD || BSDI)
  1063.    offset = 4;
  1064. #else
  1065. #ifdef SOLARIS
  1066.    offset = 8;
  1067. #else
  1068.    offset = 24; /* Anyone use this? */
  1069. #endif /* ifdef solaris */
  1070. #endif /* if freebsd || openbsd || netbsd || bsdi */
  1071.    break;
  1072.  case DLT_RAW: offset = 0; break;
  1073.  case DLT_FDDI: offset = 21; break;
  1074. #ifdef DLT_ENC
  1075.  case DLT_ENC: offset = 12; break;
  1076. #endif /* DLT_ENC */
  1077. #ifdef DLT_LINUX_SLL
  1078.  case DLT_LINUX_SLL: offset = 16; break;
  1079. #endif
  1080.  default:
  1081.    p = (char *) pcap_next(pd, &head);
  1082.    if (head.caplen == 0) {
  1083.      /* Lets sleep a brief time and try again to increase the chance of seeing
  1084.     a real packet ... */
  1085.      usleep(500000);
  1086.      p = (char *) pcap_next(pd, &head);
  1087.    }
  1088.    if (head.caplen > 100000) {
  1089.      fatal("FATAL: readip_pcap: bogus caplen from libpcap (%d) on interface type %d", head.caplen, datalink);
  1090.    } 
  1091.    error("FATAL:  Unknown datalink type (%d). Caplen: %d; Packet:\n", datalink, head.caplen);
  1092.    lamont_hdump(p, head.caplen);
  1093.    exit(1);
  1094.  }
  1095.  
  1096.  if (to_usec > 0) {
  1097.    gettimeofday(&tv_start, NULL);
  1098.  }
  1099.  do {
  1100.    p = (char *) pcap_next(pd, &head);
  1101.    if (p)
  1102.      p += offset;
  1103.    if (!p || (*p & 0x40) != 0x40) {
  1104.      /* Should we timeout? */
  1105.      if (to_usec == 0) {
  1106.        timedout = 1;
  1107.      } else if (to_usec > 0) {
  1108.        gettimeofday(&tv_end, NULL);
  1109.        if (TIMEVAL_SUBTRACT(tv_end, tv_start) >= to_usec) {
  1110.      timedout = 1;     
  1111.        }
  1112.      }
  1113.    }
  1114.  } while(!timedout && (!p || (*p & 0x40) != 0x40)); /* Go until we get IPv4 packet */
  1115.  if (timedout) {
  1116.    *len = 0;
  1117.    return NULL;
  1118.  }
  1119.  *len = head.caplen - offset;
  1120.  if (*len > alignedbufsz) {
  1121.    alignedbuf = realloc(alignedbuf, *len);
  1122.    if (!alignedbuf) {
  1123.      fatal("Unable to realloc %d bytes of mem", *len);
  1124.    }
  1125.    alignedbufsz = *len;
  1126.  }
  1127.  memcpy(alignedbuf, p, *len);
  1128.  return alignedbuf;
  1129. }
  1130.  
  1131. /* Set a pcap filter */
  1132. void set_pcap_filter(struct hoststruct *target,
  1133.              pcap_t *pd, PFILTERFN filter, char *bpf, ...)
  1134. {
  1135.   va_list ap;
  1136.   char buf[512];
  1137.   struct bpf_program fcode;
  1138.   unsigned int localnet, netmask;
  1139.   char err0r[256];
  1140.   
  1141.   if (pcap_lookupnet(target->device, &localnet, &netmask, err0r) < 0)
  1142.     fatal("Failed to lookup device subnet/netmask: %s", err0r);
  1143.   
  1144.   va_start(ap, bpf);
  1145.   vsprintf(buf, bpf, ap);
  1146.   va_end(ap);
  1147.   
  1148.   if (o.debugging)
  1149.     log_write(LOG_STDOUT, "Packet capture filter: %s\n", buf);
  1150.   
  1151.   /* Due to apparent bug in libpcap */
  1152.   if (islocalhost(&(target->host)))
  1153.     buf[0] = '\0';
  1154.   
  1155.   if (pcap_compile(pd, &fcode, buf, 0, netmask) < 0)
  1156.     fatal("Error compiling our pcap filter: %s\n", pcap_geterr(pd));
  1157.   if (pcap_setfilter(pd, &fcode) < 0 )
  1158.     fatal("Failed to set the pcap filter: %s\n", pcap_geterr(pd));
  1159. }
  1160.  
  1161. #endif /* WIN32 */
  1162.  
  1163. /* This is ugly :(.  We need to get rid of these at some poitn */
  1164. unsigned long flt_dsthost, flt_srchost, flt_baseport;
  1165.  
  1166. int flt_icmptcp(const char *packet, int len)
  1167. {
  1168.   struct ip* ip = (struct ip*)packet;
  1169.   if(ip->ip_dst.s_addr != flt_dsthost) return 0;
  1170.   if(ip->ip_p == IPPROTO_ICMP) return 1;
  1171.   if(ip->ip_src.s_addr != flt_srchost) return 0;
  1172.   if(ip->ip_p == IPPROTO_TCP) return 1;
  1173.   return 0;
  1174. }
  1175.  
  1176. int flt_icmptcp_2port(const char *packet, int len)
  1177. {
  1178.   struct ip* ip = (struct ip*)packet;
  1179.   if(ip->ip_dst.s_addr != flt_dsthost) return 0;
  1180.   if(ip->ip_p == IPPROTO_ICMP) return 1;
  1181.   if(ip->ip_src.s_addr != flt_srchost) return 0;
  1182.   if(ip->ip_p == IPPROTO_TCP)
  1183.     {
  1184.       struct tcphdr* tcp = (struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl);
  1185.       if(len < 4 * ip->ip_hl + 4) return 0;
  1186.       if(tcp->th_dport == flt_baseport || tcp->th_dport == flt_baseport + 1)
  1187.     return 1;
  1188.     }
  1189.   
  1190.   return 0;
  1191. }
  1192.  
  1193. int flt_icmptcp_5port(const char *packet, int len)
  1194. {
  1195.   unsigned short dport;
  1196.   struct ip* ip = (struct ip*)packet;
  1197.   if(ip->ip_dst.s_addr != flt_dsthost) return 0;
  1198.   if(ip->ip_p == IPPROTO_ICMP) return 1;
  1199.   if(ip->ip_p == IPPROTO_TCP)
  1200.     {
  1201.       struct tcphdr* tcp = (struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl);
  1202.       if(len < 4 * ip->ip_hl + 4) return 0;
  1203.       dport = ntohs(tcp->th_dport);
  1204.       if(dport >= flt_baseport && dport <= flt_baseport + 4) return 1;
  1205.     }
  1206.   
  1207.   return 0;
  1208. }
  1209.  
  1210.  
  1211. #ifndef WIN32 /* Currently the Windows code for next few functions is 
  1212.                  in wintcpip.c -- should probably be merged at some
  1213.                  point */
  1214. int ipaddr2devname( char *dev, struct in_addr *addr ) {
  1215. struct interface_info *mydevs;
  1216. int numdevs;
  1217. int i;
  1218. mydevs = getinterfaces(&numdevs);
  1219.  
  1220. if (!mydevs) return -1;
  1221.  
  1222. for(i=0; i < numdevs; i++) {
  1223.   if (addr->s_addr == mydevs[i].addr.s_addr) {
  1224.     strcpy(dev, mydevs[i].name);
  1225.     return 0;
  1226.   }
  1227. }
  1228. return -1;
  1229. }
  1230.  
  1231. int devname2ipaddr(char *dev, struct in_addr *addr) {
  1232. struct interface_info *mydevs;
  1233. int numdevs;
  1234. int i;
  1235. mydevs = getinterfaces(&numdevs);
  1236.  
  1237. if (!mydevs) return -1;
  1238.  
  1239. for(i=0; i < numdevs; i++) {
  1240.   if (!strcmp(dev, mydevs[i].name)) {  
  1241.     memcpy(addr, (char *) &mydevs[i].addr, sizeof(struct in_addr));
  1242.     return 0;
  1243.   }
  1244. }
  1245. return -1;
  1246. }
  1247. #endif /* WIN32 */
  1248.  
  1249. #ifndef WIN32 /* ifdef'd out for now because 'doze apparently doesn't
  1250.                  support ioctl() */
  1251. struct interface_info *getinterfaces(int *howmany) {
  1252.   static int initialized = 0;
  1253.   static struct interface_info mydevs[128];
  1254.   static int numinterfaces = 0;
  1255.   int sd;
  1256.   int len;
  1257.   char *p;
  1258.   char buf[10240];
  1259.   struct ifconf ifc;
  1260.   struct ifreq *ifr;
  1261.   struct sockaddr_in *sin;
  1262.  
  1263.   if (!initialized) {
  1264.  
  1265.     initialized = 1;
  1266.     /* Dummy socket for ioctl */
  1267.     sd = socket(AF_INET, SOCK_DGRAM, 0);
  1268.     if (sd < 0) pfatal("socket in getinterfaces");
  1269.     ifc.ifc_len = sizeof(buf);
  1270.     ifc.ifc_buf = buf;
  1271.     if (ioctl(sd, SIOCGIFCONF, &ifc) < 0) {
  1272.       fatal("Failed to determine your configured interfaces!\n");
  1273.     }
  1274.     close(sd);
  1275.     ifr = (struct ifreq *) buf;
  1276.     if (ifc.ifc_len == 0) 
  1277.       fatal("getinterfaces: SIOCGIFCONF claims you have no network interfaces!\n");
  1278. #if HAVE_SOCKADDR_SA_LEN
  1279.     /*    len = MAX(sizeof(struct sockaddr), ifr->ifr_addr.sa_len);*/
  1280.     len = ifr->ifr_addr.sa_len + sizeof(ifr->ifr_name);
  1281. #else
  1282.     len = sizeof(struct ifreq);
  1283.     /* len = sizeof(SA); */
  1284. #endif
  1285.  
  1286. #if TCPIP_DEBUGGING
  1287.     printf("ifnet list length = %d\n",ifc.ifc_len);
  1288.     printf("sa_len = %d\n",len);
  1289.     hdump(buf, ifc.ifc_len);
  1290.     printf("ifr = %X\n",(unsigned int)(*(char **)&ifr));
  1291.     printf("Size of struct ifreq: %d\n", sizeof(struct ifreq));
  1292. #endif
  1293.  
  1294.     for(; ifr && *((char *)ifr) && ((char *)ifr) < buf + ifc.ifc_len; 
  1295.     ((*(char **)&ifr) += len )) {
  1296. #if TCPIP_DEBUGGING
  1297.       printf("ifr_name size = %d\n", sizeof(ifr->ifr_name));
  1298.       printf("ifr = %X\n",(unsigned int)(*(char **)&ifr));
  1299. #endif
  1300.  
  1301.       /* skip any device with no name */
  1302.       if (!*((char *)ifr))
  1303.         continue;
  1304.  
  1305.       sin = (struct sockaddr_in *) &ifr->ifr_addr;
  1306.       memcpy(&(mydevs[numinterfaces].addr), (char *) &(sin->sin_addr), sizeof(struct in_addr));
  1307.       /* In case it is a stinkin' alias */
  1308.       if ((p = strchr(ifr->ifr_name, ':')))
  1309.     *p = '\0';
  1310.       strncpy(mydevs[numinterfaces].name, ifr->ifr_name, 63);
  1311.       mydevs[numinterfaces].name[63] = '\0';
  1312.  
  1313.  
  1314. #if TCPIP_DEBUGGING
  1315.       printf("Interface %d is %s\n",numinterfaces,mydevs[numinterfaces].name);
  1316. #endif
  1317.  
  1318.       numinterfaces++;
  1319.       if (numinterfaces == 127)  {      
  1320.     error("My God!  You seem to have WAY too many interfaces!  Things may not work right\n");
  1321.     break;
  1322.       }
  1323. #if HAVE_SOCKADDR_SA_LEN
  1324.       /* len = MAX(sizeof(struct sockaddr), ifr->ifr_addr.sa_len);*/
  1325.       len = ifr->ifr_addr.sa_len + sizeof(ifr->ifr_name);
  1326. #endif 
  1327.       mydevs[numinterfaces].name[0] = '\0';
  1328.     }
  1329.   }
  1330.   if (howmany) *howmany = numinterfaces;
  1331.   return mydevs;
  1332. }
  1333. #endif
  1334.  
  1335.  
  1336. /* An awesome function to determine what interface a packet to a given
  1337.    destination should be routed through.  It returns NULL if no appropriate
  1338.    interface is found, oterwise it returns the device name and fills in the
  1339.    source parameter.   Some of the stuff is
  1340.    from Stevens' Unix Network Programming V2.  He had an easier suggestion
  1341.    for doing this (in the book), but it isn't portable :( */
  1342. #ifndef WIN32 /* Windows functionality is currently in wintcpip.c --
  1343.                  should probably be merged at some point */
  1344.  
  1345. #define ROUTETHROUGH_MAXROUTES 1024
  1346. char *routethrough(struct in_addr *dest, struct in_addr *source) {
  1347.   static int initialized = 0;
  1348.   int i;
  1349.   struct in_addr addy;
  1350.   static enum { procroutetechnique, connectsockettechnique, guesstechnique } technique = procroutetechnique;
  1351.   char buf[10240];
  1352.   struct interface_info *mydevs;
  1353.   static struct myroute {
  1354.     struct interface_info *dev;
  1355.     u32 mask;
  1356.     u32 dest;
  1357.   } myroutes[ROUTETHROUGH_MAXROUTES];
  1358.   int numinterfaces = 0;
  1359.   char *p, *endptr;
  1360.   char iface[64];
  1361.   static int numroutes = 0;
  1362.   FILE *routez;
  1363.  
  1364.   if (!dest) fatal("ipaddr2devname passed a NULL dest address");
  1365.  
  1366.   if (!initialized) {  
  1367.     /* Dummy socket for ioctl */
  1368.     initialized = 1;
  1369.     mydevs = getinterfaces(&numinterfaces);
  1370.  
  1371.     /* Now we must go through several techniques to determine info */
  1372.     routez = fopen("/proc/net/route", "r");
  1373.  
  1374.     if (routez) {
  1375.       /* OK, linux style /proc/net/route ... we can handle this ... */
  1376.       /* Now that we've got the interfaces, we g0 after the r0ut3Z */
  1377.       
  1378.       fgets(buf, sizeof(buf), routez); /* Kill the first line */
  1379.       while(fgets(buf,sizeof(buf), routez)) {
  1380.     p = strtok(buf, " \t\n");
  1381.     if (!p) {
  1382.       error("Could not find interface in /proc/net/route line");
  1383.       continue;
  1384.     }
  1385.     if (*p == '*')
  1386.       continue; /* Deleted route -- any other valid reason for
  1387.                a route to start with an asterict? */
  1388.     Strncpy(iface, p, sizeof(iface));
  1389.     if ((p = strchr(iface, ':'))) {
  1390.       *p = '\0'; /* To support IP aliasing */
  1391.     }
  1392.     p = strtok(NULL, " \t\n");
  1393.     endptr = NULL;
  1394.     myroutes[numroutes].dest = strtoul(p, &endptr, 16);
  1395.     if (!endptr || *endptr) {
  1396.       error("Failed to determine Destination from /proc/net/route");
  1397.       continue;
  1398.     }
  1399.     for(i=0; i < 6; i++) {
  1400.       p = strtok(NULL, " \t\n");
  1401.       if (!p) break;
  1402.     }
  1403.     if (!p) {
  1404.       error("Failed to find field %d in /proc/net/route", i + 2);
  1405.       continue;
  1406.     }
  1407.     endptr = NULL;
  1408.     myroutes[numroutes].mask = strtoul(p, &endptr, 16);
  1409.     if (!endptr || *endptr) {
  1410.       error("Failed to determine mask from /proc/net/route");
  1411.       continue;
  1412.     }
  1413.  
  1414.  
  1415. #if TCPIP_DEBUGGING
  1416.       printf("#%d: for dev %s, The dest is %X and the mask is %X\n", numroutes, iface, myroutes[numroutes].dest, myroutes[numroutes].mask);
  1417. #endif
  1418.       for(i=0; i < numinterfaces; i++)
  1419.         if (!strcmp(iface, mydevs[i].name)) {
  1420.           myroutes[numroutes].dev = &mydevs[i];
  1421.           break;
  1422.         }
  1423.       if (i == numinterfaces) 
  1424.         fatal("Failed to find interface %s mentioned in /proc/net/route\n", iface);
  1425.       numroutes++;
  1426.       if (numroutes == ROUTETHROUGH_MAXROUTES)
  1427.         fatal("My God!  You seem to have WAY too many routes!\n");
  1428.       }
  1429.       fclose(routez);
  1430.     } else {
  1431.       technique = connectsockettechnique;
  1432.     }
  1433.   } else {  
  1434.     mydevs = getinterfaces(&numinterfaces);
  1435.   }
  1436.   /* WHEW, that takes care of initializing, now we have the easy job of 
  1437.      finding which route matches */
  1438.   if (islocalhost(dest)) {
  1439.     if (source)
  1440.       source->s_addr = htonl(0x7F000001);
  1441.     /* Now we find the localhost interface name, assuming 127.0.0.1 is
  1442.        localhost (it damn well better be!)... */
  1443.     for(i=0; i < numinterfaces; i++) {    
  1444.       if (mydevs[i].addr.s_addr == htonl(0x7F000001)) {
  1445.     return mydevs[i].name;
  1446.       }
  1447.     }
  1448.     return NULL;
  1449.   }
  1450.  
  1451.   if (technique == procroutetechnique) {    
  1452.     for(i=0; i < numroutes; i++) {  
  1453.       if ((dest->s_addr & myroutes[i].mask) == myroutes[i].dest) {
  1454.     if (source) {
  1455.       source->s_addr = myroutes[i].dev->addr.s_addr;
  1456.     }
  1457.     return myroutes[i].dev->name;      
  1458.       }
  1459.     }
  1460.   } else if (technique == connectsockettechnique) {
  1461.       if (!getsourceip(&addy, dest))
  1462.     return NULL;
  1463.       if (!addy.s_addr)  {  /* Solaris 2.4 */
  1464.         struct hostent *myhostent = NULL;
  1465.         char myname[MAXHOSTNAMELEN + 1];
  1466.         if (gethostname(myname, MAXHOSTNAMELEN) || 
  1467.            !(myhostent = gethostbyname(myname)))
  1468.       fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  1469.         memcpy(&(addy.s_addr), myhostent->h_addr_list[0], sizeof(struct in_addr));
  1470. #if ( TCPIP_DEBUGGING )
  1471.       printf("We skillfully deduced that your address is %s\n", 
  1472.         inet_ntoa(*source));
  1473. #endif
  1474.       }
  1475.  
  1476.       /* Now we insure this claimed address is a real interface ... */
  1477.       for(i=0; i < numinterfaces; i++)
  1478.     if (mydevs[i].addr.s_addr == addy.s_addr) {
  1479.       if (source) {
  1480.         source->s_addr = addy.s_addr;      
  1481.       }
  1482.       return mydevs[i].name;
  1483.     }  
  1484.       return NULL;
  1485.     } else 
  1486.       fatal("I know sendmail technique ... I know rdist technique ... but I don't know what the hell kindof technique you are attempting!!!");
  1487.     return NULL;
  1488. }
  1489. #endif /* WIN32 */
  1490.  
  1491. /* Maximize the receive buffer of a socket descriptor (up to 500K) */
  1492. void max_rcvbuf(int sd) {
  1493.   int optval = 524288 /*2^19*/;
  1494.   NET_SIZE_T optlen = sizeof(int);
  1495.  
  1496. #ifndef WIN32
  1497.   if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (const char *) &optval, optlen))
  1498.     if (o.debugging) perror("Problem setting large socket recieve buffer");
  1499.   if (o.debugging) {
  1500.     getsockopt(sd, SOL_SOCKET, SO_RCVBUF,(char *) &optval, &optlen);
  1501.     log_write(LOG_STDOUT, "Our buffer size is now %d\n", optval);
  1502.   }
  1503. #endif /* WIN32 */
  1504. }
  1505.  
  1506. /* Maximize the open file descriptor limit for this process go up to the
  1507.    max allowed  */
  1508. int max_sd() {
  1509. #if !defined(WIN32) && !defined(__EMX__)
  1510.   struct rlimit r;
  1511.   static int maxfds = -1;
  1512.  
  1513.   if (maxfds > 0)
  1514.     return maxfds;
  1515.  
  1516. #if(defined(RLIMIT_NOFILE))
  1517.   if (!getrlimit(RLIMIT_NOFILE, &r)) {
  1518.     r.rlim_cur = r.rlim_max;
  1519.     if (setrlimit(RLIMIT_NOFILE, &r))
  1520.       if (o.debugging) perror("setrlimit RLIMIT_NOFILE failed");
  1521.     if (!getrlimit(RLIMIT_NOFILE, &r)) {
  1522.       maxfds =  MIN(r.rlim_cur, MAX_SOCKETS_ALLOWED);
  1523.       /* I do not feel comfortable going over 255 for now .. */
  1524.       maxfds = MIN(maxfds, 250);
  1525.       return maxfds;
  1526.     } else return 0;
  1527.   }
  1528. #endif
  1529. #if(defined(RLIMIT_OFILE) && !defined(RLIMIT_NOFILE))
  1530.   if (!getrlimit(RLIMIT_OFILE, &r)) {
  1531.     r.rlim_cur = r.rlim_max;
  1532.     if (setrlimit(RLIMIT_OFILE, &r))
  1533.       if (o.debugging) perror("setrlimit RLIMIT_OFILE failed");
  1534.     if (!getrlimit(RLIMIT_OFILE, &r)) {
  1535.       maxfds =  MIN(r.rlim_cur, MAX_SOCKETS_ALLOWED);
  1536.       /* I do not feel comfortable going over 255 for now .. */
  1537.       maxfds = MIN(maxfds, 250);
  1538.       return maxfds;
  1539.     }
  1540.     else return 0;
  1541.   }
  1542. #endif
  1543. #endif /* WIN32 */
  1544.   return 0;
  1545. }
  1546.  
  1547. /* Convert a socket to blocking mode */
  1548. int block_socket(int sd) {
  1549. #ifdef WIN32
  1550.   unsigned long options=0;
  1551.   if(sd == 501) return 1;
  1552.   ioctlsocket(sd, FIONBIO, (unsigned long *)&options);
  1553. #else
  1554.   int options;
  1555.   options = (~O_NONBLOCK) & fcntl(sd, F_GETFL);
  1556.   fcntl(sd, F_SETFL, options);
  1557. #endif
  1558.  
  1559.   return 1;
  1560. }
  1561.  
  1562. /* Give broadcast permission to a socket */
  1563. void broadcast_socket(int sd) {
  1564.   int one = 1;
  1565. #ifdef WIN32
  1566.   if(sd == 501) return;
  1567. #endif
  1568.   if (setsockopt(sd, SOL_SOCKET, SO_BROADCAST, (const char *)&one, sizeof(int)) != 0) {
  1569.     fprintf(stderr, "Failed to secure socket broadcasting permission\n");
  1570.     perror("setsockopt");
  1571.   }
  1572. }
  1573.  
  1574. /* Do a receive (recv()) on a socket and stick the results (upt to
  1575.    len) into buf .  Give up after 'seconds'.  Returns the number of
  1576.    bytes read (or -1 in the case of an error.  It only does one recv
  1577.    (it will not keep going until len bytes are read */
  1578. int recvtime(int sd, char *buf, int len, int seconds) {
  1579.  
  1580.   int res;
  1581.   struct timeval timeout;
  1582.   fd_set readfd;
  1583.  
  1584.   timeout.tv_sec = seconds;
  1585.   timeout.tv_usec = 0;
  1586.   FD_ZERO(&readfd);
  1587.   FD_SET(sd, &readfd);
  1588.   res = select(sd + 1, &readfd, NULL, NULL, &timeout);
  1589.   if (res > 0 ) {
  1590.     res = recv(sd, buf, len, 0);
  1591.     if (res >= 0) return res;
  1592.     perror("recv in recvtime");
  1593.     return 0; 
  1594.   }
  1595.   else if (!res) return 0;
  1596.   perror("select() in recvtime");
  1597.   return -1;
  1598. }
  1599.  
  1600. /* This attempts to calculate the round trip time (rtt) to a host by timing a
  1601.    connect() to a port which isn't listening.  A better approach is to time a
  1602.    ping (since it is more likely to get through firewalls (note, this isn't
  1603.    always true nowadays --fyodor).  This is now 
  1604.    implemented in isup() for users who are root.  */
  1605. unsigned long calculate_sleep(struct in_addr target) {
  1606.   struct timeval begin, end;
  1607.   int sd;
  1608.   struct sockaddr_in sock;
  1609.   int res;
  1610.  
  1611.   if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
  1612.     {perror("Socket troubles"); exit(1);}
  1613.  
  1614.   sock.sin_family = AF_INET;
  1615.   sock.sin_addr.s_addr = target.s_addr;
  1616.   sock.sin_port = htons(o.magic_port);
  1617.  
  1618.   gettimeofday(&begin, NULL);
  1619.   if ((res = connect(sd, (struct sockaddr *) &sock, 
  1620.              sizeof(struct sockaddr_in))) != -1)
  1621.     fprintf(stderr, "WARNING: You might want to use a different value of -g (or change o.magic_port in the include file), as it seems to be listening on the target host!\n");
  1622.   close(sd);
  1623.   gettimeofday(&end, NULL);
  1624.   if (end.tv_sec - begin.tv_sec > 5 ) /*uh-oh!*/
  1625.     return 0;
  1626.   return (end.tv_sec - begin.tv_sec) * 1000000 + (end.tv_usec - begin.tv_usec);
  1627. }
  1628.  
  1629.  
  1630. /* Examines the given tcp packet and obtains the TCP timestamp option
  1631.    information if available.  Note that the CALLER must ensure that
  1632.    "tcp" contains a valid header (in particular the th_off must be the
  1633.    true packet length and tcp must contain it).  If a valid timestamp
  1634.    option is found in the header, nonzero is returned and the
  1635.    'timestamp' and 'echots' parameters are filled in with the
  1636.    appropriate value (if non-null).  Otherwise 0 is returned and the
  1637.    parameters (if non-null) are filled with 0.  Remember that the
  1638.    correct way to check for errors is to look at the return value
  1639.    since a zero ts or echots could possibly be valid. */
  1640. int gettcpopt_ts(struct tcphdr *tcp, u32 *timestamp, u32 *echots) {
  1641.  
  1642.   unsigned char *p;
  1643.   int len = 0;
  1644.   int op;
  1645.   int oplen;
  1646.  
  1647.   /* first we find where the tcp options start ... */
  1648.   p = ((unsigned char *)tcp) + 20;
  1649.   len = 4 * tcp->th_off - 20;
  1650.   while(len > 0 && *p != 0 /* TCPOPT_EOL */) {
  1651.     op = *p++;
  1652.     if (op == 0 /* TCPOPT_EOL */) break;
  1653.     if (op == 1 /* TCPOPT_NOP */) { len--; continue; }
  1654.     oplen = *p++;
  1655.     if (oplen < 2) break; /* No infinite loops, please */
  1656.     if (oplen > len) break; /* Not enough space */
  1657.     if (op == 8 /* TCPOPT_TIMESTAMP */ && oplen == 10) {
  1658.       /* Legitimate ts option */
  1659.       if (timestamp) { 
  1660.     memcpy((char *) timestamp, p, 4); 
  1661.     *timestamp = ntohl(*timestamp); 
  1662.       }
  1663.       p += 4;
  1664.       if (echots) { 
  1665.     memcpy((char *) echots, p, 4);
  1666.     *echots = ntohl(*echots);
  1667.       }
  1668.       return 1;
  1669.     }
  1670.     len -= oplen;
  1671.     p += oplen - 2;
  1672.   }
  1673.  
  1674.   /* Didn't find anything */
  1675. if (timestamp) *timestamp = 0;
  1676. if (echots) *echots = 0;
  1677. return 0;
  1678. }
  1679.  
  1680.