예제 #1
0
int
main (int argc, char **argv)
{

       int rows, cols;
       struct termios tio;
       char buf[BUFSIZ];
       struct winsize ws;
       char *name_of_tty;

       myname = x_basename(argv[0]);

       if (argc > 1) Usage();

       name_of_tty = "/dev/tty";

       if ((ttyfp = fopen (name_of_tty, "r+")) == NULL) {
           fprintf (stderr, "%s:  can't open terminal %s\n",
                    myname, name_of_tty);
           exit (1);
       }
       tty = fileno(ttyfp);

       tcgetattr(tty, &tioorig);
       tio = tioorig;
       tio.c_iflag &= ~ICRNL;
       tio.c_lflag &= ~(ICANON | ECHO);
       tio.c_cflag |= CS8;
       tio.c_cc[VMIN] = 6;
       tio.c_cc[VTIME] = 1;
       signal(SIGINT, onintr);
       signal(SIGQUIT, onintr);
       signal(SIGTERM, onintr);
       tcsetattr(tty, TCSADRAIN, &tio);

       write(tty, getsize, strlen(getsize));
       readstring(ttyfp, buf, size);
       if(sscanf (buf, size, &rows, &cols) != 2) {
               fprintf(stderr, "%s: Can't get rows and columns\r\n", myname);
               onintr(0);
       }
       write(tty, restore, strlen(restore));

       if (ioctl (tty, TIOCGWINSZ, &ws) != -1) {
           /* we don't have any way of directly finding out
              the current height & width of the window in pixels.  We try
              our best by computing the font height and width from the "old"
              struct winsize values, and multiplying by these ratios...*/
           if (ws.ws_col != 0)
               ws.ws_xpixel = cols * (ws.ws_xpixel / ws.ws_col);
           if (ws.ws_row != 0)
               ws.ws_ypixel = rows * (ws.ws_ypixel / ws.ws_row);
           ws.ws_row = rows;
           ws.ws_col = cols;
           ioctl (tty, TIOCSWINSZ, &ws);
       }

       tcsetattr(tty, TCSADRAIN, &tioorig);
       signal(SIGINT, SIG_DFL);
       signal(SIGQUIT, SIG_DFL);
       signal(SIGTERM, SIG_DFL);

       exit(0);
}
예제 #2
0
int main(int argc, char* argv[])
{
    int i;
    int nThreads = CPLGetNumCPUs();
    std::vector<CPLJoinableThread*> apsThreads;
    Strategy eStrategy = STRATEGY_RANDOM;
    int bNewDatasetOption = FALSE;
    int nXSize = 5000;
    int nYSize = 5000;
    int nBands = 4;
    char** papszOptions = NULL;
    int bOnDisk = FALSE;
    std::vector<ThreadDescription> asThreadDescription;
    int bMemDriver = FALSE;
    GDALDataset* poMEMDS = NULL;
    int bMigrate = FALSE;
    int nMaxRequests = -1;

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );

    GDALAllRegister();

    for(i = 1; i < argc; i++)
    {
        if( EQUAL(argv[i], "-threads") && i + 1 < argc)
        {
            i ++;
            nThreads = atoi(argv[i]);
        }
        else if( EQUAL(argv[i], "-loops") && i + 1 < argc)
        {
            i ++;
            nLoops = atoi(argv[i]);
            if( nLoops <= 0 )
                nLoops = INT_MAX;
        }
        else if( EQUAL(argv[i], "-max_requests") && i + 1 < argc)
        {
            i ++;
            nMaxRequests = atoi(argv[i]);
        }
        else if( EQUAL(argv[i], "-strategy") && i + 1 < argc)
        {
            i ++;
            if( EQUAL(argv[i], "random") )
                eStrategy = STRATEGY_RANDOM;
            else if( EQUAL(argv[i], "line") )
                eStrategy = STRATEGY_LINE;
            else if( EQUAL(argv[i], "block") )
                eStrategy = STRATEGY_BLOCK;
            else
                Usage();
        }
        else if( EQUAL(argv[i], "-xsize") && i + 1 < argc)
        {
            i ++;
            nXSize = atoi(argv[i]);
            bNewDatasetOption = TRUE;
        }
        else if( EQUAL(argv[i], "-ysize") && i + 1 < argc)
        {
            i ++;
            nYSize = atoi(argv[i]);
            bNewDatasetOption = TRUE;
        }
        else if( EQUAL(argv[i], "-bands") && i + 1 < argc)
        {
            i ++;
            nBands = atoi(argv[i]);
            bNewDatasetOption = TRUE;
        }
        else if( EQUAL(argv[i], "-co") && i + 1 < argc)
        {
            i ++;
            papszOptions = CSLAddString(papszOptions, argv[i]);
            bNewDatasetOption = TRUE;
        }
        else if( EQUAL(argv[i], "-ondisk"))
        {
            bOnDisk = TRUE;
            bNewDatasetOption = TRUE;
        }
        else if( EQUAL(argv[i], "-check"))
        {
            bCheck = TRUE;
            bNewDatasetOption = TRUE;
        }
        else if( EQUAL(argv[i], "-memdriver"))
        {
            bMemDriver = TRUE;
            bNewDatasetOption = TRUE;
        }
        else if( EQUAL(argv[i], "-migrate"))
            bMigrate = TRUE;
        else if( argv[i][0] == '-' )
            Usage();
        else if( pszDataset == NULL )
            pszDataset = argv[i];
        else
        {
            Usage();
        }
    }

    if( pszDataset != NULL && bNewDatasetOption )
        Usage();

    CPLDebug("TEST", "Using %d threads", nThreads);

    int bCreatedDataset = FALSE;
    if( pszDataset == NULL )
    {
        bCreatedDataset = TRUE;
        if( bOnDisk )
            pszDataset = "/tmp/tmp.tif";
        else
            pszDataset = "/vsimem/tmp.tif";
        GDALDataset* poDS = ((GDALDriver*)GDALGetDriverByName((bMemDriver) ? "MEM" : "GTiff"))->Create(pszDataset,
                            nXSize, nYSize, nBands, GDT_Byte, papszOptions);
        if( bCheck )
        {
            GByte* pabyLine = (GByte*) VSIMalloc(nBands * nXSize);
            for(int iY=0; iY<nYSize; iY++)
            {
                for(int iX=0; iX<nXSize; iX++)
                {
                    for(int iBand=0; iBand<nBands; iBand++)
                    {
                        unsigned long seed = iBand * nXSize * nYSize + iY * nXSize + iX;
                        pabyLine[iBand * nXSize + iX] = (GByte)(myrand_r(&seed) & 0xff);
                    }
                }
                poDS->RasterIO(GF_Write, 0, iY, nXSize, 1,
                               pabyLine, nXSize, 1,
                               GDT_Byte,
                               nBands, NULL,
                               0, 0, 0
#ifdef GDAL_COMPILATION
                               , NULL
#endif
                              );
            }
            VSIFree(pabyLine);
        }
        if( bMemDriver )
            poMEMDS = poDS;
        else
            GDALClose(poDS);
    }
    else
    {
        bCheck = FALSE;
    }
    CSLDestroy(papszOptions);
    papszOptions = NULL;

    Request* psGlobalRequestLast = NULL;

    for(i = 0; i < nThreads; i++ )
    {
        GDALDataset* poDS;
        // Since GDAL 2.0, the MEM driver is thread-safe, i.e. does not use the block
        // cache, but only for operations not involving resampling, which is
        // the case here
        if( poMEMDS )
            poDS = poMEMDS;
        else
        {
            poDS = (GDALDataset*)GDALOpen(pszDataset, GA_ReadOnly);
            if( poDS == NULL )
                exit(1);
        }
        if( bMigrate )
        {
            Resource* psResource = (Resource*)CPLMalloc(sizeof(Resource));
            psResource->poDS = poDS;
            int nBufferSize;
            if( eStrategy == STRATEGY_RANDOM )
                nBufferSize = CreateRandomStrategyRequests(
                                  poDS, nMaxRequests, psGlobalRequestList, psGlobalRequestLast);
            else if( eStrategy == STRATEGY_LINE )
                nBufferSize = CreateLineStrategyRequests(
                                  poDS, nMaxRequests, psGlobalRequestList, psGlobalRequestLast);
            else
                nBufferSize = CreateBlockStrategyRequests(
                                  poDS, nMaxRequests, psGlobalRequestList, psGlobalRequestLast);
            psResource->pBuffer = CPLMalloc(nBufferSize);
            PutResourceAtEnd(psResource);
        }
        else
        {
            ThreadDescription sThreadDescription;
            sThreadDescription.poDS = poDS;
            sThreadDescription.psRequestList = NULL;
            Request* psRequestLast = NULL;
            if( eStrategy == STRATEGY_RANDOM )
                sThreadDescription.nBufferSize = CreateRandomStrategyRequests(
                                                     poDS, nMaxRequests, sThreadDescription.psRequestList, psRequestLast);
            else if( eStrategy == STRATEGY_LINE )
                sThreadDescription.nBufferSize = CreateLineStrategyRequests(
                                                     poDS, nMaxRequests, sThreadDescription.psRequestList, psRequestLast);
            else
                sThreadDescription.nBufferSize = CreateBlockStrategyRequests(
                                                     poDS, nMaxRequests, sThreadDescription.psRequestList, psRequestLast);
            asThreadDescription.push_back(sThreadDescription);
        }
    }

    if( bCreatedDataset && poMEMDS == NULL && bOnDisk )
    {
        CPLPushErrorHandler(CPLQuietErrorHandler);
        VSIUnlink(pszDataset);
        CPLPopErrorHandler();
    }

    if( bMigrate )
    {
        psLock = CPLCreateLock(LOCK_SPIN);
    }

    for(i = 0; i < nThreads; i++ )
    {
        CPLJoinableThread* pThread;
        if( bMigrate )
            pThread = CPLCreateJoinableThread(ThreadFuncWithMigration, NULL);
        else
            pThread = CPLCreateJoinableThread(ThreadFuncDedicatedDataset,
                                              &(asThreadDescription[i]));
        apsThreads.push_back(pThread);
    }
    for(i = 0; i < nThreads; i++ )
    {
        CPLJoinThread(apsThreads[i]);
        if( !bMigrate && poMEMDS == NULL )
            GDALClose(asThreadDescription[i].poDS);
    }
    while( psGlobalResourceList != NULL )
    {
        CPLFree( psGlobalResourceList->pBuffer);
        if( poMEMDS == NULL )
            GDALClose(psGlobalResourceList->poDS);
        Resource* psNext = psGlobalResourceList->psNext;
        CPLFree( psGlobalResourceList );
        psGlobalResourceList = psNext;
    }

    if( psLock )
    {
        CPLDestroyLock( psLock );
    }

    if( bCreatedDataset && poMEMDS == NULL  )
    {
        CPLPushErrorHandler(CPLQuietErrorHandler);
        VSIUnlink(pszDataset);
        CPLPopErrorHandler();
    }
    if( poMEMDS )
        GDALClose(poMEMDS);

    assert( GDALGetCacheUsed64() == 0 );

    GDALDestroyDriverManager();
    CSLDestroy( argv );

    return 0;
}
예제 #3
0
	virtual int RunCommand(CSimpleOptA & opts) override
	{
		try
		{
		opts.Init(opts.FileCount(), opts.Files(), optionList, SO_O_NOERR | SO_O_USEALL | SO_O_ICASE);
		while (opts.Next())
		{
			if (opts.LastError() == SO_SUCCESS)
			{
				if (opts.OptionId() == OPT_HELP)
				{
					Usage();
					return 0;
				}
			}
			else
			{
				Usage();
				return 1;
			}
		}

		size_t count = GetAlgorithmCount();

		for (size_t i = 0; i < count; i++)
		{
			tscrypto::tsCryptoString name = GetAlgorithmNameByIndex(i);
			std::shared_ptr<Selftest> test = std::dynamic_pointer_cast<Selftest>(ConstructAlgorithmByIndex(i));
			std::shared_ptr<AlgorithmInfo> info = std::dynamic_pointer_cast<AlgorithmInfo>(test);


			if (!test)
			{
				printf("%-25s -> No self test published\n", name.c_str());
			}
			else 
			{
				tscrypto::tsCryptoString name(info->AlgorithmName());
				tscrypto::tsCryptoString oid(info->AlgorithmOID());
				tscrypto::tsCryptoString id;
				id << info->AlgorithmID();
				name.resize(35, ' ');
				oid.resize(27, ' ');
				id.resize(4, ' ');

				cout << name << " " << oid << "  " << id;

				if (test->runTests(true))
				{
					printf(" -> success\n");
				}
				else
				{
					printf(" -> FAILED\n");
				}
			}
		}
		}
		catch (...)
		{
			printf(" -> EXCEPTION\n");
		}
		return 0;
	}
