home *** CD-ROM | disk | FTP | other *** search
/ Steganos Hacker Tools / SHT151.iso / programme / scanner / nmapNTsp1 / Win_2000.exe / nmapNT-src / utils.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-07-07  |  13.8 KB  |  569 lines

  1. #include "utils.h"
  2.  
  3.  
  4. void *safe_malloc(int size)
  5. {
  6.   void *mymem;
  7.   if (size < 0)
  8.     fatal("Tried to malloc negative amount of memory!!!");
  9.   mymem = malloc(size);
  10.   if (mymem == NULL)
  11.     fatal("Malloc Failed! Probably out of space.");
  12.   return mymem;
  13. }
  14.  
  15.  
  16. /* Hex dump */
  17. void hdump(unsigned char *packet, int len) {
  18. unsigned int i=0, j=0;
  19.  
  20. printf("Here it is:\n");
  21.  
  22. for(i=0; i < len; i++){
  23.   j = (unsigned) (packet[i]);
  24.   printf("%-2X ", j);
  25.   if (!((i+1)%16))
  26.     printf("\n");
  27.   else if (!((i+1)%4))
  28.     printf("  ");
  29. }
  30. printf("\n");
  31. }
  32.  
  33. /* A better version of hdump, from Lamont Granquist.  Modified slightly
  34.    by Fyodor (fyodor@DHP.com) */
  35. void lamont_hdump(unsigned char *bp, int length) {
  36.  
  37.   /* stolen from tcpdump, then kludged extensively */
  38.  
  39.   static const char asciify[] = "................................ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~.................................................................................................................................";
  40.  
  41.   register const u_short *sp;
  42.   register const u_char *ap;
  43.   register u_int i, j;
  44.   register int nshorts, nshorts2;
  45.   register int padding;
  46.  
  47.   printf("\n\t");
  48.   padding = 0;
  49.   sp = (u_short *)bp;
  50.   ap = (u_char *)bp;
  51.   nshorts = (u_int) length / sizeof(u_short);
  52.   nshorts2 = (u_int) length / sizeof(u_short);
  53.   i = 0;
  54.   j = 0;
  55.   while(1) {
  56.     while (--nshorts >= 0) {
  57.       printf(" %04x", ntohs(*sp));
  58.       sp++;
  59.       if ((++i % 8) == 0)
  60.         break;
  61.     }
  62.     if (nshorts < 0) {
  63.       if ((length & 1) && (((i-1) % 8) != 0)) {
  64.         printf(" %02x  ", *(u_char *)sp);
  65.         padding++;
  66.       }
  67.       nshorts = (8 - (nshorts2 - nshorts));
  68.       while(--nshorts >= 0) {
  69.         printf("     ");
  70.       }
  71.       if (!padding) printf("     ");
  72.     }
  73.     printf("  ");
  74.  
  75.     while (--nshorts2 >= 0) {
  76.       printf("%c%c", asciify[*ap], asciify[*(ap+1)]);
  77.       ap += 2;
  78.       if ((++j % 8) == 0) {
  79.         printf("\n\t");
  80.         break;
  81.       }
  82.     }
  83.     if (nshorts2 < 0) {
  84.       if ((length & 1) && (((j-1) % 8) != 0)) {
  85.         printf("%c", asciify[*ap]);
  86.       }
  87.       break;
  88.     }
  89.   }
  90.   if ((length & 1) && (((i-1) % 8) == 0)) {
  91.     printf(" %02x", *(u_char *)sp);
  92.     printf("                                       %c", asciify[*ap]);
  93.   }
  94.   printf("\n");
  95. }
  96.  
  97. #ifndef HAVE_STRCASESTR
  98. char *strcasestr(char *haystack, char *pneedle) {
  99. char buf[512];
  100. unsigned int needlelen;
  101. char *needle, *p, *q, *foundto;
  102.  
  103. /* Should crash if !pneedle -- this is OK */
  104. if (!*pneedle) return haystack;
  105. if (!haystack) return NULL;
  106.  
  107. needlelen = strlen(pneedle);
  108.  if (needlelen >= sizeof(buf)) {
  109.    needle = (char *) malloc(needlelen + 1);
  110.  } else needle = buf;
  111.  p = pneedle; q = needle;
  112. #ifdef WIN32
  113.  while((*q++ = _tolower(*p++)))
  114.    ;
  115.  p = haystack - 1; foundto = needle;
  116.  while(*++p) {
  117.    if(_tolower(*p) == *foundto) {
  118. #else
  119.  while((*q++ = tolower(*p++)))
  120.    ;
  121.  p = haystack - 1; foundto = needle;
  122.  while(*++p) {
  123.    if(tolower(*p) == *foundto) {
  124. #endif
  125.      if(!*++foundto) {
  126.        /* Yeah, we found it */
  127.        if (needlelen >= sizeof(buf))
  128.          free(needle);
  129.        return p - needlelen + 1;
  130.      }
  131.    } else foundto = needle;
  132.  }
  133.  if (needlelen >= sizeof(buf))
  134.    free(needle);
  135.  return NULL;
  136. }
  137. #endif
  138.  
  139. int Strncpy(char *dest, const char *src, size_t n) {
  140.   strncpy(dest, src, n);
  141.   if (dest[n-1] == '\0')
  142.     return 0;
  143.   dest[n-1] = '\0';
  144.   return -1;
  145. }
  146.  
  147. #ifndef HAVE_USLEEP
  148. #ifdef HAVE_NANOSLEEP
  149. void usleep(unsigned long usec) {
  150. struct timespec ts; 
  151. ts.tv_sec = usec / 1000000; 
  152. ts.tv_nsec = (usec % 1000000) * 1000; 
  153. nanosleep(&ts, NULL);
  154. }
  155. #endif
  156. #endif
  157.  
  158. #ifndef HAVE_STRERROR
  159. char *strerror(int errnum) {
  160.   static char buf[1024];
  161.   sprintf(buf, "your system is too old for strerror of errno %d\n", errnum);
  162.   return buf;
  163. }
  164. #endif
  165.  
  166. /* Like the perl equivialent -- It removes the terminating newline from string
  167.    IF one exists.  It then returns the POSSIBLY MODIFIED string */
  168. char *chomp(char *string) {
  169.   int len;
  170.   len = strlen(string);
  171.   if (len < 1)
  172.     return string;
  173.   if (string[len - 1] != '\n')
  174.     return string;  
  175.   if (len > 1 && string[len-2] == '\r') {
  176.     string[len-2] = '\0';
  177.   } else string[len-1] = '\0';
  178.   return string;
  179. }
  180.  
  181.  
  182. int get_random_int() {
  183. int i;
  184. get_random_bytes(&i, sizeof(int));
  185. return i;
  186. }
  187.  
  188. unsigned int get_random_uint() {
  189. unsigned int i;
  190. get_random_bytes(&i, sizeof(unsigned int));
  191. return i;
  192. }
  193.  
  194. unsigned short get_random_ushort() {
  195. unsigned short s;
  196. get_random_bytes(&s, sizeof(unsigned short));
  197. return s;
  198. }
  199.  
  200. int get_random_bytes(void *buf, int numbytes) {
  201. static char bytebuf[2048];
  202. static char badrandomwarning = 0;
  203. static int bytesleft = 0;
  204. int res;
  205. int tmp;
  206. struct timeval tv;
  207. FILE *fp = NULL;
  208. unsigned int i;
  209. short *iptr;
  210.  
  211. if (numbytes < 0 || numbytes > 0xFFFF) return -1;
  212.  
  213. if (bytesleft == 0) {
  214.   fp = fopen("/dev/urandom", "r");
  215.   if (!fp) fp = fopen("/dev/random", "r");
  216.   if (fp) {
  217.     res = fread(bytebuf, 1, sizeof(bytebuf), fp);
  218.     if (res != sizeof(bytebuf)) {    
  219.       error("Failed to read from /dev/urandom or /dev/random");
  220.       fclose(fp);
  221.       fp = NULL;
  222.     }      
  223.     bytesleft = sizeof(bytebuf);
  224.   }
  225.   if (!fp) {  
  226.     if (badrandomwarning == 0) {
  227.       badrandomwarning++;
  228.       /*      error("WARNING: your system apparently does not offer /dev/urandom or /dev/random.  Reverting to less secure version."); */
  229.     }
  230.     /* Seed our random generator */
  231.     gettimeofday(&tv, NULL);
  232.     srand((tv.tv_sec ^ tv.tv_usec) ^ getpid());
  233.  
  234.     for(i=0; i < sizeof(bytebuf) / sizeof(short); i++) {
  235.       iptr = (short *) ((char *)bytebuf + i * sizeof(short));
  236.       *iptr = rand();
  237.     }
  238.     bytesleft = (sizeof(bytebuf) / sizeof(short)) * sizeof(short);
  239.     /*    ^^^^^^^^^^^^^^^not as meaningless as it looks  */
  240.   } else fclose(fp);
  241. }
  242.  
  243. if (numbytes <= bytesleft) { /* we can cover it */
  244.   memcpy(buf, bytebuf + (sizeof(bytebuf) - bytesleft), numbytes);
  245.   bytesleft -= numbytes;
  246.   return 0;
  247. }
  248.  
  249. /* We don't have enough */
  250. memcpy(buf, bytebuf + (sizeof(bytebuf) - bytesleft), bytesleft);
  251. tmp = bytesleft;
  252. bytesleft = 0;
  253. return get_random_bytes((char *)buf + tmp, numbytes - tmp);
  254. }
  255.  
  256. /* Scramble the contents of an array*/
  257. void genfry(unsigned char *arr, int elem_sz, int num_elem) {
  258. int i;
  259. unsigned int pos;
  260. unsigned char *bytes;
  261. unsigned char *cptr;
  262. unsigned short *sptr;
  263. unsigned int *iptr;
  264. unsigned char *tmp;
  265. int bpe;
  266.  
  267. if (sizeof(unsigned char) != 1)
  268.   fatal("genfry() requires 1 byte chars");
  269.  
  270. if (num_elem < 2)
  271.   return;
  272.  
  273.  if (elem_sz == sizeof(unsigned short)) {
  274.    shortfry((unsigned short *)arr, num_elem);
  275.    return;
  276.  }
  277.  
  278. /* OK, so I am stingy with the random bytes! */
  279. if (num_elem < 256) 
  280.   bpe = sizeof(unsigned char);
  281. else if (num_elem < 65536)
  282.   bpe = sizeof(unsigned short);
  283. else bpe = sizeof(unsigned int);
  284.  
  285. bytes = malloc(bpe * num_elem);
  286. tmp = malloc(elem_sz);
  287.  
  288. get_random_bytes(bytes, bpe * num_elem);
  289. cptr = bytes;
  290. sptr = (unsigned short *)bytes;
  291. iptr = (unsigned int *) bytes;
  292.  
  293.  for(i=num_elem - 1; i > 0; i--) {
  294.    if (num_elem < 256) {
  295.      pos = *cptr; cptr++;
  296.    }
  297.    else if (num_elem < 65536) {
  298.      pos = *sptr; sptr++;
  299.    } else {
  300.      pos = *iptr; iptr++;
  301.    }
  302.    pos %= i+1;
  303.    memcpy(tmp, arr + elem_sz * i, elem_sz);
  304.    memcpy(arr + elem_sz * i, arr + elem_sz * pos, elem_sz);
  305.    memcpy(arr + elem_sz * pos, tmp, elem_sz);
  306.  }
  307.  free(bytes);
  308.  free(tmp);
  309. }
  310.  
  311. void shortfry(unsigned short *arr, int num_elem) {
  312. int num;
  313. unsigned short tmp;
  314. int i;
  315.  
  316. if (num_elem < 2)
  317.   return;
  318.  
  319.  for(i= num_elem - 1; i > 0 ; i--) {
  320.    num = get_random_ushort() % (i + 1);
  321.    tmp = arr[i];
  322.    arr[i] = arr[num];
  323.    arr[num] = tmp;
  324.  } 
  325.  
  326.  return;
  327. }
  328.  
  329. ssize_t Write(int fd, const void *buf, size_t count) {
  330.   int res;
  331.   unsigned int len;
  332.  
  333.   len = 0;
  334.   do {
  335.     res = write(fd,(char *) buf + len,count - len);
  336.     if (res > 0)
  337.       len += res;
  338.   } while(len < count && (res != -1 || errno == EINTR));
  339.  
  340.   return res;
  341. }
  342.  
  343.  
  344. /* gcd_1 and gcd_n_long were sent in by Peter Kosinar <goober@gjh.sk> 
  345.    Not needed for gcd_n_long, just for the case you'd want to have gcd
  346.    for two arguments too. */
  347. unsigned long gcd_ulong(unsigned long a, unsigned long b)
  348. {
  349.   /* Shorter
  350.      while (b) { a%=b; if (!a) return b; b%=a; } */
  351.   
  352.   /* Faster */
  353.   unsigned long c; 
  354.   if (a<b) { c=a; a=b; b=c; }
  355.   while (b) { c=a%b; a=b; b=c; }
  356.   
  357.   /* Common for both */
  358.   return a;
  359. }
  360.  
  361. unsigned long gcd_n_ulong(long nvals, unsigned long *val)
  362.  {
  363.    unsigned long a,b,c;
  364.    
  365.    if (!nvals) return 1;
  366.    a=*val;
  367.    for (nvals--;nvals;nvals--)
  368.      {
  369.        b=*++val;
  370.        if (a<b) { c=a; a=b; b=c; }
  371.        while (b) { c=a%b; a=b; b=c; }
  372.      }
  373.    return a;
  374.  }
  375.  
  376. unsigned int gcd_uint(unsigned int a, unsigned int b)
  377. {
  378.   /* Shorter
  379.      while (b) { a%=b; if (!a) return b; b%=a; } */
  380.   
  381.   /* Faster */
  382.   unsigned int c; 
  383.   if (a<b) { c=a; a=b; b=c; }
  384.   while (b) { c=a%b; a=b; b=c; }
  385.   
  386.   /* Common for both */
  387.   return a;
  388. }
  389.  
  390. unsigned int gcd_n_uint(int nvals, unsigned int *val)
  391.  {
  392.    unsigned int a,b,c;
  393.    
  394.    if (!nvals) return 1;
  395.    a=*val;
  396.    for (nvals--;nvals;nvals--)
  397.      {
  398.        b=*++val;
  399.        if (a<b) { c=a; a=b; b=c; }
  400.        while (b) { c=a%b; a=b; b=c; }
  401.      }
  402.    return a;
  403.  }
  404.  
  405. /* This function takes a command and the address of an uninitialized
  406.    char ** .  It parses the command (by seperating out whitespace)
  407.    into an argv[] style char **, which it sets the argv parameter to.
  408.    The function returns the number of items filled up in the array
  409.    (argc), or -1 in the case of an error.  This function allocates
  410.    memmory for argv and thus it must be freed -- use argv_parse_free()
  411.    for that.  If arg_parse returns <1, then argv does not need to be freed.
  412.    The returned arrays are always terminated with a NULL pointer */
  413. int arg_parse(const char *command, char ***argv) {
  414.   char **myargv = NULL;
  415.   int argc = 0;
  416.   char mycommand[4096];
  417.   unsigned char *start, *end;
  418.   char oldend;
  419.  
  420.   *argv = NULL;
  421.   if (Strncpy(mycommand, command, 4096) == -1) {      
  422.     return -1;
  423.   }
  424.   myargv = malloc((MAX_PARSE_ARGS + 2) * sizeof(char *));
  425.   bzero(myargv, (MAX_PARSE_ARGS+2) * sizeof(char *));
  426.   myargv[0] = (char *) 0x123456; /* Integrity checker */
  427.   myargv++;
  428.   start = mycommand;
  429.   while(start && *start) {
  430.     while(*start && isspace(*start))
  431.       start++;
  432.     if (*start == '"') {
  433.       start++;
  434.       end = strchr(start, '"');
  435.     } else if (*start == '\'') {
  436.       start++;
  437.       end = strchr(start, '\'');      
  438.     } else if (!*start) {
  439.       continue;
  440.     } else {
  441.       end = start+1;
  442.       while(*end && !isspace(*end)) {      
  443.     end++;
  444.       }
  445.     }
  446.     if (!end) {
  447.       arg_parse_free(myargv);
  448.       return -1;
  449.     }
  450.     if (argc >= MAX_PARSE_ARGS) {
  451.       arg_parse_free(myargv);
  452.       return -1;
  453.     }
  454.     oldend = *end;
  455.     *end = '\0';
  456.     myargv[argc++] = strdup(start);
  457.     if (oldend)
  458.       start = end + 1;
  459.     else start = end;
  460.   }
  461.   myargv[argc+1] = 0;
  462.   *argv = myargv;
  463.   return argc;
  464. }
  465.  
  466. /* Free an argv allocated inside arg_parse */
  467. void arg_parse_free(char **argv) {
  468.   char **current;
  469.   /* Integrity check */
  470.   argv--;
  471.   assert(argv[0] == (char *) 0x123456);
  472.   current = argv + 1;
  473.   while(*current) {
  474.     free(*current);
  475.     current++;
  476.   }
  477.   free(argv);
  478. }
  479.  
  480.  
  481. /* mmap() an entire file into the address space.  Returns a pointer
  482.    to the beginning of the file.  The mmap'ed length is returned
  483.    inside the length parameter.  If there is a problem, NULL is
  484.    returned, the value of length is undefined, and errno is set to
  485.    something appropriate.  The user is responsible for doing
  486.    an munmap(ptr, length) when finished with it.  openflags should 
  487.    be O_RDONLY or O_RDWR, or O_WRONLY
  488. */
  489. #ifdef WIN32
  490. char *mmapfile(char *fname, int *length, int openflags) {
  491. //  struct _stat st;
  492. //  int fd;
  493. HANDLE fd;
  494.   char *fileptr;
  495.  
  496.   if (!length || !fname) {
  497.     errno = EINVAL;
  498.     return NULL;
  499.   }
  500.  
  501.   *length = -1;
  502.  
  503. fd= CreateFile(fname,
  504.              openflags,                // open for writing 
  505.              0,                            // do not share 
  506.              NULL,                         // no security 
  507.              OPEN_EXISTING,                // overwrite existing 
  508.              FILE_ATTRIBUTE_NORMAL,
  509.              NULL);                        // no attr. template 
  510.  
  511. //  fd = _open(fname, openflags);
  512. //  if (fd == -1) {
  513. //    return NULL;
  514. //  }
  515. gmap=CreateFileMapping(fd,NULL, (openflags & O_RDONLY)? PAGE_READONLY:(openflags & O_RDWR)? (PAGE_READONLY|PAGE_READWRITE) : PAGE_READWRITE,0,0,NULL);
  516.  
  517. fileptr = (char *)MapViewOfFile(gmap, FILE_MAP_ALL_ACCESS,0,0,0);
  518. //  fileptr = (char *) mmap(0, st.st_size, (openflags & O_RDONLY)? PROT_READ :
  519. //                 (openflags & O_RDWR)? (PROT_READ|PROT_WRITE) : PROT_WRITE,
  520. //                 MAP_SHARED, fd, 0);
  521. *length = (int) GetFileSize(fd,NULL);
  522.   CloseHandle(fd);
  523.  
  524. #ifdef MAP_FAILED
  525.   if (fileptr == MAP_FAILED) return NULL;
  526. #else
  527.   if (fileptr == (char *) -1) return NULL;
  528. #endif
  529.   return fileptr;
  530. }
  531. #else
  532. char *mmapfile(char *fname, int *length, int openflags) {
  533.   struct stat st;
  534.   int fd;
  535.   char *fileptr;
  536.  
  537.   if (!length || !fname) {
  538.     errno = EINVAL;
  539.     return NULL;
  540.   }
  541.  
  542.   *length = -1;
  543.  
  544.   if (stat(fname, &st) == -1) {
  545.     errno = ENOENT;
  546.     return NULL;
  547.   }
  548.  
  549.   fd = open(fname, openflags);
  550.   if (fd == -1) {
  551.     return NULL;
  552.   }
  553.  
  554.   fileptr = (char *) mmap(0, st.st_size, (openflags & O_RDONLY)? PROT_READ :
  555.                  (openflags & O_RDWR)? (PROT_READ|PROT_WRITE) : PROT_WRITE,
  556.                  MAP_SHARED, fd, 0);
  557.  
  558.   close(fd);
  559.  
  560. #ifdef MAP_FAILED
  561.   if (fileptr == MAP_FAILED) return NULL;
  562. #else
  563.   if (fileptr == (char *) -1) return NULL;
  564. #endif
  565.  
  566.   *length = st.st_size;
  567.   return fileptr;
  568. }
  569. #endif