コード例 #1
0
int main(int argc, const char *argv[]) {
    
    const char* argument;
    
    long int initial_timestamp;
    float initial_lat, initial_lng, initial_alt;
    float burst_alt, ascent_rate, drag_coeff, rmswinderror;
    int descent_mode;
    int scenario_idx, n_scenarios;
    int alarm_time;
    char* endptr;       // used to check for errors on strtod calls 
    
    wind_file_cache_t* file_cache;
    dictionary*        scenario = NULL;
    
    // configure command-line options parsing
    void *options = gopt_sort(&argc, argv, gopt_start(
        gopt_option('h', 0, gopt_shorts('h', '?'), gopt_longs("help")),
        gopt_option('z', 0, gopt_shorts(0), gopt_longs("version")),
        gopt_option('v', GOPT_REPEAT, gopt_shorts('v'), gopt_longs("verbose")),
        gopt_option('o', GOPT_ARG, gopt_shorts('o'), gopt_longs("output")),
        gopt_option('k', GOPT_ARG, gopt_shorts('k'), gopt_longs("kml")),
        gopt_option('t', GOPT_ARG, gopt_shorts('t'), gopt_longs("start_time")),
        gopt_option('i', GOPT_ARG, gopt_shorts('i'), gopt_longs("data_dir")),
        gopt_option('d', 0, gopt_shorts('d'), gopt_longs("descending")),
        gopt_option('e', GOPT_ARG, gopt_shorts('e'), gopt_longs("wind_error")),
        gopt_option('a', GOPT_ARG, gopt_shorts('a'), gopt_longs("alarm"))
    ));

    if (gopt(options, 'h')) {
        // Help!
        // Print usage information
        printf("Usage: %s [options] [scenario files]\n", argv[0]);
        printf("Options:\n\n");
        printf(" -h --help               Display this information.\n");
        printf(" --version               Display version information.\n");
        printf(" -v --verbose            Display more information while running,\n");
        printf("                           Use -vv, -vvv etc. for even more verbose output.\n");
        printf(" -t --start_time <int>   Start time of model, defaults to current time.\n");
        printf("                           Should be a UNIX standard format timestamp.\n");
        printf(" -o --output <file>      Output file for CSV data, defaults to stdout. Overrides scenario.\n");
        printf(" -k --kml <file>         Output KML file.\n");
        printf(" -d --descending         We are in the descent phase of the flight, i.e. after\n");
        printf("                           burst or cutdown. burst_alt and ascent_rate ignored.\n");
        printf(" -i --data_dir <dir>     Input directory for wind data, defaults to current dir.\n\n");
        printf(" -e --wind_error <err>   RMS windspeed error (m/s).\n");
        printf(" -a --alarm <seconds>    Use alarm() to kill pred incase it hangs.\n");
        printf("The scenario file is an INI-like file giving the launch scenario. If it is\n");
        printf("omitted, the scenario is read from standard input.\n");
      exit(0);
    }

    if (gopt(options, 'z')) {
      // Version information
      printf("Landing Prediction version: %s\nCopyright (c) CU Spaceflight 2009\n", VERSION);
      exit(0);
    }

    if (gopt_arg(options, 'a', &argument) && strcmp(argument, "-")) {
      alarm_time = strtol(argument, &endptr, 0);
      if (endptr == argument) {
        fprintf(stderr, "ERROR: %s: invalid alarm length\n", argument);
        exit(1);
      }
      alarm(alarm_time);
    }
    
    verbosity = gopt(options, 'v');
    
    if (gopt(options, 'd'))
        descent_mode = DESCENT_MODE_DESCENDING;
    else
        descent_mode = DESCENT_MODE_NORMAL;
      
    if (gopt_arg(options, 'k', &argument) && strcmp(argument, "-")) {
      kml_file = fopen(argument, "wb");
      if (!kml_file) {
        fprintf(stderr, "ERROR: %s: could not open KML file for output\n", argument);
        exit(1);
      }
    }
    else
      kml_file = NULL;

    if (gopt_arg(options, 't', &argument) && strcmp(argument, "-")) {
      initial_timestamp = strtol(argument, &endptr, 0);
      if (endptr == argument) {
        fprintf(stderr, "ERROR: %s: invalid start timestamp\n", argument);
        exit(1);
      }
    } else {
      initial_timestamp = time(NULL);
    }
    
    if (!(gopt_arg(options, 'i', &data_dir) && strcmp(data_dir, "-")))
      data_dir = "./";


    // populate wind data file cache
    file_cache = wind_file_cache_new(data_dir);

    // read in flight parameters
    n_scenarios = argc - 1;
    if(n_scenarios == 0) {
        // we'll parse from std in
        n_scenarios = 1;
    }

    for(scenario_idx = 0; scenario_idx < n_scenarios; ++scenario_idx) {
        char* scenario_output = NULL;

        if(argc > scenario_idx+1) {
            scenario = iniparser_load(argv[scenario_idx+1]);
        } else {
            scenario = iniparser_loadfile(stdin);
        }

        if(!scenario) {
            fprintf(stderr, "ERROR: could not parse scanario file.\n");
            exit(1);
        }

        if(verbosity > 1) {
            fprintf(stderr, "INFO: Parsed scenario file:\n");
            iniparser_dump_ini(scenario, stderr);
        }

        scenario_output = iniparser_getstring(scenario, "output:filename", NULL);

        if (gopt_arg(options, 'o', &argument) && strcmp(argument, "-")) {
            if(verbosity > 0) {
                fprintf(stderr, "INFO: Writing output to file specified on command line: %s\n", argument);
            }
            output = fopen(argument, "wb");
            if (!output) {
                fprintf(stderr, "ERROR: %s: could not open CSV file for output\n", argument);
                exit(1);
            }
        } else if (scenario_output != NULL) {
            if(verbosity > 0) {
                fprintf(stderr, "INFO: Writing output to file specified in scenario: %s\n", scenario_output);
            }
            output = fopen(scenario_output, "wb");
            if (!output) {
                fprintf(stderr, "ERROR: %s: could not open CSV file for output\n", scenario_output);
                exit(1);
            }
        } else {
            if(verbosity > 0) {
                fprintf(stderr, "INFO: Writing output to stdout.\n");
            }
            output = stdout;
        }

        // write KML header
        if (kml_file)
            start_kml();

        // The observant amongst you will notice that there are default values for
        // *all* keys. This information should not be spread around too well.
        // Unfortunately, this means we lack some error checking.

        initial_lat = iniparser_getdouble(scenario, "launch-site:latitude", 0.0);
        initial_lng = iniparser_getdouble(scenario, "launch-site:longitude", 0.0);
        initial_alt = iniparser_getdouble(scenario, "launch-site:altitude", 0.0);

        ascent_rate = iniparser_getdouble(scenario, "altitude-model:ascent-rate", 1.0);

        // The 1.1045 comes from a magic constant buried in
        // ~cuspaceflight/public_html/predict/index.php.
        drag_coeff = iniparser_getdouble(scenario, "altitude-model:descent-rate", 1.0) * 1.1045;

        burst_alt = iniparser_getdouble(scenario, "altitude-model:burst-altitude", 1.0);

        rmswinderror = iniparser_getdouble(scenario, "atmosphere:wind-error", 0.0);
        if(gopt_arg(options, 'e', &argument) && strcmp(argument, "-")) {
            rmswinderror = strtod(argument, &endptr);
            if (endptr == argument) {
                fprintf(stderr, "ERROR: %s: invalid RMS wind speed error\n", argument);
                exit(1);
            }
        }

        {
            int year, month, day, hour, minute, second;
            year = iniparser_getint(scenario, "launch-time:year", -1);
            month = iniparser_getint(scenario, "launch-time:month", -1);
            day = iniparser_getint(scenario, "launch-time:day", -1);
            hour = iniparser_getint(scenario, "launch-time:hour", -1);
            minute = iniparser_getint(scenario, "launch-time:minute", -1);
            second = iniparser_getint(scenario, "launch-time:second", -1);

            if((year >= 0) && (month >= 0) && (day >= 0) && (hour >= 0)
                    && (minute >= 0) && (second >= 0)) 
            {
                struct tm timeval = { 0 };
                time_t scenario_launch_time = -1;

                if(verbosity > 0) {
                    fprintf(stderr, "INFO: Using launch time from scenario: "
                            "%i/%i/%i %i:%i:%i\n",
                            year, month, day, hour, minute, second);
                }

                timeval.tm_sec = second;
                timeval.tm_min = minute;
                timeval.tm_hour = hour;
                timeval.tm_mday = day; /* 1 - 31 */
                timeval.tm_mon = month - 1; /* 0 - 11 */
                timeval.tm_year = year - 1900; /* f**k you Millenium Bug! */

#ifndef _BSD_SOURCE
#               warning This version of mktime does not allow explicit setting of timezone. 
#else
                timeval.tm_zone = "UTC";
#endif

                scenario_launch_time = mktime(&timeval);
                if(scenario_launch_time <= 0) {
                    fprintf(stderr, "ERROR: Launch time in scenario is invalid\n");
                    exit(1);
                } else {
                    initial_timestamp = scenario_launch_time;
                }
            }
        }

        if(verbosity > 0) {
            fprintf(stderr, "INFO: Scenario loaded:\n");
            fprintf(stderr, "    - Initial latitude  : %lf deg N\n", initial_lat);
            fprintf(stderr, "    - Initial longitude : %lf deg E\n", initial_lng);
            fprintf(stderr, "    - Initial altitude  : %lf m above sea level\n", initial_alt);
            fprintf(stderr, "    - Initial timestamp : %li\n", initial_timestamp);
            fprintf(stderr, "    - Drag coeff.       : %lf\n", drag_coeff);
            if(!descent_mode) {
                fprintf(stderr, "    - Ascent rate       : %lf m/s\n", ascent_rate);
                fprintf(stderr, "    - Burst alt.        : %lf m\n", burst_alt);
            }
            fprintf(stderr, "    - Windspeed err.    : %f m/s\n", rmswinderror);
        }
        
        {
            // do the actual stuff!!
            altitude_model_t* alt_model = altitude_model_new(descent_mode, burst_alt, 
                                                             ascent_rate, drag_coeff);
            if(!alt_model) {
                    fprintf(stderr, "ERROR: error initialising altitude profile\n");
                    exit(1);
            }

            if (!run_model(file_cache, alt_model, 
                           initial_lat, initial_lng, initial_alt, initial_timestamp,
                           rmswinderror)) {
                    fprintf(stderr, "ERROR: error during model run!\n");
                    exit(1);
            }

            altitude_model_free(alt_model);
        }

        // release the scenario
        iniparser_freedict(scenario);
        
        // write footer to KML and close output files
        if (kml_file) {
            finish_kml();
            fclose(kml_file);
        }

        if (output != stdout) {
            fclose(output);
        }
    }

    // release gopt data, 
    gopt_free(options);

    // release the file cache resources.
    wind_file_cache_free(file_cache);

    return 0;
}
コード例 #2
0
ファイル: proclaunch.c プロジェクト: luke-chang/gecko-1
int main(int argc, char **argv) {
  int children = 0;
  int maxtime = 0;
  int passedtime = 0;
  dictionary *dict = NULL;

  // Command line handling
  if (argc == 1 || (0 == strcmp(argv[1], "-h")) || (0 == strcmp(argv[1], "--help"))) {
    printf("ProcLauncher takes an ini file.  Specify the ini file as the only\n");
    printf("parameter of the command line:\n");
    printf("proclauncher my.ini\n\n");
    printf("The ini file has the form:\n");
    printf("[main]\n");
    printf("children=child1,child2  ; These comma separated values are sections\n");
    printf("maxtime=60              ; Max time this process lives\n");
    printf("[child1]                ; Here is a child section\n");
    printf("children=3              ; You can have grandchildren: this spawns 3 of them for child1\n");
    printf("maxtime=30              ; Max time, note it's in seconds. If this time\n");
    printf("                        ; is > main:maxtime then the child process will be\n");
    printf("                        ; killed when the parent exits. Also, grandchildren\n");
    printf("[child2]                ; inherit this maxtime and can't change it.\n");
    printf("maxtime=25              ; You can call these sections whatever you want\n");
    printf("children=0              ; as long as you reference them in a children attribute\n");
    printf("....\n");
    return 0;
  } else if (argc == 2) {
    // This is ini file mode:
    // proclauncher <inifile>
    dict = iniparser_load(argv[1]);

  } else if (argc == 3) {
    // Then we've been called in child process launching mode:
    // proclauncher <children> <maxtime>
    children = atoi(argv[1]);
    maxtime = atoi(argv[2]);
  }

  if (dict) {
    /* Dict operation */
    char *childlist = iniparser_getstring(dict, "main:children", NULL);
    maxtime = iniparser_getint(dict, (char*)"main:maxtime", 10);;
	if (childlist) {
      int c = 0, m = 10;
      char childkey[50], maxkey[50];
      char cmd[25];
      char *token = strtok(childlist, ",");

      while (token) {
        // Reset defaults
        memset(childkey, 0, 50);
        memset(maxkey, 0, 50);
        memset(cmd, 0, 25);
        c = 0;
        m = 10;

        sprintf(childkey, "%s:children", token);
        sprintf(maxkey, "%s:maxtime", token);
        c = iniparser_getint(dict, childkey, 0);
        m = iniparser_getint(dict, maxkey, 10);

        // Launch the child process
        #ifdef _WIN32
          launchWindows(c, m);
        #else
          sprintf(cmd, "./proclaunch %d %d &", c, m);
          system(cmd);
        #endif

        // Get the next child entry
        token = strtok(NULL, ",");
      }
    }
    iniparser_freedict(dict);
  } else {
    // Child Process operation - put on your recursive thinking cap
    char cmd[25];
    // This is launching grandchildren, there are no great grandchildren, so we
    // pass in a 0 for the children to spawn.
    #ifdef _WIN32
      while(children > 0) {
        launchWindows(0, maxtime);
        children--;
      }
    #else
      sprintf(cmd, "./proclaunch %d %d &", 0, maxtime);
      printf("Launching child process: %s\n", cmd);
      while (children  > 0) {
        system(cmd);
        children--;
      }
    #endif
  }

  /* Now we have launched all the children.  Let's wait for max time before returning
     This does pseudo busy waiting just to appear active */
  while (passedtime < maxtime) {
#ifdef _WIN32
		Sleep(1000);
#else
	    sleep(1);
#endif
    passedtime++;
  }
  exit(0);
  return 0;
}
コード例 #3
0
ファイル: et_params.c プロジェクト: kohr-h/ETreco
void
EtParams_assign_from_file (EtParams *params, const char *fname_params)
{
  double dtmp;
  dictionary *dict;

  CAPTURE_NULL_VOID (params);
  CAPTURE_NULL_VOID (fname_params);

  if ((dict = iniparser_load (fname_params)) == NULL)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Unable to read parameters from %s.", fname_params);
      return;
    }


  /* GEOMETRY */

  if ((dtmp = iniparser_getdouble (dict, "optics:magnification", -1.0)) == -1.0)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'magnification' not found in %s.", fname_params);
      return;
    }

  params->magnification = (float) dtmp;
  

  /* CTF */

  /* Ignore CTF if acc_voltage is zero or not present */
  if ((dtmp = iniparser_getdouble (dict, "electronbeam:acc_voltage", 0.0)) == 0.0)
    {
      use_ctf_flag = 0;
      iniparser_freedict (dict);
      return;
    }

  use_ctf_flag = 1;
  params->acc_voltage = (float) dtmp * ONE_KILOVOLT;

  if ((dtmp = iniparser_getdouble (dict, "electronbeam:energy_spread", -1.0)) == -1.0)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'energy_spread' not found in %s.", 
        fname_params);
      return;
    }

  params->energy_spread = (float) dtmp;

  if ((dtmp = iniparser_getdouble (dict, "optics:cs", -1.0)) == -1.0)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'cs' not found in %s.", fname_params);
      return;
    }

  params->cs = (float) dtmp * ONE_MILLIMETER;

  if ((dtmp = iniparser_getdouble (dict, "optics:cc", -1.0)) == -1.0)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'cc' not found in %s.", fname_params);
      return;
    }

  params->cc = (float) dtmp * ONE_MILLIMETER;

  if ((dtmp = iniparser_getdouble (dict, "optics:aperture", -1.0)) == -1.0)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'aperture' not found in %s.", fname_params);
      return;
    }

  params->aperture = (float) dtmp * ONE_MICROMETER;

  if ((dtmp = iniparser_getdouble (dict, "optics:focal_length", -1.0)) == -1.0)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'focal_length' not found in %s.", fname_params);
      return;
    }

  params->focal_length = (float) dtmp * ONE_MILLIMETER;

  if ((dtmp = iniparser_getdouble (dict, "optics:cond_ap_angle", -1.0)) == -1.0)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'cond_ap_angle' not found in %s.", fname_params);
      return;
    }

  params->cond_ap_angle = (float) dtmp * ONE_MILLIRADIAN;

  if ((dtmp = iniparser_getdouble (dict, "optics:defocus_nominal", -1.0)) == -1.0)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'defocus_nominal' not found in %s.", fname_params);
      return;
    }

  params->defocus_nominal = (float) dtmp * ONE_MICROMETER;

  /* If not found in config file, set to predefined ACR */
  params->acr = (float) iniparser_getdouble (dict, "volume:famp", ACR);

  /* The MTF parameters all have default values */

  use_mtf_flag = 1;
  
  params->mtf_a     = iniparser_getdouble (dict, "detector:mtf_a", 0.0);
  params->mtf_b     = iniparser_getdouble (dict, "detector:mtf_b", 0.0);
  params->mtf_c     = iniparser_getdouble (dict, "detector:mtf_c", 1.0);
  params->mtf_alpha = iniparser_getdouble (dict, "detector:mtf_alpha", 0.0);
  params->mtf_beta  = iniparser_getdouble (dict, "detector:mtf_beta", 0.0);
  params->mtf_p     = iniparser_getint (dict, "detector:mtf_p", 1);  
  params->mtf_q     = iniparser_getint (dict, "detector:mtf_q", 1);  

  /* If a and b are zero, the MTF collapses to a constant. This means 'no MTF'. */
  if ((params->mtf_a == 0.0) && (params->mtf_b == 0.0))
    use_mtf_flag = 0;
   

  iniparser_freedict (dict);


  /* Derived parameters */

  /* Compute relativistic wave number (unit: [1/nm]) */

  /* momentum * c [eV] */
  dtmp = sqrtf (params->acc_voltage * params->acc_voltage + 2 * params->acc_voltage * EL_REST_ENERGY); 
  params->wave_number = (float) 2 * M_PI * dtmp / HC;


  /* Compute constant derived from cc (unit: [nm]) */
  dtmp = 1.0 / (2 * EL_REST_ENERGY); // some factor
  params->cc1 = (float) (1 + 2 * dtmp * params->acc_voltage) 
                / (params->acc_voltage * (1 + dtmp * params->acc_voltage)) * params->cc;

  /* Compute cutoff radius due to aperture */
  params->aper_cutoff = (params->wave_number * params->aperture) / params->focal_length;

  return;
}
コード例 #4
0
ファイル: main.c プロジェクト: crnt/myservices
int main(int argc, char *argv[]) 
{
	service_location_t service = {0};
	const char *host, *parent, *pid_file, *log_file;
	int i;
	
	if (argc < 2) {
		fprintf(stderr, "Usage: %s <config file>", argv[0]);
		exit(1);
	}
	
	/* Parse the configuration */
	if (strlen(argv[1]) >= PATH_MAX) {
		LOG_WARN(stderr, "The config file path exceeds PATH_MAX, possibly truncating");
	}
	strncpy(service.config_file, argv[1], PATH_MAX);

	if (load_config(&service) == false) {
		LOG_FATAL(stderr, "Failed to load configuration(%s): %s", service.config_file, strerror(errno));
		exit(1);
	}
	
	/* Open log file */
	log_file = iniparser_getstring(service.config, "main:log_file", MYSERVICES_LOG_FILE);
	
	if (strlen(log_file) >= PATH_MAX) {
		LOG_WARN(stderr, "The log_file path exceeds PATH_MAX, possibly truncating");
	}
	strncpy(service.log_file, log_file, PATH_MAX);
	
	if (open_log_file(&service, service.log_file) == false) {
		LOG_FATAL(stderr, "Failed to open log file: %s", log_file, strerror(errno));
		exit(1);
	}

	signal(SIGINT, SIG_IGN);
	signal(SIGKILL, SIG_IGN);

	if (fork() == 0) {
		int code;
		uid_t uid;
		gid_t gid;
		
		signal(SIGINT, SIG_DFL);
		signal(SIGKILL, SIG_DFL);
		
		if (gethostname(service.hostname, HOSTNAME_MAX)) {
			LOG_FATAL(service.log_fd, "Failed to gethostname: %s", strerror(errno));
			exit(1);
		}

		/* Initialize service locations */
		service_info_init(&(service.info));

		if (service_info_parse(&service, &(service.info)) == false) {
			LOG_FATAL(service.log_fd, "Failed to parse service information");
			exit(1);
		}
		
		if (resolve_uid_and_gid(&service, &uid, &gid) == false) {
			LOG_FATAL(service.log_fd, "Failed to resolve user/group");
			exit(1);
		}
		
		pid_file = iniparser_getstring(service.config, "main:pid_file", MYSERVICES_PID_FILE);
		if (write_pid_file(&service, pid_file, uid, gid) == false) {
			LOG_FATAL(service.log_fd, "Failed to write pid file");
			exit(1);
		}

		// Drop privileges and chown pid to the current user
		if (drop_privileges(uid, gid) == false) {
			LOG_FATAL(service.log_fd, "Failed to lower privileges: %s", strerror(errno));
			exit(1);
		}

		fclose(stdin);
		fclose(stdout);
		
		do {
			/* ZooKeeper client floods the logs with messages if given a chance */
			zoo_set_debug_level(0);
			
			if (connect_zookeeper(&service, true) == false) {
				LOG_FATAL(service.log_fd, "Failed to connect");
				break;
			}

			if (false == run_myservices(&service)) {
				LOG_FATAL(service.log_fd, "Failed to run MyServices daemon");
				break;
			}
		
		} while (0);
		
		/* Unlink pid-file */
		if (unlink(pid_file) == -1) {
			LOG_FATAL(service.log_fd, "Failed to remove pid file (%s): %s", pid_file, strerror(errno));
		}
		service_info_deinit(&(service.info));
		
		if (service.config)
			iniparser_freedict(service.config);
		
		if (service.zk)
			zookeeper_close(service.zk);
		
		LOG_INFO(service.log_fd, "Terminating MyServices daemon..");
		fclose(service.log_fd);
		exit(0);
	} else {
		signal(SIGINT, SIG_DFL);
		signal(SIGKILL, SIG_DFL);
		exit(0);
	}

	return 0;
}
コード例 #5
0
ファイル: SearchBWT.c プロジェクト: Questionman/SOAP3-dp-1
int main(int argc, char** argv) {

    char c;
    unsigned int i, j, k;
    MMPool *mmPool;
    dictionary *programInput, *ini;
    char argumentText[11] = "argument:0";
    double startTime;
    double elapsedTime = 0, totalElapsedTime = 0;

    BWT *bwt;
    HSP *hsp;

    unsigned char charMap[256];

    unsigned char *convertedKey;
    unsigned int *packedKey;

    unsigned int found;
    unsigned int numberOfPattern, numberOfPatternFound;
    unsigned int saIndexLeft, saIndexRight;
    SaIndexGroupNew *saIndexGroup;
    SaIndexList *tempSaIndex1, *tempSaIndex2;
    unsigned int numberOfSaIndexGroup;
    HitList *hitList;
    unsigned int textPositionMatched, textPositionRetrieved;
    unsigned long long totalTextPositionMatched, totalTextPositionRetrieved;
    BWTSaRetrievalStatistics BWTSaRetrievalStatistics;

    FILE *logFile;
    

    init(textPositionRetrieved);    // to avoid compiler warning only
    init(textPositionMatched);        // to avoid compiler warning only

    programInput = ParseInput(argc, argv);
    ini = ParseIniFile();

    ProcessIni();
    ValidateIni();

    PrintIni();

    if (Confirmation == TRUE) {
        printf("BWT Search. Press Y to go or N to cancel. ");
        c = (char)getchar();
        while (c != 'y' && c != 'Y' && c != 'n' && c!= 'N') {
            c = (char)getchar();
        }
        if (c == 'n' || c == 'N') {
            exit(0);
        }
    }

    startTime = setStartTime();

    MMMasterInitialize(1, 0, FALSE, NULL);
    mmPool = MMPoolCreate(PoolSize);

    // Load Database
    printf("Loading Database..");
    fflush(stdout);

    bwt = BWTLoad(mmPool, BWTCodeFileName, BWTOccValueFileName, SaValueFileName, NULL, SaIndexFileName, NULL);
    HSPFillCharMap(charMap);
    hsp = HSPLoad(mmPool, PackedDNAFileName, AnnotationFileName, AmbiguityFileName, MAX_SEARCH_PATTERN_LENGTH / CHAR_PER_WORD);
    if (bwt->textLength != hsp->dnaLength) {
        fprintf(stderr, "BWT-BLAST: Database length inconsistent!\n");
        exit(1);
    }


    if (LogFileName[0] != '\0') {
        logFile = fopen64(LogFileName, "w");
        if (logFile == NULL) {
            fprintf(stderr, "Cannot open log file!\n");
            exit(1);
        }
    } else {
        logFile = NULL;
    }

    packedKey = MMPoolDispatch(mmPool, WordPackedLengthFromText(MAX_SEARCH_PATTERN_LENGTH, BIT_PER_CHAR));
    convertedKey = MMPoolDispatch(mmPool, MAX_SEARCH_PATTERN_LENGTH);

    saIndexGroup = MMUnitAllocate(MaxNumberOfHitGroups * sizeof(SaIndexGroup));
    hitList = MMUnitAllocate(MaxNumberOfTextPosition * sizeof(HitList));
    tempSaIndex1 = MMUnitAllocate(MaxNumberOfTextPosition * sizeof(SaIndexList));
    tempSaIndex2 = MMUnitAllocate(MaxNumberOfTextPosition * sizeof(SaIndexList));

    elapsedTime = getElapsedTime(startTime) - totalElapsedTime;
    printf("Elapsed time = ");
    printElapsedTime(stdout, FALSE, FALSE, TRUE, 4, elapsedTime);
    totalElapsedTime += elapsedTime;
    printf("\n");

    // Process search pattern files
    for (i=1; i<=NumberOfSearchPatternFile; i++) {

        argumentText[9] = '0' + (char)(i + 2);
        iniparser_copystring(programInput, argumentText, PatternFileName, PatternFileName, MAX_FILENAME_LEN);

        printf("Loading search pattern : %s\n", PatternFileName);
        numberOfPattern = ProcessSearchPattern();
        printf("Finished loading search pattern.\n");
        elapsedTime = getElapsedTime(startTime) - totalElapsedTime;
        printf("Elapsed time = ");
        printElapsedTime(stdout, FALSE, FALSE, TRUE, 4, elapsedTime);
        totalElapsedTime += elapsedTime;
        printf("\n");

        if (LogFileName[0] != '\0') {
            fprintf(logFile, "Searching for pattern : %s\n", PatternFileName);
        }

        if (SABinarySearch == TRUE) {

            printf("Start forward search with SA index.\n");
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Forward search with SA index.\n");
            }

            numberOfPatternFound = 0;
            totalTextPositionMatched = 0;
            totalTextPositionRetrieved = 0;
            BWTInitializeSaRetrievalStatistics(&BWTSaRetrievalStatistics);

            for (j=0; j<numberOfPattern; j++) {
                //ConvertTextToWordPacked(searchPattern + searchPatternPosition[j], packedKey, charMap, ALPHABET_SIZE, 
                //                    searchPatternPosition[j+1] - searchPatternPosition[j]);
                //found = BWTForwardSearchSaIndex(packedKey, searchPatternPosition[j+1] - searchPatternPosition[j],
                //                         bwt, hsp->packedDNA, &saIndexLeft, &saIndexRight);

                ConvertTextToCode(searchPattern + searchPatternPosition[j], convertedKey, charMap, 
                                    searchPatternPosition[j+1] - searchPatternPosition[j]);
                found = BWTSaBinarySearch(convertedKey, searchPatternPosition[j+1] - searchPatternPosition[j],
                                         bwt, hsp->packedDNA, &saIndexLeft, &saIndexRight, packedKey);

                if (found) {
                    numberOfPatternFound++;
                    textPositionMatched = saIndexRight - saIndexLeft + 1;
                    totalTextPositionMatched += textPositionMatched;

                    if (FindTextPosition) {
                        saIndexGroup->startSaIndex = saIndexLeft;
                        if (textPositionMatched <= MaxNumberOfTextPosition) {
                            saIndexGroup->numOfMatch = textPositionMatched;
                        } else {
                            saIndexGroup->numOfMatch = MaxNumberOfTextPosition;
                            printf("Max no of text positions reached! Only %u out of %u text positions retrieved.\n", MaxNumberOfTextPosition, textPositionMatched);
                        }
                        saIndexGroup->posQuery = 0;
                        saIndexGroup->info = 0;
                        textPositionRetrieved = BWTTextPosition(bwt, saIndexGroup, 1, hitList, tempSaIndex1, tempSaIndex2, &BWTSaRetrievalStatistics, FALSE);
                        totalTextPositionRetrieved += textPositionRetrieved;
                    }
                }

                if (LogFileName[0] != '\0') {
                    if (found) {
                        fprintf(logFile, "Pattern number %u found. SA Index from %u to %u.  ", 
                                j + 1, saIndexLeft, saIndexRight);
                        if (FindTextPosition) {
                            fprintf(logFile, "%u matches of %u located. ", textPositionRetrieved, textPositionMatched);
                            for (k=0; k<textPositionRetrieved; k++) {
                                fprintf(logFile, "%u ", hitList[k].posText);
                            }
                        }
                    } else {
                        fprintf(logFile, "Pattern number %u not found.", j + 1); 
                    }
                    fprintf(logFile, "\n");
                }
            }

            printf("Finished forward search with SA index.\n");
            printf("%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
            if (FindTextPosition) {
                printf("Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                              BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                              BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
            }
            elapsedTime = getElapsedTime(startTime) - totalElapsedTime;
            printf("Elapsed time = ");
            printElapsedTime(stdout, FALSE, FALSE, TRUE, 4, elapsedTime);
            totalElapsedTime += elapsedTime;
            printf("\n");
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Finished forward search with SA index.\n");
                fprintf(logFile, "%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
                if (FindTextPosition) {
                    fprintf(logFile, "Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                                  BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                                  BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
                }
                fprintf(logFile, "Elapsed time = ");
                printElapsedTime(logFile, FALSE, FALSE, TRUE, 4, elapsedTime);
                fprintf(logFile, "\n");
            }

        }

        if (BackwardSearch == TRUE) {

            printf("Start backward search.\n");
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Backward search.\n");
            }

            numberOfPatternFound = 0;
            totalTextPositionMatched = 0;
            totalTextPositionRetrieved = 0;
            BWTInitializeSaRetrievalStatistics(&BWTSaRetrievalStatistics);

            for (j=0; j<numberOfPattern; j++) {
                ConvertTextToCode(searchPattern + searchPatternPosition[j], convertedKey, charMap, 
                                    searchPatternPosition[j+1] - searchPatternPosition[j]);
                found = BWTBackwardSearch(convertedKey, searchPatternPosition[j+1] - searchPatternPosition[j],
                                         bwt, &saIndexLeft, &saIndexRight);
                if (found) {
                    numberOfPatternFound++;
                    textPositionMatched = saIndexRight - saIndexLeft + 1;
                    totalTextPositionMatched += textPositionMatched;

                    if (FindTextPosition) {
                        saIndexGroup->startSaIndex = saIndexLeft;
                        if (textPositionMatched <= MaxNumberOfTextPosition) {
                            saIndexGroup->numOfMatch = textPositionMatched;
                        } else {
                            saIndexGroup->numOfMatch = MaxNumberOfTextPosition;
                            printf("Max no of text positions reached! Only %u out of %u text positions retrieved.\n", MaxNumberOfTextPosition, textPositionMatched);
                        }
                        saIndexGroup->posQuery = 0;
                        saIndexGroup->info = 0;
                        textPositionRetrieved = BWTTextPosition(bwt, saIndexGroup, 1, hitList, tempSaIndex1, tempSaIndex2, &BWTSaRetrievalStatistics, FALSE);
                        totalTextPositionRetrieved += textPositionRetrieved;
                    }
                }

                if (LogFileName[0] != '\0') {
                    if (found) {
                        fprintf(logFile, "Pattern number %u found. SA Index from %u to %u. Total %u occurrences ", j + 1, saIndexLeft, saIndexRight, saIndexRight - saIndexLeft + 1);
                        if (FindTextPosition) {
                            fprintf(logFile, "%u matches of %u located. ", textPositionRetrieved, textPositionMatched);
                            for (k=0; k<textPositionRetrieved; k++) {
                                fprintf(logFile, "%u ", hitList[k].posText);
                            }
                        }
                    } else {
                        fprintf(logFile, "Pattern number %u not found.", j + 1); 
                    }
                    fprintf(logFile, "\n");
                }
            }

            printf("Finished backward search.\n");
            printf("%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
            if (FindTextPosition) {
                printf("Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                              BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                              BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
            }
            elapsedTime = getElapsedTime(startTime) - totalElapsedTime;
            printf("Elapsed time = ");
            printElapsedTime(stdout, FALSE, FALSE, TRUE, 4, elapsedTime);
            totalElapsedTime += elapsedTime;
            printf("\n");
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Finished backward search.\n");
                fprintf(logFile, "%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
                if (FindTextPosition) {
                    fprintf(logFile, "Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                                  BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                                  BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
                }
                fprintf(logFile, "Elapsed time = ");
                printElapsedTime(logFile, FALSE, FALSE, TRUE, 4, elapsedTime);
                fprintf(logFile, "\n");
            }

        }

        if (BackwardSearchCheck == TRUE) {

            printf("Start backward search with text.\n");
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Backward search with text.\n");
            }

            numberOfPatternFound = 0;
            totalTextPositionMatched = 0;
            totalTextPositionRetrieved = 0;
            BWTInitializeSaRetrievalStatistics(&BWTSaRetrievalStatistics);

            for (j=0; j<numberOfPattern; j++) {
                ConvertTextToCode(searchPattern + searchPatternPosition[j], convertedKey, charMap, 
                                    searchPatternPosition[j+1] - searchPatternPosition[j]);
                ConvertTextToWordPacked(searchPattern + searchPatternPosition[j], packedKey, charMap, ALPHABET_SIZE, 
                                    searchPatternPosition[j+1] - searchPatternPosition[j]);
                found = BWTBackwardSearchCheckWithText(convertedKey, packedKey, searchPatternPosition[j+1] - searchPatternPosition[j],
                                                  bwt, hsp->packedDNA, TextCheckCostFactor, MaxNumberOfTextPosition, 
                                                  hitList, &saIndexLeft, &saIndexRight);
                if (found) {
                    numberOfPatternFound++;
                    textPositionMatched = saIndexRight - saIndexLeft + 1;
                    totalTextPositionMatched += textPositionMatched;

                    // Find text position if text check not used
                    if (FindTextPosition && saIndexLeft != 0) {
                        saIndexGroup->startSaIndex = saIndexLeft;
                        if (textPositionMatched <= MaxNumberOfTextPosition) {
                            saIndexGroup->numOfMatch = textPositionMatched;
                        } else {
                            saIndexGroup->numOfMatch = MaxNumberOfTextPosition;
                            printf("Max no of text positions reached! Only %u out of %u text positions retrieved.\n", MaxNumberOfTextPosition, textPositionMatched);
                        }
                        saIndexGroup->posQuery = 0;
                        saIndexGroup->info = 0;
                        textPositionRetrieved = BWTTextPosition(bwt, saIndexGroup, 1, hitList, tempSaIndex1, tempSaIndex2, &BWTSaRetrievalStatistics, FALSE);
                        totalTextPositionRetrieved += textPositionRetrieved;
                    } else {
                        textPositionRetrieved = textPositionMatched;
                        totalTextPositionRetrieved += textPositionRetrieved;
                    }
                }

                if (LogFileName[0] != '\0') {
                    if (found) {
                        fprintf(logFile, "Pattern number %u found. ", j + 1);
                        if (FindTextPosition) {
                            fprintf(logFile, "%u matches of %u located. ", textPositionRetrieved, textPositionMatched);
                            for (k=0; k<textPositionRetrieved; k++) {
                                fprintf(logFile, "%u ", hitList[k].posText);
                            }
                        }
                    } else {
                        fprintf(logFile, "Pattern number %u not found.", j + 1); 
                    }
                    fprintf(logFile, "\n");
                }
            }

            printf("Finished backward search with text.\n");
            printf("%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
            if (FindTextPosition) {
                printf("Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                              BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                              BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
            }
            elapsedTime = getElapsedTime(startTime) - totalElapsedTime;
            printf("Elapsed time = ");
            printElapsedTime(stdout, FALSE, FALSE, TRUE, 4, elapsedTime);
            totalElapsedTime += elapsedTime;
            printf("\n");
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Finished backward search with text.\n");
                fprintf(logFile, "%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
                if (FindTextPosition) {
                    fprintf(logFile, "Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                                  BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                                  BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
                }
                fprintf(logFile, "Elapsed time = ");
                printElapsedTime(logFile, FALSE, FALSE, TRUE, 4, elapsedTime);
                fprintf(logFile, "\n");
            }

        }

        if (HammingDistSearch == TRUE) {

            printf("Start hamming distance %u approximate match.\n", MaxErrorAllowed);
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Hamming distance %u approximate match.\n", MaxErrorAllowed);
            }

            numberOfPatternFound = 0;
            totalTextPositionMatched = 0;
            totalTextPositionRetrieved = 0;
            BWTInitializeSaRetrievalStatistics(&BWTSaRetrievalStatistics);

            for (j=0; j<numberOfPattern; j++) {
                ConvertTextToCode(searchPattern + searchPatternPosition[j], convertedKey, charMap, 
                                    searchPatternPosition[j+1] - searchPatternPosition[j]);
                numberOfSaIndexGroup = BWTHammingDistMatchOld(convertedKey, searchPatternPosition[j+1] - searchPatternPosition[j],
                                                           bwt, MaxErrorAllowed, saIndexGroup, MaxNumberOfHitGroups, 0, 0);
                if (numberOfSaIndexGroup) {
                    numberOfPatternFound++;
                    textPositionMatched = 0;
                    for (k=0; k<numberOfSaIndexGroup; k++) {
                        textPositionMatched += saIndexGroup[k].numOfMatch;
                    }
                    if (textPositionMatched > MaxNumberOfTextPosition) {
                        textPositionMatched = 0;
                        for (k=0; k<numberOfSaIndexGroup && textPositionMatched < MaxNumberOfTextPosition; k++) {
                            textPositionMatched += saIndexGroup[k].numOfMatch;
                        }
                        numberOfSaIndexGroup = k - 1;
                        saIndexGroup[numberOfSaIndexGroup].numOfMatch -= textPositionMatched - MaxNumberOfTextPosition;
                        for (; k<numberOfSaIndexGroup; k++) {
                            textPositionMatched += saIndexGroup[k].numOfMatch;
                        }
                        printf("Max no of text positions reached! Only %u out of %u text positions retrieved.\n", MaxNumberOfTextPosition, textPositionMatched);
                    }
                    totalTextPositionMatched += textPositionMatched;

                    if (FindTextPosition) {
                        textPositionRetrieved = BWTTextPosition(bwt, saIndexGroup, numberOfSaIndexGroup, hitList, tempSaIndex1, tempSaIndex2, &BWTSaRetrievalStatistics, FALSE);
                        totalTextPositionRetrieved += textPositionRetrieved;
                    }
                }

                if (LogFileName[0] != '\0') {
                    if (numberOfSaIndexGroup) {
                        fprintf(logFile, "Pattern number %u found. %u matches", j + 1, textPositionMatched);
                        if (FindTextPosition) {
                            fprintf(logFile, "%u matches of %u located. ", textPositionRetrieved, textPositionMatched);
                            for (k=0; k<textPositionRetrieved; k++) {
                                fprintf(logFile, "%u ", hitList[k].posText);
                            }
                        }
                    } else {
                        fprintf(logFile, "Pattern number %u not found.", j + 1); 
                    }
                    fprintf(logFile, "\n");
                }
            }

            printf("Finished hamming distance search.\n");
            printf("%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
            if (FindTextPosition) {
                printf("Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                              BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                              BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
            }
            elapsedTime = getElapsedTime(startTime) - totalElapsedTime;
            printf("Elapsed time = ");
            printElapsedTime(stdout, FALSE, FALSE, TRUE, 4, elapsedTime);
            totalElapsedTime += elapsedTime;
            printf("\n");
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Finished hamming distance search.\n");
                fprintf(logFile, "%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
                if (FindTextPosition) {
                    fprintf(logFile, "Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                                  BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                                  BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
                }
                fprintf(logFile, "Elapsed time = ");
                printElapsedTime(logFile, FALSE, FALSE, TRUE, 4, elapsedTime);
                fprintf(logFile, "\n");
            }

        }

        if (EditDistSearch == TRUE) {

            printf("Start edit distance %u approximate match.\n", MaxErrorAllowed);
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Edit distance %u approximate match.\n", MaxErrorAllowed);
            }

            numberOfPatternFound = 0;
            totalTextPositionMatched = 0;
            totalTextPositionRetrieved = 0;
            BWTInitializeSaRetrievalStatistics(&BWTSaRetrievalStatistics);

            for (j=0; j<numberOfPattern; j++) {
                ConvertTextToCode(searchPattern + searchPatternPosition[j], convertedKey, charMap, 
                                    searchPatternPosition[j+1] - searchPatternPosition[j]);
                numberOfSaIndexGroup = BWTEditDistMatchOld(convertedKey, searchPatternPosition[j+1] - searchPatternPosition[j],
                                                        bwt, MaxErrorAllowed, (SaIndexGroupWithLengthError*)saIndexGroup, MaxNumberOfHitGroups);
                if (numberOfSaIndexGroup > MaxNumberOfHitGroups) {
                    fprintf(stderr, "numberOfSaIndexGroup > MaxNumberOfHitGroups!\n");
                }
                if (numberOfSaIndexGroup) {
                    numberOfPatternFound++;
                    textPositionMatched = 0;
                    for (k=0; k<numberOfSaIndexGroup; k++) {
                        textPositionMatched += saIndexGroup[k].numOfMatch;
                    }
                    if (textPositionMatched > MaxNumberOfTextPosition) {
                        textPositionMatched = 0;
                        for (k=0; k<numberOfSaIndexGroup && textPositionMatched < MaxNumberOfTextPosition; k++) {
                            textPositionMatched += saIndexGroup[k].numOfMatch;
                        }
                        numberOfSaIndexGroup = k - 1;
                        saIndexGroup[numberOfSaIndexGroup].numOfMatch -= textPositionMatched - MaxNumberOfTextPosition;
                        for (; k<numberOfSaIndexGroup; k++) {
                            textPositionMatched += saIndexGroup[k].numOfMatch;
                        }
                        printf("Max no of text positions reached! Only %u out of %u text positions retrieved.\n", MaxNumberOfTextPosition, textPositionMatched);
                    }
                    totalTextPositionMatched += textPositionMatched;

                    if (FindTextPosition) {
                        textPositionRetrieved = BWTTextPosition(bwt, saIndexGroup, numberOfSaIndexGroup, hitList, tempSaIndex1, tempSaIndex2, &BWTSaRetrievalStatistics, FALSE);
                        totalTextPositionRetrieved += textPositionRetrieved;
                    }
                }

                if (LogFileName[0] != '\0') {
                    if (numberOfSaIndexGroup) {
                        fprintf(logFile, "Pattern number %u found. %u matches. ", j + 1, textPositionMatched);
                        if (FindTextPosition) {
                            fprintf(logFile, "%u matches of %u located. ", textPositionRetrieved, textPositionMatched);
                            for (k=0; k<textPositionRetrieved; k++) {
                                fprintf(logFile, "%u ", hitList[k].posText);
                            }
                        }
                    } else {
                        fprintf(logFile, "Pattern number %u not found.", j + 1); 
                    }
                    fprintf(logFile, "\n");
                }
            }

            printf("Finished edit distance search.\n");
            printf("%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
            if (FindTextPosition) {
                printf("Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                              BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                              BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
            }
            elapsedTime = getElapsedTime(startTime) - totalElapsedTime;
            printf("Elapsed time = ");
            printElapsedTime(stdout, FALSE, FALSE, TRUE, 4, elapsedTime);
            totalElapsedTime += elapsedTime;
            printf("\n");
            if (LogFileName[0] != '\0') {
                fprintf(logFile, "Finished edit distance search.\n");
                fprintf(logFile, "%u patterns out of %u found. %llu of %llu matches located.\n", numberOfPatternFound, numberOfPattern, totalTextPositionRetrieved, totalTextPositionMatched);
                if (FindTextPosition) {
                    fprintf(logFile, "Hits: BWT/Cached/Diag/Dup      : %u/%u/%u/%u\n", 
                                  BWTSaRetrievalStatistics.bwtSaRetrieved, BWTSaRetrievalStatistics.cachedSaRetrieved, 
                                  BWTSaRetrievalStatistics.saDiagonalLinked, BWTSaRetrievalStatistics.saDuplicated);
                }
                fprintf(logFile, "Elapsed time = ");
                printElapsedTime(logFile, FALSE, FALSE, TRUE, 4, elapsedTime);
                fprintf(logFile, "\n");
            }

        }

    }

    MMPoolReturn(mmPool, packedKey, WordPackedLengthFromText(MAX_SEARCH_PATTERN_LENGTH, BIT_PER_CHAR));
    MMPoolReturn(mmPool, convertedKey, MAX_SEARCH_PATTERN_LENGTH);

    HSPFree(mmPool, hsp, MAX_SEARCH_PATTERN_LENGTH / CHAR_PER_WORD);
    BWTFree(mmPool, bwt);

    if (searchPattern != NULL) {
        MMUnitFree(searchPattern, searchPatternAllocated);
    }
    if (searchPatternPosition != NULL) {
        MMUnitFree(searchPatternPosition, searchPatternPositionAllocated);
    }
    MMUnitFree(saIndexGroup, MaxNumberOfHitGroups * sizeof(unsigned int));
    MMUnitFree(hitList, MaxNumberOfTextPosition * sizeof(unsigned int));

    MMPoolFree(mmPool);

    iniparser_freedict(programInput);
    iniparser_freedict(ini);

    return 0;

}
コード例 #6
0
ファイル: devinfo.c プロジェクト: SomebodyLuo/exm_onvif
/**********************************************************************************************
 * 函数名	:init_devinfo()
 * 功能	:初始化设备信息
 * 输入	:无
 * 返回值	:0表示正常,负值表示出错
 * 注		:应用程序在刚启动的时候需要调用这个函数从/conf/devinfo.ini中读取系统信息
 *			如果/conf/devinfo.ini不存在,则把设备信息设置成初始值,并返回-1
  **********************************************************************************************/
int init_devinfo(void)
{
	dictionary      *ini=NULL;
    	char *pstr=NULL;
    	int status;
	struct GT_GUID guid;
	int num;
//	struct tm *ptime=NULL;
//	time_t ctime;
	FILE *fp=NULL;
	int  write_file_flag=0;
	
	
	if(init_flag)
		return 0;
	init_flag=1;
	memset((void*)&info,0,sizeof(devinfo_struct));
	ini=iniparser_load_lockfile(DEVINFO_PARA_FILE,1,&fp);
	if(ini==NULL)
	{
		
                printf("init_devinfo() cannot parse ini file file [%s]", DEVINFO_PARA_FILE);
                gtlogerr("init_devinfo() cannot parse ini file file [%s]", DEVINFO_PARA_FILE);
                return -1 ;
        }
       // iniparser_dump_ini(ini,stdout); //将ini文件内容显示在屏幕上,实际使用时没有用,应去掉
	pstr=iniparser_getstring(ini,"devinfo:devguid",def_dev_guid);
	guid=hex2guid(pstr);
	memcpy((char*)info.guid,(char*)(&guid),sizeof(guid));
	guid2hex(guid,info.guid_str);
	
	//设备型号字符串
	pstr=iniparser_getstring(ini,"devinfo:devtypestring",T_GTIP2004_STR);
	info.dvsr=get_dvsr_by_typestr(pstr);
	if(info.dvsr==NULL)
		info.dvsr=get_dvsr_by_typestr(T_GTIP2004_STR);//默认为IP2004

	//设备型号代码
	num=iniparser_getint(ini,"devinfo:devtype",-1);
	if(num!=conv_dev_str2type(pstr))	//pstr存放型号字符串
	{
		iniparser_setint(ini,"devinfo:devtype",conv_dev_str2type(pstr));
		write_file_flag=1;
	}
	

	if(fix_devinfo_file(ini,info.dvsr)==1)
		write_file_flag=1;

	pstr=iniparser_getstring(ini,"devinfo:batchseq","NULL");
	sprintf(info.batch_seq,"%s",pstr);

	pstr=iniparser_getstring(ini,"devinfo:cpuboard","NULL");
	sprintf(info.board_seq,"%s",pstr);
	//	ctime=time(NULL); //	ptime=localtime(&ctime);	//	memcpy((void*)&info.lv_fac_time,(void *)ptime,sizeof(info.lv_fac_time));


	info.lv_fac_time.tm_year=iniparser_getint(ini,"leave_fac:year",2000)-1900;
	info.lv_fac_time.tm_mon=iniparser_getint(ini,"leave_fac:mon",1)-1;
	info.lv_fac_time.tm_mday=iniparser_getint(ini,"leave_fac:day",1);
	info.lv_fac_time.tm_hour=iniparser_getint(ini,"leave_fac:hour",0);
	info.lv_fac_time.tm_min=iniparser_getint(ini,"leave_fac:min",0);
	info.lv_fac_time.tm_sec=iniparser_getint(ini,"leave_fac:sec",0);	
	info.lfc_flag=iniparser_getint(ini,"leave_fac:lfc_flag",-1);

	num=iniparser_getint(ini,"resource:disk_capacity",-1);
	info.disk_capacity=num;
	if(info.disk_capacity<0)
	{
		iniparser_setstr(ini,"resource:disk_capacity","0");
		write_file_flag=1;		
	}	

	if(write_file_flag)
		save_inidict_file(DEVINFO_PARA_FILE,ini,&fp);
	else
	{
		if(fp!=NULL)
		{
			unlock_file(fileno(fp));
			fsync(fileno(fp));
			fclose(fp);
		}	
	}

	iniparser_freedict(ini);
	return 0;
}
コード例 #7
0
ファイル: fpga.c プロジェクト: doebrowsk/tank-chair
//  Initializes the FPGA, the sabertooth and the mototrs
void FPGA_Boot(void)
{
	LOG.INFO("Initializing FPGA...");
	FPGA_Status = NiFpga_Initialize();
	if (NiFpga_IsNotError(FPGA_Status))
	{
		// opens a session, downloads the bitstream, and runs the FPGA.
		LOG.INFO("Opening a session FPGA...");

		NiFpga_MergeStatus(&FPGA_Status, NiFpga_Open(NiFpga_mainFPGA_Bitfile,
					NiFpga_mainFPGA_Signature,
					"RIO0",
					NiFpga_OpenAttribute_NoRun,
					&FPGA_Session));
		if (NiFpga_IsNotError(FPGA_Status))
		{
			LOG.INFO("ReDownloading the FPGA");
			NiFpga_MergeStatus(&FPGA_Status,NiFpga_Download(FPGA_Session));
			if (NiFpga_IsNotError(FPGA_Status))
			{
				LOG.INFO("Restarting the FPGA");
				NiFpga_MergeStatus(&FPGA_Status,NiFpga_Reset(FPGA_Session));
				if (NiFpga_IsNotError(FPGA_Status))
				{
					LOG.INFO("Running the FPGA");
					NiFpga_MergeStatus(&FPGA_Status,NiFpga_Run(FPGA_Session, 0));

					if (NiFpga_IsNotError(FPGA_Status))
					{
					}
					else
					{
						LOG.ERR("FPGA Fail to run  fpga %d ",FPGA_Status);
					}

				}
				else
				{
					LOG.ERR("FPGA Fail to redownload fpga %d ",FPGA_Status);
				}
			}
			else
			{
				LOG.ERR("FPGA Fail to redownload fpga %d ",FPGA_Status);
			}
		}
		else
		{
			LOG.ERR("FPGA Fail to  open a session. Error Code %d ",FPGA_Status);
		}
	}
	LOG.VERBOSE("Reading Constants for the fpga");

	if(fileExists("config/odometry.ini"))
	{
		dictionary* config = iniparser_load("config/odometry.ini");
		leftWheelConversionConstant  = 1/(iniparser_getdouble(config,"MotorEncoderConstant:MeterPerTickLeft",0)) * PIDUpdateRateInMs/1000;
		rightWheelConversionConstant = 1/(iniparser_getdouble(config,"MotorEncoderConstant:MeterPerTickRight",0)) * PIDUpdateRateInMs/1000;
		iniparser_freedict(config);
		LOG.VERBOSE("Odometry Ini file loaded for fpga!");

	}
	else
	{
		LOG.ERR("!!!!!!!!!!!!!!!!odomentry.ini was not found!!!!!!!!!!!!!!!!!!!!!!");
	}

        if(fileExists("config/pid.ini")) {
            dictionary* config = iniparser_load("config/pid.ini");
            max_pid_speed = (uint16_t) iniparser_getint(config, "Both:MaxSpeedTicksPerDt", 0);
            left_pid_pro_gain = iniparser_getint(config, "LeftPID:ProportionalGain",0);
            left_pid_int_gain = iniparser_getint(config, "LeftPID:IntegralGain",0);
            left_pid_der_gain = iniparser_getint(config, "LeftPID:DerivativeGain", 0);
            right_pid_pro_gain = iniparser_getint(config, "RightPID:ProportionalGain",0);
            right_pid_int_gain = iniparser_getint(config, "RightPID:IntegralGain",0);
            right_pid_der_gain = iniparser_getint(config, "RightPID:DerivativeGain",0);
            iniparser_freedict(config);
            LOG.VERBOSE("PID INI file loaded for FPGA");
        }
        else {
            LOG.ERR("PID.ini was not found");
        }

        if(fileExists("config/CRIO.ini")) {
            dictionary* config = iniparser_load("config/CRIO.ini");
            sabertooth_address = (uint8_t) iniparser_getint(config, "Sabertooth:Address", 130);
            iniparser_freedict(config);
            LOG.VERBOSE("Sabertooth address loaded for FPGA");            
        }
        else {
            LOG.ERR("Unable to load Sabertooth address");
        }

        NiFpga_MergeStatus(&FPGA_Status,NiFpga_WriteU8(FPGA_Session,NiFpga_mainFPGA_ControlU8_SlewRateControl, 10));
        if (NiFpga_IsError(FPGA_Status))
        {
                LOG.ERR("Failed to set Sabertooth slew rate");
        }

        FPGA_SetPIDdt(PIDUpdateRateInMs * 1000);
        FPGA_setMaxPIDSpeed(max_pid_speed);
        FPGA_setLPIDProGain(left_pid_pro_gain);
        FPGA_setLPIDIntGain(left_pid_int_gain);
        FPGA_setLPIDDerGain(left_pid_der_gain);
        FPGA_setRPIDProGain(right_pid_pro_gain);
        FPGA_setRPIDIntGain(right_pid_int_gain);
        FPGA_setRPIDDerGain(right_pid_der_gain);
        FPGA_setSabertoothAddress(sabertooth_address);

	    // This logs the version number
        LOG.INFO("FPGA VERSION =  %d",FPGA_GetVersion());

	LOG.INFO("Turning on the motors");
	FPGA_SetMotorStatus(1);
}
コード例 #8
0
/*  ...
 */
void CBaIniParse::TwistedIni() {

   IBaIniParser *pNewHdl = 0;
   dictionary   *pOrgHdl = 0;
   std::string   tmp;

   CPPUNIT_ASSERT(!IBaIniParserCreate("You/Shall/Not/Path"));
   CPPUNIT_ASSERT(!iniparser_load("You/Shall/Not/Path"));
   CPPUNIT_ASSERT(!IBaIniParserCreate(ERRORINI));
   CPPUNIT_ASSERT(!iniparser_load(ERRORINI));

   CPPUNIT_ASSERT(!iniparser_load(OFKEYINI));
   CPPUNIT_ASSERT(!IBaIniParserCreate(OFKEYINI));


   CPPUNIT_ASSERT(!IBaIniParserCreate(OFVALINI));
   CPPUNIT_ASSERT(!iniparser_load(OFVALINI));

   pNewHdl = IBaIniParserCreate(TWISTEDINI);
   pOrgHdl = iniparser_load(TWISTEDINI);
   CPPUNIT_ASSERT(pNewHdl);
   CPPUNIT_ASSERT(pOrgHdl);

   pNewHdl->Dump(stdout);
   std::cout << "a==============================================================\n\n";
   iniparser_dump(pOrgHdl, stdout);
   std::cout << "a==============================================================\n\n";

   pNewHdl->DumpIni(stdout);
   std::cout << "a==============================================================\n\n";
   iniparser_dump_ini(pOrgHdl, stdout);


   CPPUNIT_ASSERT_EQUAL(
         (bool) iniparser_find_entry(pOrgHdl, "open["),
         pNewHdl->Exists("open["));

   // Multi-lines
   tmp = pNewHdl->GetString("multi:multi line key", "");
   CPPUNIT_ASSERT_MESSAGE(tmp, tmp == "multi line value");
   tmp = pNewHdl->GetString("multi:visible", "");
   CPPUNIT_ASSERT_MESSAGE(tmp, tmp == "1");
   tmp = pNewHdl->GetString("multi:a", "");
   CPPUNIT_ASSERT_MESSAGE(tmp, tmp == "beginend");
   tmp = pNewHdl->GetString("multi:c", "");
   CPPUNIT_ASSERT_MESSAGE(tmp, tmp == "begin  end");

   CPPUNIT_ASSERT(IBaIniParserDestroy(pNewHdl));
   iniparser_freedict(pOrgHdl);
   pNewHdl = 0;
   pOrgHdl = 0;

   pNewHdl = IBaIniParserCreate(0);
   pOrgHdl = dictionary_new(10);
   CPPUNIT_ASSERT(pNewHdl);
   CPPUNIT_ASSERT(pOrgHdl);

   CPPUNIT_ASSERT_EQUAL(pNewHdl->Set(0, 0), !iniparser_set(pOrgHdl, 0, 0));

   CPPUNIT_ASSERT_EQUAL(pNewHdl->Set("section", 0),
         !iniparser_set(pOrgHdl, "section", 0));

   CPPUNIT_ASSERT_EQUAL(pNewHdl->Set("section:key", "value"),
         !iniparser_set(pOrgHdl, "section:key", "value"));

   tmp = pNewHdl->GetString("section:key", 0);
   CPPUNIT_ASSERT_MESSAGE(tmp, tmp == iniparser_getstring(pOrgHdl, "section:key", 0));

   /* reset the key's value*/
   CPPUNIT_ASSERT_EQUAL(pNewHdl->Set("section:key", 0),
         !iniparser_set(pOrgHdl, "section:key", 0));

   tmp = iniparser_getstring(pOrgHdl, "section:key", "dummy") ?
         iniparser_getstring(pOrgHdl, "section:key", "dummy") : "";
   CPPUNIT_ASSERT_MESSAGE(tmp, tmp == pNewHdl->GetString("section:key", "dummy"));
   CPPUNIT_ASSERT_EQUAL(pNewHdl->Set("section:key", "value"),
         !iniparser_set(pOrgHdl, "section:key", "value"));

   tmp = pNewHdl->GetString("section:key", 0);
   CPPUNIT_ASSERT_MESSAGE(tmp, tmp == iniparser_getstring(pOrgHdl, "section:key", 0));

   iniparser_unset(pOrgHdl, "section:key");
   pNewHdl->Reset("section:key");

   tmp = pNewHdl->GetString("section:key",  "dummy");
   CPPUNIT_ASSERT_MESSAGE(tmp, tmp == iniparser_getstring(pOrgHdl, "section:key",  "dummy"));

   CPPUNIT_ASSERT_EQUAL(pNewHdl->Set("section:key", 0), !iniparser_set(pOrgHdl, "section:key", 0));
   CPPUNIT_ASSERT_EQUAL(pNewHdl->Set("section:key1", 0), !iniparser_set(pOrgHdl, "section:key1", 0));
   CPPUNIT_ASSERT_EQUAL(pNewHdl->Set("section:key2", 0), !iniparser_set(pOrgHdl, "section:key2", 0));

}
コード例 #9
0
ファイル: pcl.c プロジェクト: hwstar/pbl
int main(int argc, char *argv[])
{
	char optchar;
	int longindex, i,res, crcerr;
	u8 writecmd;
	u32 bufbytepos;
	u8 *buffer,*lastrow;
	u16 wordaddr;
	u16 rowsexceptlast, toprow;
	u16 crc16;
	u16 load_size, load_size_bytes, load_address;
	u16 bootloader_size;
	u32 max_app_size;
	u32 bytes_received, bytes_sent;
	ihx_t *ihx;
	response_t *r;
	config_area_t *cf;
	serioStuff *s;
	dictionary *dict = NULL;
	static char exten[20];
	char *q;

	/* Die if packet structures screwed up */
	assert(sizeof(packet_t) == PACKET_SIZE);
		
	progname = argv[0];

	// Argument pre scan for config file name change first

	while((optchar=getopt_long(argc, argv, SHORT_OPTIONS, long_options, &longindex)) != EOF) {
		
		//Handle each argument. 
		switch(optchar) {
			
			// Was it a long option? 
			case 0:	
				// Hrmm, something we don't know about? 
				fatal("Unhandled long getopt option '%s'", long_options[longindex].name);
			
			// If it was an error, exit right here. 
			case '?':
				exit(1);

			// Was it a config file name? 
			case 'z':
				memset(config_file, 0, MAX_PATH);
				strncpy(config_file, optarg, MAX_PATH);
				flags.configfileoverride = 1;
				break;

			default: // Don't care about the rest of the args right now
				break;	
		}
	}
	optind = 1; // Reset option index for second scan later


	if((dict = iniparser_load(config_file))){
		char *s;
		s = iniparser_getstring(dict, "general:file", NULL);
		if(s)
			strncpy(file, s, MAX_PATH - 1);
		s = iniparser_getstring(dict, "general:port", NULL);
		if(s)
			strncpy(port, s, MAX_PATH - 1);
		s = iniparser_getstring(dict, "general:han-host",NULL);
		if(s)
			strncpy(host, s, MAX_PATH - 1);
		s = iniparser_getstring(dict, "general:han-service",NULL);
		if(s)
			strncpy(service, s, MAX_PATH - 1);
		s = iniparser_getstring(dict, "general:product-id", NULL);
		if(s){
			if(sscanf(s, "%X", &i) != 1)
				fatal("In pcl.conf, product ID needs to be a hexadecimal value");
			productid = (u16) i;
		}
		iniparser_freedict(dict);
	}
	else if(flags.configfileoverride){
		fatal("Cannot open config file: %s\n", config_file);
	}


	/* Parse the arguments. */
	while((optchar=getopt_long(argc, argv, SHORT_OPTIONS, long_options, &longindex)) != EOF) {
		
		/* Handle each argument. */
		switch(optchar) {
			
			/* Was it a long option? */
			case 0:
				
				/* Hrmm, something we don't know about? */
				fatal("Unhandled long getopt option '%s'", long_options[longindex].name);
			
			/* If it was an error, exit right here. */
			case '?':
				exit(1);

			/* Was it han node address request? */
			case 'a':
				if(sscanf(optarg, "%hx", &hannodeaddr) != 1)
					fatal("Invalid node address");
				if(hannodeaddr > 32)
					fatal("Node address out of range");
				flags.hanmode = 1;
				break;	


			/* Was it a check app request? */
			case 'c':
				flags.checkapp = 1;
				break;	

			/* Was it a debug level set? */
			case 'd':

				/* Save the value. */
				debuglvl=strtol(optarg, NULL, 10);
				if((debuglvl < 0 || debuglvl > DEBUG_MAX)) {
					fatal("Invalid debug level");
				}
				break;

			case 'e':
				flags.eeprom = 1;
				break;


			/* Was it a file request? */
			case 'f': 
				memset(file, 0, MAX_PATH);
				strncpy(file, optarg, MAX_PATH);
				break;
			
			/* Was it a help request? */
			case 'h':
				show_help();
				exit(0);

			case 'i':
				flags.interrogateonly = 1;
				break;

			case 'o':
				if(sscanf(optarg, "%X", &i) != 1)
					fatal("Product ID needs hexadecimal value");
				productid = (u16) i;
				break;

			/* Was it a port request? */
			case 'p': 
				memset(port, 0, MAX_PATH);
				strncpy(port, optarg, MAX_PATH);
				break;

			/* Was it a reset request */
			case 'r':
				flags.reset = 1;
				break;	

			/* Was it a verbose request? */
			case 'v':
				flags.verbose = 1;
				break;	

			case 'V':
				printf("PCL version %s\n", PCL_VERSION);
				exit(0);

			/* Was it Execute App ? */
			case 'x':
				flags.execute = 1;
				break;

			case 'z': /* handled previously */
				break;

			/* It was something weird.. */
			default:
				panic("Unhandled getopt return value %c", optchar);
		}
	}
	
	/* If there were any extra arguments, we should complain. */

	if(optind < argc) {
		fatal("Extra argument on commandline, '%s'", argv[optind]);
	}

	if(flags.eeprom && (flags.execute | flags.checkapp))
		fatal("-e is not valid with -x or -c");

	if(!(flags.interrogateonly | flags.execute | flags.checkapp | flags.eeprom))
		fatal("What do you want me to do, anyhow? Must specify -e, -c, -i, or -x");

	r = (response_t *) ((flags.hanmode) ? packet.han.payload : packet.pbl.payload);
	cf = (config_area_t *) r->config;


	// Send a query packet
	packet_init();

	if(flags.hanmode){ // If HAN address specified
		res  = hanclient_connect_setup("","", service, host);
		if(!res){ // if connect setup OK
			printf("Test for hand running\n"); 
			client_command.request = HAN_CCMD_DAEMON_INFO;
			res =  hanclient_send_command_return_res(&client_command);
			printf("Hand %s running\n", (res) ? "is not" : "is");

			if(!res){ // If hand is loaded, send boot loader entry command 
 		               	debug(DEBUG_EXPECTED,"Hand version: %s", client_command.cmd.info.version);
				// Check for structure size match between us and han daemon
                		if(client_command.cmd.info.cmdpktsize != sizeof(struct han_packet)){
                        		debug(DEBUG_UNEXPECTED, "Hand command structure incompatible");
                        		fatal(not_comp);
                		}
            		    	if(client_command.cmd.info.rawsize != sizeof(struct han_raw)){
                        		debug(DEBUG_UNEXPECTED, "Hand raw command structure incompatible");
                        		fatal(not_comp);
                		}

				flags.handisrunning = 1; // Set flag indicating comm is going to go through hand
				memset(&client_command,0,sizeof(Client_Command)); // Send boot loader entry command
				client_command.request = HAN_CCMD_SENDPKT;
				client_command.cmd.pkt.nodecommand = HAN_CMD_GEBL; 
				client_command.cmd.pkt.numnodeparams = 2;
				client_command.cmd.pkt.nodeparams[0] = 0x55;
				client_command.cmd.pkt.nodeparams[1] = 0xAA;
				client_command.cmd.pkt.nodeaddress = hannodeaddr;
				printf("Sending boot loader entry request\n");
				res = hanclient_send_command_return_res(&client_command);
				res = res | client_command.commstatus;
				printf("Boot loader %s entered via HAN command\n", (res) ? "not" : "was");
				if(!res){
					printf("Waiting for boot loader to initialize...");
					fflush(stdout);
					usleep(3000000); // Wait for boot loader to activate 
					printf("OK\n");
				}
			}
		}
		// Set up packet parameters for addressable mode
		packet.han.param = 0x55AA; // Not required by protocol
		packet.han.pkttype = HDC;
		packet.han.addr = (u8) hannodeaddr;
		packet_size = sizeof(packet_t);
	}
	else{ // Non-addressable operating mode
		packet.pbl.param = 0x55AA; // Not required by protocol
		packet_size = sizeof(packet_t_pbl);
	}


	if(!flags.handisrunning){ // If not going through hand
		if(!port[0])
			fatal("Missing port (-p) option on command line or config file");

		if(!(s = serio_open(port, (flags.hanmode) ? 9600 : 57600)))
			fatal("Can't open serial port %s\n", port);

		serio_flush_input(s);
		packet_finalize();
		debug(DEBUG_ACTION, "Transmit Packet CRC: 0x%04X", (flags.hanmode) ? packet.han.crc16 : packet.pbl.crc16);
		if((bytes_sent = packet_tx(s, packet.buffer, packet_size, 5000000)) < 0)
			fatal("Packet write error");
		debug(DEBUG_ACTION, "Bytes Sent: %d", bytes_sent);

		if(bytes_sent != packet_size)
			fatal("Packet write incomplete");


		packet_init(); // Just to be sure we get something


		// Wait for response
		bytes_received = packet_rx(s, packet.buffer, packet_size, 5000000);
		debug(DEBUG_ACTION, "Bytes Received: %d", bytes_received);
		if(bytes_received < 0)
			fatal("Packet read error");
		if((bytes_received != packet_size)) // Must see a packet, not just an ACK
			fatal("Packet read incomplete, received %d bytes", bytes_received);
		if(packet_check())
			fatal("Packet CRC error");


	}
	else{ // Send packets through hand */

		debug(DEBUG_ACTION,"Sending packets through hand");
		packet_finalize();
		debug(DEBUG_ACTION, "Transmit Packet CRC: 0x%04X", (flags.hanmode) ? packet.han.crc16 : packet.pbl.crc16);
		for(i = 0; i < PACKET_RETRIES; i++){
			client_command.cmd.raw.txlen = packet_format(client_command.cmd.raw.txbuffer, &packet.han, packet_size);
			client_command.cmd.raw.rxexpectlen = 255;
			client_command.cmd.raw.txtimeout = 100000;
			client_command.cmd.raw.rxtimeout = 500000;
			client_command.request = HAN_CCMD_RAW_PACKET;
			res = hanclient_send_command_return_res(&client_command);
			if((!res) && (client_command.cmd.raw.rxexpectlen))
				bytes_received = packet_unformat(packet.buffer, client_command.cmd.raw.rxbuffer, 255);
			else
				bytes_received = 0;
			if(bytes_received)
				crcerr = packet_check();
			else
				crcerr = 0;
			if((bytes_received == packet_size) && (!crcerr)) // Must see a packet with a good CRC, not just an ACK
				break;
			debug(DEBUG_UNEXPECTED,"Query packet receive error, try = %d", i);
			debug(DEBUG_UNEXPECTED,"bytes_received = %d crcerr = %d", bytes_received, crcerr);
		}
		if(i == PACKET_RETRIES)
			fatal("Too many packet retries!");
	}

	if(flags.verbose || flags.interrogateonly){
		printf("Loader Size in Words: 0x%04X\n", r->lsize);
		printf("App. Size In Words  : 0x%04X\n", r->appsize);
		printf("Product ID          : 0x%04X\n", r->prodid); 
		printf("Boot Program Version: 0x%02X\n", r->bootvers);
		printf("Protocol Number     : 0x%02X\n", r->proto);
		printf("Device User 1       : 0x%04X\n", cf->user1);
		printf("Device User 2       : 0x%04X\n", cf->user2);
		printf("Device User 3       : 0x%04X\n", cf->user3);
		printf("Device User 4       : 0x%04X\n", cf->user4);
		printf("Device ID           : 0x%04X\n", cf->deviceid);
		printf("Device Config 1     : 0x%04X\n", cf->config1);
		printf("Device Config 2     : 0x%04X\n", cf->config2);
	}

	if((flags.execute) && (!file[0])){ /* Special case for execute without load */
		printf("Check App: ");	
		if(send_command(s, BC_CHECK_APP, 0, NULL)){
			printf("FAILED\n");
			exit(1);
		}
		else
			printf("PASSED\n");
		printf("Executing App... ");
		if(send_command(s, BC_EXEC_APP, 0, NULL)){
			printf("FAILED\n");
			exit(1);
		}
		printf("\n");
		exit(0);
	}
	
	if(flags.interrogateonly) /* If interrogate only, exit now */
		exit(0);

	if(r->prodid != productid)
		fatal("Wrong product ID: specified: %04X, device reports: %04X", productid, r->prodid); 


	if(r->bootvers > BOOT_VERSION_SUPPORTED)
		fatal("Do not know how to deal with bootversion %d\n", r->bootvers);

	if(r->proto)
		fatal("Does not support protocol version %d\n", r->proto);

	max_app_size = r->appsize;
	bootloader_size = r->lsize;

	if(!file[0])
		fatal("Missing file (-f) option on command line");

	// Allocate buffer
	if(!(buffer = malloc(max_app_size << 1)))
		fatal("No memory for buffer");

	if(!flags.eeprom){
		/* Fill buffer with erase pattern */	
		for(i = 0 ; i < max_app_size << 1; i++)
			buffer[i] = (i & 1) ? 0x3F : 0xFF;
	}

	/* Locate the extension if it exists */
	for(i = strlen(file), q = NULL; i >= 0 ; i--){
		if(file[i] == '/'){
			break;
		}
		if(file[i] == '.'){
			q = file + i + 1;
			break;
		}
	}

	if(q)
		strncpy(exten, q, 18);

	if(!strcmp(exten, "hex")){
		/* Hex files */
		if(!(ihx = ihx_read( file, buffer, max_app_size << 1)))
			fatal("Could not open and/or read hex file");

		load_address = ihx->load_address >> 1;
		load_size = ihx->size >> 1;
		load_size_bytes = ihx->size;
		ihx_free(ihx);
	}
	else if(!strcmp(exten, "bin")){
コード例 #10
0
ファイル: ykfde.c プロジェクト: stevesbrain/mkinitcpio-ykfde
int main(int argc, char **argv) {
	unsigned int version = 0, help = 0;
	char challenge_old[CHALLENGELEN + 1],
		challenge_new[CHALLENGELEN + 1],
		response_old[RESPONSELEN],
		response_new[RESPONSELEN],
		passphrase_old[PASSPHRASELEN + 1],
		passphrase_new[PASSPHRASELEN + 1];
		const char * tmp;
	char challengefilename[sizeof(CHALLENGEDIR) + 11 /* "/challenge-" */ + 10 /* unsigned int in char */ + 1],
		challengefiletmpname[sizeof(CHALLENGEDIR) + 11 /* "/challenge-" */ + 10 /* unsigned int in char */ + 7 /* -XXXXXX */ + 1];
	int challengefile = 0, challengefiletmp = 0;
	struct timeval tv;
	int i;
	size_t len;
	int8_t rc = EXIT_FAILURE;
	/* cryptsetup */
	const char * device_name;
	int8_t luks_slot = -1;
	struct crypt_device *cryptdevice;
	crypt_status_info cryptstatus;
	crypt_keyslot_info cryptkeyslot;
	char * passphrase = NULL;
	/* keyutils */
	key_serial_t key;
	void * payload = NULL;
	char * second_factor = NULL, * new_2nd_factor = NULL, * new_2nd_factor_verify = NULL;
	/* yubikey */
	YK_KEY * yk;
	uint8_t yk_slot = SLOT_CHAL_HMAC2;
	unsigned int serial = 0;
	/* iniparser */
	dictionary * ini;
	char section_ykslot[10 /* unsigned int in char */ + 1 + sizeof(CONFYKSLOT) + 1];
	char section_luksslot[10 + 1 + sizeof(CONFLUKSSLOT) + 1];

	/* get command line options */
	while ((i = getopt_long(argc, argv, optstring, options_long, NULL)) != -1)
		switch (i) {
			case 'h':
				help++;
				break;
			case 'n':
			case 'N':
				if (new_2nd_factor != NULL) {
					fprintf(stderr, "We already have a new second factor. Did you specify it twice?\n");
					goto out10;
				}

				if (optarg == NULL) { /* N */
					if ((new_2nd_factor = ask_secret("new second factor")) == NULL)
						goto out10;

					if ((new_2nd_factor_verify = ask_secret("new second factor for verification")) == NULL)
						goto out10;

					if (strcmp(new_2nd_factor, new_2nd_factor_verify) != 0) {
						fprintf(stderr, "Verification failed, given strings do not match.\n");
						goto out10;
					}
				} else { /* n */
					new_2nd_factor = strdup(optarg);
					memset(optarg, '*', strlen(optarg));
				}

				break;
			case 's':
			case 'S':
				if (second_factor != NULL) {
					fprintf(stderr, "We already have a second factor. Did you specify it twice?\n");
					goto out10;
				}

				if (optarg == NULL) { /* S */
					second_factor = ask_secret("current second factor");
				} else { /* s */
					second_factor = strdup(optarg);
					memset(optarg, '*', strlen(optarg));
				}

				break;
			case 'V':
				version++;
				break;
		}

	if (version > 0)
		printf("%s: %s v%s (compiled: " __DATE__ ", " __TIME__ ")\n", argv[0], PROGNAME, VERSION);

	if (help > 0)
		fprintf(stderr, "usage: %s [-h|--help] [-n|--new-2nd-factor <new-2nd-factor>] [-N|--ask-new-2nd-factor]\n"
				"        [-s|--2nd-factor <2nd-factor>] [-S|--ask-2nd-factor] [-V|--version]\n", argv[0]);

	if (version > 0 || help > 0)
		return EXIT_SUCCESS;


	/* initialize random seed */
	gettimeofday(&tv, NULL);
	srand(tv.tv_usec * tv.tv_sec);

	/* initialize static buffers */
	memset(challenge_old, 0, CHALLENGELEN + 1);
	memset(challenge_new, 0, CHALLENGELEN + 1);
	memset(response_old, 0, RESPONSELEN);
	memset(response_new, 0, RESPONSELEN);
	memset(passphrase_old, 0, PASSPHRASELEN + 1);
	memset(passphrase_new, 0, PASSPHRASELEN + 1);

	if ((ini = iniparser_load(CONFIGFILE)) == NULL) {
		fprintf(stderr, "Could not parse configuration file.\n");
		goto out10;
	}

	if ((device_name = iniparser_getstring(ini, "general:" CONFDEVNAME, NULL)) == NULL) {
		/* read from crypttab? */
		/* get device from currently open devices? */
		fprintf(stderr, "Could not read LUKS device from configuration file.\n");
		goto out20;
	}

	/* init and open first Yubikey */
	if (yk_init() == 0) {
		perror("yk_init() failed");
		goto out20;
	}

	if ((yk = yk_open_first_key()) == NULL) {
		fprintf(stderr, "No Yubikey available.\n");
		goto out30;
	}

	/* read the serial number from key */
	if (yk_get_serial(yk, 0, 0, &serial) == 0) {
		perror("yk_get_serial() failed");
		goto out40;
	}

	/* get the yk slot */
	sprintf(section_ykslot, "%d:" CONFYKSLOT, serial);
	yk_slot = iniparser_getint(ini, "general:" CONFYKSLOT, yk_slot);
	yk_slot = iniparser_getint(ini, section_ykslot, yk_slot);
	switch (yk_slot) {
		case 1:
		case SLOT_CHAL_HMAC1:
			yk_slot = SLOT_CHAL_HMAC1;
			break;
		case 2:
		case SLOT_CHAL_HMAC2:
		default:
			yk_slot = SLOT_CHAL_HMAC2;
			break;
	}

	/* get the luks slot */
	sprintf(section_luksslot, "%d:" CONFLUKSSLOT, serial);
	luks_slot = iniparser_getint(ini, section_luksslot, luks_slot);
	if (luks_slot < 0) {
		fprintf(stderr, "Please set LUKS key slot for Yubikey with serial %d!\n"
				"Add something like this to " CONFIGFILE ":\n\n"
				"[%d]\nluks slot = 1\n", serial, serial);
		goto out40;
	}

	if (second_factor == NULL) {
		/* get second factor from key store */
		if ((key = request_key("user", "ykfde-2f", NULL, 0)) < 0)
			fprintf(stderr, "Failed requesting key. That's ok if you do not use\n"
					"second factor. Give it manually if required.\n");

		if (key > -1) {
			/* if we have a key id we have a key - so this should succeed */
			if (keyctl_read_alloc(key, &payload) < 0) {
				perror("Failed reading payload from key");
				goto out40;
			}
			second_factor = payload;
		} else
			second_factor = strdup("");
	}

	/* warn when second factor is not enabled in config */
	if ((*second_factor != 0 || new_2nd_factor != NULL) &&
			iniparser_getboolean(ini, "general:" CONF2NDFACTOR, 0) == 0)
		fprintf(stderr, "Warning: Processing second factor, but not enabled in config!\n");

	/* get random number and limit to printable ASCII character (32 to 126) */
	for(i = 0; i < CHALLENGELEN; i++)
		challenge_new[i] = (rand() % (126 - 32)) + 32;

	/* these are the filenames for challenge
	 * we need this for reading and writing */
	sprintf(challengefilename, CHALLENGEDIR "/challenge-%d", serial);
	sprintf(challengefiletmpname, CHALLENGEDIR "/challenge-%d-XXXXXX", serial);

	/* write new challenge to file */
	if ((challengefiletmp = mkstemp(challengefiletmpname)) < 0) {
		fprintf(stderr, "Could not open file %s for writing.\n", challengefiletmpname);
		goto out40;
	}
	if (write(challengefiletmp, challenge_new, CHALLENGELEN) < 0) {
		fprintf(stderr, "Failed to write challenge to file.\n");
		goto out50;
	}
	challengefiletmp = close(challengefiletmp);

	/* now that the new challenge has been written to file...
	 * add second factor to new challenge */
	tmp = new_2nd_factor ? new_2nd_factor : second_factor;
	len = strlen(tmp);
	memcpy(challenge_new, tmp, len < MAX2FLEN ? len : MAX2FLEN);

	/* do challenge/response and encode to hex */
	if (yk_challenge_response(yk, yk_slot, true,
			CHALLENGELEN, (unsigned char *) challenge_new,
			RESPONSELEN, (unsigned char *) response_new) == 0) {
		perror("yk_challenge_response() failed");
		goto out50;
	}
	yubikey_hex_encode((char *) passphrase_new, (char *) response_new, SHA1_DIGEST_SIZE);

	/* get status of crypt device
	 * We expect this to be active (or busy). It is the actual root device, no? */
	cryptstatus = crypt_status(cryptdevice, device_name);
	if (cryptstatus != CRYPT_ACTIVE && cryptstatus != CRYPT_BUSY) {
                fprintf(stderr, "Device %s is invalid or inactive.\n", device_name);
		goto out50;
	}

	/* initialize crypt device */
	if (crypt_init_by_name(&cryptdevice, device_name) < 0) {
		fprintf(stderr, "Device %s failed to initialize.\n", device_name);
		goto out60;
	}

	cryptkeyslot = crypt_keyslot_status(cryptdevice, luks_slot);

	if (cryptkeyslot == CRYPT_SLOT_INVALID) {
		fprintf(stderr, "Key slot %d is invalid.\n", luks_slot);
		goto out60;
	} else if (cryptkeyslot == CRYPT_SLOT_ACTIVE || cryptkeyslot == CRYPT_SLOT_ACTIVE_LAST) {
		/* read challenge from file */
		if ((challengefile = open(challengefilename, O_RDONLY)) < 0) {
			perror("Failed opening challenge file for reading");
			goto out60;
		}

		if (read(challengefile, challenge_old, CHALLENGELEN) < 0) {
			perror("Failed reading challenge from file");
			goto out60;
		}

		challengefile = close(challengefile);
		/* finished reading challenge */

		/* copy the second factor */
		len = strlen(second_factor);
		memcpy(challenge_old, second_factor, len < MAX2FLEN ? len : MAX2FLEN);

		/* do challenge/response and encode to hex */
		if (yk_challenge_response(yk, yk_slot, true,
				CHALLENGELEN, (unsigned char *) challenge_old,
				RESPONSELEN, (unsigned char *) response_old) == 0) {
			perror("yk_challenge_response() failed");
			goto out60;
		}
		yubikey_hex_encode((char *) passphrase_old, (char *) response_old, SHA1_DIGEST_SIZE);

		if (crypt_keyslot_change_by_passphrase(cryptdevice, luks_slot, luks_slot,
				passphrase_old, PASSPHRASELEN,
				passphrase_new, PASSPHRASELEN) < 0) {
			fprintf(stderr, "Could not update passphrase for key slot %d.\n", luks_slot);
			goto out60;
		}

		if (unlink(challengefilename) < 0) {
			fprintf(stderr, "Failed to delete old challenge file.\n");
			goto out60;
		}
	} else { /* ck == CRYPT_SLOT_INACTIVE */
		if ((passphrase = ask_secret("existing LUKS passphrase")) == NULL)
			goto out60;

		if (crypt_keyslot_add_by_passphrase(cryptdevice, luks_slot,
				passphrase, strlen(passphrase),
				passphrase_new, PASSPHRASELEN) < 0) {
			fprintf(stderr, "Could not add passphrase for key slot %d.\n", luks_slot);
			goto out60;
		}
	}

	if (rename(challengefiletmpname, challengefilename) < 0) {
		fprintf(stderr, "Failed to rename new challenge file.\n");
		goto out60;
	}

	rc = EXIT_SUCCESS;

out60:
	/* free crypt context */
	crypt_free(cryptdevice);

out50:
	/* close the challenge file */
	if (challengefile)
		close(challengefile);
	if (challengefiletmp)
		close(challengefiletmp);
	if (access(challengefiletmpname, F_OK) == 0)
		unlink(challengefiletmpname);

out40:
	/* close Yubikey */
	if (yk_close_key(yk) == 0)
		perror("yk_close_key() failed");

out30:
	/* release Yubikey */
	if (yk_release() == 0)
		perror("yk_release() failed");

out20:
	/* free iniparser dictionary */
	iniparser_freedict(ini);

out10:
	/* wipe response (cleartext password!) from memory */
	/* This is statically allocated and always save to wipe! */
	memset(challenge_old, 0, CHALLENGELEN + 1);
	memset(challenge_new, 0, CHALLENGELEN + 1);
	memset(response_old, 0, RESPONSELEN);
	memset(response_new, 0, RESPONSELEN);
	memset(passphrase_old, 0, PASSPHRASELEN + 1);
	memset(passphrase_new, 0, PASSPHRASELEN + 1);

	free(passphrase);
	free(new_2nd_factor_verify);
	free(new_2nd_factor);
	free(second_factor);

	return rc;
}
コード例 #11
0
ファイル: util.c プロジェクト: odmann/mca
int
parse_ini_file(char *key, char *def, char *val, char *res)
{
	FILE		*fd;
	dictionary	*d;
	int		ini_update = 0;
	char		section[256] = {0};

	switch( check_inifile() ) {
	case 0:
		return 0;
	case 1:
		return 1;
	case 2:
		ini_cur = ini_default;
		d = iniparser_load(ini_default);
		if (d) {
			fd = fopen(ini_name, "w");
			if (fd) {
				iniparser_dump_ini(d, fd);
				fclose(fd);
				iniparser_freedict(d);
				ini_cur = ini_name;
				ini_update = 1;
				break;
			}
		} else {
			fprintf(stderr, "cannot parse file: %s\n",ini_cur);
		}
		return 0;
		break;
	case 3:
		ini_cur = ini_name;
		break;
	case 4:
		ini_cur = "/mnt/sd/mcaboot.ini";
		break;
	default:
		break;
	}

	d = iniparser_load(ini_cur);
	if (!d) {
		fprintf(stderr, "cannot parse file: %s\n", ini_cur);
		return -1;
	}

	if (key && val) {
		char *s = iniparser_getstring(d, key, NULL);
		if (s) {
			if (strcmp(s, val)) {
				iniparser_set(d, key, val);
				ini_update = 1;
			}
		} else {
			iniparser_get_section_string(key, section);
			iniparser_set(d, section, NULL);
			iniparser_set(d, key, val);
			ini_update = 1;
		}
	}

	if (key && res) {
		char *s = iniparser_getstring(d, key, def);
		strcpy(res, s);
	}

	if (ini_update) {
		fd = fopen(ini_name, "w");
		if (fd) {
			iniparser_dump_ini(d, fd);
			fflush(fd);
			fclose(fd);
		}
	}
	iniparser_freedict(d);
	return 0;
}
コード例 #12
0
/** 
 *	Load all Sensors and read their
 *	preferences from the ini file 
 */
int LoadSensors(void)
{
	//load the iniparser on the sensor path
	dictionary*ini=iniparser_load(sensorinipath());
	if(!ini)
		return EXIT_FAILURE;

	// just to be sure
	//SetupSensors();

	if(!iniparser_find_entry(ini, "sensor"))
	{
		Log(LOGT_SERVER, LOGL_ERROR, "File %s does not contain sensor config section",  sensorinipath());
		goto exit_failure;
	}
	if(!iniparser_find_entry(ini, "sensor:typecount"))
	{
		Log(LOGT_SERVER, LOGL_ERROR, "No sensor typecount present");
		goto exit_failure;
	}
	{
		int typecount = iniparser_getint(ini, "sensor:typecount", 0);
		interval = iniparser_getint(ini, "sensor:interval", 1);

		// user requested to turn off sensors.
		if(typecount<1)goto exit_success;
		for(;typecount;typecount--)
		{
			const unsigned int idstringlen=12+numlen((unsigned)typecount);
			const unsigned int namelen=idstringlen+4;
			const unsigned int amountlen=idstringlen+5;
			const unsigned int typelen=idstringlen+4;
			char idstring[idstringlen];
			char name[namelen];
			char amount[amountlen];
			char typeq[typelen];
			sensortype stype=integersensor;

			snprintf(idstring, sizeof(char)*idstringlen, "sensor:type%d", typecount);
			snprintf(name, sizeof(char)*namelen, "%s%s", idstring, "name");
			snprintf(amount, sizeof(char)*amountlen, "%s%s", idstring, "count");

			if(!iniparser_find_entry(ini, name)||!iniparser_find_entry(ini, amount))
			{
				Log(LOGT_SERVER, LOGL_WARNING, "Skipping incomplete %s definition", idstring);
				continue;
			}

			snprintf(typeq, sizeof(char)*typelen, "%s%s", idstring, "type");
			{
				char const*const typea = iniparser_getstring(ini, typeq, "integer");

				if(!strcmp(typea, "binary"))
				{
					stype=binarysensor;
				}
				else if(!strcmp(typea, "integer")){;/*fallthrough*/;}
				else
				{
					Log(LOGT_SERVER, LOGL_WARNING, "Unrecognised type %s,  falling back on integer");
				}
	
				if(stype==binarysensor)
				{
					const unsigned int alarmlen=idstringlen+5;
					char alarmq[alarmlen];

					snprintf(alarmq, sizeof(char)*alarmlen, "%s%s", idstring, "alarm");

					genbSensors(
						iniparser_getstring(ini, name, "genericb"), 
						iniparser_getint(ini, amount, 0), 
						iniparser_getstring(ini, alarmq, "Alarm!"));
				}
				else if(stype==integersensor)
				{
					const unsigned int startlen=idstringlen+5;
					const unsigned int alarmlen=idstringlen+6;
					const unsigned int boundlen=idstringlen+6;
					const unsigned int boundcrosslen=idstringlen+11;
					signed int min, max;
					char startq[startlen];
					char lalarmq[alarmlen];
					char ualarmq[alarmlen];
					char lboundq[boundlen];
					char uboundq[boundlen];
					char lboundcrossq[boundcrosslen];
					char uboundcrossq[boundcrosslen];

					snprintf(startq, sizeof(char)*startlen, "%s%s", idstring, "start");
					snprintf(lalarmq, sizeof(char)*alarmlen, "%s%s", idstring, "lalarm");
					snprintf(ualarmq, sizeof(char)*alarmlen, "%s%s", idstring, "ualarm");
					snprintf(lboundq, sizeof(char)*boundlen, "%s%s", idstring, "lbound");
					snprintf(uboundq, sizeof(char)*boundlen, "%s%s", idstring, "ubound");
					snprintf(lboundcrossq, sizeof(char)*boundcrosslen, "%s%s", idstring, "lboundcross");
					snprintf(uboundcrossq, sizeof(char)*boundcrosslen, "%s%s", idstring, "uboundcross");
					
					min = iniparser_getint(ini, lboundq, INT_MIN);
					max = iniparser_getint(ini, uboundq, INT_MAX);

					geniSensors(
						iniparser_getstring(ini, name, "generici"), 
						iniparser_getint(ini, amount, 0), 
						iniparser_getint(ini, startq, ((min+max)/2)),
						min,
						max, 
						iniparser_getstring(ini, lalarmq, "lower bound Alarm!"), 
						iniparser_getstring(ini, ualarmq, "upper bound Alarm!"),
						iniparser_getboolean(ini, lboundcrossq, true), 
						iniparser_getboolean(ini, uboundcrossq, true));
				}
				else
				{
					Log(LOGT_SERVER, LOGL_ERROR, "Unknown sensor type %d from %s", stype, typea);
				}
			}		
		}
	}

	exit_success:
		iniparser_freedict(ini);
		return EXIT_SUCCESS;
	exit_failure:
		iniparser_freedict(ini);
		return EXIT_FAILURE;
}
コード例 #13
0
ファイル: main.c プロジェクト: Kakama/denice
// Main function
int main(int argc, char** argv){
	irc_callbacks_t irc_callbacks;
	char* host_str;
	int host_len, ssl;
	I = 0;
	
	if(argc != 2)
		error(1, "Error: config file must be specified on comand line\n");
	
	// load config from ini
	conf_file = argv[1];
	C = iniparser_load(conf_file);
	
	// parse server config and generate a string to give to libircclient
	ssl = iniparser_getboolean(C, "server:ssl", 0);
	host_len = strlen(iniparser_getstring(C, "server:host", "")) + (ssl ? 1 : 0);
	host_str = malloc(host_len + 1);
	host_str[0] = '#';
	host_str[host_len] = '\0';
	strcpy(&host_str[ssl ? 1 : 0], iniparser_getstring(C, "server:host", ""));
	
	// init local data structures
	mem_init();
	cbtable_init();
		
	// init mysql
	S = mysql_init(NULL);
	if(mysql_real_connect(S,
	      iniparser_getstring(C, "mysql:host", "localhost"),
	      iniparser_getstring(C, "mysql:user", "root"),
	      iniparser_getstring(C, "mysql:pass", ""),
	      iniparser_getstring(C, "mysql:database", ""),
	      iniparser_getint(C, "mysql:port", 0), 0, 0) == NULL) 
	    error(1, "Unable to connect to mysql: %s\n", mysql_error(S));
	
	// init lua
	L = luaL_newstate();
	luaL_openlibs(L);
	register_lua_functions();
	if(luaL_dofile(L, iniparser_getstring(C,"bot:file","/dev/null"))){
		size_t lua_errlen = 0;
		const char* lua_error = luaL_checklstring(L, -1, &lua_errlen);
		error(1, "Error processing Lua script:\n%s\n", lua_error);
	}

	// init libircclient
	memset(&irc_callbacks, 0, sizeof(irc_callbacks));
	irc_callbacks.event_connect = event_generic;
	irc_callbacks.event_nick    = event_generic;
	irc_callbacks.event_quit    = event_generic;
	irc_callbacks.event_join    = event_generic;
	irc_callbacks.event_part    = event_generic;
	irc_callbacks.event_mode    = event_generic;
	irc_callbacks.event_umode   = event_generic;
	irc_callbacks.event_topic   = event_generic;
	irc_callbacks.event_kick    = event_generic;
	irc_callbacks.event_channel = event_command;
	irc_callbacks.event_privmsg = event_command;
	irc_callbacks.event_notice  = event_generic;
	irc_callbacks.event_unknown = event_generic;
	irc_callbacks.event_invite  = event_generic;
	irc_callbacks.event_ctcp_req = event_generic;
	irc_callbacks.event_ctcp_rep = event_generic;
	irc_callbacks.event_ctcp_action = event_generic;
	irc_callbacks.event_channel_notice = event_generic;
	irc_callbacks.event_numeric = event_numeric;
	do_quit = 0;

	while(!do_quit){
		if(I) irc_destroy_session(I);

		I = irc_create_session(&irc_callbacks);
		if(!I)
			error(1, "Unable to create IRC session... probably out of memory\n");
		irc_option_set(I, LIBIRC_OPTION_STRIPNICKS);
		irc_option_set(I, LIBIRC_OPTION_SSL_NO_VERIFY);
		//irc_option_set(I, LIBIRC_OPTION_DEBUG);
		
		// initialize irc server connection
		if(irc_connect(I,
				   host_str,
				   iniparser_getint(C,"server:port",6667), 0,
				   iniparser_getstring(C,"bot:nick","bot"),
				   iniparser_getstring(C,"bot:user","bot"),
				   "libircclient"
				  ))
			irc_error(I,1);
	
		// not sure why we need to sleep here, but if we don't, we can't connect
		sleep(1);
	
		// run the irc client loop
		if(irc_run(I))
		irc_error(I,0);
	}
	
	// clean up
	mysql_close(S);
	irc_destroy_session(I);
	lua_close(L);
	cbtable_destroy();
	iniparser_freedict(C);
	free(host_str);
	return EXIT_SUCCESS;
}
コード例 #14
0
ファイル: cspay.c プロジェクト: rosedu/cspay
char *
cspay_convert_single_file(char *fname)
{
	struct class_info *ci;
	char *ods_fname = NULL;
	size_t class_index;
	time_t month_start;
	time_t month_end;
	time_t index;
	size_t table_crt;	/* int vs. size_t ???*/
	char *tmp_str;
	int ccs;	/* current cell style */

	int tmp_sum_prof;
	int tmp_sum_conf;
	int tmp_sum_sl;
	int tmp_sum_as;
	int tmp_sum;

	int i;

	const char roles[4][14] = {
			{"as"},
			{"conf"},
			{"sl"},
			{"prof"}
	};

	Dprintf("Processing ini file\n");


	/* init ini file parsing */
	ini = iniparser_load(fname);
	if (!ini) {
		fprintf(stderr, ".ini file not found, try personal.ini\n");
		ini = iniparser_load("personal.ini");
		if (!ini){
			fprintf(stderr, "personal.ini not found, bye!\n");
			return NULL;
		}
	}

	/* create new spreadsheet */
	doc = spreadconv_new_spreadconv_data("Date", 60, 9);

	/* configure spreadsheet column and cell styles */
	if (config_styles()){
		iniparser_freedict(ini);
		spreadconv_free_spreadconv_data(doc);
		return NULL;
	}

	/* use ini file to create spreadsheet header */
	if (create_header()) {
		iniparser_freedict(ini);
		spreadconv_free_spreadconv_data(doc);
		return NULL;
	}

	month_start = mktime(month_date);
	++ month_date->tm_mon;
	if (month_date->tm_mon == 12){
		month_date->tm_mon = 0;
		++ month_date->tm_year;
	}
	month_end = mktime(month_date) - 1;
	
	/*
	 * browse the classes and add data to spreadsheet
	 * FIXME str* hazards
	 */

	class_index = 1;
	table_crt = 0;

	while (1) {
		Dprintf("Begin rule number%d\n", class_index);

		ci = read_class_info (class_index);
		if (ci == NULL)
			break;

		index = get_first_work_day(month_start, month_end, cfg, ci);
		
		Dprintf("First working day is: %d\n",
					localtime(&index)->tm_mday);
		
		/*
		 * iterate through the same day of different weeks
		 */

		tmp_sum_prof = tmp_sum_conf = tmp_sum_sl = tmp_sum_as = 0;
		tmp_sum = 0;
		#define TC	7	/*table content start row*/
		for (/* no init */; index < month_end;
				index += ci->class_parity * WEEK) {
			if (!is_work(cfg, index))
				continue;
			/* NR. crt */
			ccs = ds->table_c[0];
			doc->cells[TC + table_crt][0].text = malloc(4);
			sprintf(doc->cells[TC + table_crt][0].text, "%d", (int) table_crt + 1);
			spreadconv_set_cell_style(TC + table_crt, 0, ccs, doc);

			/* Felul si nr. post*/
			ccs = ds->table_c[1];
			doc->cells[TC + table_crt][1].text = malloc(10);
			sprintf(doc->cells[TC + table_crt][1].text, "%s%s", roles[ci->class_role_type], ci->class_role_num);
			spreadconv_set_cell_style(TC + table_crt, 1, ccs, doc);


			/* faculty */
			doc->cells[TC + table_crt][2].text = strdup(ci->class_faculty);
			spreadconv_set_cell_style(TC + table_crt, 2, ccs, doc);

			/* course */
			doc->cells[TC + table_crt][3].text = strdup(ci->class_course);
			spreadconv_set_cell_style(TC + table_crt, 3, ccs, doc);

			if (ci->class_type) {/* e aplicatie */
				doc->cells[TC + table_crt][5].value_type = strdup("float");
				doc->cells[TC + table_crt][5].text = malloc(4);
				sprintf(doc->cells[TC + table_crt][5].text, "%d", ci->class_h_end - ci->class_h_start);
			} else { /* e curs */
				doc->cells[TC + table_crt][4].value_type = strdup("float");
				doc->cells[TC + table_crt][4].text = malloc(4);
				sprintf(doc->cells[TC + table_crt][4].text, "%d", ci->class_h_end - ci->class_h_start);
			}
			spreadconv_set_cell_style(TC + table_crt, 4, ccs, doc);
			spreadconv_set_cell_style(TC + table_crt, 5, ccs, doc);

			ccs = ds->table_c[2];
			/* group */
			doc->cells[TC + table_crt][6].text = strdup(ci->class_group);
			spreadconv_set_cell_style(TC + table_crt, 6, ccs, doc);

			/* date */
			doc->cells[TC + table_crt][7].text = malloc(20);
			strftime(doc->cells[TC + table_crt][7].text, 19, "%d-%b", localtime(&index));
			spreadconv_set_cell_style(TC + table_crt, 7, ccs, doc);
				
			/* FIXME: no validation on class timeline */
			/* Time */
			tmp_str = malloc (10);
			sprintf (tmp_str, "%02d-%02d", ci->class_h_start,
					ci->class_h_end);
			doc->cells[TC + table_crt][8].text = tmp_str;
			spreadconv_set_cell_style(TC + table_crt, 8, ccs, doc);

			++ table_crt;
			tmp_sum +=  ci->class_h_end - ci->class_h_start;
		}

		Dprintf("End rule number: %d\n", class_index);
		if (ci->class_type) {/* e aplicatie*/
			if (ci->class_role_type == 0)
				result.aplic.as += tmp_sum;
			if (ci->class_role_type == 1)
				result.aplic.conf += tmp_sum;
			if (ci->class_role_type == 2)
				result.aplic.sl += tmp_sum;
			if (ci->class_role_type == 3)
				result.aplic.prof += tmp_sum;
		} else {	/* e curs */
			if (ci->class_role_type == 0)
				result.course.as += tmp_sum;
			if (ci->class_role_type == 1)
				result.course.conf += tmp_sum;
			if (ci->class_role_type == 2)
				result.course.sl += tmp_sum;
			if (ci->class_role_type == 3)
				result.course.prof += tmp_sum;
		}
		++ class_index;
		free (ci);
	}
	Dprintf("End of all rules.\n");
	
	spreadconv_set_cell_style(TC + table_crt - 1, 0, ds->table_b[0], doc);
	spreadconv_set_cell_style(TC + table_crt - 1, 1, ds->table_b[1], doc);
	spreadconv_set_cell_style(TC + table_crt - 1, 2, ds->table_b[1], doc);
	spreadconv_set_cell_style(TC + table_crt - 1, 3, ds->table_b[1], doc);
	spreadconv_set_cell_style(TC + table_crt - 1, 4, ds->table_b[1], doc);
	spreadconv_set_cell_style(TC + table_crt - 1, 5, ds->table_b[1], doc);
	spreadconv_set_cell_style(TC + table_crt - 1, 6, ds->table_b[2], doc);
	spreadconv_set_cell_style(TC + table_crt - 1, 7, ds->table_b[2], doc);
	spreadconv_set_cell_style(TC + table_crt - 1, 8, ds->table_b[2], doc);
	
	/* create spreadsheet footer */
	create_footer (TC + table_crt);

	spreadconv_dir_name = strdup("./out/");

	Dprintf("Begin output file\n");

	ods_fname = spreadconv_create_spreadsheet(doc, LSC_FILE_ODS);
	if (!ods_fname) {
		fprintf(stderr, "Error creating .ods file\n");
		return NULL;
	} else {
		Dprintf("Output: %s\n\n", ods_fname);
	}

	spreadconv_free_spreadconv_data(doc);
	iniparser_freedict(ini);
	free(spreadconv_dir_name);

	return ods_fname;
}
コード例 #15
0
ファイル: vt_config.c プロジェクト: sniweef/VoiceTester
int vt_initConfig(const char *pFilePath)
{
    dictionary *pIniDict;

    if ((pIniDict = iniparser_load(pFilePath)) == NULL)
    {
        CX_LOGL(CX_WARN, "Loading ini file: %s failed! Will load default config.", pFilePath);
        loadDefaultConfig();
        return VT_FAILED;
    }

    //iniparser_dump(pIniDict, stderr);

    char *pIPStr = iniparser_getstring(pIniDict, "VoIPServer:IP", VOIP_SERVER_IP_STR);
    if (inet_pton(AF_INET, pIPStr, &g_vtConfig.serverIP) != 1)
    {
        g_vtConfig.serverIP = VOIP_SERVER_IP_INT;
        CX_LOGL(CX_ERR, "inet_pton: IP %s is incorrect. Modify it to %x", pIPStr, VOIP_SERVER_IP_INT);
        return VT_FAILED;
    }

    g_vtConfig.serverIP = ntohl(g_vtConfig.serverIP);
    g_vtConfig.serverPort = iniparser_getint(pIniDict, "VoIPServer:Port", VOIP_SERVER_PORT);
    g_vtConfig.clientListenPort = iniparser_getint(pIniDict, "VoIPClient:ListenPort", CLIENT_PORT);

    pIPStr = iniparser_getstring(pIniDict, "OuterVoIPClient:IP", OUTER_CLIENT_IP_STR);
    if (inet_pton(AF_INET, pIPStr, &g_vtConfig.outerClientIP) != 1)
    {
        g_vtConfig.outerClientIP = OUTER_CLIENT_IP;
        CX_LOGL(CX_ERR, "inet_pton: IP %s is incorrect.", pIPStr);
        return VT_FAILED;
    }

    g_vtConfig.outerClientIP = ntohl(g_vtConfig.outerClientIP);
    g_vtConfig.outerClientListenPort = iniparser_getint(pIniDict, "OuterVoIPClient:ListenPort", OUTER_CLIENT_PORT);
    g_vtConfig.outClientNumber = iniparser_getint(pIniDict, "OuterVoIPClient:Number", OUTER_CLIENT_NUM);

    g_vtConfig.breakMax = iniparser_getint(pIniDict, "Debug:BreakMax", DEFAULT_BREAK_MAX);

    int index;
    char keyname[BUFF_MAX];

    for (index = 0; index < DTMF_DIGIT_AMOUNT; index++)
    {
        snprintf(keyname, BUFF_MAX, "DTMFDigitMap:Key%d", index);

        g_vtConfig.dtmfDigitMap[index] = iniparser_getint(pIniDict, keyname, 0);
    }

    for (index = 0; index < VT_ENDPT_MAX; index++)
    {
        snprintf(keyname, BUFF_MAX, "Endpt%d:Port", index);
        g_vtConfig.endptInfo[index].port = iniparser_getint(pIniDict, keyname, 0);

        snprintf(keyname, BUFF_MAX, "Endpt%d:CtrlPort", index);
        g_vtConfig.endptInfo[index].ctrlport = iniparser_getint(pIniDict, keyname, 0);

        snprintf(keyname, BUFF_MAX, "Endpt%d:Number", index);
        g_vtConfig.endptInfo[index].number = iniparser_getint(pIniDict, keyname, 0);
    }

    g_vtConfig.storeEventMax = iniparser_getint(pIniDict, "EventQueue:EventMax", DEFAULT_EVENT_QUEUE_SIZE);

    g_vtConfig.historySize = iniparser_getint(pIniDict, "Readline:HistorySize", DEFAULT_HISTORY_SIZE);

    iniparser_freedict(pIniDict);

    return VT_SUCCESS;
}
コード例 #16
0
ファイル: cras_card_config.c プロジェクト: drinkcat/adhd
void cras_card_config_destroy(struct cras_card_config *card_config)
{
	assert(card_config);
	iniparser_freedict(card_config->ini);
	free(card_config);
}
コード例 #17
0
int main(int argc, char* argv[])
{
#ifdef VAULTMP_DEBUG
#ifdef __WIN32__

	if (LoadLibrary("exchndl.dll") == NULL)
		return 0;

#else
	system("ulimit -c unlimited");
#endif
#endif

#ifdef __WIN32__
	printf("Vault-Tec dedicated server %s (Windows)\n----------------------------------------------------------\n", DEDICATED_VERSION);
#else
	printf("Vault-Tec dedicated server %s (Unix)\n----------------------------------------------------------\n", DEDICATED_VERSION);
#endif

	unsigned char game;
	int port;
	int players;
	int fileslots;
	bool query;
	bool files;
	const char* announce;
	const char* scripts;
	const char* mods;
	const char* savegame;

	dictionary* config = iniparser_load(argc > 1 ? argv[1] : "vaultserver.ini");

	const char* game_str = iniparser_getstring(config, "general:game", "fallout3");

	if (stricmp(game_str, "newvegas") == 0)
		game = NEWVEGAS;
	else
		game = FALLOUT3;

	port = iniparser_getint(config, "general:port", RAKNET_STANDARD_PORT);
	players = iniparser_getint(config, "general:players", RAKNET_STANDARD_CONNECTIONS);
	query = (bool) iniparser_getboolean(config, "general:query", 1);
	files = (bool) iniparser_getboolean(config, "general:fileserve", 0);
	fileslots = iniparser_getint(config, "general:fileslots", 8);
	announce = iniparser_getstring(config, "general:master", "vaultmp.com");
	savegame = iniparser_getstring(config, "general:save", "default.fos");
	scripts = iniparser_getstring(config, "scripts:scripts", "");
	mods = iniparser_getstring(config, "mods:mods", "");

	ServerEntry* self = new ServerEntry(game);
	self->SetServerRule("version", DEDICATED_VERSION);
	Dedicated::SetServerEntry(self);

	char base[MAX_PATH];
	_getcwd(base, sizeof(base));

	try
	{
		putenv(PWNFILES_PATH);
		char _scripts[strlen(scripts) + 1];
		snprintf(_scripts, sizeof(_scripts), "%s", scripts);
		Script::LoadScripts(_scripts, base);
	}

	catch (std::exception& e)
	{
		try
		{
			VaultException& vaulterror = dynamic_cast<VaultException&>(e);
			vaulterror.Console();
		}

		catch (std::bad_cast& no_vaulterror)
		{
			VaultException vaulterror(e.what());
			vaulterror.Console();
		}
	}

	try
	{
		char file[MAX_PATH];
		snprintf(file, sizeof(file), "%s/%s/%s", base, SAVEGAME_PATH, savegame);

		unsigned int crc;

		if (!Utils::crc32file(file, &crc))
			throw VaultException("Could not find savegame %s in folder %s", savegame, SAVEGAME_PATH);

		Dedicated::SetSavegame(Savegame(string(savegame), crc));

		char buf[strlen(mods) + 1];
		strcpy(buf, mods);
		char* token = strtok(buf, ",");
		ModList modfiles;

		while (token != NULL)
		{
			snprintf(file, sizeof(file), "%s/%s/%s", base, MODFILES_PATH, token);

			if (!Utils::crc32file(file, &crc))
				throw VaultException("Could not find modfile %s in folder %s", token, MODFILES_PATH);

			modfiles.push_back(pair<string, unsigned int>(string(token), crc));

			token = strtok(NULL, ",");
		}

		Dedicated::SetModfiles(modfiles);

		thread hDedicatedThread = Dedicated::InitializeServer(port, players, announce, query, files, fileslots);
		thread hInputThread = thread(InputThread);

		hDedicatedThread.join();

		if (hInputThread.joinable())
			hInputThread.join();
	}

	catch (std::exception& e)
	{
		try
		{
			VaultException& vaulterror = dynamic_cast<VaultException&>(e);
			vaulterror.Console();
		}

		catch (std::bad_cast& no_vaulterror)
		{
			VaultException vaulterror(e.what());
			vaulterror.Console();
		}
	}

	Script::UnloadScripts();
	iniparser_freedict(config);
	delete self;

#ifdef __WIN32__
	system("PAUSE");
#endif

	return 0;
}
コード例 #18
0
ファイル: GameMain_GLFW.cpp プロジェクト: ilijabc/Kosmos2D
int main(int argc, char *argv[])
{
    if (!glfwInit())
    {
        LOG("init fail");
        return 0;
    }

    dictionary *ini = iniparser_load("Data/settings.ini");
    int width = iniparser_getint(ini, "video:width", 640);
    int height = iniparser_getint(ini, "video:height", 480);
    int fullscreen = iniparser_getint(ini, "video:fullscreen", 0);
    int desktop = iniparser_getint(ini, "video:desktop", 0);
	int audio = iniparser_getint(ini, "audio:enabled", 0);
    iniparser_freedict(ini);
#ifdef DEBUG
	width = 800;
	height = 600;
	fullscreen = 0;
	desktop = 0;
#else
    if (desktop)
    {
        GLFWvidmode dm;
        glfwGetDesktopMode(&dm);
        width = dm.Width;
        height = dm.Height;
        fullscreen = 1;
    }
#endif

    //glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
    if (!glfwOpenWindow(width, height, 8, 8, 8, 8, 16, 0, fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOW))
    {
        LOG("failed opening window");
        glfwTerminate();
        return 0;
    }
    glfwSwapInterval(0);
    glfwSetWindowTitle("GLFW Application + GLPlus");
    glfwSetKeyCallback(cb_key);
    glfwSetMousePosCallback(cb_mouse_pos);
    glfwSetMouseButtonCallback(cb_mouse_button);
    glfwSetMouseWheelCallback(cb_mouse_wheel);
    glfwSetWindowSizeCallback(cb_size);
    if (fullscreen)
        glfwEnable(GLFW_MOUSE_CURSOR);

    //
    //init
    //
    g_game = new GameApp(width, height, audio ? true : false);
    float ftime = glfwGetTime();

    while (glfwGetWindowParam(GLFW_OPENED))
    {
        //
        //update
        //
        float dt = glfwGetTime() - ftime;
        g_game->onUpdate(dt);
        ftime = glfwGetTime();

        //
        //draw
        //
        glClearColor(0.2, 0.2, 0.2, 1.0);
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
        g_game->onDraw();
        glfwSwapBuffers();
    }

    //finish
    delete g_game;

    glfwTerminate();

    return 0;
}
コード例 #19
0
void IniFreeDict(dictionary * dict)
{
    iniparser_freedict((struct _dictionary_ *)dict);
}
コード例 #20
0
ファイル: ini_config.c プロジェクト: gozfree/libraries
static void ini_unload(struct config *c)
{
    dictionary *ini = (dictionary *)c->priv;
    iniparser_freedict(ini);
}
コード例 #21
0
ファイル: INIManager.c プロジェクト: mechpaul/NXPatcher
void INIDestroyManager(void)
{
	iniparser_freedict(ConfigINI);
	ConfigINI = NULL;
}
コード例 #22
0
ファイル: ai_params.c プロジェクト: kohr-h/ETreco
void
AiParams_assign_from_AiOpts (AiParams *params, const AiOpts *opts)
{
  int itmp;
  float ta_sx, ta_sy;
  double dtmp;
  dictionary *dict;

  CAPTURE_NULL_VOID (params);
  CAPTURE_NULL_VOID (opts);

  if ((dict = iniparser_load (opts->fname_params)) == NULL)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Unable to read parameters from %s.", opts->fname_params);
      return;
    }

  /* Regularization */

  /* TODO: implement anisotropic mollifier (3 gamma's) */
  vec3_set_all (params->gamma, opts->gamma * ONE_MICROMETER);
  params->moll_ft = moll_types[opts->moll_type];


  /* VOLUME */

  if ((itmp = iniparser_getint (dict, "volume:nx", -1)) == -1)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'nx' not found in %s.", opts->fname_params);
      return;
    }

  params->vol_shape[0] = itmp;
  
  if ((itmp = iniparser_getint (dict, "volume:ny", -1)) == -1)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'ny' not found in %s.", opts->fname_params);
      return;
    }

  params->vol_shape[1] = itmp;

  if ((itmp = iniparser_getint (dict, "volume:nz", -1)) == -1)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'nz' not found in %s.", opts->fname_params);
      return;
    }

  params->vol_shape[2] = itmp;

  if ((dtmp = iniparser_getdouble (dict, "volume:voxel_size", FLT_MAX)) == FLT_MAX)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'voxel_size' not found in %s.", opts->fname_params);
      return;
    }

  vec3_set_all (params->vol_csize, (float) dtmp);

  /* Overrides MRC header */
  params->vol_shift_px[0] = (float) iniparser_getdouble (dict, "volume:shift_x", FLT_MAX);
  params->vol_shift_px[1] = (float) iniparser_getdouble (dict, "volume:shift_y", FLT_MAX);
  params->vol_shift_px[2] = (float) iniparser_getdouble (dict, "volume:shift_z", FLT_MAX);

  
  /* GEOMETRY */
  
  /* Single axis: parallel tilt axis shift */
  dtmp = iniparser_getdouble (dict, "geometry:tilt_axis", 0.0);
  if (fabsf (dtmp) < 45.0)  /* Use "x" backprojection variant */
    {
      params->tilt_axis = 0;
      params->tilt_axis_rotation = (float) dtmp;
    }
  else
    {
      params->tilt_axis = 1;
      /* What's missing to +- 90 degrees */
      params->tilt_axis_rotation = (dtmp > 0) ? (float)(dtmp - 90.0) : (float)(-dtmp + 90.0);
    }

  ta_sx = (float) iniparser_getdouble (dict, "geometry:axis_shift_x", 0.0);
  ta_sy = (float) iniparser_getdouble (dict, "geometry:axis_shift_y", 0.0);

  params->tilt_axis_par_shift_px = ta_sx * sinf (params->tilt_axis_rotation * ONE_DEGREE) 
    + ta_sy * cosf (params->tilt_axis_rotation * ONE_DEGREE);


  
  /* DETECTOR */
  
  /* Overrides MRC header */
  dtmp = iniparser_getdouble (dict, "detector:pixel_size", 0.0);
  params->detector_px_size[0] = (float) dtmp * ONE_MICROMETER;
  params->detector_px_size[1] = (float) dtmp * ONE_MICROMETER;
  params->detector_px_size[2] = 1.0;


  iniparser_freedict (dict);


  /* REGULARIZATION 2 */

  if (use_ctf_flag && truncate_ctf_flag)
    params->ctf_trunc = opts->ctf_trunc;

  return;
}
コード例 #23
0
ファイル: economy.c プロジェクト: eaglexboy/shares
int main(void){

/************************** Initializing variables ***************************/
	int i, j;					//Misc counter
	int workforcePercentage;	// Total amount of the population that is
								// workforce.
	int growthPercentage;		// Total amount of population growth
	float taxCollection;		// Money Collected from Taxes.
	float productionCost;		// Cost to produce resources
	int consumed;				// Amount of the Good Consumed.
	float goodReserve;			// Amount of a Good to Reserve
	float fluxFactor;			// Fluctuation Factor
	float fluxPrice;			// Good price based on the fluctuation

	systemDemographics SystemData;	// System Demographics
	production Products;			// Produced Product data


/******************************* Main Program ********************************/

	// Seeding Randomizer
	srand(time(NULL));

	// Loading Settings
	printf("Loading Config.ini....");
	if(loadConfig()){
		exit(0);
	}
	printf("Done.\n");

	// Connecting to DB
	printf("Connecting to DB...");
	if(connectToDB()){
		exit(0);
	}
	printf("Done.\n");

	// Loading Goods
	printf("Loading Goods...");
	loadGoods();
	printf("Done.\n");

	// Setting Good Rates
	productionRate = malloc(numberOfGoods * sizeof(goodRate));
	consumptionRate = malloc(numberOfGoods * sizeof(goodRate));
	productionFactor = malloc(numberOfGoods * sizeof(goodRate));

	// Loading Rates
	printf("Loading Consumption and Production Rates...");
	if(loadRates()){
		exit(0);
	}
	printf("Done.\n");

	// Loading Markets
	printf("Loading Markets...");
	loadDestinations();
	if(loadMarkets()){
		exit(0);
	}
	printf("Done.\n");


	// Cycling through each market
	for(i = 0; i < numberOfDestinations; i++){
		// Loading Demographic Data
		SystemData = loadSystemDemographics(destinations[i].destinationID);

		// Setting Growth
		growthPercentage = ((rand() % 10) + 1) * ((rand() % 2) ? 1:-1);
		SystemData.pop += round(SystemData.pop * ((float)growthPercentage/100));

		// Setting Workforce
		workforcePercentage = ((rand() % 25) + 1);
		SystemData.workPop = round(SystemData.pop * ((float)workforcePercentage / 100));

		// Collecting Taxes
		taxCollection = (SystemData.workPop * SystemData.taxes);
		SystemData.funds += (SystemData.workPop * taxCollection);
		updateDemographics(SystemData);

		//Producing/Consuming Goods
		productionCost = 0;
		for(j = 0; j < numberOfGoods; j++){
			Products = produceGood(SystemData.systemID, goodsID[j], SystemData.workPop);

			// Removing workers used to produce this good from work popultion
			(SystemData.workPop -= Products.workers);
			if(SystemData.workPop < 0){
				SystemData.workPop = 0;
			}

			// Updating Total Production Cost for the System
			productionCost += Products.cost;

			// Calculating Consumption Amount of the Good
			consumed = ((SystemData.pop * consumptionRateForGood(goodsID[j])) * (0 -1));

			// Updating System's Stock
			updateStock(SystemData.systemID, goodsID[j], consumed);

			// Determining Amount to reserve
			goodReserve = ((float)consumed * (0 - 1)) * TICKS_TO_RESERVE_FOR;

			// Calculating  Factor
			fluxFactor = 1 - ((stockLevel(SystemData.systemID, goodsID[j]) - goodReserve)/goodReserve);

			// Calculating New Sell Price
			fluxPrice = fluxFactor * goodPrice(goodsID[j], SystemData.systemID);

			// Did it cost more to produce then the current Sell Price
			if(goodPrice(goodsID[j], SystemData.systemID) - calculateProductionCost(SystemData.systemID, goodsID[j]) < 0){
				// Add the difference to the new Sell Price.
				fluxPrice += (calculateProductionCost(SystemData.systemID, goodsID[j]) - goodPrice(goodsID[j], SystemData.systemID));
			}

			// Update New Sell Price
			updatePrice(SystemData.systemID, goodsID[j], fluxPrice);
		} // Good Cycle for()

		// Update Taxes
		if(taxCollection - productionCost < 0){
			updateTaxes(SystemData.systemID, 1);
		}
		else {
			updateTaxes(SystemData.systemID, -1);
		}
	}// Markets Cycle for()

	// Clearing memory
	printf("Clearing Memory...");
	mysql_free_result(result);
	iniparser_freedict(settings);
	free(destinations);
	free(markets);
	printf("Done.\n");

	return 0;
}
コード例 #24
0
ファイル: gps.c プロジェクト: doebrowsk/tank-chair
// Initialize the GPS sensor
void GPS_Boot(Sensor * sensor,SensorVariable * start)
{
	if(fileExists("config/GPS.ini"))
	{
		dictionary* config = iniparser_load("config/GPS.ini");
		GPS_LatitudeRatio = iniparser_getdouble(config,"Conversion:Latitude",0);
		GPS_LongitudeRatio= iniparser_getdouble(config,"Conversion:Longitude",0);
		GPS_longLowLimit= iniparser_getdouble(config,"Limit:LowLongitude",0);
		GPS_longHighLimit= iniparser_getdouble(config,"Limit:HighLongitude",360);
		GPS_latLowLimit= iniparser_getdouble(config,"Limit:LowLatitude",0);
		GPS_latHighLimit= iniparser_getdouble(config,"Limit:HighLatitude",360);
		GPS_angleDtLength = iniparser_getdouble(config,"Angle:DtLength",1.0);
		GPS_angleVarianceMult = iniparser_getdouble(config,"Angle:VarianceMultiplyer",1);
		GPS_latOffset = iniparser_getdouble(config,"Offset:Latitude",1.0);
		GPS_longOffset = iniparser_getdouble(config,"Offset:Longitude",1);
		GPS_velocityMin = iniparser_getdouble(config,"Limit:VelocityMin",.5);
		GPS_velcityBeliefFactor = iniparser_getdouble(config,"Conversion:VelocityBeliefFactor",.5);
        GPS_networkOutputOnly = iniparser_getboolean(config, "Output:NetworkOutputOnly", 0);
		iniparser_freedict(config);
		LOG.GPS("GPS Ini file loaded");
	}
	else
	{
		LOG.GPS("gps.ini was not found");
	}

	// CHAD: I am awsome DELETE ME 
	GPS_angleVarianceMult = 10;

	GPS_angleLastLat = 0.0;
	GPS_angleLastLong  = 0.0;
	GPS_anglePrevious = 0;

	int bootUpAttempt = 0;
	GPS_angleSum=10000;
    GPS_networkOutputOnly = 1;

    // TODO: figure out if this is required or not
	/*
	 * This may or may not be required!!!!!!
	 * It is required for initalization purposes:)
	 */
	/*
	StateVariable TestState;
	while(bootUpAttempt == 0)
	{
		GPS_Update(sensor,TestState);
		if(sensor->hasBeenUpdated)
		{
			WOOOOO Major HACK
			if(sensor->state->Location.columns==2)
			{
				Matrix_SetValue(start->Location,1,1,Matrix_GetValue(sensor->state->Location,1,1));
				Matrix_SetValue(start->Location,2,1,Matrix_GetValue(sensor->state->Location,2,1));
			}
			else
			{
				LOG.VERBOSE("Retrying to find gps corrdinates to get an inital offset.");
			}
		}
		else
		{
			LOG.VERBOSE("Retrying to find gps corrdinates to get an inital offset.");
		}
	}
	*/
}
コード例 #25
0
ファイル: ipmi-fru-it.c プロジェクト: 46826114/ipmi-fru-it
int main(int argc, char **argv)
{
    char *fru_ini_file, *outfile, *data;
    int c, length, max_size=0, result;
    dictionary *ini;

    /* supported cmdline options */
    char options[] = "hvri:aws:c:o:";

    fru_ini_file = outfile = data = NULL;
    ini = NULL;
    packer = &pack_ascii6;

    while((c = getopt(argc, argv, options)) != -1) {
        switch(c) {
            case 'r':
                fprintf(stderr, "\nError! Option not implemented\n\n");
                exit(EXIT_FAILURE);
            case 'i':
                fprintf(stderr, "\nError! Option not implemented\n\n");
                exit(EXIT_FAILURE);
            case 's':
                result = sscanf(optarg, "%d", &max_size);
                if (result == 0 || result == EOF) {
                    fprintf(stderr, "\nError! Invalid maximum file size (-s %s)\n\n",
                            optarg);
                    exit(EXIT_FAILURE);
                }
                break;
            case 'c':
                fru_ini_file = optarg;
                break;
            case 'o':
                outfile = optarg;
                break;
            case 'a':
                packer = &pack_ascii8;
                break;

            case 'v':
                fprintf(stdout, "\nipmi-fru-it version %s\n\n", TOOL_VERSION);
                return 0;
            default:
                fprintf(stdout, "\nipmi-fru-it version %s\n", TOOL_VERSION);
                fprintf(stdout, usage, argv[0]);
                return -1;
        }
    }

    if (!fru_ini_file || !outfile) {
        fprintf(stderr, usage, argv[0]);
        exit(EXIT_FAILURE);
    }

    ini = iniparser_load(fru_ini_file);
    if (!ini) {
        fprintf(stderr, "\nError parsing INI file %s!\n\n", fru_ini_file);
        exit(EXIT_FAILURE);
    }

    length = gen_fru_data(ini, &data);

    if (length < 0) {
        fprintf(stderr, "\nError generating FRU data!\n\n");
        exit(EXIT_FAILURE);
    }

    // only bother checking max_size if the parameter set it
    if (max_size  && (length > max_size)) {
        fprintf(stderr, "\nError! FRU data length (%d bytes) exceeds maximum "
                "file size (%d bytes)\n\n", length, max_size);
        exit(EXIT_FAILURE);
    }
    
    if (write_fru_data(outfile, data, length)) {
        fprintf(stderr, "\nError writing %s\n\n", outfile);
        exit(EXIT_FAILURE);
    }
    
    iniparser_freedict(ini);

    fprintf(stdout, "\nFRU file \"%s\" created\n\n", outfile);

    return 0;
}
コード例 #26
0
ファイル: fwd_op_params.c プロジェクト: kohr-h/ETreco
void
FwdParams_assign_from_file (FwdParams *params, const char *fname_params)
{
  int itmp;
  float ta_sx, ta_sy;
  double dtmp;
  dictionary *dict;

  CAPTURE_NULL_VOID (params);
  CAPTURE_NULL_VOID (fname_params);

  if ((dict = iniparser_load (fname_params)) == NULL)
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Unable to read parameters from %s.", fname_params);
      return;
    }


  /* VOLUME */

  /* All these settings override MRC header */
  params->vol_shape[0] = iniparser_getint (dict, "volume:nx", -1);
  params->vol_shape[1] = iniparser_getint (dict, "volume:ny", -1);
  params->vol_shape[2] = iniparser_getint (dict, "volume:nz", -1);
  
  dtmp = iniparser_getdouble (dict, "volume:voxel_size", FLT_MAX);
  vec3_set_all (params->vol_csize, (float) dtmp);

  params->vol_shift_px[0] = (float) iniparser_getdouble (dict, "volume:shift_x", FLT_MAX);
  params->vol_shift_px[1] = (float) iniparser_getdouble (dict, "volume:shift_y", FLT_MAX);
  params->vol_shift_px[2] = (float) iniparser_getdouble (dict, "volume:shift_z", FLT_MAX);

  
  /* GEOMETRY */
  
  /* Single axis: parallel tilt axis shift */
  dtmp = iniparser_getdouble (dict, "geometry:tilt_axis", 0.0);
  if (fabsf (dtmp) < 45.0)  /* Use "x" backprojection variant */
    {
      params->tilt_axis = 0;
      params->tilt_axis_rotation = (float) dtmp;
    }
  else
    {
      params->tilt_axis = 1;
      /* What's missing to +- 90 degrees */
      params->tilt_axis_rotation = (dtmp > 0) ? (float)(dtmp - 90.0) : (float)(-dtmp + 90.0);
    }

  ta_sx = (float) iniparser_getdouble (dict, "geometry:axis_shift_x", 0.0);
  ta_sy = (float) iniparser_getdouble (dict, "geometry:axis_shift_y", 0.0);

  params->tilt_axis_par_shift_px = ta_sx * sinf (params->tilt_axis_rotation * ONE_DEGREE) 
    + ta_sy * cosf (params->tilt_axis_rotation * ONE_DEGREE);


  
  /* DETECTOR */

  if ( (itmp = iniparser_getint (dict, "detector:det_pix_x", -1)) == -1 )
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'detector:det_pix_x' not found in %s.", fname_params);
      return;
    }
  
  params->detector_shape[0] = itmp;
  
  if ( (itmp = iniparser_getint (dict, "detector:det_pix_y", -1)) == -1 )
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'detector:det_pix_y' not found in %s.", fname_params);
      return;
    }
  
  params->detector_shape[1] = itmp;
  params->detector_shape[2] = 1;
  
  if ( (dtmp = iniparser_getdouble (dict, "detector:pixel_size", FLT_MAX)) == FLT_MAX )
    {
      EXC_THROW_CUSTOMIZED_PRINT (EXC_IO, "Key 'detector:pixel_size' not found in %s.", fname_params);
      return;
    }

  params->detector_px_size[0] = (float) dtmp * ONE_MICROMETER;
  params->detector_px_size[1] = (float) dtmp * ONE_MICROMETER;
  params->detector_px_size[2] = 1.0;

  iniparser_freedict (dict);

  return;
}
コード例 #27
0
ファイル: baseline.c プロジェクト: ricardomaraschini/nada
int main(int argc, char *argv[]) {

	FILE *command = NULL;
	char *command_line = NULL;
	char *line = NULL;
	char *line_bkp = NULL;
	char *baseline_perfdata = NULL;
	char *baseline_perfdata_aux = NULL;
	char *ini_path;
	char *aux = NULL;
	struct metric_t *mt;
	struct metric_t *aux_mt;
	struct metric_t *metrics_root;
	struct deviation_t *deviation;
	int exit_code = OK;
	int ret = 0;
	int min_entries = 0;
	int collected_entries = 0;
	int allow_negatives = TRUE;
	float tolerance = 0;
	unsigned int name_last_pos = 0;
	dictionary *ini;
	extern char **environ;

	if (argc <= 1) {
		printf("Invalid check command supplied\n");
		return UNKNOWN;
	}

	// search for hostname and servicedescription macros
	line = *(environ + ret++);
	while(line) {
		aux = strtok(line,"=");
		if (!strcmp(aux,"NAGIOS_HOSTNAME")) { 
			host_name = strtok(NULL,"=");
		} else if (!strcmp(aux,"NAGIOS_SERVICEDESC")) {
			service_description = strtok(NULL,"=");
		}
		ret++;
		line = *(environ + ret);
	}
	line = NULL;

	if (!host_name || !service_description) {
		printf("Unable to locate NAGIOS_HOSTNAME and NAGIOS_SERVICEDESC macros\n");
		return UNKNOWN;
	}

	asprintf(&ini_path,"%s/baseline.ini",INSTALLPATH);

	ini = iniparser_load(ini_path);
	if (ini == NULL) {
		printf("Unable to process %s file\n",ini_path);
		return UNKNOWN;
	}

	// i personally dont like to use 'extern' variables 
	// with this approach we can easily provide more backends support
	aux = iniparser_getstring(ini, "database:host", NULL);
	ret = (aux) ? db_set_dbserver(aux) : db_set_dbserver("localhost");
	if (ret != OK)
		goto memory_allocation_error;

	aux = iniparser_getstring(ini, "database:user", NULL);
	ret = (aux) ? db_set_dbuser(aux) : db_set_dbuser("root");
	if (ret != OK)
		goto memory_allocation_error;

	aux = iniparser_getstring(ini, "database:password", NULL);
	ret = (aux) ? db_set_dbpassword(aux) : db_set_dbpassword("");
	if (ret != OK)
		goto memory_allocation_error;

	aux = iniparser_getstring(ini, "general:baselinealgorithm", "standard_deviation");
	baseline_algorithm = STANDARDDEVIATION; 
	if (strstr(aux,"exponential_smoothing"))
		baseline_algorithm = EXPONENTIALSMOOTH;

	aux = iniparser_getstring(ini, "database:dbname", NULL);
	ret = (aux) ? db_set_dbname(aux) : db_set_dbname("nada");
	if (ret != OK)
		goto memory_allocation_error;

	db_set_max_entries( iniparser_getint(ini, "general:maxentries", MAXENTRIESTODEVIATION) );
	db_set_sazonality( iniparser_getint(ini, "general:sazonality", SAZONALITY) );
	min_entries = iniparser_getint(ini, "general:minentries", MINENTRIESTODEVIATION);
	allow_negatives = iniparser_getboolean(ini, "general:allownegatives", TRUE);
	tolerance = (float)iniparser_getint(ini, "general:tolerance", DEVIATIONTOLERANCE) / 100 + 1;

	// we no longer need dictionary
	iniparser_freedict(ini);
	free(ini_path);

	command_line = read_command_line(argc,argv);
	if (command_line == NULL) {
		printf("Error getting command line\n");
		return UNKNOWN;
	}

	command = popen(command_line,"r");
	if (!command) {
		printf("Unable to run supplied command\n");
		free(command_line);
		return UNKNOWN;
	}

	line = malloc(MAXPLUGINOUTPUT + 1);
	if (line == NULL) {
		free(command_line);
		pclose(command);
		goto memory_allocation_error;
	}

	if (fgets(line, MAXPLUGINOUTPUT,command) == NULL) {
		printf("Unable to read plugin output\n");
		free(command_line);
		pclose(command);
		free(line);
		return UNKNOWN;
	}

	if (strstr(line,"|") == NULL) {
		printf("%s",line);
		free(command_line);
		pclose(command);
		free(line);
		return OK;
	}

	// plugin output returned value becames
	// our default output return code
	exit_code = WEXITSTATUS(pclose(command));

	if ((line_bkp = malloc(strlen(line) + 1)) == NULL) {
		free(command_line);
		free(line);
		goto memory_allocation_error;
	}
	strcpy(line_bkp,line);
	line[strlen(line) - 1] = '\x0';

	strtok(line_bkp,"|");
	metrics_root = parse_perfdata(strtok(NULL,"|"));
	if (metrics_root == NULL) {
		printf("Error parsing metric data - %s\n",line);
		free(command_line);
		free(line_bkp);
		return UNKNOWN;
	}

	ret = db_open_conn();
	if (ret != OK) {
		printf("Unable to connect to database\n");
		free(command_line);
		free(line);
		free(line_bkp);
		return UNKNOWN;
	}

	if ((baseline_perfdata = malloc(1)) == NULL) {
		free(command_line);
		free(line);
		free(line_bkp);
		goto memory_allocation_error;
	}
	*baseline_perfdata = '\x0';
	for(mt=metrics_root; mt != NULL; mt=mt->next) {

		deviation = get_deviation( command_line, 
		                           mt, 
		                           &collected_entries, 
		                           tolerance,
		                           allow_negatives
		);


		if (collected_entries > min_entries) {

			// baseline has been broken
			if (mt->value < deviation->bottom || mt->value > deviation->top) {
				// change return code
				exit_code = CRITICAL;
			}
 
		}

		/* XXX
		 * this certainly is not the more 
		 * appropriate way to do it
		 */
		name_last_pos = strlen(mt->name) - 1;
		if (mt->name[name_last_pos] == '\'') {
			mt->name[name_last_pos] = '\x0';
			asprintf( &baseline_perfdata_aux," %s_top'=%.3f%s;;;; %s_bottom'=%.3f%s;;;; ", 
			                                 mt->name, 
			                                 deviation->top,
			                                 mt->unit, 
			                                 mt->name, 
			                                 deviation->bottom,
			                                 mt->unit
			);

		} else if (mt->name[name_last_pos] == '"') {
			mt->name[name_last_pos] = '\x0';
			asprintf( &baseline_perfdata_aux," %s_top\"=%.3f%s;;;; %s_bottom\"=%.3f%s;;;; ", 
			                                 mt->name, 
			                                 deviation->top,
			                                 mt->unit, 
			                                 mt->name, 
			                                 deviation->bottom,
			                                 mt->unit
			);
		} else {
			asprintf( &baseline_perfdata_aux," %s_top=%.3f%s;;;; %s_bottom=%.3f%s;;;; ", 
			                                 mt->name, 
			                                 deviation->top,
			                                 mt->unit, 
			                                 mt->name, 
			                                 deviation->bottom,
			                                 mt->unit
			);
		}

		baseline_perfdata = realloc(baseline_perfdata, strlen(baseline_perfdata) + strlen(baseline_perfdata_aux) + 1);
		strcat(baseline_perfdata,baseline_perfdata_aux);
		free(baseline_perfdata_aux);

		free(deviation);
	}

	printf( "%s %s\n", line, baseline_perfdata);

	mt = metrics_root;
	while(mt) {
		aux_mt = mt->next;
		free(mt->name);
		free(mt->unit);
		free(mt);
		mt = aux_mt;		
	}

	free(command_line);
	free(line);
	free(line_bkp);
	free(baseline_perfdata);
	db_close_conn();

	return exit_code;

	memory_allocation_error:
	fprintf(stderr,"Memory allocation error\n");
	return CRITICAL;

}
コード例 #28
0
ファイル: gpo_parse.c プロジェクト: AllardJ/Tomato
static NTSTATUS parse_gpttmpl_system_access(const char *filename)
{
	NTSTATUS status;
	dictionary *d = NULL;
	uint32 pwd_min_age, pwd_max_age, pwd_min_len, pwd_history;
	uint32 lockout_count;
	BOOL pwd_complex;
	uint32 version;

	d = iniparser_load(filename);
	if (d == NULL) {
		return NT_STATUS_NO_SUCH_FILE;
	}

	status = parse_gpttmpl(d, &version);
	if (!NT_STATUS_IS_OK(status)) {
		goto out;
	}

	status = NT_STATUS_INVALID_PARAMETER;

	if ((pwd_min_age = iniparser_getint(d, GPTTMPL_SECTION_SYSTEM_ACCESS
			":"GPTTMPL_PARAMETER_MINPWDAGE, Undefined)) == Undefined) {
		goto out;
	}

	if ((pwd_max_age = iniparser_getint(d, GPTTMPL_SECTION_SYSTEM_ACCESS
			":"GPTTMPL_PARAMETER_MINPWDAGE, Undefined)) == Undefined) {
		goto out;
	}

	if ((pwd_min_len = iniparser_getint(d, GPTTMPL_SECTION_SYSTEM_ACCESS
			":"GPTTMPL_PARAMETER_MINPWDLEN, Undefined)) == Undefined) {
		goto out;
	}

	if ((pwd_complex = iniparser_getboolean(d, GPTTMPL_SECTION_SYSTEM_ACCESS
			":"GPTTMPL_PARAMETER_PWDCOMPLEX, Undefined)) == Undefined) {
		goto out;
	}

	if ((pwd_history = iniparser_getint(d, GPTTMPL_SECTION_SYSTEM_ACCESS
			":"GPTTMPL_PARAMETER_PWDHISTORY, Undefined)) == Undefined) {
		goto out;
	}

	if ((lockout_count = iniparser_getint(d, GPTTMPL_SECTION_SYSTEM_ACCESS
			":"GPTTMPL_PARAMETER_LOCKOUTCOUNT, Undefined)) == Undefined) {
		goto out;
	}

	/* TODO ? 
	RequireLogonToChangePassword = 0
	ForceLogoffWhenHourExpire = 0
	ClearTextPassword = 0
	*/

	status = NT_STATUS_OK;

 out:
	if (d) {
		iniparser_freedict(d);
	}

 	return status;
}
コード例 #29
0
void InitParser::free_dico(void)
{
	iniparser_freedict(dico);
}
コード例 #30
0
ファイル: ini.c プロジェクト: liuning587/FileJoint
/**
 ******************************************************************************
 * @brief   从配置文件中获取文件合并信息
 * @param[out] *pinfo   : 返回info
 *
 * @retval     -1 失败
 * @retval      0 成功
 ******************************************************************************
 */
int
ini_get_info(filejoint_ini_t *pinfo)
{
    dictionary  *   ini ;
    char *pstr = NULL;
    char ftmp[32];
    int i;

    memset(pinfo, 0x00, sizeof(*pinfo));

    ini = iniparser_load(DEFAULT_INI_FILE);
    if (NULL == ini)
    {
        create_example_ini_file();
        ini = iniparser_load(DEFAULT_INI_FILE);
        if (ini == NULL)
        {
            return -1;
        }
    }

    iniparser_dump(ini, NULL);//stderr
    pinfo->files = iniparser_getint(ini, "cfg:Files", -1);
    if ((pinfo->files > DEFAULT_MAX_FILE) || (pinfo->files <= 0))
    {
        iniparser_freedict(ini);
        return -1;
    }
    pinfo->blank = iniparser_getint(ini, "cfg:Blank", -1);
    if (pinfo->blank < 0)
    {
        iniparser_freedict(ini);
        return -1;
    }
    if (pinfo->blank > 255)
    {
        pinfo->blank = 255;
    }
    pinfo->islog = iniparser_getint(ini, "cfg:IsLog", -1);
    if (pinfo->islog == -1)
    {
        iniparser_freedict(ini);
        return -1;
    }
    pstr = iniparser_getstring(ini, "cfg:LogFile", NULL);
    if (pstr == NULL)
    {
        iniparser_freedict(ini);
        return -1;
    }
    strncpy(pinfo->logfile, pstr, sizeof(pinfo->logfile));

    pstr = iniparser_getstring(ini, "cfg:OutFile", NULL);
    if (pstr == NULL)
    {
        strncpy(pinfo->outfile, DEFAULT_DEST_FILE, sizeof(pinfo->outfile));
    }
    else
    {
        strncpy(pinfo->outfile, pstr, sizeof(pinfo->logfile));
    }

    /* 扫描所以文件 */
    for (i = 0; i < pinfo->files; i++)
    {
        sprintf(ftmp, "f%d:FileName", i + 1);
        pstr = iniparser_getstring(ini, ftmp, NULL);
        if (pstr == NULL)
        {
            iniparser_freedict(ini);
            return -1;
        }
        strncpy(pinfo->file[i].filename, pstr, sizeof(pinfo->file[i].filename));

        sprintf(ftmp, "f%d:FileMaxSize", i + 1);
        pinfo->file[i].filemaxsize = iniparser_getint(ini, ftmp, -1);
        if (pinfo->file[i].filemaxsize == -1)
        {
            iniparser_freedict(ini);
            return -1;
        }
    }

    iniparser_freedict(ini);

    return 0;
}