예제 #4
0
static void Usage(int bShort = TRUE)
{
    Usage(NULL, bShort);
}
int main(int argc, char* argv[])
{
	char lpPipeName[50];
	char *lpBuffer = NULL;
	unsigned long ulSize = 0;

	BOOL bResult;
	DWORD dwWritten = 0, dwMode;
	HANDLE hPipe;

	Usage();

	printf("Starting...\n");

	if (argc != 3)
		goto Exit0;
	
	if (strlen(argv[1]) < 20)
	{
		sprintf(lpPipeName, "\\\\%s\\\\.\\pipe\\sql\\query", argv[1]);
	}
	else
	{
		printf("Error!server\n");
		goto Exit0;
	}

	ulSize= atol(argv[2]);

	lpBuffer = (char*)malloc(ulSize + 2);
	if (NULL == lpBuffer)
	{
		printf("malloc error!\n");
		goto Exit0;
	}

	memset(lpBuffer, 0, ulSize + 2);
	memset(lpBuffer, 'A', ulSize);
	*lpBuffer = '\x12';
	*(lpBuffer + 1) = '\x01';
	*(lpBuffer + 2) = '\x00';
	
	printf("Connecting Server...\n");

	hPipe = CreateFile(lpPipeName, 
					GENERIC_READ | GENERIC_WRITE,
					0,
					NULL,
					OPEN_EXISTING,
					0,
					NULL);
	if (INVALID_HANDLE_VALUE == hPipe)
	{
		printf("Error!Connect server!%d\n", GetLastError());
		goto Exit0;
	}

   dwMode = PIPE_READMODE_MESSAGE; 
   bResult = SetNamedPipeHandleState( 
      hPipe,    // pipe handle 
      &dwMode,  // new pipe mode 
      NULL,     // don't set maximum bytes 
      NULL);    // don't set maximum time 
   if (!bResult)
   {
		printf("Error!SetNamedPipeHandleState.%d\n", GetLastError());
		goto Exit0;
   }

	bResult = WriteFile(hPipe, lpBuffer, ulSize + 1, &dwWritten, NULL);

	if (!bResult)
	{
		printf("\n\tError!WriteFile.%d\n\n", GetLastError());
		printf("When see the error message, the target may be crashed!!\n\n");
		goto Exit0;
	}

Exit0:
	
	return 0;
}
예제 #6
0
int
main(int argc, char* argv[])
{

  void **parameters;

  char* JobHistoryFileName=NULL;

  int i;
  parameters = (void **) malloc(NUM_PARAMETERS * sizeof(void *));
  myDistro->Init( argc, argv );

  config();
  Termlog = 1;
  dprintf_config("TOOL", get_param_functions());

  for(i=1; i<argc; i++) {

    if (strcmp(argv[i],"-f")==0) {
		if (i+1==argc || JobHistoryFileName) break;
		i++;
		JobHistoryFileName=argv[i];
    }
    else if (strcmp(argv[i],"-help")==0) {
		Usage(argv[0],0);
    }
    else if (strcmp(argv[i],"-name")==0) {
		if (i+1==argc || ScheddName) break;
		i++;
		ScheddName=strdup(argv[i]);
        if ((i+1==argc) || ScheddBirthdate) break;
        i++;
        ScheddBirthdate = atoi(argv[i]);
    }
/*    else if (strcmp(argv[i],"-debug")==0) {
          // dprintf to console
          Termlog = 1;
    }
*/
    else {
		Usage(argv[0]);
    }
  }
  if (i<argc) Usage(argv[0]);

  if (JobHistoryFileName == NULL) 
	  Usage(argv[0]);

  if ((ScheddName == NULL) || (ScheddBirthdate == 0)) {

    if (ScheddName) 
        fprintf(stdout, "You specified Schedd name without a Job Queue"
                        "Birthdate. Ignoring value %s\n", ScheddName);
        
    Daemon schedd( DT_SCHEDD, 0, 0 );

    if ( schedd.locate() ) {
        char *scheddname; 
        if( (scheddname = schedd.name()) ) {
            ScheddName = strdup(scheddname);
        } else {
            fprintf(stderr, "You did not specify a Schedd name and Job Queue "
                           "Birthdate on the command line "
                           "and there was an error getting the Schedd "
                           "name from the local Schedd Daemon Ad. Please "
                           "check that the SCHEDD_DAEMON_AD_FILE config "
                           "parameter is set and the file contains a valid "
                           "Schedd Daemon ad.\n");
            exit(1);
        }
        ClassAd *daemonAd = schedd.daemonAd();
        if(daemonAd) {
            if (!(daemonAd->LookupInteger( ATTR_JOB_QUEUE_BIRTHDATE, 
                        ScheddBirthdate) )) {
                // Can't find the job queue birthdate
                fprintf(stderr, "You did not specify a Schedd name and "
                           "Job Queue Birthdate on the command line "
                           "and there was an error getting the Job Queue "
                           "Birthdate from the local Schedd Daemon Ad. Please "
                           "check that the SCHEDD_DAEMON_AD_FILE config "
                           "parameter is set and the file contains a valid "
                           "Schedd Daemon ad.\n");
                exit(1);
            }
        }
    } else {

		fprintf(stderr, "You did not specify a Schedd name and Job Queue "
				        "Birthdate on the command line and there was "
				        "an error getting the Schedd Daemon Ad. Please "
				        "check that Condor is running and the SCHEDD_DAEMON_AD_FILE "
				        "config parameter is set and the file contains a valid "
				        "Schedd Daemon ad.\n");
		exit(1);
	}
  }

  doDBconfig();
  readHistoryFromFile(JobHistoryFileName);

  if(parameters) free(parameters);
  if(ScheddName) free(ScheddName);
  return 0;
}
예제 #7
0
ObitInfoList* TabCopyIn (int argc, char **argv, ObitErr *err)
/*----------------------------------------------------------------------- */
/*  Parse control info from command line                                  */
/*   Input:                                                               */
/*      argc   Number of arguments from command line                      */
/*      argv   Array of strings from command line                         */
/*   Output:                                                              */
/*      err    Obit Error stack                                           */
/*   return  ObitInfoList with defaults/parsed values                     */
/*----------------------------------------------------------------------- */
{
  olong ax;
  gchar *arg;
  gboolean init=FALSE;
  ObitInfoType type;
  gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
  gchar *strTemp;
  oint    itemp, i, j, k;
  ObitInfoList* list=NULL;
  gchar *routine = "TabCopyIn";

  /* error checks */
  g_assert(ObitErrIsA(err));
  if (err->error) return list;

  /* Make default inputs InfoList */
  list = defaultInputs(err);

  /* command line arguments */
  /* fprintf (stderr,"DEBUG arg %d %s\n",argc,argv[0]); DEBUG */
  if (argc<=1) Usage(); /* must have arguments */
  /* parse command line */
  for (ax=1; ax<argc; ax++) {

     /*fprintf (stderr,"DEBUG next arg %s %s\n",argv[ax],argv[ax+1]); DEBUG */
    arg = argv[ax];
    if (strcmp(arg, "-input") == 0){ /* input parameters */
      infile = argv[++ax];
      /* parse input file */
      ObitParserParse (infile, list, err);
      init = TRUE;

    } else if (strcmp(arg, "-output") == 0){ /* output results */
      outfile = argv[++ax];

    } else if (strcmp(arg, "-pgmNumber") == 0) { /*Program number */
      dim[0] = 1;
      itemp = strtol(argv[++ax], NULL, 0);
      ObitInfoListPut (list, "pgmNumber", OBIT_oint, dim, &itemp, err);
      
    } else if (strcmp(arg, "-AIPSuser") == 0) { /* AIPS user number */
      dim[0] = 1;
      itemp = strtol(argv[++ax], NULL, 0);
      ObitInfoListPut (list, "AIPSuser", OBIT_oint, dim, &itemp, err);
      
    } else if (strcmp(arg, "-inSeq") == 0) { /* AIPS sequence number */
      dim[0] = 1;
      itemp = strtol(argv[++ax], NULL, 0);
      ObitInfoListPut (list, "inSeq", OBIT_oint, dim, &itemp, err);
      
    } else if (strcmp(arg, "-inDisk") == 0) { /* input disk number */
      dim[0] = 1;
      itemp = strtol(argv[++ax], NULL, 0);
      ObitInfoListPut (list, "inDisk", OBIT_oint, dim, &itemp, err);
      
     } else if (strcmp(arg, "-DataType") == 0) { /* File type AIPS or FITS */
      strTemp = argv[++ax];
      dim[0] = strlen (strTemp);
      ObitInfoListAlwaysPut (list, "DataType", OBIT_string, dim, strTemp);
      
     } else if (strcmp(arg, "-inName") == 0) { /* AIPS inName*/
      strTemp = argv[++ax];
      dim[0] = strlen (strTemp);
      ObitInfoListAlwaysPut (list, "inName", OBIT_string, dim, strTemp);
      
     } else if (strcmp(arg, "-inClass") == 0) { /* AIPS inClass*/
      strTemp = argv[++ax];
      dim[0] = strlen (strTemp);
      ObitInfoListAlwaysPut (list, "inClass", OBIT_string, dim, strTemp);
      
     } else if (strcmp(arg, "-inFile") == 0) { /*inFile */
      strTemp = argv[++ax];
      dim[0] = strlen (strTemp);
      ObitInfoListAlwaysPut (list, "inFile", OBIT_string, dim, strTemp);
      
   } else { /* unknown argument */
      Usage();
    }
    if (err->error) Obit_traceback_val (err, routine, "GetInput", list);
  } /* end parsing input arguments */
  
  /* Read defaults if no file specified */
  if (!init) ObitParserParse (infile, list, err);

  /* Extract basic information to program globals */
  ObitInfoListGet(list, "pgmNumber", &type, dim, &pgmNumber, err);
  ObitInfoListGet(list, "AIPSuser",  &type, dim, &AIPSuser,  err);
  ObitInfoListGet(list, "nAIPS",     &type, dim, &nAIPS,     err);
  ObitInfoListGet(list, "nFITS",     &type, dim, &nFITS,     err);
  if (err->error) Obit_traceback_val (err, routine, "GetInput", list);

  /* Directories more complicated */
  ObitInfoListGetP(list, "AIPSdirs",  &type, dim, (gpointer)&strTemp);
  if (strTemp) {  /* Found? */
    AIPSdirs = g_malloc0(dim[1]*sizeof(gchar*));
    for (i=0; i<dim[1]; i++) {
      AIPSdirs[i] =  g_malloc0(dim[0]*sizeof(gchar));
      k = 0;
      for (j=0; j<dim[0]; j++) { /* Don't copy blanks */
	if (strTemp[j]!=' ') {AIPSdirs[i][k] = strTemp[j]; k++;}
      }
      AIPSdirs[i][k] = 0;
      strTemp += dim[0];
    }
  }

  ObitInfoListGetP(list, "FITSdirs",  &type, dim, (gpointer)&strTemp);
  if (strTemp)   {  /* Found? */
    FITSdirs = g_malloc0(dim[1]*sizeof(gchar*));
    for (i=0; i<dim[1]; i++) {
      FITSdirs[i] =  g_malloc0(dim[0]*sizeof(gchar));
      k = 0;
      for (j=0; j<dim[0]; j++) { /* Don't copy blanks */
	if (strTemp[j]!=' ') {FITSdirs[i][k] = strTemp[j]; k++;}
      }
      FITSdirs[i][k] = 0;
      strTemp += dim[0];
    }
  }

  /* Initialize output */
  myOutput = defaultOutputs(err);
  ObitReturnDumpRetCode (-999, outfile, myOutput, err);
  if (err->error) Obit_traceback_val (err, routine, "GetInput", list);

  return list;
} /* end TabCopyIn */
예제 #8
0
파일: misc.c 프로젝트: aosm/X11
void 
doProcessInputArgs (
    struct config 	* config_info, 
    int 		argc, 
    char 		* argv[])
{
  int 			arg_counter;
  int			break_flag = 0;

  config_info->num_servers = 0;
  config_info->num_pm_conns = 0;
  config_info->pm_data_timeout = 0;
  config_info->client_listen_timeout = 0;
  config_info->client_data_timeout = 0;
  config_info->log_level = 0;
  config_info->rule_count = config_info->lines_allocated = 0;
  config_info->pm_listen_port = NULL;
  config_info->config_file_data = NULL;
  config_info->config_file_path = NULL;
  config_info->log_file_path = NULL;
  
  /*
   * initialize timeout for three port types; if a timeout for a 
   * particular port type (pmdata, clientlisten, clientdata) is 
   * not specified explicitly, then it assumes the hard-coded
   * default value; initialize other command line options here
   * as well
   */
  for (arg_counter = 1; arg_counter < argc; arg_counter++)
  {
    if (argv[arg_counter][0] == '-')
    {
      if (!strcmp("-pdt", argv[arg_counter]))
      {
        if (arg_counter + 1 == argc)
	{
          break_flag = 1; 
	  break;
        }
	config_info->pm_data_timeout = atoi(argv[arg_counter + 1]);
      }
      else if (!strcmp("-clt", argv[arg_counter]))
      {
        if (arg_counter + 1 == argc)
        {
	  break_flag = 1;
          break; 
        }
	config_info->client_listen_timeout = atoi(argv[arg_counter + 1]);
      }
      else if (!strcmp("-cdt", argv[arg_counter]))
      {
        if (arg_counter + 1 == argc)
        {
          break_flag = 1;
          break; 
        }
	config_info->client_data_timeout = atoi(argv[arg_counter + 1]);
      }
      else if (!strcmp("-pmport", argv[arg_counter]))
      {
        if (arg_counter + 1 == argc)
        {
          break_flag = 1; 
          break;
        }
	if (atoi(argv[arg_counter + 1]) > 65536)
        {
          break_flag = 1;
	  break;     
        }
	config_info->pm_listen_port = Malloc(strlen(argv[arg_counter+1])+1);
	strcpy(config_info->pm_listen_port, argv[arg_counter + 1]);
      }
      else if (!strcmp("-max_pm_conns", argv[arg_counter]))
      {
        if (arg_counter + 1 == argc)
        {
          break_flag = 1; 
          break;
        }
	config_info->num_pm_conns = atoi(argv[arg_counter + 1]);
      }
      else if (!strcmp("-max_server_conns", argv[arg_counter]))
      {
        if (arg_counter + 1 == argc)
        {
          break_flag = 1; 
          break;
        }
	config_info->num_servers = atoi(argv[arg_counter + 1]);
      }
      else if (!strcmp("-config", argv[arg_counter]))
      {
        if (arg_counter + 1 == argc)
        {
          break_flag = 1;
          break; 
        }
        config_info->config_file_path = Malloc(strlen(argv[arg_counter+1])+1);
	strcpy(config_info->config_file_path, argv[arg_counter + 1]);
      }
      else if (!strcmp("-verify", argv[arg_counter]))
      {
	  printConfigVerify = TRUE;
      }
      else if (!strcmp("-logfile", argv[arg_counter]))
      {
        if (arg_counter + 1 == argc)
        {
          break_flag = 1;
          break;
        }
        config_info->log_file_path = Malloc(strlen(argv[arg_counter+1])+1);
        strcpy(config_info->log_file_path, argv[arg_counter + 1]);
      }
      else if (!strcmp("-loglevel", argv[arg_counter]))
      {
        if ((arg_counter + 1 == argc) || (atoi(argv[arg_counter + 1]) > 1))
        {
          break_flag = 1;
          break; 
        }
	config_info->log_level = atoi(argv[arg_counter + 1]);
      }
      else
      {
        (void) fprintf(stderr, "Unrecognized command line argument\n");
	Usage();
      }
    }
  } 
  if (break_flag)
      Usage();

  /*
   * Create space for the global connection arrays
   */
#ifdef XNO_SYSCONF      /* should only be on FreeBSD 1.x and NetBSD 0.x */
#undef _SC_OPEN_MAX
#endif
#ifdef _SC_OPEN_MAX
    config_info->num_client_conns = sysconf(_SC_OPEN_MAX) - 1;
#else
#ifdef hpux
    config_info->num_client_conns = _NFILE - 1;
#else
    config_info->num_client_conns = getdtablesize() - 1;
#endif
#endif

  client_conn_array = (struct client_conn_buf **) 
     malloc (config_info->num_client_conns * sizeof (struct client_conn_buf *));
  if (!client_conn_array)
  {
    (void) fprintf (stderr, "malloc - client connection array\n");
    exit (1);
  }

  if (!config_info->num_pm_conns)
    config_info->num_pm_conns = MAX_PM_CONNS;
  pm_conn_array = (struct pm_conn_buf **) 
     malloc (config_info->num_client_conns * sizeof (struct pm_conn_buf *));
  if (!pm_conn_array) 
  {
    (void) fprintf (stderr, "malloc - PM connection array\n");
    exit (1);
  }

  if (!config_info->num_servers)
    config_info->num_servers = MAX_SERVERS;
  server_array = (struct server_list **)
    malloc (config_info->num_servers * sizeof (struct server_list *));
  if (!server_array)
  {
    (void) fprintf (stderr, "malloc - server listen array\n");
    exit (1);
  }

  /*
   * check timeout values; if still zero then apply defaults
   */
  if (config_info->pm_data_timeout <= 0)
    config_info->pm_data_timeout = PM_DATA_TIMEOUT_DEFAULT;
  if (config_info->client_listen_timeout <= 0)
    config_info->client_listen_timeout = CLIENT_LISTEN_TIMEOUT_DEFAULT;
  if (config_info->client_data_timeout <= 0)
    config_info->client_data_timeout = CLIENT_DATA_TIMEOUT_DEFAULT;
  if (config_info->pm_listen_port == NULL)
  {
    config_info->pm_listen_port = Malloc(strlen(PM_LISTEN_PORT) + 1);
    strcpy(config_info->pm_listen_port, PM_LISTEN_PORT);
  }
}
예제 #9
0
int main(int argc, char* argv[])
{
  enum {prNone, prTelnet} protocol = prNone;
  const char *pTermType = NULL;
  const BYTE *pAwakSeq = NULL;
  const char *pIF = NULL;
  char **pArgs = &argv[1];
  ComParams comParams;

  while (argc > 1) {
    if (**pArgs != '-')
      break;

    if (!strcmp(*pArgs, "--help")) {
      Usage(argv[0]);
    } else
    if (!strcmp(*pArgs, "--telnet")) {
      protocol = prTelnet;
      pArgs++;
      argc--;
    } else
    if (!strcmp(*pArgs, "--ignore-dsr")) {
      pArgs++;
      argc--;
      comParams.SetIgnoreDSR(TRUE);
    } else
    if (argc < 3) {
      Usage(argv[0]);
    } else
    if (!strcmp(*pArgs, "--terminal")) {
      pArgs++;
      argc--;
      pTermType = *pArgs;
      pArgs++;
      argc--;
    } else
    if (!strcmp(*pArgs, "--baud")) {
      pArgs++;
      argc--;
      comParams.SetBaudRate(*pArgs);
      pArgs++;
      argc--;
    } else
    if (!strcmp(*pArgs, "--data")) {
      pArgs++;
      argc--;
      comParams.SetByteSize(*pArgs);
      pArgs++;
      argc--;
    } else
    if (!strcmp(*pArgs, "--parity")) {
      pArgs++;
      argc--;
      if (!comParams.SetParity(*pArgs)) {
        fprintf(stderr, "Unknown parity value %s\n", *pArgs);
        exit(1);
      }
      pArgs++;
      argc--;
    } else
    if (!strcmp(*pArgs, "--stop")) {
      pArgs++;
      argc--;
      if (!comParams.SetStopBits(*pArgs)) {
        fprintf(stderr, "Unknown stop bits value %s\n", *pArgs);
        exit(1);
      }
      pArgs++;
      argc--;
    } else
    if (!strcmp(*pArgs, "--awak-seq")) {
      pArgs++;
      argc--;
      pAwakSeq = (const BYTE *)*pArgs;
      pArgs++;
      argc--;
    } else
    if (!strcmp(*pArgs, "--interface")) {
      pArgs++;
      argc--;
      pIF = *pArgs;
      pArgs++;
      argc--;
    } else {
      fprintf(stderr, "Unknown option %s\n", *pArgs);
      exit(1);
    }
  }

  if (argc < 3 || argc > 4)
    Usage(argv[0]);

  WSADATA wsaData;

  WSAStartup(MAKEWORD(1, 1), &wsaData);

  Protocol *pProtocol;

  switch (protocol) {
  case prTelnet:
    pProtocol = new TelnetProtocol(10, 10);
    ((TelnetProtocol *)pProtocol)->SetTerminalType(pTermType);
    break;
  default:
    pProtocol = new Protocol(10, 10);
  };

  int res;

  if (argc == 4)
    res = com2tcp(pArgs[0], comParams, pIF, pArgs[1], pArgs[2], *pProtocol, pAwakSeq);
  else
    res = tcp2com(pArgs[0], comParams, pIF, pArgs[1], *pProtocol);

  delete pProtocol;

  WSACleanup();
  return res;
}
예제 #10
0
int main( int argc, char ** argv )

