コード例 #1
0
int main(int argc, char **argv)
{
    char *password = "";
    int c, o;

    while ((c = fz_getopt(argc, argv, "d:")) != -1)
    {
	switch (c)
	{
	    case 'd': password = fz_optarg; break;
	    default:
		      showusage();
		      break;
	}
    }

    if (fz_optind == argc)
	showusage();

    openxref(argv[fz_optind++], password, 0);

    if (fz_optind == argc)
        for (o = 0; o < xref->len; o++)
            showobject(o, 0);
    else
        while (fz_optind < argc)
        {
            showobject(atoi(argv[fz_optind]), 0);
            fz_optind++;
        }

    closexref();
}
コード例 #2
0
ファイル: echoserv.c プロジェクト: mskuta/tcpserver
int main(int argc, char* argv[]) {
	char* host = NULL;  // listen on all local IP addresses
	char* port = "echo";
	int ch;
	while ((ch = getopt(argc, argv, "h:p:")) != -1) {
		switch (ch) {
			case 'h':
				host = optarg;
				break;
			case 'p':
				port = optarg;
				break;
			default:
				showusage(argv[0]);
				return 2;
		}
	}
	if (argc - optind != 0) {
		showusage(argv[0]);
		return 2;
	}

	tcpserver_t serv = tcpserver_new(host, port, on_listen);
	if (serv == NULL)
		return 1;
	while (true)
		tcpserver_update(serv, -1);
}
コード例 #3
0
ファイル: main.c プロジェクト: rchiossi/radare2
int main(int argc, char **argv) {
    int i;
    if (argc<2)
        showusage (1);
    if (!strcmp (argv[1], "-v"))
        showversion ();
    if (!strcmp (argv[1], "-h"))
        showusage (0);
    if (argc == 2)
        return sdb_dump (argv[1]);

#if USE_MMAN
    signal (SIGINT, terminate);
    signal (SIGHUP, syncronize);
#endif

    if (!strcmp (argv[2], "=")) {
        createdb (argv[1]);
    } else if (!strcmp (argv[2], "-")) {
        char line[SDB_VALUESIZE];
        if ((s = sdb_new (argv[1], 0)))
            for (;;) {
                fgets (line, sizeof line, stdin);
                if (feof (stdin))
                    break;
                line[strlen (line)-1] = 0;
                runline (s, line);
            }
    } else if ((s = sdb_new (argv[1], 0)))
        for (i=2; i<argc; i++)
            runline (s, argv[i]);
    terminate (0);
    return 0;
}
コード例 #4
0
ファイル: main.c プロジェクト: codepongo/radare2
int main(int argc, const char **argv) {
	char *line;
	int i;

	if (argc<2) showusage (1);
	if (!strcmp (argv[1], "-d")) {
		if (argc == 4)
			return dbdiff (argv[2], argv[3]);
		showusage(0);
	} else
	if (!strcmp (argv[1], "-v")) showversion ();
	if (!strcmp (argv[1], "-h")) showusage (0);
	if (!strcmp (argv[1], "-j")) {
		if (argc>2)
			return sdb_dump (argv[2], 1);
		printf ("Missing database filename after -j\n");
		return 1;
	}
	if (!strcmp (argv[1], "-")) {
		argv[1] = "";
		if (argc == 2) {
			argv[2] = "-";
			argc++;
		}
	}
	if (argc == 2)
		return sdb_dump (argv[1], 0);
#if USE_MMAN
	signal (SIGINT, terminate);
	signal (SIGHUP, syncronize);
#endif
	if (!strcmp (argv[2], "="))
		return createdb (argv[1]);
	else if (!strcmp (argv[2], "-")) {
		if ((s = sdb_new (NULL, argv[1], 0))) {
			sdb_config (s, SDB_OPTION_FS | SDB_OPTION_NOSTAMP);
			for (;(line = stdin_gets ());) {
				save = sdb_query (s, line);
				free (line);
			}
		}
	} else {
		s = sdb_new (NULL, argv[1], 0);
		if (!s) return 1;
		sdb_config (s, SDB_OPTION_FS | SDB_OPTION_NOSTAMP);
		for (i=2; i<argc; i++)
			save = sdb_query (s, argv[i]);
	}
	terminate (0);
	return 0;
}
コード例 #5
0
ファイル: test.c プロジェクト: lmaddalena/commander
//
// main:
int main(int argc, char *argv[])
{
	printf("Commander is a command line parsing module writed by L. Maddalena\n");

	t_commander *cmd = makecommander();
	addparam(cmd, "source");
	addparam(cmd, "destination");
	addoption(cmd, "f", "foo", "the foo parameter", 0, "value");
	addoption(cmd, "g", "gas", "the gas parameter", 0, NULL);
	addoption(cmd, "b", "bar", "the bar parameter", 1, "1|2|3");
	addoption(cmd, "z", "baz", "the baz parameter", 1, "name");
	addoption(cmd, "h", "help", "output usage information", 0, NULL);

	int p = parseargs(cmd, argc, argv);
	
	if(argc == 1)
	{
		showusage(argv[0], cmd);
		return 0;		
	}

	if(p == 0 || strcmp(getoptionbysname("h", cmd)->value, "1") == 0)
	{
		showhelp(argv[0], cmd);
		return 0;		
	}
	
	showreport(cmd);
}
コード例 #6
0
ファイル: i2c.c プロジェクト: DavoudiDavoud/ali
int main(int argc, char **argv) {

    printf("Running ... \n");
    
    // parse the command line
    if (comparse(argc, argv) == EXIT_FAILURE) return showusage (EXIT_FAILURE);

    if (!bcm2835_init())
    {
      printf("bcm2835_init failed. Are you running as root??\n");
      return 1;
    }
      
    // I2C begin if specified    
    if (init == I2C_BEGIN)
    {
      if (!bcm2835_i2c_begin())
      {
        printf("bcm2835_i2c_begin failed. Are you running as root??\n");
	return 1;
      }
    }
	  

    // If len is 0, no need to continue, but do I2C end if specified
    if (len == 0) {
         if (init == I2C_END) bcm2835_i2c_end();
	 printf("... done!\n");
         return EXIT_SUCCESS;
    }

    bcm2835_i2c_setSlaveAddress(slave_address);
    bcm2835_i2c_setClockDivider(clk_div);
    fprintf(stderr, "Clock divider set to: %d\n", clk_div);
    fprintf(stderr, "len set to: %d\n", len);
    fprintf(stderr, "Slave address set to: %d\n", slave_address);   
    
    if (mode == MODE_READ) {
    	for (i=0; i<MAX_LEN; i++) buf[i] = 'n';
    	data = bcm2835_i2c_read(buf, len);
    	printf("Read Result = %d\n", data);   
    	for (i=0; i<MAX_LEN; i++) {
    		if(buf[i] != 'n') printf("Read Buf[%d] = %x\n", i, buf[i]);
	}    
    }
    if (mode == MODE_WRITE) {
    	data = bcm2835_i2c_write(wbuf, len);
    	printf("Write Result = %d\n", data);
    }   

    // This I2C end is done after a transfer if specified
    if (init == I2C_END) bcm2835_i2c_end();   
    bcm2835_close();
    printf("... done!\n");
    return 0;
}
コード例 #7
0
ファイル: main.c プロジェクト: 0xroot/radare2
int main(int argc, char **argv) {
	int i;

	if (argc<2)
		showusage (1);
	if (!strcmp (argv[1], "-v"))
		showversion ();
	if (!strcmp (argv[1], "-h"))
		showusage (0);
	if (!strcmp (argv[1], "-")) {
		argv[1] = "";
		if (argc == 2) {
			argv[2] = "-";
			argc++;
		}
	}
	if (argc == 2)
		return sdb_dump (argv[1]);
#if USE_MMAN
	signal (SIGINT, terminate);
	signal (SIGHUP, syncronize);
#endif
	if (!strcmp (argv[2], "=")) {
		createdb (argv[1]);
	} else
	if (!strcmp (argv[2], "-")) {
		char line[SDB_VSZ+SDB_KSZ]; // XXX can overflow stack
		if ((s = sdb_new (argv[1], 0)))
			for (;;) {
				fgets (line, sizeof line, stdin);
				if (feof (stdin))
					break;
				line[strlen (line)-1] = 0;
				save = sdb_query (s, line);
			}
	} else
	if ((s = sdb_new (argv[1], 0))) {
		for (i=2; i<argc; i++)
			save = sdb_query (s, argv[i]);
	}
	terminate (0);
	return 0;
}
コード例 #8
0
ファイル: main.c プロジェクト: djpohly/radare2
int main(int argc, const char **argv) {
	char *line;
	int i;

	if (argc<2) showusage (1);
	if (!strcmp (argv[1], "-v")) showversion ();
	if (!strcmp (argv[1], "-h")) showusage (0);
	if (!strcmp (argv[1], "-")) {
		argv[1] = "";
		if (argc == 2) {
			argv[2] = "-";
			argc++;
		}
	}
	if (argc == 2)
		return sdb_dump (argv[1], 0);
#if USE_MMAN
	signal (SIGINT, terminate);
	signal (SIGHUP, syncronize);
#endif
	if (!strcmp (argv[2], "[]")) {
		return sdb_dump (argv[1], 1);
	} if (!strcmp (argv[2], "="))
		return createdb (argv[1]);
	else if (!strcmp (argv[2], "-")) {
		if ((s = sdb_new (NULL, argv[1], 0))) {
			for (;(line = stdin_gets ());) {
				save = sdb_query (s, line);
				free (line);
			}
		}
	} else {
		s = sdb_new (NULL, argv[1], 0);
		if (!s) return 1;
		for (i=2; i<argc; i++)
			save = sdb_query (s, argv[i]);
	}
	terminate (0);
	return 0;
}
コード例 #9
0
ファイル: pdfshow.c プロジェクト: Limsik/e17
int main(int argc, char **argv)
{
	char *password = "";
	int c;

	while ((c = fz_getopt(argc, argv, "d:bx")) != -1)
	{
		switch (c)
		{
		case 'd': password = fz_optarg; break;
		case 'b': showbinary ++; break;
		case 'x': showdecode ++; break;
		default:
			showusage();
			break;
		}
	}

	if (fz_optind == argc)
		showusage();

	openxref(argv[fz_optind++], password, 0);

	if (fz_optind == argc)
		showtrailer();

	while (fz_optind < argc)
	{
		if (!strcmp(argv[fz_optind], "trailer"))
			showtrailer();
		else if (!strcmp(argv[fz_optind], "xref"))
			showxref();
		else
			showobject(atoi(argv[fz_optind]), 0);
		fz_optind++;
	}

	closexref();
}
コード例 #10
0
ファイル: mtd_debug.c プロジェクト: berte/mediaplayer
int main (int argc,char *argv[])
{
   const char *progname;
   int err = 0,fd,option = OPT_INFO;
   int open_flag;
   (progname = strrchr (argv[0],'/')) ? progname++ : (progname = argv[0]);

   /* parse command-line options */
   if (argc == 3 && !strcmp (argv[1],"info"))
	 option = OPT_INFO;
   else if (argc == 6 && !strcmp (argv[1],"read"))
	 option = OPT_READ;
   else if (argc == 6 && !strcmp (argv[1],"write"))
	 option = OPT_WRITE;
   else if (argc == 5 && !strcmp (argv[1],"erase"))
	 option = OPT_ERASE;
   else
	 showusage (progname);

   /* open device */
   open_flag = (option==OPT_INFO || option==OPT_READ) ? O_RDONLY : O_RDWR;
   if ((fd = open (argv[2],O_SYNC | open_flag)) < 0)
	 {
		perror ("open()");
		exit (1);
	 }

   switch (option)
	 {
	  case OPT_INFO:
		showinfo (fd);
		break;
	  case OPT_READ:
		err = flash_to_file (fd,strtol (argv[3],NULL,0),strtol (argv[4],NULL,0),argv[5]);
		break;
	  case OPT_WRITE:
		err = file_to_flash (fd,strtol (argv[3],NULL,0),strtol (argv[4],NULL,0),argv[5]);
		break;
	  case OPT_ERASE:
		err = erase_flash (fd,strtol (argv[3],NULL,0),strtol (argv[4],NULL,0));
		break;
	 }

   /* close device */
   if (close (fd) < 0)
	 perror ("close()");

   exit (err);
}
コード例 #11
0
ファイル: SamplePdfTool.cpp プロジェクト: iroot/sopdf
void
showmain(int argc, char **argv)
{
	int c;

	while ((c = getopt(argc, argv, "bd")) != -1)
	{
		switch (c)
		{
		case 'b': showbinary ++; break;
		case 'd': showdecode ++; break;
		default:
			  showusage();
			  break;
		}
	}

	if (optind == argc)
		showusage();

	opensrc(argv[optind++], "", 0);

	if (optind == argc)
		showtrailer();

	while (optind < argc)
	{
		if (!strcmp(argv[optind], "trailer"))
			showtrailer();
		else if (!strcmp(argv[optind], "xref"))
			showxref();
		else
			showobject(atoi(argv[optind]), 0);
		optind++;
	}
}
コード例 #12
0
ファイル: brp.c プロジェクト: AirSage/bashreduce
int main(int argc, char * argv[])
{
  line_t line;
  int i, j, col_index;
  int first_line = 1;

  if (argc < 5)
    showusage();
  if (strcmp(argv[1], "-") != 0)
    line.pin = try_open(argv[1], "rb");
  else
    line.pin = stdin;
  col_index = atoi(argv[2]);
  int pouts_len = atoi(argv[3]);
  const char* output_format = argv[4];

  FILE ** pouts = (FILE **) malloc( pouts_len * sizeof(FILE *) );
  char out_path[256];
  for (i = 0; i != pouts_len; ++i)
  {
    sprintf(out_path, output_format, i);
    pouts[i] = try_open(out_path, "wb");
  }

  while (fgets(line.buf, sizeof(line.buf), line.pin)) {
    if (first_line) {
      for (j = 0; j != pouts_len; ++j)
      {
        fputs(line.buf, pouts[j]); // write header to all the files
        first_line = 0;
      }
    }
    else if ( find_col(col_index, &line) ) // if this string has the requisite number of columns
      fputs(line.buf, pouts[fnv_hash(line.col_beg, line.col_end) % pouts_len]); // write it to the correct file
  }

  if (line.pin != stdin)
    fclose(line.pin);

  for (i = 0; i != pouts_len; ++i)
    fclose(pouts[i]);

  return 0;
}
コード例 #13
0
ファイル: main.cpp プロジェクト: CompBioUIC/Kinalyzer
// main function
int main(int argc, char ** argv)
{
  int i = 0;

  if(dolog)
  for(i = 0; i < argc; i ++)
    {
      printf("Argument %d is %s\n", i, argv[i]);
    }

  if(argc <= 1)
    {
      showusage();
      testConsensus();
    }

  /*  else if(strcmp(argv[1], "test") == 0)
    {
      printf("testing mode\n");
    }
  
  else if(strcmp(argv[1], "sibs") == 0)
    {
      printf("sibs mode\n");
      }*/
  else if(strcmp(argv[1], "fathers")== 0 || strcmp(argv[1], "father") == 0)
    {
      if(argc < 5)
        {
          showusage();
          exit(1);
        }

      nloci = atoi( argv[2]);
      mothersmode = 1;
      init();
      readData(argv[3]);
      initMother(); 
     //SetAssigner a(loci);
      if(argc >=6)
        {
          if(strcmp(argv[5],"on") == 0)
            {
              dolog = 1;
            }
          else{
            dolog = 0;
          }
          if(argc>=7)
            {
              readPossibilities(argv[6]);
            }
          else
            {
              readPossibilities("siblings-complete.csv");
            }
        }
      else
        {
          dolog = 0;
          readPossibilities("siblings-complete.csv");
        }
      if( NULL == (dumpfile = fopen( argv[4], "w")))
        {
          printf("Unable to write results\n");
          exit(-1);
        }
      sortLociByAlleleFrequency();
      reconstruct();


      writeResultsFile(argv[4]);
      cleanUp();

    }
  else if(strcmp(argv[1], "test") == 0)
    {

      if(argc < 5)
	{
	  showusage();
	  exit(1);
	}
      
      nloci = atoi( argv[2]);
      init();
      readData(argv[3]);
      //SetAssigner a(loci);
      if(argc >=6)
	{
	  if(strcmp(argv[5],"on") == 0)
	    {
	      dolog = 1;
	    }
	  else{
	    dolog = 0;
	  }
	  if(argc>=7)
	    {
	      readPossibilities(argv[6]);
	    }
	  else
	    {
	      readPossibilities("siblings-complete.csv");
	    }
	}
      else
	{
	  dolog = 0;
	  readPossibilities("siblings-complete.csv");
	}
      if( NULL == (dumpfile = fopen( argv[4], "w")))
	{
	  printf("Unable to write results\n");
	  exit(-1);
	}
      sortLociByAlleleFrequency();
      reconstruct();

      writeResultsFile(argv[4]);
      char gamsname[512];
      strcpy(gamsname, argv[4]);
      strcat(gamsname, ".gms");
      writeGamsFile(gamsname,  sibgroupsmap);
      cleanUp();
      /*readPossibilities(argv[3]);
			  readSlashyData(argv[4]);
			  assignSets();
			  writeResultsToFile(argv[5]);*/
    }
  
  /** 
   * Sibs mode reads actual sibling groups from data and turn by turn
   * gives each group to the setassigner so that we know all the
   * possibilities and can calculate the distance for each possibility
   * 
   */
  else if(argc > 1 && (strcmp(argv[1],"sib") == 0 || strcmp(argv[1],"sibs")==0))
    {
      if(argc < 8)
	{
	  showusage();
	  exit(1);
	}
      if( (strcmp(argv[7],"on") == 0))
	{
	  dolog = 1;
	}
      else
	{
	  dolog = 0;
	}
      nloci = atoi( argv[2]);
      //			doSibsAnalysis(nloci, log, argv[3],argv[5], argv[4], argv[6]	);
      
    }
  else if(argc > 1 && strcmp(argv[1],"consensus") == 0)
    {
      if(argc < 5)
	{	
	  showusage();
	  return 1;
	}
      //      if(argc >= 3)
	{

	  //  if( (strcmp(argv[4],"on") == 0))
	    {
	      dolog = 1;
	    }
	  
	}
      nloci = atoi( argv[2]);
      int minsets = atoi(argv[3]);
      if(nloci == 0)
	{
	  printf("Erroneous # loci\n");
	  exit(-1);
	}
      /*      if(minsets == 0)
	{
	  printf("Erroneous # minsets\n");
	  exit(-1);
	  }*/
      init();     
      readCosts(NULL);
      readPossibilities("siblings-complete.csv");

      doConsensus(argv[3],  (argv+4), argc-4);
      //SetAssigner a(loci);
      //readPossibilities(argv[3]);
      //			Tester t(a);
      /*      if(argc >= 6)
	{
	   doConsensus(argv[3] , (argv+4), );
	  
	  //doEnsemble(argv[4], nloci, a, atoi(argv[5]));
	}
      else
	{
	  
	  for(l = 0; l < nloci; l ++)
	    {
	      //	doEnsemble(argv[4], loci, a, l);
	    }
	    }*/

    }
  else if(argc > 1 && strcmp(argv[1],"greedyconsensus") == 0)
    {
      printf("Entering Greedy Consensus mode\n");
      if(argc < 5)
	{	
	  showusage();
	  return 1;
	}
            if(argc >= 3)
	{

	    if( (strcmp(argv[4],"on") == 0))
	    {
	      dolog = 1;
	    }
	  
	}
      nloci = atoi( argv[2]);
      int minsets = atoi(argv[3]);
        if(nloci == 0)
	{
	  printf("Erroneous # loci\n");
	  exit(-1);
	}
	/*      if(minsets == 0)
	{
	  printf("Erroneous # minsets\n");
	  exit(-1);
	  }*/
      init();     
      readCosts(NULL);
      readPossibilities("siblings-complete.csv");

      doGreedyConsensus(argv[3], (argv+4), argc-4);
      //SetAssigner a(loci);
      //readPossibilities(argv[3]);
      //			Tester t(a);
      /*      if(argc >= 6)
	{
	   doConsensus(argv[3] , (argv+4), );
	  
	  //doEnsemble(argv[4], nloci, a, atoi(argv[5]));
	}
      else
	{
	  
	  for(l = 0; l < nloci; l ++)
	    {
	      //	doEnsemble(argv[4], loci, a, l);
	    }
	    }*/

    }
  
  else if(argc > 1 && strcmp(argv[1],"autoconsensus") == 0)
    {
      if(argc < 3)
        {
          showusage();
          return 1;
        }

      if(argc >= 5)
	{
	  
          if( (strcmp(argv[4],"on") == 0))
	    {
	      dolog = 1;
	    }
	  
	}

      nloci = atoi( argv[2]);
      init();
      readCosts(NULL);
      readPossibilities("siblings-complete.csv");
      doAutoConsensus(argv[3], nloci);
      //SetAssigner a(loci);
      //readPossibilities(argv[3]);
      //                        Tester t(a);
      /*      if(argc >= 6)
        {
           doConsensus(argv[3] , (argv+4), );

          //doEnsemble(argv[4], nloci, a, atoi(argv[5]));
        }
      else
        {

          for(l = 0; l < nloci; l ++)
            {
              //        doEnsemble(argv[4], loci, a, l);
            }
            }*/

    }
  
  else if(argc > 1 && strcmp(argv[1],"autogreedyconsensus") == 0)
    {
      if(argc < 3)
        {
          showusage();
          return 1;
        }

      if(argc >= 5)
	{
	  
          if( (strcmp(argv[4],"on") == 0))
	    {
	      dolog = 1;
	    }
	  
	}

      nloci = atoi( argv[2]);
      init();
      readCosts(NULL);
      readPossibilities("siblings-complete.csv");
      doAutoGreedyConsensus(argv[3], nloci);
      //SetAssigner a(loci);
      //readPossibilities(argv[3]);
      //                        Tester t(a);
      /*      if(argc >= 6)
        {
           doConsensus(argv[3] , (argv+4), );

          //doEnsemble(argv[4], nloci, a, atoi(argv[5]));
        }
      else
        {

          for(l = 0; l < nloci; l ++)
            {
              //        doEnsemble(argv[4], loci, a, l);
            }
            }*/

    }
  else{
    showusage();
  }
#ifndef WINDOWS
  getrusage(RUSAGE_SELF,&usage );
  dumpusage("usage");
#endif // WINDOWS

  
  return 0;
}
コード例 #14
0
ファイル: jamrouter.c プロジェクト: EQ4/jamrouter
/*****************************************************************************
 * main()
 *
 * Parse command line, load patch, start midi_tx, midi_rx, and jack threads.
 *****************************************************************************/
