home *** CD-ROM | disk | FTP | other *** search
/ Steganos Hacker Tools / SHT151.iso / programme / scanner / nmapNTsp1 / Win_2000.exe / nmapNT-src / targets.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-06  |  40.5 KB  |  1,242 lines

  1. #include "targets.h"
  2.  
  3. extern struct ops o;
  4.  
  5. /* Fills up the hostgroup_state structure passed in (which must point
  6.    to valid memory).  Lookahead is the number of hosts that can be
  7.    checked (such as ping scanned) in advance.  Randomize causes each
  8.    group of up to lookahead hosts to be internally shuffled around.
  9.    The target_expressions array must remail valid in memory as long as
  10.    this hostgroup_state structure is used -- the array is NOT copied */
  11. int hostgroup_state_init(struct hostgroup_state *hs, int lookahead,
  12.              int randomize, char *target_expressions[],
  13.              int num_expressions) {
  14.   bzero(hs, sizeof(struct hostgroup_state));
  15.   assert(lookahead > 0);
  16.   hs->hostbatch = safe_malloc(lookahead * sizeof(struct hostgroup_state));
  17.   hs->max_batch_sz = lookahead;
  18.   hs->current_batch_sz = 0;
  19.   hs->next_batch_no = 0;
  20.   hs->randomize = randomize;
  21.   hs->target_expressions = target_expressions;
  22.   hs->num_expressions = num_expressions;
  23.   hs->next_expression = 0;
  24.   hs->current_expression.nleft = 0; 
  25.   return 0;
  26. }
  27.  
  28.  
  29. /* If there is at least one IP address left in t, one is pulled out and placed
  30.    in sin and then zero is returned and state information in t is updated
  31.    to reflect that the IP was pulled out.  If t is empty, -1 is returned */
  32. int target_struct_get(struct targets *t, struct in_addr *sin) {
  33.   int octet;
  34.  
  35.   startover: /* to hande nmap --resume where I have already
  36.         scanned many of the IPs */  
  37.  
  38.   if (t->nleft <= 0)
  39.     return -1;
  40.   
  41.   if (t->maskformat) {
  42.     if (t->currentaddr.s_addr <= t->end.s_addr) {
  43.       sin->s_addr = htonl(t->currentaddr.s_addr++);
  44.     } else {
  45.       error("Bogus target structure passed to target_struct_get");
  46.       t->nleft = 0;
  47.       sin->s_addr = 0;
  48.       return -1;
  49.     }
  50.   }
  51.   else {
  52.     if (o.debugging > 2) {
  53.       log_write(LOG_STDOUT, "doing %d.%d.%d.%d = %d.%d.%d.%d\n", t->current[0], t->current[1], t->current[2], t->current[3], t->addresses[0][t->current[0]],t->addresses[1][t->current[1]],t->addresses[2][t->current[2]],t->addresses[3][t->current[3]]);
  54.     }
  55.     /* Set the IP to the current value of everything */
  56.     sin->s_addr = htonl(t->addresses[0][t->current[0]] << 24 | 
  57.             t->addresses[1][t->current[1]] << 16 |
  58.             t->addresses[2][t->current[2]] << 8 | 
  59.             t->addresses[3][t->current[3]]);
  60.     
  61.     /* Now we nudge up to the next IP */
  62.     for(octet = 3; octet >= 0; octet--) {
  63.       if (t->current[octet] < t->last[octet]) {
  64.     /* OK, this is the column I have room to nudge upwards */
  65.     t->current[octet]++;
  66.     break;
  67.       } else {
  68.     /* This octet is finished so I reset it to the beginning */
  69.     t->current[octet] = 0;
  70.       }
  71.     }
  72.     if (octet == -1) {
  73.       /* It didn't find anything to bump up, I muast have taken the last IP */
  74.       assert(t->nleft == 1);
  75.       /* So I set current to last with the very final octet up one ... */
  76.       /* Note that this may make t->current[3] == 256 */
  77.       t->current[0] = t->last[0]; t->current[1] = t->last[1];
  78.       t->current[2] = t->last[2]; t->current[3] = t->last[3] + 1;
  79.     } else {
  80.       assert(t->nleft > 1); /* There must be at least one more IP left */
  81.     }
  82.   }
  83.   t->nleft--;
  84.   assert(t->nleft >= 0);
  85.   
  86.   /* If we are resuming from a previous scan, we have already finished
  87.      scans up to o.resume_ip.  */
  88.   if (o.resume_ip.s_addr) {
  89.     if (o.resume_ip.s_addr == sin->s_addr)
  90.       o.resume_ip.s_addr = 0; /* So that we will KEEP the next one */
  91.     goto startover; /* Try again */
  92.   }
  93.  
  94.   return 1;
  95. }
  96.  
  97. /* Undoes the previous target_struct_get operation */
  98. void target_struct_return(struct targets *t) {
  99.   int octet;
  100.   t->nleft++;
  101.   if (t->maskformat) {
  102.     assert(t->currentaddr.s_addr > t->start.s_addr);
  103.     t->currentaddr.s_addr--;
  104.   }
  105.   else {
  106.     for(octet = 3; octet >= 0; octet--) {
  107.       if (t->current[octet] > 0) {
  108.     /* OK, this is the column I have room to nudge downwards */
  109.     t->current[octet]--;
  110.     break;
  111.       } else {
  112.     /* This octet is already at the beginning, so I set it to the end */
  113.     t->current[octet] = t->last[octet];
  114.       }
  115.     }
  116.     assert(octet != -1);
  117.   }
  118. }
  119.  
  120. void hoststructfry(struct hoststruct *hostbatch, int nelem) {
  121.   genfry((unsigned char *)hostbatch, sizeof(struct hoststruct), nelem);
  122.   return;
  123. }
  124.  
  125. struct hoststruct *nexthost(struct hostgroup_state *hs) 
  126. {
  127.     int hidx;
  128.     struct interface_info device;
  129.     int i;
  130.  
  131.     if (hs->next_batch_no < hs->current_batch_sz) 
  132.     {
  133.         /* Woop!  This is easy -- we just pass back the next host struct */
  134.         return &hs->hostbatch[hs->next_batch_no++];
  135.     }
  136.     
  137.     /* Doh, we need to refresh our array */
  138.     bzero(hs->hostbatch, hs->max_batch_sz * sizeof(struct hostgroup_state));
  139.     hs->current_batch_sz = hs->next_batch_no = 0;
  140.     do 
  141.     {
  142.         /* Grab anything we have in our current_expression */
  143.         while (hs->current_batch_sz < hs->max_batch_sz && target_struct_get(&hs->current_expression, &(hs->hostbatch[hs->current_batch_sz].host)) != -1)
  144.         {
  145.             hidx = hs->current_batch_sz;
  146.             /* Lets figure out what device this IP uses ... */
  147.             if (o.source) 
  148.             {
  149.                 memcpy((char *)&hs->hostbatch[hidx].source_ip,(char *) o.source, sizeof(struct in_addr));
  150.                 hs->hostbatch[hidx].device= o.device;
  151.             } 
  152.             else 
  153.             {
  154.                 /* We figure out the source IP/device IFF
  155.                 1) We are r00t AND
  156.                 2) We are doing tcp pingscan OR
  157.                 3) We are doing NO scan AND we are doing a raw-mode portscan or 
  158.                 osscan */
  159.                 if (o.isr00t && 
  160.                     ((o.pingtype & PINGTYPE_TCP) || 
  161.                     (o.pingtype == PINGTYPE_NONE && 
  162.                     (o.synscan || o.finscan || o.xmasscan || o.nullscan || o.maimonscan || o.ackscan || o.udpscan || o.osscan || o.windowscan)))) {
  163.                     if(*o.device.name != NULL)
  164.                     {    
  165.                         device = o.device;
  166.                     }
  167.                     else
  168.                     {
  169.                         device = routethrough(&(hs->hostbatch[hidx].host), &(hs->hostbatch[hidx].source_ip));
  170.                     }
  171.                     if (*device.name == NULL) 
  172.                     {
  173.                         if (o.pingtype == PINGTYPE_NONE) 
  174.                         {
  175.                             fatal("Could not determine what interface to route packets through, run again with -e <device>");
  176.                         } 
  177.                         else 
  178.                         {
  179.                             error("WARNING:  Could not determine what interface to route packets through to %s, changing ping scantype to ICMP only", inet_ntoa(hs->hostbatch[hidx].host));
  180.                             o.pingtype = PINGTYPE_ICMP;
  181.                         }
  182.                     } 
  183.                     else 
  184.                     {
  185.                         hs->hostbatch[hidx].device=device;
  186.                     }
  187.                 }  
  188.             }
  189.             /* In some cases, we can only allow hosts that use the same device
  190.             in a group. */
  191.             if (o.isr00t && hidx > 0 && *hs->hostbatch[hidx].device.name && hs->hostbatch[hidx].source_ip.s_addr != hs->hostbatch[0].source_ip.s_addr) 
  192.             {
  193.                 /* Cancel everything!  This guy must go in the next group and we are
  194.                 outtof here */
  195.                 target_struct_return(&(hs->current_expression));
  196.                 goto batchfull;
  197.             }
  198.             hs->current_batch_sz++;
  199.         }
  200.         if (hs->current_batch_sz < hs->max_batch_sz && hs->next_expression < hs->num_expressions) 
  201.         {
  202.             /* We are going to have to plop in another expression. */
  203.             while (!parse_targets(&(hs->current_expression), hs->target_expressions[hs->next_expression++])) 
  204.             {
  205.                 if (hs->next_expression >= hs->num_expressions) break;
  206.             }     
  207.         } 
  208.         else break;
  209.     } while(1);
  210.  
  211.     batchfull:
  212.     if (hs->current_batch_sz == 0) return NULL;
  213.     /* OK, now we have our complete batch of entries.  The next step is to
  214.         randomize them (if requested) */
  215.     if (hs->randomize) 
  216.     {
  217.         hoststructfry(hs->hostbatch, hs->current_batch_sz);
  218.     }
  219.     /* Finally we do the mass ping (if required) */
  220.     if ((o.pingtype == PINGTYPE_ICMP) || (hs->hostbatch[0].host.s_addr && (o.pingtype != PINGTYPE_NONE))) massping(hs->hostbatch, hs->current_batch_sz);
  221.     else for(i=0; i < hs->current_batch_sz; i++)  
  222.     {
  223.         hs->hostbatch[i].to.srtt = -1;
  224.         hs->hostbatch[i].to.rttvar = -1;
  225.         hs->hostbatch[i].to.timeout = o.initial_rtt_timeout * 1000;
  226.         hs->hostbatch[i].flags |= HOST_UP; /*hostbatch[i].up = 1;*/
  227.     }
  228.     return &hs->hostbatch[hs->next_batch_no++];
  229. }
  230.  
  231. int parse_targets(struct targets *targets, char *h) {
  232. int i=0,j=0,k=0;
  233. int start, end;
  234. char *r,*s, *target_net;
  235. char *addy[5];
  236. char *hostexp = strdup(h);
  237. struct hostent *target;
  238. unsigned long longtmp;
  239. int namedhost = 0;
  240.  
  241. bzero(targets, sizeof(struct targets));
  242. targets->nleft = 0;
  243. /*struct in_addr current_in;*/
  244. addy[0] = addy[1] = addy[2] = addy[3] = addy[4] = NULL;
  245. addy[0] = r = hostexp;
  246. /* First we break the expression up into the four parts of the IP address
  247.    + the optional '/mask' */
  248. target_net = strtok(hostexp, "/");
  249. s = strtok(NULL, "");    /* find the end of the token from hostexp */
  250. targets->netmask  = ( s ) ? atoi(s) : 32;
  251. if ((int) targets->netmask < 0 || targets->netmask > 32) {
  252.   fprintf(stderr, "Illegal netmask value (%d), must be /0 - /32 .  Assuming /32 (one host)\n", targets->netmask);
  253.   targets->netmask = 32;
  254. }
  255. for(i=0; *(hostexp + i); i++) 
  256.   if (isupper((int) *(hostexp +i)) || islower((int) *(hostexp +i))) {
  257.   namedhost = 1;
  258.   break;
  259. }
  260. if (targets->netmask != 32 || namedhost) {
  261.   targets->maskformat = 1;
  262.  if (!inet_aton(target_net, &(targets->start))) {
  263.     if ((target = gethostbyname(target_net)))
  264.       memcpy(&(targets->start), target->h_addr_list[0], sizeof(struct in_addr));
  265.     else {
  266.       fprintf(stderr, "Failed to resolve given hostname/IP: %s.  Note that you can't use '/mask' AND '[1-4,7,100-]' style IP ranges\n", target_net);
  267.       free(hostexp);
  268.       return 0;
  269.     }
  270.  } 
  271.  longtmp = ntohl(targets->start.s_addr);
  272.  targets->start.s_addr = longtmp & (unsigned long) (0 - (1<<(32 - targets->netmask)));
  273.  targets->end.s_addr = longtmp | (unsigned long)  ((1<<(32 - targets->netmask)) - 1);
  274.  targets->currentaddr = targets->start;
  275.  if (targets->start.s_addr <= targets->end.s_addr) { 
  276.    targets->nleft = targets->end.s_addr - targets->start.s_addr + 1;
  277.    free(hostexp); 
  278.    return 1; 
  279.  }
  280.  fprintf(stderr, "Host specification invalid");
  281.  free(hostexp);
  282.  return 0;
  283. }
  284. else {
  285.   i=0;
  286.   targets->maskformat = 0;
  287.   while(*++r) {
  288.     if (*r == '.' && ++i < 4) {
  289.       *r = '\0';
  290.       addy[i] = r + 1;
  291.     }
  292.     else if (*r == '[') {
  293.       *r = '\0';
  294.       addy[i]++;
  295.     }
  296.     else if (*r == ']') *r = '\0';
  297.     /*else if ((*r == '/' || *r == '\\') && i == 3) {
  298.      *r = '\0';
  299.      addy[4] = r + 1;
  300.      }*/
  301.     else if (*r != '*' && *r != ',' && *r != '-' && !isdigit((int)*r)) fatal("Invalid character in  host specification.");
  302.   }
  303.   if (i != 3) fatal("Target host specification is illegal.");
  304.   
  305.   for(i=0; i < 4; i++) {
  306.     j=0;
  307.     while((s = strchr(addy[i],','))) {
  308.       *s = '\0';
  309.       if (*addy[i] == '*') { start = 0; end = 255; } 
  310.       else if (*addy[i] == '-') {
  311.     start = 0;
  312.     if (!addy[i] + 1) end = 255;
  313.     else end = atoi(addy[i]+ 1);
  314.       }
  315.       else {
  316.     start = end = atoi(addy[i]);
  317.     if ((r = strchr(addy[i],'-')) && *(r+1) ) end = atoi(r + 1);
  318.     else if (r && !*(r+1)) end = 255;
  319.       }
  320.       if (o.debugging)
  321.     log_write(LOG_STDOUT, "The first host is %d, and the last one is %d\n", start, end);
  322.       if (start < 0 || start > end) fatal("Your host specifications are illegal!");
  323.       for(k=start; k <= end; k++)
  324.     targets->addresses[i][j++] = k;
  325.       addy[i] = s + 1;
  326.     }
  327.     if (*addy[i] == '*') { start = 0; end = 255; } 
  328.     else if (*addy[i] == '-') {
  329.       start = 0;
  330.       if (!addy[i] + 1) end = 255;
  331.       else end = atoi(addy[i]+ 1);
  332.     }
  333.     else {
  334.       start = end = atoi(addy[i]);
  335.       if ((r =  strchr(addy[i],'-')) && *(r+1) ) end = atoi(r+1);
  336.       else if (r && !*(r+1)) end = 255;
  337.     }
  338.     if (o.debugging)
  339.       log_write(LOG_STDOUT, "The first host is %d, and the last one is %d\n", start, end);
  340.     if (start < 0 || start > end) fatal("Your host specifications are illegal!");
  341.     if (j + (end - start) > 255) fatal("Your host specifications are illegal!");
  342.     for(k=start; k <= end; k++) 
  343.       targets->addresses[i][j++] = k;
  344.     targets->last[i] = j - 1;
  345.     
  346.   }
  347. }
  348.   bzero((char *)targets->current, 4);
  349.   targets->nleft = (targets->last[0] + 1) * (targets->last[1] + 1) *
  350.     (targets->last[2] + 1) * (targets->last[3] + 1);
  351.   free(hostexp);
  352.   return 1;
  353. }
  354.  
  355.  
  356. void massping(struct hoststruct *hostbatch, int num_hosts) {
  357. static struct timeout_info to = { 0,0,0};
  358. static int gsize = LOOKAHEAD;
  359. int hostnum;
  360. struct pingtune pt;
  361. struct scanstats ss;
  362. struct timeval begin_select;
  363. struct pingtech ptech;
  364. struct tcpqueryinfo tqi;
  365. int max_block_size = 40;
  366. char err0r[PCAP_ERRBUF_SIZE];
  367. struct ppkt {
  368.   unsigned char type;
  369.   unsigned char code;
  370.   unsigned short checksum;
  371.   unsigned short id;
  372.   unsigned short seq;
  373. };
  374. unsigned int elapsed_time;
  375. int blockinc;
  376. int sd_blocking = 1;
  377. struct sockaddr_in sock;
  378. short seq = 0;
  379. int sd = -1, rawsd = -1, rawpingsd = -1;
  380. struct timeval *time;
  381. struct timeval start, end, t1, t2;
  382. unsigned short id;
  383. pcap_t *pd = NULL;
  384. struct bpf_program fcode;
  385. char filter[512];
  386. unsigned int localnet, netmask;
  387. unsigned short sportbase;
  388. int max_width = 0;
  389.  
  390. bzero((char *)&ptech, sizeof(struct pingtech));
  391.  
  392. bzero((char *) &pt, sizeof(struct pingtune)); 
  393.  
  394. pt.up_this_block = 0;
  395. pt.block_unaccounted = LOOKAHEAD;
  396. pt.discardtimesbefore = 0;
  397. pt.down_this_block = 0;
  398. pt.num_responses = 0;
  399. pt.max_tries = 5; /* Maximum number of tries for a block */
  400. pt.group_size = (o.max_parallelism)? MIN(o.max_parallelism, gsize) : gsize;
  401. pt.group_start = 0;
  402. pt.block_tries = 0; /* How many tries this block has gone through */
  403.  
  404. /* What port should we send from? */
  405. if (o.magic_port_set) sportbase = o.magic_port;
  406. else sportbase = o.magic_port + 20;
  407.  
  408. /* What kind of scans are we doing? */
  409. if ((o.pingtype & PINGTYPE_ICMP) &&  hostbatch[0].source_ip.s_addr) 
  410.   ptech.rawicmpscan = 1;
  411. else if (o.pingtype & PINGTYPE_ICMP) 
  412.   ptech.icmpscan = 1;
  413. if (o.pingtype & PINGTYPE_TCP) {
  414.   if (o.isr00t)
  415.     ptech.rawtcpscan = 1;
  416.   else ptech.connecttcpscan = 1;
  417. }
  418.  
  419. time = safe_malloc(sizeof(struct timeval) * ((pt.max_tries) * num_hosts));
  420. bzero(time, sizeof(struct timeval) * pt.max_tries * num_hosts);
  421. id = (unsigned short) get_random_uint();
  422.  
  423. if (ptech.connecttcpscan)  {
  424.   max_width = (o.max_parallelism)? o.max_parallelism : MAX(1, max_sd() - 4);
  425.   max_block_size = MIN(50, max_width);
  426. }
  427.  
  428.  
  429. bzero((char *)&tqi, sizeof(tqi));
  430. if (ptech.connecttcpscan) {
  431.   tqi.sockets = safe_malloc(sizeof(int) * (pt.max_tries) * num_hosts);
  432.   memset(tqi.sockets, 255, sizeof(int) * (pt.max_tries) * num_hosts);
  433.   FD_ZERO(&(tqi.fds_r));
  434.   FD_ZERO(&(tqi.fds_w));
  435.   FD_ZERO(&(tqi.fds_x));
  436.   tqi.sockets_out = 0;
  437.   tqi.maxsd = 0;
  438. }
  439.  
  440. //#ifdef WIN32
  441. //sd=500;
  442. //#else
  443. if (ptech.icmpscan) {
  444.   sd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  445.   if (sd < 0) pfatal("Socket trouble in massping"); 
  446.   unblock_socket(sd);
  447.   sd_blocking = 0;
  448.   if (num_hosts > 10)
  449.     max_rcvbuf(sd);
  450.   broadcast_socket(sd);
  451. } else sd = -1;
  452. //#endif
  453.  
  454. /* if to timeout structure hasn't been initialized yet */
  455. if (!to.srtt && !to.rttvar && !to.timeout) {
  456.   /*  to.srtt = 800000;
  457.       to.rttvar = 500000; */ /* we will init these when we get real data */
  458.   to.timeout = o.initial_rtt_timeout * 1000;
  459.  
  460. /* Init our raw socket */
  461. #ifdef WIN32
  462.     rawsd=500;
  463.     rawpingsd=500;
  464. #else
  465. if (o.numdecoys > 1 || ptech.rawtcpscan || ptech.rawicmpscan) {
  466.   if ((rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
  467.     pfatal("socket trobles in massping");
  468.   broadcast_socket(rawsd);
  469.  
  470.   
  471.   if ((rawpingsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
  472.     pfatal("socket trobles in massping");
  473.   broadcast_socket(rawpingsd);
  474.  
  475. }
  476.  else { rawsd = -1; rawpingsd = -1; }
  477. #endif
  478. if (ptech.rawicmpscan || ptech.rawtcpscan) {
  479.   /* we need a pcap descript0r! */
  480.   /* MAX snaplen needed = 
  481.      24 bytes max link_layer header
  482.      64 bytes max IPhdr
  483.      16 bytes of the TCP header
  484.      ---
  485.    = 104 byte snaplen */
  486.   pd = my_pcap_open_live(hostbatch[0].device.name, 104, o.spoofsource, 20);
  487.  
  488.   if (pcap_lookupnet(hostbatch[0].device.name, &localnet, &netmask, err0r) < 0)
  489.     fatal("Failed to lookup device subnet/netmask: %s", err0r);
  490. snprintf(filter, sizeof(filter), "(icmp and dst host %s) or (tcp and dst host %s and ( dst port %d or dst port %d or dst port %d or dst port %d))", 
  491.       inet_ntoa(hostbatch[0].source_ip),inet_ntoa(hostbatch[0].source_ip),
  492.       sportbase , sportbase + 1, sportbase + 2, sportbase + 3 );
  493. /*printf("(icmp and dst host %s) or (tcp and dst host %s and ( dst port %d or dst port %d or dst port %d or dst port %d))", 
  494.       inet_ntoa(hostbatch[0].source_ip),inet_ntoa(hostbatch[0].source_ip),
  495.       sportbase , sportbase + 1, sportbase + 2, sportbase + 3 );
  496.  
  497.       /*snprintf(filter, sizeof(filter), "(icmp and dst host %s) or (tcp and dst host %s and ( dst port %d or dst port %d or dst port %d or dst port %d or dst port %d))", 
  498.       inet_ntoa(hostbatch[0].source_ip),inet_ntoa(hostbatch[0].source_ip),
  499.       sportbase , sportbase + 1, sportbase + 2, sportbase + 3, 
  500.       sportbase + 4);*/
  501.  
  502. //snprintf(filter, sizeof(filter), "(icmp and dst host %s)", inet_ntoa(hostbatch[0].source_ip));
  503. //snprintf(filter, sizeof(filter), "icmp");
  504.  
  505.  
  506.   /* Due to apparent bug in libpcap */
  507.   if (islocalhost(&(hostbatch[0].host)))// filter[0] ='\0';
  508. {
  509.       localnet=0;
  510.       netmask=0;
  511. snprintf(filter, sizeof(filter), "icmp[0] = 8");
  512. }
  513.  
  514.   if (o.debugging)
  515.     log_write(LOG_STDOUT, "Packet capture filter: %s\n", filter);
  516.   if (pcap_compile(pd, &fcode, filter, 0, netmask) < 0)
  517.     fatal("Error compiling our pcap filter: %s\n", pcap_geterr(pd));
  518.   if (pcap_setfilter(pd, &fcode) < 0 )
  519.     fatal("Failed to set the pcap filter: %s\n", pcap_geterr(pd));
  520.   
  521. }
  522.  
  523.  if (ptech.rawicmpscan + ptech.icmpscan + ptech.connecttcpscan +
  524.      ptech.rawtcpscan == 1)
  525.    blockinc = 8;
  526.  else blockinc = 5;
  527.  
  528. bzero((char *)&sock,sizeof(struct sockaddr_in));
  529. gettimeofday(&start, NULL);
  530.  
  531.  pt.group_end = MIN(pt.group_start + pt.group_size -1, num_hosts -1);
  532.  
  533.  while(pt.group_start < num_hosts) { /* while we have hosts left to scan */
  534.    do { /* one block */
  535.      pt.discardtimesbefore = -1;
  536.      pt.up_this_block = 0;
  537.      pt.down_this_block = 0;
  538.      pt.block_unaccounted = 0;
  539.      for(hostnum=pt.group_start; hostnum <= pt.group_end; hostnum++) {      
  540.        /* If (we don't know whether the host is up yet) ... */
  541.        if (!(hostbatch[hostnum].flags & HOST_UP) && !hostbatch[hostnum].wierd_responses && !(hostbatch[hostnum].flags & HOST_DOWN)) {  
  542.      /* Send a ping packet to it */
  543.      seq = hostnum * pt.max_tries + pt.block_tries;
  544.      if (ptech.icmpscan && !sd_blocking) { 
  545.        block_socket(sd); sd_blocking = 1; 
  546.      }
  547.      if (o.scan_delay) enforce_scan_delay(NULL);
  548.      if (ptech.icmpscan || ptech.rawicmpscan)
  549.        sendpingquery(sd, rawpingsd, &hostbatch[hostnum],  
  550.              seq, id, &ss, time, ptech);
  551.        
  552.      if (ptech.rawtcpscan) {
  553.        sendrawtcppingquery(rawsd, &hostbatch[hostnum],  seq, time, &pt);
  554.      }
  555.      else if (ptech.connecttcpscan) {
  556.        sendconnecttcpquery(hostbatch, &tqi, &hostbatch[hostnum], seq, time, &pt, &to, max_width);
  557.      }
  558.      pt.block_unaccounted++;
  559.      gettimeofday(&t2, NULL);
  560.      if (TIMEVAL_SUBTRACT(t2,time[seq]) > 1000000) {
  561.        pt.discardtimesbefore = hostnum;
  562.        if (o.debugging) 
  563.          log_write(LOG_STDOUT, "Huge send delay: %lu microseconds\n", (unsigned long) TIMEVAL_SUBTRACT(t2,t1));
  564.      }
  565.        }
  566.      } /* for() loop */
  567.      /* OK, we have sent our ping packets ... now we wait for responses */
  568.      gettimeofday(&begin_select, NULL);
  569.      do {
  570.        if (ptech.icmpscan && sd_blocking ) { 
  571.      unblock_socket(sd); sd_blocking = 0; 
  572.        }
  573.        if(ptech.icmpscan || ptech.rawicmpscan || ptech.rawtcpscan) {       
  574.      get_ping_results(sd, pd, hostbatch, time, &pt, &to, id, &ptech);
  575.        }
  576.        if (ptech.connecttcpscan) {
  577.      get_connecttcpscan_results(&tqi, hostbatch, time, &pt, &to);
  578.        }
  579.        gettimeofday(&end, NULL);
  580.        elapsed_time = TIMEVAL_SUBTRACT(end, begin_select);
  581.      } while( elapsed_time < to.timeout);
  582.      /* try again if a new box was found but some are still unaccounted for and
  583.     we haven't run out of retries.  Also retry if the block is extremely
  584.         small.
  585.      */
  586.      pt.dropthistry = 0;
  587.      pt.block_tries++;
  588.    } while ((pt.up_this_block > 0 || pt.group_end - pt.group_start <= 3) && pt.block_unaccounted > 0 && pt.block_tries < pt.max_tries);
  589.  
  590.    if (o.debugging)
  591.      log_write(LOG_STDOUT, "Finished block: srtt: %d rttvar: %d timeout: %d block_tries: %d up_this_block: %d down_this_block: %d group_sz: %d\n", to.srtt, to.rttvar, to.timeout, pt.block_tries, pt.up_this_block, pt.down_this_block, pt.group_end - pt.group_start + 1);
  592.  
  593.    if ((pt.block_tries == 1) || (pt.block_tries == 2 && pt.up_this_block == 0 && pt.down_this_block == 0)) 
  594.      /* Then it did not miss any hosts (that we know of)*/
  595.        pt.group_size = MIN(pt.group_size + blockinc, max_block_size);
  596.    
  597.    /* Move to next block */
  598.    pt.block_tries = 0;
  599.    pt.group_start = pt.group_end +1;
  600.    pt.group_end = MIN(pt.group_start + pt.group_size -1, num_hosts -1);
  601.    /*   pt.block_unaccounted = pt.group_end - pt.group_start + 1;   */
  602.  }
  603.  
  604.  close(sd);
  605.  if (ptech.connecttcpscan) free(tqi.sockets);
  606.  if (sd >= 0) close(sd);
  607.  if (rawsd >= 0) close(rawsd);
  608.  if (rawpingsd >= 0) close(rawpingsd);
  609.  free(time);
  610.  if (pd) pcap_close(pd);
  611.  if (o.debugging) 
  612.    log_write(LOG_STDOUT, "massping done:  num_hosts: %d  num_responses: %d\n", num_hosts, pt.num_responses);
  613.  gsize = pt.group_size;
  614.  return;
  615. }
  616.  
  617. int sendconnecttcpquery(struct hoststruct *hostbatch, struct tcpqueryinfo *tqi,
  618.             struct hoststruct *target, int seq, 
  619.             struct timeval *time, struct pingtune *pt, 
  620.             struct timeout_info *to, int max_width) {
  621.  
  622.   int res,i;
  623.   int tmpsd;
  624.   int hostnum, trynum;
  625.   struct sockaddr_in sock;
  626.   int sockaddr_in_len = sizeof(struct sockaddr_in);
  627.   
  628.   trynum = seq % pt->max_tries;
  629.   hostnum = seq / pt->max_tries;
  630.  
  631.   assert(tqi->sockets_out <= max_width);
  632.   if (tqi->sockets_out == max_width) {
  633.     /* We've got to free one! */
  634.     for(i=0; i < trynum; i++) {
  635.       tmpsd = hostnum * pt->max_tries + i;
  636.       if (tqi->sockets[tmpsd] >= 0) {
  637.     if (o.debugging) 
  638.       log_write(LOG_STDOUT, "sendconnecttcpquery: Scavenging a free socket due to serious shortage\n");
  639.     close(tqi->sockets[tmpsd]);
  640.     tqi->sockets[tmpsd] = -1;
  641.     tqi->sockets_out--;
  642.     break;
  643.       }
  644.     }
  645.     if (i == trynum)
  646.       fatal("sendconnecttcpquery: Could not scavenge a free socket!");
  647.   }
  648.     
  649.   /* Since we know we now have a free s0cket, lets take it */
  650.  
  651.   assert(tqi->sockets[seq] == -1);
  652.   tqi->sockets[seq] =  socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  653.   if (tqi->sockets[seq] == -1) 
  654.     fatal("Socket creation in sendconnecttcpquery");
  655.   tqi->maxsd = MAX(tqi->maxsd, tqi->sockets[seq]);
  656.   tqi->sockets_out++;
  657.   unblock_socket(tqi->sockets[seq]);
  658.   init_socket(tqi->sockets[seq]);
  659.  
  660.   bzero(&sock, sockaddr_in_len);
  661.   sock.sin_family = AF_INET;
  662.   sock.sin_port = htons(o.tcp_probe_port);
  663.   sock.sin_addr.s_addr = target->host.s_addr;
  664.   
  665.   res = connect(tqi->sockets[seq],(struct sockaddr *)&sock,sizeof(struct sockaddr));
  666.   gettimeofday(&time[seq], NULL);
  667.  
  668.   if ((res != -1 || errno == ECONNREFUSED)) {
  669.     /* This can happen on localhost, successful/failing connection immediately
  670.        in non-blocking mode */
  671.       hostupdate(hostbatch, target, HOST_UP, 1, trynum, to, 
  672.          &time[seq], pt, tqi, PINGTYPE_CONNECTTCP);
  673.     if (tqi->maxsd == tqi->sockets[seq]) tqi->maxsd--;
  674.   }
  675.   else if (errno == ENETUNREACH) {
  676.     if (o.debugging) 
  677.       error("Got ENETUNREACH from sendconnecttcpquery connect()");
  678.     hostupdate(hostbatch, target, HOST_DOWN, 1, trynum, to, 
  679.            &time[seq], pt, tqi, PINGTYPE_CONNECTTCP);
  680.   }
  681.   else {
  682.     /* We'll need to select() and wait it out */
  683. //    FD_SET(tqi->sockets[seq], &(tqi->fds_r));
  684. //    FD_SET(tqi->sockets[seq], &(tqi->fds_w));
  685. //    FD_SET(tqi->sockets[seq], &(tqi->fds_x));
  686.   }
  687. return 0;
  688. }
  689.  
  690. int sendrawtcppingquery(int rawsd, struct hoststruct *target, int seq,
  691.             struct timeval *time, struct pingtune *pt) {
  692. int trynum;
  693. int myseq;
  694. unsigned short sportbase;
  695. unsigned long myack = get_random_uint();
  696.  
  697. if (o.magic_port_set) sportbase = o.magic_port;
  698. else sportbase = o.magic_port + 20;
  699. trynum = seq % pt->max_tries;
  700.  
  701.  myseq = (get_random_uint() << 19) + (seq << 3) + 3; /* Response better end in 011 or 100 */
  702.  memcpy((char *)&(o.decoys[o.decoyturn]), (char *)&target->source_ip, sizeof(struct in_addr));
  703.  if (o.pingtype & PINGTYPE_TCP_USE_SYN) {   
  704.    send_tcp_raw_decoys( rawsd, &(target->host), sportbase + trynum, o.tcp_probe_port, myseq, myack, TH_SYN, 0, NULL, 0, NULL, 0,&target->device);
  705.  } else {
  706.    send_tcp_raw_decoys( rawsd, &(target->host), sportbase + trynum, o.tcp_probe_port, myseq, myack, TH_ACK, 0, NULL, 0, NULL, 0,&target->device);
  707.  }
  708.  
  709.  gettimeofday(&time[seq], NULL);
  710.  return 0;
  711. }
  712.  
  713.  
  714. int sendpingquery(int sd, int rawsd, struct hoststruct *target,  
  715.           int seq, unsigned short id, struct scanstats *ss, 
  716.           struct timeval *time, struct pingtech ptech) {
  717.   
  718. struct ppkt {
  719.   unsigned char type;
  720.   unsigned char code;
  721.   unsigned short checksum;
  722.   unsigned short id;
  723.   unsigned short seq;
  724. } pingpkt;
  725. int decoy;
  726. int res;
  727. struct sockaddr_in sock;
  728. char *ping = (char *) &pingpkt;
  729.  
  730. /* Fill out the ping packet */
  731. pingpkt.type = 8;
  732. pingpkt.code = 0;
  733. pingpkt.id = id;
  734. pingpkt.seq = seq;
  735. pingpkt.checksum = 0;
  736. pingpkt.checksum = in_cksum((unsigned short *)ping, 8);
  737.  
  738. /* Now for our sock */
  739. if (ptech.icmpscan) {
  740.   bzero((char *)&sock, sizeof(struct sockaddr_in));
  741.   sock.sin_family= AF_INET;
  742.   sock.sin_addr = target->host;
  743.   
  744.   if (sizeof(struct ppkt) != 8) 
  745.     fatal("Your native data type sizes are too screwed up for this to work.");
  746. } else {
  747.     memcpy((char *) &(o.decoys[o.decoyturn]), (char *)&target->source_ip, sizeof(struct in_addr));
  748. }
  749.  
  750.  for (decoy = 0; decoy < o.numdecoys; decoy++) {
  751.    if (ptech.icmpscan && decoy == o.decoyturn) {
  752.        /*     if ((res = sendto(sd,(char *) ping,8,0,(struct sockaddr *)&sock,*/
  753.      if ((res = Sendto("sendpingquery",sd,(char *) ping,8,0,(struct sockaddr *)&sock,
  754.                sizeof(struct sockaddr),&target->device)) != 8) {
  755.        fprintf(stderr, "sendto in sendpingquery returned %d (should be 8)!\n", res);
  756.        perror("sendto");
  757.      }
  758.    } else {
  759.      send_ip_raw( rawsd, &o.decoys[decoy], &(target->host), IPPROTO_ICMP, ping, 8,&target->device);
  760.    }
  761.  }
  762.  gettimeofday(&time[seq], NULL);
  763.  return 0;
  764. }
  765.  
  766. int get_connecttcpscan_results(struct tcpqueryinfo *tqi, 
  767.                    struct hoststruct *hostbatch, 
  768.                    struct timeval *time, struct pingtune *pt, 
  769.                    struct timeout_info *to) {
  770.  
  771. int res, res2, tm;
  772. struct timeval myto, start, end;
  773. int hostindex;
  774. int trynum, newstate = HOST_DOWN;
  775. int seq;
  776. char buf[256];
  777. int foundsomething = 0;
  778. fd_set myfds_r,myfds_w,myfds_x;
  779. gettimeofday(&start, NULL);
  780.  
  781. while(pt->block_unaccounted) {
  782.  
  783.   /* OK so there is a little fudge factor, SUE ME! */
  784.   myto.tv_sec  = to->timeout / 1000000; 
  785.   myto.tv_usec = to->timeout % 1000000;
  786.   foundsomething = 0;
  787.   myfds_r = tqi->fds_r;
  788.   myfds_w = tqi->fds_w;
  789.   myfds_x = tqi->fds_x;
  790.   res = select(tqi->maxsd + 1, &myfds_r, &myfds_w, &myfds_x, &myto);
  791.   if (res > 0) {
  792.     for(hostindex = pt->group_start; hostindex <= pt->group_end; hostindex++) {
  793.       for(trynum=0; trynum <= pt->block_tries; trynum++) {
  794.     seq = hostindex * pt->max_tries + trynum;
  795.     if (tqi->sockets[seq] >= 0) {
  796.       if (o.debugging > 1) {
  797.         if (FD_ISSET(tqi->sockets[seq], &(myfds_r))) {
  798.           log_write(LOG_STDOUT, "WRITE selected for machine %s\n", inet_ntoa(hostbatch[hostindex].host));  
  799.         }
  800.         if ( FD_ISSET(tqi->sockets[seq], &myfds_w)) {
  801.           log_write(LOG_STDOUT, "READ selected for machine %s\n", inet_ntoa(hostbatch[hostindex].host)); 
  802.         }
  803.         if  ( FD_ISSET(tqi->sockets[seq], &myfds_x)) {
  804.           log_write(LOG_STDOUT, "EXC selected for machine %s\n", inet_ntoa(hostbatch[hostindex].host));
  805.         }
  806.       }
  807.       if (FD_ISSET(tqi->sockets[seq], &myfds_r) || FD_ISSET(tqi->sockets[seq], &myfds_w) ||  FD_ISSET(tqi->sockets[seq], &myfds_x)) {
  808.         foundsomething = 0;
  809.         res2 = read(tqi->sockets[seq], buf, sizeof(buf));
  810.         if (res2 == -1) {
  811.           switch(errno) {
  812.           case ECONNREFUSED:
  813.           case EAGAIN:
  814.         if (errno == EAGAIN && o.verbose) {
  815.           log_write(LOG_STDOUT, "Machine %s MIGHT actually be listening on probe port %d\n", inet_ntoa(hostbatch[hostindex].host), o.tcp_probe_port);
  816.         }
  817.         foundsomething = 1;
  818.         newstate = HOST_UP;    
  819.         break;
  820.           case ENETDOWN:
  821.           case ENETUNREACH:
  822.           case ENETRESET:
  823.           case ECONNABORTED:
  824.           case ETIMEDOUT:
  825.           case EHOSTDOWN:
  826.           case EHOSTUNREACH:
  827.         foundsomething = 1;
  828.         newstate = HOST_DOWN;
  829.         break;
  830.           default:
  831.         snprintf (buf, sizeof(buf), "Strange read error from %s", inet_ntoa(hostbatch[hostindex].host));
  832.         perror(buf);
  833.         break;
  834.           }
  835.         } else { 
  836.           foundsomething = 1;
  837.           newstate = HOST_UP;
  838.           if (o.verbose) {          
  839.         buf[res2] = '\0';
  840.         if (res2 == 0)
  841.           log_write(LOG_STDOUT, "Machine %s is actually LISTENING on probe port %d\n",
  842.              inet_ntoa(hostbatch[hostindex].host), 
  843.              o.tcp_probe_port);
  844.         else 
  845.           log_write(LOG_STDOUT, "Machine %s is actually LISTENING on probe port %d, banner: %s\n",
  846.              inet_ntoa(hostbatch[hostindex].host), 
  847.              o.tcp_probe_port, buf);
  848.           }
  849.         }
  850.         if (foundsomething) {
  851.           hostupdate(hostbatch, &hostbatch[hostindex], newstate, 1, trynum,
  852.              to,  &time[seq], pt, tqi, PINGTYPE_CONNECTTCP);
  853.           /*          break;*/
  854.         }
  855.       }
  856.     }
  857.       }
  858.     }
  859.   }
  860.   gettimeofday(&end, NULL);
  861.   tm = TIMEVAL_SUBTRACT(end,start);  
  862.   if (tm > (30 * to->timeout)) {
  863.     error("WARNING: getconnecttcpscanresults is taking way too long, skipping");
  864.     break;
  865.   }
  866.   if (res == 0 &&  tm > to->timeout) break; 
  867. }
  868.  
  869. /* OK, now we have to kill all outstanding queries to make room for
  870.    the next group :( I'll miss these little guys. */
  871.  for(hostindex = pt->group_start; hostindex <= pt->group_end; hostindex++) { 
  872.       for(trynum=0; trynum <= pt->block_tries; trynum++) {
  873.     seq = hostindex * pt->max_tries + trynum;
  874.     if ( tqi->sockets[seq] >= 0) {
  875.       tqi->sockets_out--;
  876.       close(tqi->sockets[seq]);
  877.       tqi->sockets[seq] = -1;
  878.     }
  879.       }
  880.  }
  881.  tqi->maxsd = 0;
  882.  assert(tqi->sockets_out == 0);
  883.  FD_ZERO(&(tqi->fds_r));
  884.  FD_ZERO(&(tqi->fds_w));
  885.  FD_ZERO(&(tqi->fds_x));
  886.      
  887. return 0;
  888. }
  889.  
  890.  
  891. int get_ping_results(int sd, pcap_t *pd, struct hoststruct *hostbatch, struct timeval *time,  struct pingtune *pt, struct timeout_info *to, int id, struct pingtech *ptech) 
  892. {
  893.     fd_set fd_r, fd_x;
  894.     struct timeval myto, tmpto, start, end;
  895.     int bytes, res;
  896.     struct ppkt 
  897.     {
  898.         unsigned char type;
  899.         unsigned char code;
  900.         unsigned short checksum;
  901.         unsigned short id;
  902.         unsigned short seq;
  903.     } *ping = NULL, *ping2 = NULL;
  904.     char response[16536]; 
  905.     struct tcphdr *tcp;
  906.     struct ip *ip, *ip2;
  907.     int hostnum = -99999; /* This ought to crash us if it is used uninitialized */
  908.     int tm;
  909.     int dotimeout = 1;
  910.     int newstate = HOST_DOWN;
  911.     int foundsomething;
  912.     unsigned short newport;
  913.     int trynum = -999999;
  914.     int pingtype = -999999;
  915.     int timeout = 0;
  916.     unsigned short sequence = 65534;
  917.     unsigned long tmpl;
  918.     unsigned short sportbase;
  919.  
  920. //FD_ZERO(&fd_r);
  921. //FD_ZERO(&fd_x);
  922.  
  923. /* Decide on the timeout, based on whether we need to also watch for TCP stuff */
  924.     if (ptech->icmpscan && !ptech->rawtcpscan) 
  925.     {
  926.         /* We only need to worry about pings, so we set timeout for the whole she-bang! */
  927.         myto.tv_sec  = to->timeout / 1000000;
  928.         myto.tv_usec = to->timeout % 1000000;
  929.     } 
  930.     else 
  931.     {
  932.         myto.tv_sec = 0;
  933.         myto.tv_usec = 20000;
  934.     }
  935.     if (o.magic_port_set) sportbase = o.magic_port;
  936.     else sportbase = o.magic_port + 20;
  937.  
  938.     gettimeofday(&start, NULL);
  939.     while(pt->block_unaccounted > 0 && !timeout) 
  940.     {
  941.         tmpto = myto;
  942.         if (pd) 
  943.         {
  944.             ip = (struct ip*) readip_pcap(pd, &bytes, to->timeout);
  945.         } 
  946.         else 
  947.         {    
  948.             res = select(sd+1, &fd_r, NULL, &fd_x, &tmpto);
  949.             if (res == 0) break;
  950.             bytes = read(sd,&response,sizeof(response));
  951.             ip = (struct ip *) &(response);
  952.         }
  953.     //if(ip->ip_v > 0 )    printf("ippacket protocol: %d\n",ip->ip_p);
  954. //        printf("PACKET!\n");
  955.         if (o.debugging > 1) lamont_hdump((char *)ip, bytes);
  956.         gettimeofday(&end, NULL);
  957.         tm = TIMEVAL_SUBTRACT(end,start);  
  958.         if (tm > (MAX(400000,3 * to->timeout))) timeout = 1;
  959.         if (bytes == 0 &&  tm > to->timeout) 
  960.         {  
  961.             timeout = 1;
  962.         }
  963.         if (bytes == 0) continue;
  964.         if (bytes > 0 && bytes <= 20) 
  965.         {  
  966.             error("%d byte micro packet received in get_ping_results");
  967.             continue;
  968.         }  
  969.         foundsomething = 0;
  970.         dotimeout = 0;
  971.  
  972.         /* First check if it is ICMP or TCP */
  973.         if (ip->ip_p == IPPROTO_ICMP) 
  974.         {    
  975.             /* if it is our response */
  976.             ping = (struct ppkt *) ((ip->ip_hl * 4) + (char *) ip);
  977.             if (bytes < ip->ip_hl * 4 + 8) 
  978.             {
  979.                 error("Supposed ping packet is only %d bytes long!", bytes);
  980.                 continue;
  981.             }
  982.             //printf( "PING: type = %d, code = %d, id = %d : regular id=%d\n", ping->type, ping->code, ping->id,id);
  983.             if  ( !ping->type && !ping->code && ping->id == id) 
  984.             {
  985.                 hostnum = ping->seq / pt->max_tries;
  986.                 if (hostnum > pt->group_end) 
  987.                 {
  988.                     if (o.debugging) error("Ping sequence %d leads to hostnum %d which is beyond the end of this group (%d)", ping->seq, hostnum, pt->group_end);
  989.                     continue;
  990.                 }
  991.                 if (!hostbatch[hostnum].source_ip.s_addr) hostbatch[hostnum].source_ip.s_addr = ip->ip_dst.s_addr;
  992.                 if (o.debugging) log_write(LOG_STDOUT, "We got a ping packet back from %s: id = %d seq = %d checksum = %d\n", inet_ntoa(ip->ip_src), ping->id, ping->seq, ping->checksum);
  993.                 if (hostbatch[hostnum].host.s_addr == ip->ip_src.s_addr) 
  994.                 {
  995.                     foundsomething = 1;
  996.                     pingtype = PINGTYPE_ICMP;
  997.                     sequence = ping->seq;
  998.                     newstate = HOST_UP;
  999.                     trynum = sequence % pt->max_tries;
  1000.                     if (pt->discardtimesbefore < ping->seq) dotimeout = 1;
  1001.                     else dotimeout = 0;
  1002.                 }
  1003.                 else hostbatch[hostnum].wierd_responses++;
  1004.             }
  1005.             else if (ping->type == 3 || ping->type == 11 || ping->type == 4 || o.debugging) 
  1006.             {
  1007.                 if (bytes <  ip->ip_hl * 4 + 28) 
  1008.                 {
  1009.                     if (o.debugging) error("ICMP type %d code %d packet is only %d bytes\n", ping->type, ping->code, bytes);
  1010.                     continue;
  1011.                 }
  1012.                 ip2 = (struct ip *) ((char *)ip + ip->ip_hl * 4 + 8);
  1013.                 if (bytes < ip->ip_hl * 4 + 8 + ip2->ip_hl * 4 + 8) 
  1014.                 {
  1015.                     if (o.debugging) error("ICMP type %d code %d packet is only %d bytes\n", ping->type, ping->code, bytes);
  1016.                     continue;
  1017.                 }
  1018.                 ping2 = (struct ppkt *) ((char *)ip2 + ip2->ip_hl * 4);
  1019.                 if (ping2->id != id) 
  1020.                 {
  1021.                     if (o.debugging) 
  1022.                     {    
  1023.                         error("Illegal id %d found, should be %d (icmp type/code %d/%d)", ping2->id, id, ping->type, ping->code);
  1024.                         if (o.debugging > 1) lamont_hdump((char *)ip, bytes);
  1025.                     }
  1026.                     continue;
  1027.                 }
  1028.                 sequence = ping2->seq;
  1029.                 hostnum = sequence / pt->max_tries;
  1030.                 trynum = sequence % pt->max_tries;
  1031.                 if (hostnum > pt->group_end) 
  1032.                 {
  1033.                     if (o.debugging) error("Bogus ping sequence: %d leads to bogus hostnum %d (icmp type/code %d/%d", sequence, hostnum, ping->type, ping->code);
  1034.                     continue;
  1035.                 }
  1036.                 if (ping->type == 3) 
  1037.                 {
  1038.                     if (o.debugging) 
  1039.                     log_write(LOG_STDOUT, "Got destination unreachable for %s\n", inet_ntoa(hostbatch[hostnum].host));
  1040.                     /* Since this gives an idea of how long it takes to get an answer,
  1041.                     we add it into our times */
  1042.                     if (pt->discardtimesbefore < sequence) dotimeout = 1;    
  1043.                     foundsomething = 1;
  1044.                     pingtype = PINGTYPE_ICMP;
  1045.                     newstate = HOST_DOWN;
  1046.                 } 
  1047.                 else if (ping->type == 11) 
  1048.                 {
  1049.                     if (o.debugging) 
  1050.                     log_write(LOG_STDOUT, "Got Time Exceeded for %s\n", inet_ntoa(hostbatch[hostnum].host));
  1051.                     dotimeout = 0; /* I don't want anything to do with timing this */
  1052.                     foundsomething = 1;
  1053.                     pingtype = PINGTYPE_ICMP;
  1054.                     newstate = HOST_DOWN;
  1055.                 }
  1056.                 else if (ping->type == 4) 
  1057.                 {      
  1058.                     if (o.debugging) log_write(LOG_STDOUT, "Got ICMP source quench\n");
  1059.                     usleep(50000);
  1060.                 }  
  1061.                 else if (o.debugging > 0) 
  1062.                 {
  1063.                     log_write(LOG_STDOUT, "Got ICMP message type %d code %d\n", ping->type, ping->code);
  1064.                 }
  1065.             }
  1066.         } 
  1067.         else if (ip->ip_p == IPPROTO_TCP) 
  1068.         {
  1069.             tcp = (struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl);
  1070.             if (!(tcp->th_flags & TH_RST) && ((tcp->th_flags & (TH_SYN|TH_ACK)) != (TH_SYN|TH_ACK))) continue;
  1071.             newport = ntohs(tcp->th_sport);
  1072.             tmpl = ntohl(tcp->th_ack);
  1073.             /* Grab the sequence nr */
  1074.             if (o.pingtype & PINGTYPE_TCP_USE_SYN) 
  1075.             {      
  1076.                 if ((tmpl & 7) == 4 || (tmpl & 7) == 3) 
  1077.                 {
  1078.                     sequence = (tmpl >> 3) & 0xffff;
  1079.                     hostnum = sequence / pt->max_tries;
  1080.                     trynum = sequence % pt->max_tries;
  1081.                 } 
  1082.                 else 
  1083.                 {
  1084.                     if (o.debugging) 
  1085.                     {
  1086.                         error("Whacked ACK number from %s", inet_ntoa(ip->ip_src));
  1087.                     }    
  1088.                     continue;    
  1089.                 }
  1090.             } 
  1091.             else 
  1092.             {
  1093.                     trynum = ntohs(tcp->th_dport) - sportbase;
  1094.                     if (trynum >= pt->max_tries) 
  1095.                     {
  1096.                         if (o.debugging) error("Bogus trynum %d", trynum);
  1097.                         continue;
  1098.                     }
  1099.                     /* FUDGE!  This ACK scan is cool but we don't get sequence numbers
  1100.                     back! We'll have to brute force lookup to find the hostnum */
  1101.                 for(hostnum = pt->group_end; hostnum >= 0; hostnum--) 
  1102.                 {
  1103.                     if (hostbatch[hostnum].host.s_addr == ip->ip_src.s_addr) break;
  1104.                 }
  1105.                 if (hostnum < 0) 
  1106.                 {    
  1107.                     if (o.debugging > 1) 
  1108.                     error("Warning, unexpacted packet from machine %s", inet_ntoa(ip->ip_src));
  1109.                     continue;
  1110.                 }    
  1111.                 sequence = hostnum * pt->max_tries + trynum;
  1112.             }
  1113.             if (hostnum > pt->group_end) 
  1114.             {
  1115.                 if (o.debugging) 
  1116.                 {
  1117.                     error("Response from host beyond group_end");
  1118.                 }
  1119.                 continue;
  1120.             }
  1121.             if (o.debugging)  log_write(LOG_STDOUT, "We got a TCP ping packet back from %s (hostnum = %d trynum = %d\n", inet_ntoa(ip->ip_src), hostnum, trynum);
  1122.             pingtype = PINGTYPE_RAWTCP;
  1123.             foundsomething = 1;
  1124.             if (pt->discardtimesbefore < sequence) dotimeout = 1;
  1125.             newstate = HOST_UP;
  1126.         } 
  1127.         else if (o.debugging) 
  1128.         {
  1129.             error("Found whacked packet protocol %d in get_ping_results", ip->ip_p);
  1130.         }
  1131.         if (foundsomething) 
  1132.         {  
  1133.             hostupdate(hostbatch, &hostbatch[hostnum], newstate, dotimeout, trynum, to, &time[sequence], pt, NULL,pingtype);
  1134.         }
  1135.     }
  1136.     return 0;
  1137. }
  1138.  
  1139. int hostupdate(struct hoststruct *hostbatch, struct hoststruct *target, 
  1140.            int newstate, int dotimeout, int trynum, 
  1141.            struct timeout_info *to, struct timeval *sent, 
  1142.            struct pingtune *pt, struct tcpqueryinfo *tqi, int pingtype) {
  1143.  
  1144. int hostnum = target - hostbatch;
  1145. int i;
  1146. int seq;
  1147. int tmpsd;
  1148. struct timeval tv;
  1149.  
  1150. if (o.debugging)  {
  1151.   gettimeofday(&tv, NULL);
  1152.   log_write(LOG_STDOUT, "Hostupdate called for machine %s state %s -> %s (trynum %d, dotimeadj: %s time: %ld)\n", inet_ntoa(target->host), readhoststate(target->flags), readhoststate(newstate), trynum, (dotimeout)? "yes" : "no", (long) TIMEVAL_SUBTRACT(tv, *sent));
  1153. }
  1154. assert(hostnum <= pt->group_end);
  1155.  
  1156. if (dotimeout) {
  1157.   adjust_timeouts(*sent, to);
  1158. }
  1159.  
  1160. /* If this is a tcp connect() pingscan, close all sockets */
  1161.  
  1162. if (pingtype == PINGTYPE_CONNECTTCP) {
  1163.   seq = (target - hostbatch) * pt->max_tries + trynum;
  1164.   assert(tqi->sockets[seq] >= 0);
  1165.   for(i=0; i <= pt->block_tries; i++) {  
  1166.     seq = (target - hostbatch) * pt->max_tries + i;
  1167.     tmpsd = tqi->sockets[seq];
  1168.     if (tmpsd >= 0) {
  1169.       assert(tqi->sockets_out > 0);
  1170.       tqi->sockets_out--;
  1171.       close(tmpsd);
  1172.       if (tmpsd == tqi->maxsd) tqi->maxsd--;
  1173. //      FD_CLR(tmpsd, &(tqi->fds_r));
  1174. //      FD_CLR(tmpsd, &(tqi->fds_w));
  1175. //      FD_CLR(tmpsd, &(tqi->fds_x));
  1176.       tqi->sockets[seq] = -1;
  1177.     }
  1178.   }
  1179. }
  1180.  
  1181.  
  1182. target->to = *to;
  1183.  
  1184. if (target->flags & HOST_UP) {
  1185.   /* The target is already up and that takes precedence over HOST_DOWN
  1186.      or HOST_FIREWALLED, so we just return. */
  1187.   return 0;
  1188. }
  1189.  
  1190. if (trynum > 0 && !(pt->dropthistry)) {
  1191.   pt->dropthistry = 1;
  1192.   if (o.debugging) 
  1193.     log_write(LOG_STDOUT, "Decreasing massping group size from %d to ", pt->group_size);
  1194.   pt->group_size = MAX(pt->group_size * 0.75, 10);
  1195.   if (o.debugging) 
  1196.     log_write(LOG_STDOUT, "%d\n", pt->group_size);
  1197. }
  1198.  
  1199. if (newstate == HOST_DOWN && (target->flags & HOST_DOWN)) {
  1200.   /* I see nothing to do here */
  1201. } else if (newstate == HOST_UP && (target->flags & HOST_DOWN)) {
  1202.   /* We give host_up precedence */
  1203.   target->flags &= ~HOST_DOWN; /* Kill the host_down flag */
  1204.   target->flags |= HOST_UP;
  1205.   if (hostnum >= pt->group_start) {  
  1206.     assert(pt->down_this_block > 0);
  1207.     pt->down_this_block--;
  1208.     pt->up_this_block++;
  1209.   }
  1210. } else if (newstate == HOST_DOWN) {
  1211.   target->flags |= HOST_DOWN;
  1212.   pt->down_this_block++;
  1213.   pt->block_unaccounted--;
  1214.   pt->num_responses++;
  1215. } else {
  1216.   assert(newstate == HOST_UP);
  1217.   target->flags |= HOST_UP;
  1218.   pt->up_this_block++;
  1219.   pt->block_unaccounted--;
  1220.   pt->num_responses++;
  1221. }
  1222. return 0;
  1223. }
  1224.  
  1225. char *readhoststate(int state) {
  1226.   switch(state) {
  1227.   case HOST_UP:
  1228.     return "HOST_UP";
  1229.   case HOST_DOWN:
  1230.     return "HOST_DOWN";
  1231.   case HOST_FIREWALLED:
  1232.     return "HOST_FIREWALLED";
  1233.   default:
  1234.     return "UNKNOWN/COMBO";
  1235.   }
  1236.   return NULL;
  1237. }
  1238.  
  1239.  
  1240.  
  1241.