{
    SHPHandle	hSHP;
    SHPTree	*psTree;
    int		nExpandShapes = 0;
    int		nMaxDepth = 0;
    int		bDoSearch = 0;
    double	adfSearchMin[4], adfSearchMax[4];
    const char *pszOutputIndexFilename = NULL;
    const char *pszInputIndexFilename = NULL;
    const char *pszTargetFile = NULL;

/* -------------------------------------------------------------------- */
/*	Consume flags.							*/
/* -------------------------------------------------------------------- */
    while( argc > 1 )
    {
        if( strcmp(argv[1],"-v") == 0 )
        {
            nExpandShapes = 1;
            argv++;
            argc--;
        }
        else if( strcmp(argv[1],"-maxdepth") == 0 && argc > 2 )
        {
            nMaxDepth = atoi(argv[2]);
            argv += 2;
            argc -= 2;
        }
        else if( strcmp(argv[1],"-o") == 0 && argc > 2 )
        {
            pszOutputIndexFilename = argv[2];
            argv += 2;
            argc -= 2;
        }
        else if( strcmp(argv[1],"-i") == 0 && argc > 2 )
        {
            pszInputIndexFilename = argv[2];
            argv += 2;
            argc -= 2;
        }
        else if( strcmp(argv[1],"-search") == 0 && argc > 5 )
        {
            bDoSearch = 1;

            adfSearchMin[0] = atof(argv[2]);
            adfSearchMin[1] = atof(argv[3]);
            adfSearchMax[0] = atof(argv[4]);
            adfSearchMax[1] = atof(argv[5]);

            adfSearchMin[2] = adfSearchMax[2] = 0.0;
            adfSearchMin[3] = adfSearchMax[3] = 0.0;

            if( adfSearchMin[0] > adfSearchMax[0]
                || adfSearchMin[1] > adfSearchMax[1] )
            {
                printf( "Min greater than max in search criteria.\n" );
                Usage();
            }
            
            argv += 5;
            argc -= 5;
        }
        else if( pszTargetFile == NULL )				
        {
            pszTargetFile = argv[1];
            argv++;
            argc--;
        }
        else
        {
            printf( "Unrecognised argument: %s\n", argv[1] );
            Usage();
        }
    }

/* -------------------------------------------------------------------- */
/*      Do a search with an existing index file?                        */
/* -------------------------------------------------------------------- */
    if( bDoSearch && pszInputIndexFilename != NULL )
    {
        FILE *fp = fopen( pszInputIndexFilename, "rb" );
        int  *panResult, nResultCount = 0, iResult;

        if( fp == NULL )
        {
            perror( pszInputIndexFilename );
            exit( 1 );
        }

        panResult = SHPSearchDiskTree( fp, adfSearchMin, adfSearchMax, 
                                       &nResultCount );

        printf( "Result: " );
        for( iResult = 0; iResult < nResultCount; iResult++ )
            printf( "%d ", panResult[iResult] );
        printf( "\n" );
        free( panResult );

        fclose( fp );
        
        exit( 0 );
    }

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( pszTargetFile == NULL )
    {
        Usage();
    }

/* -------------------------------------------------------------------- */
/*      Open the passed shapefile.                                      */
/* -------------------------------------------------------------------- */
    hSHP = SHPOpen( pszTargetFile, "rb" );

    if( hSHP == NULL )
    {
	printf( "Unable to open:%s\n", pszTargetFile );
	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Build a quadtree structure for this file.                       */
/* -------------------------------------------------------------------- */
    psTree = SHPCreateTree( hSHP, 2, nMaxDepth, NULL, NULL );

/* -------------------------------------------------------------------- */
/*      Trim unused nodes from the tree.                                */
/* -------------------------------------------------------------------- */
    SHPTreeTrimExtraNodes( psTree );

/* -------------------------------------------------------------------- */
/*      Dump tree to .qix file.                                         */
/* -------------------------------------------------------------------- */
    if( pszOutputIndexFilename != NULL )
    {
        SHPWriteTree( psTree, pszOutputIndexFilename );
    }

/* -------------------------------------------------------------------- */
/*      Dump tree by recursive descent.                                 */
/* -------------------------------------------------------------------- */
    else if( !bDoSearch )
        SHPTreeNodeDump( psTree, psTree->psRoot, "", nExpandShapes );

/* -------------------------------------------------------------------- */
/*      or do a search instead.                                         */
/* -------------------------------------------------------------------- */
    else
        SHPTreeNodeSearchAndDump( psTree, adfSearchMin, adfSearchMax );

/* -------------------------------------------------------------------- */
/*      cleanup                                                         */
/* -------------------------------------------------------------------- */
    SHPDestroyTree( psTree );

    SHPClose( hSHP );

#ifdef USE_DBMALLOC
    malloc_dump(2);
#endif

    exit( 0 );
}
예제 #11
0
int main(int argc, char *argv[]) {

	
	long i;
	int nextSN = 0;
	int base = 0;
	int F = 2;
	int tempposi=0;
	
	
	//--------------
	char *Server = DEFAULT_SERVER;
	char *Filename = "";
	char *Port = DEFAULT_PORT;
	char *Window_size = DEFAULT_WINDOW;
	//Timerhandling
	struct timeouts *timelist = NULL;
	int intervall = 1000; //1000millisekunden

	struct request req;
	struct answer ans;
	int isDropped = false;


	FILE *fp;

	if (argc > 1) {
		for (i = 1; i < argc; i++) {
			if (((argv[i][0] == '-') || (argv[i][0] == '/')) && (argv[i][1] != 0) && (argv[i][2] == 0)) {
				switch (tolower(argv[i][1]))
				{
				case 'a'://Server address
					if (argv[i + 1]) {
						if (argv[i + 1][0] != '-') {
							Server = argv[++i];
							break;
						}
					}
					Usage(argv[0]);
					break;
				case 'p': //server port
					if (argv[i + 1]) {
						if (argv[i + 1][0] != '-') {
							Port = argv[++i];
							break;
						}
					}
					Usage(argv[0]);
					break;
				case 'f': //file name
					if (argv[i + 1]) {
						if (argv[i + 1][0] != '-') {
							Filename = argv[++i];
							break;
						}
					}
					Usage(argv[0]);
					break;
				case 'w': //window size
					if (argv[i + 1]) {
						if (argv[i + 1][0] != '-') {
							Window_size = argv[++i];
							break;
						}
					}
					Usage(argv[0]);
					break;
				default:
					Usage(argv[0]);
					break;
				}
			}
			else Usage(argv[0]);
		}
	}

	initClient(Server, Port);
	File *f = newFile("test.txt");
	
	while (1) {

		
		fromApp(f, &req, nextSN,&tempposi);
	
		//Fenster 1 ---------------------------------------------
		if (nextSN < base + F) {
			printf("Sending Packet: %d\n", nextSN);
			if (nextSN == 1) {
				isDropped = true;
			}
			else isDropped = false;
			timelist = sendData(&req, timelist, isDropped);
			listenToSock();
			//NACKRECEIVE() + DEL_TIMER
			decrement_timer(timelist);
			nextSN++;
		}//-------------------------------------------------------WAIT for TIMEOUT 3 TIMES

		if (nextSN >= base + F) {
			if (timelist->timer == 0) {
				timelist = del_timer(timelist, timelist->seq_nr);
				base++;
			}
			else {
				decrement_timer(timelist);
				listenToSock();
			}
		}
				
		

	
		
	}

	
			
	
	
	getchar();
	getchar();
	return 0;
}
예제 #12
0
파일: tiff-palette.c 프로젝트: aosm/tcl
int main(int argc, char **argv)
{
    int             bits_per_pixel = 8, cmsize, i, j, k,
                    cmap_index, chunk_size = 32, nchunks = 16;
    unsigned char * scan_line;
    uint16          *red, *green, *blue;
    TIFF *          tif;

    programName = argv[0];

    if (argc != 4)
        Usage();

    if (!strcmp(argv[1], "-depth"))
         bits_per_pixel = atoi(argv[2]);
    else
         Usage();

    switch (bits_per_pixel) {
        case 8:
            nchunks = 16;
            chunk_size = 32;
            break;
        case 4:
            nchunks = 4;
            chunk_size = 128;
            break;
        case 2:
            nchunks = 2;
            chunk_size = 256;
            break;
	case 1:
	    nchunks = 2;
	    chunk_size = 256;
	    break;
        default:
            Usage();
    }

    if (bits_per_pixel != 1) {
	cmsize = nchunks * nchunks;
    } else {
	cmsize = 2;
    }
    red = (uint16 *) malloc(cmsize * sizeof(uint16));
    green = (uint16 *) malloc(cmsize * sizeof(uint16));
    blue = (uint16 *) malloc(cmsize * sizeof(uint16));

    switch (bits_per_pixel) {
    case 8:
        for (i = 0; i < cmsize; i++) {
            if (i < 32)
                red[i] = 0;
            else if (i < 64)
                red[i] = SCALE(36);
            else if (i < 96)
                red[i] = SCALE(73);
            else if (i < 128)
                red[i] = SCALE(109);
            else if (i < 160)
                red[i] = SCALE(146);
            else if (i < 192)
                red[i] = SCALE(182);
            else if (i < 224)
                red[i] = SCALE(219);
            else if (i < 256)
                red[i] = SCALE(255);

            if ((i % 32) < 4)
                green[i] = 0;
            else if (i < 8)
                green[i] = SCALE(36);
            else if ((i % 32) < 12)
                green[i] = SCALE(73);
            else if ((i % 32) < 16)
                green[i] = SCALE(109);
            else if ((i % 32) < 20)
                green[i] = SCALE(146);
            else if ((i % 32) < 24)
                green[i] = SCALE(182);
            else if ((i % 32) < 28)
                green[i] = SCALE(219);
            else if ((i % 32) < 32)
                green[i] = SCALE(255);

            if ((i % 4) == 0)
                blue[i] = SCALE(0);
            else if ((i % 4) == 1)
                blue[i] = SCALE(85);
            else if ((i % 4) == 2)
                blue[i] = SCALE(170);
            else if ((i % 4) == 3)
                blue[i] = SCALE(255);
        }
        break;
    case 4:
        red[0] = SCALE(255);
        green[0] = 0;
        blue[0] = 0;

        red[1] = 0;
        green[1] = SCALE(255);
        blue[1] = 0;

        red[2] = 0;
        green[2] = 0;
        blue[2] = SCALE(255);

        red[3] = SCALE(255);
        green[3] = SCALE(255);
        blue[3] = SCALE(255);

        red[4] = 0;
        green[4] = SCALE(255);
        blue[4] = SCALE(255);

        red[5] = SCALE(255);
        green[5] = 0;
        blue[5] = SCALE(255);

        red[6] = SCALE(255);
        green[6] = SCALE(255);
        blue[6] = 0;

        red[7] = 0;
        green[7] = 0;
        blue[7] = 0;

        red[8] = SCALE(176);
        green[8] = SCALE(224);
        blue[8] = SCALE(230);
        red[9] = SCALE(100);
        green[9] = SCALE(149);
        blue[9] = SCALE(237);
        red[10] = SCALE(46);
        green[10] = SCALE(139);
        blue[10] = SCALE(87);
        red[11] = SCALE(160);
        green[11] = SCALE(82);
        blue[11] = SCALE(45);
        red[12] = SCALE(238);
        green[12] = SCALE(130);
        blue[12] = SCALE(238);
        red[13] = SCALE(176);
        green[13] = SCALE(48);
        blue[13] = SCALE(96);
        red[14] = SCALE(50);
        green[14] = SCALE(205);
        blue[14] = SCALE(50);
        red[15] = SCALE(240);
        green[15] = SCALE(152);
        blue[15] = SCALE(35);
        break;
    case 2:
        red[0] = SCALE(255);
        green[0] = 0;
        blue[0] = 0;

        red[1] = 0;
        green[1] = SCALE(255);
        blue[1] = 0;

        red[2] = 0;
        green[2] = 0;
        blue[2] = SCALE(255);
        red[3] = SCALE(255);
        green[3] = SCALE(255);
        blue[3] = SCALE(255);
        break;
    case 1:
        red[0] = 0;
        green[0] = 0;
        blue[0] = 0;

        red[1] = SCALE(255);
        green[1] = SCALE(255);
        blue[1] = SCALE(255);
        break;
    }

    if ((tif = TIFFOpen(argv[3], "w")) == NULL) {
        fprintf(stderr, "can't open %s as a TIFF file\n", argv[3]);
        return 0;
    }

    TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, WIDTH);
    TIFFSetField(tif, TIFFTAG_IMAGELENGTH, HEIGHT);
    TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bits_per_pixel);
    TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
    TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
    TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
    TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
    TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
    TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_NONE);
    TIFFSetField(tif, TIFFTAG_COLORMAP, red, green, blue);

    scan_line = (unsigned char *) malloc(WIDTH / (8 / bits_per_pixel));

    for (i = 0; i < HEIGHT; i++) {
        for (j = 0, k = 0; j < WIDTH;) {
            cmap_index = (j / chunk_size) + ((i / chunk_size) * nchunks);

            switch (bits_per_pixel) {
            case 8:
                scan_line[k++] = cmap_index;
                j++;
                break;
            case 4:
                scan_line[k++] = (cmap_index << 4) + cmap_index;
                j += 2;
                break;
            case 2:
                scan_line[k++] = (cmap_index << 6) + (cmap_index << 4)
                    + (cmap_index << 2) + cmap_index;
                j += 4;
                break;
	    case 1:
		scan_line[k++] =
			((j / chunk_size) == (i / chunk_size)) ? 0x00 : 0xff;
		j += 8;
		break;
            }
        }
        TIFFWriteScanline(tif, scan_line, i, 0);
    }

    free(scan_line);
    TIFFClose(tif);
    return 0;
}
예제 #13
0
int main(int argc, char** argv) {

  if (argc != 2)
    return Usage(std::string(argv[0]));

  // Initialize logging.
  const bool log_to_file = false;

  if (log_to_file) {

    const int nb_rolling_logfiles = 2;
    const int max_logfile_size = 1000000;
    plog::init(plog::verbose, "wave_propagator.log", max_logfile_size, nb_rolling_logfiles);

  } else {

    static plog::ColorConsoleAppender<plog::TxtFormatter> console_appender;
    plog::init(plog::verbose, &console_appender);

  }

  LOG_INFO << "**** 2D/3D wave propagator in heterogeneous media ****\n";

  char const* const parameter_filename_c = argv[1];
  const std::string parameter_filename = std::string(parameter_filename_c);

  RectilinearGrid3D propagation_grid;
  MultiDimensionalStorage4D variable_storage;
  MathematicalParser math_parser;
  std::vector<OutputEvent> output_events;
  TimeloopManager timeloop_manager;
  WaveSolverOptions wave_solver_options = WaveSolverOptions();;

  LOG_INFO << "Reading parameter file \"" << parameter_filename << "\"...";

  std::ifstream parameter_file(parameter_filename.c_str(), std::ifstream::in);
  const int nx_padding = 10;

  ParseParameterFile(nx_padding, &parameter_file, &propagation_grid, 
                     &variable_storage, &math_parser, &output_events,
                     &timeloop_manager, &wave_solver_options);

  parameter_file.close();

  math_parser.PrintConstants();

  const int nb_iter = timeloop_manager.nb_iter();

  // Variables information (hardcoded for now, in variable_definitions.hpp).
  const int nb_variables = variable::NB_VARIABLES;
  
  std::stringstream var_name_msg;

  var_name_msg << "List of variables: [";
  for (int ivar = 0; ivar < nb_variables; ++ivar)
    var_name_msg << " " << variable::VARIABLE_NAMES[ivar];
  var_name_msg << " ]\n";

  LOG_DEBUG << var_name_msg.str();

  const RealT dx = propagation_grid.dx_fast();
  const RealT dy = propagation_grid.dx_medium();
  const RealT dz = propagation_grid.dx_slow();

  RealT* pressure_0 = variable_storage.RawDataSlowDimension(variable::PRESSURE_0);
  RealT* pressure_1 = variable_storage.RawDataSlowDimension(variable::PRESSURE_1);
  RealT* laplace_p = variable_storage.RawDataSlowDimension(variable::LAPLACE_PRESSURE);
  RealT* velocity = variable_storage.RawDataSlowDimension(variable::VELOCITY);

  // Init output events.
  for (auto it = output_events.begin(); it != output_events.end(); ++it)
    it->Create(nb_iter, variable_storage, propagation_grid);

  RealT* sponge_fast = VectorRawData<RealT>(wave_solver_options.sponge_fast());
  RealT* sponge_medium = VectorRawData<RealT>(wave_solver_options.sponge_medium());
  RealT* sponge_slow = VectorRawData<RealT>(wave_solver_options.sponge_slow());

  std::ofstream sponge_fast_out("sponge_fast.txt", std::ofstream::out);
  std::ofstream sponge_medium_out("sponge_medium.txt", std::ofstream::out);
  std::ofstream sponge_slow_out("sponge_slow.txt", std::ofstream::out);

  wave_solver_options.DumpAllSponges(&sponge_fast_out,
                                     &sponge_medium_out,
                                     &sponge_slow_out);

  sponge_fast_out.close();
  sponge_medium_out.close();
  sponge_slow_out.close();

  const RealT dt = timeloop_manager.dt();
  RealT t = 0.0;

  // Main time loop. All numerics (except time step computation) is in
  // here.
  for (int iter = 0; iter < timeloop_manager.nb_iter(); ++iter) {

    t += dt;
    math_parser.AddConstant("t", t);

    const int stencil_radius = 1;

    const int n_fast = variable_storage.dimensions().at(0);
    const int n_fast_padding = variable_storage.padding_fast();
    const int n_medium = variable_storage.dimensions().at(1);
    const int n_slow = variable_storage.dimensions().at(2);

    timer_start = Timer::Now();

    // Apply sponge.
    ApplySpongeLayer_0(n_fast, n_fast_padding, n_medium, n_slow,
                       sponge_fast, sponge_medium, sponge_slow, 
                       pressure_1);

    ComputeLaplacian_0(n_fast, n_fast_padding, n_medium, n_slow,
                       stencil_radius, dx, dy, dz, 
                       pressure_0, laplace_p);
     
    // Advance pressure.
    AdvanceWavePressure_0(n_fast, n_fast_padding, n_medium, n_slow, 
                          stencil_radius, dt,
                          velocity, laplace_p, pressure_0, pressure_1);

    // Apply sponge.
    ApplySpongeLayer_0(n_fast, n_fast_padding, n_medium, n_slow,
                       sponge_fast, sponge_medium, sponge_slow, 
                       pressure_1);

    timer_stop = Timer::Now();
    
    timings_numerics.push_back(Timer::DiffTime(timer_start, timer_stop));

    for (auto it = output_events.begin(); it != output_events.end(); ++it) {

      const bool event_happens = 
        ((iter % it->rhythm() == 0) && (it->rhythm() >= 0)) ||
        ((iter == timeloop_manager.nb_iter() - 1) && (it->rhythm() == - 1));

      if (event_happens) {

        it->Execute(iter, propagation_grid, &math_parser, &variable_storage);

      }
    }

    // Exchange pressure arrays.
    std::swap(pressure_0, pressure_1);

  }

  // Variables cleanup.
  variable_storage.DeAllocate();

  for (auto it = output_events.begin(); it != output_events.end(); ++it)
    it->Destroy();

  const RealT minimum_time = 
    *std::min_element(timings_numerics.begin(), timings_numerics.end());
  assert(0.0 < minimum_time);

  const size_t nb_grid_points = 
    propagation_grid.n_fast() * propagation_grid.n_medium() * propagation_grid.n_slow();

  LOG_INFO << "****************************************";
  std::cout << "\n";
  Timer::PrintTimings(timings_numerics, "            Wave propagation", &std::cout);
  std::cout << "            Wave propagation : " 
            << std::scientific << (RealT)nb_grid_points / (minimum_time * 1.0e-3)
            << " grid updates per second";
  std::cout << "\n";
  std::cout << "\n";
  LOG_INFO << "****************************************";

  return 0;
}
예제 #14
0
파일: skypelog.c 프로젝트: mulaz/skypelog
/*********************************************
 main():
 *********************************************/