int
main(int argc, char **argv)
{
	char            thread_name[16];
	char            opts[NUM_OPTS * 2 + 1];
	struct option   *op;
	char            *cp;
	char            *p;
	char            *term;
	char            *tokbuf;
	int             c;
	int             j                       = 0;
	int             ret                     = 0;
	int             saved_errno;
	int             argcount                = 0;
	char            **argvals               = argv;
	char            **envp                  = environ;
	char            *argvend                = (char *)argv;
	size_t          argsize;
	unsigned char   rx_channel;

	setlocale(LC_ALL, "C");

	jamrouter_instance = get_instance_num();
	fprintf(stderr, "Starting jamrouter instance %d.\n", jamrouter_instance);

	/* Start debug thread.  debug_class is not set until arguemnts are parsed,
	   so use fprintf() until then. */
	if ((ret = pthread_create(&debug_thread_p, NULL, &jamrouter_debug_thread, NULL)) != 0) {
		fprintf(stderr, "***** ERROR:  Unable to start debug thread.\n");
	}

	/* lock down memory (rt hates page faults) */
	if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
		saved_errno = errno;
		fprintf(stderr, "Unable to unlock memory:  errno=%d (%s)\n",
		        saved_errno, strerror(saved_errno));
	}

	/* init lash client */
#ifndef WITHOUT_LASH
	for (j = 0; j < argc; j++) {
		if ((strcmp(argv[j], "-L") == 0) || (strcmp(argv[j], "--disable-lash") == 0) ||
		    (strcmp(argv[j], "-h") == 0) || (strcmp(argv[j], "--help") == 0) ||
		    (strcmp(argv[j], "-l") == 0) || (strcmp(argv[j], "--list") == 0) ||
		    (strcmp(argv[j], "-v") == 0) || (strcmp(argv[j], "--version") == 0) ||
		    (strcmp(argv[j], "-D") == 0) || (strcmp(argv[j], "--session-dir") == 0) ||
		    (strcmp(argv[j], "-u") == 0) || (strcmp(argv[j], "--uuid") == 0)) {
			lash_disabled = 1;
			break;
		}
	}
	if (!lash_disabled) {
		snprintf(thread_name, 16, "jamrouter%c-lash", ('0' + jamrouter_instance));
		pthread_setname_np(pthread_self(), thread_name);
		if (lash_client_init(&argc, &argv) == 0) {
			lash_poll_event();
		}
		snprintf(thread_name, 16, "jamrouter%c-main", ('0' + jamrouter_instance));
		pthread_setname_np(pthread_self(), thread_name);
	}
#endif

	/* startup initializations */
	init_midi_event_queue();
	init_jack_audio_driver();
	select_midi_driver(NULL, DEFAULT_MIDI_DRIVER);

	/* save original command line for session handling */
	if (jamrouter_cmdline[0] == '\0') {
		jamrouter_cmdline[0] = '\0';
		for (j = 0; j < argc; j++) {
			strcat(&(jamrouter_cmdline[0]), argv[j]);
			strcat(&(jamrouter_cmdline[0]), " ");
		}
		jamrouter_cmdline[strlen(jamrouter_cmdline) - 1] = '\0';
		term = get_color_terminal();
		if (term == NULL) {
			strcpy(jamrouter_full_cmdline, jamrouter_cmdline);
		}
		else {
			snprintf(jamrouter_full_cmdline, 512, "%s -e \"%s \"",
			         term, jamrouter_cmdline);
		}
		argcount = argc;
		argvals  = argv;
	}
	/* command line args supplied by session manager */
	else {
		argcount = 0;
		cp = strdup(jamrouter_cmdline);
		p = cp;
		while ((p = index(p, ' ')) != NULL) {
			p++;
			argcount++;
		}
		if ((argvals = malloc(((size_t)(argcount) + 1UL) *
		                      (size_t)sizeof(char *))) == NULL) {
			fprintf(stderr, "Out of Memory!\n");
			return -1;
		}
		if ((tokbuf = alloca(strlen(jamrouter_cmdline) * 4)) == NULL) {
			fprintf(stderr, "Out of Memory!\n");
			return -1;
		}
		while ((p = strtok_r(cp, " ", &tokbuf)) != NULL) {
			cp = NULL;
			argvals[j++] = p;
		}
		argvals[argcount] = NULL;
	}

	/* build the short option string */
	cp = opts;
	for (op = long_opts; op < &long_opts[NUM_OPTS]; op++) {
		*cp++ = (char) op->val;
		if (op->has_arg) {
			*cp++ = ':';
		}
	}

	/* handle options */
	for (;;) {
		c = getopt_long(argcount, argvals, opts, long_opts, NULL);
		if (c == -1) {
			break;
		}

		switch (c) {
		case 'M':   /* MIDI driver */
			select_midi_driver(optarg, -1);
			break;
		case 'D':   /* MIDI Rx/Tx port/device */
			midi_rx_port_name = strdup(optarg);
			midi_tx_port_name = strdup(optarg);
			break;
		case 'r':   /* MIDI Rx port/device */
			midi_rx_port_name = strdup(optarg);
			break;
		case 't':   /* MIDI Tx port/device */
			midi_tx_port_name = strdup(optarg);
			break;
		case 'x':   /* MIDI Rx latency periods */
			rx_latency_periods = atoi(optarg);
			break;
		case 'X':   /* MIDI Tx latency periods */
			tx_latency_periods = atoi(optarg);
			break;
		case 'g':   /* Tx byte guard time in usec */
			byte_guard_time_usec = atoi(optarg);
			break;
		case 'G':   /* Tx event guard time in usec */
			event_guard_time_usec = atoi(optarg);
			break;
		case 'i':   /* JACK MIDI input port */
			jack_input_port_name = strdup(optarg);
			break;
		case 'o':   /* JACK MIDI output port */
			jack_output_port_name = strdup(optarg);
			break;
		case 'j':   /* Jitter correction mode */
			jitter_correct_mode = 1;
			break;
		case 'z':   /* JACK wake phase within MIDI Rx/Tx period */
			setting_midi_phase_lock = (timecalc_t)(atof(optarg));
			if (setting_midi_phase_lock < (timecalc_t)(0.0625)) {
				setting_midi_phase_lock = (timecalc_t)(0.0625);
			}
			else if (setting_midi_phase_lock > (timecalc_t)(0.9375)) {
				setting_midi_phase_lock = (timecalc_t)(0.9375);
			}
			break;
#ifndef WITHOUT_JACK_DLL
		case '4':   /* JACK DLL timing level 4 */
			jack_dll_level = 4;
			break;
		case '3':   /* JACK DLL timing level 3 */
			jack_dll_level = 3;
			break;
		case '2':   /* JACK DLL timing level 2 */
			jack_dll_level = 2;
			break;
		case '1':   /* JACK DLL timing level 1 */
			jack_dll_level = 1;
			break;
#endif
		case 'k':   /* key to controller mapping */
			if (optarg != NULL) {
				if ((tokbuf = alloca(strlen((const char *)optarg) * 4)) == NULL) {
					jamrouter_shutdown("Out of memory!\n");
				}
				if ((p = strtok_r(optarg, ",", &tokbuf)) != NULL) {
					rx_channel = (atoi(p) - 1) & 0x0F;
					if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
						keymap_tx_channel[rx_channel] = (atoi(p) - 1) & 0x0F;
						if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
							keymap_tx_controller[rx_channel] = atoi(p) & 0x7F;
						}
					}
					JAMROUTER_DEBUG(DEBUG_CLASS_INIT, "Key --> Controller Map:  "
					                "rx_channel=%0d  tx_channel=%d  tx_cc=%d\n",
					                rx_channel + 1,
					                keymap_tx_channel[rx_channel] + 1,
					                keymap_tx_controller[rx_channel]);
				}
			}
			break;
		case 'p':   /* key to pitchbend translation */
			if (optarg != NULL) {
				if ((tokbuf = alloca(strlen((const char *)optarg) * 4)) == NULL) {
					jamrouter_shutdown("Out of memory!\n");
				}
				if ((p = strtok_r(optarg, ",", &tokbuf)) != NULL) {
					rx_channel = (atoi(p) - 1) & 0x0F;
					if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
						pitchmap_tx_channel[rx_channel] = (atoi(p) - 1) & 0x0F;
						if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
							pitchmap_center_note[rx_channel] = atoi(p) & 0x7F;
							if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
								pitchmap_bend_range[rx_channel] = atoi(p) & 0x7F;
							}
						}
					}
					JAMROUTER_DEBUG(DEBUG_CLASS_INIT,
					                "Key --> Pitchbend Map:  "
					                "rx_chan=%0d  tx_chan=%d  center=%d  range=%d\n",
					                rx_channel + 1, pitchmap_tx_channel[rx_channel] + 1,
					                pitchmap_center_note[rx_channel],
					                pitchmap_bend_range[rx_channel]);
				}
			}
			break;
		case 'q':   /* pitchbend to controller translation */
			if (optarg != NULL) {
				if ((tokbuf = alloca(strlen((const char *)optarg) * 4)) == NULL) {
					jamrouter_shutdown("Out of memory!\n");
				}
				if ((p = strtok_r(optarg, ",", &tokbuf)) != NULL) {
					rx_channel = (atoi(p) - 1) & 0x0F;
					if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
						pitchcontrol_tx_channel[rx_channel] = (atoi(p) - 1) & 0x0F;
						if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
							pitchcontrol_controller[rx_channel] = atoi(p) & 0x7F;
						}
					}
					JAMROUTER_DEBUG(DEBUG_CLASS_INIT,
					                "Pitchbend --> Controller Map:  "
					                "rx_chan=%0d  tx_chan=%d  controller=%d\n",
					                rx_channel + 1, pitchcontrol_tx_channel[rx_channel] + 1,
					                pitchcontrol_controller[rx_channel]);
				}
			}
			break;
#ifndef WITHOUT_JUNO
		case 'J':   /* Juno-106 sysex controller translation */
			translate_juno_sysex = 1;
			break;
		case 's':   /* echo sysex translations back to originator */
			echosysex = 1;
			break;
