#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/stat.h>
#include <sys/types.h>

#define MAX_COUNT 65536

unsigned char vars[7] = { 0, 1, 127, 128, 254, 255 };

char *inject[MAX_COUNT];
int inject_len[MAX_COUNT];
unsigned int injoff[MAX_COUNT];
int injlen[MAX_COUNT];

int main(int argc, char *argv[]) {
  FILE *f, *g, *inj;
  unsigned int i, j, k, count, pos, size, value, max_size = 0, pos_cnt = 0, flen, cpos = 0;
  char *fname, *fext = "bin", *foo, *ptr, *newname, rbuf[67556];
  char *buf, *buf2, amount, verbose = 0, conv, tmp;
  int change_count = 1, cnt, do_random = 1, do_inject = 0, inj_cnt = 0, inj_max_len = 0, fixed = -1, forward = 0, ii;
  struct stat st;

  setvbuf(stdout, NULL, _IONBF, 0);
  setvbuf(stderr, NULL, _IONBF, 0);

  if (argc < 3) {
    printf("Syntax: %s [-vxf] [-X value] count inputfile [max-offset] [no-of-changes] [injectfile]\n", argv[0]);
    printf("\nOptions:\n");
    printf(" -v  verbose output\n");
    printf(" -x  special values for the numbers (0,1,127,128,254,255,xor; default: random)\n");
    printf(" -X value  always fixed byte value, the character is defined in decimal\n");
//    printf(" -f  instead of random location start by 0 and increase by 1 until EOF\n");
    printf("Mandatory parameters:\n count - how many cases to generate\n inputfile - the input file\n");
    printf("Additional optional parameters:\n");
    printf(" max-offset     maximum offset (byte, default: file size))\n");
    printf(" no-of-changes  number of changes to make per file (default: 1)\n");
    printf(" inject-file    adds text string injection (also of number of counts)\n");
    printf("    The inject-file may contain %%hex values which will be converted to binary.\n    Use %%%% to send a %%.\n");
    exit(-1);
  }

  while ((ii = getopt(argc, argv, "vxX:f")) >= 0) {
    switch (ii) {
      case 'v':
        verbose = 1;
        break;
      case 'X':
        fixed = atoi(optarg);
        // fall through
      case 'x':
        do_random = 0;
        break;
      case 'f':
        forward = 1;
        break;
      default:
        fprintf(stderr, "Error: invalid option %c\n", ii);
        exit(-1);
    }
  }

  if ((f = fopen(argv[optind + 1], "r")) == NULL) {
    printf("File not found: %s\n", argv[optind + 1]);
    exit(-1);
  }

  fstat(fileno(f), &st);
  flen = st.st_size;

  buf = malloc(flen + 256);
  buf2 = malloc(flen + 256);
  if (buf == NULL || buf2 == NULL) {
    fprintf(stderr, "Error allocating %d bytes\n", flen * 2 + 512);
    exit(-1);
  }

  if ((count = atoi(argv[optind])) < 1) {
    printf("count wrong\n");
    exit(-1);
  }

  if ((size = fread(buf, 1, flen, f)) < 1) {
    printf("file could not be read\n");
    exit(-1);
  }
  memcpy(buf2, buf, size);

  if (argc - optind > 2)
    max_size = atoi(argv[optind + 2]);
  else
    max_size = size;

  if (argc - optind > 3)
    change_count = atoi(argv[optind + 3]);

  if (argc - optind > 4) {
    j = 0;
    for (i = 0; i < size; i++) {
      if (isprint(buf[i]) != 0)
        j++;
      else {
        if (j > 2) {
          injoff[pos_cnt] = i - j;
          injlen[pos_cnt] = j;
          pos_cnt++;
        }
        if (j > inj_max_len)
          inj_max_len = j;
        j = 0;
      }
    }
    if (verbose)
      printf("Found %d possible entries to inject in the input file\n", pos_cnt);
    if ((inj = fopen(argv[optind + 4], "r")) == NULL) {
      printf("File not found: %s\n", argv[optind + 4]);
      exit(-1);
    }
    while (fgets(rbuf, sizeof(rbuf), inj) != NULL && inj_cnt < MAX_COUNT) {
      if (rbuf[strlen(rbuf) - 1] == '\n')
        rbuf[strlen(rbuf) - 1] = 0;
      if (rbuf[strlen(rbuf) - 1] == '\r')
        rbuf[strlen(rbuf) - 1] = 0;
      if (index(rbuf, '%') != NULL) {
        ptr = rbuf;
        j = strlen(rbuf);
        for (i = 0; i < j; i++) {
          if (rbuf[i] == '%') {
            if (i + 2 <= j && isxdigit((int) rbuf[i + 1]) && isxdigit((int) rbuf[i + 2])) {
              conv = 0;
              tmp = toupper((int) rbuf[i + 1]) - '0';
              if (tmp > 9)
                conv = (tmp + '0' - 'A') * 16;
              else
                conv = tmp * 16;
              tmp = toupper((int) rbuf[i + 2]) - '0';
              if (tmp > 9)
                conv += tmp + '0' - 'A';
              else
                conv += tmp;
              *ptr = conv;
              i += 2;
            } else {
              if (rbuf[i + 1] == '%' && i + 1 <= j)
                i++;
              else
                printf("Warning: %% found in fuzzfile that could not be converted to binary!\n");
              *ptr = rbuf[i];
            }
          } else
            *ptr = rbuf[i];
          ptr++;
        }
        *ptr = 0;
      }

      if (strlen(rbuf) <= inj_max_len) {
        inject_len[inj_cnt] = strlen(rbuf);
        inject[inj_cnt++] = strdup(rbuf);
      }
    }
    if (verbose)
      printf("Read in %d lines from %s with maximum length of %d\n", inj_cnt, argv[optind + 4], inj_max_len);
    if (inj_cnt && pos_cnt)
      do_inject = 1;
    else
      printf("Warning: unable to do injection\n");
  }

  if (max_size > size)
    max_size = size;

  foo = strdup(argv[optind + 1]);
  fname = foo;
  if ((ptr = strchr(fname, '.')) != NULL) {
    *ptr = 0;
    fext = ptr + 1;
  }
  newname = malloc(strlen(fname) + strlen(fext) + 16);
  if (newname == NULL || fext == NULL || fname == NULL) {
    printf("null? bailing\n");
    exit(-1);
  }

  printf("Creating %d fuzz files for template %s ...\n", count, argv[optind + 1]);
  srandom(getpid());
  for (i = 1; i <= count; i++) {
    sprintf(newname, "%s_%d.%s", fname, i, fext);
    cnt = 0;
    if ((g = fopen(newname, "w")) != NULL) {
      if (verbose)
        printf("Wrote %s with ", newname);
      do {
        if (forward == 0)
          pos = random() % max_size;
        else
          pos = cpos++;
        
        amount = random() % 4;
        amount++;
        if (amount == 3)
          amount = 1;
        if (do_random) {
          value = (unsigned int) ((unsigned int)random() % 4294967295u); // C90 NOWARN
          memcpy(buf2 + pos, (char *) &value, amount);
          if (verbose)
            printf("%d byte%s of 0x%x at %d  ", amount, amount == 1 ? "" : "s", (unsigned int) value, pos);
        } else {
          amount = 1;
          if (verbose)
            printf("%d byte%s 0x", amount, amount == 1 ? "" : "s");
          if (fixed >= 0) {
            buf2[pos] = fixed % 256;
            printf("%02x", (unsigned char) buf2[pos]);
          } else {
            for (j = 0; j < amount; j++) {
              value = random() % 8;
              if (value < 6) {
                value = vars[value];
                buf2[pos + j] = value % 256;
              } else
                buf2[pos + j] = buf2[pos + j] ^ 0xff;
              printf("%02x", (unsigned char) buf2[pos + j]);
            }
          }
          printf(" at %d", pos);
        }
        cnt++;
        if (verbose && cnt < change_count)
          printf(", ");
      } while (cnt < change_count);
      if (do_inject) {
        cnt = 0;
        do {
          pos = random() % pos_cnt;
          j = 0;
          for (k = 0; k < inj_cnt; k++)
            if (inject_len[k] <= injlen[pos])
              j++;
          if (j) {
            amount = (random() % j) + 1;
            k = 0;
            while (j > 0) {
              if (inject_len[k] <= injlen[pos])
                j--;
              k++;
            }
            k--;
            memcpy(buf2 + injoff[pos] + (random() % (injlen[pos] - inject_len[k])), inject[k], inject_len[k]);
          }
          cnt++;
        } while (cnt < change_count);
      }

      fwrite(buf2, 1, size, g);
      fclose(g);
      if (verbose)
        printf("\n");
      else
        printf(".");
      memcpy(buf2, buf, size);
    } else
      printf("!");
  }
  printf("\nDone.\n");

  return 0;
}