int	main	(int argc, char *argv[])
{
  int c;
  long RecordNum=0;
  long RecordLen=0;
  offset RecordEnd=0;
  time_t Time;
  struct tm *TimeS;
  uint64_t SequenceNum;
  uint64_t Number;
  int First=0;
  int PrintString=0;
  char *Label;
  int z;
  while((c = getopt(argc,argv,"bF:v")) != -1)
    {
    switch(c)
      {
      case 'b':	BlankFlag=1; break;
      case 'F':
	Divider=optarg[0];
	if (!strcmp(optarg,"\\n")) Divider='\n';
	break;
      case 'v':	Verbose++; break;
      default:
	Usage(argv[0]);
	exit(-1);
      }
    }

  /* Process each file */
  for( ; optind < argc; optind++)
    {
    SkypeOpenFile(argv[optind]);
    Index=0;
    while( (Index < MemorySize) && (SkypeFindRecord() != (offset)(-1)) )
      {
      RecordNum++;
      if (Verbose) printf("# Record %ld in %s\n",RecordNum,argv[optind]);
      RecordLen = Bytes2Val(4);
      RecordEnd = Index + RecordLen;
      if (Verbose)
	{
	printf("# Record length: %ld bytes (0x%08lx)\n",
		(long)RecordLen,(long)RecordLen);
	}

      if (Index+RecordLen > MemorySize)
	{
	fprintf(stderr,"WARNING: Fractional record being processed.\n");
	/* Permit it to go on! */
	RecordLen = MemorySize - Index;
	}

      SequenceNum = Bytes2Val(4);
      if (Verbose)
	{
	printf("# Sequence: %08lx\n",(unsigned long)SequenceNum);
	}

      /* Process the record */
      First = 0; /* no output yet (first entry not seen) */
      Time=0;
      while(Index < RecordEnd)
        {
	/* Skip until we hit 0x03 */
	while ((Index < RecordEnd) && (Memory[Index] != 0x03))
	   {
	   if (Verbose > 2) printf(" {%02x}",Memory[Index]);
	   Index++;
	   }

	/* Check if we found the start */
	while ((Index < RecordEnd) && (Memory[Index] == 0x03))
		{
		Number=0;
		/* Skip multiple 0x03 */
		while (Memory[Index] == 0x03) Index++;
		Number = ReadNumber();

		PrintString=1;
		Label=NULL;
		switch(Number)
		  {
		  case 15: Label="VoicemailFile"; break;
		  case 16: Label="Call"; break;
		  case 20: Label="Summary"; break;
		  case 36: Label="Language"; break;
		  case 40: Label="Country"; break;
		  case 48: Label="City"; break;
		  case 51: Label="File"; break;
		  case 55: Label="Peek"; break;
		  case 64: Label="Email"; break;
		  case 68: Label="URL"; break;
		  case 72: Label="Description"; break;
		  case 116: Label="Country"; break;
		  case 184: Label="Phone"; break;
		  case 296: Label="Type"; break;
		  case 404: Label="User"; break; /* voicemail */
		  case 408: Label="User"; break; /* voicemail */
		  case 440: Label="Session"; break;
		  case 456: Label="Members"; break; /* username */
		  case 460: Label="Members"; break;
		  case 468: Label="User"; break;
		  case 472: Label="Name"; break;
		  case 480: Label="Session"; break;
		  case 488: Label="Sender"; break; /* username */
		  case 492: Label="Sender"; break; /* screenname */
		  case 500: Label="Recipient"; break;
		  case 508: Label="Message"; break;
		  case 584: Label="Session"; break;
		  case 588: Label="Member"; break;
		  case 828: Label="User"; break;
		  case 840: Label="User"; break;
		  case 868: Label="Number"; break;
		  case 920: Label="Screenname"; break;
		  case 924: Label="Fullname"; break;
		  case 3160: Label="LogBy"; break; /* username */
		  default:
		  	PrintString=0;
			/* Chatmsg lines have TWO big integers that
			   look like timestamps.  The first is really
			   a timestamp.  The second is the log ID number. */
			if (!Time && (Number > 1000000000))
			  {
			  if (First) { printf(" %c ",Divider); }
			  Time = Number;
			  TimeS = gmtime(&Time);
			  printf("%04d-%02d-%02d %02d:%02d:%02d",
			    TimeS->tm_year+1900, TimeS->tm_mon+1,
			    TimeS->tm_mday, TimeS->tm_hour,
			    TimeS->tm_min, TimeS->tm_sec);
			  First=1;
			  }
			else if (Time && (Number > 1000000000))
			  {
			  if (First) { printf(" %c ",Divider); }
			  printf("LogId: %ld",(long)Number);
			  }
		 	break;
		  } /* switch */

		/* Print the string */
		if (PrintString && First) { printf(" %c ",Divider); }
		if (Verbose > 1) printf(" [%ld] ",(long)Number);
		if (PrintString && Label) { printf("%s: ",Label); }
		while((Index < RecordEnd) && (Memory[Index] > 0x03))
		  {
		    //if (PrintString && isprint(Memory[Index]))
		    if (PrintString && Memory[Index])
		      {
			
			//	printf("%i \n %c\n",Memory[Index],Memory[Index]);
			
			if(isprint(Memory[Index])) {
			  fputc(Memory[Index],stdout);
			}
			else {
			  z=Memory[Index];
			  printf("_u{%i}_",z);
			}
			


			First=1;
		      }
		    else
		      {
		    if (Verbose > 2) { printf(" *%02x*",Memory[Index]); }
		    }
		  Index++;
		  }
		}
	  } /* while reading record */
	if (First || Verbose) { printf("\n"); }
	if (BlankFlag && (First || Verbose)) { printf("\n"); }
	} /* while records exist */
    SkypeCloseFile(argv[optind]);
    } /* for each file */
  return(0);
} /* main() */
예제 #15
0
파일: client.c 프로젝트: pykoder/cyassl
THREAD_RETURN CYASSL_THREAD client_test(void* args)
{
    SOCKET_T sockfd = 0;

    CYASSL_METHOD*  method  = 0;
    CYASSL_CTX*     ctx     = 0;
    CYASSL*         ssl     = 0;
    
    CYASSL*         sslResume = 0;
    CYASSL_SESSION* session = 0;
    char         resumeMsg[] = "resuming cyassl!";
    int          resumeSz    = sizeof(resumeMsg);

    char msg[32] = "hello cyassl!";   /* GET may make bigger */
    char reply[80];
    int  input;
    int  msgSz = (int)strlen(msg);

    int   port   = yasslPort;
    char* host   = (char*)yasslIP;
    char* domain = (char*)"www.yassl.com";

    int    ch;
    int    version = CLIENT_INVALID_VERSION;
    int    usePsk   = 0;
    int    sendGET  = 0;
    int    benchmark = 0;
    int    doDTLS    = 0;
    int    matchName = 0;
    int    doPeerCheck = 1;
    int    nonBlocking = 0;
    int    resumeSession = 0;
    int    trackMemory   = 0;
    char*  cipherList = NULL;
    char*  verifyCert = (char*)caCert;
    char*  ourCert    = (char*)cliCert;
    char*  ourKey     = (char*)cliKey;

    int     argc = ((func_args*)args)->argc;
    char**  argv = ((func_args*)args)->argv;

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef NO_RSA
    verifyCert = (char*)eccCert;
    ourCert    = (char*)cliEccCert;
    ourKey     = (char*)cliEccKey;
#endif
    (void)resumeSz;
    (void)session;
    (void)sslResume;
    (void)trackMemory;

    while ((ch = mygetopt(argc, argv, "?gdusmNrth:p:v:l:A:c:k:b:z")) != -1) {
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'g' :
                sendGET = 1;
                break;

            case 'd' :
                doPeerCheck = 0;
                break;

            case 'u' :
                doDTLS  = 1;
                break;

            case 's' :
                usePsk = 1;
                break;

            case 't' :
            #ifdef USE_CYASSL_MEMORY
                trackMemory = 1;
            #endif
                break;

            case 'm' :
                matchName = 1;
                break;

            case 'h' :
                host   = myoptarg;
                domain = myoptarg;
                break;

            case 'p' :
                port = atoi(myoptarg);
                #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API)
                    if (port == 0)
                        err_sys("port number cannot be 0");
                #endif
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'b' :
                benchmark = atoi(myoptarg);
                if (benchmark < 0 || benchmark > 1000000) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'N' :
                nonBlocking = 1;
                break;

            case 'r' :
                resumeSession = 1;
                break;

            case 'z' :
                #ifndef CYASSL_LEANPSK
                    CyaSSL_GetObjectSize();
                #endif
                break;

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    myoptind = 0;      /* reset for test cases */

    /* sort out DTLS versus TLS versions */
    if (version == CLIENT_INVALID_VERSION) {
        if (doDTLS)
            version = CLIENT_DTLS_DEFAULT_VERSION;
        else
            version = CLIENT_DEFAULT_VERSION;
    }
    else {
        if (doDTLS) {
            if (version == 3)
                version = -2;
            else
                version = -1;
        }
    }

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        InitMemoryTracker(); 
#endif

    switch (version) {
#ifndef NO_OLD_TLS
        case 0:
            method = CyaSSLv3_client_method();
            break;

        case 1:
            method = CyaTLSv1_client_method();
            break;

        case 2:
            method = CyaTLSv1_1_client_method();
            break;
#endif

        case 3:
            method = CyaTLSv1_2_client_method();
            break;

#ifdef CYASSL_DTLS
        case -1:
            method = CyaDTLSv1_client_method();
            break;

        case -2:
            method = CyaDTLSv1_2_client_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = CyaSSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");

    if (cipherList)
        if (CyaSSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("client can't set cipher list 1");

#ifdef CYASSL_LEANPSK
    usePsk = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    usePsk = 1;
#endif

    if (usePsk) {
#ifndef NO_PSK
        CyaSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb);
        if (cipherList == NULL) {
            const char *defaultCipherList;
            #ifdef HAVE_NULL_CIPHER
                defaultCipherList = "PSK-NULL-SHA256";
            #else
                defaultCipherList = "PSK-AES128-CBC-SHA256";
            #endif
            if (CyaSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS)
                err_sys("client can't set cipher list 2");
        }
#endif
    }

#ifdef OPENSSL_EXTRA
    CyaSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    if (cipherList == NULL) {
        /* don't use EDH, can't sniff tmp keys */
        if (CyaSSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS) {
            err_sys("client can't set cipher list 3");
        }
    }
#endif

#ifdef USER_CA_CB
    CyaSSL_CTX_SetCACb(ctx, CaCb);
#endif

#ifdef VERIFY_CALLBACK
    CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify);
#endif
#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (!usePsk){
        if (CyaSSL_CTX_use_certificate_file(ctx, ourCert, SSL_FILETYPE_PEM)
                                     != SSL_SUCCESS)
            err_sys("can't load client cert file, check file and run from"
                    " CyaSSL home dir");

        if (CyaSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load client private key file, check file and run "
                    "from CyaSSL home dir");    

        if (CyaSSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
                err_sys("can't load ca file, Please run from CyaSSL home dir");
    }
#endif
#if !defined(NO_CERTS)
    if (!usePsk && doPeerCheck == 0)
        CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
#endif

#ifdef HAVE_CAVIUM
    CyaSSL_CTX_UseCavium(ctx, CAVIUM_DEV_ID);
#endif

    if (benchmark) {
        /* time passed in number of connects give average */
        int times = benchmark;
        int i = 0;

        double start = current_time(), avg;

        for (i = 0; i < times; i++) {
            tcp_connect(&sockfd, host, port, doDTLS);
            ssl = CyaSSL_new(ctx);
            CyaSSL_set_fd(ssl, sockfd);
            if (CyaSSL_connect(ssl) != SSL_SUCCESS)
                err_sys("SSL_connect failed");

            CyaSSL_shutdown(ssl);
            CyaSSL_free(ssl);
            CloseSocket(sockfd);
        }
        avg = current_time() - start;
        avg /= times;
        avg *= 1000;   /* milliseconds */
        printf("CyaSSL_connect avg took: %8.3f milliseconds\n", avg);

        CyaSSL_CTX_free(ctx);
        ((func_args*)args)->return_code = 0;

        exit(EXIT_SUCCESS);
    }

    ssl = CyaSSL_new(ctx);
    if (ssl == NULL)
        err_sys("unable to get SSL object");
    if (doDTLS) {
        SOCKADDR_IN_T addr;
        build_addr(&addr, host, port);
        CyaSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
        tcp_socket(&sockfd, 1);
    }
    else {
        tcp_connect(&sockfd, host, port, 0);
    }
    CyaSSL_set_fd(ssl, sockfd);
#ifdef HAVE_CRL
    if (CyaSSL_EnableCRL(ssl, CYASSL_CRL_CHECKALL) != SSL_SUCCESS)
        err_sys("can't enable crl check");
    if (CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS)
        err_sys("can't load crl, check crlfile and date validity");
    if (CyaSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS)
        err_sys("can't set crl callback");
#endif
    if (matchName && doPeerCheck)
        CyaSSL_check_domain_name(ssl, domain);
#ifndef CYASSL_CALLBACKS
    if (nonBlocking) {
        CyaSSL_set_using_nonblock(ssl, 1);
        tcp_set_nonblocking(&sockfd);
        NonBlockingSSL_Connect(ssl);
    }
    else if (CyaSSL_connect(ssl) != SSL_SUCCESS) {
        /* see note at top of README */
        int  err = CyaSSL_get_error(ssl, 0);
        char buffer[80];
        printf("err = %d, %s\n", err,
                                CyaSSL_ERR_error_string(err, buffer));
        err_sys("SSL_connect failed");
        /* if you're getting an error here  */
    }
#else
    timeout.tv_sec  = 2;
    timeout.tv_usec = 0;
    NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif
    showPeer(ssl);

    if (sendGET) {
        printf("SSL connect ok, sending GET...\n");
        msgSz = 28;
        strncpy(msg, "GET /index.html HTTP/1.0\r\n\r\n", msgSz);
        msg[msgSz] = '\0';
    }
    if (CyaSSL_write(ssl, msg, msgSz) != msgSz)
        err_sys("SSL_write failed");

    input = CyaSSL_read(ssl, reply, sizeof(reply)-1);
    if (input > 0) {
        reply[input] = 0;
        printf("Server response: %s\n", reply);

        if (sendGET) {  /* get html */
            while (1) {
                input = CyaSSL_read(ssl, reply, sizeof(reply)-1);
                if (input > 0) {
                    reply[input] = 0;
                    printf("%s\n", reply);
                }
                else
                    break;
            }
        }
    }
    else if (input < 0) {
        int readErr = CyaSSL_get_error(ssl, 0);
        if (readErr != SSL_ERROR_WANT_READ)
            err_sys("CyaSSL_read failed");
    }

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            strncpy(msg, "break", 6);
            msgSz = (int)strlen(msg);
            /* try to send session close */
            CyaSSL_write(ssl, msg, msgSz);
        }
        session   = CyaSSL_get_session(ssl);
        sslResume = CyaSSL_new(ctx);
    }
#endif

    if (doDTLS == 0)            /* don't send alert after "break" command */
        CyaSSL_shutdown(ssl);  /* echoserver will interpret as new conn */
    CyaSSL_free(ssl);
    CloseSocket(sockfd);

#ifndef NO_SESSION_CACHE
    if (resumeSession) {
        if (doDTLS) {
            SOCKADDR_IN_T addr;
            #ifdef USE_WINDOWS_API 
                Sleep(500);
            #else
                sleep(1);
            #endif
            build_addr(&addr, host, port);
            CyaSSL_dtls_set_peer(sslResume, &addr, sizeof(addr));
            tcp_socket(&sockfd, 1);
        }
        else {
            tcp_connect(&sockfd, host, port, 0);
        }
        CyaSSL_set_fd(sslResume, sockfd);
        CyaSSL_set_session(sslResume, session);
       
        showPeer(sslResume);
#ifndef CYASSL_CALLBACKS
        if (nonBlocking) {
            CyaSSL_set_using_nonblock(sslResume, 1);
            tcp_set_nonblocking(&sockfd);
            NonBlockingSSL_Connect(sslResume);
        }
        else if (CyaSSL_connect(sslResume) != SSL_SUCCESS)
            err_sys("SSL resume failed");
#else
        timeout.tv_sec  = 2;
        timeout.tv_usec = 0;
        NonBlockingSSL_Connect(ssl);  /* will keep retrying on timeout */
#endif

        if (CyaSSL_session_reused(sslResume))
            printf("reused session id\n");
        else
            printf("didn't reuse session id!!!\n");

        if (CyaSSL_write(sslResume, resumeMsg, resumeSz) != resumeSz)
            err_sys("SSL_write failed");

        if (nonBlocking) {
            /* give server a chance to bounce a message back to client */
            #ifdef USE_WINDOWS_API
                Sleep(500);
            #else
                sleep(1);
            #endif
        }

        input = CyaSSL_read(sslResume, reply, sizeof(reply)-1);
        if (input > 0) {
            reply[input] = 0;
            printf("Server resume response: %s\n", reply);
        }

        /* try to send session break */
        CyaSSL_write(sslResume, msg, msgSz); 

        CyaSSL_shutdown(sslResume);
        CyaSSL_free(sslResume);
        CloseSocket(sockfd);
    }
#endif /* NO_SESSION_CACHE */

    CyaSSL_CTX_free(ctx);

    ((func_args*)args)->return_code = 0;

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        ShowMemoryTracker();
#endif /* USE_CYASSL_MEMORY */

    return 0;
}
예제 #16
0
파일: main.cpp 프로젝트: takei-yuya/groupby
int main(int argc, char** argv)
{
  GroupBy::Option option;

  while (1) {
    static struct option long_options[] = {
      { "width",            required_argument, 0, 'w' },
      { "fields",           required_argument, 0, 'f' },
      { "skip",             required_argument, 0, 's' },
      { "delimiters",       required_argument, 0, 'd' },
      { "join-delimiter",   required_argument, 0, 'j' },
      { "help",             no_argument,       0, '?' },
      { 0,                 0 ,                 0, 0 },
    };

    int c = getopt_long(argc, argv, "w:d:j:f:s:", long_options, NULL);
    if (c == -1) {
      break;
    }

    switch(c) {
    case 'w':
      option.get_key_mode = GroupBy::Option::GET_KEY_MODE_CHARS;
      option.key_length = std::atoi(optarg);
      break;

    case 'f':
      option.get_key_mode = GroupBy::Option::GET_KEY_MODE_FIELDS;
      option.field_length = std::atoi(optarg);
      break;

    case 's':
      option.n_skip = std::atoi(optarg);
      break;

    case 'd':
      option.get_key_mode = GroupBy::Option::GET_KEY_MODE_FIELDS;
      option.delimiters = optarg;
      break;

    case 'j':
      option.join_delimiter = optarg;
      break;

    case '?':
      Usage(argc, argv, option);
      return 0;
      break;

    default:
      Usage(argc, argv, option);
      return -1;
    }
  }

  if (optind < argc) {
    Usage(argc, argv, option);
    return -1;
  }

  argc -= optind;
  argv += optind;

  GroupBy group_by(option);
  while (std::cin) {
    std::string line;
    if (std::getline(std::cin, line).eof()) {
      break;
    }
    group_by.Append(line);
  }

  const std::vector<std::string>& buffers = group_by.Buffers();
  for (std::vector<std::string>::const_iterator it = buffers.begin(); it != buffers.end(); ++it) {
    std::cout << *it << std::endl;
  }

  return 0;
}
예제 #17
0
int main( int argc, char ** argv )