#endif
		case 'e':   /* echo pitchbend and controller translations back to originator */
			echotrans = 1;
			break;
		case 'T':   /* alternate sysex terminator byte */
			sysex_terminator = hex_to_byte(optarg);
			break;
		case 'U':   /* alternate sysex terminator byte */
			sysex_extra_terminator = hex_to_byte(optarg);
			break;
		case 'A':   /* Active-Sensing mode */
			if (strcmp(optarg, "on") == 0) {
				active_sensing_mode = ACTIVE_SENSING_MODE_ON;
			}
			else if (strcmp(optarg, "thru") == 0) {
				active_sensing_mode = ACTIVE_SENSING_MODE_THRU;
			}
			else if (strcmp(optarg, "drop") == 0) {
				active_sensing_mode = ACTIVE_SENSING_MODE_DROP;
			}
			break;
		case 'R':   /* Omit running status byte on MIDI Tx */
			use_running_status = 1;
			break;
		case 'n':   /* Note-On Velocity */
			note_on_velocity = hex_to_byte(optarg);
			break;
		case 'N':   /* Note-Off Velocity */
			note_off_velocity = hex_to_byte(optarg);
			break;
		case 'f':   /* Send multiple Note-Off messages as All-Notes-Off */
			tx_prefer_all_notes_off = 1;
			break;
		case 'F':   /* Tx send real Note-Off instead of Velocity-0-Note-On */
			tx_prefer_real_note_off = 1;
			break;
		case '0':   /* Rx queue real Note-Off instead of Velocity-0-Note-On */
			rx_queue_real_note_off = 1;
			break;
		case 'y':   /* MIDI Rx thread priority */
			if ((midi_rx_thread_priority = atoi(optarg)) <= 0) {
				midi_rx_thread_priority = MIDI_RX_THREAD_PRIORITY;
			}
			break;
		case 'Y':   /* MIDI Tx thread priority */
			if ((midi_tx_thread_priority = atoi(optarg)) <= 0) {
				midi_tx_thread_priority = MIDI_TX_THREAD_PRIORITY;
			}
			break;
		case 'd':   /* debug */
			debug = 1;
			for (j = 0; debug_class_list[j].name != NULL; j++) {
				if (strcmp(debug_class_list[j].name, optarg) == 0) {
					debug_class |= debug_class_list[j].id;
				}
			}
			break;
		case 'v':   /* version */
			printf("jamrouter-%s\n", PACKAGE_VERSION);
			return 0;
		case 'L':   /* disable lash */
			lash_disabled = 1;
			break;
		case 'l':   /* list midi devices */
			scan_midi();
			return 0;
		case 'u':   /* jack session uuid */
			jack_session_uuid = strdup(optarg);
			break;
		case '?':
		case 'h':   /* help */
		default:
			showusage(argv[0]);
			return -1;
		}
	}

	/* Rewrite process title */
	argcount = argc;
	argvals  = argv;
	for (j = 0; j <= argcount; j++) {
		if ((j == 0) || ((argvend + 1) == argvals[j])) {
			argvend = argvals[j] + strlen(argvals[j]);
		}
		else {
			continue;
		}
	}

	/* steal space from first environment entry */
	if (envp[0] != NULL) {
		argvend = envp[0] + strlen (envp[0]);
	}

	/* calculate size we have for process title */
	argsize = (size_t)((char *)argvend - (char *)*argvals - 1);
	memset (*argvals, 0, argsize);

	/* rewrite process title */
	argc = 0;
	snprintf((char *)*argvals, argsize, "jamrouter%d", jamrouter_instance);

	/* signal handlers for clean shutdown */
	init_signal_handlers();

	/* init MIDI system based on selected driver */
	JAMROUTER_DEBUG(DEBUG_CLASS_INIT, "Initializing MIDI:  driver=%s.\n",
	                midi_driver_names[midi_driver]);
	init_sync_info(0, 0);
	init_midi();

	/* initialize JACK audio system based on selected driver */
	snprintf(thread_name, 16, "jamrouter%c-clnt", ('0' + jamrouter_instance));
	pthread_setname_np(pthread_self(), thread_name);
	init_jack_audio();
	while (sample_rate == 0) {
		JAMROUTER_DEBUG(DEBUG_CLASS_INIT,
		                "JACK did not set sample rate.  Re-initializing...\n");
		init_jack_audio();
		usleep(125000);
	}

	/* start the JACK audio system */
	start_jack_audio();

	/* wait for JACK audio to start before starting midi. */
	wait_jack_audio_start();

	snprintf(thread_name, 16, "jamrouter%c-main", ('0' + jamrouter_instance));
	pthread_setname_np(pthread_self(), thread_name);

	/* start MIDI Rx/Tx threads. */
	start_midi_rx();
	wait_midi_rx_start();
	start_midi_tx();
	wait_midi_tx_start();

	/* debug thread not needed once watchdog is running */
	debug_done = 1;
	pthread_join(debug_thread_p, NULL);

	/* Jamrouter watchdog handles restarting threads on config changes,
	   runs driver supplied watchdog loop iterations, and handles debug
	   output. */
	jamrouter_watchdog();
	stop_midi_tx();
	stop_midi_rx();
	stop_jack_audio();
	output_pending_debug();

	/* Wait for threads created directly by JAMROUTER to terminate. */
	if (midi_rx_thread_p != 0) {
		pthread_join(midi_rx_thread_p,  NULL);
	}
	if (midi_tx_thread_p != 0) {
		pthread_join(midi_tx_thread_p,  NULL);
	}
	output_pending_debug();

	return 0;
}
コード例 #15
0
ファイル: pptpd.c プロジェクト: WiseMan787/ralink_sdk
int main(int argc, char **argv)
{
	/* command line options */
	int c;

	/* function-local options */
	int foreground = FALSE;
	char *pid_file = NULL;

	/* config file */
	char *configFile = NULL;

	/* config file parsing temp strings */
	char tmp[MAX_CONFIG_STRING_SIZE], *tmpstr;

	/* open a connection to the syslog daemon */
	openlog("pptpd", LOG_PID, PPTP_FACILITY);
	syslog(LOG_ERR, "MGR: Config file not found!");

	/* process command line options */
	while (1) {
		int option_index = 0;
#ifdef BCRELAY
		char *optstring = "b:c:de:fhil:o:p:s:t:T:vwC:Dk";
#else
		char *optstring = "c:de:fhil:o:p:s:t:T:vwC:Dk";
#endif

		static struct option long_options[] =
		{
#ifdef BCRELAY
			{"bcrelay", 1, 0, 0},
#endif
			{"conf", 1, 0, 'c'},
			{"debug", 0, 0, 'd'},
			{"ppp", 1, 0, 'e'},
			{"fg", 0, 0, 'f'},
			{"help", 0, 0, 'h'},
			{"noipparam", 0, 0, 'i'},
			{"listen", 1, 0, 'l'},
			{"option", 1, 0, 'o'},
			{"pidfile", 1, 0, 'p'},
			{"speed", 1, 0, 's'},
			{"stimeout", 1, 0, 't'},
			{"ptimeout", 1, 0, 'T'},
			{"version", 0, 0, 'v'},
			{"logwtmp", 0, 0, 'w'},
			{"connections", 1, 0, 'C'},
			{"delegate", 0, 0, 'D'},
			{"keep", 0, 0, 'k'},
			{0, 0, 0, 0}
		};

		c = getopt_long(argc, argv, optstring, long_options, &option_index);
		if (c == -1)
			break;
		/* convert long options to short form */
		if (c == 0)
#ifdef BCRELAY
			c = "bcdefhilopstvwCDk"[option_index];
#else
			c = "cdefhilopstvwCDk"[option_index];
#endif
		switch (c) {
#ifdef BCRELAY
		case 'b': /* --bcrelay */
			if (bcrelay) free(bcrelay);
			bcrelay = strdup(optarg);
			break;
#endif

		case 'l': /* --listen */
			tmpstr = lookup(optarg);
			if (!tmpstr) {
				syslog(LOG_ERR, "MGR: Invalid listening address: %s!", optarg);
				return 1;
			}
			if (bindaddr) free(bindaddr);
			bindaddr = strdup(tmpstr);
			break;

		case 'h': /* --help */
			showusage(argv[0]);
			return 0;

		case 'i': /* --noipparam */
			pptp_noipparam = TRUE;
			break;

		case 'e': /* --ppp */
			if (ppp_binary) free(ppp_binary);
			ppp_binary = strdup(optarg);
			break;

		case 'd': /* --debug */
			pptp_debug = TRUE;
			break;

		case 'f': /* --fg */
			foreground = TRUE;
			break;

		case 'v': /* --version */
			showversion();
			return 0;

		case 'w': /* --logwtmp */
		        pptp_logwtmp = TRUE;
			break;

		case 'C': /* --connections */
		        pptp_connections = atoi(optarg);
			break;

		case 'D': /* --delegate */
		        pptp_delegate = TRUE;
			break;

		case 'o': /* --option */
			if (pppdoptstr) free(pppdoptstr);
			pppdoptstr = strdup(optarg);
			break;

		case 'p': /* --pidfile */
			if (pid_file) free(pid_file);
			pid_file = strdup(optarg);
			break;

		case 's': /* --speed */
			if (speedstr) free(speedstr);
			speedstr = strdup(optarg);
			break;

		case 't': /* --stimeout */
			pptp_stimeout = atoi(optarg);
			break;

		case 'T': /* --stimeout */
			pptp_ptimeout = atoi(optarg);
			break;
		case 'k': /* --keep */
			keep_connections = 1;
			break;

		case 'c': /* --conf */
			{
				FILE *f;
				if (!(f = fopen(optarg, "r"))) {
					syslog(LOG_ERR, "MGR: Config file not found!");
					return 1;
				}
				fclose(f);
				if(configFile) free(configFile);
				configFile = strdup(optarg);
				break;
			}

		default:
			showusage(argv[0]);
			return 1;
		}
	}

	/* Now that we have all the command line args.. lets open the
	 * conf file and add anything else (remembering not to override
	 * anything since the command line has more privilages :-)
	 */

	if (!configFile)
		configFile = strdup(PPTPD_CONFIG_FILE_DEFAULT);

	if (read_config_file(configFile, CONNECTIONS_KEYWORD, tmp) > 0) {
		pptp_connections = atoi(tmp);
		if (pptp_connections <= 0)
			pptp_connections = CONNECTIONS_DEFAULT;
	}

	slot_init(pptp_connections);

	if (!pptp_debug && read_config_file(configFile, DEBUG_KEYWORD, tmp) > 0)
		pptp_debug = TRUE;

#ifdef BCRELAY
	if (!bcrelay && read_config_file(configFile, BCRELAY_KEYWORD, tmp) > 0) 
		bcrelay = strdup(tmp);
#endif

	if (!pptp_stimeout && read_config_file(configFile, STIMEOUT_KEYWORD, tmp) > 0) {
		pptp_stimeout = atoi(tmp);
		if (pptp_stimeout <= 0)
			pptp_stimeout = STIMEOUT_DEFAULT;
	}

	if (!pptp_ptimeout && read_config_file(configFile, PTIMEOUT_KEYWORD, tmp) > 0) {
		pptp_ptimeout = atoi(tmp);
		if (pptp_ptimeout <= 0)
			pptp_ptimeout = PTIMEOUT_DEFAULT;
	}

	if (!pptp_noipparam && read_config_file(configFile, NOIPPARAM_KEYWORD, tmp) > 0) {
		pptp_noipparam = TRUE;
	}

	if (!bindaddr && read_config_file(configFile, LISTEN_KEYWORD, tmp) > 0) {
		tmpstr = lookup(tmp);
		if(!tmpstr) {
			syslog(LOG_ERR, "MGR: Invalid listening address: %s!", tmp);
			return 1;
		}
		bindaddr = strdup(tmpstr);
	}

	if (!speedstr && read_config_file(configFile, SPEED_KEYWORD, tmp) > 0)
		speedstr = strdup(tmp);

	if (!pppdoptstr && read_config_file(configFile, PPPD_OPTION_KEYWORD, tmp) > 0) {
		pppdoptstr = strdup(tmp);
	}

	if (!ppp_binary && read_config_file(configFile, PPP_BINARY_KEYWORD, tmp) > 0) {
		ppp_binary = strdup(tmp);
	}

	if (!pptp_logwtmp && read_config_file(configFile, LOGWTMP_KEYWORD, tmp) > 0) {
		pptp_logwtmp = TRUE;
	}

	if (!pptp_delegate && read_config_file(configFile, DELEGATE_KEYWORD, tmp) > 0) {
		pptp_delegate = TRUE;
	}

	if (read_config_file(configFile, KEEP_KEYWORD, tmp) > 0) {
		keep_connections = TRUE;
	}

	if (!pid_file)
		pid_file = strdup((read_config_file(configFile, PIDFILE_KEYWORD,
					tmp) > 0) ? tmp : PIDFILE_DEFAULT);

	if (!pptp_delegate) {
		/* NOTE: remote then local, reason can be seen at the end of processIPStr */

		/* grab the remoteip string from the config file */
		if (read_config_file(configFile, REMOTEIP_KEYWORD, tmp) <= 0) {
			/* use "smart" defaults */
			strlcpy(tmp, DEFAULT_REMOTE_IP_LIST, sizeof(tmp));
		}
		processIPStr(REMOTE, tmp);
	
		/* grab the localip string from the config file */
		if (read_config_file(configFile, LOCALIP_KEYWORD, tmp) <= 0) {
			/* use "smart" defaults */
			strlcpy(tmp, DEFAULT_LOCAL_IP_LIST, sizeof(tmp));
		}
		processIPStr(LOCAL, tmp);
	}

	free(configFile);

	/* if not yet set, adopt default PPP binary path */
	if (!ppp_binary) ppp_binary = strdup(PPP_BINARY);
	/* check that the PPP binary is executable */
	if (access(ppp_binary, X_OK) < 0) {
		syslog(LOG_ERR, "MGR: PPP binary %s not executable",
		       ppp_binary);
		return 1;
	}
	/* check that the PPP options file is readable */
	if (pppdoptstr && access(pppdoptstr, R_OK) < 0) {
		syslog(LOG_ERR, "MGR: PPP options file %s not readable",
		       pppdoptstr);
		return 1;
	}
#ifdef BCRELAY
	/* check that the bcrelay binary is executable */
	if (bcrelay && access(BCRELAY_BIN, X_OK) < 0) {
		syslog(LOG_ERR, "MGR: bcrelay binary %s not executable", 
		       BCRELAY_BIN);
		return 1;
	}
#endif

	syslog(LOG_INFO, "accel-pptpd-%s compiled for pppd-%s\n",VERSION, "2.4.2");

	if (!foreground) {
#if HAVE_DAEMON
		closelog();
		freopen("/dev/null", "r", stdin);
		daemon(0, 0);
		/* returns to child only */
		/* pid will have changed */
		openlog("pptpd", LOG_PID, PPTP_FACILITY);
#else	/* !HAVE_DAEMON */
		my_daemon(argc, argv);
		/* returns to child if !HAVE_FORK
		 * never returns if HAVE_FORK (re-execs with -f)
		 */
#endif
	}

#ifdef BCRELAY
      if (bcrelay) {
             syslog(LOG_DEBUG, "CTRL: BCrelay incoming interface is %s", bcrelay);
             /* Launch BCrelay  */
#ifndef HAVE_FORK
             switch(bcrelayfork = vfork()){
#else
             switch(bcrelayfork = fork()){
#endif
             case -1:        /* fork() error */
                   syslog(LOG_ERR, "CTRL: Error forking to exec bcrelay");
                   _exit(1);

             case 0:         /* child */
                   syslog(LOG_DEBUG, "CTRL (BCrelay Launcher): Launching BCrelay with pid %i", bcrelayfork);
                   launch_bcrelay();
                   syslog(LOG_ERR, "CTRL (BCrelay Launcher): Failed to launch BCrelay.");
                   _exit(1);
             }
       } /* End bcrelay */
#endif

#ifdef CONFIG_NETtel
	/* turn the NETtel VPN LED on */
	ledman_cmd(LEDMAN_CMD_ON, LEDMAN_VPN);
#endif
	/* after we have our final pid... */
	log_pid(pid_file);

	/* manage connections until SIGTERM */
	pptp_manager(argc, argv);
	
#ifdef BCRELAY
	if (bcrelayfork > 0) {
		syslog(LOG_DEBUG, "CTRL: Closing child BCrelay with pid %i", bcrelayfork);
		kill(bcrelayfork, SIGTERM);
	}
#endif

	slot_free();
	return 0;
}

static void log_pid(char *pid_file) {
        FILE    *f;
        pid_t   pid;

        pid = getpid();
        if ((f = fopen(pid_file, "w")) == NULL) {
                syslog(LOG_ERR, "PPTPD: failed to open(%s), errno=%d\n",
                        pid_file, errno);
                return;
        }
        fprintf(f, "%d\n", pid);
        fclose(f);
}
コード例 #16
0
ファイル: bcrelay.c プロジェクト: AllardJ/Tomato
int main(int argc, char **argv) {
  regex_t preg;
  /* command line options */
  int c;
  char *ifout = "";
  char *ifin = "";

#ifndef BCRELAY
  fprintf(stderr,
	  "bcrelay: pptpd was compiled without support for bcrelay, exiting.\n"
	  "         run configure --with-bcrelay, make, and install.\n");
  exit(1);
#endif

        /* open a connection to the syslog daemon */
        openlog("bcrelay", LOG_PID, PPTP_FACILITY);

  while (1) {
                int option_index = 0;

                static struct option long_options[] =
                {
                        {"nolog", 0, 0, 0},
                        {"daemon", 0, 0, 0},
                        {"help", 0, 0, 0},
                        {"incoming", 1, 0, 0},
                        {"outgoing", 1, 0, 0},
                        {"ipsec", 1, 0, 0},
                        {"version", 0, 0, 0},
                        {0, 0, 0, 0}
                };

                c = getopt_long(argc, argv, "ndhi:o:s:v", long_options, &option_index);
                if (c == -1)
                        break;
                /* convert long options to short form */
                if (c == 0)
                        c = "ndhiosv"[option_index];
                switch (c) {
                case 'n':
                        vnologging = 1;
                        break;
                case 'd':
                        vdaemon = 1;
                        break;
                case 'h':
                        showusage(argv[0]);
                        return 0;
                case 'i':
                        ifin = strdup(optarg);
                        break;
                case 'o':
                        ifout = strdup(optarg);
                        break;
                case 's':
                        ipsec = strdup(optarg);
                        // Validate the ipsec parameters
                        regcomp(&preg, "ipsec[0-9]+:[0-9]+.[0-9]+.[0-9]+.255", REG_EXTENDED);
                        if (regexec(&preg, ipsec, 0, NULL, 0)) {
                                syslog(LOG_INFO,"Bad syntax: %s", ipsec);
                                fprintf(stderr, "\nBad syntax: %s\n", ipsec);
                                showusage(argv[0]);
                                return 0;
                        } else {
                                regfree(&preg);
                                break;
                        }
                case 'v':
                        showversion();
                        return 0;
                default:
                        showusage(argv[0]);
                        return 1;
                }
  }
  if (ifin == "") {
       syslog(LOG_INFO,"Incoming interface required!");
       showusage(argv[0]);
       _exit(1);
  }
  if (ifout == "" && ipsec == "") {
       syslog(LOG_INFO,"Listen-mode or outgoing or IPsec interface required!");
       showusage(argv[0]);
       _exit(1);
  } else {
        sprintf(interfaces,"%s|%s", ifin, ifout);
  }

  // If specified, become Daemon.
  if (vdaemon) {
#if HAVE_DAEMON
    closelog();
    freopen("/dev/null", "r", stdin);
    /* set noclose, we want stdout/stderr still attached if we can */
    daemon(0, 1);
    /* returns to child only */
    /* pid will have changed */
    openlog("bcrelay", LOG_PID, PPTP_FACILITY);
#else   /* !HAVE_DAEMON */
    my_daemon(argc, argv);
    /* returns to child if !HAVE_FORK
     * never returns if HAVE_FORK (re-execs without -d)
     */
#endif
  } else {
    syslog(LOG_INFO, "Running as child\n");
  }
  mainloop(argc,argv);
  _exit(0);
}
コード例 #17
0
ファイル: savefile.c プロジェクト: yfyang86/yytex
int main(int argc, char *argv[]) {
	int k, i, n, c;
	int firstarg=1;
	FILE *input, *output;
/*	char destination[FILENAME_MAX]; */
	char infilecivil[FILENAME_MAX], outfilecivil[FILENAME_MAX];
	time_t infiletime, outfiletime;
	char *s;
	time_t timenow;
/*	time_t targettime, sourcetime; */

/*	First lay in background of current date and time */
	timenow = time (NULL);
	if (timenow == -1) fprintf(stderr, "Time does not exist!\n");
	tm = localtime (&timenow);
	year = tm->tm_year + 1900;
	month = tm->tm_mon;
	day = tm->tm_mday;
	hour = tm->tm_hour;
	minute = tm->tm_min;
	second = tm->tm_sec;

	defyear = year;				/* remember current year */
	defmonth = month;			/* remember current month */
	defday = day;				/* remember current day */

/*	if (argc < firstarg + 2) { */
	if (argc < firstarg + 1) showusage (argc, argv);

	firstarg = commandline(argc, argv, firstarg);

/*	if (argc < firstarg + 2) { */
	if (argc < firstarg + 1) showusage(argc, argv);

/*	if (verboseflag != 0)  */
	if (verboseflag != 0 && (startchar != 0 || endchar != 255)) 
		printf("Start %d (%c) end %d (%c)\n", 
			startchar, startchar, endchar, endchar);

	if (strcmp(destination, "") == 0) {	/* last arg is destination direct ? */
/*		strcpy(destination, argv[argc-1]); */
		destination = argv[argc-1];		/* the old way of doing this */
		argc--;
		printf("WARNING: destination not specified, using %s\n", destination);
	}

	if (verboseflag) printf("Destination is %s\n", destination);

/*	for (k = firstarg; k < argc-1; k++) { */
	for (k = firstarg; k < argc; k++) {

		strcpy(infilename, argv[k]);
		s = stripfilename(infilename);
		c = *s;										/* 1992/Oct/ 11 */
		if (c >= 'a' && c <= 'z') c = c  + 'A' - 'a';
		if (c < startchar || c > endchar) continue;

		strcpy(outfilename, destination);
		strcat(outfilename, "\\");
		strcat(outfilename, s);
	
		if (getinfo(infilename, 0) < 0) continue;
/*		infiletime = statbuf.st_atime; */
		infiletime = statbuf[0].st_atime;
		strcpy(infilecivil, timeptr);

		if (traceflag != 0) printf("Considering file %s\n", infilename);

		if (thresholdflag) {
			if (infiletime < newtime){
				if (verboseflag)
					printf("%s not younger than threshold\n", infilename);
				continue;
			}
		}

		if (getinfo(outfilename, 1) < 0) {
			outfiletime = 0;
			strcpy(outfilecivil, "");			
		} 
		else {
/*			outfiletime = statbuf.st_atime; */
			outfiletime = statbuf[1].st_atime;
			strcpy(outfilecivil, timeptr);
		}

/*		if (outfiletime == 0 || outfiletime < infiletime) { */
		if (outfiletime != 0 && outfiletime >= infiletime) {
			if (traceflag) printf("Not younger than destination\n");
			continue;
		}
		
/*		printf("Copying %s ", infilename); */
		printf("Copying %s ", s);
/*		if (strcmp(outfilecivil, "") != 0) { */
		n = strlen(s);
		for (i = n; i < 14; i++) putc(' ', stdout);
		printf("new: %s   ", infilecivil);
		if (strcmp(outfilecivil, "") != 0) 
			printf("old: %s", outfilecivil);
/*		} */
		printf("\n");
		if ((input = fopen(infilename, "rb")) == NULL) {
			perror(infilename);
			continue;
		}
		if (outputflag == 0) {
			printf("Skipping %s\n", outfilename);
			fclose(input);
			continue;
		}
		if (safeflag != 0) { /* temporary, until debugged */
			if ((output = fopen(outfilename, "rb")) != NULL) {
				fclose(output);
				printf("%s already exist\n", outfilename);
				fclose(input);
				continue;
			}
		}
		if ((output = fopen(outfilename, "wb")) == NULL) {
			fclose(input);
			perror(outfilename);
			exit(3);
		}
/*		while ((c = getc(input)) != EOF) putc(c, output); */
		copyfile(output, input);
		if (ferror(input) != 0) {
			perror(infilename);
		}
		fclose(input);
		if (ferror(output) != 0) {
			perror(outfilename);
			exit(5);
		}
		fclose(output);
		if (copydate != 0) {
			timebuf.actime = statbuf[0].st_atime; 
			timebuf.modtime = statbuf[0].st_atime; 
/*			if (utime(argv[k], &timebuf) != 0) {  */
/*			if (utime(outfilename, &timebuf) != 0) {  */
			if (_utime(outfilename, &timebuf) != 0) { 
				fprintf(stderr, "Unable to modify date/time\n");
				perror(argv[1]);
				exit(3);
			} 
		}
/*		} */

/*		if (traceflag != 0) {
			if (getinfo(argv[1]) < 0) exit(1);
		} */
	}
	return 0;
}
コード例 #18
0
ファイル: main.c プロジェクト: commiebstrd/radare2
int main(int argc, const char **argv) {
	char *line;
	int i, ret, fmt = MODE_DFLT;
	int db0 = 1, argi = 1;
	int interactive = 0;

	/* terminate flags */
	if (argc<2) showusage (1);
	if (!strcmp (argv[1], "-d")) {
		if (argc == 4)
			return dbdiff (argv[2], argv[3]);
		showusage (0);
	}
	if (!strcmp (argv[1], "-v")) showversion ();
	if (!strcmp (argv[1], "-h")) showusage (2);
	if (!strcmp (argv[1], "-j")) {
		if (argc>2)
			return sdb_dump (argv[db0+1], MODE_JSON);
		eprintf ("Missing database filename after -j\n");
		return 1;
	}

	/* flags */
	if (!strcmp (argv[argi], "-0")) {
		fmt = MODE_ZERO;
		db0++;
		argi++;
	}
	if (!strcmp (argv[argi], "-")) {
		/* no database */
		argv[argi] = "";
		if (argc == db0+1) {
			interactive = 1;
			/* if no argument passed */
			argv[argi] = "-";
			argc++;
			argi++;
		}
	}
	if (argc-1 == db0)
		return sdb_dump (argv[db0], fmt);
#if USE_MMAN
	signal (SIGINT, terminate);
	signal (SIGHUP, syncronize);
#endif
	ret = 0;
	if (interactive || !strcmp (argv[db0+1], "-")) {
		if ((s = sdb_new (NULL, argv[db0], 0))) {
			save |= insertkeys (s, argv+3, argc-3, '-');
			sdb_config (s, SDB_OPTION_FS | SDB_OPTION_NOSTAMP);
			for (;(line = stdin_gets ());) {
				save |= sdb_query (s, line);
				if (fmt) {
					fflush (stdout);
					write (1, "", 1);
				}
				free (line);
			}
		}
	} else if (!strcmp (argv[db0+1], "=")) {
		ret = createdb (argv[db0], argv+db0+2, argc-(db0+2));
	} else {
		s = sdb_new (NULL, argv[db0], 0);
		if (!s) return 1;
		sdb_config (s, SDB_OPTION_FS | SDB_OPTION_NOSTAMP);
		for (i=db0+1; i<argc; i++) {
			save |= sdb_query (s, argv[i]);
			if (fmt) {
				fflush (stdout);
				write (1, "", 1);
			}
		}
	}
	terminate (0);
	return ret;
}
コード例 #19
0
ファイル: flashcp.c プロジェクト: 119/aircam-openwrt
int main (int argc,char *argv[])
{
	const char *filename = NULL,*device = NULL;
	int i,flags = FLAG_NONE;
	ssize_t result;
	size_t size,written;
	struct mtd_info_user mtd;
	struct erase_info_user erase;
	struct stat filestat;
	unsigned char src[BUFSIZE],dest[BUFSIZE];

	/*********************
	 * parse cmd-line
	 *****************/

	for (;;) {
		int option_index = 0;
		static const char *short_options = "hv";
		static const struct option long_options[] = {
			{"help", no_argument, 0, 'h'},
			{"verbose", no_argument, 0, 'v'},
			{0, 0, 0, 0},
		};

		int c = getopt_long(argc, argv, short_options,
				long_options, &option_index);
		if (c == EOF) {
			break;
		}

		switch (c) {
			case 'h':
				flags |= FLAG_HELP;
				DEBUG("Got FLAG_HELP\n");
				break;
			case 'v':
				flags |= FLAG_VERBOSE;
				DEBUG("Got FLAG_VERBOSE\n");
				break;
			default:
				DEBUG("Unknown parameter: %s\n",argv[option_index]);
				showusage(true);
		}
	}
	if (optind+2 == argc) {
		flags |= FLAG_FILENAME;
		filename = argv[optind];
		DEBUG("Got filename: %s\n",filename);

		flags |= FLAG_DEVICE;
		device = argv[optind+1];
		DEBUG("Got device: %s\n",device);
	}

	if (flags & FLAG_HELP || device == NULL)
		showusage(flags != FLAG_HELP);

	atexit (cleanup);

	/* get some info about the flash device */
	dev_fd = safe_open (device,O_SYNC | O_RDWR);
	if (ioctl (dev_fd,MEMGETINFO,&mtd) < 0)
	{
		DEBUG("ioctl(): %m\n");
		log_printf (LOG_ERROR,"This doesn't seem to be a valid MTD flash device!\n");
		exit (EXIT_FAILURE);
	}

	/* get some info about the file we want to copy */
	fil_fd = safe_open (filename,O_RDONLY);
	if (fstat (fil_fd,&filestat) < 0)
	{
		log_printf (LOG_ERROR,"While trying to get the file status of %s: %m\n",filename);
		exit (EXIT_FAILURE);
	}

	/* does it fit into the device/partition? */
	if (filestat.st_size > mtd.size)
	{
		log_printf (LOG_ERROR,"%s won't fit into %s!\n",filename,device);
		exit (EXIT_FAILURE);
	}

	/*****************************************************
	 * erase enough blocks so that we can write the file *
	 *****************************************************/

#warning "Check for smaller erase regions"

	erase.start = 0;
	erase.length = (filestat.st_size + mtd.erasesize - 1) / mtd.erasesize;
	erase.length *= mtd.erasesize;

	if (flags & FLAG_VERBOSE)
	{
		/* if the user wants verbose output, erase 1 block at a time and show him/her what's going on */
		int blocks = erase.length / mtd.erasesize;
		erase.length = mtd.erasesize;
		log_printf (LOG_NORMAL,"Erasing blocks: 0/%d (0%%)",blocks);
		for (i = 1; i <= blocks; i++)
		{
			log_printf (LOG_NORMAL,"\rErasing blocks: %d/%d (%d%%)",i,blocks,PERCENTAGE (i,blocks));
			if (ioctl (dev_fd,MEMERASE,&erase) < 0)
			{
				log_printf (LOG_NORMAL,"\n");
				log_printf (LOG_ERROR,
						"While erasing blocks 0x%.8x-0x%.8x on %s: %m\n",
						(unsigned int) erase.start,(unsigned int) (erase.start + erase.length),device);
				exit (EXIT_FAILURE);
			}
			erase.start += mtd.erasesize;
		}
		log_printf (LOG_NORMAL,"\rErasing blocks: %d/%d (100%%)\n",blocks,blocks);
	}
	else
	{
		/* if not, erase the whole chunk in one shot */
		if (ioctl (dev_fd,MEMERASE,&erase) < 0)
		{
			log_printf (LOG_ERROR,
					"While erasing blocks from 0x%.8x-0x%.8x on %s: %m\n",
					(unsigned int) erase.start,(unsigned int) (erase.start + erase.length),device);
			exit (EXIT_FAILURE);
		}
	}
	DEBUG("Erased %u / %luk bytes\n",erase.length,filestat.st_size);

	/**********************************
	 * write the entire file to flash *
	 **********************************/

	if (flags & FLAG_VERBOSE) log_printf (LOG_NORMAL,"Writing data: 0k/%luk (0%%)",KB (filestat.st_size));
	size = filestat.st_size;
	i = BUFSIZE;
	written = 0;
	while (size)
	{
		if (size < BUFSIZE) i = size;
		if (flags & FLAG_VERBOSE)
			log_printf (LOG_NORMAL,"\rWriting data: %dk/%luk (%lu%%)",
					KB (written + i),
					KB (filestat.st_size),
					PERCENTAGE (written + i,filestat.st_size));

		/* read from filename */
		safe_read (fil_fd,filename,src,i,flags & FLAG_VERBOSE);

		/* write to device */
		result = write (dev_fd,src,i);
		if (i != result)
		{
			if (flags & FLAG_VERBOSE) log_printf (LOG_NORMAL,"\n");
			if (result < 0)
			{
				log_printf (LOG_ERROR,
						"While writing data to 0x%.8x-0x%.8x on %s: %m\n",
						written,written + i,device);
				exit (EXIT_FAILURE);
			}
			log_printf (LOG_ERROR,
					"Short write count returned while writing to x%.8x-0x%.8x on %s: %d/%lu bytes written to flash\n",
					written,written + i,device,written + result,filestat.st_size);
			exit (EXIT_FAILURE);
		}

		written += i;
		size -= i;
	}
	if (flags & FLAG_VERBOSE)
		log_printf (LOG_NORMAL,
				"\rWriting data: %luk/%luk (100%%)\n",
				KB (filestat.st_size),
				KB (filestat.st_size));
	DEBUG("Wrote %d / %luk bytes\n",written,filestat.st_size);

	/**********************************
	 * verify that flash == file data *
	 **********************************/

	safe_rewind (fil_fd,filename);
	safe_rewind (dev_fd,device);
	size = filestat.st_size;
	i = BUFSIZE;
	written = 0;
	if (flags & FLAG_VERBOSE) log_printf (LOG_NORMAL,"Verifying data: 0k/%luk (0%%)",KB (filestat.st_size));
	while (size)
	{
		if (size < BUFSIZE) i = size;
		if (flags & FLAG_VERBOSE)
			log_printf (LOG_NORMAL,
					"\rVerifying data: %dk/%luk (%lu%%)",
					KB (written + i),
					KB (filestat.st_size),
					PERCENTAGE (written + i,filestat.st_size));

		/* read from filename */
		safe_read (fil_fd,filename,src,i,flags & FLAG_VERBOSE);

		/* read from device */
		safe_read (dev_fd,device,dest,i,flags & FLAG_VERBOSE);

		/* compare buffers */
		if (memcmp (src,dest,i))
		{
			log_printf (LOG_ERROR,
					"File does not seem to match flash data. First mismatch at 0x%.8x-0x%.8x\n",
					written,written + i);
			exit (EXIT_FAILURE);
		}

		written += i;
		size -= i;
	}
	if (flags & FLAG_VERBOSE)
		log_printf (LOG_NORMAL,
				"\rVerifying data: %luk/%luk (100%%)\n",
				KB (filestat.st_size),
				KB (filestat.st_size));
	DEBUG("Verified %d / %luk bytes\n",written,filestat.st_size);

	exit (EXIT_SUCCESS);
}
コード例 #20
0
int main( int argc, char *argv[] ) {

    cout << "extremely randomized trees predictor, coded by Atlee Brink\n\n";

    if( !processarguments( argc, argv ) ) {
        showusage();
        return 0;
    }

    // all the stuff that goes in a model
    string labelname;
    vector< string > exnames;
    vector< string > featurenames;
    nextratrees::forest_t forest;
    size_t nmin, numattr, optimizationlayers;

    // load model from file
    cout << "loading model..." << flush;
    if( !nextratrees::loadmodelfromfile(
        modelfile,
        labelname,
        exnames,
        featurenames,
        forest,
        nmin,
        numattr,
        optimizationlayers )
    ) {
        cerr << "failed to load model from: " << modelfile << endl;
        return 1;
    }
    cout << "done" << endl;

    // convert vector exnames to set
    set< string > excludedfeatures;
    for( auto &name : exnames ) excludedfeatures.insert( name );

    // load test set from file
    cout << "loading test set..." << flush;
    cexampleset testset;
    bool islabeled = false;
    if( !testset.loadfromfile(
        testfile,
        labelname,
        islabeled, // in: says we don't care, out: says whether it was found
        excludedfeatures )
    ) {
        cerr << "failed to load test set from: " << testfile << endl;
        return 1;
    }
    cout << "done" << endl;

    // find index column index
    size_t indexcolumnindex = 0;
    bool usingindex = false;
    if( !indexcolumn.empty() ) {
        while( testset.exnames[ indexcolumnindex ] != indexcolumn ) {
            indexcolumnindex++;
        }
        if( indexcolumnindex < testset.exnames.size() ) {
            usingindex = true;
        }
    }

    // if asked to compute accuracy, check that the data is labeled
    if( computeaccuracy && !islabeled ) {
        cerr << "asked to compute accuracy, but data is not labeled\n";
        return 1;
    }

    // predict labels
    cout << "predicting..." << flush;
    bool dostorepredictions = !predictionsfile.empty();
    ofstream outfile; // may go unused
    if( dostorepredictions ) {
        outfile.open( predictionsfile );
        if( !outfile ) {
            cerr << "error creating output file: " << predictionsfile << endl;
            return false;
        }
        if( usingindex ) outfile << indexcolumn << ",";
        outfile << labelname << "\n";
    }
    size_t numcorrect = 0; // may go unused
    auto Ii = testset.exfeaturevectors.cbegin();
    auto Yi = testset.labels.cbegin(); // may be empty
    for( auto &X : testset.featurevectors ) {

        auto predictedlabel = forest.classify( X );

        if( computeaccuracy ) numcorrect += predictedlabel == *Yi++;
        if( dostorepredictions ) {
            if( usingindex ) outfile << (*Ii++)[indexcolumnindex] << ",";
            outfile << predictedlabel << "\n";
        }

    }
    cout << "done" << endl;

    if( computeaccuracy ) {
        double accuracy = 100.0 * (double)numcorrect / testset.featurevectors.size();
        cout << "accuracy on test set: " << accuracy << "%\n";
    }

    return 0;
}
コード例 #21
0
ファイル: queue.c プロジェクト: wjzhangq/-queue
int main(int argc, char **argv)
{
  int c;
  int     sockfd;
  struct sockaddr_in servaddr, cliaddr;
  int n;
  socklen_t len;
  char msg[MAX_MSG_LENGTH];
  int i;

  settings_init();

  /* process arguments */
  while (-1 != (c = getopt(argc, argv, "hp:dl:Lc:n:e:v"))) {
    switch (c) {
    case 'h':
      showusage();
      exit(EXIT_SUCCESS);
      break;
    case 'p':
      settings.port = atoi(optarg);
      break;
    case 'd':
      settings.daemon = 1;
      break;
    case 'l':
      settings.ipaddr = strdup(optarg);
      break;
    case 'L':
      settings.localonly = 1;
      break;
    case 'c':
      settings.workernum = atoi(optarg);
      break;
    case 'n':
      settings.queuesize = atoi(optarg);
      break;
    case 'e':
      settings.exepath = strdup(optarg);
      break;
    case 'v':
      settings.verbose++;
      break;
    default:
      //fprintf(stderr, "unknown option -- '%c'\n", c);
      return 1;
    }
  }

  if (settings.port < 1) {
    fprintf(stderr, "please use '-p' to specify a port(>1) to listen to\n");
    exit(-1);
  }

  if (settings.workernum < 1) {
    fprintf(stderr, "please use '-c' to specify max num(>1) of concurrent workers\n");
    exit(-1);
  }

  if (settings.queuesize < 1) {
    fprintf(stderr, "please use '-n' to specify queue size(>1)\n");
    exit(-1);
  }

  
  if (settings.exepath == NULL || settings.exepath[0] == '\0') {
    fprintf(stderr, "empty 'script path', use '-e' to specify it\n");
    exit(-1);
  }
  if (access(settings.exepath, R_OK | X_OK) != 0) {
    fprintf(stderr, "script not readble or executable: %s\n", strerror(errno));
    exit(-1);
  }
  
  /* print setttngs */
  printf("settings:\n");
  printf("\tlisten port:  %d\n", settings.port);
  printf("\tdaemon mode:  %s\n", ON_OFF(settings.daemon));
  printf("\tlisten addr:  %s\n",
         (settings.ipaddr != NULL) ? settings.ipaddr : "INADDR_ANY");
  printf("\tlocal only:   %s\n", ON_OFF(settings.localonly));
  printf("\tworker num    %d\n", settings.workernum);
  printf("\tqueue size    %d\n", settings.queuesize);
  printf("\tscript path:  '%s'\n", settings.exepath);
  printf("\tverbose:      %s\n", ON_OFF(settings.verbose));

  /* allocate space for queue */
  id_queue = (int*)malloc(sizeof(int) * settings.queuesize);
  if (id_queue == NULL) {
    fprintf(stderr, "can not allocate memory for id queue\n");
    exit(-1);
  }
  
  for (i = 0; i < MAX_IFNUM; i++) {
    ipaddrs[i] = (char*)malloc(20);
    bzero(ipaddrs[i], 20);
  }
  ifnum = getaddrs(ipaddrs);
  if (ifnum <= 0) {
    fprintf(stderr, "can not get ip address of interface(s)\n");
    exit(EXIT_FAILURE);
  } else if (settings.verbose > 0) {
    printf("ip address of interface(s):\n");
    for (i = 0; i < ifnum; i++) {
      printf("\t%s\n", ipaddrs[i]);
    }
  }

  if (settings.daemon) {
    if (daemonize()) {
      fprintf(stderr, "can't run as daemon\n");
      exit(EXIT_FAILURE);
    }
    printf("run as daemon\n");
  }

  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sockfd == -1) {
    perror("socket error: ");
    exit(EXIT_FAILURE);
  }

  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  if (settings.ipaddr != NULL) {
    if (inet_aton(settings.ipaddr, &(servaddr.sin_addr)) == 0) {
      fprintf(stderr, "invalid ip address to listen: %s\n", settings.ipaddr);
      exit(EXIT_FAILURE);
    }
  } else {
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  }
  servaddr.sin_port = htons(settings.port);

  if (bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))) {
    perror("bind error: ");
    exit(EXIT_FAILURE);
  }

  pthread_mutex_init(&lock, NULL);
  pthread_cond_init(&cond, NULL);
  pthread_mutex_init(&workerlock, NULL);
  pthread_cond_init(&workercond, NULL);
  pthread_mutex_init(&reaperlock, NULL);
  pthread_cond_init(&reapercond, NULL);
  
  /* start thread to reap children */
  do {
    pthread_t t;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    if (pthread_create(&t, &attr, reaper_worker, NULL) != 0) {
      perror("pthread_create error: ");
      exit(EXIT_FAILURE);
    }
  } while (0);

  /* start thread to scan queue */
  do {
    pthread_t t;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    if (pthread_create(&t, &attr, scan_worker, NULL) != 0) {
      perror("pthread_create error: ");
      exit(EXIT_FAILURE);
    }
  } while (0);

  /* close stdio if verbose == 0*/
  if (close_stdio(settings.verbose)) {
    fprintf(stderr, "can't close fd: 0, 1, 2\n");
    exit(EXIT_FAILURE);
  }

  len = sizeof(cliaddr);
  while (1) {
    n = recvfrom(sockfd, msg, MAX_MSG_LENGTH, 0, (struct sockaddr *)&cliaddr, &len);
    if (n < 1) {
      if (settings.verbose > 0) {
        fprintf(stderr, "recvfrom error\n");
      }
      continue;
    }
    if (settings.localonly) {
      char *from = inet_ntoa(cliaddr.sin_addr);
      if (is_local_ip(from)) {
        if (settings.verbose > 0) {
          fprintf(stderr, "deny msg from %s\n", from);
        }
        continue;        
      }
    }
    msg[n] = '\0';
    if (settings.verbose > 0) {
      handle_msg(msg, n, inet_ntoa(cliaddr.sin_addr));
    } else {
      handle_msg(msg, n, NULL);
    }
    /*
    sendto(sockfd, msg, n, 0, (struct sockaddr *)&cliaddr, len);
    */
  }

  return 0;
}
コード例 #22
0
ファイル: maxmatopt.cpp プロジェクト: garviz/Toci
Sint parsemaxmatoptions(MMcallinfo *mmcallinfo,int argc, char *argv[])
{ 
  OptionDescription options[NUMOFOPTIONS];   // store the options
  Sint optval;         // neg. return val. if error, otherwise option number
  Uint argnum;         // pointer to argv
  signed long readint; // temporary integer to read value from string
  char leastlengthtext[128+1];

  initoptions(&options[0],(Uint) NUMOFOPTIONS);
  ADDOPTION(OPTMUM,"-mum",
            "compute maximal matches that are unique in both sequences");
  ADDOPTION(OPTMUMREF,"-mumreference",
	    "compute maximal matches that are unique in the reference-\n"
            "sequence but not necessarily in the query-sequence (default)");
  ADDOPTION(OPTMUMCAND,"-mumcand",
            "same as -mumreference");
  ADDOPTION(OPTMAXMATCH,"-maxmatch",
	    "compute all maximal matches regardless of their uniqueness");
  ADDOPTION(OPTMATCHNUCLEOTIDESONLY,"-n",
            "match only the characters a, c, g, or t\n"
            "they can be in upper or in lower case");
  makeleastlengthtext(&leastlengthtext[0]);
  ADDOPTION(OPTLEASTLENGTH,"-l",&leastlengthtext[0]);
  ADDOPTION(OPTCOMPUTEBOTHDIRECTIONS,"-b",
            "compute forward and reverse complement matches");
  ADDOPTION(OPTONLYREVERSECOMPLEMENT,"-r",
            "only compute reverse complement matches");
  ADDOPTION(OPTSHOWSTRING,"-s",
            "show the matching substrings");
  ADDOPTION(OPTSHOWREVERSEPOSITIONS,"-c",
            "report the query-position of a reverse complement match\n"
            "relative to the original query sequence");
  ADDOPTION(OPTFOURCOLUMN,"-F",
	    "force 4 column output format regardless of the number of\n"
	    "reference sequence inputs");
  ADDOPTION(OPTSHOWSEQUENCELENGTHS,"-L",
            "show the length of the query sequences on the header line");
  ADDOPTION(OPTCHUNKS,"-C","number of chunks to split query sequence");
  ADDOPTION(OPTPREFIXLENGTH,"-P","length of prefix for Direct Access Table");
  ADDOPTION(OPTH,"-h",
	    "show possible options");
  ADDOPTION(OPTHELP,"-help",
            "show possible options");
  mmcallinfo->showstring = false;
  mmcallinfo->reversecomplement = false;
  mmcallinfo->forward = true;
  mmcallinfo->showreversepositions = false;
  mmcallinfo->fourcolumn = false;
  mmcallinfo->showsequencelengths = false;
  mmcallinfo->matchnucleotidesonly = false;
  mmcallinfo->cmum = false;
  mmcallinfo->cmumcand = false;
  mmcallinfo->cmaxmatch = false;
  mmcallinfo->minmatchlength = (Uint) DEFAULTMINUNIQUEMATCHLEN;
  mmcallinfo->chunks = (Uint) DEFAULTCHUNK;

  if(argc == 1)
  {
    showusage(argv[0],&options[0],(Uint) NUMOFOPTIONS);
    return 1;
  }

  for(argnum = UintConst(1); argnum < (Uint) argc && argv[argnum][0] == '-'; 
      argnum++)
  {
    optval = procoption(options,(Uint) NUMOFOPTIONS,argv[argnum]);
    if(optval < 0)
    {
      return -1;
    }
    switch(optval)
    {
      case OPTSHOWSTRING:
        mmcallinfo->showstring = true; 
        break;
      case OPTCOMPUTEBOTHDIRECTIONS:
        mmcallinfo->reversecomplement = true; 
        break;
      case OPTSHOWREVERSEPOSITIONS:
        mmcallinfo->showreversepositions = true; 
        break;
      case OPTLEASTLENGTH:  // additionally check the length parameter
        argnum++;
        if(argnum > (Uint) (argc-2))
        {
          ERROR1("missing argument for option %s",
                  options[OPTLEASTLENGTH].optname);
          return -2;
        }
        if(sscanf(argv[argnum],"%ld",&readint) != 1 || readint <= 0)
        {
          ERROR2("argument %s for option %s is not a positive integer",
                  argv[argnum],options[OPTLEASTLENGTH].optname);
          return -3;
        }
        mmcallinfo->minmatchlength = (Uint) readint;
        break;
      case OPTFOURCOLUMN:
	    mmcallinfo->fourcolumn = true;
	    break;
      case OPTSHOWSEQUENCELENGTHS:
        mmcallinfo->showsequencelengths = true; 
        break;
      case OPTMATCHNUCLEOTIDESONLY:
        mmcallinfo->matchnucleotidesonly = true; 
        break;
      case OPTONLYREVERSECOMPLEMENT:
        mmcallinfo->forward = false; 
        mmcallinfo->reversecomplement = true; 
        break;
      case OPTMAXMATCH:
	    mmcallinfo->cmaxmatch = true;
	    break;
      case OPTMUMREF:
      case OPTMUMCAND:
        mmcallinfo->cmumcand = true;
        break;
      case OPTMUM:
        mmcallinfo->cmum = true;
        break;
      case OPTCHUNKS:
        argnum++;
        if(argnum > (Uint) (argc-2))
        {
          ERROR1("missing argument for option %s",
                  options[OPTCHUNKS].optname);
          return -2;
        }
        if(sscanf(argv[argnum],"%ld",&readint) != 1 || readint <= 0)
        {
          ERROR2("argument %s for option %s is not a positive integer",
                  argv[argnum],options[OPTCHUNKS].optname);
          return -3;
        }
        mmcallinfo->chunks = (Uint) readint;
        break;
      case OPTPREFIXLENGTH:
        argnum++;
        if(argnum > (Uint) (argc-2))
        {
          ERROR1("missing argument for option %s",
                  options[OPTPREFIXLENGTH].optname);
          return -2;
        }
        if(sscanf(argv[argnum],"%ld",&readint) != 1 || readint <= 0)
        {
          ERROR2("argument %s for option %s is not a positive integer",
                  argv[argnum],options[OPTPREFIXLENGTH].optname);
          return -3;
        }
        mmcallinfo->prefix = (Uint) readint;
        break;
      case OPTH:
      case OPTHELP:
        showusage(argv[0],&options[0],(Uint) NUMOFOPTIONS);
        return 1;
    }
  }
  if(argnum > (Uint) (argc-2))
  {
    ERROR0("missing file arguments");
    return -4;
  }
  if(safestringcopy(&mmcallinfo->program[0],argv[0],PATH_MAX) != 0)
  {
    return -5;
  }
  if(safestringcopy(&mmcallinfo->subjectfile[0],argv[argnum],PATH_MAX) != 0)
  {
    return -6;
  }
  for(argnum++, mmcallinfo->numofqueryfiles = 0; 
      argnum < (Uint) argc; mmcallinfo->numofqueryfiles++, argnum++)
  {
    if(mmcallinfo->numofqueryfiles >= (Uint) MAXNUMOFQUERYFILES)
    {
      ERROR1("too many query files, maximal number is %d",
              (int) MAXNUMOFQUERYFILES);
      return -7;
    }
    if(safestringcopy(&mmcallinfo->queryfilelist
                       [mmcallinfo->numofqueryfiles][0],
                      argv[argnum],PATH_MAX) != 0)
    {
      return -8;
    }
  }
  /*
    verify that mum options are not interchanged
  */
  OPTIONEXCLUDE(OPTMUM,OPTMUMCAND);
  OPTIONEXCLUDE(OPTMUM,OPTMUMREF);
  OPTIONEXCLUDE(OPTMUM,OPTMAXMATCH);
  OPTIONEXCLUDE(OPTMUMCAND,OPTMAXMATCH);
  OPTIONEXCLUDE(OPTMUMREF,OPTMAXMATCH);
  if ( mmcallinfo->cmaxmatch )
    {
      mmcallinfo->cmum = false;
      mmcallinfo->cmumcand = false;
    }
  else if ( mmcallinfo->cmum )
    {

    }
  else /* default to cmumcand */
    {
      mmcallinfo->cmumcand = true;
    }
  /*
    verify that the options -b and -r are not used at the same time
  */
  OPTIONEXCLUDE(OPTCOMPUTEBOTHDIRECTIONS,OPTONLYREVERSECOMPLEMENT);
  /*
    verify that -c is only used in combination with either -b or -r
  */
  OPTIONIMPLYEITHER2(OPTSHOWREVERSEPOSITIONS,
                     OPTCOMPUTEBOTHDIRECTIONS,OPTONLYREVERSECOMPLEMENT);
  return 0;
}
コード例 #23
0
ファイル: stripcom.c プロジェクト: yfyang86/yytex
int main(int argc, char *argv[]) {
	char infilename[FILENAME_MAX], outfilename[FILENAME_MAX], bakfilename[FILENAME_MAX];
	FILE *input, *output;
	int m, firstarg = 1;
	int backflag;		/* whether had to rename in file */
	char *s;

	if (argc < firstarg + 1) showusage(argc, argv);
	
/*	while (*argv[firstarg] == '-') */
	while (firstarg < argc && *argv[firstarg] == '-') {
		if (strchr(argv[firstarg], '?') != NULL) showusage(argc, argv);
		if (strchr(argv[firstarg], 'v') != NULL) verboseflag = 1;
		if (strchr(argv[firstarg], 't') != NULL) traceflag = 1;
		if (strchr(argv[firstarg], 'l') != NULL) linestrip = 1;
		if (strchr(argv[firstarg], 'i') != NULL) inlineflag = 1;
		if (strchr(argv[firstarg], 'p') != NULL) commentflag = 1;
		if (strchr(argv[firstarg], 'r') != NULL) stripcontrolm = 1;
		if (strchr(argv[firstarg], 'c') != NULL) checkcontrol = 1;
		if (strchr(argv[firstarg], 'f') != NULL) deleteback = 1;
		if (strchr(argv[firstarg], 'd') != NULL) {
			firstarg++;
			destination = argv[firstarg];
		}
		firstarg++;
	}

	for (m = firstarg; m < argc; m++) {
		backflag=0; linestripped=0; inlinestrip=0;
		strcpy(infilename, argv[m]);
		if (strcmp(destination, "") != 0) {
			strcpy(outfilename, destination);
			strcat(outfilename, "\\");
			strcat(outfilename, stripname(argv[m]));
		}
		else strcpy(outfilename, stripname(argv[m]));
		if (strcmp(infilename, outfilename) == 0) {
			strcpy (bakfilename, infilename);
			if ((s = strrchr(infilename, '.')) != NULL) {
				strcpy (s, ".bak");
				remove (infilename);
				rename (bakfilename, infilename);
				backflag++;
			}
		}
		if (traceflag != 0) printf("Opening %s and %s\n", 
			infilename,	outfilename);
		if ((input = fopen(infilename, "r")) == NULL) {
			perror(infilename); exit(1);
		}
		if (stripcontrolm != 0) {
			if ((output = fopen(outfilename, "wb")) == NULL) {
				perror(outfilename); exit(1);
			}
		}
		else {
			if ((output = fopen(outfilename, "w")) == NULL) {
				perror(outfilename); exit(1);
			}
		}
		if (traceflag != 0) printf("Stripping %s\n", infilename);
		while (fgets(buffer, MAXLINE, input) != NULL) {
			if (stripcomments (buffer) == 0) {
				if (checkcontrol != 0) scancontrol(buffer);
				if (fputs(buffer, output) == EOF) {
					perror(outfilename); break;
				}
			}
		}

		if (traceflag != 0) printf("Closing %s and %s\n", 
			infilename, outfilename);
		fclose(input);
		if (ferror(output) != 0) {
			perror(outfilename); exit(1);
		}
		else fclose(output);

		if (verboseflag != 0) {
			if (linestripped > 0 || inlinestrip > 0) {
				printf("Stripped ");
				if (linestripped > 0) 
					printf("%d complete lines ", linestripped);
				if (inlinestrip > 0) 
					printf("%d comments in lines ", inlinestrip); 
				putc('\n', stdout);
			}				
		}
		if (traceflag != 0) printf("Copying date and time\n");
		if (getinfo(infilename, verboseflag) < 0) {
			exit(1);
		}
	
		timebuf.actime = statbuf.st_atime;
		timebuf.modtime = statbuf.st_atime;
		if (_utime(outfilename, &timebuf) != 0) {
			fprintf(stderr, "Unable to modify date/time\n");
			perror(outfilename);
/*			exit(3); */
		}

/*		see if it worked */
		if (getinfo(outfilename, traceflag) < 0) exit(1);
		
		if (backflag != 0 && deleteback != 0)
			remove(infilename);
	}
	return 0;
}
コード例 #24
0
ファイル: main.c プロジェクト: lionaneesh/radare2
int main(int argc, const char **argv) {
	char *line;
	const char *arg, *grep = NULL;
	int i, ret, fmt = MODE_DFLT;
	int db0 = 1, argi = 1;
	bool interactive = false;

	/* terminate flags */
	if (argc < 2) {
		return showusage (1);
	}
	arg = argv[1];

	if (arg[0] == '-') {// && arg[1] && arg[2]==0) {
		switch (arg[1]) {
		case 0:
			/* no-op */
			break;
		case '0':
			fmt = MODE_ZERO;
			db0++;
			argi++;
			if (db0 >= argc) {
				return showusage (1);
			}
			break;
		case 'g':
			db0 += 2;
			if (db0 >= argc) {
				return showusage (1);
			}
			grep = argv[2];
			argi += 2;
			break;
		case 'J':
			options |= SDB_OPTION_JOURNAL;
			db0++;
			argi++;
			if (db0 >= argc) {
				return showusage (1);
			}
			break;
		case 'c': return (argc < 3)? showusage (1) : showcount (argv[2]);
		case 'v': return showversion ();
		case 'h': return showusage (2);
		case 'e': return base64encode ();
		case 'd': return base64decode ();
		case 'D':
			if (argc == 4) {
				return dbdiff (argv[2], argv[3]);
			}
			return showusage (0);
		case 'j':
			if (argc > 2) {
				return sdb_dump (argv[db0 + 1], MODE_JSON);
			}
			return jsonIndent();
		default:
			eprintf ("Invalid flag %s\n", arg);
			break;
		}
	}

	/* sdb - */
	if (argi == 1 && !strcmp (argv[argi], "-")) {
		/* no database */
		argv[argi] = "";
		if (argc == db0 + 1) {
			interactive = true;
			/* if no argument passed */
			argv[argi] = "-";
			argc++;
			argi++;
		}
	}
	/* sdb dbname */
	if (argc - 1 == db0) {
		if (grep) {
			return sdb_grep (argv[db0], fmt, grep);
		}
		return sdb_dump (argv[db0], fmt);
	}
#if USE_MMAN
	signal (SIGINT, terminate);
	signal (SIGHUP, synchronize);
#endif
	ret = 0;
	if (interactive || !strcmp (argv[db0 + 1], "-")) {
		if ((s = sdb_new (NULL, argv[db0], 0))) {
			sdb_config (s, options);
			int kvs = db0 + 2;
			if (kvs < argc) {
				save |= insertkeys (s, argv + argi + 2, argc - kvs, '-');
			}
			for (;(line = stdin_slurp (NULL));) {
				save |= sdb_query (s, line);
				if (fmt) {
					fflush (stdout);
					write (1, "", 1);
				}
				free (line);
			}
		}
	} else if (!strcmp (argv[db0 + 1], "=")) {
		ret = createdb (argv[db0], NULL, 0);
	} else {
		s = sdb_new (NULL, argv[db0], 0);
		if (!s) {
			return 1;
		}
		sdb_config (s, options);
		for (i = db0 + 1; i < argc; i++) {
			save |= sdb_query (s, argv[i]);
			if (fmt) {
				fflush (stdout);
				write (1, "", 1);
			}
		}
	}
	terminate (0);
	return ret;
}
コード例 #25
0
/** entry point */
int main(int argc, char *argv[])
{
    const char *uuid = NULL;
    int c;
    int listHostModes = 0;
    int quit = 0;
    const struct option options[] =
    {
        { "help",          no_argument,       NULL, 'h' },
        { "startvm",       required_argument, NULL, 's' },
        { "fixedres",      required_argument, NULL, 'f' },
        { "listhostmodes", no_argument,       NULL, 'l' },
        { "scale",         no_argument,       NULL, 'c' }
    };

    printf("VirtualBox DirectFB GUI built %s %s\n"
           "(C) 2004-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
           "(C) 2004-2005 secunet Security Networks AG\n", __DATE__, __TIME__);

    for (;;)
    {
        c = getopt_long(argc, argv, "s:", options, NULL);
        if (c == -1)
            break;
        switch (c)
        {
            case 'h':
            {
                showusage();
                exit(0);
                break;
            }
            case 's':
            {
                // UUID as string, parse it
                RTUUID buuid;
                if (!RT_SUCCESS(RTUuidFromStr((PRTUUID)&buuid, optarg)))
                {
                    printf("Error, invalid UUID format given!\n");
                    showusage();
                    exit(-1);
                }
                uuid = optarg;
                break;
            }
            case 'f':
            {
                if (sscanf(optarg, "%ux%ux%u", &fixedVideoMode.width, &fixedVideoMode.height,
                           &fixedVideoMode.bpp) != 3)
                {
                    printf("Error, invalid resolution argument!\n");
                    showusage();
                    exit(-1);
                }
                useFixedVideoMode = 1;
                break;
            }
            case 'l':
            {
                listHostModes = 1;
                break;
            }
            case 'c':
            {
                scaleGuest = 1;
                break;
            }
            default:
                break;
        }
    }

    // check if we got a UUID
    if (!uuid)
    {
        printf("Error, no UUID given!\n");
        showusage();
        exit(-1);
    }


    /**
     * XPCOM setup
     */

    nsresult rc;
    /*
     * Note that we scope all nsCOMPtr variables in order to have all XPCOM
     * objects automatically released before we call NS_ShutdownXPCOM at the
     * end. This is an XPCOM requirement.
     */
    {
        nsCOMPtr<nsIServiceManager> serviceManager;
        rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), nsnull, nsnull);
        if (NS_FAILED(rc))
        {
            printf("Error: XPCOM could not be initialized! rc=0x%x\n", rc);
            exit(-1);
        }

        // register our component
        nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(serviceManager);
        if (!registrar)
        {
            printf("Error: could not query nsIComponentRegistrar interface!\n");
            exit(-1);
        }
        registrar->AutoRegister(nsnull);

        /*
         * Make sure the main event queue is created. This event queue is
         * responsible for dispatching incoming XPCOM IPC messages. The main
         * thread should run this event queue's loop during lengthy non-XPCOM
         * operations to ensure messages from the VirtualBox server and other
         * XPCOM IPC clients are processed. This use case doesn't perform such
         * operations so it doesn't run the event loop.
         */
        nsCOMPtr<nsIEventQueue> eventQ;
        rc = NS_GetMainEventQ(getter_AddRefs (eventQ));
        if (NS_FAILED(rc))
        {
            printf("Error: could not get main event queue! rc=%08X\n", rc);
            return -1;
        }

        /*
         * Now XPCOM is ready and we can start to do real work.
         * IVirtualBox is the root interface of VirtualBox and will be
         * retrieved from the XPCOM component manager. We use the
         * XPCOM provided smart pointer nsCOMPtr for all objects because
         * that's very convenient and removes the need deal with reference
         * counting and freeing.
         */
        nsCOMPtr<nsIComponentManager> manager;
        rc = NS_GetComponentManager (getter_AddRefs (manager));
        if (NS_FAILED(rc))
        {
            printf("Error: could not get component manager! rc=%08X\n", rc);
            exit(-1);
        }

        nsCOMPtr<IVirtualBox> virtualBox;
        rc = manager->CreateInstanceByContractID(NS_VIRTUALBOX_CONTRACTID,
                                                 nsnull,
                                                 NS_GET_IID(IVirtualBox),
                                                 getter_AddRefs(virtualBox));
        if (NS_FAILED(rc))
        {
            printf("Error, could not instantiate object! rc=0x%x\n", rc);
            exit(-1);
        }

        nsCOMPtr<ISession> session;
        rc = manager->CreateInstance(CLSID_Session,
                                     nsnull,
                                     NS_GET_IID(ISession),
                                     getter_AddRefs(session));
        if (NS_FAILED(rc))
        {
            printf("Error: could not instantiate Session object! rc = %08X\n", rc);
            exit(-1);
        }

        // open session for this VM
        rc = virtualBox->OpenSession(session, NS_ConvertUTF8toUTF16(uuid).get());
        if (NS_FAILED(rc))
        {
            printf("Error: given machine not found!\n");
            exit(-1);
        }
        nsCOMPtr<IMachine> machine;
        session->GetMachine(getter_AddRefs(machine));
        if (!machine)
        {
            printf("Error: given machine not found!\n");
            exit(-1);
        }
        nsCOMPtr<IConsole> console;
        session->GetConsole(getter_AddRefs(console));
        if (!console)
        {
            printf("Error: cannot get console!\n");
            exit(-1);
        }

        nsCOMPtr<IDisplay> display;
        console->GetDisplay(getter_AddRefs(display));
        if (!display)
        {
            printf("Error: could not get display object!\n");
            exit(-1);
        }

        nsCOMPtr<IKeyboard> keyboard;
        nsCOMPtr<IMouse> mouse;
        VBoxDirectFB *frameBuffer = NULL;

        /**
         * Init DirectFB
         */
        IDirectFB *dfb = NULL;
        IDirectFBSurface *surface = NULL;
        IDirectFBInputDevice *dfbKeyboard = NULL;
        IDirectFBInputDevice *dfbMouse = NULL;
        IDirectFBEventBuffer *dfbEventBuffer = NULL;
        DFBSurfaceDescription dsc;
        int screen_width, screen_height;

        DFBCHECK(DirectFBInit(&argc, &argv));
        DFBCHECK(DirectFBCreate(&dfb));
        DFBCHECK(dfb->SetCooperativeLevel(dfb, DFSCL_FULLSCREEN));
        // populate our structure of supported video modes
        DFBCHECK(dfb->EnumVideoModes(dfb, enumVideoModesHandler, NULL));

        if (listHostModes)
        {
            printf("*****************************************************\n");
            printf("Number of available host video modes: %u\n", numVideoModes);
            for (uint32_t i = 0; i < numVideoModes; i++)
            {
                printf("Mode %u: xres = %u, yres = %u, bpp = %u\n", i,
                       videoModes[i].width, videoModes[i].height, videoModes[i].bpp);
            }
            printf("Note: display modes with bpp < have been filtered out\n");
            printf("*****************************************************\n");
            goto Leave;
        }

        if (useFixedVideoMode)
        {
            int32_t bestVideoMode = getBestVideoMode(fixedVideoMode.width,
                                                     fixedVideoMode.height,
                                                     fixedVideoMode.bpp);
            // validate the fixed mode
            if ((bestVideoMode == -1) ||
                ((fixedVideoMode.width  != videoModes[bestVideoMode].width) ||
                (fixedVideoMode.height != videoModes[bestVideoMode].height) ||
                (fixedVideoMode.bpp    != videoModes[bestVideoMode].bpp)))
            {
                printf("Error: the specified fixed video mode is not available!\n");
                exit(-1);
            }
        } else
        {
            initialVideoMode = getBestVideoMode(640, 480, 16);
            if (initialVideoMode == -1)
            {
                printf("Error: initial video mode 640x480x16 is not available!\n");
                exit(-1);
            }
        }

        dsc.flags = DSDESC_CAPS;
        dsc.caps = DSCAPS_PRIMARY;
        DFBCHECK(dfb->CreateSurface(dfb, &dsc, &surface));
        DFBCHECK(surface->Clear(surface, 0, 0, 0, 0));
        DFBCHECK(surface->GetSize(surface, &screen_width, &screen_height));
        DFBCHECK(dfb->GetInputDevice(dfb, DIDID_KEYBOARD, &dfbKeyboard));
        DFBCHECK(dfbKeyboard->CreateEventBuffer(dfbKeyboard, &dfbEventBuffer));
        DFBCHECK(dfb->GetInputDevice(dfb, DIDID_MOUSE, &dfbMouse));
        DFBCHECK(dfbMouse->AttachEventBuffer(dfbMouse, dfbEventBuffer));


        if (useFixedVideoMode)
        {
            printf("Information: setting video mode to %ux%ux%u\n", fixedVideoMode.width,
                   fixedVideoMode.height, fixedVideoMode.bpp);
            DFBCHECK(dfb->SetVideoMode(dfb, fixedVideoMode.width,
                                       fixedVideoMode.height, fixedVideoMode.bpp));
        } else
        {
            printf("Information: starting with default video mode %ux%ux%u\n",
                   videoModes[initialVideoMode].width, videoModes[initialVideoMode].height,
                   videoModes[initialVideoMode].bpp);
            DFBCHECK(dfb->SetVideoMode(dfb, videoModes[initialVideoMode].width,
                                            videoModes[initialVideoMode].height,
                                            videoModes[initialVideoMode].bpp));
        }

        // register our framebuffer
        frameBuffer = new VBoxDirectFB(dfb, surface);
        display->SetFramebuffer(0, frameBuffer);

        /**
         * Start the VM execution thread
         */
        console->PowerUp(NULL);

        console->GetKeyboard(getter_AddRefs(keyboard));
        console->GetMouse(getter_AddRefs(mouse));

        /**
         * Main event loop
         */
        #define MAX_KEYEVENTS 10
        PRInt32 keyEvents[MAX_KEYEVENTS];
        int numKeyEvents;

        while (!quit)
        {
            DFBInputEvent event;

            numKeyEvents = 0;
            DFBCHECK(dfbEventBuffer->WaitForEvent(dfbEventBuffer));
            while (dfbEventBuffer->GetEvent(dfbEventBuffer, DFB_EVENT(&event)) == DFB_OK)
            {
                int mouseXDelta = 0;
                int mouseYDelta = 0;
                int mouseZDelta = 0;
                switch (event.type)
                {
                    #define QUEUEEXT() keyEvents[numKeyEvents++] = 0xe0
                    #define QUEUEKEY(scan) keyEvents[numKeyEvents++] = scan | (event.type == DIET_KEYRELEASE ? 0x80 : 0x00)
                    #define QUEUEKEYRAW(scan) keyEvents[numKeyEvents++] = scan
                    case DIET_KEYPRESS:
                    case DIET_KEYRELEASE:
                    {
                        // @@@AH development hack to get out of it!
                        if ((event.key_id == DIKI_ESCAPE) && (event.modifiers & (DIMM_CONTROL | DIMM_ALT)))
                            quit = 1;

                        if (numKeyEvents < MAX_KEYEVENTS)
                        {
                            //printf("%s: key_code: 0x%x\n", event.type == DIET_KEYPRESS ? "DIET_KEYPRESS" : "DIET_KEYRELEASE", event.key_code);
                            switch ((uint32_t)event.key_id)
                            {
                                case DIKI_CONTROL_R:
                                    QUEUEEXT();
                                    QUEUEKEY(0x1d);
                                    break;
                                case DIKI_INSERT:
                                    QUEUEEXT();
                                    QUEUEKEY(0x52);
                                    break;
                                case DIKI_DELETE:
                                    QUEUEEXT();
                                    QUEUEKEY(0x53);
                                    break;
                                case DIKI_HOME:
                                    QUEUEEXT();
                                    QUEUEKEY(0x47);
                                    break;
                                case DIKI_END:
                                    QUEUEEXT();
                                    QUEUEKEY(0x4f);
                                    break;
                                case DIKI_PAGE_UP:
                                    QUEUEEXT();
                                    QUEUEKEY(0x49);
                                    break;
                                case DIKI_PAGE_DOWN:
                                    QUEUEEXT();
                                    QUEUEKEY(0x51);
                                    break;
                                case DIKI_LEFT:
                                    QUEUEEXT();
                                    QUEUEKEY(0x4b);
                                    break;
                                case DIKI_RIGHT:
                                    QUEUEEXT();
                                    QUEUEKEY(0x4d);
                                    break;
                                case DIKI_UP:
                                    QUEUEEXT();
                                    QUEUEKEY(0x48);
                                    break;
                                case DIKI_DOWN:
                                    QUEUEEXT();
                                    QUEUEKEY(0x50);
                                    break;
                                case DIKI_KP_DIV:
                                    QUEUEEXT();
                                    QUEUEKEY(0x35);
                                    break;
                                case DIKI_KP_ENTER:
                                    QUEUEEXT();
                                    QUEUEKEY(0x1c);
                                    break;
                                case DIKI_PRINT:
                                    // the break code is inverted!
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEEXT();
                                        QUEUEKEY(0x2a);
                                        QUEUEEXT();
                                        QUEUEKEY(0x37);
                                    } else
                                    {
                                        QUEUEEXT();
                                        QUEUEKEY(0x37);
                                        QUEUEEXT();
                                        QUEUEKEY(0x2a);
                                    }
                                    break;
                                case DIKI_PAUSE:
                                    // This is a super weird key. No break code and a 6 byte
                                    // combination.
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEKEY(0xe1);
                                        QUEUEKEY(0x1d);
                                        QUEUEKEY(0x45);
                                        QUEUEKEY(0xe1);
                                        QUEUEKEY(0x9d);
                                        QUEUEKEY(0xc5);
                                    }
                                    break;
                                case DIKI_META_L:
                                    // the left Windows logo is a bit different
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0x1f);
                                    } else
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0xf0);
                                        QUEUEKEYRAW(0x1f);
                                    }
                                    break;
                                case DIKI_META_R:
                                    // the right Windows logo is a bit different
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0x27);
                                    } else
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0xf0);
                                        QUEUEKEYRAW(0x27);
                                    }
                                    break;
                                case DIKI_SUPER_R:
                                    // the popup menu is a bit different
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0x2f);
                                    } else
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0xf0);
                                        QUEUEKEYRAW(0x2f);
                                    }
                                    break;

                                default:
                                    // check if we got a hardware scancode
                                    if (event.key_code != -1)
                                    {
                                        // take the scancode from DirectFB as is
                                        QUEUEKEY(event.key_code);
                                    } else
                                    {
                                        // XXX need extra handling!
                                    }
                            }
                        }
                        break;
                    }
                    #undef QUEUEEXT
                    #undef QUEUEKEY
                    #undef QUEUEKEYRAW

                    case DIET_AXISMOTION:
                    {
                        switch (event.axis)
                        {
                            case DIAI_X:
                                mouseXDelta += event.axisrel;
                                break;
                            case DIAI_Y:
                                mouseYDelta += event.axisrel;
                                break;
                            case DIAI_Z:
                                mouseZDelta += event.axisrel;
                                break;
                            default:
                                break;
                        }
                        // fall through
                    }
                    case DIET_BUTTONPRESS:
                        // fall through;
                    case DIET_BUTTONRELEASE:
                    {
                        int buttonState = 0;
                        if (event.buttons & DIBM_LEFT)
                            buttonState |= MouseButtonState::LeftButton;
                        if (event.buttons & DIBM_RIGHT)
                            buttonState |= MouseButtonState::RightButton;
                        if (event.buttons & DIBM_MIDDLE)
                            buttonState |= MouseButtonState::MiddleButton;
                        mouse->PutMouseEvent(mouseXDelta, mouseYDelta, mouseZDelta,
                                             buttonState);
                        break;
                    }
                    default:
                        break;
                }
            }
            // did we get any keyboard events?
            if (numKeyEvents > 0)
            {
                uint32_t codesStored;
                if (numKeyEvents > 1)
                {
                    keyboard->PutScancodes(numKeyEvents, keyEvents,
                                           &codesStored);
                } else
                {
                    keyboard->PutScancode(keyEvents[0]);
                }
            }
        }
        {
            nsCOMPtr<IProgress> progress;
            console->PowerDown(getter_AddRefs(progress));
            progress->WaitForCompletion(-1);
        }
    }

