Ejemplo n.º 1
0
void tUtil::ShowHelp(const char *filename, unsigned long context)
{
  // filename must have at least the extension
  if(!filename || strlen(filename) < 5)
    return;

  const char* extension = &filename[strlen(filename) - 4];

  if(_stricmp(extension, ".chm") == 0)
  {
    char context_param[50];
  
    if(context != 0)
      sprintf(context_param, "-mapid %d", context);
    else
      context_param[0] = '\0';
  
    _spawnlp(_P_NOWAIT, "hh.exe", "hh.exe", context_param, filename, NULL);
  }
  else if(_stricmp(extension, ".hlp") == 0)
  {
    if(context != 0)
      WinHelp(NULL, filename, HELP_CONTEXT, context);
    else
      WinHelp(NULL, filename, HELP_FINDER, 0);
  }
}
/* goodG2B uses the GoodSource with the BadSink */
void CWE78_OS_Command_Injection__char_console_w32_spawnlp_52c_goodG2BSink(char * data)
{
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
Ejemplo n.º 3
0
int _CRTAPI1  Z_spawnlp (int Arg1,const char* Arg2,const char* Arg3, DWORD64ARGS)
{

    int RetVal;

    SHORT sTimerHandle;
    ULONG ulElapsedTime;

    if (fInitDone == FALSE) {
        ApfInitDll();
    }
    TimerOpen(&sTimerHandle, MICROSECONDS);
    TimerInit(sTimerHandle);
    //
    // Call the api
    //
    RetVal = _spawnlp(Arg1,Arg2,Arg3, ARGS64);
    //
    // Get the elapsed time
    //
    ulElapsedTime = TimerRead(sTimerHandle);
    ApfRecordInfo(I__spawnlp, ulElapsedTime - ApfData[I_CALIBRATE].ulFirstTime);
    TimerClose(sTimerHandle);

    return(RetVal);
}
Ejemplo n.º 4
0
void tUtil::ShowHelp(const char *filename, unsigned long context)
{
  // filename must have at least the extension
  if(!filename || strlen(filename) < 5)
    return;

  const char* extension = &filename[strlen(filename) - 4];

  if(_stricmp(extension, ".chm") == 0)
  {
    char context_param[50];
  
    if(context != 0)
      sprintf(context_param, "-mapid %d", context);
    else
      context_param[0] = '\0';
#if !defined(__WINE__) || defined(__MSVCRT__)
    _spawnlp(_P_NOWAIT, "hh.exe", "hh.exe", context_param, filename, NULL);
#else
    MessageBox(NULL, "FIX - not implemented - _spawnlp", "LuaCOM", MB_ICONEXCLAMATION);
    #warning FIX - not implemented - _spawnlp
#endif
  }
  else if(_stricmp(extension, ".hlp") == 0)
  {
    if(context != 0)
      WinHelp(NULL, filename, HELP_CONTEXT, context);
    else
      WinHelp(NULL, filename, HELP_FINDER, 0);
  }
}
void CWE78_OS_Command_Injection__char_file_w32_spawnlp_01_bad()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    {
        /* Read input from a file */
        size_t dataLen = strlen(data);
        FILE * pFile;
        /* if there is room in data, attempt to read the input from a file */
        if (100-dataLen > 1)
        {
            pFile = fopen(FILENAME, "r");
            if (pFile != NULL)
            {
                /* POTENTIAL FLAW: Read data from a file */
                if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                {
                    printLine("fgets() failed");
                    /* Restore NUL terminator if fgets fails */
                    data[dataLen] = '\0';
                }
                fclose(pFile);
            }
        }
    }
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<char *> dataList)
{
    char * data = dataList.back();
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
void CWE78_OS_Command_Injection__char_file_w32_spawnlp_67b_badSink(CWE78_OS_Command_Injection__char_file_w32_spawnlp_67_structType myStruct)
{
    char * data = myStruct.structFirst;
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
void badSink(map<int, char *> dataMap)
{
    /* copy data out of dataMap */
    char * data = dataMap[2];
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
void CWE78_OS_Command_Injection__char_connect_socket_w32_spawnlp_66b_badSink(char * dataArray[])
{
    /* copy data out of dataArray */
    char * data = dataArray[2];
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
Ejemplo n.º 10
0
int main(int ac, char **av)
{
  int  savo, savi;
  FILE *fnul;
  char name[256];
  char fullname[256];
  char *p;

  kpse_set_program_name(av[0], "mkocp");

  if(ac != 2) {
    fprintf(stderr,"%s : Usage %s ocpname\n", av[0], av[0]);
    return 1;
  }

  p = strrchr(av[1], '.');
  if(p)
    *p = '\0';
  strcpy(name, av[1]);
  strcpy(fullname, name);
  strcat(fullname, ".ocp");

/* save stdout and stdin */
  savo = _dup(fileno(stdout));
  savi = _dup(fileno(stdin));

/* connect stdout to stderr */
  _dup2(fileno(stderr), fileno(stdout));

/* connect stdin to nul device */
  if(!(fnul = fopen("nul", "r"))) {
    fprintf(stderr, "Cannot open nul device to read\n");
    exit(100);
  }
  _dup2(fileno(fnul), fileno(stdin));

/* COMMAND */

  _spawnlp(_P_WAIT, "otp2ocp", "otp2ocp", name, NULL);

/* END COMMAND */
  
/* return to original stdout and stdin */
  _dup2(savo, fileno(stdout));
  close(savo);
  _dup2(savi, fileno(stdin));
  close(savi);

/* close nul device */
  fclose(fnul);

  if(_access(fullname, 0) == 0)
    printf("%s\n", fullname);

  return 0;
}
static void goodG2B()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    goodG2BSource(data);
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
void CWE78_OS_Command_Injection__char_file_w32_spawnlp_61_bad()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    data = CWE78_OS_Command_Injection__char_file_w32_spawnlp_61b_badSource(data);
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
Ejemplo n.º 13
0
shell(void)
{
        char *shell;            /* Name of system command processor */


        /*  get name of system shell  */
        if ((shell = getenv("COMSPEC")) == NULL) {
                return(FALSE);          /*  No shell located  */
        }

        return (_spawnlp(_P_WAIT, shell, shell, NULL));
}
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    /* FIX: Append a fixed string to data (not user / external input) */
    strcat(data, "*.*");
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
/* goodG2B1() - use goodsource and badsink by changing the 1 to 0 */
static void goodG2B1()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    if(0)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Append a fixed string to data (not user / external input) */
        strcat(data, "*.*");
    }
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
void CWE78_OS_Command_Injection__char_console_w32_spawnlp_34_bad()
{
    char * data;
    CWE78_OS_Command_Injection__char_console_w32_spawnlp_34_unionType myUnion;
    char dataBuffer[100] = "";
    data = dataBuffer;
    {
        /* Read input from the console */
        size_t dataLen = strlen(data);
        /* if there is room in data, read into it from the console */
        if (100-dataLen > 1)
        {
            /* POTENTIAL FLAW: Read data from the console */
            if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
            {
                /* The next few lines remove the carriage return from the string that is
                 * inserted by fgets() */
                dataLen = strlen(data);
                if (dataLen > 0 && data[dataLen-1] == '\n')
                {
                    data[dataLen-1] = '\0';
                }
            }
            else
            {
                printLine("fgets() failed");
                /* Restore NUL terminator if fgets fails */
                data[dataLen] = '\0';
            }
        }
    }
    myUnion.unionFirst = data;
    {
        char * data = myUnion.unionSecond;
        /* spawnlp - searches for the location of the command among
         * the directories specified by the PATH environment variable */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
    }
}
Ejemplo n.º 17
0
main(int argc,char *argv[])
  {
  int codesize;
  char *z;
  printf("%d\n",sizeof(TKOUZLO));
  if (argc<2)
     {
     puts("Tento program vyzaduje jmeno souboru, ve kterem se nalezaji\n"
          "platne definice kouzel pro hru BRANY SKELDALU v 1.0");
     exit(0);
     }
  puts("");
  puts("Prob¡h  kompilace:");
  puts("   Spouçt¡m program LEX_LIB.EXE\n");
//  putenv("DOS4G=QUIET");
  z=(char *)malloc(strlen(argv[1])+10);
  sprintf(z,"\"%s\"",argv[1]);
  if (_spawnlp(P_WAIT,GetLexLibPath(),"lex_lib.exe",z,"temp.$$$",NULL))
     exit(1);
  free(z);
  if (errno)
     {
     puts("Nemohu spustit program lex_lib.exe");
     exit(1);
     }
  puts("Byla kompilov na tato kouzla:");
  puts("¬¡slo, zaŸ tek, jmeno:");
  puts("======================");
  memset(kouzla_tab,0,sizeof(kouzla_tab));
  init("temp.$$$");
  codesize=build_tables();
  add_prog_command(0xff);
  fclose(source);
  save_tab("kouzla.dat");
  remove("temp.$$$");
  puts("Kompilace £spØçn ...");
  printf("D‚lka k¢du: %d (+%d)",codesize,sizeof(kouzla_tab));
  }
Ejemplo n.º 18
0
int
main (int ac, char **av)
{
  static char execfile[SBUF];
  char rbuff[LBUF];
  char buff[LBUF];
  char cmd[LBUF];
  char mfname[TBUF];
  char tfname[TBUF];
  char pkname[TBUF];

  char name[TBUF];
  char dpi[TBUF];
  char ydpi[TBUF];
  char bdpi[TBUF];
  char mag[TBUF];
  char mode[TBUF];
  char destdir[SBUF];
  char designsize[64];

  char *arg[4];

  char currdir[SBUF];
  char kpsedot[SBUF];
  char *tmp;
  int cdrive, tdrive;

  FILE *fr, *fw, *fnul, *tfmfileptr;

  int i, savo, savi, ret;
  int style;
  int issetdest;
  int app;
  int oldform;
  int ps2pkok;
  char *env;
  char *p, *fpp;

  double Xdpi, Ydpi;

  char texname[TBUF], pfbname[TBUF], slant[TBUF], extend[TBUF], encname[TBUF];

  char texbindir[256];
  char fullbin[512];

/*
 * style =  0 : MAKETEXPK_STYLE undefined or other than dosnames
 * style =  1 : MAKETEXPK_STYLE = dosnames
 */

/*
 * issetdest = 0 : no destdir
 * issetdest = 1 : destdir
 * issetdest = 2 : current working dir
 */

/*
 * app = 0 : mf
 * app = 1 : ps2pk
 * app = 2 : gsftopk
 * app = 3 : ttf2pk
 * app = 4 : hbf2gf
 */

/*
 * oldform = 0 : newform of the command line
 * oldform = 1 : oldform of the command line
 */

/*
 * TEMP | TMP | TMPDIR (necessary)
 *
 */

  tmp = getenv ("TEMP");
  if (!tmp)
    tmp = getenv ("TMP");
  if (!tmp)
    tmp = getenv ("TMPDIR");
  if (!tmp) {
    tpkerr ("Please define TEMP | TMP | TMPDIR.");
    return (100);
  }
  tmp = xstrdup(tmp);

/*
 * normalize directory separators
 */
  normalize (tmp);

  for (i = 0; i < 4; i++)
    arg[i] = (char *) malloc (SBUF);

  kpse_set_program_name (av[0], NULL);
  progname = kpse_program_name;

/*
 * get tex binary dir
 *
 */
  p = kpse_var_value("SELFAUTOLOC");
  if(p == 0) {
     fprintf(stderr, "I cannot get SELFAUTOLOC\n");
     exit(100);
  }
  strcpy(texbindir, p);
  free(p);
  for(p=texbindir; *p; p++) {
     if(*p == '/') *p = '\\';
  }
  *p = '\\';
  *(p+1) = '\0';

  if (ac < 2) {
    usage ();
    relmem (arg);
    free(tmp);
    return (100);
  }

  issetdest = 0;
  ps2pkok = 0;

/*
 * oldform or newform ?
 *
 */

  if (av[1][0] == '-')
    oldform = 0;
  else
    oldform = 1;


/*
 * Old form of the command line
 */

  if (oldform == 1) {
    if (ac < 5) {
      usage ();
      relmem (arg);
      free(tmp);
      return (100);
    }
    if((strlen(av[1]) > TBUF -1 ) ||
       (strlen(av[2]) > TBUF -1 ) ||
       (strlen(av[3]) > TBUF -1 ) ||
       (strlen(av[4]) > TBUF -1 )) {
      fprintf(stderr, "\nToo long a string.\n");
      free(tmp);
      return 100;
    }

    strcpy (name, av[1]);
    strcpy (dpi, av[2]);
    strcpy (bdpi, av[3]);
    strcpy (mag, av[4]);
    if (ac > 5) {
      if(strlen(av[5]) > TBUF -1) {
        fprintf(stderr, "\nToo long a string.\n");
        free(tmp);
        return 100;
      } 
      strcpy (mode, av[5]);
    }
    else
      mode[0] = '\0';
  } else {
/*
 * New form of the command line
 */
    name[0] = dpi[0] = bdpi[0] = mag[0] = mode[0] = destdir[0] = '\0';
    i = 1;
    while (i < ac) {
      if(strlen(av[i]) > TBUF - 1) {
        fprintf(stderr, "\nToo long a string.\n");
        free(tmp);
        return 100;
      }
      if (av[i][0] != '-') {
        strcpy (name, av[i]);
        break;
      }
      if (!strcmp (av[i], "--dpi") || !strcmp (av[i], "-dpi")) {
        i++;
        if (i >= ac) {
          tpkerr ("Invalid arguments.");
          relmem (arg);
          free(tmp);
          return (100);
        }
        strcpy (dpi, av[i]);
        i++;
      } else if (!strcmp (av[i], "--bdpi") || !strcmp (av[i], "-bdpi")) {
        i++;
        if (i >= ac) {
          tpkerr ("Invalid arguments.");
          relmem (arg);
          free(tmp);
          return (100);
        }
        strcpy (bdpi, av[i]);
        i++;
      } else if (!strcmp (av[i], "--mag") || !strcmp (av[i], "-mag")) {
        i++;
        if (i >= ac) {
          tpkerr ("Invalid arguments.");
          relmem (arg);
          free(tmp);
          return (100);
        }
        strcpy (mag, av[i]);
        i++;
      } else if (!strcmp (av[i], "--mfmode") || !strcmp (av[i], "-mfmode")) {
        i++;
        if (i >= ac) {
          tpkerr ("Invalid arguments.");
          relmem (arg);
          free(tmp);
          return (100);
        }
        strcpy (mode, av[i]);
        i++;
      } else if (!strcmp (av[i], "--destdir") || !strcmp (av[i], "-destdir")) {
        i++;
        if (i >= ac) {
          tpkerr ("Invalid arguments.");
          relmem (arg);
          free(tmp);
          return (100);
        }
        strcpy (destdir, av[i]);
        issetdest = 1;
        i++;
      } else if (!strcmp (av[i], "--version") || !strcmp (av[i], "-version")) {
        version ();
        relmem (arg);
        free(tmp);
        return (0);
      } else if (!strcmp (av[i], "--help") || !strcmp (av[i], "-help")) {
        help ();
        relmem (arg);
        free(tmp);
        return (0);
      } else {
        tpkerr ("Argument error.");
        relmem (arg);
        free(tmp);
        return (100);
      }
    }
  }                             /* End of command line analysis */

  env = kpse_var_value ("MAKETEXPK_STYLE");

  if ((env == NULL) || !(*env) || (env && strcmp (env, "dosnames"))) {
    style = 0;
  } else
    style = 1;

/*
 * Default program is mf
 */

  app = 0;

/*
 * check if mfmode and bdpi are consistent or not
 */

  if (bdpi[0] && mode[0] && mode[0] != '/') {
    FILE *frd;
    char buff[128];
    int len;

    strcpy (fullbin, texbindir);
    strcat (fullbin, "mf-nowin.exe \"\\mode:=");
    strcat (fullbin, mode);
    strcat (fullbin, ";mode_setup;message");
    strcat (fullbin, "(decimal round pixels_per_inch);");
    strcat (fullbin, "end. <nul\"");

    frd = popen (fullbin, "r");
    if (!frd) {
      tpkerr ("I cannot find METAFONT.\n");
      relmem (arg);
      free(tmp);
      return (100);
    }
    (void) fgets (buff, 126, frd);
    (void) fgets (buff, 126, frd);
    pclose (frd);
    system("del /Q mfput.*");

    len = (int)strlen (buff);
    if (buff[len - 1] == '\n') {
      buff[len - 1] = '\0';
      if (buff[len - 2] == '\r')
        buff[len - 2] = '\0';
    }
    if (strcmp (bdpi, buff)) {
      fprintf(stderr, "mode_dpi %s and bdpi %s are inconsistent.\n", buff, bdpi);
      fprintf(stderr, "therefore I reset mfmode.\n");
      mode[0] = '\0';
    }
  }

/*
 * determine mfmode if not given
 */

  if (mode[0] == 0 || mode[0] == '/') {
    if (bdpi[0] == 0) {
      tpkerr ("Cannot determine the mode.");
      tpkerr ("I will try other possibilities.");
      app = 1;
    } else {
      strcpy (rbuff, "MAKETEXPK_MODE_");
      strcat (rbuff, bdpi);
      if ((env = kpse_var_value ("MAKETEXPK_MODE")) && *env)
        strcpy (mode, env);
      else if ((env = kpse_var_value (rbuff)))
        strcpy (mode, env);
      else if (!strcmp (bdpi, "85"))
        strcpy (mode, "sun");
      else if (!strcmp (bdpi, "100"))
        strcpy (mode, "nextscrn");
      else if (!strcmp (bdpi, "118"))
        strcpy (mode, "pcprevw");
      else if (!strcmp (bdpi, "160"))
        strcpy (mode, "nectzo");
      else if (!strcmp (bdpi, "180"))
        strcpy (mode, "toshiba");
      else if (!strcmp (bdpi, "200"))
        strcpy (mode, "highfax");
      else if (!strcmp (bdpi, "240"))
        strcpy (mode, "canonlbp");
      else if (!strcmp (bdpi, "300"))
        strcpy (mode, "cx");
      else if (!strcmp (bdpi, "320"))
        strcpy (mode, "neclm");
      else if (!strcmp (bdpi, "360"))
        strcpy (mode, "epstylus");
      else if (!strcmp (bdpi, "400"))
        strcpy (mode, "nexthi");
      else if (!strcmp (bdpi, "600"))
        strcpy (mode, "ljfour");
      else if (!strcmp (bdpi, "720"))
        strcpy (mode, "epscszz");
      else if (!strcmp (bdpi, "800"))
        strcpy (mode, "lwpro");
      else if (!strcmp (bdpi, "1000"))
        strcpy (mode, "lmaster");
      else if (!strcmp (bdpi, "1200"))
        strcpy (mode, "ultre");
      else if (!strcmp (bdpi, "1270"))
        strcpy (mode, "linoone");
      else if (!strcmp (bdpi, "1800"))
        strcpy (mode, "vtftzz");
      else if (!strcmp (bdpi, "2400"))
        strcpy (mode, "supre");
      else if (!strcmp (bdpi, "2540"))
        strcpy (mode, "linotzzh");
      else if (!strcmp (bdpi, "3386"))
        strcpy (mode, "linolttz");
      else if (!strcmp (bdpi, "8000"))
        strcpy (mode, "dpdfezzz");
      else if (!strcmp (bdpi, "9600"))
        strcpy (mode, "ibx");
      else {
        tpkerr ("Cannot determine the mode.");
        tpkerr ("I will try other possibilities.");
        app = 1;
      }
    }
  }

  if (env) free (env);

  if (name[0] == 0) {
    tpkerr ("Font name is not given.");
    relmem (arg);
    free(tmp);
    return (100);
  }

  if ((p = strrchr (name, '.')))
    *p = '\0';

  strcpy (mfname, name);
  strcat (mfname, ".mf");

  if (app == 0) {
    if (!(p = kpse_var_value ("MFINPUTS"))) {
      tpkerr ("Cannot get value of MFINPUTS.");
      relmem (arg);
      free(tmp);
      return (100);
    }
    free (p);
    xputenv("MKTEXMF", "1");
    if (!(p = kpse_find_file (mfname, kpse_mf_format, 1))) {
      fprintf (stderr, "Cannot find %s .\n", mfname);
      tpkerr ("I try ps2pk --> gsftopk --> ttf2pk --> hbf2gf.");
      app = 1;
    }
  }

  if (app != 0) {
    strcpy (mode, "modeless");
    strcpy (tfname, name);
    strcat (tfname, ".tfm");
    if (!(p = kpse_var_value ("TFMFONTS"))) {
      tpkerr ("Cannot get value of TFMFONTS.");
      relmem (arg);
      free(tmp);
      return (100);
    }
    free (p);
/*
 I don't try to create nonexisting tfm here.
*/
    if (!(p = kpse_find_file (tfname, kpse_tfm_format, 0))) {
      fprintf (stderr, "Cannot find %s .\n", tfname);
      relmem (arg);
      free(tmp);
      return 100;
    }
    tfmfileptr = fopen (p, "rb");
    if (!tfmfileptr) {
      fprintf (stderr, "I cannot open %s.\n", p);
      relmem (arg);
      free(tmp);
      return 100;
    }
    i = 256 * getc (tfmfileptr);
    i += getc (tfmfileptr);
    fclose (tfmfileptr);
    if ((i == 9) || (i == 11)) {
      fprintf (stderr, "Current font seems to be a Japanese one.\n");
      fprintf (stderr, "I give up to create a PK font.\n");
      relmem (arg);
      free(tmp);
      return 100;
    }
  }

  if ((p[0] == '.') && (p[1] == '/') && (issetdest != 1))
    issetdest = 2;

  fpp = _getcwd (currdir, SBUF);
  if (!fpp) {
    fprintf (stderr, "Failed to get current working directory.\n");
    relmem (arg);
    free(tmp);
    return (100);
  }
  normalize (currdir);

  i = (int)strlen (currdir);
  if (currdir[i - 1] == '/')
    currdir[i - 1] = '\0';

  strcpy (kpsedot, "KPSE_DOT=.;");
  strcat (kpsedot, currdir);
  _putenv (kpsedot);

  if (issetdest == 2) {
    strcpy (destdir, currdir);
  }

  if (issetdest == 0) {
    strcpy (arg[0], "Dummy");
    strcpy (arg[1], "pk");
    strcpy (arg[2], p);
    strcpy (arg[3], mode);

    if (!(p = getdestdir (4, arg))) {
      tpkerr ("Cannot get destination directory name.");
      relmem (arg);
      free(tmp);
      return (100);
    }
    strcpy (rbuff, p);
  } else
    strcpy (rbuff, destdir);

/*
 * Change backslash into slash
 */
  normalize (rbuff);

  p = rbuff;
  i = (int)strlen (p);
  if (p[i - 1] == '/')
    p[i - 1] = '\0';

  if (issetdest) {
    if (!is_dir (p)) {
      fprintf (stderr, "Destination %s is not found.\n", p);
      relmem (arg);
      free(tmp);
      return (100);
    }
  } else if (!is_dir (p)) {
    if (make_dir (p)) {
      tpkerr ("Error in make_dir.");
      relmem (arg);
      free(tmp);
      return (100);
    }
  }

  strcpy (buff, p);
  p = buff;

  i = (int)strlen (p);

  if (p[i - 1] != '/')
    strcat (p, "/");

  if (dpi[0] == 0) {
    tpkerr ("Cannot determine DPI.");
    relmem (arg);
    free(tmp);
    return (100);
  }

  if (style == 1 && issetdest != 2) {   /* dosnames */
    strcat (p, "dpi");
    strcat (p, dpi);
    if (!is_dir (p)) {
      if (make_dir (p)) {
        tpkerr ("Error in make_dir.");
        relmem (arg);
        free(tmp);
        return (100);
      }
    }
    strcat (p, "/");
  }

  strcat (p, name);
  strcat (p, ".");

  if (style != 1 || issetdest == 2)
    strcat (p, dpi);            /* long suffix */
  strcat (p, "pk");

/* Now buff and p is the full path name of pk file */
/* check the existence of pk file */

  if (_access (p, 0) == 0) {
    fprintf (stderr, "%s exists.\n", p);
    relmem (arg);
    printf ("%s\n", p);
    free(tmp);
    return (0);
  }

/*
 * Go to the temporary directory
 */

  cdrive = _getdrive ();
  if (tmp[1] == ':') {
    tdrive = tolower (*tmp) - 'a' + 1;
    _chdrive (tdrive);
  }
  _chdir (tmp);

/*
 * save stdout and stdin
 */
  savo = _dup (fileno (stdout));
  savi = _dup (fileno (stdin));

/*
 * connect stdout to stderr
*/
  _dup2 (fileno (stderr), fileno (stdout));

/*
 * connect stdin to nul
 */
  if (!(fnul = fopen ("nul", "rb"))) {
    fprintf (stderr, "Cannot open nul device to read.\n");
    _chdrive (cdrive);
    _chdir (currdir);
    relmem (arg);
    free(tmp);
    return (100);
  }
  _dup2 (fileno (fnul), fileno (stdin));

/*
 * pkname is the filename of PK font
 */
  sprintf (pkname, "%s.%spk", name, dpi);

  if (app == 0) {
/*
 * METAFONT command line
 */
    if (mag[0] == 0) {
      tpkerr ("Cannot determine MAG.");
      _chdrive (cdrive);
      _chdir (currdir);
      relmem (arg);
      free(tmp);
      return (100);
    }
    sprintf (cmd,
       "--progname=mf --base=mf \\mode:=%s; \\mag:=%s; nonstopmode; input %s;",
        mode, mag, name);

    strcpy (execfile, "mf-nowin.exe");
    fprintf (stderr, "%s %s\n", execfile, cmd);
    strcpy(fullbin, texbindir);
    strcat(fullbin, execfile);
    (void) _spawnlp (_P_WAIT, fullbin, execfile, cmd, NULL);

    sprintf (cmd, "%s.%sgf", name, dpi);

/*
 * check the consistency
 */
    if (_access (cmd, 0) != 0) {
      tpkerr ("Failed to make gf font by METAFONT.");
      _chdrive (cdrive);
      _chdir (currdir);
      relmem (arg);
      free(tmp);
      return (100);
    }

/*
 * Change gf into pk
 */
    strcpy (execfile, "gftopk.exe");
    fprintf (stderr, "%s %s %s\n", execfile, cmd, pkname);
    strcpy(fullbin, texbindir);
    strcat(fullbin, execfile);
    (void) _spawnlp (_P_WAIT, fullbin, execfile, cmd, pkname, NULL);

    if (_access (pkname, 0) != 0) {
      tpkerr ("Failed to make pk from gf.");
      _chdrive (cdrive);
      _chdir (currdir);
      relmem (arg);
      free(tmp);
      return (100);
    }

/*
 * erase gf file
 */
    remove (cmd);

/*
 * erase log file
 */
    sprintf (cmd, "%s.log", name);
    remove (cmd);
/*
 * erase tfm file
 */
    sprintf (cmd, "%s.tfm", name);
    remove (cmd);

    goto finale;
  }

/*
 * app = 1 : ps2pk --> gsftopk --> ttf2pk --> hbf2gf
 */

  p = kpse_find_file ("pspksupp.map", kpse_fontmap_format, 0);
  if(p) {
    fr = fopen (p, "r");        /* Read pspksupp.map */
    free (p);

    if (!fr) {
      tpkerr ("Cannot open pspksupp.map to read.");
      ps2pkok = 0;
      goto do_ps2pk;
    }

    while (fgets (rbuff, SBUF, fr)) {
      if (rbuff[0] == '%' || rbuff[0] == '#' || rbuff[0] == '\n')
        continue;
      texname[0] = pfbname[0] = slant[0] = extend[0] = encname[0] = '\0';
      i = sscanf (rbuff, "%s %s %s %s %s", texname, pfbname, slant, extend,
                  encname);
      if (i == 2 && !strncmp (texname, "AspectRatio", 11)) {
        if (!sscanf (pfbname, "%lf", &AspectRatio)) {
          tpkerr ("File format of pspksupp.map is wrong.");
          fclose (fr);
          ps2pkok = 0;
          goto do_ps2pk;
        }
        UseAspectRatio = 1;
        continue;
      } else if (i > 0 && !stricmp (texname, name)) {
        p = kpse_var_value ("T1FONTS");
        if (!p) {
          tpkerr ("T1FONTS is not defined.");
          ps2pkok = 0;
          break;
        }
        free (p);
        p = kpse_find_file (pfbname, kpse_type1_format, 0);
        if (!p) {
          fprintf (stderr, "%s is not found.\n", pfbname);
          ps2pkok = 0;
          break;
        }
        free (p);
        ps2pkok = 1;
        if(bdpi[0] == 0)
          i--;
        break;
      }
    }
    fclose (fr);
    goto do_ps2pk;
  } else {
    char *q;
    char a[SBUF];
    char b[SBUF];
    char psname[SBUF];
    char pscommand[SBUF];
    double slantval, extendval;

    texname[0] = pfbname[0] = encname[0] = '\0';
    a[0] = b[0] = psname[0] = pscommand[0] = '\0';
    FileName = 0;
    strcpy(slant, "0");
    strcpy(extend, "1");

    ps2pkok = 0;

    p = kpse_find_file ("ps2pk.map", kpse_fontmap_format, 0);
    if(!p) {
      tpkerr("Necessary map file for ps2pk is not found.");
      goto do_ps2pk;
    }
    fr = fopen(p,"rb");
    free(p);
    if (!fr) {
      tpkerr ("Cannot open ps2pk.map to read.");
      goto do_ps2pk;
    }
    while ((ret=ffgets (rbuff, LBUF, fr)) != FFILE_END) {
      if(ret == BBUFF_FUL) {
        fprintf(stderr, "A line in ps2pk.map seems to be too long.\n");
        fprintf(stderr, "I try to continue. But something may be wrong.\n");
      }
      p = rbuff;
      skipchar(&p);
      if((*p == '%') || (*p == '#') || (*p == '\n'))
        continue;
      q = texname;
      while(!isskip(*p) && (*p != '\n'))
        *q++ = *p++;
      *q = '\0';
      if(stricmp(texname, name))
        continue;
      skipchar(&p);
      if((*p == '%') || (*p == '#') || (*p == '\n')) {
        fprintf(stderr, "Incorrect line in \"ps2pk.map\".\n");
        break;
      }
      if(FileName)
        q = a;
      else
        q = psname;
      while(!isskip(*p) && (*p != '\n'))
        *q++ = *p++;
      *q = '\0';
      skipchar(&p);
/*
skip flag
*/
      if(!FileName) {
        while(isdigit(*p))
          p++;
        skipchar(&p);
      }
      if((*p == '%') || (*p == '#') || (*p == '\n')) {
        tpkerr("I cannot use ps2pk due to lack of data.");
        break;
      }
      if(*p == '\"') {
        q = pscommand;
        *q++ = *p++;
        while(*p != '\"')
          *q++ = *p++;
        *q++ = *p++;
        *q = '\0';
        skipchar(&p);
        if((*p == '%') || (*p == '#') || (*p == '\n'))
          break;
      }
      if(FileName && a[0] == '\0')
        q = a;
      else if(FileName && b[0] == '\0')
        q = b;
      else {
        tpkerr("Incorrect line in ps2pk.map.");
        break;
      }
      while(!isskip(*p) && (*p != '\n'))
        *q++ = *p++;
      *q = '\0';
      skipchar(&p);
      if((*p == '%') || (*p == '#') || (*p == '\n'))
        break;
      if(*p == '\"') {
        q = pscommand;
        *q++ = *p++;
        while(*p != '\"')
          *q++ = *p++;
        *q++ = *p++;
        *q = '\0';
        skipchar(&p);
        if((*p == '%') || (*p == '#') || (*p == '\n'))
          break;
      }
      if (FileName && a[0] == '\0')
        q = a;
      else if (FileName && b[0] == '\0')
        q = b;
      else {
        fprintf(stderr, "Incorrect line in \"ps2pk.map\".\n");
        break;
      }
      while(!isskip(*p) && (*p != '\n'))
        *q++ = *p++;
      *q = '\0';
      skipchar(&p);
      if((*p == '%') || (*p == '#') || (*p == '\n'))
        break;
      if(*p == '\"') {
        q = pscommand;
        *q++ = *p++;
        while(*p != '\"')
          *q++ = *p++;
        *q++ = *p++;
        *q = '\0';
        skipchar(&p);
        if((*p == '%') || (*p == '#') || (*p == '\n'))
          break;
      }
      skipchar(&p);
      if((*p == '%') || (*p == '#') || (*p == '\n'))
        break;
      else {
        fprintf(stderr, "Incorrect line in \"ps2pk.map\".\n");
        break;
      }
    }
    fclose(fr);

    if(pscommand[0]) {
      p = strstr(pscommand, "SlantFont");
      if(p) {
        p--;
        while(*p == ' ' || *p == '\t') p--;
        while(*p != ' ' && *p != '\t' && *p != '\"') p--;
        p++;
        sscanf(p, "%lf SlantFont", &slantval);
        sprintf(slant, "%lf", slantval);
        p = slant + strlen(slant) - 1;
        while(*p == '0') {
          *p = '\0';
          p--;
        }
      }
      p = strstr(pscommand, "ExtendFont");
      if(p) {
        p--;
        while(*p == ' ' || *p == '\t') p--;
        while(*p != ' ' && *p != '\t' && *p != '\"') p--;
        p++;
        sscanf(p, "%lf ExtendFont", &extendval);
        sprintf(extend, "%lf", extendval);
        p = extend + strlen(extend) - 1;
        while(*p == '0') {
          *p = '\0';
          p--;
        }
      }
    }
    if(a[0]) {
      p = strrchr(a, '.');
      if(p && !stricmp(p, ".enc")) {
        *p = '\0';
        strcpy(encname, a);
      }
      else if(p && !stricmp(p, ".pfb")) {
        *p = '\0';
        strcpy(pfbname, a);
      }
    }
    if(b[0]) {
      p = strrchr(b, '.');
      if(p && !stricmp(p, ".enc")) {
        *p = '\0';
        strcpy(encname, b);
      }
      else if(p && !stricmp(p, ".pfb")) {
        *p = '\0';
        strcpy(pfbname, b);
      }
    }
    if(pfbname[0] == '\0')
      goto do_ps2pk;
    p = kpse_find_file (pfbname, kpse_type1_format, 0);
    if(!p)
      goto do_ps2pk;
    free(p);
    ps2pkok = 1;
    if(encname[0] && bdpi[0]) {
      i = 5;
    } else if(!encname[0] && !bdpi[0]) {
      i = 3;
    } else {
      i = 4;
    }
  }

 do_ps2pk:

  if (ps2pkok) {
    if (UseAspectRatio) {
      sscanf (dpi, "%lf", &Xdpi);
      Ydpi = Xdpi * AspectRatio;
      sprintf (ydpi, "%d", (int) Ydpi);
    } else
      strcpy (ydpi, dpi);

    strcpy(tfname, name);
    strcat(tfname, ".tfm");
    get_designsize(tfname, designsize);

    if (i == 3) {
      sprintf (cmd, "-X%s -Y%s -S%s -E%s -P%s %s %s",
               dpi, ydpi, slant, extend, designsize, pfbname, pkname);
    } else if (i == 4 && bdpi[0]) {
      sprintf (cmd, "-X%s -Y%s -R%s -S%s -E%s -P%s %s %s",
               dpi, ydpi, bdpi, slant, extend, designsize, pfbname, pkname);
    } else if (i == 4 && encname[0]) {
      sprintf (cmd, "-e%s -X%s -Y%s -S%s -E%s -P%s %s %s",
               encname, dpi, ydpi, slant, extend, designsize, pfbname, pkname);
    } else if (i == 5) {
      sprintf (cmd, "-e%s -X%s -Y%s -R%s -S%s -E%s -P%s %s %s",
               encname, dpi, ydpi, bdpi, slant, extend, designsize, pfbname, pkname);
    } else {
      tpkerr ("File format of pspksupp.map is wrong.");
      goto do_gsftopk;
    }

    strcpy (execfile, "ps2pk.exe");
    fprintf (stderr, "%s %s\n", execfile, cmd);
    strcpy(fullbin, texbindir);
    strcat(fullbin, execfile);
    (void) _spawnlp (_P_WAIT, fullbin, execfile, cmd, NULL);

    if (_access (pkname, 0) != 0) {
      tpkerr ("ps2pk failed to make pk font.");
      goto do_gsftopk;
    }
    goto finale;
  }

/*
 * ps2pk is impossible to use
 */

 do_gsftopk:

  tpkerr ("ps2pk cannot be used.");
  tpkerr ("I try gsftopk.");
  app = 2;

  strcpy (execfile, "gsftopk.exe");
  fprintf (stderr, "%s %s %s\n", execfile, name, dpi);
  strcpy(fullbin, texbindir);
  strcat(fullbin, execfile);
  (void) _spawnlp (_P_WAIT, fullbin, execfile, name, dpi, NULL);

  if (_access (pkname, 0) != 0) {
    tpkerr ("gsftopk cannot be used.");
    tpkerr ("Next I try ttf2pk.");
    app = 3;
    strcpy (execfile, "ttf2pk.exe");
    fprintf (stderr, "%s -q %s %s\n", execfile, name, dpi);
    strcpy(fullbin, texbindir);
    strcat(fullbin, execfile);
    (void) _spawnlp (_P_WAIT, fullbin, execfile, "-q", name, dpi, NULL);

    if (_access (pkname, 0) != 0) {
      tpkerr ("ttf2pk failed.");
      tpkerr ("Finally I try hbf2gf.");
      app = 4;
      strcpy (execfile, "hbf2gf.exe");
      fprintf (stderr, "%s -q -p %s %s\n", execfile, name, dpi);
      strcpy(fullbin, texbindir);
      strcat(fullbin, execfile);
      (void) _spawnlp (_P_WAIT, fullbin, execfile, "-q -p", name, dpi, NULL);

      sprintf (cmd, "%s.%sgf", name, dpi);
      if (_access (cmd, 0) != 0) {
        tpkerr ("All trials failed.");
        _chdrive (cdrive);
        _chdir (currdir);
        relmem (arg);
        free(tmp);
        return (100);
      }
      strcpy (execfile, "gftopk.exe");
      fprintf (stderr, "%s %s %s\n", execfile, cmd, pkname);
      strcpy(fullbin, texbindir);
      strcat(fullbin, execfile);
      (void) _spawnlp (_P_WAIT, fullbin, execfile, cmd, pkname, NULL);

      if (_access (pkname, 0) != 0) {
        tpkerr ("All trials failed.");
        _chdrive (cdrive);
        _chdir (currdir);
        relmem (arg);
        free(tmp);
        return (100);
      }
      remove (cmd);
    }
  }

 finale:

/*
 * return to original stdout and stdin
 */
  _dup2 (savo, fileno (stdout));
  close (savo);
  _dup2 (savi, fileno (stdin));
  close (savi);

/*
 * close nul device
 */
  fclose (fnul);

/*
 * copy the pk file
 */
  if (!(fr = fopen (pkname, "rb"))) {
    fprintf (stderr, "Cannot open %s to read.\n", pkname);
    _chdrive (cdrive);
    _chdir (currdir);
    relmem (arg);
    free(tmp);
    return (100);
  }

  if (!(fw = fopen (buff, "wb"))) {
    fprintf (stderr, "Cannot open %s to write.\n", buff);
    _chdrive (cdrive);
    _chdir (currdir);
    relmem (arg);
    free(tmp);
    return (100);
  }

  while ((i = (int)fread (rbuff, 1, LBUF, fr)))
    fwrite (rbuff, 1, i, fw);

  fclose (fr);
  fclose (fw);
  remove (pkname);

  relmem (arg);

/*
 * update ls-R if it exists
 */
  mktexupd (buff);

/*
 * tell kpathsea
 */

  printf ("%s\n", buff);
  _chdrive (cdrive);
  _chdir (currdir);
  free(tmp);

  return (0);
}
Ejemplo n.º 19
0
/* Main Dialog */
BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
    int ret_code = 0;


    switch(Message)
    {
        case WM_INITDIALOG:
        {
            int statwidths[] = {130, -1};
            HMENU hMenu, hSubMenu;

            UINT menuflags = MF_STRING;

            if(config_inst.admin_access == 0)
            {
                menuflags = MF_STRING|MF_GRAYED;
            }

            hMenu = CreateMenu();

            /* Creating management menu */
            hSubMenu = CreatePopupMenu();
            AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_START,"&Start OSSEC");
            AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_STOP,"&Stop OSSEC");
            AppendMenu(hSubMenu, MF_SEPARATOR, UI_MENU_NONE,"");
            AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_RESTART,"&Restart");
            AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_STATUS,"&Status");
            AppendMenu(hSubMenu, MF_SEPARATOR, UI_MENU_NONE,"");
            AppendMenu(hSubMenu, MF_STRING,UI_MENU_MANAGE_EXIT,"&Exit");
            AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu,"&Manage");

            /* Create view menu */
            hSubMenu = CreatePopupMenu();
            AppendMenu(hSubMenu, MF_STRING, UI_MENU_VIEW_LOGS, "&View Logs");
            AppendMenu(hSubMenu, MF_STRING, UI_MENU_VIEW_CONFIG,"V&iew Config");
            AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu,"&View");

            hSubMenu = CreatePopupMenu();
            AppendMenu(hSubMenu, MF_STRING, UI_MENU_HELP_ABOUT, "A&bout");
            AppendMenu(hSubMenu, MF_STRING, UI_MENU_HELP_HELP, "Help");
            AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, "&Help");


            AppendMenu(hMenu, MF_SEPARATOR, 0, NULL);
            SetMenu(hwnd, hMenu);


            hStatus = CreateWindowEx(0, STATUSCLASSNAME, NULL,
                    WS_CHILD|WS_VISIBLE,
                    0, 0, 0, 0,
                    hwnd, (HMENU)IDC_MAIN_STATUS,
                    GetModuleHandle(NULL), NULL);

            SendMessage(hStatus, SB_SETPARTS,
                    sizeof(statwidths)/sizeof(int),
                    (LPARAM)statwidths);
            SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"http://www.ossec.net");


            /* Initializing config */
            config_read(hwnd);
            gen_server_info(hwnd);


            /* Setting the icons */
            SendMessage(hwnd, WM_SETICON, ICON_SMALL,
                    (LPARAM)LoadIcon(GetModuleHandle(NULL),
                                     MAKEINTRESOURCE(IDI_OSSECICON)));
            SendMessage(hwnd, WM_SETICON, ICON_BIG,
                    (LPARAM)LoadIcon(GetModuleHandle(NULL),
                                     MAKEINTRESOURCE(IDI_OSSECICON)));

            if(config_inst.admin_access == 0)
            {
                MessageBox(hwnd, "Admin access required. Some features may not work properly. \n\n"
                        "**If on Vista (or Server 2008), choose the \"Run as administrator\" option.",
                        "Admin Access Required", MB_OK);
                break;
            }

        }
        break;

        case WM_COMMAND:
        switch(LOWORD(wParam))
        {
            /* In case of SAVE */
            case IDC_ADD:
            {
                int chd = 0;
                int len;


                if(config_inst.admin_access == 0)
                {
                    MessageBox(hwnd, "Unable to edit configuration. "
                                     "Admin access required.",
                                     "Error Saving.", MB_OK);
                    break;
                }

                /* Getting server ip */
                len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_TEXT));
                if(len > 0)
                {
                    char *buf;


                    /* Allocating buffer */
                    buf = (char*)GlobalAlloc(GPTR, len + 1);
                    if(!buf)
                    {
                        exit(-1);
                    }

                    GetDlgItemText(hwnd, UI_SERVER_TEXT, buf, len + 1);

                    /* If auth key changed, set it */
                    if(strcmp(buf, config_inst.server) != 0)
                    {
                        if(set_ossec_server(buf, hwnd))
                        {
                            chd = 1;
                        }
                    }
                    else
                    {
                        GlobalFree(buf);
                    }
                }


                /* Getting auth key */
                len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_AUTH));
                if(len > 0)
                {
                    char *buf;

                    /* Allocating buffer */
                    buf = (char*)GlobalAlloc(GPTR, len + 1);
                    if(!buf)
                    {
                        exit(-1);
                    }

                    GetDlgItemText(hwnd, UI_SERVER_AUTH, buf, len + 1);

                    /* If auth key changed, set it */
                    if(strcmp(buf, config_inst.key) != 0)
                    {
                        int ret;
                        char *tmp_str;
                        char *decd_buf = NULL;
                        char *decd_to_write = NULL;
                        char *id = NULL;
                        char *name = NULL;
                        char *ip = NULL;

                        /* Getting new fields */
                        decd_buf = decode_base64(buf);
                        if(decd_buf)
                        {
                            decd_to_write = strdup(decd_buf);

                            /* Getting id, name and ip */
                            id = decd_buf;
                            name = strchr(id, ' ');
                            if(name)
                            {
                                *name = '\0';
                                name++;

                                ip = strchr(name, ' ');
                                if(ip)
                                {
                                    *ip = '\0';
                                    ip++;

                                    tmp_str = strchr(ip, ' ');
                                    if(tmp_str)
                                    {
                                        *tmp_str = '\0';
                                    }
                                }
                            }
                        }

                        /* If ip isn't set, it is because we have an invalid
                         * auth key.
                         */
                        if(!ip)
                        {
                            MessageBox(hwnd, "Unable to import "
                                             "authentication key because it was invalid.",
                                             "Error -- Failure Saving Auth Key", MB_OK);
                        }
                        else
                        {
                            char mbox_msg[1024 +1];
                            mbox_msg[1024] = '\0';

                            snprintf(mbox_msg, 1024, "Adding key for:\r\n\r\n"
                                               "Agent ID: %s\r\n"
                                               "Agent Name: %s\r\n"
                                               "IP Address: %s\r\n",
                                               id, name, ip);

                            ret = MessageBox(hwnd, mbox_msg,
                                             "Confirm Importing Key", MB_OKCANCEL);
                            if(ret == IDOK)
                            {
                                if(set_ossec_key(decd_to_write, hwnd))
                                {
                                    chd += 2;
                                }
                            }
                        }

                        /* Free used memory */
                        if(decd_buf)
                        {
                            free(decd_to_write);
                            free(decd_buf);
                        }
                    }
                    else
                    {
                        GlobalFree(buf);
                    }

                } /* Finished adding AUTH KEY */

                /* Re-printing messages */
                if(chd)
                {
                    config_read(hwnd);

                    /* Set status to restart */
                    if(strcmp(config_inst.status,ST_RUNNING) == 0)
                    {
                        config_inst.status = ST_RUNNING_RESTART;
                    }

                    gen_server_info(hwnd);

                    if(chd == 1)
                    {
                        SendMessage(hStatus, SB_SETTEXT, 0,
                                (LPARAM)"Server IP saved");
                    }
                    else if(chd == 2)
                    {
                        SendMessage(hStatus, SB_SETTEXT, 0,
                                (LPARAM)"Auth key imported");

                    }
                    else
                    {
                        SendMessage(hStatus, SB_SETTEXT, 0,
                                (LPARAM)"Auth key and IP saved");

                    }
                }
            }
            break;

            case UI_MENU_MANAGE_EXIT:
                PostMessage(hwnd, WM_CLOSE, 0, 0);
                break;

            case UI_MENU_VIEW_LOGS:
                _spawnlp( _P_NOWAIT, "notepad", "notepad " OSSECLOGS, NULL );
                break;
            case UI_MENU_VIEW_CONFIG:
                _spawnlp( _P_NOWAIT, "notepad", "notepad " CONFIG, NULL );
                break;
            case UI_MENU_HELP_HELP:
                _spawnlp( _P_NOWAIT, "notepad", "notepad " HELPTXT, NULL );
                break;
            case UI_MENU_HELP_ABOUT:
                {
                    DialogBox(GetModuleHandle(NULL),
                            MAKEINTRESOURCE(IDD_ABOUT), hwnd, AboutDlgProc);
                }
                break;
            case IDC_CANCEL:
                config_read(hwnd);
                gen_server_info(hwnd);
                break;

            case UI_MENU_MANAGE_START:

                /* Starting OSSEC  -- must have a valid config before. */
                if((strcmp(config_inst.key, FL_NOKEY) != 0) &&
                   (strcmp(config_inst.server, FL_NOSERVER) != 0))
                {
                    ret_code = os_start_service();
                }
                else
                {
                    ret_code = 0;
                }

                if(ret_code == 0)
                {
                    MessageBox(hwnd, "Unable to start agent (check config)",
                                     "Error -- Unable to Start Agent", MB_OK);
                }
                else if(ret_code == 1)
                {
                    config_read(hwnd);
                    gen_server_info(hwnd);

                    SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Started");

                    MessageBox(hwnd, "Agent started",
                                     "Agent Started", MB_OK);
                }
                else
                {
                    MessageBox(hwnd, "Agent already running (try restart)",
                                     "Agent Running", MB_OK);
                }
                break;
            case UI_MENU_MANAGE_STOP:

                /* Stopping OSSEC */
                ret_code = os_stop_service();
                if(ret_code == 1)
                {
                    config_read(hwnd);
                    gen_server_info(hwnd);

                    SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Stopped");
                    MessageBox(hwnd, "Agent stopped",
                                     "Agent Stopped", MB_OK);
                }
                else
                {
                    MessageBox(hwnd, "Agent already stopped",
                                     "Agent Stopped", MB_OK);
                }
                break;
            case UI_MENU_MANAGE_STATUS:
                if(CheckServiceRunning())
                {
                    MessageBox(hwnd, "Agent running",
                                     "Agent Running", MB_OK);

                }
                else
                {
                    MessageBox(hwnd, "Agent stopped",
                                     "Agent Stopped", MB_OK);
                }
                break;
            case UI_MENU_MANAGE_RESTART:

                if((strcmp(config_inst.key, FL_NOKEY) == 0) ||
                   (strcmp(config_inst.server, FL_NOSERVER) == 0))
                {
                    MessageBox(hwnd, "Unable to restart agent (check config)",
                                     "Error -- Unable to Restart Agent", MB_OK);
                    break;

                }

                ret_code = os_stop_service();

                /* Starting OSSEC */
                ret_code = os_start_service();
                if(ret_code == 0)
                {
                    MessageBox(hwnd, "Unable to restart agent (check config)",
                                     "Error -- Unable to Restart Agent", MB_OK);
                }
                else
                {
                    config_read(hwnd);
                    gen_server_info(hwnd);

                    SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Restarted");
                    MessageBox(hwnd, "Agent restarted",
                                     "Agent Restarted", MB_OK);
                }
                break;
        }
        break;

        case WM_CLOSE:
            EndDialog(hwnd, 0);
            break;

        default:
            return FALSE;
    }
    return TRUE;
}
Ejemplo n.º 20
0
int main(int ac, char **av)
{
  int  savo, savi;
  FILE *fnul;
  char *fmtname;
  char *p;
  char orgname[256];

  char texbindir[256];
  char fullbin[256];

  kpse_set_program_name(av[0], NULL);

  if(ac != 2) {
    fprintf(stderr,"%s : Usage %s formatname\n", av[0], av[0]);
    fprintf(stderr,"formatname :  (foo.fmt, foo.nfmt, foo.mem, foo.base)\n");
    return 1;
  }

  if(strlen(av[1]) > 127) {
    fprintf(stderr, "\nToo long a format name.\n");
    return 100;
  }

  p = kpse_var_value("SELFAUTOLOC");
  if(p == 0) {
     fprintf(stderr, "I cannot get SELFAUTOLOC\n");
     exit(1);
  }
  strcpy(texbindir, p);
  free(p);
  for(p=texbindir; *p; p++) {
     if(*p == '/') *p = '\\';
  }
  strcat(texbindir, "\\");

  strcpy(orgname, av[1]);

  p = strrchr(av[1], '.');
  if(!p) {
    fprintf(stderr, "formatname needs a suffix.\n");
    return 1;
  }

  if(stricmp(p, ".fmt") && stricmp(p, ".nfmt") &&
     stricmp(p, ".base") && stricmp(p, ".mem")) {
    fprintf(stderr, "%s : unknown format type.\n", av[1]);
    return 1;
  }

  *p = '\0';

/* save stdout and stdin */
  savo = _dup(fileno(stdout));
  savi = _dup(fileno(stdin));

/* connect stdout to stderr */
  _dup2(fileno(stderr), fileno(stdout));

/* connect stdin to nul device */
  if(!(fnul = fopen("nul", "r"))) {
    fprintf(stderr, "Cannot open nul device to read\n");
    exit(100);
  }
  _dup2(fileno(fnul), fileno(stdin));

/* COMMAND */
  strcpy(fullbin, texbindir);
  strcat(fullbin, "fmtutil.exe");
  fprintf(stderr, "Running the command %s\n", fullbin);
  _spawnlp(_P_WAIT, fullbin, "fmtutil", "--byfmt", av[1], NULL);

/* END COMMAND */
  
/* return to original stdout and stdin */
  _dup2(savo, fileno(stdout));
  close(savo);
  _dup2(savi, fileno(stdin));
  close(savi);

/* close nul device */
  fclose(fnul);

  fmtname = kpse_find_file(orgname , kpse_fmt_format, 0);
  if(fmtname) {
    printf("%s\n", fmtname);
    free(fmtname);
  }
  return 0;
}
Ejemplo n.º 21
0
int
main (int ac, char **av)
{
  char rbuff[TBUF];
  char buff[TBUF];
  char savebuff[TBUF];
  char cmd[TBUF];
  char mffile[TBUF];
  char *arg[4];
  static char execfile[TBUF];

  char kpsedot[TBUF];
  char currdir[TBUF];
  char *tmp;
  int cdrive, tdrive;

  FILE *fr, *fw, *fnul;

  int i, savo, savi;
  char *p, *fp, *fpp;
  int issetdest;
  char fontname[TBUF];

  char texbindir[TBUF];
  char fullbin[TBUF];

  kpse_set_program_name (av[0], NULL);
  progname = kpse_program_name;

/*
 * get tex binary dir
 *
 */
  p = kpse_var_value("SELFAUTOLOC");
  if(p == 0) {
     fprintf(stderr, "I cannot get SELFAUTOLOC\n");
     exit(100);
  }
  strcpy(texbindir, p);
  free(p);
  for(p=texbindir; *p; p++) {
     if(*p == '/') *p = '\\';
  }
  *p = '\\';
  *(p+1) = '\0';

  tmp = getenv ("TEMP");
  if (!tmp)
    tmp = getenv ("TMP");
  if (!tmp)
    tmp = getenv ("TMPDIR");
  if (!tmp) {
    fprintf (stderr, "Please define TEMP | TMP | TMPDIR.\n");
    return (100);
  }

  tmp = xstrdup(tmp);

  for (fpp = tmp; *fpp; fpp++) {
    if (IS_KANJI(fpp))
      fpp++;
    else if (*fpp == '\\')
      *fpp = '/';
  }
/*
issetdest = 0 : TDS
issetdest = 1 : user setting
issetdest = 2 : current directory
*/

  issetdest = 0;

  if (ac < 2) {
    usage ();
    free(tmp);
    return (100);
  }

  if ((!strcmp (av[1], "--version")) || (!strcmp (av[1], "-version"))) {
    version ();
    free(tmp);
    return (100);
  }

  if ((!strcmp (av[1], "--help")) || (!strcmp (av[1], "-help"))) {
    help ();
    free(tmp);
    return (100);
  }

  for (i = 0; i < 4; i++)
    arg[i] = (char *) malloc (TBUF);

  if ((!strcmp (av[1], "--destdir")) || (!strcmp (av[1], "-destdir"))) {
    if (ac != 4) {
      usage ();
      relmem (arg);
      free(tmp);
      return (100);
    }
    issetdest = 1;
    if (strlen(av[2]) > TBUF - 1 || strlen(av[3]) > TBUF - 1) {
      fprintf (stderr, "Too long a string.\n");
      return (100);
    }
    strcpy (buff, av[2]);
    strcpy (fontname, av[3]);
    for (p = buff; *p; p++) {
      if (IS_KANJI(p))
        p++;
      else if (*p == '\\')
        *p = '/';
    }
  } else {
    if (strlen(av[1]) > TBUF - 1) {
      fprintf (stderr, "Too long a string.\n");
      return (100);
    }
    strcpy (fontname, av[1]);
  }


  /* fontname = font name
   */
  if ((p = strrchr (fontname, '.')))
    *p = '\0';

  /* mffile is METAFONT file name
   */
  strcpy (mffile, fontname);
  strcat (mffile, ".mf");

  if (!(fp = kpse_var_value ("MFINPUTS"))) {
    fprintf (stderr, "Cannot get value of MFINPUTS\n");
    relmem (arg);
    free(tmp);
    return (100);
  }

  free (fp);

  xputenv("MKTEXMF", "1");
  if (!(p = kpse_find_file (mffile, kpse_mf_format, 1))) {
    fprintf (stderr, "Cannot find %s.\n", mffile);
    relmem (arg);
    free(tmp);
    return (100);
  }

  fpp = _getcwd (currdir, TBUF);
  if (!fpp) {
    fprintf (stderr, "Failed to get current working directory.\n");
    relmem (arg);
    free(tmp);
    return (100);
  }
  for (fpp = currdir; *fpp; fpp++) {
    if (IS_KANJI(fpp))
      fpp++;
    else if (*fpp == '\\')
      *fpp = '/';
  }

  i = (int)strlen (currdir);
  if (currdir[i - 1] == '/')
    currdir[i - 1] = '\0';
  strcpy (kpsedot, "KPSE_DOT=.;");
  strcat (kpsedot, currdir);
  _putenv (kpsedot);

  if ((p[0] == '.') && (p[1] == '/') && (issetdest != 1)) {
    issetdest = 2;
    strcpy (buff, currdir);
  }

  if (issetdest == 0) {
    /* now path of ${name}.mf is in p */
    strcpy (arg[0], "Dummy");
    strcpy (arg[1], "tfm");
    strcpy (arg[2], p);

    if (!(p = getdestdir (3, arg))) {
      fprintf (stderr, "Cannot get destination directory name.\n");
      relmem (arg);
      free(tmp);
      return (100);
    }
    strcpy (buff, p);
  }

/* Now buff is the destdir */
  p = buff;

  i = (int)strlen (p);

  if (p[i - 1] != '/')
    strcat (p, "/");
  strcat (p, fontname);
  strcat (p, ".tfm");

/* now p (or buff) is the full path name of the tfm font */
/* check if it exists */
  if (_access (p, 0) == 0) {
    fprintf (stderr, "%s exists\n", p);
    printf ("%s\n", p);
    relmem (arg);
    free(tmp);
    return (0);
  }

  cdrive = _getdrive ();
  if (tmp[1] == ':') {
    tdrive = tolower (*tmp) - 'a' + 1;
    _chdrive (tdrive);
  }
  _chdir (tmp);

/* save stdout and stdin */
  savo = _dup (fileno (stdout));
  savi = _dup (fileno (stdin));

/* connect stdout to stderr */
  _dup2 (fileno (stderr), fileno (stdout));

/* connect stdin to nul device */
  if (!(fnul = fopen ("nul", "r"))) {
    fprintf (stderr, "Cannot open nul device to read\n");
    relmem (arg);
    _chdrive (cdrive);
    _chdir (currdir);
    free(tmp);
    return (100);
  }
  _dup2 (fileno (fnul), fileno (stdin));

/* METAFONT command line */
  strcpy (cmd, "--progname=mf --base=mf ");
  strcat (cmd, "\\mode:=ljfour; \\mag:=1; nonstopmode; input ");
  strcat (cmd, fontname);
  strcat (cmd, ";");

  strcpy (execfile, "mf-nowin.exe");
  fprintf (stderr, "%s %s\n", execfile, cmd);
  strcpy(fullbin, texbindir);
  strcat(fullbin, execfile);
  (void) _spawnlp (_P_WAIT, fullbin, execfile, cmd, NULL);

/* return to original stdout and stdin */
  _dup2 (savo, fileno (stdout));
  close (savo);
  _dup2 (savi, fileno (stdin));
  close (savi);

/* close nul device */
  fclose (fnul);

/* check consistency */
  strcpy (cmd, fontname);
  strcat (cmd, ".600gf");

  if (_access (cmd, 0) == -1) {
    fprintf (stderr, "METAFONT failed to make gf font.\n");
    relmem (arg);
    _chdrive (cdrive);
    _chdir (currdir);
    free(tmp);
    return (100);
  }

  remove (cmd);

  strcpy (cmd, fontname);
  strcat (cmd, ".tfm");

/* copy the tfm file */
  if (!(fr = fopen (cmd, "rb"))) {
    fprintf (stderr, "Cannot open %s to read\n", cmd);
    _chdrive (cdrive);
    _chdir (currdir);
    relmem (arg);
    free(tmp);
    return (100);
  }
  if (!(fw = fopen (buff, "wb"))) {
    fprintf (stderr, "Cannot open %s to write\n", buff);
    _chdrive (cdrive);
    _chdir (currdir);
    relmem (arg);
    free(tmp);
    return (100);
  }

  while ((i = (int)fread (rbuff, 1, TBUF, fr)))
    fwrite (rbuff, 1, i, fw);
  fclose (fr);
  fclose (fw);

  strcpy(savebuff, buff);

/* 
  copy log file into the current directory
  in the case that issetdest == 2,
  because feynmf package requires the
  log file.
*/

  if(issetdest == 2) {
    i = (int)strlen(buff);
    if(i > 3) {
      i -= 4;
      buff[i] = '\0';
      strcat(buff, ".log");
      strcpy(cmd, fontname);
      strcat(cmd, ".log");
      if (!(fr = fopen (cmd, "rb"))) {
        fprintf (stderr, "Cannot open %s to read\n", cmd);
        _chdrive (cdrive);
        _chdir (currdir);
        relmem (arg);
        free(tmp);
        return (100);
      }
      if (!(fw = fopen (buff, "wb"))) {
        fprintf (stderr, "Cannot open %s to write\n", buff);
        _chdrive (cdrive);
        _chdir (currdir);
        relmem (arg);
        free(tmp);
        return (100);
      }
      while ((i = (int)fread (rbuff, 1, TBUF, fr)))
        fwrite (rbuff, 1, i, fw);
      fclose (fr);
      fclose (fw);
    }
  }

  relmem (arg);
  if(issetdest != 2)
    mktexupd (savebuff);

/* erase files */
  strcpy (cmd, fontname);
  strcat (cmd, ".log");
  remove (cmd);

  strcpy (cmd, fontname);
  strcat (cmd, ".tfm");
  remove (cmd);

  _chdrive (cdrive);
  _chdir (currdir);

/* send message to Kpathsea */
  printf ("%s\n", savebuff);
  free(tmp);

  return (0);
}
Ejemplo n.º 22
0
static int initDevice(struct net_device *net_dev)
{
	char device_path[256];
	char device_guid[0x100];
	char device_name[1024];

	ULONG tapVer[3];
	ULONG len = 0;

	tap_win32 *dev = (net_dev ? (tap_win32*)(net_dev->priv) : NULL);
	if(dev == NULL) return -1;
	bzero(dev, sizeof(tap_win32));

	if(get_device_guid(device_guid, sizeof(device_guid), device_name, sizeof(device_name)) != 0)
	{
		printm("ERROR: SkyEye requires a TAP-Win32 driver that is at least version %d.%d\n"
		       "Please install from http://prdownloads.sourceforge.net/openvpn/openvpn-2.0_beta2-install.exe\n",
		       TAP_WIN32_MIN_MAJOR, TAP_WIN32_MIN_MINOR);
		return -1;
	}

	if(GetVersion() < 0x80000000)
	{
		char hostip[16];

		sprintf(hostip, "%d.%d.%d.%d",
			net_dev->hostip[0], net_dev->hostip[1], net_dev->hostip[2], net_dev->hostip[3]);

		if(_spawnlp(_P_DETACH, "netsh.exe", "netsh.exe",
			    "interface", "ip", "set", "address", device_name,
			    "static", hostip, "255.255.255.0", NULL) == -1)
		{
			printm("WARNING: Failed to Change IP Address/Mask.\n");
		}
	}

	snprintf(device_path, sizeof(device_path), "%s%s%s", USERMODEDEVICEDIR, device_guid, TAPSUFFIX);

	dev->fHandle = CreateFile(device_path,
				  GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
				  NULL, OPEN_EXISTING,
				  FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, NULL);
	if(dev->fHandle == INVALID_HANDLE_VALUE)
	{
		printm("Opening TAP connection failed\n");
		return -1;
	}

	bzero(&tapVer[0], sizeof(tapVer));
	if(!DeviceIoControl(dev->fHandle, TAP_IOCTL_GET_VERSION,
			    &tapVer[0], sizeof(tapVer), &tapVer[0], sizeof(tapVer), &len, NULL))
	{
		ShowErrorMsg("Could not get driver version info");
		CloseHandle(dev->fHandle);
		return -1;
	}
	if(!(tapVer[0] > TAP_WIN32_MIN_MAJOR || (tapVer[0] == TAP_WIN32_MIN_MAJOR && tapVer[1] >= TAP_WIN32_MIN_MINOR)))
	{
		printm("ERROR: SkyEye requires a TAP-Win32 driver that is at least version %d.%d\n"
		       "Please install an updated version from http://prdownloads.sourceforge.net/openvpn/openvpn-2.0_beta2-install.exe\n",
		       TAP_WIN32_MIN_MAJOR, TAP_WIN32_MIN_MINOR);
		CloseHandle(dev->fHandle);
		return -1;
	}

	tapVer[0] = 1;
	if(!DeviceIoControl(dev->fHandle, TAP_IOCTL_SET_MEDIA_STATUS,
			    &tapVer[0], sizeof(ULONG), &tapVer[0], sizeof(ULONG), &len, NULL))
	{
		ShowErrorMsg("Setting Media Status to connected failed");
		CloseHandle(dev->fHandle);
		return -1;
	}

	InitializeCriticalSection(&dev->fLocker);
	dev->fEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	return 0;
}
Ejemplo n.º 23
0
static enum MqErrorE SysServerSpawn (
    struct MqS * const context,
    char * * argv,
    MQ_CST  name,
    struct MqIdS * idP
)
{
    pid_t pid;
    int err=0;

    // spawn setup !before! a spawn is created
    if (context->setup.fSpawnInit) (*context->setup.fSpawnInit)(context);

    // perl !need! sigschiled enabled at startup make it the default

#if defined(HAVE_POSIX_SPAWN)
    {
        posix_spawnattr_t sa;
        if ((err=posix_spawnattr_init(&sa)) != 0) {
            goto error;
        }
        if (unlikely ((err=posix_spawnp(&pid, name, NULL, &sa, (char *const *) argv, __environ)) != 0)) {
            posix_spawnattr_destroy(&sa);
            goto error;
        }
        if ((err=posix_spawnattr_destroy(&sa)) != 0) {
            goto error;
        }
    }
    goto ok;

#elif (defined(HAVE_FORK) || defined(HAVE_VFORK))  && defined(HAVE_EXECVP)
//#if (defined(HAVE_FORK) || defined(HAVE_VFORK))  && defined(HAVE_EXECVP)

    // fork to create the child
#if defined(HAVE_VFORK)
    if (unlikely ((pid = vfork()) == -1)) goto error;
#elif defined(HAVE_FORK)
    if (unlikely ((pid = MqSysFork()) == -1)) goto error;
#else
    goto error;
#endif

    if (pid == 0) {
        // this is the child
        if (execvp(name, argv) == -1) {
            _exit (EXIT_FAILURE);
        }
        // the child will never reach this
    }
    goto ok;

#elif defined(MQ_IS_WIN32)
    char buf[2048];
    char *nbuf=buf;

    // build command-line
    for (; *argv != '\0'; argv++) {
        nbuf += sprintf(nbuf, "\"%s\" ", *argv);
    }

    // start process
    if (unlikely ((pid = _spawnlp (_P_NOWAIT, name, buf, NULL)) == -1)) {
        //printC(strerror(errno))
        goto error;
    }
    goto ok;

#else
# error unable to SysServerSpawn
#endif

ok:
    (*idP).val = (mqpid_t)pid;
    (*idP).type = MQ_ID_PROCESS;
    return MQ_OK;

error:
    MqErrorDbV (MQ_ERROR_CAN_NOT_START_SERVER, name);
    if (err != 0) {
        MqErrorSysAppend (__func__, err);
    }
    return MqErrorGetCodeI(context);
}
void CWE78_OS_Command_Injection__char_listen_socket_w32_spawnlp_01_bad()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        char *replace;
        SOCKET listenSocket = INVALID_SOCKET;
        SOCKET acceptSocket = INVALID_SOCKET;
        size_t dataLen = strlen(data);
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a listen socket */
            listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (listenSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = INADDR_ANY;
            service.sin_port = htons(TCP_PORT);
            if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
            {
                break;
            }
            acceptSocket = accept(listenSocket, NULL, NULL);
            if (acceptSocket == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed */
            recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* Append null terminator */
            data[dataLen + recvResult / sizeof(char)] = '\0';
            /* Eliminate CRLF */
            replace = strchr(data, '\r');
            if (replace)
            {
                *replace = '\0';
            }
            replace = strchr(data, '\n');
            if (replace)
            {
                *replace = '\0';
            }
        }
        while (0);
        if (listenSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(listenSocket);
        }
        if (acceptSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(acceptSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    /* spawnlp - searches for the location of the command among
     * the directories specified by the PATH environment variable */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
Ejemplo n.º 25
0
/**************************** callBrowser (WIN32) ************************/
int callBrowser(char *url)
/* Returns non-zero on success, 0 on failure */
/* Should use the default browser            */
/* Does nothing with "quit"                  */
{
    static int first=1;
    static char *ComSpec;
    char command[BUFSIZ];
    intptr_t status;

    /* Handle quit */
    if(!strcmp(url,"quit")) {
        /* For compatibility, but do nothing */
        return(3);
    }

    /* Get ComSpec for the command shell (should be defined) */
    if (first) {
        first=0;
        ComSpec = getenv("ComSpec");
    }
    if (!ComSpec) return(0);     /* Abort with no message like the UNIX version*/
    /* Spawn the process that handles a url */
#if 0
    /* Works, command window that goes away */
    sprintf(command,"start \"%s\"",url);
    status = _spawnl(_P_WAIT, ComSpec, ComSpec, "/C", command, NULL);

    /* Works, command window that goes away */
    sprintf(command,"start \"%s\"",url);
    status = _spawnl(_P_DETACH, ComSpec, ComSpec, "/C", command, NULL);

    /* Works, command window that goes away */
    sprintf(command,"\"%s\"",url);
    status = _spawnl(_P_NOWAIT, "c:\\windows\\command\\start.exe",
                     "c:\\windows\\command\\start.exe", command, NULL);

    /* Works, command window that goes away */
    sprintf(command,"\"%s\"",url);
    status = _spawnl(_P_WAIT, ComSpec, "start", command, NULL);

    /* Works, command window that goes away */
    sprintf(command,"start \"%s\"",url);
    status = _spawnl(_P_NOWAIT, ComSpec, ComSpec, "/C", command, NULL);

    /* Doesn't work on 95 (No such file or directory), works on NT */
    sprintf(command,"start \"%s\"",url);
    status = _spawnl(_P_NOWAIT, ComSpec, "/C", command, NULL);

    /* Works on 95, not NT, no command window
       *   No start.exe for NT */
    sprintf(command,"\"%s\"",url);
    status = _spawnlp(_P_DETACH, "start", "start", command, NULL);

    /* Doesn't work on 95 */
    sprintf(command,"\"start %s\"",url);
    status = _spawnl(_P_DETACH, ComSpec, ComSpec, "/C", command, NULL);
#else
    /* This seems to work on 95 and NT, with a command box on 95
       *   It may have trouble if the URL has spaces */
    sprintf(command,"start %s",url);
    status = _spawnl(_P_DETACH, ComSpec, ComSpec, "/C", command, NULL);
#endif
    if(status == -1) {
        char *errstring=strerror(errno);

        printf("\ncallBrowser: Cannot start browser:\n"
               "%s %s\n"
               "  %s\n",ComSpec,command,errstring);
        /* 	perror("callBrowser:"); */
        return(0);
    }
    return(1);
}
Ejemplo n.º 26
0
void EyeDx(char *up_filename,	/* filename of up-image to process; may be empty */
		   char *side_filename,	/* filename of side-image to process; may be empty */
		   int SideOrientation,	/* 0 means left, otherwise right */
		   int FULL_FLAG)		/* flag on outputing full-size annotated images */

{
char	text[250],text1[250],text2[250],savepath[150];
char	BrowserCommand[MAX_FILENAME_CHARS],BrowserPath[MAX_FILENAME_CHARS];
int		up_report,side_report,i;
double	up_lefteye_circles[4],up_righteye_circles[4];
double	side_lefteye_circles[4],side_righteye_circles[4];
int		up_strabismus,side_strabismus;
int		up_red_reflex_lumin,side_red_reflex_lumin;
int		up_left_arr_class,up_right_arr_class;
int		side_left_arr_class,side_right_arr_class;
int		up_left_arr_row,up_left_arr_col;
int		up_right_arr_row,up_right_arr_col;
int		side_left_arr_row,side_left_arr_col;
int		side_right_arr_row,side_right_arr_col,Referral;
FILE	*fpt;
struct tm *newtime;
time_t	aclock;
HANDLE	hFind;
WIN32_FIND_DATA	fd;
HKEY	hKeyHTML,hKeyCommand;
DWORD	Type,Bytes;
char	strab_names[6][20]={"N.A.","NONE","EXOTROPIA","ESOTROPIA",\
					"HYPERTROPIA","NOT LOOKING?"};
char	lumin_names[4][20]={"N.A.","NORMAL","NOT_DETECTED","UNEQUAL"};
char	arr_names[4][20]={"N.A.","NONE","CRESCENT","OTHER"};


		/*********************************************************
		** Process given images.  Result for each image is an eye
		** model (two concentric circles), a strabismus value (0-5),
		** a red reflex luminensce value (0-3), and left & right
		** abnormal red reflex values (0-3).
		*********************************************************/

if (strcmp(up_filename,"") != 0)
  up_report=ProcessImage(up_filename,0,up_lefteye_circles,
	up_righteye_circles,&up_strabismus,&up_red_reflex_lumin,
	&up_left_arr_class,&up_right_arr_class,&up_left_arr_col,
	&up_left_arr_row,&up_right_arr_col,&up_right_arr_row,
	FULL_FLAG,1);
else
  up_report=-1;
if (strcmp(side_filename,"") != 0  &&  SideOrientation == 0)
  side_report=ProcessImage(side_filename,1,side_lefteye_circles,
	side_righteye_circles,&side_strabismus,&side_red_reflex_lumin,
	&side_left_arr_class,&side_right_arr_class,&side_left_arr_col,
	&side_left_arr_row,&side_right_arr_col,&side_right_arr_row,
	FULL_FLAG,1);
else if (strcmp(side_filename,"") != 0  &&  SideOrientation != 0)
  side_report=ProcessImage(side_filename,2,side_lefteye_circles,
	side_righteye_circles,&side_strabismus,&side_red_reflex_lumin,
	&side_left_arr_class,&side_right_arr_class,&side_left_arr_col,
	&side_left_arr_row,&side_right_arr_col,&side_right_arr_row,
	FULL_FLAG,1);
else
  side_report=-1;

		/*********************************************************
		** Make referral decision based on reports
		*********************************************************/

Referral=0;	/* don't refer */
if (up_report >= 0  &&  side_report >= 0)
  {
  if (up_strabismus == 5  ||  side_strabismus == 5  ||
		(up_strabismus == 0  &&  side_strabismus == 0))
    Referral=2;	/* retry */
  if (Referral == 0  &&  (up_strabismus > 1  ||  side_strabismus > 1  ||
		up_red_reflex_lumin == 2  ||  side_red_reflex_lumin == 2  ||
		up_right_arr_class > 1  ||  up_left_arr_class > 1  ||
		side_right_arr_class > 1  ||  side_left_arr_class > 1))
	Referral=1;	/* refer */
  if (Referral == 1  &&  up_strabismus == 1  &&  side_strabismus == 1  &&
	    up_red_reflex_lumin == 1  &&  side_red_reflex_lumin == 1  &&
		up_right_arr_class >= 1  &&  up_right_arr_class <= 2  &&
		up_left_arr_class >= 1  &&  up_left_arr_class <= 2  &&
		side_right_arr_class >= 1  &&  side_right_arr_class <= 2  &&
		side_left_arr_class >= 1  &&  side_left_arr_class <= 2)
	if (DialogBox(hInst,"ID_ONE_YEAR_DIALOG",MainWnd,(DLGPROC)YesNoDlgProc) == IDYES)
	  Referral=0;	/* crescent only, less than one year old = don't refer */
/*
    fprintf(fpt,"Strabismus: <B> %s, %s </B><P>\n",strab_names[up_strabismus],
		strab_names[side_strabismus]);
    fprintf(fpt,"Red Reflex: <B> %s, %s </B><P>\n",
		lumin_names[up_red_reflex_lumin],
		lumin_names[side_red_reflex_lumin]);
    fprintf(fpt,"Abnormal Pupil Area: <B> %s, %s ; %s , %s </B><P>\n",
		arr_names[up_right_arr_class],arr_names[up_left_arr_class],
		arr_names[side_right_arr_class],arr_names[side_left_arr_class]);
*/
  }
else if (up_report >= 0)
  {
  if (up_strabismus == 5  ||  up_strabismus == 0)
    Referral=2;	/* retry */
  if (Referral == 0  &&  (up_strabismus > 1  ||  up_red_reflex_lumin == 2  ||
		up_right_arr_class > 1  ||  up_left_arr_class > 1))
    Referral=1;	/* refer */
  if (Referral == 1  &&  side_strabismus == 1  &&
	    side_red_reflex_lumin == 1  &&
		side_right_arr_class >= 1  &&  side_right_arr_class <= 2  &&
		side_left_arr_class >= 1  &&  side_left_arr_class <= 2)
	if (DialogBox(hInst,"ID_ONE_YEAR_DIALOG",MainWnd,(DLGPROC)YesNoDlgProc) == IDYES)
	  Referral=0;	/* crescent only, less than one year old = don't refer */
/*
    fprintf(fpt,"Strabismus: <B> %s </B><P>\n",strab_names[up_strabismus]);
    fprintf(fpt,"Red Reflex: <B> %s </B><P>\n",lumin_names[up_red_reflex_lumin]);
    fprintf(fpt,"Abnormal Pupil Area: <B> %s, %s </B><P>\n",
		arr_names[up_right_arr_class],arr_names[up_left_arr_class]);
*/
  }
else if (side_report >= 0)
  {
  if (side_strabismus == 5  ||  side_strabismus == 0)
    Referral=2;	/* retry */
  if (Referral == 0  &&  (side_strabismus > 1  ||  side_red_reflex_lumin == 2  ||
		side_right_arr_class > 1  ||  side_left_arr_class > 1))
    Referral=1;	/* refer */
  if (Referral == 1  &&  up_strabismus == 1  &&
	    up_red_reflex_lumin == 1  &&
		up_right_arr_class >= 1  &&  up_right_arr_class <= 2  &&
		up_left_arr_class >= 1  &&  up_left_arr_class <= 2)
	if (DialogBox(hInst,"ID_ONE_YEAR_DIALOG",MainWnd,(DLGPROC)YesNoDlgProc) == IDYES)
	  Referral=0;	/* crescent only, less than one year old = don't refer */
/*
    fprintf(fpt,"Strabismus: <B>%s</B><P>\n",strab_names[side_strabismus]);
    fprintf(fpt,"Red Reflex: <B>%s</B><P>\n",lumin_names[side_red_reflex_lumin]);
    fprintf(fpt,"Abnormal Pupil Area: <B> %s, %s </B><P>\n",
		arr_names[side_right_arr_class],arr_names[side_left_arr_class]);
*/
  }

		/*********************************************************
		** Write graphic and/or letter report
		*********************************************************/

time( &aclock );                 /* Get time in seconds */
newtime = localtime( &aclock );  /* Convert time to struct tm form */
if (/* DisplayGraphics == */1)
  {
  strcpy(savepath,DataPath);
  if (savepath[strlen(savepath)-1] != '\\')
	strcat(savepath,"\\");
  strcat(savepath,"reports");
  if ((hFind=FindFirstFile(savepath,&fd)) == INVALID_HANDLE_VALUE)
    {
    if (!CreateDirectory(savepath,NULL))
	  {
	  MessageBox(NULL,"Saving report","Unable to create reports folder; saving in runtime folder",
		  MB_APPLMODAL | MB_OK);
	  strcpy(savepath,".");
	  }
    }

  FindClose(hFind);

  if (up_report >= 0)
    StripFilename(up_filename,text1);
  if (side_report >= 0)
    StripFilename(side_filename,text2);
  /*
  if (up_report >= 0  &&  side_report >= 0)
    sprintf(text,"%s\\%s-%s.htm",savepath,text1,text2);
  else if (up_report >= 0)
    sprintf(text,"%s\\%s.htm",savepath,text1);
  else
    sprintf(text,"%s\\%s.htm",savepath,text2);
  */
  sprintf(text,"%s\\%s.htm",savepath,report_filename);
  if ((fpt=fopen(text,"w")) == NULL)
    {
    MessageBox(MainWnd,text,"Unable to open report for writing:",MB_APPLMODAL | MB_OK);
    exit(0);
    }
  fprintf(fpt,"<TITLE>EyeDx Photoscreening Results</TITLE>\n");
  fprintf(fpt,"<CENTER><H3>EyeDx Photoscreening Results:  %s</H3><P>\n",report_filename);
  fprintf(fpt,"<H3>Referral recommended: ");
  if (Referral == 1)
	fprintf(fpt,"Yes");
  else if (Referral == 0)
	fprintf(fpt,"No");
  else
	fprintf(fpt,"Image(s) unclear.  Please repeat.");
  fprintf(fpt,"</H3><P>\n<CENTER>\n\n");
  fprintf(fpt,"<TABLE BORDER=3 CELLSPACING=2 CELLPADDING=2>\n");
  fprintf(fpt,"<TR ALIGN=CENTER> ");
  if (up_report >= 0)
    fprintf(fpt,"<TD> Photo ID:  %s (up) ",text1);
  if (side_report >= 0)
    fprintf(fpt,"<TD> Photo ID:  %s (%s) ",text2,
		(SideOrientation == 0 ? "left" : "right"));
  fprintf(fpt,"\n");
    fprintf(fpt,"<TR> ");
  if (up_report >= 0)
    fprintf(fpt,"<TD> <IMG HEIGHT=240 WIDTH=320 SRC=\"..\\Simages\\S%s\">\n",&(up_filename[1]));
  if (side_report >= 0)
    fprintf(fpt,"<TD> <IMG HEIGHT=240 WIDTH=320 SRC=\"..\\Simages\\S%s\">\n",&(side_filename[1]));
  fprintf(fpt,"\n");

  fprintf(fpt,"<TR ALIGN=CENTER> ");
  if (up_report >= 0)
    {
    fprintf(fpt,"<TD> <TABLE BORDER=1 CELLSPACING=2 CELLPADDING=2>\n");
    fprintf(fpt,"  <TR ALIGN=CENTER> <TD> ");
    if (up_report == 0)
      fprintf(fpt,"Please try another photograph.\n");
    else
      {
      fprintf(fpt,"<IMG HEIGHT=150 WIDTH=150 SRC=\"..\\eyes\\%s.right_raw.jpg\">\n",text1);
      fprintf(fpt,"  <TD> <IMG HEIGHT=150 WIDTH=150 SRC=\"..\\eyes\\%s.left_raw.jpg\">\n",text1);
      }
    fprintf(fpt,"  </TABLE><P>\n");
    }
  if (side_report >= 0)
    {
    fprintf(fpt,"<TD> <TABLE BORDER=1 CELLSPACING=2 CELLPADDING=2>\n");
    fprintf(fpt,"  <TR ALIGN=CENTER> <TD> ");
    if (side_report == 0)
      fprintf(fpt,"Please try another photograph.\n");
    else
      {
      fprintf(fpt,"<IMG HEIGHT=150 WIDTH=150 SRC=\"..\\eyes\\%s.right_raw.jpg\">\n",text2);
      fprintf(fpt,"  <TD> <IMG HEIGHT=150 WIDTH=150 SRC=\"..\\eyes\\%s.left_raw.jpg\">\n",text2);
      }
    fprintf(fpt,"  </TABLE><P>\n");
    }
  if (1 /* DisplayGraphics == 1 */)
    {
    fprintf(fpt,"<TR ALIGN=CENTER> ");
    if (up_report >= 0)
      {
      fprintf(fpt,"<TD> <TABLE BORDER=1 CELLSPACING=2 CELLPADDING=2>\n");
      fprintf(fpt,"  <TR ALIGN=CENTER> <TD> ");
      if (up_report == 0)
        fprintf(fpt,"Photo inconclusive.\n");
      else
        {
        fprintf(fpt,"<IMG HEIGHT=150 WIDTH=150 SRC=\"..\\eyes\\%s.right_eye.jpg\">\n",text1);
        fprintf(fpt,"  <TD> <IMG HEIGHT=150 WIDTH=150 SRC=\"..\\eyes\\%s.left_eye.jpg\">\n",text1);
        }
      fprintf(fpt,"  </TABLE><P>\n");
      }
    if (side_report >= 0)
      {
      fprintf(fpt,"<TD> <TABLE BORDER=1 CELLSPACING=2 CELLPADDING=2>\n");
      fprintf(fpt,"  <TR ALIGN=CENTER> <TD> ");
      if (side_report == 0)
        fprintf(fpt,"Photo inconclusive.\n");
      else
        {
        fprintf(fpt,"<IMG HEIGHT=150 WIDTH=150 SRC=\"..\\eyes\\%s.right_eye.jpg\">\n",text2);
        fprintf(fpt,"  <TD> <IMG HEIGHT=150 WIDTH=150 SRC=\"..\\eyes\\%s.left_eye.jpg\">\n",text2);
       }
      fprintf(fpt,"  </TABLE><P>\n");
      }
	}
  fprintf(fpt,"</TABLE><P>\n");
  fprintf(fpt,"</CENTER>\n\n");
  fprintf(fpt,"EyeDx screening estimates refractive errors, strabismus and pupil opacities.\n");
  fprintf(fpt,"Please be aware of the tolerances of the system noted in your manual.\n");
  fprintf(fpt,"Display of annotated eyes is for viewing purposes only and is not required\n");
  fprintf(fpt,"by the EyeDx software to provide the referral recommendation.\n");
  fprintf(fpt,"Patent pending.\n");

  fprintf(fpt,"\n<HR>\n\n");
  fprintf(fpt,"<ADDRESS> [email protected] / %s / %s </A></ADDRESS>\n",Version,asctime(newtime));
  fclose(fpt);
  }
if (1 /* AutoReport == 1 */)
  {		/* look in Windows registry for default command to open html file */
  if (RegOpenKeyEx(HKEY_CLASSES_ROOT,".htm",0,KEY_ALL_ACCESS,&hKeyHTML) == ERROR_SUCCESS)
    {
	Bytes=250;
	RegQueryValueEx(hKeyHTML,"",0,&Type,text1,&Bytes);
	strcat(text1,"\\shell\\open\\command");
	if (RegOpenKeyEx(HKEY_CLASSES_ROOT,text1,0,KEY_ALL_ACCESS,&hKeyCommand) == ERROR_SUCCESS)
	  {
	  Bytes=MAX_FILENAME_CHARS;
	  RegQueryValueEx(hKeyCommand,"",0,&Type,BrowserCommand,&Bytes);
	  i=1;
	  while (BrowserCommand[i] != ':'  ||  BrowserCommand[i+1] != '\\')
		i++;
	  strcpy(BrowserPath,&(BrowserCommand[i-1]));
	  i=0;
	  while (i < (int)strlen(BrowserPath)  &&  BrowserPath[i] != ' ')
		i++;
	  while (i > 0  &&  !(BrowserPath[i] == 'e'  ||  BrowserPath[i] == 'E'))
		i--;
	  BrowserPath[i+1]='\0';
	  RegCloseKey(hKeyCommand);
	  i=strlen(BrowserPath)-1;
	  while (BrowserPath[i] != '\\')
		i--;
	  strcpy(BrowserCommand,&(BrowserPath[i+1]));
	  }
	else
	  {
	  strcpy(BrowserPath,"NotGoingToWork");
	  strcpy(BrowserCommand,"CouldNotFindIt");
	  }
	RegCloseKey(hKeyHTML);
    if (_spawnlp(_P_NOWAIT,BrowserPath,BrowserCommand,text,NULL) == -1)
      MessageBox(NULL,"Unable to start web browser.\nPlease display report manually.",
				"Report finished",MB_OK | MB_APPLMODAL);
	}
  else	/* try some default locations... */
	{
    if (_spawnlp(_P_NOWAIT,"C:\\Program Files\\Netscape\\Navigator\\Program\\netscape","netscape",text,NULL) == -1)
      if (_spawnlp(_P_NOWAIT,"C:\\Program Files\\Netscape\\Communicator\\Program\\netscape","netscape",text,NULL) == -1)
        MessageBox(NULL,"Unable to start web browser.\nPlease display report manually.",
				"Report finished",MB_OK | MB_APPLMODAL);
	}
  }
}
Ejemplo n.º 27
0
	static bool createImage(string fileName, string extension) {
		extension = "-T" + extension;
		auto rv = _spawnlp(P_WAIT, "dot", "dot", extension.c_str(), "-O", fileName.c_str(), NULL);
		return (rv == 0);
	}