{
    int i, b3D = FALSE;
    int bInverse = FALSE;
    const char *pszSrcFilename = NULL;
    const char *pszDstFilename = NULL;
    char **papszLayers = NULL;
    const char *pszSQL = NULL;
    const char *pszBurnAttribute = NULL;
    const char *pszWHERE = NULL;
    std::vector<int> anBandList;
    std::vector<double> adfBurnValues;
    char **papszRasterizeOptions = NULL;
    double dfXRes = 0, dfYRes = 0;
    int bCreateOutput = FALSE;
    const char* pszFormat = "GTiff";
    int bFormatExplicitelySet = FALSE;
    char **papszCreateOptions = NULL;
    GDALDriverH hDriver = NULL;
    GDALDataType eOutputType = GDT_Float64;
    std::vector<double> adfInitVals;
    int bNoDataSet = FALSE;
    double dfNoData = 0;
    OGREnvelope sEnvelop;
    int bGotBounds = FALSE;
    int nXSize = 0, nYSize = 0;
    int bQuiet = FALSE;
    GDALProgressFunc pfnProgress = GDALTermProgress;
    OGRSpatialReferenceH hSRS = NULL;
    int bTargetAlignedPixels = FALSE;
    

    /* Check that we are running against at least GDAL 1.4 */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
    {
        fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, "
                "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME);
        exit(1);
    }

    GDALAllRegister();
    OGRRegisterAll();

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") )
        {
            bQuiet = TRUE;
            pfnProgress = GDALDummyProgress;
        }
        else if( EQUAL(argv[i],"-a") && i < argc-1 )
        {
            pszBurnAttribute = argv[++i];
        }
        else if( EQUAL(argv[i],"-b") && i < argc-1 )
        {
            if (strchr(argv[i+1], ' '))
            {
                char** papszTokens = CSLTokenizeString( argv[i+1] );
                char** papszIter = papszTokens;
                while(papszIter && *papszIter)
                {
                    anBandList.push_back(atoi(*papszIter));
                    papszIter ++;
                }
                CSLDestroy(papszTokens);
                i += 1;
            }
            else
            {
                while(i < argc-1 && ArgIsNumeric(argv[i+1]))
                {
                    anBandList.push_back(atoi(argv[i+1]));
                    i += 1;
                }
            }
        }
        else if( EQUAL(argv[i],"-3d")  )
        {
            b3D = TRUE;
            papszRasterizeOptions = 
                CSLSetNameValue( papszRasterizeOptions, "BURN_VALUE_FROM", "Z");
        }
        else if( EQUAL(argv[i],"-i")  )
        {
            bInverse = TRUE;
        }
        else if( EQUAL(argv[i],"-at")  )
        {
            papszRasterizeOptions = 
                CSLSetNameValue( papszRasterizeOptions, "ALL_TOUCHED", "TRUE" );
        }
        else if( EQUAL(argv[i],"-burn") && i < argc-1 )
        {
            if (strchr(argv[i+1], ' '))
            {
                char** papszTokens = CSLTokenizeString( argv[i+1] );
                char** papszIter = papszTokens;
                while(papszIter && *papszIter)
                {
                    adfBurnValues.push_back(atof(*papszIter));
                    papszIter ++;
                }
                CSLDestroy(papszTokens);
                i += 1;
            }
            else
            {
                while(i < argc-1 && ArgIsNumeric(argv[i+1]))
                {
                    adfBurnValues.push_back(atof(argv[i+1]));
                    i += 1;
                }
            }
        }
        else if( EQUAL(argv[i],"-where") && i < argc-1 )
        {
            pszWHERE = argv[++i];
        }
        else if( EQUAL(argv[i],"-l") && i < argc-1 )
        {
            papszLayers = CSLAddString( papszLayers, argv[++i] );
        }
        else if( EQUAL(argv[i],"-sql") && i < argc-1 )
        {
            pszSQL = argv[++i];
        }
        else if( EQUAL(argv[i],"-of") && i < argc-1 )
        {
            pszFormat = argv[++i];
            bFormatExplicitelySet = TRUE;
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-init") && i < argc - 1 )
        {
            if (strchr(argv[i+1], ' '))
            {
                char** papszTokens = CSLTokenizeString( argv[i+1] );
                char** papszIter = papszTokens;
                while(papszIter && *papszIter)
                {
                    adfInitVals.push_back(atof(*papszIter));
                    papszIter ++;
                }
                CSLDestroy(papszTokens);
                i += 1;
            }
            else
            {
                while(i < argc-1 && ArgIsNumeric(argv[i+1]))
                {
                    adfInitVals.push_back(atof(argv[i+1]));
                    i += 1;
                }
            }
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-a_nodata") && i < argc - 1 )
        {
            dfNoData = atof(argv[i+1]);
            bNoDataSet = TRUE;
            i += 1;
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-a_srs") && i < argc-1 )
        {
            hSRS = OSRNewSpatialReference( NULL );

            if( OSRSetFromUserInput(hSRS, argv[i+1]) != OGRERR_NONE )
            {
                fprintf( stderr, "Failed to process SRS definition: %s\n", 
                         argv[i+1] );
                exit( 1 );
            }

            i++;
            bCreateOutput = TRUE;
        }   

        else if( EQUAL(argv[i],"-te") && i < argc - 4 )
        {
            sEnvelop.MinX = atof(argv[++i]);
            sEnvelop.MinY = atof(argv[++i]);
            sEnvelop.MaxX = atof(argv[++i]);
            sEnvelop.MaxY = atof(argv[++i]);
            bGotBounds = TRUE;
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-a_ullr") && i < argc - 4 )
        {
            sEnvelop.MinX = atof(argv[++i]);
            sEnvelop.MaxY = atof(argv[++i]);
            sEnvelop.MaxX = atof(argv[++i]);
            sEnvelop.MinY = atof(argv[++i]);
            bGotBounds = TRUE;
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-co") && i < argc-1 )
        {
            papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] );
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-ot") && i < argc-1 )
        {
            int	iType;
            
            for( iType = 1; iType < GDT_TypeCount; iType++ )
            {
                if( GDALGetDataTypeName((GDALDataType)iType) != NULL
                    && EQUAL(GDALGetDataTypeName((GDALDataType)iType),
                             argv[i+1]) )
                {
                    eOutputType = (GDALDataType) iType;
                }
            }

            if( eOutputType == GDT_Unknown )
            {
                printf( "Unknown output pixel type: %s\n", argv[i+1] );
                Usage();
            }
            i++;
            bCreateOutput = TRUE;
        }
        else if( (EQUAL(argv[i],"-ts") || EQUAL(argv[i],"-outsize")) && i < argc-2 )
        {
            nXSize = atoi(argv[++i]);
            nYSize = atoi(argv[++i]);
            if (nXSize <= 0 || nYSize <= 0)
            {
                printf( "Wrong value for -outsize parameters\n");
                Usage();
            }
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-tr") && i < argc-2 )
        {
            dfXRes = atof(argv[++i]);
            dfYRes = fabs(atof(argv[++i]));
            if( dfXRes == 0 || dfYRes == 0 )
            {
                printf( "Wrong value for -tr parameters\n");
                Usage();
            }
            bCreateOutput = TRUE;
        }
        else if( EQUAL(argv[i],"-tap") )
        {
            bTargetAlignedPixels = TRUE;
            bCreateOutput = TRUE;
        }
        else if( pszSrcFilename == NULL )
        {
            pszSrcFilename = argv[i];
        }
        else if( pszDstFilename == NULL )
        {
            pszDstFilename = argv[i];
        }
        else
            Usage();
    }

    if( pszSrcFilename == NULL || pszDstFilename == NULL )
    {
        fprintf( stderr, "Missing source or destination.\n\n" );
        Usage();
    }

    if( adfBurnValues.size() == 0 && pszBurnAttribute == NULL && !b3D )
    {
        fprintf( stderr, "At least one of -3d, -burn or -a required.\n\n" );
        Usage();
    }

    if( bCreateOutput )
    {
        if( dfXRes == 0 && dfYRes == 0 && nXSize == 0 && nYSize == 0 )
        {
            fprintf( stderr, "'-tr xres yes' or '-ts xsize ysize' is required.\n\n" );
            Usage();
        }
    
        if (bTargetAlignedPixels && dfXRes == 0 && dfYRes == 0)
        {
            fprintf( stderr, "-tap option cannot be used without using -tr\n");
            Usage();
        }

        if( anBandList.size() != 0 )
        {
            fprintf( stderr, "-b option cannot be used when creating a GDAL dataset.\n\n" );
            Usage();
        }

        int nBandCount = 1;

        if (adfBurnValues.size() != 0)
            nBandCount = adfBurnValues.size();

        if ((int)adfInitVals.size() > nBandCount)
            nBandCount = adfInitVals.size();

        if (adfInitVals.size() == 1)
        {
            for(i=1;i<=nBandCount - 1;i++)
                adfInitVals.push_back( adfInitVals[0] );
        }

        int i;
        for(i=1;i<=nBandCount;i++)
            anBandList.push_back( i );
    }
    else
    {
        if( anBandList.size() == 0 )
            anBandList.push_back( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Open source vector dataset.                                     */
/* -------------------------------------------------------------------- */
    OGRDataSourceH hSrcDS;

    hSrcDS = OGROpen( pszSrcFilename, FALSE, NULL );
    if( hSrcDS == NULL )
    {
        fprintf( stderr, "Failed to open feature source: %s\n", 
                 pszSrcFilename);
        exit( 1 );
    }

    if( pszSQL == NULL && papszLayers == NULL )
    {
        if( OGR_DS_GetLayerCount(hSrcDS) == 1 )
        {
            papszLayers = CSLAddString(NULL, OGR_L_GetName(OGR_DS_GetLayer(hSrcDS, 0)));
        }
        else
        {
            fprintf( stderr, "At least one of -l or -sql required.\n\n" );
            Usage();
        }
    }

/* -------------------------------------------------------------------- */
/*      Open target raster file.  Eventually we will add optional       */
/*      creation.                                                       */
/* -------------------------------------------------------------------- */
    GDALDatasetH hDstDS = NULL;

    if (bCreateOutput)
    {
/* -------------------------------------------------------------------- */
/*      Find the output driver.                                         */
/* -------------------------------------------------------------------- */
        hDriver = GDALGetDriverByName( pszFormat );
        if( hDriver == NULL 
            || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) == NULL )
        {
            int	iDr;

            printf( "Output driver `%s' not recognised or does not support\n", 
                    pszFormat );
            printf( "direct output file creation.  The following format drivers are configured\n"
                    "and support direct output:\n" );

            for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
            {
                GDALDriverH hDriver = GDALGetDriver(iDr);

                if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL) != NULL )
                {
                    printf( "  %s: %s\n",
                            GDALGetDriverShortName( hDriver  ),
                            GDALGetDriverLongName( hDriver ) );
                }
            }
            printf( "\n" );
            exit( 1 );
        }

        if (!bQuiet && !bFormatExplicitelySet)
            CheckExtensionConsistency(pszDstFilename, pszFormat);
    }
    else
    {
        hDstDS = GDALOpen( pszDstFilename, GA_Update );
        if( hDstDS == NULL )
            exit( 2 );
    }

/* -------------------------------------------------------------------- */
/*      Process SQL request.                                            */
/* -------------------------------------------------------------------- */
    if( pszSQL != NULL )
    {
        OGRLayerH hLayer;

        hLayer = OGR_DS_ExecuteSQL( hSrcDS, pszSQL, NULL, NULL ); 
        if( hLayer != NULL )
        {
            if (bCreateOutput)
            {
                std::vector<OGRLayerH> ahLayers;
                ahLayers.push_back(hLayer);

                hDstDS = CreateOutputDataset(ahLayers, hSRS,
                                 bGotBounds, sEnvelop,
                                 hDriver, pszDstFilename,
                                 nXSize, nYSize, dfXRes, dfYRes,
                                 bTargetAlignedPixels,
                                 anBandList.size(), eOutputType,
                                 papszCreateOptions, adfInitVals,
                                 bNoDataSet, dfNoData);
            }

            ProcessLayer( hLayer, hSRS != NULL, hDstDS, anBandList, 
                          adfBurnValues, b3D, bInverse, pszBurnAttribute,
                          papszRasterizeOptions, pfnProgress, NULL );

            OGR_DS_ReleaseResultSet( hSrcDS, hLayer );
        }
    }

/* -------------------------------------------------------------------- */
/*      Create output file if necessary.                                */
/* -------------------------------------------------------------------- */
    int nLayerCount = CSLCount(papszLayers);

    if (bCreateOutput && hDstDS == NULL)
    {
        std::vector<OGRLayerH> ahLayers;

        for( i = 0; i < nLayerCount; i++ )
        {
            OGRLayerH hLayer = OGR_DS_GetLayerByName( hSrcDS, papszLayers[i] );
            if( hLayer == NULL )
            {
                continue;
            }
            ahLayers.push_back(hLayer);
        }

        hDstDS = CreateOutputDataset(ahLayers, hSRS,
                                bGotBounds, sEnvelop,
                                hDriver, pszDstFilename,
                                nXSize, nYSize, dfXRes, dfYRes,
                                bTargetAlignedPixels,
                                anBandList.size(), eOutputType,
                                papszCreateOptions, adfInitVals,
                                bNoDataSet, dfNoData);
    }

/* -------------------------------------------------------------------- */
/*      Process each layer.                                             */
/* -------------------------------------------------------------------- */

    for( i = 0; i < nLayerCount; i++ )
    {
        OGRLayerH hLayer = OGR_DS_GetLayerByName( hSrcDS, papszLayers[i] );
        if( hLayer == NULL )
        {
            fprintf( stderr, "Unable to find layer %s, skipping.\n", 
                      papszLayers[i] );
            continue;
        }

        if( pszWHERE )
        {
            if( OGR_L_SetAttributeFilter( hLayer, pszWHERE ) != OGRERR_NONE )
                break;
        }

        void *pScaledProgress;
        pScaledProgress =
            GDALCreateScaledProgress( 0.0, 1.0 * (i + 1) / nLayerCount,
                                      pfnProgress, NULL );

        ProcessLayer( hLayer, hSRS != NULL, hDstDS, anBandList, 
                      adfBurnValues, b3D, bInverse, pszBurnAttribute,
                      papszRasterizeOptions, GDALScaledProgress, pScaledProgress );

        GDALDestroyScaledProgress( pScaledProgress );
    }

/* -------------------------------------------------------------------- */
/*      Cleanup                                                         */
/* -------------------------------------------------------------------- */

    OGR_DS_Destroy( hSrcDS );
    GDALClose( hDstDS );

    OSRDestroySpatialReference(hSRS);

    CSLDestroy( argv );
    CSLDestroy( papszRasterizeOptions );
    CSLDestroy( papszLayers );
    CSLDestroy( papszCreateOptions );
    
    GDALDestroyDriverManager();
    OGRCleanupAll();

    return 0;
}
예제 #18
0
int main(int argc, char **argv)
{
  int status;
  Menu *menu;
  char *motd, **arg;
  struct sigaction act;

  if (!(program_name = strrchr(argv[0], '/')))
    program_name = argv[0];
  else
    program_name++;
  program_name = strdup(program_name);
  whoami = strdup(program_name); /* used by menu.c,  ugh !!! */

  user = mrcl_krb_user();
  if (!user)
    exit(1);

  verbose = TRUE;
  arg = argv;
  moira_server = NULL;

  while (++arg - argv < argc)
    {
      if (**arg == '-')
	{
	  if (!strcmp(*arg, "-nomenu"))
	    {
#ifdef HAVE_CURSES
	      use_menu = FALSE;
#else
	      ;
#endif
	    }
	  else if (!strcmp(*arg, "-menu"))
	    {
#ifdef HAVE_CURSES
	      use_menu = TRUE;
#else
	      fprintf(stderr, "%s: No curses support. -menu option ignored\n",
		      whoami);
#endif
	    }
	  else if (!strcmp(*arg, "-db"))
	    if (arg - argv < argc - 1)
	      {
		++arg;
		moira_server = *arg;
	      }
	    else
	      Usage();
	  else
	    Usage();
	}
    }

  if (mrcl_connect(moira_server, program_name, QUERY_VERSION, 0)
      != MRCL_SUCCESS)
    exit(1);

  if ((status = mr_krb5_auth(program_name)))
    {
      if (status == MR_UNKNOWN_PROC)
	status = mr_auth(program_name);

      if (status)
	{
	  if (status == MR_USER_AUTH)
	    {
	      char buf[BUFSIZ];
	      com_err(program_name, status, "\nPress [RETURN] to continue");
	      fgets(buf, BUFSIZ, stdin);
	    }
	  else
	    ErrorExit("\nAuthorization failed -- please run kinit", status);
	}
    }

  /*
   * These signals should not be set until just before we fire up the menu
   * system.
   */

  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;
  act.sa_handler = Signal_Handler;
  sigaction(SIGHUP, &act, NULL);
  sigaction(SIGQUIT, &act, NULL);
#ifdef HAVE_CURSES
  if (use_menu)
    sigaction(SIGINT, &act, NULL);
  else
#endif
    {
      act.sa_handler = CatchInterrupt;
      sigaction(SIGINT, &act, NULL);
    }

  menu = &namespace_menu;

#ifdef HAVE_CURSES
  if (use_menu)		/* Start menus that execute program */
    {
      Start_paging();
      Start_menu(menu);
      Stop_paging();
    }
  else			/* Start program without menus. */
#endif
    Start_no_menu(menu);

  mr_disconnect();
  exit(0);
}
예제 #19
0
void
main (INT argc,       /* Number of command line arguments */
      char *argv[],   /* Array of command line arguments */
      char *envp[])   /* Array of environment pointers */
{
   WN          *pu;
   INT32        inp_file_count;
   PU_Info     *pu_tree, *current_pu;

   /* Here are things that every process driver should do as soon as
    * possible upon start-up.
    */
   MEM_Initialize ();
   Init_Error_Handler (10);
   Set_Error_Line (ERROR_LINE_UNKNOWN);
   Set_Error_Phase ("IR Walker");
   Set_Error_File (NULL);

   Init_Operator_To_Opcode_Table ();
    
   /* Process the input file */
   inp_file_count = Get_Irb_File_Name (argc, argv);
   if (inp_file_count == 0)
   {
      Usage ();
      fprintf (stderr, "ERROR: missing input file on command line\n");
   }
   else if (inp_file_count > 1)
   {
      Usage ();
      fprintf (stderr, "ERROR: too many input files on command line\n");
   }
   else if (stat (Irb_File_Name, &statbuf) != 0)
   {
      fprintf (stderr, "ERROR: input file (%s) does not exist\n",
	       Irb_File_Name);
   }
   else if (!gflag)
   {
      Usage ();
      fprintf (stderr, "ERROR: missing GDAR file on command line\n");
   }
   else if (stat (GDAR_File_Name, &statbuf) != 0)
   {
      fprintf (stderr, "ERROR: GDAR file (%s) does not exist\n",
	       GDAR_File_Name);
   }
   else
   {

      /* Setup output file */
      if (!oflag)
	(void) strcpy (filename_out, filename_in);
      (void) sprintf (temp_filename, "%s$%d", filename_out, (INT32) getpid ());
      (void) remove (temp_filename);

      /* Get the global symbol table, the string table, the constant table,
       * and the initialization table.
       */
      (void) Open_Input_Info (Irb_File_Name);
      pu_tree = Read_Global_Info (NULL);

      /* Open output file */
      (void) Open_Output_Info (temp_filename);

      /* Read all the PUs */
      read_pu (pu_tree);

      /* Process global symbol table. */
      Process_GDAR (GDAR_File_Name, Global_Symtab, &pu_tree);

      /* Write all the PUs */
      write_pu (pu_tree);

      /* Finish up output file */
      Write_Global_Info (pu_tree);
      Close_Output_Info ();
      (void) remove (filename_out);
      (void) rename (temp_filename, filename_out);

   }
   
   exit (0);
} /* main */
예제 #20
0
int main (int argc, char ** argv) {

  char buffer [buflen];
  vrpn_HANDLERPARAM header;
  int file;
  int retval;

  if (argc != 2) {
    Usage(argv[0]);
    exit(0);
  }

  file = open(argv[1], O_RDONLY);
  if (file == -1) {
    fprintf(stderr, "Couldn't open \"%s\".\n", argv[1]);
    exit(0);
  }

  while (1) {

    int len;
    struct timeval time;
    long sender;
    long type;
    int len2;

    retval = read(file, &header, sizeof(header));
    if (retval < 0) { printf("ERROR\n"); close(file); exit(0); }
    if (!retval) { printf("EOF\n"); close(file); exit(0); }

    len = ntohl(header.payload_len);
    time.tv_sec = ntohl(header.msg_time.tv_sec);
    time.tv_usec = ntohl(header.msg_time.tv_usec);
    sender = ntohl(header.sender);
    type = ntohl(header.type);

    //printf("Message type %d, sender %d, payload length %d\n",
            //type, sender, len);

    retval = read(file, buffer, len);
    if (retval < 0) { printf("ERROR\n"); close(file); exit(0); }
    if (!retval) { printf("EOF\n"); close(file); exit(0); }

    //printf(" <%d bytes>\n", retval);

    switch (type) {

      case vrpn_CONNECTION_SENDER_DESCRIPTION:
        len2 = ntohl(* ((int *) buffer));
        buffer[len2 + sizeof(int)] = 0;
	printf(" The name of sender #%ld is \"%s\".\n", sender, buffer + sizeof(int));
        break;

      case vrpn_CONNECTION_TYPE_DESCRIPTION:
        len2 = ntohl(* ((int *) buffer));
        buffer[len2 + sizeof(int)] = 0;
	//printf(" The name of type #%d is \"%s\".\n", sender, buffer + sizeof(int));
        break;

      case vrpn_CONNECTION_UDP_DESCRIPTION:
        buffer[len] = 0;
        //printf(" UDP host is \"%s\", port %d.\n", buffer, sender);
        break;

      case vrpn_CONNECTION_LOG_DESCRIPTION:
        buffer[len] = 0;
        //printf(" Log to file \"%s\".\n", buffer);
        break;

    }
  }
}
예제 #21
0
int main( int nArgc, char ** papszArgv )

{
    int bQuiet = FALSE;

    const char *pszDataSource = NULL;

    GNMGFID nFromFID = -1;
    GNMGFID nToFID = -1;
    int nK = 1;
    const char *pszDataset = NULL;
    const char *pszFormat = "ESRI Shapefile";
    const char *pszLayer = NULL;
    GNMNetwork *poDS = NULL;
    OGRLayer* poResultLayer = NULL;
    char  **papszDSCO = NULL, **papszLCO = NULL, **papszALO = NULL;

    operation stOper = op_unknown;

    int          nRet = 0;

    // Check strict compilation and runtime library version as we use C++ API
    if (! GDAL_CHECK_VERSION(papszArgv[0]))
        exit(1);

    EarlySetConfigOptions(nArgc, papszArgv);

/* -------------------------------------------------------------------- */
/*      Register format(s).                                             */
/* -------------------------------------------------------------------- */
    GDALAllRegister();

/* -------------------------------------------------------------------- */
/*      Processing command line arguments.                              */
/* -------------------------------------------------------------------- */
    nArgc = GDALGeneralCmdLineProcessor( nArgc, &papszArgv, GDAL_OF_GNM );

    if( nArgc < 1 )
    {
        exit( -nArgc );
    }

    for( int iArg = 1; iArg < nArgc; iArg++ )
    {
        if( EQUAL(papszArgv[1], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                    papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            CSLDestroy( papszArgv );
            return 0;
        }

        else if( EQUAL(papszArgv[iArg],"--help") )
        {
            Usage();
        }

        else if ( EQUAL(papszArgv[iArg], "--long-usage") )
        {
            Usage(FALSE);
        }

        else if( EQUAL(papszArgv[iArg],"-q") || EQUAL(papszArgv[iArg],"-quiet") )
        {
            bQuiet = TRUE;
        }

        else if( EQUAL(papszArgv[iArg],"dijkstra") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2);
            stOper = op_dijkstra;
            nFromFID = atoi(papszArgv[++iArg]);
            nToFID = atoi(papszArgv[++iArg]);
        }

        else if( EQUAL(papszArgv[iArg],"kpaths") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(3);
            stOper = op_kpaths;
            nFromFID = atoi(papszArgv[++iArg]);
            nToFID = atoi(papszArgv[++iArg]);
            nK = atoi(papszArgv[++iArg]);
        }

        else if( EQUAL(papszArgv[iArg],"resource") )
        {
            stOper = op_resource;
        }

        else if( EQUAL(papszArgv[iArg],"-ds") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszDataset = papszArgv[++iArg];
        }

        else if( EQUAL(papszArgv[iArg],"-f") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszFormat = papszArgv[++iArg];
        }

        else if( EQUAL(papszArgv[iArg],"-l") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszLayer = papszArgv[++iArg];
        }
        else if( EQUAL(papszArgv[iArg],"-dsco") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            papszDSCO = CSLAddString(papszDSCO, papszArgv[++iArg] );
        }
        else if( EQUAL(papszArgv[iArg],"-lco") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            papszLCO = CSLAddString(papszLCO, papszArgv[++iArg] );
        }
        else if( EQUAL(papszArgv[iArg],"-alo") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            papszALO = CSLAddString(papszALO, papszArgv[++iArg] );
        }
        else if( papszArgv[iArg][0] == '-' )
        {
            Usage(CPLSPrintf("Unknown option name '%s'", papszArgv[iArg]));
        }

        else if( pszDataSource == NULL )
            pszDataSource = papszArgv[iArg];
    }

// do the work ////////////////////////////////////////////////////////////////

    if(stOper == op_dijkstra)
    {
        if(pszDataSource == NULL)
            Usage("No network dataset provided");

        if(nFromFID == -1 || nToFID == -1)
            Usage("Invalid input from or to identificators");

        // open
        poDS = (GNMNetwork*) GDALOpenEx( pszDataSource,
                             GDAL_OF_UPDATE | GDAL_OF_GNM, NULL, NULL, NULL );
        if(NULL == poDS)
        {
            fprintf( stderr, "\nFailed to open network at %s\n", pszDataSource);
            nRet = 1;
            goto exit;
        }

        poResultLayer = poDS->GetPath(nFromFID, nToFID, GATDijkstraShortestPath,
                                      papszALO);
        if(NULL == pszDataset)
        {
            ReportOnLayer(poResultLayer, bQuiet == FALSE);
        }
        else
        {
            if(CreateAndFillOutputDataset(poResultLayer, pszDataset, pszFormat,
                                          pszLayer, papszDSCO, papszLCO, bQuiet)
                    != OGRERR_NONE)
            {
                nRet = 1;
                goto exit;
            }
        }
    }
    else if(stOper == op_kpaths)
    {
        if(pszDataSource == NULL)
            Usage("No network dataset provided");

        if(nFromFID == -1 || nToFID == -1)
            Usage("Invalid input from or to identificators");

        // open
        poDS = (GNMNetwork*) GDALOpenEx( pszDataSource,
                             GDAL_OF_UPDATE | GDAL_OF_GNM, NULL, NULL, NULL );
        if(NULL == poDS)
        {
            fprintf( stderr, "\nFailed to open network at %s\n", pszDataSource);
            nRet = 1;
            goto exit;
        }

        if(CSLFindName(papszALO, GNM_MD_NUM_PATHS) == -1)
        {
            CPLDebug("GNM", "No K in options, add %d value", nK);
            papszALO = CSLAddNameValue(papszALO, GNM_MD_NUM_PATHS,
                                       CPLSPrintf("%d", nK));
        }

        poResultLayer = poDS->GetPath(nFromFID, nToFID, GATKShortestPath,
                                      papszALO);

        if(NULL == pszDataset)
        {
            ReportOnLayer(poResultLayer, bQuiet == FALSE);
        }
        else
        {
            if(CreateAndFillOutputDataset(poResultLayer, pszDataset, pszFormat,
                                          pszLayer, papszDSCO, papszLCO, bQuiet)
                    != OGRERR_NONE)
            {
                nRet = 1;
                goto exit;
            }
        }
    }
    else if(stOper == op_resource)
    {
        if(pszDataSource == NULL)
            Usage("No network dataset provided");

        // open
        poDS = (GNMNetwork*) GDALOpenEx( pszDataSource,
                             GDAL_OF_UPDATE | GDAL_OF_GNM, NULL, NULL, NULL );
        if(NULL == poDS)
        {
            fprintf( stderr, "\nFailed to open network at %s\n", pszDataSource);
            nRet = 1;
            goto exit;
        }

        poResultLayer = poDS->GetPath(nFromFID, nToFID, GATConnectedComponents,
                                      papszALO);

        if(NULL == pszDataset)
        {
            ReportOnLayer(poResultLayer, bQuiet == FALSE);
        }
        else
        {
            if(CreateAndFillOutputDataset(poResultLayer, pszDataset, pszFormat,
                                          pszLayer, papszDSCO, papszLCO, bQuiet)
                    != OGRERR_NONE)
            {
                nRet = 1;
                goto exit;
            }
        }
    }
    else
    {
        printf("\nNeed an operation. See help what you can do with gnmanalyse:\n");
        Usage();
    }

 exit:
    CSLDestroy(papszDSCO);
    CSLDestroy(papszLCO);
    CSLDestroy(papszALO);
    CSLDestroy( papszArgv );

    if(poResultLayer != NULL)
        poDS->ReleaseResultSet(poResultLayer);

    if( poDS != NULL )
        GDALClose( (GDALDatasetH)poDS );

    GDALDestroyDriverManager();

    return nRet;
}
예제 #22
0
파일: server.c 프로젝트: Pratheekmb/ARMWork
THREAD_RETURN CYASSL_THREAD server_test(void* args)
{
    SOCKET_T sockfd   = 0;
    SOCKET_T clientfd = 0;

    SSL_METHOD* method = 0;
    SSL_CTX*    ctx    = 0;
    SSL*        ssl    = 0;

    char   msg[] = "I hear you fa shizzle!";
    char   input[80];
    int    idx;
    int    ch;
    int    version = SERVER_DEFAULT_VERSION;
    int    doCliCertCheck = 1;
    int    useAnyAddr = 0;
    int    port = yasslPort;
    int    usePsk = 0;
    int    doDTLS = 0;
    int    useNtruKey   = 0;
    int    nonBlocking  = 0;
    int    trackMemory  = 0;
    int    fewerPackets = 0;
    char*  cipherList = NULL;
    char*  verifyCert = (char*)cliCert;
    char*  ourCert    = (char*)svrCert;
    char*  ourKey     = (char*)svrKey;
    int    argc = ((func_args*)args)->argc;
    char** argv = ((func_args*)args)->argv;

#ifdef HAVE_SNI
    char*  sniHostName = NULL;
#endif

    ((func_args*)args)->return_code = -1; /* error state */

#ifdef NO_RSA
    verifyCert = (char*)cliEccCert;
    ourCert    = (char*)eccCert;
    ourKey     = (char*)eccKey;
#endif
    (void)trackMemory;

    while ((ch = mygetopt(argc, argv, "?dbstnNufp:v:l:A:c:k:S:")) != -1) {
        switch (ch) {
            case '?' :
                Usage();
                exit(EXIT_SUCCESS);

            case 'd' :
                doCliCertCheck = 0;
                break;

            case 'b' :
                useAnyAddr = 1;
                break;

            case 's' :
                usePsk = 1;
                break;

            case 't' :
            #ifdef USE_CYASSL_MEMORY
                trackMemory = 1;
            #endif
                break;

            case 'n' :
                useNtruKey = 1;
                break;

            case 'u' :
                doDTLS  = 1;
                break;

            case 'f' :
                fewerPackets = 1;
                break;

            case 'p' :
                port = atoi(myoptarg);
                #if !defined(NO_MAIN_DRIVER) || defined(USE_WINDOWS_API)
                    if (port == 0)
                        err_sys("port number cannot be 0");
                #endif
                break;

            case 'v' :
                version = atoi(myoptarg);
                if (version < 0 || version > 3) {
                    Usage();
                    exit(MY_EX_USAGE);
                }
                break;

            case 'l' :
                cipherList = myoptarg;
                break;

            case 'A' :
                verifyCert = myoptarg;
                break;

            case 'c' :
                ourCert = myoptarg;
                break;

            case 'k' :
                ourKey = myoptarg;
                break;

            case 'N':
                nonBlocking = 1;
                break;

            case 'S' :
                #ifdef HAVE_SNI
                    sniHostName = myoptarg;
                #endif
                break;

            default:
                Usage();
                exit(MY_EX_USAGE);
        }
    }

    myoptind = 0;      /* reset for test cases */

    /* sort out DTLS versus TLS versions */
    if (version == CLIENT_INVALID_VERSION) {
        if (doDTLS)
            version = CLIENT_DTLS_DEFAULT_VERSION;
        else
            version = CLIENT_DEFAULT_VERSION;
    }
    else {
        if (doDTLS) {
            if (version == 3)
                version = -2;
            else
                version = -1;
        }
    }

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        InitMemoryTracker(); 
#endif

    switch (version) {
#ifndef NO_OLD_TLS
        case 0:
            method = SSLv3_server_method();
            break;

    #ifndef NO_TLS
        case 1:
            method = TLSv1_server_method();
            break;


        case 2:
            method = TLSv1_1_server_method();
            break;

        #endif
#endif

#ifndef NO_TLS
        case 3:
            method = TLSv1_2_server_method();
            break;
#endif
                
#ifdef CYASSL_DTLS
        case -1:
            method = DTLSv1_server_method();
            break;

        case -2:
            method = DTLSv1_2_server_method();
            break;
#endif

        default:
            err_sys("Bad SSL version");
    }

    if (method == NULL)
        err_sys("unable to get method");

    ctx = SSL_CTX_new(method);
    if (ctx == NULL)
        err_sys("unable to get ctx");

    if (cipherList)
        if (SSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
            err_sys("server can't set cipher list 1");

#ifdef CYASSL_LEANPSK
    usePsk = 1;
#endif

#if defined(NO_RSA) && !defined(HAVE_ECC)
    usePsk = 1;
#endif

    if (fewerPackets)
        CyaSSL_CTX_set_group_messages(ctx);

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (!usePsk) {
        if (SSL_CTX_use_certificate_file(ctx, ourCert, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load server cert file, check file and run from"
                    " CyaSSL home dir");
    }
#endif

#ifdef HAVE_NTRU
    if (useNtruKey) {
        if (CyaSSL_CTX_use_NTRUPrivateKey_file(ctx, ourKey)
                                               != SSL_SUCCESS)
            err_sys("can't load ntru key file, "
                    "Please run from CyaSSL home dir");
    }
#endif

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    if (!useNtruKey && !usePsk) {
        if (SSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM)
                                         != SSL_SUCCESS)
            err_sys("can't load server cert file, check file and run from"
                " CyaSSL home dir");
    }
#endif

    if (usePsk) {
#ifndef NO_PSK
        SSL_CTX_set_psk_server_callback(ctx, my_psk_server_cb);
        SSL_CTX_use_psk_identity_hint(ctx, "cyassl server");
        if (cipherList == NULL) {
            const char *defaultCipherList;
            #ifdef HAVE_NULL_CIPHER
                defaultCipherList = "PSK-NULL-SHA256";
            #else
                defaultCipherList = "PSK-AES128-CBC-SHA256";
            #endif
            if (SSL_CTX_set_cipher_list(ctx, defaultCipherList) != SSL_SUCCESS)
                err_sys("server can't set cipher list 2");
        }
#endif
    }

#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
    /* if not using PSK, verify peer with certs */
    if (doCliCertCheck && usePsk == 0) {
        SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |
                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT,0);
        if (SSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
            err_sys("can't load ca file, Please run from CyaSSL home dir");
    }
#endif

#ifdef OPENSSL_EXTRA
    SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif

#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
    /* don't use EDH, can't sniff tmp keys */
    if (cipherList == NULL) {
        if (SSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS)
            err_sys("server can't set cipher list 3");
    }
#endif

#ifdef HAVE_SNI
    if (sniHostName) {
        if (CyaSSL_CTX_UseSNI(ctx, CYASSL_SNI_HOST_NAME, sniHostName,
                                                          XSTRLEN(sniHostName)))
            err_sys("UseSNI failed");
        else
            CyaSSL_CTX_SNI_SetOptions(ctx, CYASSL_SNI_HOST_NAME,
                                                  CYASSL_SNI_ABORT_ON_MISMATCH);
    }
#endif

    ssl = SSL_new(ctx);
    if (ssl == NULL)
        err_sys("unable to get SSL");
    CyaSSL_set_quiet_shutdown(ssl, 1) ;
#ifdef HAVE_CRL
    CyaSSL_EnableCRL(ssl, 0);
    CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, CYASSL_CRL_MONITOR |
                                                     CYASSL_CRL_START_MON);
    CyaSSL_SetCRL_Cb(ssl, CRL_CallBack);
#endif
        osDelay(5000) ;
    tcp_accept(&sockfd, &clientfd, (func_args*)args, port, useAnyAddr, doDTLS);
    if (!doDTLS) 
        CloseSocket(sockfd);

    SSL_set_fd(ssl, clientfd);
    if (usePsk == 0) {
        #if !defined(NO_FILESYSTEM) && defined(OPENSSL_EXTRA)
            CyaSSL_SetTmpDH_file(ssl, dhParam, SSL_FILETYPE_PEM);
        #elif !defined(NO_CERTS)
            SetDH(ssl);  /* repick suites with DHE, higher priority than PSK */
        #endif
    }
        osDelay(5000) ;
#ifndef CYASSL_CALLBACKS
    if (nonBlocking) {
        CyaSSL_set_using_nonblock(ssl, 1);
        tcp_set_nonblocking(&clientfd);
        NonBlockingSSL_Accept(ssl);
    } else if (SSL_accept(ssl) != SSL_SUCCESS) {
        int err = SSL_get_error(ssl, 0);
        char buffer[80];
        printf("error = %d, %s\n", err, ERR_error_string(err, buffer));
        err_sys("SSL_accept failed");
    }
#else
    NonBlockingSSL_Accept(ssl);
#endif
    showPeer(ssl);
        osDelay(5000) ;
    idx = SSL_read(ssl, input, sizeof(input)-1);
    if (idx > 0) {
        input[idx] = 0;
        printf("Client message: %s\n", input);

    }
    else if (idx < 0) {
        int readErr = SSL_get_error(ssl, 0);
        if (readErr != SSL_ERROR_WANT_READ)
            err_sys("SSL_read failed");
    }

    if (SSL_write(ssl, msg, sizeof(msg)) != sizeof(msg))
        err_sys("SSL_write failed");
        
    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ctx);
    
    CloseSocket(clientfd);
    ((func_args*)args)->return_code = 0;

#ifdef USE_CYASSL_MEMORY
    if (trackMemory)
        ShowMemoryTracker();
#endif /* USE_CYASSL_MEMORY */

    return 0;
}
void __cdecl main(int argc, char * argv[])
{
   unsigned char *pszProtocolSequence = DEFAULT_PROTOCOL_SEQUENCE;
   unsigned char *pszEndpoint         = DEFAULT_ENDPOINT;
   unsigned char *pszSpn              = NULL; 
   unsigned int   nMinCalls           = DEFAULT_MIN_CALLS;
   unsigned int   nMaxCalls           = DEFAULT_MAX_CALLS;
   BOOL bDontWait                     = DEFAULT_WAIT_FLAG;
   PSECURITY_DESCRIPTOR pszSecurity   = NULL;
   int i;
   RPC_STATUS status;

   // allow the user to override settings with command line switches
   for (i = 1; i < argc; i++)
   {
      if ((*argv[i] == '-') || (*argv[i] == '/'))
      {
         switch (tolower(*(argv[i]+1)))
         {
            case 'p':
               pszProtocolSequence = argv[++i];
               break;
            case 'e':
               pszEndpoint = argv[++i];
               break;
            case 'a':
               pszSpn = argv[++i];
               break;				
            case 'm':
               nMaxCalls = (unsigned int) atoi(argv[++i]);
               break;
            case 'n':
               nMinCalls = (unsigned int) atoi(argv[++i]);
               break;
            case 'f':
               bDontWait = (unsigned int) atoi(argv[++i]);
               break;
	  
            case 'h':
            case '?':
            default:
               Usage(argv[0]);
         }
      }
      else
         Usage(argv[0]);
   }

   if ((pszProtocolSequence == NULL) || (pszEndpoint == NULL) ||
       (nMinCalls < 1) || (nMinCalls > nMaxCalls))
      Usage(argv[0]);

   status = RpcServerUseProtseqEp(pszProtocolSequence,
                                  nMaxCalls,
                                  pszEndpoint,
                                  pszSecurity);
   printf_s("RpcServerUseProtseqEp returned 0x%x\n", status);
   if (status)
      Quit(status);

   
   // User did not specify spn, construct one.
   if (pszSpn == NULL) {
	   MakeSpn(&pszSpn);
   }
   
   // Using Negotiate as security provider.
   status = RpcServerRegisterAuthInfo(pszSpn,
									  RPC_C_AUTHN_GSS_NEGOTIATE,
									  NULL,
									  NULL);
   
   printf_s("RpcServerRegisterAuthInfo returned 0x%x\n", status);
   if (status) {
	   exit(status);
   }   
   
   status = RpcServerRegisterIfEx(AsyncRPC_ServerIfHandle,
                                  NULL,
                                  NULL,
                                  0,
                                  RPC_C_LISTEN_MAX_CALLS_DEFAULT,
                                  NULL);

   printf_s("Calling RpcServerListen\n");
   status = RpcServerListen(nMinCalls,
                            nMaxCalls,
                            bDontWait);
   printf_s("RpcServerListen returned: 0x%x\n", status);
   if (status)
      Quit(status);

   if (bDontWait)
   {
      printf_s("Calling RpcMgmtWaitServerListen\n");
      status = RpcMgmtWaitServerListen();  // wait operation
      printf_s("RpcMgmtWaitServerListen returned: 0x%x\n", status);
      if (status)
         Quit(status);
   }

   free(pszSecurity);
}
예제 #24
0
int main( int argc, char ** argv )

{
    GDALDatasetH        hDataset, hOutDS;
    int                 i;
    const char          *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff";
    int bFormatExplicitlySet = FALSE;
    GDALDriverH         hDriver;
    GDALDataType        eOutputType = GDT_Unknown;
    char                **papszCreateOptions = NULL;
    GDALProgressFunc    pfnProgress = GDALTermProgress;
    int                 nLUTBins = 256;
    const char         *pszMethod = "minmax";
//    double              dfStdDevMult = 0.0;
    double             *padfScaleMin = NULL;
    double             *padfScaleMax = NULL;
    int               **papanLUTs = NULL;
    int                 iBand;
    const char         *pszConfigFile = NULL;
    int                 bQuiet = FALSE;

    /* Check strict compilation and runtime library version as we use C++ API */
    if (! GDAL_CHECK_VERSION(argv[0]))
        exit(1);
/* -------------------------------------------------------------------- */
/*      Register standard GDAL drivers, and process generic GDAL        */
/*      command options.                                                */
/* -------------------------------------------------------------------- */
    GDALAllRegister();
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Handle command line arguments.                                  */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i],"-of") && i < argc-1 )
        {
            pszFormat = argv[++i];
            bFormatExplicitlySet = TRUE;
        }

        else if( EQUAL(argv[i],"-ot") && i < argc-1 )
        {
            int iType;

            for( iType = 1; iType < GDT_TypeCount; iType++ )
            {
                if( GDALGetDataTypeName((GDALDataType)iType) != NULL
                    && EQUAL(GDALGetDataTypeName((GDALDataType)iType),
                             argv[i+1]) )
                {
                    eOutputType = (GDALDataType) iType;
                }
            }

            if( eOutputType == GDT_Unknown )
            {
                printf( "Unknown output pixel type: %s\n", argv[i+1] );
                Usage();
            }
            i++;
        }

        else if( STARTS_WITH_CI(argv[i], "-s_nodata") )
        {
            // TODO
            i += 1;
        }

        else if( EQUAL(argv[i],"-co") && i < argc-1 )
        {
            papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] );
        }

        else if( STARTS_WITH_CI(argv[i], "-src_scale") && i < argc-2)
        {
            // TODO
            i += 2;
        }

        else if( STARTS_WITH_CI(argv[i], "-dst_scale") && i < argc-2 )
        {
            // TODO
            i += 2;
        }

        else if( EQUAL(argv[i],"-config") && i < argc-1 )
        {
            pszConfigFile = argv[++i];
        }

        else if( EQUAL(argv[i],"-equalize") )
        {
            pszMethod = "equalize";
        }

        else if( EQUAL(argv[i],"-quiet") )
        {
            pfnProgress = GDALDummyProgress;
            bQuiet = TRUE;
        }

        else if( argv[i][0] == '-' )
        {
            printf( "Option %s incomplete, or not recognised.\n\n",
                    argv[i] );
            Usage();
        }
        else if( pszSource == NULL )
        {
            pszSource = argv[i];
        }
        else if( pszDest == NULL )
        {
            pszDest = argv[i];
        }

        else
        {
            printf( "Too many command options.\n\n" );
            Usage();
        }
    }

    if( pszSource == NULL )
    {
        Usage();
    }