Leave:
    /*
     * Perform the standard XPCOM shutdown procedure.
     */
    NS_ShutdownXPCOM(nsnull);

    return 0;
}
コード例 #26
0
ファイル: mysql.cpp プロジェクト: Leveltlab/2Pimage
void mexFunction(int nlhs, mxArray *plhs[],
      int nrhs, const mxArray *prhs[])
{
	int cid=-1;  // Handle of the current connection (invalid until we identify)
	int jarg=0;  // Number of first string arg: becomes 1 if id is specified

	/*********************************************************************/
	// Parse the first argument to see if it is a specific database handle
	if ( nrhs>0 && mxIsNumeric(prhs[0]) )
		{ if ( mxGetM(prhs[0])!=1 || mxGetN(prhs[0])!=1 )
			{ showusage();
			  mexPrintf("First argument is array %d x %d, but it should be a scalar\n",
			      mxGetM(prhs[0]),mxGetN(prhs[0]) );
			  mexErrMsgTxt("Invalid connection handle"); }
		  double xid = *mxGetPr(prhs[0]);
		  cid = int(xid);
		  if ( double(cid)!=xid || cid<0 || cid>=MAXCONN )
			{ showusage();
			  mexPrintf("dbHandle = %g -- Must be integer between 0 and %d\n",
			      xid,MAXCONN-1);
			  mexErrMsgTxt("Invalid connection handle"); }
		  jarg = 1;
		  if (debug) mexPrintf("| Explicit  cid = %d\n",cid); }

	/*********************************************************************/
	//  Check that the remaining arguments are all character strings
	{ for ( int j=jarg ; j<nrhs ; j++ )
		{ if (!mxIsChar(prhs[j]))
			{ showusage();
			  mexErrMsgTxt("All args must be strings, except dbHandle"); }}}

	/*********************************************************************/
	//  Identify what action he wants to do

	enum querytype { OPEN, CLOSE, CLOSEALL, USENAMED, USE,
	                     STATUS, STATSALL, QUOTE, CMD } q;
	char *query = NULL;

	if (nrhs<=jarg)   q = STATSALL;
	else
		{ query = mxArrayToString(prhs[jarg]);
		  if (streq(query,"open"))          q = OPEN;
		  else if (streq(query,"close"))    q = CLOSE;
		  else if (streq(query,"closeall")) q = CLOSEALL;
		  else if (streq(query,"use"))      q = USENAMED;
		  else if (streq(query,"use",3))    q = USE;
		  else if (streq(query,"status"))   q = STATUS;
		  else if (streq(query,"quote"))    q = QUOTE;
		  else q = CMD; }

	if (debug)
		{ switch(q)
			{ case OPEN:     mexPrintf("| q = OPEN\n");     break;
			  case CLOSE:    mexPrintf("| q = CLOSE\n");    break;
			  case CLOSEALL: mexPrintf("| q = CLOSEALL\n"); break;
			  case USENAMED: mexPrintf("| q = USENAMED\n"); break;
			  case USE:      mexPrintf("| q = USE\n");      break;
			  case STATUS:   mexPrintf("| q = STATUS\n");   break;
			  case STATSALL: mexPrintf("| q = STATSALL\n"); break;
			  case QUOTE:    mexPrintf("| q = QUOTE\n");    break;
			  case CMD:      mexPrintf("| q = CMD\n");      break;
			                 mexPrintf("| q = ??\n");              }}

	/*********************************************************************/
	//  If he did not specify the handle, choose the appropriate one
	//  If there are no previous connections, then we will still have
	//     cid=-1, and this will be handled in the appropriate place.
	if (jarg==0)
		{
		if (q==OPEN)
			{ for ( cid=0 ; cid<MAXCONN & c[cid].isopen ; cid++ );
			  if (cid>=MAXCONN) mexErrMsgTxt("Can\'t find free handle"); }
		else if (ncid>0)
			cid=prevcid[ncid-1];
		}

	if (debug) mexPrintf("| cid = %d\n",cid);

	//  Shorthand notation so we don't need to write c[cid]...
	//  These values must not be used if  cid<0
	mp dummyconn;     mp &conn = (cid>=0) ? c[cid].conn : dummyconn;
	bool dummyisopen; bool &isopen = (cid>=0) ? c[cid].isopen : dummyisopen;

	if (q==OPEN)
		{
		if (cid<0)
			{ mexPrintf("cid = %d !\n",cid);
			  mexErrMsgTxt("Internal code error\n"); }
		//  Close connection if it is open
		if (isopen)
			{ mexWarnMsgIdAndTxt("mysql:ConnectionAlreadyOpen",
			    "Connection %d has been closed and overwritten",cid);
			  mysql_close(conn);
			  conn=NULL;  isopen=false;  stackdelete(cid); }

		//  Extract information from input arguments
		char *host=NULL;   if (nrhs>=jarg+2)  host = mxArrayToString(prhs[jarg+1]);
		char *user=NULL;   if (nrhs>=jarg+3)  user = mxArrayToString(prhs[jarg+2]);
		char *pass=NULL;   if (nrhs>=jarg+4)  pass = mxArrayToString(prhs[jarg+3]);
		int port = hostport(host);  // returns zero if there is no port

		if (nlhs<1)
			{ mexPrintf("Connecting to  host=%s", (host) ? host : "localhost" );
			  if (port) mexPrintf("  port=%d",port);
			  if (user) mexPrintf("  user=%s",user);
			  if (pass) mexPrintf("  password=%s",pass);
			  mexPrintf("\n"); }

		//  Establish and test the connection
		//  If this fails, then conn is still set, but isopen stays false
		if (!(conn=mysql_init(conn)))
			mexErrMsgTxt("Couldn\'t initialize MySQL connection object");
		if (!mysql_real_connect( conn, host, user, pass, NULL,port,NULL,0 ))
			mexErrMsgTxt(mysql_error(conn));
		const char *c=mysql_stat(conn);
		if (c)  { if (nlhs<1) mexPrintf("%s\n",c); }
		else    mexErrMsgTxt(mysql_error(conn));

		isopen=true;
		ncid++;
		if (ncid>MAXCONN)
			{ mexPrintf("ncid = %d ?\n",ncid);
			  mexErrMsgTxt("Internal logic error\n"); }
		prevcid[ncid-1] = cid;

		if (debug) stackprint();

		//  Now we are OK -- return the connection handle opened.
		setScalarReturn(nlhs,plhs,cid);
		}

	else if (q==CLOSE)
		{
		if ( cid>=0 && isopen )
			{ if (debug) mexPrintf("| Closing %d\n",cid);
			  mysql_close(conn);
			  conn = NULL; isopen=false;  stackdelete(cid); }
		if (debug) stackprint();
		}

	else if (q==CLOSEALL)
		{ while (ncid>0)
			{ if (debug) stackprint();
			  cid = prevcid[ncid-1];
			  if (debug) mexPrintf("| Closing %d\n",cid);
			  if (!(c[cid].isopen))
				{ mexPrintf("Connection %d is not marked open!\n",cid);
				  mexErrMsgTxt("Internal logic error"); }
			  mysql_close(c[cid].conn);
			  c[cid].conn=NULL;  c[cid].isopen=false;  ncid--; }}

	else if ( q==USE || q==USENAMED )
		{
		if ( cid<0 || !isopen ) mexErrMsgTxt("Not connected");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexPrintf(mysql_error(conn));
			  mexPrintf("\nClosing connection %d\n",cid);
			  mexErrMsgTxt("Use command failed"); }
		char *db=NULL;
		if (q==USENAMED)
			{ if (nrhs>=2) db=mxArrayToString(prhs[jarg+1]);
			  else         mexErrMsgTxt("Must specify a database to use"); }
		else
			{ db = query + 3;
			  while ( *db==' ' || *db=='\t' ) db++; }
		if (mysql_select_db(conn,db))  mexErrMsgTxt(mysql_error(conn));
		if (nlhs<1) mexPrintf("Current database is \"%s\"\n",db); 
		else        setScalarReturn(nlhs,plhs,1.);
		}

	else if (q==STATUS)
		{
		if (nlhs<1)  //  He wants a report
			{ // print connection handle only if multiple connections
			  char idstr[10];  idstr[0]=0;
			  if ( cid>=0 && ncid>1 )  sprintf(idstr,"(%d) ",cid);
			  if ( cid<0 || !isopen )
			   { mexPrintf("%sNot connected\n",idstr,cid);  return; }
			  if (mysql_ping(conn))
				{ mexErrMsgTxt(mysql_error(conn)); }
			  mexPrintf("%s%-30s   Server version %s\n",
			    idstr, mysql_get_host_info(conn), mysql_get_server_info(conn) ); }
		else         //  He wants a return value for this connection
			{ double *pr=setScalarReturn(nlhs,plhs,0.);
			  if ( cid<0 || !isopen ) { *pr=1.; return; }
			  if (mysql_ping(conn))   { *pr=2.; return; }}
		}

	else if (q==STATSALL)
		{
		if (debug) stackprint();
		if (ncid==0)      mexPrintf("No connections open\n");
		else if (ncid==1) mexPrintf("1 connection open\n");
		else              mexPrintf("%d connections open\n",ncid);
		for ( int j=0 ; j<ncid ; j++ )
			{ cid = prevcid[j];
			  if (mysql_ping(c[cid].conn))
				  mexPrintf("%2d:  %s\n",cid,mysql_error(conn));
			  else
				  mexPrintf("%2d:  %-30s   Server version %s\n",
				        cid, mysql_get_host_info(c[cid].conn),
				        mysql_get_server_info(c[cid].conn) ); }
		}

	// Quote the second string argument and return it (Chris Rodgers)
	else if (q==QUOTE)
		{
		if ((nrhs-jarg)!=2)
			mexErrMsgTxt("mysql('quote','string_to_quote') takes two string arguments!");

		//  Check that we have a valid connection
		if ( cid<0 || !isopen ) mexErrMsgTxt("No connection open");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexErrMsgTxt(mysql_error(conn)); }

		const mxArray *a = prhs[jarg+1];
		int llen = mxGetM(a)*mxGetN(a)*sizeof(mxChar);
		char *from = (char *) mxCalloc(llen+1,sizeof(char));
		if (mxGetString(a,from,llen)) mexErrMsgTxt("Can\'t copy string");
		int l = strlen(from);

		/* Allocate memory for input and output strings. */
		char *to = (char*) mxCalloc( llen*2+3, sizeof(char));

		/* Call the C subroutine. */
		to[0] = '\'';
		int n = mysql_real_escape_string( conn, to+1, from, l );
		to[n+1] = '\'';

		/* Set C-style string output_buf to MATLAB mexFunction output*/
		plhs[0] = mxCreateString(to);

		mxFree(from);  mxFree(to);  // just in case Matlab forgets
		}

	else if (q==CMD)
		{
		//  Check that we have a valid connection
		if ( cid<0 || !isopen ) mexErrMsgTxt("No connection open");
		if (mysql_ping(conn))
			{ stackdelete(cid);  isopen=false;
			  mexPrintf(mysql_error(conn));
			  mexPrintf("Closing connection %d\n",cid);
			  mexErrMsgTxt("Query failed"); }

		//  Execute the query (data stays on server)
		if (mysql_query(conn,query))  mexErrMsgTxt(mysql_error(conn));

		//  Download the data from server into our memory
		//     We need to be careful to deallocate res before returning.
		//  Matlab's allocation routines return instantly if there is not
		//  enough free space, without giving us time to dealloc res.
		//  This is a potential memory leak but I don't see how to fix it.
		MYSQL_RES *res = mysql_store_result(conn);

		//  As recommended in Paul DuBois' MySQL book (New Riders, 1999):
		//  A NULL result set after the query can indicate either
		//    (1) the query was an INSERT, DELETE, REPLACE, or UPDATE, that
		//        affect rows in the table but do not return a result set; or
		//    (2) an error, if the query was a SELECT, SHOW, or EXPLAIN
		//        that should return a result set but didn't.
		//  Distinguish between the two by checking mysql_field_count()
		//  We return in either case, either correctly or with an error
		if (!res)
			{
			if (!mysql_field_count(conn))
				{ unsigned long nrows=mysql_affected_rows(conn);
				  if (nlhs<1)
					{ mexPrintf("%u rows affected\n",nrows);
					  return; }
				  else
					{ setScalarReturn(nlhs,plhs,nrows);
					  return; }}
			else
				  mexErrMsgTxt(mysql_error(conn));
			}

		unsigned long nrow=mysql_num_rows(res), nfield=mysql_num_fields(res);

		//  If he didn't ask for any output (nlhs=0),
		//       then display the output and return
		if ( nlhs<1 )
			{ fancyprint(res);
			  mysql_free_result(res);
			  return; }

		//  If we are here, he wants output
		//  He must give exactly the right number of output arguments
// 		if ( nlhs != nfield )
// 			{ mysql_free_result(res);
// 			  mexPrintf("You specified %d output arguments, "
// 			         "and got %d columns of data\n",nlhs,nfield);
// 			  mexErrMsgTxt("Must give one output argument for each column"); }
        
        if(nlhs > 1) mexErrMsgIdAndTxt( "MYSQL query: ",
                        "Too many output arguments.");

		//  Fix the column types to fix MySQL C API sloppiness
		MYSQL_FIELD *f = mysql_fetch_fields(res);
		fix_types( f, res );

		//  Create the Matlab arrays for output
// 		double **pr = (double **) mxMalloc( nfield * sizeof(double *) );
// 		{ for ( int j=0 ; j<nfield ; j++ )
// 			{ if ( can_convert(f[j].type) )
// 				{ if (!( plhs[j] = mxCreateDoubleMatrix( nrow, 1, mxREAL ) ))
// 					{ mysql_free_result(res);
// 					  mexErrMsgTxt("Unable to create numeric matrix for output"); }
// 				  pr[j] = mxGetPr(plhs[j]); }
// 			  else
// 				{ if (!( plhs[j] = mxCreateCellMatrix( nrow, 1 ) ))
// 					{ mysql_free_result(res);
// 					  mexErrMsgTxt("Unable to create cell matrix for output"); }
// 				  pr[j] = NULL; }}}
        
         if (!( plhs[0] = mxCreateCellMatrix( nrow, nfield ) )){
					 mysql_free_result(res);
                     mexErrMsgTxt("Unable to create cell matrix for output");                 
         }

		//  Load the data into the cells
		mysql_data_seek(res,0);
		for ( int i=0 ; i<nrow ; i++ ){ 
			  MYSQL_ROW row = mysql_fetch_row(res);
			  if (!row) { 
				mexPrintf("Scanning row %d for data extraction\n",i+1);
				  mexErrMsgTxt("Internal error:  Failed to get a row"); }
// 			  for ( int j=0 ; j<nfield ; j++ ){ 
//                   if (can_convert(f[j].type)) { 
// 					pr[j][i] = field2num(row[j],f[j].type); 
//                   }
// 				  else {
// 					 mxArray *c = mxCreateString(row[j]);
// 					  mxSetCell(plhs[j],i,c); 
//                   }
//               }
             for ( int j=0 ; j <nfield ; j++ ){
                 mxArray *c = mxCreateString(row[j]);
 					  mxSetCell(plhs[0],j*nrow + i,c); 
             }
        }
		mysql_free_result(res);
		}
	else
		{ mexPrintf("Unknown query type q = %d\n",q);
		  mexErrMsgTxt("Internal code error"); }
}
コード例 #27
0
ファイル: tacc.c プロジェクト: jeroennijhof/pam_tacplus
int main(int argc, char **argv) {
    char *pass = NULL;
    char *tty = NULL;
    char *command = NULL;
    char *remote_addr = NULL;
    char *service = NULL;
    char *protocol = NULL;
    struct addrinfo *tac_server;
    char *tac_server_name = NULL;
    char *tac_secret = NULL;
    int tac_fd;
    short int task_id = 0;
    char buf[40];
    int ret;
#ifndef USE_SYSTEM
    pid_t pid;
#endif
    struct areply arep;

    /* options */
    flag log_wtmp = 1;
    flag do_author = 0;
    flag do_authen = 0;
    flag do_account = 0;
    flag login_mode = 0;

    /* check argc */
    if (argc < 2) {
        showusage(argv[0]);
        exit(EXIT_ERR);
    }

    /* check for login mode */
    if (argc == 2 && isalpha(*argv[1])) {
        g_user = argv[1];
        do_author = do_authen = do_account = 1;
        command = DEFAULT_COMMAND;
        login_mode = 1;
    } else {
        int c;
        int opt_index;

        while ((c = getopt_long(argc, argv, opt_string, long_options,
                                &opt_index)) != EOF) {
            switch (c) {
                case 'T':
                    do_authen = 1;
                    break;
                case 'R':
                    do_author = 1;
                    break;
                case 'A':
                    do_account = 1;
                    break;
                case 'V':
                    showversion(argv[0]);
                    /*NOTREACHED*/
                    break;
                case 'h':
                    showusage(argv[0]);
                    /*NOTREACHED*/
                    break;
                case 'u':
                    g_user = optarg;
                    break;
                case 'r':
                    remote_addr = optarg;
                    break;
                case 'L':
                    // tac_login is a global variable initialized in libtac
                    xstrcpy(tac_login, optarg, sizeof(tac_login));
                    break;
                case 'p':
                    pass = optarg;
                    break;
                case 's':
                    tac_server_name = optarg;
                    break;
                case 'k':
                    tac_secret = optarg;
                    break;
                case 'c':
                    command = optarg;
                    break;
                case 'S':
                    service = optarg;
                    break;
                case 'P':
                    protocol = optarg;
                    break;
                case 'q':
                    quiet = 1;
                    break;
                case 'w':
                    log_wtmp = 0;
                    break;
                case 'n':
                    tac_encryption = 0;
                    break;
                case 'y':
                    tty = optarg;
                    break;
            }
        }
    }

    /* check available information and set to defaults if needed */
    if (do_authen + do_author + do_account == 0) {
        printf("error: one of -TRAVh options is required\n");
        exit(EXIT_ERR);
    }

    if (g_user == NULL) {
        printf("error: username is required.\n");
        exit(EXIT_ERR);
    }

    if (remote_addr == NULL) {
        printf("error: remote address is required.\n");
        exit(EXIT_ERR);
    }

    if (service == NULL) {
        printf("error: service is required.\n");
        exit(EXIT_ERR);
    }

    if (protocol == NULL) {
        printf("error: protocol is required.\n");
        exit(EXIT_ERR);
    }

    if (tac_server_name == NULL) {
        printf("error: server name is required.\n");
        exit(EXIT_ERR);
    }

    struct addrinfo hints;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    ret = getaddrinfo(tac_server_name, "tacacs", &hints, &tac_server);
    if (ret != 0) {
        printf("error: resolving name %s: %s", tac_server_name,
               gai_strerror(ret));
        exit(EXIT_ERR);
    }

    if (tac_secret == NULL) {
        printf("error: server secret is required.\n");
        exit(EXIT_ERR);
    }

    if (pass == NULL) {
        signal(SIGALRM, timeout_handler);
        alarm(GETPASS_TIMEOUT);
        pass = getpass(PASSWORD_PROMPT);
        alarm(0);
        signal(SIGALRM, SIG_DFL);
        if (!strlen(pass))
            exit(EXIT_ERR);
    }

    if (tty == NULL) {
        printf("error: tty name is required.\n");
        exit(EXIT_ERR);
    }

    /* open syslog before any TACACS+ calls */
    openlog("tacc", LOG_CONS | LOG_PID, LOG_AUTHPRIV);

    if (do_authen)
        authenticate(tac_server, tac_secret, g_user, pass, tty, remote_addr);

    if (do_author) {
        /* authorize user */
        struct tac_attrib *attr = NULL;
        tac_add_attrib(&attr, "service", service);
        tac_add_attrib(&attr, "protocol", protocol);

        tac_fd = tac_connect_single(tac_server, tac_secret, NULL, 60);
        if (tac_fd < 0) {
            if (!quiet)
                printf("Error connecting to TACACS+ server: %m\n");
            exit(EXIT_ERR);
        }

        tac_author_send(tac_fd, g_user, tty, remote_addr, attr);

        tac_author_read(tac_fd, &arep);
        if (arep.status != AUTHOR_STATUS_PASS_ADD
            && arep.status != AUTHOR_STATUS_PASS_REPL) {
            if (!quiet)
                printf("Authorization FAILED: %s\n", arep.msg);
            exit(EXIT_FAIL);
        } else {
            if (!quiet)
                printf("Authorization OK: %s\n", arep.msg);
        }

        tac_free_attrib(&attr);
    }

    /* we no longer need the password in our address space */
    bzero(pass, strlen(pass));
    pass = NULL;

    if (do_account) {
        /* start accounting */
        struct tac_attrib *attr = NULL;

        sprintf(buf, "%lu", time(0));
        tac_add_attrib(&attr, "start_time", buf);

        // this is not crypto but merely an identifier
        long rnd_id = random();
        memcpy(&task_id, &rnd_id, sizeof(task_id));

        sprintf(buf, "%hu", task_id);
        tac_add_attrib(&attr, "task_id", buf);
        tac_add_attrib(&attr, "service", service);
        tac_add_attrib(&attr, "protocol", protocol);

        tac_fd = tac_connect_single(tac_server, tac_secret, NULL, 60);
        if (tac_fd < 0) {
            if (!quiet)
                printf("Error connecting to TACACS+ server: %m\n");
            exit(EXIT_ERR);
        }

        tac_acct_send(tac_fd, TAC_PLUS_ACCT_FLAG_START, g_user, tty, remote_addr,
                      attr);

        ret = tac_acct_read(tac_fd, &arep);
        if (ret == 0) {
            if (!quiet)
                printf("Accounting: START failed: %s\n", arep.msg);
            syslog(LOG_INFO, "TACACS+ accounting start failed: %s", arep.msg);
        } else if (!login_mode && !quiet)
            printf("Accounting: START OK\n");

        close(tac_fd);

        tac_free_attrib(&attr);

    }

    /* log in local utmp */
    if (log_wtmp) {
#if defined(HAVE_PUTUTXLINE)
        struct timeval tv;

        gettimeofday(&tv, NULL);

        memset(&utmpx, 0, sizeof(utmpx));
        utmpx.ut_type = USER_PROCESS;
        utmpx.ut_pid = getpid();
        xstrcpy(utmpx.ut_line, tty, sizeof(utmpx.ut_line));
        strncpy(utmpx.ut_id, tty + C_STRLEN("tty"), sizeof(utmpx.ut_id));
        xstrcpy(utmpx.ut_host, "dialup", sizeof(utmpx.ut_host));
        utmpx.ut_tv.tv_sec = tv.tv_sec;
        utmpx.ut_tv.tv_usec = tv.tv_usec;
        xstrcpy(utmpx.ut_user, g_user, sizeof(utmpx.ut_user));
        /* ut_addr unused ... */
        setutxent();
        pututxline(&utmpx);
#elif defined(HAVE_LOGWTMP)
        logwtmp(tty, g_user, "dialup");
#endif
    }

    if (command != NULL) {
        int ret;

        syslog(LOG_DEBUG, "starting %s for %s", command, g_user);

        signal(SIGHUP, SIG_IGN);
        signal(SIGTERM, SIG_IGN);
        signal(SIGINT, SIG_IGN);
        signal(SIGCHLD, SIG_IGN);

#ifdef COMMAND_MESSAGE
        printf(COMMAND_MESSAGE);
#endif

#if USE_SYSTEM
        ret = system(command);
        if (ret < 0)
            syslog(LOG_WARNING, "command failed: %m");
        else
            syslog(LOG_NOTICE, "command exit code %u", ret);
#else
        pid=fork();

        if(pid == 0) {
            /* child */

            execl(DEFAULT_COMMAND, DEFAULT_COMMAND, ARGS, NULL);
            syslog(LOG_ERR, "execl() failed: %m");
            _exit(EXIT_FAIL);
        }

        if(pid < 0) {
            /* error */
            syslog(LOG_ERR, "fork failed: %m");
            exit(EXIT_FAIL);
        }

        if(pid > 0) {
            /* parent */
            int st, r;

            r=wait(&st);
        }
#endif
    }

    if (do_account) {
        /* stop accounting */
        struct tac_attrib *attr = NULL;
        sprintf(buf, "%lu", time(0));
        tac_add_attrib(&attr, "stop_time", buf);
        sprintf(buf, "%hu", task_id);
        tac_add_attrib(&attr, "task_id", buf);

        tac_fd = tac_connect_single(tac_server, tac_secret, NULL, 60);
        if (tac_fd < 0) {
            if (!quiet)
                printf("Error connecting to TACACS+ server: %m\n");
            exit(EXIT_ERR);
        }

        tac_acct_send(tac_fd, TAC_PLUS_ACCT_FLAG_STOP, g_user, tty, remote_addr,
                      attr);
        ret = tac_acct_read(tac_fd, &arep);
        if (ret == 0) {
            if (!quiet)
                printf("Accounting: STOP failed: %s", arep.msg);
            syslog(LOG_INFO, "TACACS+ accounting stop failed: %s\n", arep.msg);
        } else if (!login_mode && !quiet)
            printf("Accounting: STOP OK\n");

        close(tac_fd);

        tac_free_attrib(&attr);
    }

    /* logout from utmp */
    if (log_wtmp) {
#if defined(HAVE_PUTUTXLINE)
        utmpx.ut_type = DEAD_PROCESS;
        memset(utmpx.ut_line, 0, sizeof(utmpx.ut_line));
        memset(utmpx.ut_user, 0, sizeof(utmpx.ut_user));
        memset(utmpx.ut_host, 0, sizeof(utmpx.ut_host));
        utmpx.ut_tv.tv_sec = utmpx.ut_tv.tv_usec = 0;
        setutxent();
        pututxline(&utmpx);
#elif defined(HAVE_LOGWTMP)
        logwtmp(tty, "", "");
#endif
    }

    exit(EXIT_OK);
}