/* -------------------------------------------------------------------- */
/*      Attempt to open source file.                                    */
/* -------------------------------------------------------------------- */

    hDataset = GDALOpenShared( pszSource, GA_ReadOnly );

    if( hDataset == NULL )
    {
        fprintf( stderr,
                 "GDALOpen failed - %d\n%s\n",
                 CPLGetLastErrorNo(), CPLGetLastErrorMsg() );
        GDALDestroyDriverManager();
        exit( 1 );
    }

    int nBandCount = GDALGetRasterCount(hDataset);

/* -------------------------------------------------------------------- */
/*      Find the output driver.                                         */
/* -------------------------------------------------------------------- */
    hDriver = GDALGetDriverByName( pszFormat );
    if( hDriver == NULL )
    {
        int iDr;

        printf( "Output driver `%s' not recognised.\n", pszFormat );
        printf( "The following format drivers are configured and support output:\n" );
        for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
        {
            hDriver = GDALGetDriver(iDr);

            if( GDALGetMetadataItem( hDriver, GDAL_DCAP_RASTER, NULL) != NULL &&
                (GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL
                || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY, NULL ) != NULL) )
            {
                printf( "  %s: %s\n",
                        GDALGetDriverShortName( hDriver  ),
                        GDALGetDriverLongName( hDriver ) );
            }
        }
        printf( "\n" );
        Usage();
    }

    if (!bQuiet && pszDest != NULL && !bFormatExplicitlySet)
        CheckExtensionConsistency(pszDest, pszFormat);

/* -------------------------------------------------------------------- */
/*      If histogram equalization is requested, do it now.              */
/* -------------------------------------------------------------------- */
    if( EQUAL(pszMethod,"equalize") )
    {
        ComputeEqualizationLUTs( hDataset, nLUTBins,
                                 &padfScaleMin, &padfScaleMax,
                                 &papanLUTs, pfnProgress );
    }

/* -------------------------------------------------------------------- */
/*      If we have a config file, assume it is for input and read       */
/*      it.                                                             */
/* -------------------------------------------------------------------- */
    else if( pszConfigFile != NULL )
    {
        char **papszLines = CSLLoad( pszConfigFile );
        if( CSLCount(papszLines) == 0 )
            exit( 1 );

        if( CSLCount(papszLines) != nBandCount )
        {
            fprintf( stderr, "Did not get %d lines in config file as expected.\n", nBandCount );
            exit( 1 );
        }

        padfScaleMin = (double *) CPLCalloc(nBandCount,sizeof(double));
        padfScaleMax = (double *) CPLCalloc(nBandCount,sizeof(double));

        for( iBand = 0; iBand < nBandCount; iBand++ )
        {
            int iLUT;
            char **papszTokens = CSLTokenizeString( papszLines[iBand] );

            if( CSLCount(papszTokens) < 3
                || atoi(papszTokens[0]) != iBand+1 )
            {
                fprintf( stderr, "Line %d seems to be corrupt.\n", iBand+1 );
                exit( 1 );
            }

            // Process scale min/max

            padfScaleMin[iBand] = CPLAtof(papszTokens[1]);
            padfScaleMax[iBand] = CPLAtof(papszTokens[2]);

            if( CSLCount(papszTokens) == 3 )
                continue;

            // process lut
            if( papanLUTs == NULL )
            {
                nLUTBins = CSLCount(papszTokens) - 3;
                papanLUTs = (int **) CPLCalloc(sizeof(int*),nBandCount);
            }

            papanLUTs[iBand] = (int *) CPLCalloc(nLUTBins,sizeof(int));

            for( iLUT = 0; iLUT < nLUTBins; iLUT++ )
                papanLUTs[iBand][iLUT] = atoi(papszTokens[iLUT+3]);

            CSLDestroy( papszTokens );
        }
    }

/* -------------------------------------------------------------------- */
/*      If there is no destination, just report the scaling values      */
/*      and luts.                                                       */
/* -------------------------------------------------------------------- */
    if( pszDest == NULL )
    {
        FILE *fpConfig = stdout;
        if( pszConfigFile )
            fpConfig = fopen( pszConfigFile, "w" );

        for( iBand = 0; iBand < nBandCount; iBand++ )
        {
            fprintf( fpConfig, "%d:Band ", iBand+1 );
            if( padfScaleMin != NULL )
                fprintf( fpConfig, "%g:ScaleMin %g:ScaleMax ",
                         padfScaleMin[iBand], padfScaleMax[iBand] );

            if( papanLUTs )
            {
                int iLUT;

                for( iLUT = 0; iLUT < nLUTBins; iLUT++ )
                    fprintf( fpConfig, "%d ", papanLUTs[iBand][iLUT] );
            }
            fprintf( fpConfig, "\n" );
        }

        if( pszConfigFile )
            fclose( fpConfig );

        exit( 0 );
    }

    if (padfScaleMin == NULL || padfScaleMax == NULL)
    {
        fprintf( stderr, "-equalize or -config filename command line options must be specified.\n");
        exit(1);
    }

/* ==================================================================== */
/*      Create a virtual dataset.                                       */
/* ==================================================================== */
    VRTDataset *poVDS;
    EnhanceCBInfo *pasEInfo = (EnhanceCBInfo *)
        CPLCalloc(nBandCount, sizeof(EnhanceCBInfo));

/* -------------------------------------------------------------------- */
/*      Make a virtual clone.                                           */
/* -------------------------------------------------------------------- */
    poVDS = new VRTDataset( GDALGetRasterXSize(hDataset),
                            GDALGetRasterYSize(hDataset) );

    if( GDALGetGCPCount(hDataset) == 0 )
    {
        const char *pszProjection;
        double adfGeoTransform[6];

        pszProjection = GDALGetProjectionRef( hDataset );
        if( pszProjection != NULL && strlen(pszProjection) > 0 )
            poVDS->SetProjection( pszProjection );

        if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
            poVDS->SetGeoTransform( adfGeoTransform );
    }
    else
    {
        poVDS->SetGCPs( GDALGetGCPCount(hDataset),
                        GDALGetGCPs(hDataset),
                        GDALGetGCPProjection( hDataset ) );
    }

    poVDS->SetMetadata( ((GDALDataset*)hDataset)->GetMetadata() );

    for( iBand = 0; iBand < nBandCount; iBand++ )
    {
        VRTSourcedRasterBand   *poVRTBand;
        GDALRasterBand  *poSrcBand;
        GDALDataType    eBandType;

        poSrcBand = ((GDALDataset *) hDataset)->GetRasterBand(iBand+1);

/* -------------------------------------------------------------------- */
/*      Select output data type to match source.                        */
/* -------------------------------------------------------------------- */
        if( eOutputType == GDT_Unknown )
            eBandType = GDT_Byte;
        else
            eBandType = eOutputType;

/* -------------------------------------------------------------------- */
/*      Create this band.                                               */
/* -------------------------------------------------------------------- */
        poVDS->AddBand( eBandType, NULL );
        poVRTBand = (VRTSourcedRasterBand *) poVDS->GetRasterBand( iBand+1 );

/* -------------------------------------------------------------------- */
/*      Create a function based source with info on how to apply the    */
/*      enhancement.                                                    */
/* -------------------------------------------------------------------- */
        pasEInfo[iBand].poSrcBand = poSrcBand;
        pasEInfo[iBand].eWrkType = eBandType;
        pasEInfo[iBand].dfScaleMin = padfScaleMin[iBand];
        pasEInfo[iBand].dfScaleMax = padfScaleMax[iBand];
        pasEInfo[iBand].nLUTBins = nLUTBins;

        if( papanLUTs )
            pasEInfo[iBand].panLUT = papanLUTs[iBand];

        poVRTBand->AddFuncSource( EnhancerCallback, pasEInfo + iBand );

/* -------------------------------------------------------------------- */
/*      copy over some other information of interest.                   */
/* -------------------------------------------------------------------- */
        poVRTBand->CopyCommonInfoFrom( poSrcBand );
    }

/* -------------------------------------------------------------------- */
/*      Write to the output file using CopyCreate().                    */
/* -------------------------------------------------------------------- */
    hOutDS = GDALCreateCopy( hDriver, pszDest, (GDALDatasetH) poVDS,
                             FALSE, papszCreateOptions,
                             pfnProgress, NULL );
    if( hOutDS != NULL )
        GDALClose( hOutDS );

    GDALClose( (GDALDatasetH) poVDS );

    GDALClose( hDataset );

/* -------------------------------------------------------------------- */
/*      Cleanup and exit.                                               */
/* -------------------------------------------------------------------- */
    GDALDumpOpenDatasets( stderr );
    GDALDestroyDriverManager();
    CSLDestroy( argv );
    CSLDestroy( papszCreateOptions );

    exit( 0 );
}
예제 #25
0
파일: bd.c 프로젝트: akipta/hobbyutil
void Initialize(int argc, char **argv)
{
    int ix;

    if (argc != 3 && argc != 4) {
        Usage();
    }

    if (argc == 4) {
        if (argv[1][0] != '-' && argv[1][1] != 'm') {
            Usage();
        }
        histogram = 1;
        argv++;
        argc--;

        /* Initialize histogram array */
        for(ix = 0; ix < ARRAY_SIZE; ix++) {
            diff_count[ix] = 0;
        }
    }

    globals.filename1 = argv[1];
    globals.filename2 = argv[2];

    globals.files_are_different = 0;

    GetFileSize(globals.filename1, &globals.file1_size);
    GetFileSize(globals.filename2, &globals.file2_size);
    if (globals.file1_size < globals.file2_size) {
        globals.compare_size = globals.file1_size;
    } else {
        globals.compare_size = globals.file2_size;
    }

    /* Allocate dynamic memory for the array. */
    if ((globals.rng = (RANGE *) calloc(sizeof(RANGE), ARRAY_SIZE)) == NULL) {
        fprintf(stderr, "Couldn't allocate array memory\n");
        exit(EXIT_MALLOC_FAILED);
    }
    /* Initialize the array elements (even though calloc sets everything
    to zero). */
    for (ix = 0; ix < ARRAY_SIZE; ix++) {
        globals.rng[ix].start = 0;
        globals.rng[ix].end   = 0;
    }
    globals.rng_size  = ARRAY_SIZE;
    globals.rng_numel = 0;

    /* Allocate memory for the buffers */
    if ((globals.buf1 = (char *) malloc(BUFSIZE)) == NULL) {
        fprintf(stderr, "Couldn't allocate memory for buffer 1\n");
        exit(EXIT_MALLOC_FAILED);
    }
    if ((globals.buf2 = (char *) malloc(BUFSIZE)) == NULL) {
        fprintf(stderr, "Couldn't allocate memory for buffer 2\n");
        exit(EXIT_MALLOC_FAILED);
    }

    /* Open the files for reading */
    OpenFile(&globals.ifp1, globals.filename1);
    OpenFile(&globals.ifp2, globals.filename2);
}
예제 #26
0
int __cdecl main(int argc, char **argv)
{
    char *pszIPAdress = NULL;
    char *pszPort = DEFAULT_PORT;   
    char *pszChildFileMappingObj = NULL;
    WSADATA wsaData;
    BOOL bParent = TRUE;
    int nStatus;

    if (argc > 1)
    {
        int i;

        for(i = 1; i < argc; i++)
        {
            if ((argv[i][0] == '-') || (argv[i][0] == '/'))
            {
                switch(tolower(argv[i][1]))
                {
                    case 'c':
                        bParent = FALSE;
                        if (i + 1 < argc)
                            pszChildFileMappingObj = argv[++i];
                        break;
                    case 'i':
                        if (i + 1 < argc)
                            pszIPAdress = argv[++i];
                        break;
                    case 'e':
                        if (i + 1 < argc)               
                            pszPort = argv[++i];
                        break;
                    default:
                        Usage(argv[0]);
                        exit(1);
                }
            }
            else
            {
                Usage(argv[0]);
                exit(1);
            }
        }
    }

    if ((nStatus = WSAStartup(0x202,&wsaData)) != 0)
    {
        fprintf(stderr, "\nWinsock 2 DLL initialization failed: %d\n", nStatus);
        WSACleanup();
        exit(-1);
    }

    if (bParent) // Run as parent
        DoParent(pszIPAdress, pszPort, argv[0]);
    else    // Run as child
        DoChild(pszChildFileMappingObj);

    WSACleanup();

    return 0;
}
예제 #27
0
파일: mkvers.c 프로젝트: openafs/openafs
int
main(int argc, char **argv)
{
    char stampsFile[1024];
    char stateFile[1024];
    char s[1024];
    int i;
    char *baseDir;
    int argDir = 0;
    char *outputFile = NULL;
    char outputFileBuf[sizeof(VERS_FILE) + 4];
    struct stat sbuf;
    time_t versTime;
    int reBuild = 0;
    int code;
    char *cml_prefix = NULL;

    /* initialize cmldir buffer and set default starting directory */
    for (i = 0; i < DEPTH_MAX; i++) {
	strcat(cmldir, "../");
    }
    strcat(cmldir, "src/CML");

    baseDir = strstr(cmldir, CMLDIR_DFLT);

    programName = argv[0];

    for (i = 1; i < argc; i++) {
	if (!strcmp("-d", argv[i])) {
	    i++;
	    if (i >= argc || *argv[i] == '-') {
		printf("Missing directory name for -d option.\n");
		Usage();
	    }
	    baseDir = argv[i];
	    argDir = 1;
	} else if (!strcmp("-o", argv[i])) {
	    i++;
	    if (i >= argc || *argv[i] == '-') {
		printf("Missing output file name for -o option.\n");
		Usage();
	    }
	    outputFile = argv[i];
	} else if (!strcmp("-c", argv[i])) {
	    i++;
	    if (i >= argc || *argv[i] == '-') {
		printf("Missing component for -c option.\n");
		Usage();
	    }
	    cml_prefix = argv[i];
	} else if (!strcmp("-v", argv[i])) {
	    if (cfgFormat == CF_DEFAULT || cfgFormat == CF_VERINFO) {
		cfgFormat = CF_VERINFO;
	    } else {
		printf("Specify only one alternative output format\n");
		Usage();
	    }
	} else if (!strcmp("-t", argv[i])) {
	    if (cfgFormat == CF_DEFAULT || cfgFormat == CF_TEXT) {
		cfgFormat = CF_TEXT;
	    } else {
		printf("Specify only one alternative output format\n");
		Usage();
	    }
	} else if (!strcmp("-x", argv[i])) {
	    if (cfgFormat == CF_DEFAULT || cfgFormat == CF_XML) {
		cfgFormat = CF_XML;
	    } else {
		printf("Specify only one alternative output format\n");
		Usage();
	    }
	} else {
	    printf("%s: Unknown argument.\n", argv[i]);
	    Usage();
	}
    }

    /* set outputFile if not specified */

    if (outputFile == NULL) {
	strcpy(outputFileBuf, VERS_FILE);
	if (cfgFormat == CF_VERINFO) {
	    strcat(outputFileBuf, ".h");
	} else if (cfgFormat == CF_TEXT) {
	    strcat(outputFileBuf, ".txt");
	} else if (cfgFormat == CF_XML) {
	    strcat(outputFileBuf, ".xml");
	} else {
	    strcat(outputFileBuf, ".c");
	}
	outputFile = outputFileBuf;
    }

    /* Determine if we need to create the output file. */

    if ((code = stat(outputFile, &sbuf)) < 0) {
	reBuild = 1;
	versTime = (time_t) 0;	/* indicates no output file. */
    } else {
	versTime = sbuf.st_mtime;
    }

    sprintf(stampsFile, "%s/%s", baseDir, STAMPS);
    code = stat(stampsFile, &sbuf);

    while (code < 0 && errno == ENOENT && !argDir && baseDir > cmldir) {
	/* Try path at next level of depth. */
	baseDir -= sizeof("../") - 1;
	sprintf(stampsFile, "%s/%s", baseDir, STAMPS);
	code = stat(stampsFile, &sbuf);
    }
    if (code == 0 && versTime <= sbuf.st_mtime) {
	reBuild = 1;
    }

    sprintf(stateFile, "%s/%s", baseDir, STATE);

    if (!reBuild) {
	code = stat(stateFile, &sbuf);
	/* dont' check alternate base dir, since it would be reset above */
	if (code == 0 && versTime <= sbuf.st_mtime)
	    reBuild = 1;
    }

    if (!reBuild) {
	printf("Not rebuilding %s since it is up to date.\n", outputFile);
	exit(0);
    }

    if (cml_prefix) {
	cml_string =
	    (char *)malloc(strlen("char ") + strlen(cml_prefix) + strlen(CML_STRING) +
		   1);
	if (!cml_string) {
	    printf("No space to use prefix in cml string, ignoring it.\n");
	    cml_string = CML_VER_DECL;
	} else {
	    (void)sprintf(cml_string, "%s%s%s", "char ", cml_prefix,
			  CML_STRING);
	}
    }

    fpState = fopen(stateFile, "r");
    fpStamps = fopen(stampsFile, "r");
    fpVers = fopen(outputFile, "w");

    if (fpStamps == NULL || fpState == NULL || fpVers == NULL) {
	if (fpVers) {
	    if (cfgFormat == CF_VERINFO) {
		fprintf(fpVers,
			"%s \"No configuration information available\"\n",
			VERINFO_BUILD_STRING);
	    } else if (cfgFormat == CF_TEXT) {
		fprintf(fpVers, "No configuration information available.\n");
	    } else {
		fprintf(fpVers,
			"%sNo configuration information available\";\n",
			cml_string);
		fprintf(fpVers, "%safs??\";\n", AFS_STRING);
	    }
	    fclose(fpVers);
	} else {
	    fprintf(stderr, "Can't write version information to %s.\n",
		    outputFile);
	}
	fprintf(stderr,
		"No configuration information available, continuing...\n");
	exit(1);
    }


    nStates = 0;
    while (fgets(s, sizeof(s), fpState)) {
	if (*s == 'I' || *s == 'N' || *s == 'C' || *s == 'O') {
	    stateDeltas[nStates].type = *s;
	    s[strlen(s) - 1] = '\0';
	    (void)strcpy(stateDeltas[nStates].name, s + 2);
	    nStates++;
	}

    }
    fclose(fpState);

    PrintStamps();
    fclose(fpVers);

    return 0;
}
////////////////////////////////////////////////////////////
// parse_command_line
////////////////////////////////////////////////////////////
static void parse_command_line(int argc, char **argv) {
  bool errflg = false;
  int ch;
  optarg = NULL;
  int option_index = 0;
  char* p;
  k = kK;
  // parse args
  while(!errflg && ((ch = getopt_long(argc, argv, myopts, long_options, &option_index)) != EOF)) {
  //while(!errflg && ((ch = getopt(argc, argv, myopts)) != EOF)) {
    switch(ch) {
    case 'r':
      fastqf = strdup(optarg);
      break;

    case 'f':
      file_of_fastqf = strdup(optarg);
      break;

    case 'z':
      zip_output = true;
      break;

    case 'm':
      merf = strdup(optarg);
      break;

    case 'b':
      bithashf = strdup(optarg);
      break;

    case 'c':
      cutoff = double(strtod(optarg, &p));
      if(p == optarg || cutoff < 0) {
	fprintf(stderr, "Bad mer cutoff value \"%s\"\n",optarg);
	errflg = true;
      }
      break;

    case 'a':
      ATcutf = strdup(optarg);
      break;

    case 't':
      trimq = int(strtol(optarg, &p, 10));
      if(p == optarg || trimq < 0) {
	fprintf(stderr, "Bad trim quality value \"%s\"\n",optarg);
	errflg = true;
      }
      break;

    case 'l':
      trim_t = int(strtol(optarg, &p, 10));
      if(p == optarg || trim_t < 1) {
	fprintf(stderr, "Bad trim threshold \"%s\"\n",optarg);
	errflg = true;
      }
      break;

    case 'q': 
      Read::quality_scale = int(strtol(optarg, &p, 10));
      if(p == optarg || Read::quality_scale < -1) {
	fprintf(stderr, "Bad quality value scale \"%s\"\n",optarg);
	errflg = true;
      }
      break;

    case 'C':
      contrail_out = true;
      break;

    case 'u':
      uncorrected_out = true;
      break;  

    case 'p':
      threads = int(strtol(optarg, &p, 10));
      if(p == optarg || threads <= 0) {
	fprintf(stderr, "Bad number of threads \"%s\"\n",optarg);
	errflg = true;
      }
      break;

    case 1000:
      orig_headers = true;
      break;

    case 1001:
      out_log = true;
      break;

    case 'v':
      hammerf = strdup(optarg);
      break;
      
    case 'h':
      Usage(argv[0]);
      exit(EXIT_FAILURE);

    case '?':
      fprintf (stderr, "Unrecognized option -%c\n", optopt);

    default:
      errflg = true;
    }
  }

  // for some reason, optind is not advancing properly so this
  // always returns an error

  // return errors
  /*
  if(errflg || optind != argc-1) {
    Usage(argv[0]);
    exit(EXIT_FAILURE);
  }
  */

  ////////////////////////////////////////
  // correct user input errors
  ////////////////////////////////////////
  if(fastqf == NULL && file_of_fastqf == NULL) {
    cerr << "Must provide a fastq file of reads (-r) or a file containing a list of fastq files of reads (-f)" << endl;
    exit(EXIT_FAILURE);
  }

  if(k == 0) {
    cerr << "Must provide kmer size (-k)" << endl;
    exit(EXIT_FAILURE);
  }

  if(merf != NULL) {
    if(cutoff == 0 && ATcutf == NULL) {
      cerr << "Must provide a trusted/untrusted kmer cutoff (-c) or a file containing the cutoff as a function of the AT content (-a)" << endl;
      exit(EXIT_FAILURE);
    }
  } else if(bithashf == NULL && hammerf == NULL) {
    cerr << "Must provide a file of kmer counts (-m) or a saved bithash (-b) or solid kmers from Hammer (-v)" << endl;
    exit(EXIT_FAILURE);
  }
  
}
예제 #29
0
int main( int argc, char ** argv )

{
    const char         *pszLocX = NULL, *pszLocY = NULL;
    const char         *pszSrcFilename = NULL;
    const char         *pszSourceSRS = NULL;
    std::vector<int>   anBandList;
    bool               bAsXML = false, bLIFOnly = false;
    bool               bQuiet = false, bValOnly = false;

    GDALAllRegister();
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    int i;

    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i],"-b") && i < argc-1 )
        {
            anBandList.push_back( atoi(argv[++i]) );
        }
        else if( EQUAL(argv[i],"-l_srs") && i < argc-1 )
        {
            pszSourceSRS = SanitizeSRS(argv[++i]);
        }
        else if( EQUAL(argv[i],"-geoloc") )
        {
            pszSourceSRS = "-geoloc";
        }
        else if( EQUAL(argv[i],"-wgs84") )
        {
            pszSourceSRS = SanitizeSRS("WGS84");
        }
        else if( EQUAL(argv[i],"-xml") )
        {
            bAsXML = true;
        }
        else if( EQUAL(argv[i],"-lifonly") )
        {
            bLIFOnly = true;
            bQuiet = true;
        }
        else if( EQUAL(argv[i],"-valonly") )
        {
            bValOnly = true;
            bQuiet = true;
        }
        else if( argv[i][0] == '-' && !isdigit(argv[i][1]) )
            Usage();

        else if( pszSrcFilename == NULL )
            pszSrcFilename = argv[i];

        else if( pszLocX == NULL )
            pszLocX = argv[i];

        else if( pszLocY == NULL )
            pszLocY = argv[i];

        else
            Usage();
    }

    if( pszSrcFilename == NULL || (pszLocX != NULL && pszLocY == NULL) )
        Usage();

/* -------------------------------------------------------------------- */
/*      Open source file.                                               */
/* -------------------------------------------------------------------- */
    GDALDatasetH hSrcDS = NULL;

    hSrcDS = GDALOpen( pszSrcFilename, GA_ReadOnly );
    if( hSrcDS == NULL )
        exit( 1 );

/* -------------------------------------------------------------------- */
/*      Setup coordinate transformation, if required                    */
/* -------------------------------------------------------------------- */
    OGRSpatialReferenceH hSrcSRS = NULL, hTrgSRS = NULL;
    OGRCoordinateTransformationH hCT = NULL;
    if( pszSourceSRS != NULL && !EQUAL(pszSourceSRS,"-geoloc") )
    {

        hSrcSRS = OSRNewSpatialReference( pszSourceSRS );
        hTrgSRS = OSRNewSpatialReference( GDALGetProjectionRef( hSrcDS ) );

        hCT = OCTNewCoordinateTransformation( hSrcSRS, hTrgSRS );
        if( hCT == NULL )
            exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      If no bands were requested, we will query them all.             */
/* -------------------------------------------------------------------- */
    if( anBandList.size() == 0 )
    {
        for( i = 0; i < GDALGetRasterCount( hSrcDS ); i++ )
            anBandList.push_back( i+1 );
    }
    
/* -------------------------------------------------------------------- */
/*      Turn the location into a pixel and line location.               */
/* -------------------------------------------------------------------- */
    int inputAvailable = 1;
    double dfGeoX;
    double dfGeoY;
    CPLString osXML;

    if( pszLocX == NULL && pszLocY == NULL )
    {
        if (fscanf(stdin, "%lf %lf", &dfGeoX, &dfGeoY) != 2)
        {
            inputAvailable = 0;
        }
    }
    else
    {
        dfGeoX = CPLAtof(pszLocX);
        dfGeoY = CPLAtof(pszLocY);
    }

    while (inputAvailable)
    {
        int iPixel, iLine;

        if (hCT)
        {
            if( !OCTTransform( hCT, 1, &dfGeoX, &dfGeoY, NULL ) )
                exit( 1 );
        }
    
        if( pszSourceSRS != NULL )
        {
            double adfGeoTransform[6], adfInvGeoTransform[6];
    
            if( GDALGetGeoTransform( hSrcDS, adfGeoTransform ) != CE_None )
                exit( 1 );
    
            GDALInvGeoTransform( adfGeoTransform, adfInvGeoTransform );
    
            iPixel = (int) floor(
                adfInvGeoTransform[0] 
                + adfInvGeoTransform[1] * dfGeoX
                + adfInvGeoTransform[2] * dfGeoY );
            iLine = (int) floor(
                adfInvGeoTransform[3] 
                + adfInvGeoTransform[4] * dfGeoX
                + adfInvGeoTransform[5] * dfGeoY );
        }
        else
        {
            iPixel = (int) floor(dfGeoX);
            iLine  = (int) floor(dfGeoY);
        }

    /* -------------------------------------------------------------------- */
    /*      Prepare report.                                                 */
    /* -------------------------------------------------------------------- */
        CPLString osLine;
    
        if( bAsXML )
        {
            osLine.Printf( "<Report pixel=\"%d\" line=\"%d\">", 
                          iPixel, iLine );
            osXML += osLine;
        }
        else if( !bQuiet )
        {
            printf( "Report:\n" );
            printf( "  Location: (%dP,%dL)\n", iPixel, iLine );
        }

        int bPixelReport = TRUE;

        if( iPixel < 0 || iLine < 0 
            || iPixel >= GDALGetRasterXSize( hSrcDS )
            || iLine  >= GDALGetRasterYSize( hSrcDS ) )
        {
            if( bAsXML )
                osXML += "<Alert>Location is off this file! No further details to report.</Alert>";
            else if( bValOnly )
                printf("\n");
            else if( !bQuiet )
                printf( "\nLocation is off this file! No further details to report.\n");
            bPixelReport = FALSE;
        }
        
    /* -------------------------------------------------------------------- */
    /*      Process each band.                                              */
    /* -------------------------------------------------------------------- */
        for( i = 0; bPixelReport && i < (int) anBandList.size(); i++ )
        {
            GDALRasterBandH hBand = GDALGetRasterBand( hSrcDS, anBandList[i] );
            if (hBand == NULL)
                continue;
    
            if( bAsXML )
            {
                osLine.Printf( "<BandReport band=\"%d\">", anBandList[i] );
                osXML += osLine;
            }
            else if( !bQuiet )
            {
                printf( "  Band %d:\n", anBandList[i] );
            }
    
    /* -------------------------------------------------------------------- */
    /*      Request location info for this location.  It is possible        */
    /*      only the VRT driver actually supports this.                     */
    /* -------------------------------------------------------------------- */
            CPLString osItem;
            
            osItem.Printf( "Pixel_%d_%d", iPixel, iLine );
            
            const char *pszLI = GDALGetMetadataItem( hBand, osItem, "LocationInfo");
    
            if( pszLI != NULL )
            {
                if( bAsXML )
                    osXML += pszLI;
                else if( !bQuiet )
                    printf( "    %s\n", pszLI );
                else if( bLIFOnly )
                {
                    /* Extract all files, if any. */
                 
                    CPLXMLNode *psRoot = CPLParseXMLString( pszLI );
                    
                    if( psRoot != NULL 
                        && psRoot->psChild != NULL
                        && psRoot->eType == CXT_Element
                        && EQUAL(psRoot->pszValue,"LocationInfo") )
                    {
                        CPLXMLNode *psNode;
    
                        for( psNode = psRoot->psChild;
                             psNode != NULL;
                             psNode = psNode->psNext )
                        {
                            if( psNode->eType == CXT_Element
                                && EQUAL(psNode->pszValue,"File") 
                                && psNode->psChild != NULL )
                            {
                                char* pszUnescaped = CPLUnescapeString(
                                    psNode->psChild->pszValue, NULL, CPLES_XML);
                                printf( "%s\n", pszUnescaped );
                                CPLFree(pszUnescaped);
                            }
                        }
                    }
                    CPLDestroyXMLNode( psRoot );
                }
            }
    
    /* -------------------------------------------------------------------- */
    /*      Report the pixel value of this band.                            */
    /* -------------------------------------------------------------------- */
            double adfPixel[2];
    
            if( GDALRasterIO( hBand, GF_Read, iPixel, iLine, 1, 1, 
                              adfPixel, 1, 1, GDT_CFloat64, 0, 0) == CE_None )
            {
                CPLString osValue;
    
                if( GDALDataTypeIsComplex( GDALGetRasterDataType( hBand ) ) )
                    osValue.Printf( "%.15g+%.15gi", adfPixel[0], adfPixel[1] );
                else
                    osValue.Printf( "%.15g", adfPixel[0] );
    
                if( bAsXML )
                {
                    osXML += "<Value>";
                    osXML += osValue;
                    osXML += "</Value>";
                }
                else if( !bQuiet )
                    printf( "    Value: %s\n", osValue.c_str() );
                else if( bValOnly )
                    printf( "%s\n", osValue.c_str() );
    
                // Report unscaled if we have scale/offset values.
                int bSuccess;
                
                double dfOffset = GDALGetRasterOffset( hBand, &bSuccess );
                double dfScale  = GDALGetRasterScale( hBand, &bSuccess );
    
                if( dfOffset != 0.0 || dfScale != 1.0 )
                {
                    adfPixel[0] = adfPixel[0] * dfScale + dfOffset;
                    adfPixel[1] = adfPixel[1] * dfScale + dfOffset;
    
                    if( GDALDataTypeIsComplex( GDALGetRasterDataType( hBand ) ) )
                        osValue.Printf( "%.15g+%.15gi", adfPixel[0], adfPixel[1] );
                    else
                        osValue.Printf( "%.15g", adfPixel[0] );
    
                    if( bAsXML )
                    {
                        osXML += "<DescaledValue>";
                        osXML += osValue;
                        osXML += "</DescaledValue>";
                    }
                    else if( !bQuiet )
                        printf( "    Descaled Value: %s\n", osValue.c_str() );
                }
            }
    
            if( bAsXML )
                osXML += "</BandReport>";
        }

        osXML += "</Report>";
    
        if( (pszLocX != NULL && pszLocY != NULL)  ||
            (fscanf(stdin, "%lf %lf", &dfGeoX, &dfGeoY) != 2) )
        {
            inputAvailable = 0;
        }
            
    }

/* -------------------------------------------------------------------- */
/*      Finalize xml report and print.                                  */
/* -------------------------------------------------------------------- */
    if( bAsXML )
    {
        CPLXMLNode *psRoot;
        char *pszFormattedXML;


        psRoot = CPLParseXMLString( osXML );
        pszFormattedXML = CPLSerializeXMLTree( psRoot );
        CPLDestroyXMLNode( psRoot );

        printf( "%s", pszFormattedXML );
        CPLFree( pszFormattedXML );
    }

/* -------------------------------------------------------------------- */
/*      Cleanup                                                         */
/* -------------------------------------------------------------------- */
    if (hCT) {
        OSRDestroySpatialReference( hSrcSRS );
        OSRDestroySpatialReference( hTrgSRS );
        OCTDestroyCoordinateTransformation( hCT );
    }

    if (hSrcDS)
        GDALClose(hSrcDS);

    GDALDumpOpenDatasets( stderr );
    GDALDestroyDriverManager();

    CSLDestroy( argv );

    return 0;
}
예제 #30
0
int
main(int argc, char *argv[])
{
	int opt;
	ssize_t readlen;
	unsigned char pfkey_buf[256];
	struct sadb_msg *msg;
	int fork_after_register;
	char *pidfilename;
	char *infilename;
	char *outfilename;

	static int ah_register;
	static int esp_register;
	static int ipip_register;
	static int ipcomp_register;

	static struct option long_options[] =
	{
		{"help",        no_argument, 0, 'h'},
		{"daemon",      required_argument, 0, 'f'},
		{"dumpfile",    required_argument, 0, 'd'},
		{"encodefile",  required_argument, 0, 'e'},
		{"ah",          no_argument, &ah_register, 1},
		{"esp",         no_argument, &esp_register, 1},
		{"ipip",        no_argument, &ipip_register, 1},
		{"ipcomp",      no_argument, &ipcomp_register, 1},
	};

	ah_register   = 0;
	esp_register  = 0;
	ipip_register = 0;
	ipcomp_register=0;
	dienow = 0;
	fork_after_register=0;

	pidfilename = NULL;
	infilename  = NULL;
	outfilename = NULL;
	
	progname = argv[0];
	if(strrchr(progname, '/')) {
		progname=strrchr(progname, '/')+1;
	}
	
	while((opt = getopt_long(argc, argv, "hd:e:f:",
				 long_options, NULL)) !=  EOF) {
		switch(opt) {
		case 'f':
			pidfilename=optarg;
			fork_after_register=1;
			break;

		case 'd':
			infilename = optarg;
			break;
			
		case 'e':
			outfilename = optarg;
			break;
			
		case 'h':
			Usage(progname);
			break;
		case '0':
			/* it was a long option with a flag */
			break;
		}
	}

	if(infilename  == NULL &&
	   outfilename == NULL)
	{
		if((pfkey_sock = socket(PF_KEY, SOCK_RAW, PF_KEY_V2) ) < 0)
		{
			fprintf(stderr, "%s: failed to open PF_KEY family socket: %s\n",
				progname, strerror(errno));
			exit(1);
		}

		if(ah_register == 0 &&
		   esp_register== 0 &&
		   ipip_register==0 &&
		   ipcomp_register==0) {
			ah_register=1;
			esp_register=1;
			ipip_register=1;
			ipcomp_register=1;
		}
		
		if(ah_register) {
			pfkey_register(SADB_SATYPE_AH);
		}
		if(esp_register) {
			pfkey_register(SADB_SATYPE_ESP);
		}
		if(ipip_register) {
			pfkey_register(SADB_X_SATYPE_IPIP);
		}
		if(ipcomp_register) {
			pfkey_register(SADB_X_SATYPE_COMP);
		}

		if(fork_after_register) {
			/*
			 * to aid in regression testing, we offer to register 
			 * everything first, and then we fork. As part of this
			 * we write the PID of the new process to a file
			 * provided.
			 */
			int pid;
			FILE *pidfile;
			
			fflush(stdout);
			fflush(stderr);
			
			pid=fork();
			if(pid!=0) {
				/* in parent! */
				exit(0);
			}
			
			if((pidfile=fopen(pidfilename, "w"))==NULL) {
				perror(pidfilename);
			} else {
				fprintf(pidfile, "%d", getpid());
				fclose(pidfile);
			}
		}

	} else if(infilename != NULL) {
		pfkey_sock = open(infilename, O_RDONLY);
		if(pfkey_sock < 0) {
			fprintf(stderr, "%s: failed to open %s: %s\n",
				progname, infilename, strerror(errno));
			exit(1);
		}
	} else if(outfilename != NULL) {
		/* call encoder */
		exit(1);
	}
			
	signal(SIGINT,  controlC);
	signal(SIGTERM, controlC);

	while((readlen = read(pfkey_sock, pfkey_buf, sizeof(pfkey_buf))) > 0) {
		msg = (struct sadb_msg *)pfkey_buf;
		
		/* first, see if we got enough for an sadb_msg */
		if((size_t)readlen < sizeof(struct sadb_msg)) {
			printf("%s: runt packet of size: %d (<%lu)\n",
			       progname, (int)readlen, (unsigned long)sizeof(struct sadb_msg));
			continue;
		}
		
		/* okay, we got enough for a message, print it out */
		printf("\npfkey v%d msg. type=%d(%s) seq=%d len=%d pid=%d errno=%d satype=%d(%s)\n",
		       msg->sadb_msg_version,
		       msg->sadb_msg_type,
		       pfkey_v2_sadb_type_string(msg->sadb_msg_type),
		       msg->sadb_msg_seq,
		       msg->sadb_msg_len,
		       msg->sadb_msg_pid,
		       msg->sadb_msg_errno,
		       msg->sadb_msg_satype,
		       satype2name(msg->sadb_msg_satype));
		
		if((size_t)readlen != msg->sadb_msg_len * IPSEC_PFKEYv2_ALIGN)
		{
			printf("%s: packet size read from socket=%d doesn't equal sadb_msg_len %d * %u; message not decoded\n",
			       progname,
			       (int) readlen, 
			       msg->sadb_msg_len,
			       (int) IPSEC_PFKEYv2_ALIGN);
			continue;
		}

		pfkey_print(msg, stdout);
	}
	printf("%s: exited normally\n", progname);
	exit(0);
}