示例#1
0
文件: md.c 项目: SahanGH/psi4public
void sim_md(struct state *state)
{
	msg("MOLECULAR DYNAMICS JOB\n\n\n");

	struct md *md = md_create(state);

	if (cfg_get_bool(state->cfg, "velocitize"))
		velocitize(md);

	remove_system_drift(md);
	compute_forces(md);

	msg("    INITIAL STATE\n\n");
	print_status(md);

	for (int i = 1; i <= cfg_get_int(state->cfg, "max_steps"); i++) {
		md->update_step(md);

		if (i % cfg_get_int(state->cfg, "print_step") == 0) {
			msg("    STATE AFTER %d STEPS\n\n", i);
			print_status(md);
		}
	}

	md_shutdown(md);

	msg("MOLECULAR DYNAMICS JOB COMPLETED SUCCESSFULLY\n");
}
示例#2
0
void sig_init(void)
{
	clk_tck_init();

	timer_save_interval = cfg_get_int(SECTION_OPTIONS, NULL, "Save");
	if (timer_save_interval < 0)
		timer_save_interval = TIMER_SAVE_DELAY;
	else
	if ((timer_save_interval /= TIMER_INTERVAL) <= 0)
		timer_save_interval = 1;
	if (cfg_get_param(SECTION_OPTIONS, NULL, "AbortGraceTime")) {
		abort_grace_time =
			cfg_get_int(SECTION_OPTIONS, NULL, "AbortGraceTime");
	}
#if OS_TIMER
	timer_save_value = timer_save_interval;
#elif !defined(BENCH_BUILD)
	timer_save_value = status_get_time() + timer_save_interval;
#endif
	timer_ticksafety_interval = (clock_t)1 << (sizeof(clock_t) * 8 - 4);
	timer_ticksafety_interval /= clk_tck;
	if ((timer_ticksafety_interval /= TIMER_INTERVAL) <= 0)
		timer_ticksafety_interval = 1;
	timer_ticksafety_value = timer_ticksafety_interval;

	atexit(sig_done);

	sig_install(sig_handle_update, SIGHUP);
	sig_install_abort();
	sig_install_timer();
}
示例#3
0
/* load the common things */
void load_common()
{
char *val;
int i;

  if (NULL != (val = cfg_get_str("Studio","Encode_Input_file")))
      sprintf(enc_inputfile, val);
  else 
      sprintf(enc_inputfile, "test.avi");
 
  if (NULL != (val = cfg_get_str("Studio","Encode_Output_file")))
      sprintf(enc_outputfile, val);
  else 
      sprintf(enc_outputfile,"%s/output.mpg", getenv("HOME"));

  if (NULL != (val = cfg_get_str("Studio","Encode_Audio_file")))
      sprintf(enc_audiofile, val);
  else 
      sprintf(enc_audiofile, "/tmp/audio.mp2");

  if (NULL != (val = cfg_get_str("Studio","Encode_Video_file")))
      sprintf(enc_videofile, val);
  else 
      sprintf(enc_videofile, "/tmp/video.m1v");

  if (NULL != (val = cfg_get_str("Studio","Encode_Player_use")))
      sprintf(selected_player, val);
  else 
      sprintf(selected_player, "no player selected");

  if (NULL != (val = cfg_get_str("Studio","Encode_Video_Preview")))
    if ( 0 == strcmp(val,"yes"))
        use_yuvplay_pipe = 1;
    else 
        use_yuvplay_pipe = 0;

  if (-1 != (i = cfg_get_int("Studio","Encoding_four_pel_motion_compensation")))
    fourpelmotion = i;

  if (-1 != (i = cfg_get_int("Studio","Encoding_two_pel_motion_compensation")))
    twopelmotion = i;

  if (NULL != (val = cfg_get_str("Studio","Encode_Bicubic_Scaling")))
    if ( 0 == strcmp(val,"yes"))
        use_yuvplay_pipe = 1;
    else 
        use_yuvplay_pipe = 0;
  
  if (-1 != (i = cfg_get_int("Studio","Encoding_save_on_exit")))
    saveonexit = i;
  
  if (-1 != (i = cfg_get_int("Studio","Encoding_dist_enhanced_settings")))
    enhanced_settings = i;
}
示例#4
0
bool inot_root_init(w_root_t *root, char **errmsg) {
  struct inot_root_state *state;


  state = calloc(1, sizeof(*state));
  if (!state) {
    *errmsg = strdup("out of memory");
    return false;
  }
  root->watch = state;
  pthread_mutex_init(&state->lock, NULL);

#ifdef HAVE_INOTIFY_INIT1
  state->infd = inotify_init1(IN_CLOEXEC);
#else
  state->infd = inotify_init();
#endif
  if (state->infd == -1) {
    ignore_result(asprintf(errmsg, "watch(%.*s): inotify_init error: %s",
        root->root_path->len, root->root_path->buf, inot_strerror(errno)));
    w_log(W_LOG_ERR, "%s\n", *errmsg);
    return false;
  }
  w_set_cloexec(state->infd);
  state->wd_to_name =
      w_ht_new(cfg_get_int(root, CFG_HINT_NUM_DIRS, HINT_NUM_DIRS),
               &w_ht_string_val_funcs);
  state->move_map = w_ht_new(2, &move_hash_funcs);

  return true;
}
示例#5
0
文件: kqueue.c 项目: cotizo/watchman
bool kqueue_root_init(w_root_t *root, char **errmsg) {
  struct kqueue_root_state *state;
  json_int_t hint_num_dirs =
      cfg_get_int(root, CFG_HINT_NUM_DIRS, HINT_NUM_DIRS);

  state = calloc(1, sizeof(*state));
  if (!state) {
    *errmsg = strdup("out of memory");
    return false;
  }
  root->watch = state;
  pthread_mutex_init(&state->lock, NULL);
  state->name_to_fd = w_ht_new(hint_num_dirs, &name_to_fd_funcs);
  state->fd_to_name = w_ht_new(hint_num_dirs, &w_ht_string_val_funcs);

  state->kq_fd = kqueue();
  if (state->kq_fd == -1) {
    ignore_result(asprintf(errmsg, "watch(%.*s): kqueue() error: %s",
        root->root_path->len, root->root_path->buf, strerror(errno)));
    w_log(W_LOG_ERR, "%s\n", *errmsg);
    return false;
  }
  w_set_cloexec(state->kq_fd);

  return true;
}
示例#6
0
void sig_init(void)
{
	clk_tck_init();

	timer_save_interval = cfg_get_int(SECTION_OPTIONS, NULL, "Save");
	if (timer_save_interval < 0)
		timer_save_interval = TIMER_SAVE_DELAY;
	else
	if ((timer_save_interval /= TIMER_INTERVAL) <= 0)
		timer_save_interval = 1;
	timer_save_value = timer_save_interval;

	timer_ticksafety_interval = (clock_t)1 << (sizeof(clock_t) * 8 - 4);
	timer_ticksafety_interval /= clk_tck;
	if ((timer_ticksafety_interval /= TIMER_INTERVAL) <= 0)
		timer_ticksafety_interval = 1;
	timer_ticksafety_value = timer_ticksafety_interval;

	atexit(sig_done);

	sig_install_update();
	sig_install_abort();
	sig_install_timer();
#if OS_FORK
	signal(SIGUSR2, sig_handle_status);
#endif
}
示例#7
0
Cell* ReadCells(MPI_Comm comm, const char* cellfile, int &Ncells) {
    int nprocs, myid, root;
    Cell* cells;

    MPI_Comm_size(comm, &nprocs);
    MPI_Comm_rank(comm, &myid);
    root = 0;

    /* Have root process read in cells */
    if(myid == root) {
        size_t n, size;
        char endian;
        char fmt[ABN_MAX_FORMAT_LENGTH];
        Config cellopts = cfg_new();

        /* Read basis cells from file */
        FILE* fcells = fopen(cellfile, "r");
        if(fcells == NULL) {
            fprintf(stderr, "ReadCells: could not read cells from '%s'\n", cellfile);
            MPI_Abort(comm, 1);
        }
        if(abn_read(fcells, (void**) &cells, &n, &size, &endian, fmt, cellopts) != 0) {
            report_memory_usage();
            fprintf(stderr, "ReadCells: error reading cells from '%s'\n", cellfile);
            MPI_Abort(comm, 1);
        }
        fclose(fcells);

        Ncells = cfg_get_int(cellopts, "Ncells");
        if((int)n != Ncells)
            fprintf(stderr, "Warning: consistency check fail for Ncells: %d != %d\n", Ncells, (int)n);
        if(size != sizeof(Cell))
            fprintf(stderr, "Warning: consistency check fail for sizeof(Cell): %d != %d\n", (int)sizeof(Cell), (int)size);

        /* Debugging... */
        printf("Read %d basis cells from '%s'\n", Ncells, cellfile);
    }
    MPI_Bcast(&Ncells, 1, MPI_INT, root, comm);

    /* Define MPI datatype for cells (this must be updated if struct Cell changes!) */
    MPI_Datatype cell_datatype;
    int blocklengths[2] = { 2, 8 };
    MPI_Aint displacements[2] = { 0, 8 };
    MPI_Datatype types[2] = { MPI_INT, MPI_DOUBLE };
    MPI_Type_create_struct(2, blocklengths, displacements, types, &cell_datatype);
    MPI_Type_commit(&cell_datatype);

    /* Broadcast cell data to all other processes */
    if(myid != root) {
        cells = (Cell*) malloc(Ncells*sizeof(Cell));
        if(cells == NULL) {
            fprintf(stderr, "ReadCells: could not allocate memory for cells on process %d\n", myid);
            MPI_Abort(comm, 1);
        }
    }
    MPI_Bcast(cells, Ncells, cell_datatype, root, comm);
    return cells;
}
示例#8
0
double* ReadSpectrum(const char* specfile, int* n_, int* nev_) {
    int n, nev;
    double* modes = NULL;
    Config opts = cfg_new();

    FILE* fspec = fopen(specfile, "r");
    if(fspec == NULL) {
        fprintf(stderr, "ReadSpectrum: could not open file '%s'\n", specfile);
        return NULL;
    }

    int err = abn_read(fspec, (void**) &modes, NULL, NULL, NULL, NULL, opts);
    fclose(fspec);

    if(!err && !cfg_has_keys(opts, "n,nev", ",")) {
        fprintf(stderr, "ReadSpectrum: missing options\n");
        err = 1;
    }
    else {
        n = cfg_get_int(opts, "n");
        nev = cfg_get_int(opts, "nev");
    }
    cfg_destroy(opts);

    if(err) {
        fprintf(stderr, "ReadSpectrum: error reading from '%s'\n", specfile);
        perror("system error");
        free(modes);
        return NULL;
    }
    else {
        if(n_) *n_ = n;
        if(nev_) *nev_ = nev;
        return modes;
    }
}
示例#9
0
void load_script_data(void)
{
int i;
char *val;

  if ( NULL != (val = cfg_get_str("Scriptdata","Script_name")))
    sprintf(script_name, val);
  else 
    sprintf(script_name,"script.sh");

  if ( -1 != (i = cfg_get_int("Scriptdata","Script_distributed")))
    if ( (i == 0) || (i == 1) )
      script_use_distributed = i;

  if ( -1 != (i = cfg_get_int("Scriptdata","Script_MPEG1")))
    if ( i >= 0 || i <= 8)
      script.mpeg1 = i;;

  if ( -1 != (i = cfg_get_int("Scriptdata","Script_MPEG2")))
    if ( i >= 0 || i <= 8)
      script.mpeg2 = i;;

  if ( -1 != (i = cfg_get_int("Scriptdata","Script_GENERIC")))
    if ( i >= 0 || i <= 8)
      script.generic = i;;

  if ( -1 != (i = cfg_get_int("Scriptdata","Script_VCD")))
    if ( i >= 0 || i <= 8)
      script.vcd = i;;

  if ( -1 != (i = cfg_get_int("Scriptdata","Script_SVCD")))
    if ( i >= 0 || i <= 8)
      script.svcd = i;;

  if ( -1 != (i = cfg_get_int("Scriptdata","Script_DVD")))
    if ( i >= 0 || i <= 8)
      script.dvd = i;;

  if ( -1 != (i = cfg_get_int("Scriptdata","Script_YUV2LAV")))
    if ( i >= 0 || i <= 8)
      script.yuv2lav = i;;

}
示例#10
0
RealModel::RealModel(Config cfg) {
    /* Read prior power spectrum from file */
    if(!cfg_has_key(cfg, "pkfile")) {
        fprintf(stderr, "RealModel: must set config option 'pkfile'\n");
        return;
    }
    const char* pkfile = cfg_get(cfg, "pkfile");
    pk = CubicSpline(pkfile);

    /* Determine bands */
    Band b;
    if(cfg_has_key(cfg, "bands")) {
        /* Read bands directly */
        vector<double> kvals(100);
        cfg_get_array_double(cfg, "bands", 100, &kvals[0]);

        if((kvals.size() % 2) != 0) {
            fprintf(stderr, "RealModel: odd number of kvals\n");
            kvals.pop_back();
        }
        for(int n = 0; n < (int)kvals.size()/2; n++) {
            b.min = kvals[2*n];
            b.max = kvals[2*n+1];
            bands.push_back(b);
        }
        Nbands = bands.size();
    }
    else if(cfg_has_keys(cfg, "Nbands,kmin,kmax")) {
        /* Use regularly spaced bands */
        Nbands = cfg_get_int(cfg, "Nbands");
        double kmin = cfg_get_double(cfg, "kmin");
        double kmax = cfg_get_double(cfg, "kmax");
        /* (Assume linearly spaced bands for now) */
        for(int n = 0; n < Nbands; n++) {
            b.min = kmin + n*(kmax - kmin)/Nbands;
            b.max = kmin + (n+1)*(kmax - kmin)/Nbands;
            bands.push_back(b);
        }
    }
    else {
        fprintf(stderr, "RealModel: k-bands not specified in configuration\n");
        return;
    }
}
示例#11
0
static void sqlite_parse_config(DICT_SQLITE *dict_sqlite, const char *sqlitecf)
{
    VSTRING *buf;

    /*
     * Parse the primary configuration parameters, and emulate the legacy
     * query interface if necessary. This simplifies migration from one SQL
     * database type to another.
     */
    dict_sqlite->dbpath = cfg_get_str(dict_sqlite->parser, "dbpath", "", 1, 0);
    dict_sqlite->query = cfg_get_str(dict_sqlite->parser, "query", NULL, 0, 0);
    if (dict_sqlite->query == 0) {
	buf = vstring_alloc(100);
	db_common_sql_build_query(buf, dict_sqlite->parser);
	dict_sqlite->query = vstring_export(buf);
    }
    dict_sqlite->result_format =
	cfg_get_str(dict_sqlite->parser, "result_format", "%s", 1, 0);
    dict_sqlite->expansion_limit =
	cfg_get_int(dict_sqlite->parser, "expansion_limit", 0, 0, 0);

    /*
     * Parse the query / result templates and the optional domain filter.
     */
    dict_sqlite->ctx = 0;
    (void) db_common_parse(&dict_sqlite->dict, &dict_sqlite->ctx,
			   dict_sqlite->query, 1);
    (void) db_common_parse(0, &dict_sqlite->ctx, dict_sqlite->result_format, 0);
    db_common_parse_domain(dict_sqlite->parser, dict_sqlite->ctx);

    /*
     * Maps that use substring keys should only be used with the full input
     * key.
     */
    if (db_common_dict_partial(dict_sqlite->ctx))
	dict_sqlite->dict.flags |= DICT_FLAG_PATTERN;
    else
	dict_sqlite->dict.flags |= DICT_FLAG_FIXED;
}
示例#12
0
static void single_init(void)
{
    struct db_salt *salt;

    log_event("Proceeding with \"single crack\" mode");

    if ((words_pair_max = cfg_get_int(SECTION_OPTIONS, NULL,
                                      "SingleWordsPairMax")) < 0)
        words_pair_max = SINGLE_WORDS_PAIR_MAX;

    progress = 0;

    length = single_db->format->params.plaintext_length;
    if (options.force_maxlength && options.force_maxlength < length)
        length = options.force_maxlength;
    key_count = single_db->format->params.min_keys_per_crypt;
    if (key_count < SINGLE_HASH_MIN)
        key_count = SINGLE_HASH_MIN;
    /*
     * We use "short" for buffered key indices and "unsigned short" for buffered
     * key offsets - make sure these don't overflow.
     */
    if (key_count > 0x8000)
        key_count = 0x8000;
    while (key_count > 0xffff / length + 1)
        key_count >>= 1;

    if (rpp_init(rule_ctx, pers_opts.activesinglerules)) {
        log_event("! No \"%s\" mode rules found",
                  pers_opts.activesinglerules);
        if (john_main_process)
            fprintf(stderr, "No \"%s\" mode rules found in %s\n",
                    pers_opts.activesinglerules, cfg_name);
        error();
    }

    rules_init(length);
    rec_rule = rule_number = 0;
    rule_count = rules_count(rule_ctx, 0);

    log_event("- %d preprocessed word mangling rules", rule_count);

    status_init(get_progress, 0);

    rec_restore_mode(restore_state);
    rec_init(single_db, save_state);

    salt = single_db->salts;
    do {
        single_alloc_keys(&salt->keys);
    } while ((salt = salt->next));

    if (key_count > 1)
        log_event("- Allocated %d buffer%s of %d candidate passwords%s",
                  single_db->salt_count,
                  single_db->salt_count != 1 ? "s" : "",
                  key_count,
                  single_db->salt_count != 1 ? " each" : "");

    guessed_keys = NULL;
    single_alloc_keys(&guessed_keys);

    crk_init(single_db, NULL, guessed_keys);
}
示例#13
0
文件: perf.cpp 项目: danez/watchman
void PerfLogThread::loop() {
  json_ref samples;
  char **envp;
  json_ref perf_cmd;
  int64_t sample_batch;

  w_set_thread_name("perflog");

  // Prep some things that we'll need each time we run a command
  {
    uint32_t env_size;
    auto envpht = w_envp_make_ht();
    char *statedir = dirname(strdup(watchman_state_file));
    w_envp_set_cstring(envpht, "WATCHMAN_STATE_DIR", statedir);
    w_envp_set_cstring(envpht, "WATCHMAN_SOCK", get_sock_name());
    envp = w_envp_make_from_ht(envpht, &env_size);
  }

  perf_cmd = cfg_get_json("perf_logger_command");
  if (json_is_string(perf_cmd)) {
    perf_cmd = json_array({perf_cmd});
  }
  if (!json_is_array(perf_cmd)) {
    w_log(
        W_LOG_FATAL,
        "perf_logger_command must be either a string or an array of strings\n");
  }

  sample_batch = cfg_get_int("perf_logger_command_max_samples_per_call", 4);

  while (!w_is_stopping()) {
    {
      auto wlock = samples_.wlock();
      if (!*wlock) {
        cond_.wait(wlock.getUniqueLock());
      }

      samples = nullptr;
      std::swap(samples, *wlock);
    }

    if (samples) {
      while (json_array_size(samples) > 0) {
        int i = 0;
        auto cmd = json_array();
        posix_spawnattr_t attr;
        posix_spawn_file_actions_t actions;
        pid_t pid;
        char **argv = NULL;

        json_array_extend(cmd, perf_cmd);

        while (i < sample_batch && json_array_size(samples) > 0) {
          char *stringy = json_dumps(json_array_get(samples, 0), 0);
          if (stringy) {
            json_array_append_new(
                cmd, typed_string_to_json(stringy, W_STRING_MIXED));
            free(stringy);
          }
          json_array_remove(samples, 0);
          i++;
        }

        argv = w_argv_copy_from_json(cmd, 0);
        if (!argv) {
          char *dumped = json_dumps(cmd, 0);
          w_log(W_LOG_FATAL, "error converting %s to an argv array\n", dumped);
        }

        posix_spawnattr_init(&attr);
#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
        posix_spawnattr_setflags(&attr, POSIX_SPAWN_CLOEXEC_DEFAULT);
#endif
        posix_spawn_file_actions_init(&actions);
        posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null",
                                         O_RDONLY, 0666);
        posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "/dev/null",
                                         O_WRONLY, 0666);
        posix_spawn_file_actions_addopen(&actions, STDERR_FILENO, "/dev/null",
                                         O_WRONLY, 0666);

        if (posix_spawnp(&pid, argv[0], &actions, &attr, argv, envp) == 0) {
          int status;
          while (waitpid(pid, &status, 0) != pid) {
            if (errno != EINTR) {
              break;
            }
          }
        } else {
          int err = errno;
          w_log(W_LOG_ERR, "failed to spawn %s: %s\n", argv[0],
                strerror(err));
        }

        posix_spawnattr_destroy(&attr);
        posix_spawn_file_actions_destroy(&actions);

        free(argv);
      }
    }
  }
}
void do_incremental_crack(struct db_main *db, char *mode)
{
	char *charset;
	int min_length, max_length, max_count;
	char *extra;
	FILE *file;
	struct charset_header *header;
	unsigned int check;
	char allchars[CHARSET_SIZE + 1];
	char char1[CHARSET_SIZE + 1];
	char2_table char2;
	chars_table chars[CHARSET_LENGTH - 2];
	unsigned char *ptr;
	unsigned int length, fixed, count;
	unsigned int real_count;
	int last_length, last_count;
	int pos;

	if (!mode) {
		if (db->format == &fmt_LM)
			mode = "LanMan";
		else if (db->format == &fmt_NETLM)
			mode = "LanMan";
		else if (db->format == &fmt_NETHALFLM)
			mode = "LanMan";
		else
			mode = "All";
	}

	log_event("Proceeding with \"incremental\" mode: %.100s", mode);

	if (!(charset = cfg_get_param(SECTION_INC, mode, "File"))) {
		log_event("! No charset defined");
		fprintf(stderr, "No charset defined for mode: %s\n", mode);
		error();
	}

	extra = cfg_get_param(SECTION_INC, mode, "Extra");

	if ((min_length = cfg_get_int(SECTION_INC, mode, "MinLen")) < 0)
		min_length = 0;
	if ((max_length = cfg_get_int(SECTION_INC, mode, "MaxLen")) < 0)
		max_length = CHARSET_LENGTH;
	max_count = cfg_get_int(SECTION_INC, mode, "CharCount");

	if (min_length > max_length) {
		log_event("! MinLen = %d exceeds MaxLen = %d",
			min_length, max_length);
		fprintf(stderr, "MinLen = %d exceeds MaxLen = %d\n",
			min_length, max_length);
		error();
	}

	if (min_length > db->format->params.plaintext_length) {
		log_event("! MinLen = %d is too large for this hash type",
			min_length);
		fprintf(stderr, "MinLen = %d exceeds the maximum possible "
			"length for the current hash type (%d)\n",
			min_length, db->format->params.plaintext_length);
		error();
	}

	if (max_length > db->format->params.plaintext_length) {
		log_event("! MaxLen = %d is too large for this hash type",
			max_length);
		fprintf(stderr, "Warning: "
			"MaxLen = %d is too large for the current hash type, "
			"reduced to %d\n",
			max_length, db->format->params.plaintext_length);
		max_length = db->format->params.plaintext_length;
	}

	if (max_length > CHARSET_LENGTH) {
		log_event("! MaxLen = %d exceeds the compile-time limit of %d",
			max_length, CHARSET_LENGTH);
		fprintf(stderr,
			"\n"
			"MaxLen = %d exceeds the compile-time limit of %d\n\n"
			"There are several good reasons why you probably don't "
			"need to raise it:\n"
			"- many hash types don't support passwords "
			"(or password halves) longer than\n"
			"7 or 8 characters;\n"
			"- you probably don't have sufficient statistical "
			"information to generate a\n"
			"charset file for lengths beyond 8;\n"
			"- the limitation applies to incremental mode only.\n",
			max_length, CHARSET_LENGTH);
		error();
	}

	if (!(file = fopen(path_expand(charset), "rb")))
		pexit("fopen: %s", path_expand(charset));

	header = (struct charset_header *)mem_alloc(sizeof(*header));

	charset_read_header(file, header);
	if (ferror(file)) pexit("fread");

	if (feof(file) ||
	    (memcmp(header->version, CHARSET_V1, sizeof(header->version)) &&
	    memcmp(header->version, CHARSET_V2, sizeof(header->version))) ||
	    !header->count)
		inc_format_error(charset);

	if (header->min != CHARSET_MIN || header->max != CHARSET_MAX ||
	    header->length != CHARSET_LENGTH) {
		log_event("! Incompatible charset file: %.100s", charset);
		fprintf(stderr, "Incompatible charset file: %s\n", charset);
		error();
	}

	if (header->count > CHARSET_SIZE)
		inc_format_error(charset);

	check =
		(unsigned int)header->check[0] |
		((unsigned int)header->check[1] << 8) |
		((unsigned int)header->check[2] << 16) |
		((unsigned int)header->check[3] << 24);
	if (!rec_restoring_now)
		rec_check = check;
	if (rec_check != check) {
		log_event("! Charset file has changed: %.100s", charset);
		fprintf(stderr, "Charset file has changed: %s\n", charset);
		error();
	}

	fread(allchars, header->count, 1, file);
	if (ferror(file)) pexit("fread");
	if (feof(file)) inc_format_error(charset);

	allchars[header->count] = 0;
	if (expand(allchars, extra ? extra : "", sizeof(allchars)))
		inc_format_error(charset);
	real_count = strlen(allchars);

	if (max_count < 0) max_count = CHARSET_SIZE;

	if (min_length != max_length)
		log_event("- Lengths %d to %d, up to %d different characters",
			min_length, max_length, max_count);
	else
		log_event("- Length %d, up to %d different characters",
			min_length, max_count);

	if ((unsigned int)max_count > real_count) {
		log_event("! Only %u characters available", real_count);
		fprintf(stderr, "Warning: only %u characters available\n",
			real_count);
	}

	if (!(db->format->params.flags & FMT_CASE))
	switch (is_mixedcase(allchars)) {
	case -1:
		inc_format_error(charset);

	case 1:
		log_event("! Mixed-case charset, "
			"but the hash type is case-insensitive");
		fprintf(stderr, "Warning: mixed-case charset, "
			"but the current hash type is case-insensitive;\n"
			"some candidate passwords may be unnecessarily "
			"tried more than once.\n");
	}

	if (header->length >= 2)
		char2 = (char2_table)mem_alloc(sizeof(*char2));
	else
		char2 = NULL;
	for (pos = 0; pos < (int)header->length - 2; pos++)
		chars[pos] = (chars_table)mem_alloc(sizeof(*chars[0]));

	rec_compat = 0;
	rec_entry = 0;
	memset(rec_numbers, 0, sizeof(rec_numbers));

	status_init(NULL, 0);
	rec_restore_mode(restore_state);

#ifdef WEBAPI
	if(packet_id) {
		int ret;

		// This is a new packet
		inc_rec_state.initialized = 0;

		inc_rec_state.words_requested = packet_rounds;
		inc_rec_state.words_generated = 0;
		inc_rec_state.cc_0 = -1;
		inc_rec_state.cc_1 = -1;
		inc_rec_state.cc_2 = -1;

		ret = sscanf(packet_state, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%127[^\n]", 
				&rec_entry,
				&rec_numbers[0], &rec_numbers[1], &rec_numbers[2], &rec_numbers[3],
				&rec_numbers[4], &rec_numbers[5], &rec_numbers[6], &rec_numbers[7],
				&inc_rec_state.pos,
				&inc_rec_state.numbers_cache,
				&inc_rec_state.cc_0, &inc_rec_state.cc_1, &inc_rec_state.cc_2,
				inc_rec_state.key_i);
		
		if(ret < 14 || ret > 15) {
			log_event("Invalid packet state, found %d fields in %s", ret, packet_state);
			// XXX - Handle more gracefully..
			error();
		}


		status_init(webapi_inc_get_progress, 0);
	}
#endif

	rec_init(db, save_state);

	ptr = header->order + (entry = rec_entry) * 3;
	memcpy(numbers, rec_numbers, sizeof(numbers));

	crk_init(db, fix_state, NULL);

	last_count = last_length = -1;

	entry--;
	while (ptr < &header->order[sizeof(header->order) - 1]) {
		entry++;
		length = *ptr++; fixed = *ptr++; count = *ptr++;

		if (length >= CHARSET_LENGTH ||
			fixed > length ||
			count >= CHARSET_SIZE) inc_format_error(charset);

		if (entry != rec_entry)
			memset(numbers, 0, sizeof(numbers));

		if (count >= real_count || (fixed && !count)) continue;

		if ((int)length + 1 < min_length ||
			(int)length >= max_length ||
			(int)count >= max_count) continue;

		if ((int)length != last_length) {
			inc_new_length(last_length = length,
				header, file, charset, char1, char2, chars);
			last_count = -1;
		}
		if ((int)count > last_count)
			inc_new_count(length, last_count = count, charset,
				allchars, char1, char2, chars);

		if (!length && !min_length) {
			min_length = 1;
			if (crk_process_key("")) break;
		}

#if 0
		log_event("- Trying length %d, fixed @%d, character count %d",
			length + 1, fixed + 1, count + 1);
#endif
		if (inc_key_loop(length, fixed, count, char1, char2, chars))
			break;
	}
	

	crk_done();
	rec_done(event_abort);

	for (pos = 0; pos < (int)header->length - 2; pos++)
		MEM_FREE(chars[pos]);
	MEM_FREE(char2);
	MEM_FREE(header);

	fclose(file);
}
示例#15
0
void downloader_init(upstreams *upstr_ptr, mqd_t msgq_id) {

	/* Initialise MySQL connection */
	MYSQL_RES *result;
	MYSQL_ROW row;
	int num_fields;

	if ((conn = init_mysql(conn)) == NULL) {
		mysql_close(conn);
		error_log(ERROR, "MySQL initialisation failed");
		exit(EXIT_FAILURE);
	}

	if (!connect_mysql(conn)) {
		mysql_close(conn);
		error_log(ERROR, "MySQL connection failed");
		exit(EXIT_FAILURE);
	}

	int n;
	const config_setting_t *upstr_setting;
	static int upstream_count;

	upstr_setting = config_lookup(&cfg, "upstreams");
	upstream_count = config_setting_length(upstr_setting);

	error_log(ERROR, "Connected to MySQL.");
	struct mq_attr msgq_attr;
	int fe_id = cfg_get_int("fe_id");
	static char query[QUERY_MAX];
	unsigned int msgprio = 1;

	while (running) {
		/* Schedule upstreams */
		for (n = 0; n < upstream_count; n++) {
			if (!upstr_ptr[n].alive
					&& (time(NULL) - upstr_ptr[n].deadtime)
							> cfg_get_int("upstream_dead_timeout")) {
				error_log(DEBUG,
						"Making %s live again, time of dead: %d, now: %d",
						upstr_ptr[n].upstream, upstr_ptr[n].deadtime,
						time(NULL));
				upstr_ptr[n].alive = 1;
			}
			error_log(DEBUG, "Upstream: %s, active: %d", upstr_ptr[n].upstream,
					upstr_ptr[n].alive);
		}
		/* Get latest data */
		mq_getattr(msgq_id, &msgq_attr);
		if (!msgq_attr.mq_curmsgs) {
			if (cfg_get_int("dmode") == 2) {
				/* Query for robin mode*/
				sprintf(query,
						"SELECT filename, size from scoreboard WHERE id NOT "
								"IN(SELECT id from cached where fe_id=%d) AND count >=%d "
								"order by count DESC, last_modified DESC, size limit %d",
						fe_id, cfg_get_int("cache_req_count"),
						cfg_get_int("workers"));
			} else {
				/* Query for shard mode*/
				sprintf(query,
						"SELECT filename, size from scoreboard WHERE id NOT "
								"IN(SELECT id from cached where fe_id=%d) AND count >=%d "
								"AND fe_id=%d "
								"order by count DESC, last_modified DESC, size limit %d",
						fe_id, cfg_get_int("cache_req_count"), fe_id,
						cfg_get_int("workers"));
			}

			query_mysql(conn, query);
			result = mysql_store_result(conn);
			num_fields = mysql_num_fields(result);

			while ((row = mysql_fetch_row(result))) {
				if (row[0] && row[1]) {
					if (check_file_exists(row[0], atoi(row[1])) != 0) {
						continue;
					}
					mq_send(msgq_id, row[0], strlen(row[0]) + 1, msgprio);
				}
			}
			mysql_free_result(result);
		}
		sleep(5);
	}
	error_log(ERROR, "Exiting");
}
示例#16
0
static void load_options(int *width, int *height, int *x, int *y)
{
   char *val;
   int  i, num=0, tot;
   char filename[256];
   char value_get[256];

   sprintf(filename, "%s/%s", getenv("HOME"), ".studio");
   chk_dir(filename);
   sprintf(filename, "%s/%s/%s.tv-conf",getenv("HOME"),".studio", tv_config_file);
   cfg_parse_file(filename);

   port = cfg_get_int("StudioTV", "default_port");
   if (width) *width = cfg_get_int("StudioTV", "default_width");
   if (height) *height = cfg_get_int("StudioTV", "default_height");
   if (x) *x = cfg_get_int("StudioTV", "default_x");
   if (y) *y = cfg_get_int("StudioTV", "default_y");

   if ((encoding_id = cfg_get_int("StudioTV", "default_encoding_id"))==-1)
      encoding_id = 0;

#ifdef OSS
   if (!mixer_dev) mixer_dev = cfg_get_str("StudioTV", "default_mixer_dev");
   if (!mixer_dev) mixer_dev = "/dev/mixer";
   audio_src = cfg_get_int("StudioTV", "default_audio_src");
#endif

#ifdef HAVE_LIRC
   if (!lirc_dev) lirc_dev = cfg_get_str("StudioTV", "default_lirc_dev");
   if (!lirc_dev) lirc_dev = "/dev/lircd";
   for(num=0;num<RC_NUM_KEYS;num++)
   {
      sprintf(value_get, "remote_control_key_%d", num);
      remote_buttons[num] = cfg_get_str("StudioTV",value_get);
      if (!remote_buttons[num]) remote_buttons[num] = "none";
   }
#endif

   if ((tot = cfg_get_int("StudioTV", "num_chans")) < 1)
      return;

   if (channels)
   {
      for (i=0;channels[i];i++)
         free(channels[i]);
      free(channels);
   }

   channels = (Channel**)malloc(sizeof(Channel*)*(tot+1));

   for(num=0;num<tot;num++)
   {
      sprintf(value_get, "channel_frequency_%d", num);
      i = cfg_get_int("StudioTV",value_get);
      sprintf(value_get, "channel_name_%d", num);
      val = cfg_get_str("StudioTV",value_get);
      channels[num] = (Channel*)malloc(sizeof(Channel));
      channels[num]->frequency = i;
      sprintf(channels[num]->name, val);
   }

   channels[tot] = NULL;

   if (verbose) g_print("Configuration loaded from %s\n", filename);
}
示例#17
0
DICT   *dict_ldap_open(const char *ldapsource, int dummy, int dict_flags)
{
    char   *myname = "dict_ldap_open";
    DICT_LDAP *dict_ldap;
    VSTRING *url_list;
    char   *s;
    char   *h;
    char   *server_host;
    char   *domainlist;
    char   *scope;
    char   *attr;
    int     tmp;

    if (msg_verbose)
	msg_info("%s: Using LDAP source %s", myname, ldapsource);

    dict_ldap = (DICT_LDAP *) dict_alloc(DICT_TYPE_LDAP, ldapsource,
					 sizeof(*dict_ldap));
    dict_ldap->dict.lookup = dict_ldap_lookup;
    dict_ldap->dict.close = dict_ldap_close;
    dict_ldap->dict.flags = dict_flags | DICT_FLAG_FIXED;

    dict_ldap->ld = NULL;
    dict_ldap->parser = cfg_parser_alloc(ldapsource);
    dict_ldap->ldapsource = mystrdup(ldapsource);

    server_host = cfg_get_str(dict_ldap->parser, "server_host",
			      "localhost", 1, 0);

    /*
     * get configured value of "server_port"; default to LDAP_PORT (389)
     */
    dict_ldap->server_port =
	cfg_get_int(dict_ldap->parser, "server_port", LDAP_PORT, 0, 0);

    /*
     * Define LDAP Version.
     */
    dict_ldap->version = cfg_get_int(dict_ldap->parser, "version", 2, 2, 0);
    switch (dict_ldap->version) {
    case 2:
	dict_ldap->version = LDAP_VERSION2;
	break;
    case 3:
	dict_ldap->version = LDAP_VERSION3;
	break;
    default:
	msg_warn("%s: %s Unknown version %d.", myname, ldapsource,
		 dict_ldap->version);
	dict_ldap->version = LDAP_VERSION2;
    }

#if defined(LDAP_API_FEATURE_X_OPENLDAP)
    dict_ldap->ldap_ssl = 0;
#endif

    url_list = vstring_alloc(32);
    s = server_host;
    while ((h = mystrtok(&s, " \t\n\r,")) != NULL) {
#if defined(LDAP_API_FEATURE_X_OPENLDAP)

	/*
	 * Convert (host, port) pairs to LDAP URLs
	 */
	if (ldap_is_ldap_url(h)) {
	    LDAPURLDesc *url_desc;
	    int     rc;

	    if ((rc = ldap_url_parse(h, &url_desc)) != 0) {
		msg_error("%s: error parsing URL %s: %d: %s; skipping", myname,
			  h, rc, ldap_err2string(rc));
		continue;
	    }
	    if (strcasecmp(url_desc->lud_scheme, "ldap") != 0 &&
		dict_ldap->version != LDAP_VERSION3) {
		msg_warn("%s: URL scheme %s requires protocol version 3", myname,
			 url_desc->lud_scheme);
		dict_ldap->version = LDAP_VERSION3;
	    }
	    if (strcasecmp(url_desc->lud_scheme, "ldaps") == 0)
		dict_ldap->ldap_ssl = 1;
	    ldap_free_urldesc(url_desc);
	    vstring_sprintf_append(url_list, " %s", h);
	} else {
	    if (strrchr(h, ':'))
		vstring_sprintf_append(url_list, " ldap://%s", h);
	    else
		vstring_sprintf_append(url_list, " ldap://%s:%d", h,
				       dict_ldap->server_port);
	}
#else
	vstring_sprintf_append(url_list, " %s", h);
#endif
    }
    dict_ldap->server_host =
	mystrdup(VSTRING_LEN(url_list) > 0 ? vstring_str(url_list) + 1 : "");

#if defined(LDAP_API_FEATURE_X_OPENLDAP)

    /*
     * With URL scheme, clear port to normalize connection cache key
     */
    dict_ldap->server_port = LDAP_PORT;
    if (msg_verbose)
	msg_info("%s: %s server_host URL is %s", myname, ldapsource,
		 dict_ldap->server_host);
#endif
    myfree(server_host);
    vstring_free(url_list);

    /*
     * Scope handling thanks to Carsten Hoeger of SuSE.
     */
    scope = cfg_get_str(dict_ldap->parser, "scope", "sub", 1, 0);

    if (strcasecmp(scope, "one") == 0) {
	dict_ldap->scope = LDAP_SCOPE_ONELEVEL;
    } else if (strcasecmp(scope, "base") == 0) {
	dict_ldap->scope = LDAP_SCOPE_BASE;
    } else if (strcasecmp(scope, "sub") == 0) {
	dict_ldap->scope = LDAP_SCOPE_SUBTREE;
    } else {
	msg_warn("%s: %s: Unrecognized value %s specified for scope; using sub",
		 myname, ldapsource, scope);
	dict_ldap->scope = LDAP_SCOPE_SUBTREE;
    }

    myfree(scope);

    dict_ldap->search_base = cfg_get_str(dict_ldap->parser, "search_base",
					 "", 0, 0);

    domainlist = cfg_get_str(dict_ldap->parser, "domain", "", 0, 0);
    if (*domainlist) {
#ifdef MATCH_FLAG_NONE
	dict_ldap->domain = match_list_init(MATCH_FLAG_NONE,
					    domainlist, 1, match_string);
#else
	dict_ldap->domain = match_list_init(domainlist, 1, match_string);
#endif
	if (dict_ldap->domain == NULL)
	    msg_warn("%s: domain match list creation using \"%s\" failed, will continue without it",
		     myname, domainlist);
	if (msg_verbose)
	    msg_info("%s: domain list created using \"%s\"", myname,
		     domainlist);
    } else {
	dict_ldap->domain = NULL;
    }
    myfree(domainlist);

    /*
     * get configured value of "timeout"; default to 10 seconds
     * 
     * Thanks to Manuel Guesdon for spotting that this wasn't really getting
     * set.
     */
    dict_ldap->timeout = cfg_get_int(dict_ldap->parser, "timeout",
				     10, 0, 0);

    dict_ldap->query_filter =
	cfg_get_str(dict_ldap->parser, "query_filter",
		    "(mailacceptinggeneralid=%s)", 0, 0);

    dict_ldap->result_filter =
	cfg_get_str(dict_ldap->parser, "result_filter", "%s", 0, 0);

    if (strcmp(dict_ldap->result_filter, "%s") == 0) {
	myfree(dict_ldap->result_filter);
	dict_ldap->result_filter = NULL;
    }
    attr = cfg_get_str(dict_ldap->parser, "result_attribute",
		       "maildrop", 0, 0);
    dict_ldap->result_attributes = argv_split(attr, " ,\t\r\n");
    dict_ldap->num_attributes = dict_ldap->result_attributes->argc;
    myfree(attr);

    attr = cfg_get_str(dict_ldap->parser, "special_result_attribute",
		       "", 0, 0);
    if (*attr) {
	argv_split_append(dict_ldap->result_attributes, attr, " ,\t\r\n");
    }
    myfree(attr);

    /*
     * get configured value of "bind"; default to true
     */
    dict_ldap->bind = cfg_get_bool(dict_ldap->parser, "bind", 1);

    /*
     * get configured value of "bind_dn"; default to ""
     */
    dict_ldap->bind_dn = cfg_get_str(dict_ldap->parser, "bind_dn", "", 0, 0);

    /*
     * get configured value of "bind_pw"; default to ""
     */
    dict_ldap->bind_pw = cfg_get_str(dict_ldap->parser, "bind_pw", "", 0, 0);

    /*
     * get configured value of "cache"; default to false
     */
    tmp = cfg_get_bool(dict_ldap->parser, "cache", 0);
    if (tmp)
	msg_warn("%s: %s ignoring cache", myname, ldapsource);

    /*
     * get configured value of "cache_expiry"; default to 30 seconds
     */
    tmp = cfg_get_int(dict_ldap->parser, "cache_expiry", -1, 0, 0);
    if (tmp >= 0)
	msg_warn("%s: %s ignoring cache_expiry", myname, ldapsource);

    /*
     * get configured value of "cache_size"; default to 32k
     */
    tmp = cfg_get_int(dict_ldap->parser, "cache_size", -1, 0, 0);
    if (tmp >= 0)
	msg_warn("%s: %s ignoring cache_size", myname, ldapsource);

    /*
     * get configured value of "recursion_limit"; default to 1000
     */
    dict_ldap->recursion_limit = cfg_get_int(dict_ldap->parser,
					     "recursion_limit", 1000, 1, 0);

    /*
     * get configured value of "expansion_limit"; default to 0
     */
    dict_ldap->expansion_limit = cfg_get_int(dict_ldap->parser,
					     "expansion_limit", 0, 0, 0);

    /*
     * get configured value of "size_limit"; default to expansion_limit
     */
    dict_ldap->size_limit = cfg_get_int(dict_ldap->parser, "size_limit",
					dict_ldap->expansion_limit,
					0, 0);

    /*
     * Alias dereferencing suggested by Mike Mattice.
     */
    dict_ldap->dereference = cfg_get_int(dict_ldap->parser, "dereference",
					 0, 0, 0);
    if (dict_ldap->dereference < 0 || dict_ldap->dereference > 3) {
	msg_warn("%s: %s Unrecognized value %d specified for dereference; using 0",
		 myname, ldapsource, dict_ldap->dereference);
	dict_ldap->dereference = 0;
    }
    /* Referral chasing */
    dict_ldap->chase_referrals = cfg_get_bool(dict_ldap->parser,
					      "chase_referrals", 0);

#ifdef LDAP_API_FEATURE_X_OPENLDAP

    /*
     * TLS options
     */
    /* get configured value of "start_tls"; default to no */
    dict_ldap->start_tls = cfg_get_bool(dict_ldap->parser, "start_tls", 0);
    if (dict_ldap->start_tls && dict_ldap->version < LDAP_VERSION3) {
	msg_warn("%s: %s start_tls requires protocol version 3",
		 myname, ldapsource);
	dict_ldap->version = LDAP_VERSION3;
    }
    /* get configured value of "tls_require_cert"; default to no */
    dict_ldap->tls_require_cert = cfg_get_bool(dict_ldap->parser,
					       "tls_require_cert", 0);

    /* get configured value of "tls_ca_cert_file"; default "" */
    dict_ldap->tls_ca_cert_file = cfg_get_str(dict_ldap->parser,
					      "tls_ca_cert_file", "", 0, 0);

    /* get configured value of "tls_ca_cert_dir"; default "" */
    dict_ldap->tls_ca_cert_dir = cfg_get_str(dict_ldap->parser,
					     "tls_ca_cert_dir", "", 0, 0);

    /* get configured value of "tls_cert"; default "" */
    dict_ldap->tls_cert = cfg_get_str(dict_ldap->parser, "tls_cert",
				      "", 0, 0);

    /* get configured value of "tls_key"; default "" */
    dict_ldap->tls_key = cfg_get_str(dict_ldap->parser, "tls_key",
				     "", 0, 0);

    /* get configured value of "tls_random_file"; default "" */
    dict_ldap->tls_random_file = cfg_get_str(dict_ldap->parser,
					     "tls_random_file", "", 0, 0);

    /* get configured value of "tls_cipher_suite"; default "" */
    dict_ldap->tls_cipher_suite = cfg_get_str(dict_ldap->parser,
					      "tls_cipher_suite", "", 0, 0);
#endif

    /*
     * Debug level.
     */
#if defined(LDAP_OPT_DEBUG_LEVEL) && defined(LBER_OPT_LOG_PRINT_FN)
    dict_ldap->debuglevel = cfg_get_int(dict_ldap->parser, "debuglevel",
					0, 0, 0);
#endif

    /*
     * Find or allocate shared LDAP connection container.
     */
    dict_ldap_conn_find(dict_ldap);

    /*
     * Return the new dict_ldap structure.
     */
    return (DICT_DEBUG (&dict_ldap->dict));
}
示例#18
0
文件: mboxstore.c 项目: rdebath/sgt
static char *mbox_store_literal_inner(char *boxname,
				      char *message, int msglen,
				      char *separator)
{
    int boxnum, need_set;
    int ret, fd;
    struct stat st;
    int maxsize, size;
    off_t oldlen, newlen;

    boxnum = cfg_get_int("current-mbox");
    maxsize = cfg_get_int("mbox-maxsize");

    boxnum--;			       /* to counter first `boxnum++' below */
    need_set = FALSE;
    do {
	boxnum++;
	sprintf(boxname, "%s/mbox%d", dirpath, boxnum);
	if (need_set)
	    cfg_set_int("current-mbox", boxnum);
	need_set = TRUE;

	/*
	 * See if our current mbox has space in it.
	 */
	ret = stat(boxname, &st);
	if (ret < 0) {
	    if (errno == ENOENT)
		size = 0;	       /* current mbox is empty */
	    else {
		error(err_perror, boxname, "stat");
		return NULL;	       /* failed to store message */
	    }
	} else
	    size = st.st_size;
	/*
	 * Special case: a single message that's too big always goes in
	 * its own mbox.
	 */
    } while (size > 0 && size + msglen > maxsize);

    /*
     * So now we know which mbox it's going into. Open the mbox and
     * put it there.
     */
    fd = open(boxname, O_RDWR | O_CREAT, 0600);
    if (fd < 0) {
	error(err_perror, boxname, "open");
	return NULL;		       /* failed to store message */
    }
    oldlen = lseek(fd, 0, SEEK_END);
    if (oldlen < 0) {
	error(err_perror, boxname, "lseek");
	return NULL;		       /* failed to store message */
    }

    /*
     * Invent a `From ' line if there isn't one already.
     */
    if (!separator || strncmp(separator, "From ", 5)) {
	char fromline[80];
	struct tm tm;
	time_t t;

	t = time(NULL);
	tm = *gmtime(&t);
	strftime(fromline, 80,
		 "From timber-mbox-storage %a %b %d %H:%M:%S %Y\n", &tm);

	if (!write_wrapped(fd, fromline, strlen(fromline))) {
	    if (ftruncate(fd, oldlen) < 0)
		error(err_perror, boxname, "ftruncate");
	    return NULL;
	}
    } else {
	if (!write_wrapped(fd, separator, strlen(separator)) ||
	    !write_wrapped(fd, "\n", 1)) {
	    if (ftruncate(fd, oldlen) < 0)
		error(err_perror, boxname, "ftruncate");
	    return NULL;
	}
    }

    /*
     * Now write the message.
     */
    if (!write_mbox(fd, message, msglen)) {
	if (ftruncate(fd, oldlen) < 0)
	    error(err_perror, boxname, "ftruncate");
	return NULL;
    }

    /*
     * Find out where we ended up.
     */
    newlen = lseek(fd, 0, SEEK_CUR);
    if (newlen < 0) {
	error(err_perror, boxname, "lseek");
	return NULL;		       /* failed to store message */
    }

    /*
     * Done. Sync and close the mbox, then return success.
     */
    if (!nosync && fsync(fd) < 0) {
	error(err_perror, boxname, "fsync");
	if (ftruncate(fd, oldlen) < 0)
	    error(err_perror, boxname, "ftruncate");
	return NULL;
    }
    if (close(fd) < 0) {
	error(err_perror, boxname, "close");
	if (ftruncate(fd, oldlen) < 0)
	    error(err_perror, boxname, "ftruncate");
	return NULL;
    }

    /*
     * Construct a string telling us where the message is kept.
     */
    {
	char *ret;
	ret = snewn(80, char);
	sprintf(ret, "mbox%d:%d:%d",
		boxnum, (int)oldlen, (int)(newlen - oldlen));
	return ret;
    }
}
示例#19
0
static void pgsql_parse_config(DICT_PGSQL *dict_pgsql, const char *pgsqlcf)
{
    const char *myname = "pgsql_parse_config";
    CFG_PARSER *p = dict_pgsql->parser;
    char   *hosts;
    VSTRING *query;
    char   *select_function;

    dict_pgsql->username = cfg_get_str(p, "user", "", 0, 0);
    dict_pgsql->password = cfg_get_str(p, "password", "", 0, 0);
    dict_pgsql->dbname = cfg_get_str(p, "dbname", "", 1, 0);
    dict_pgsql->result_format = cfg_get_str(p, "result_format", "%s", 1, 0);

    /*
     * XXX: The default should be non-zero for safety, but that is not
     * backwards compatible.
     */
    dict_pgsql->expansion_limit = cfg_get_int(dict_pgsql->parser,
					      "expansion_limit", 0, 0, 0);

    if ((dict_pgsql->query = cfg_get_str(p, "query", 0, 0, 0)) == 0) {

	/*
	 * No query specified -- fallback to building it from components (
	 * old style "select %s from %s where %s" )
	 */
	query = vstring_alloc(64);
	select_function = cfg_get_str(p, "select_function", 0, 0, 0);
	if (select_function != 0) {
	    vstring_sprintf(query, "SELECT %s('%%s')", select_function);
	    myfree(select_function);
	} else
	    db_common_sql_build_query(query, p);
	dict_pgsql->query = vstring_export(query);
    }

    /*
     * Must parse all templates before we can use db_common_expand()
     */
    dict_pgsql->ctx = 0;
    (void) db_common_parse(&dict_pgsql->dict, &dict_pgsql->ctx,
			   dict_pgsql->query, 1);
    (void) db_common_parse(0, &dict_pgsql->ctx, dict_pgsql->result_format, 0);
    db_common_parse_domain(p, dict_pgsql->ctx);

    /*
     * Maps that use substring keys should only be used with the full input
     * key.
     */
    if (db_common_dict_partial(dict_pgsql->ctx))
	dict_pgsql->dict.flags |= DICT_FLAG_PATTERN;
    else
	dict_pgsql->dict.flags |= DICT_FLAG_FIXED;
    if (dict_pgsql->dict.flags & DICT_FLAG_FOLD_FIX)
	dict_pgsql->dict.fold_buf = vstring_alloc(10);

    hosts = cfg_get_str(p, "hosts", "", 0, 0);

    dict_pgsql->hosts = argv_split(hosts, " ,\t\r\n");
    if (dict_pgsql->hosts->argc == 0) {
	argv_add(dict_pgsql->hosts, "localhost", ARGV_END);
	argv_terminate(dict_pgsql->hosts);
	if (msg_verbose)
	    msg_info("%s: %s: no hostnames specified, defaulting to '%s'",
		     myname, pgsqlcf, dict_pgsql->hosts->argv[0]);
    }
    myfree(hosts);
}
示例#20
0
static void *perf_log_thread(void *unused) {
  json_t *samples = NULL;
  char **envp;
  json_t *perf_cmd;
  int64_t sample_batch;

  unused_parameter(unused);

  w_set_thread_name("perflog");

  // Prep some things that we'll need each time we run a command
  {
    uint32_t env_size;
    w_ht_t *envpht = w_envp_make_ht();
    char *statedir = dirname(strdup(watchman_state_file));
    w_envp_set_cstring(envpht, "WATCHMAN_STATE_DIR", statedir);
    w_envp_set_cstring(envpht, "WATCHMAN_SOCK", get_sock_name());
    envp = w_envp_make_from_ht(envpht, &env_size);
  }

  perf_cmd = cfg_get_json(NULL, "perf_logger_command");
  if (json_is_string(perf_cmd)) {
    perf_cmd = json_pack("[O]", perf_cmd);
  }
  if (!json_is_array(perf_cmd)) {
    w_log(
        W_LOG_FATAL,
        "perf_logger_command must be either a string or an array of strings\n");
  }

  sample_batch =
      cfg_get_int(NULL, "perf_logger_command_max_samples_per_call", 4);

  while (true) {
    pthread_mutex_lock(&perf_log_lock);
    if (!perf_log_samples) {
      pthread_cond_wait(&perf_log_cond, &perf_log_lock);
    }
    samples = perf_log_samples;
    perf_log_samples = NULL;

    pthread_mutex_unlock(&perf_log_lock);

    if (samples) {
      while (json_array_size(samples) > 0) {
        int i = 0;
        json_t *cmd = json_array();
        posix_spawnattr_t attr;
        posix_spawn_file_actions_t actions;
        pid_t pid;
        char **argv = NULL;

        json_array_extend(cmd, perf_cmd);

        while (i < sample_batch && json_array_size(samples) > 0) {
          char *stringy = json_dumps(json_array_get(samples, 0), 0);
          json_array_append(cmd, typed_string_to_json(stringy, W_STRING_MIXED));
          free(stringy);
          json_array_remove(samples, 0);
          i++;
        }

        argv = w_argv_copy_from_json(cmd, 0);
        if (!argv) {
          char *dumped = json_dumps(cmd, 0);
          w_log(W_LOG_FATAL, "error converting %s to an argv array\n", dumped);
        }

        posix_spawnattr_init(&attr);
#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
        posix_spawnattr_setflags(&attr, POSIX_SPAWN_CLOEXEC_DEFAULT);
#endif
        posix_spawn_file_actions_init(&actions);
        posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null",
                                         O_RDONLY, 0666);
        posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "/dev/null",
                                         O_WRONLY, 0666);
        posix_spawn_file_actions_addopen(&actions, STDERR_FILENO, "/dev/null",
                                         O_WRONLY, 0666);

        if (posix_spawnp(&pid, argv[0], &actions, &attr, argv, envp) == 0) {
          // There's no sense waiting here, because w_reap_children is called
          // by the reaper thread.
        } else {
          int err = errno;
          w_log(W_LOG_ERR, "failed to spawn %s: %s\n", argv[0],
                strerror(err));
        }

        posix_spawnattr_destroy(&attr);
        posix_spawn_file_actions_destroy(&actions);

        free(argv);
        json_decref(cmd);
      }
      json_decref(samples);
    }
  }

  return NULL;
}
示例#21
0
void load_section(char section[LONGOPT],struct encodingoptions *point)
{
char *val;
int i;

  if (NULL != (val = cfg_get_str(section,"Encode_Notblack_size")))
        sprintf((*point).notblacksize, val);
  else
      sprintf((*point).notblacksize,"as is");

  if (NULL != (val = cfg_get_str(section,"Encode_Interlacing_Correction")))
      sprintf((*point).interlacecorr, val);
  else
      sprintf((*point).interlacecorr,"not needed");

  if (NULL != (val = cfg_get_str(section,"Encode_Input_use")))
      sprintf((*point).input_use, val);
  else
      sprintf((*point).input_use,"as is");

  if (NULL != (val = cfg_get_str(section,"Encode_Output_size")))
      sprintf((*point).output_size, val);

  if (NULL != (val = cfg_get_str(section,"Encode_Mode_keyword")))
      sprintf((*point).mode_keyword, val);
  else
      sprintf((*point).mode_keyword,"as is");

  if (-1 != (i = cfg_get_int(section,"Encode_Audiobitrate")))
        (*point).audiobitrate = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Outputbitrate")))
        (*point).outputbitrate = i;

  if (NULL != (val = cfg_get_str(section,"Encode_Force_Stereo")))
    if ( 0 != strcmp(val,"as is"))
      sprintf((*point).forcestereo, val);

  if (NULL != (val = cfg_get_str(section,"Encode_Force_Mono")))
    if ( 0 != strcmp(val,"as is"))
      sprintf((*point).forcemono, val);

  if (NULL != (val = cfg_get_str(section,"Encode_Force_Vcd")))
    if ( 0 != strcmp(val,"as is"))
      sprintf((*point).forcevcd, val);

  if (-1 != (i = cfg_get_int(section,"Encode_Use_Yuvdenoise")))
        (*point).use_yuvdenoise = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Denoise_Deinterlace")))
        (*point).deinterlace = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Denoise_Sharpness")))
        (*point).sharpness = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Denoise_Threshold")))
        (*point).denois_thhold = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Denoise_Average")))
        (*point).average_frames = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Video_Bitrate")))
        (*point).bitrate = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Quality_Factor")))
        (*point).qualityfactor = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Minimum_GOP_Size")))
        (*point).minGop = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Maximum_GOP_Size")))
        (*point).maxGop = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Sequence_Size")))
        (*point).sequencesize = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Non_Video_Bitrate")))
        (*point).nonvideorate = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Searchradius")))
        (*point).searchradius = i;
  else
        (*point).searchradius = 16;

  if (-1 != (i = cfg_get_int(section,"Encode_Muxformat")))
        (*point).muxformat = i;

  if (NULL != (val = cfg_get_str(section,"Encode_Mux_VBR")))
    if ( 0 != strcmp(val,"from stream"))
      sprintf((*point).muxvbr, val);

  if (-1 != (i = cfg_get_int(section,"Encode_Stream_Datarate")))
        (*point).streamdatarate = i;

  if (-1 != (i = cfg_get_int(section,"Encode_Decoder_Buffer")))
        (*point).decoderbuffer = i;

  if (NULL != (val = cfg_get_str(section,"Encode_Codec")))
    if ( 0 != strcmp(val,"not used"))
      sprintf((*point).codec, val);
}
示例#22
0
/* Load the machine number for the encoding process */
void load_machine_data(char section[LONGOPT],struct machine *pointm)
{
int i,j;
i=0;
j=0;

  j = g_list_length (machine_names);

  if (-1 != (i = cfg_get_int(section,"Machine_running_lav2wav")))
    {
      if ( i <= j )
         (*pointm).lav2wav = i;
      else if (verbose) 
         printf("Wrong value for lav2wav %i, setting to value: 0\n", i); 
    }
  
  if (-1 != (i = cfg_get_int(section,"Machine_running_mp2enc")))
    {
      if ( i <= j )
        (*pointm).mp2enc = i;
      else if (verbose)
         printf("Wrong value for mp2enc %i, setting to value: 0\n", i); 
    }

  if (-1 != (i = cfg_get_int(section,"Machine_running_lav2yuv")))
    {
      if ( i <= j )
        (*pointm).lav2yuv = i;
      else if (verbose) 
         printf("Wrong value for lav2yuv %i, setting to value: 0\n", i); 
    }

  if (-1 != (i = cfg_get_int(section,"Machine_running_yuvdenoise")))
    {
      if ( i <= j )
        (*pointm).yuvdenoise = i;
      else if (verbose) 
         printf("Wrong value for yuvdenoise %i, setting to value: 0\n", i); 
    }

  if (-1 != (i = cfg_get_int(section,"Machine_running_yuvscaler")))
    {
      if ( i <= j )
        (*pointm).yuvscaler = i;
      else if (verbose) 
         printf("Wrong value for yuvscaler %i, setting to value: 0\n", i); 
    }

  if (-1 != (i = cfg_get_int(section,"Machine_running_mpeg2enc")))
    {
      if ( i <= j )
        (*pointm).mpeg2enc = i;
      else if (verbose) 
         printf("Wrong value for mpeg2enc %i, setting to value: 0\n", i); 
    }

  if (-1 != (i = cfg_get_int(section,"Machine_running_yuv2lav")))
    {
      if ( i <= j )
        (*pointm).yuv2lav = i;
      else if (verbose) 
         printf("Wrong value for yuv2lav %i, setting to value: 0\n", i); 
    }


}
示例#23
0
文件: john.c 项目: mimaun/Rose
static void john_load_conf(void)
{
	int internal, target;

	if (!(options.flags & FLG_VERBOSITY)) {
		options.verbosity = cfg_get_int(SECTION_OPTIONS, NULL,
		                                "Verbosity");

		if (options.verbosity == -1)
			options.verbosity = 3;

		if (options.verbosity < 1 || options.verbosity > 5) {
			if (john_main_process)
				fprintf(stderr, "Invalid verbosity "
				        "level in config file, use 1-5\n");
			error();
		}
	}

	if (pers_opts.activepot == NULL) {
		if (options.secure)
			pers_opts.activepot = str_alloc_copy(SEC_POT_NAME);
		else
			pers_opts.activepot = str_alloc_copy(POT_NAME);
	}

	if (pers_opts.activewordlistrules == NULL)
		if (!(pers_opts.activewordlistrules =
		      cfg_get_param(SECTION_OPTIONS, NULL,
		                    "BatchModeWordlistRules")))
			pers_opts.activewordlistrules =
				str_alloc_copy(SUBSECTION_WORDLIST);

	if (pers_opts.activesinglerules == NULL)
		if (!(pers_opts.activesinglerules =
		      cfg_get_param(SECTION_OPTIONS, NULL,
		                    "SingleRules")))
			pers_opts.activesinglerules =
				str_alloc_copy(SUBSECTION_SINGLE);

	if ((options.flags & FLG_LOOPBACK_CHK) &&
	    !(options.flags & FLG_RULES)) {
		if ((pers_opts.activewordlistrules =
		     cfg_get_param(SECTION_OPTIONS, NULL,
		                   "LoopbackRules")))
			options.flags |= FLG_RULES;
	}

	if ((options.flags & FLG_WORDLIST_CHK) &&
	    !(options.flags & FLG_RULES)) {
		if ((pers_opts.activewordlistrules =
		     cfg_get_param(SECTION_OPTIONS, NULL,
		                   "WordlistRules")))
			options.flags |= FLG_RULES;
	}

	options.secure = cfg_get_bool(SECTION_OPTIONS, NULL, "SecureMode", 0);
	options.reload_at_crack =
		cfg_get_bool(SECTION_OPTIONS, NULL, "ReloadAtCrack", 1);
	options.reload_at_save =
		cfg_get_bool(SECTION_OPTIONS, NULL, "ReloadAtSave", 1);
	options.abort_file = cfg_get_param(SECTION_OPTIONS, NULL, "AbortFile");
	options.pause_file = cfg_get_param(SECTION_OPTIONS, NULL, "PauseFile");

	/* This is --crack-status. We toggle here, so if it's enabled in
	   john.conf, we can disable it using the command line option */
	if (cfg_get_bool(SECTION_OPTIONS, NULL, "CrackStatus", 0))
		options.flags ^= FLG_CRKSTAT;

#if HAVE_OPENCL
	if (cfg_get_bool(SECTION_OPTIONS, SUBSECTION_OPENCL, "ForceScalar", 0))
		options.flags |= FLG_SCALAR;
#endif

	options.loader.log_passwords = options.secure ||
		cfg_get_bool(SECTION_OPTIONS, NULL, "LogCrackedPasswords", 0);

	if (!pers_opts.input_enc && !(options.flags & FLG_TEST_CHK)) {
		if ((options.flags & FLG_LOOPBACK_CHK) &&
		    cfg_get_bool(SECTION_OPTIONS, NULL, "UnicodeStoreUTF8", 0))
			pers_opts.input_enc = cp_name2id("UTF-8");
		else {
			pers_opts.input_enc =
				cp_name2id(cfg_get_param(SECTION_OPTIONS, NULL,
				                          "DefaultEncoding"));
		}
		pers_opts.default_enc = pers_opts.input_enc;
	}

	/* Pre-init in case some format's prepare() needs it */
	internal = pers_opts.internal_enc;
	target = pers_opts.target_enc;
	initUnicode(UNICODE_UNICODE);
	pers_opts.internal_enc = internal;
	pers_opts.target_enc = target;
	pers_opts.unicode_cp = CP_UNDEF;
}
示例#24
0
static json_t *build_subscription_results(
    struct watchman_client_subscription *sub,
    w_root_t *root)
{
  w_query_res res;
  json_t *response;
  json_t *file_list;
  char clockbuf[128];
  struct w_clockspec *since_spec = sub->query->since_spec;

  if (since_spec && since_spec->tag == w_cs_clock) {
    w_log(W_LOG_DBG, "running subscription %s rules since %" PRIu32 "\n",
        sub->name->buf, since_spec->clock.ticks);
  } else {
    w_log(W_LOG_DBG, "running subscription %s rules (no since)\n",
        sub->name->buf);
  }

  // Subscriptions never need to sync explicitly; we are only dispatched
  // at settle points which are by definition sync'd to the present time
  sub->query->sync_timeout = 0;
  // We're called by the io thread, so there's little chance that the root
  // could be legitimately blocked by something else.  That means that we
  // can use a short lock_timeout
  sub->query->lock_timeout =
      (uint32_t)cfg_get_int(root, "subscription_lock_timeout_ms", 100);
  if (!w_query_execute(sub->query, root, &res, subscription_generator, sub)) {
    w_log(W_LOG_ERR, "error running subscription %s query: %s",
        sub->name->buf, res.errmsg);
    w_query_result_free(&res);
    return NULL;
  }

  w_log(W_LOG_DBG, "subscription %s generated %" PRIu32 " results\n",
      sub->name->buf, res.num_results);

  if (res.num_results == 0) {
    update_subscription_ticks(sub, &res);
    w_query_result_free(&res);
    return NULL;
  }

  file_list = w_query_results_to_json(&sub->field_list,
      res.num_results, res.results);
  w_query_result_free(&res);

  response = make_response();

  // It is way too much of a hassle to try to recreate the clock value if it's
  // not a relative clock spec, and it's only going to happen on the first run
  // anyway, so just skip doing that entirely.
  if (since_spec && since_spec->tag == w_cs_clock &&
      clock_id_string(since_spec->clock.root_number, since_spec->clock.ticks,
                      clockbuf, sizeof(clockbuf))) {
    set_unicode_prop(response, "since", clockbuf);
  }
  if (clock_id_string(res.root_number, res.ticks, clockbuf, sizeof(clockbuf))) {
    set_unicode_prop(response, "clock", clockbuf);
  }
  update_subscription_ticks(sub, &res);

  set_prop(response, "is_fresh_instance", json_boolean(res.is_fresh_instance));
  set_prop(response, "files", file_list);
  set_prop(response, "root", w_string_to_json(root->root_path));
  set_prop(response, "subscription", w_string_to_json(sub->name));
  set_prop(response, "unilateral", json_true());

  return response;
}
示例#25
0
void
palette_load (void)
{
	int i, j, l, fh, res;
	char prefname[256];
	struct stat st;
	char *cfg;
	int red, green, blue;
	int upgrade = FALSE;

	fh = xchat_open_file ("colors.conf", O_RDONLY, 0, 0);
	if (fh == -1)
	{
		fh = xchat_open_file ("palette.conf", O_RDONLY, 0, 0);
		upgrade = TRUE;
	}

	if (fh != -1)
	{
		fstat (fh, &st);
		cfg = malloc (st.st_size + 1);
		if (cfg)
		{
			cfg[0] = '\0';
			l = read (fh, cfg, st.st_size);
			if (l >= 0)
				cfg[l] = '\0';

			if (!upgrade)
			{
				/* mIRC colors 0-31 are here */
				for (i = 0; i < 32; i++)
				{
					snprintf (prefname, sizeof prefname, "color_%d", i);
					cfg_get_color (cfg, prefname, &red, &green, &blue);
					colors[i].red = red;
					colors[i].green = green;
					colors[i].blue = blue;
				}

				/* our special colors are mapped at 256+ */
				for (i = 256, j = 32; j < MAX_COL+1; i++, j++)
				{
					snprintf (prefname, sizeof prefname, "color_%d", i);
					cfg_get_color (cfg, prefname, &red, &green, &blue);
					colors[j].red = red;
					colors[j].green = green;
					colors[j].blue = blue;
				}

			} else
			{
				/* loading 2.0.x palette.conf */
				for (i = 0; i < MAX_COL+1; i++)
				{
					snprintf (prefname, sizeof prefname, "color_%d_red", i);
					red = cfg_get_int (cfg, prefname);

					snprintf (prefname, sizeof prefname, "color_%d_grn", i);
					green = cfg_get_int (cfg, prefname);

					snprintf (prefname, sizeof prefname, "color_%d_blu", i);
					blue = cfg_get_int_with_result (cfg, prefname, &res);

					if (res)
					{
						colors[remap[i]].red = red;
						colors[remap[i]].green = green;
						colors[remap[i]].blue = blue;
					}
				}

				/* copy 0-15 to 16-31 */
				for (i = 0; i < 16; i++)
				{
					colors[i+16].red = colors[i].red;
					colors[i+16].green = colors[i].green;
					colors[i+16].blue = colors[i].blue;
				}
			}
			free (cfg);
		}
		close (fh);
	}
}
示例#26
0
文件: cfg.cpp 项目: atmos/butt
int cfg_set_values()
{
    int i;
    char *srv_ent;
    char *icy_ent;
    char *strtok_buf;
    char info_buf[256];

    unsaved_changes = 0;

    if(cfg_parse_file(cfg_path) == -1)
    {
        snprintf(info_buf, sizeof(info_buf), "Missing config file %s", cfg_path);
        print_info(info_buf, 1);
        return 1;
    }

    cfg.audio.dev_num    = cfg_get_int("audio", "device");
    cfg.audio.samplerate = cfg_get_int("audio", "samplerate");
    cfg.audio.resolution = 16;
    cfg.audio.bitrate    = cfg_get_int("audio", "bitrate");
    cfg.audio.channel    = cfg_get_int("audio", "channel");
    cfg.audio.codec      = cfg_get_str("audio", "codec");
    cfg.audio.pcm_list   = snd_get_devices(&cfg.audio.dev_count);

    if(cfg.audio.samplerate == -1)
        cfg.audio.samplerate = 44100;

    if(cfg.audio.bitrate == -1)
        cfg.audio.bitrate = 128;

    if(cfg.audio.channel == -1)
        cfg.audio.channel = 2;

    if(cfg.audio.codec == NULL)
    {
        cfg.audio.codec = (char*)malloc(4*sizeof(char));
#ifdef HAVE_LIBLAME
        strcpy(cfg.audio.codec, "mp3");
#elif HAVE_LIBVORBIS
        strcpy(cfg.audio.codec, "ogg");
#else
        //error: but was compiled without ogg and mp3 support
        strcpy(cfg.audio.codec, "err");
#endif
    }

    //for config backward compability
    if(cfg.audio.dev_num >= cfg.audio.dev_count)
        cfg.audio.dev_num = 0;

    cfg.rec.bitrate    = cfg_get_int("record", "bitrate");
    cfg.rec.channel    = cfg_get_int("record", "channel");
    cfg.rec.samplerate = cfg_get_int("record", "samplerate");
    cfg.rec.start_rec  = cfg_get_int("record", "start_rec");
    cfg.rec.codec      = cfg_get_str("record", "codec");
    cfg.rec.filename   = cfg_get_str("record", "filename");
    cfg.rec.folder     = cfg_get_str("record", "folder");

    if(cfg.rec.bitrate == -1)
        cfg.rec.bitrate = 192;

    if(cfg.rec.channel == -1)
        cfg.rec.channel = 2;

    if(cfg.rec.samplerate == -1)
        cfg.rec.samplerate = 44100;

    if(cfg.rec.start_rec == -1)
        cfg.rec.start_rec = 1;

    if(cfg.rec.codec == NULL)
    {
        cfg.rec.codec = (char*)malloc(4*sizeof(char));
#ifdef HAVE_LIBLAME
        strcpy(cfg.rec.codec, "mp3");
#elif HAVE_LIB_VORBIS
        strcpy(cfg.rec.codec, "ogg");
#else
        strcpy(cfg.rec.codec, "wav");
#endif
    }

    if(cfg.rec.filename == NULL)
    {
        cfg.rec.filename = (char*)malloc(strlen("rec_(%m_%d_%y)_%i.ext")+1);
#ifdef HAVE_LIBLAME
        strcpy(cfg.rec.filename, "rec_(%m_%d_%y)_%i.mp3");
#elif HAVE_LIB_VORBIS
        strcpy(cfg.rec.filename, "rec_(%m_%d_%y)_%i.ogg");
#else
        strcpy(cfg.rec.filename, "rec_(%m_%d_%y)_%i.wav");
#endif
    }

    if(cfg.rec.folder == NULL)
    {
        cfg.rec.folder = (char*)malloc(3*sizeof(char));
        strcpy(cfg.rec.folder, "./");
    }


    cfg.main.num_of_srv = cfg_get_int("main", "num_of_srv");
    if(cfg.main.num_of_srv > 0)
    {
        cfg.main.srv     = cfg_get_str("main", "server");
        cfg.main.srv_ent = cfg_get_str("main", "srv_ent");

        cfg.srv = (server_t**)malloc(sizeof(server_t*) * cfg.main.num_of_srv);

        for(i = 0; i < cfg.main.num_of_srv; i++)
            cfg.srv[i] = (server_t*)malloc(sizeof(server_t));

        srv_ent = (char*)malloc((MAX_SECTION_LENGTH+1) * sizeof(char));
        strtok_buf = strdup(cfg.main.srv_ent);
        srv_ent = strtok(strtok_buf, ";");

        for(i = 0; srv_ent != NULL; i++)
        {
            cfg.srv[i]->name = (char*)malloc((MAX_SECTION_LENGTH+1) * sizeof(char));
            snprintf(cfg.srv[i]->name, MAX_SECTION_LENGTH, srv_ent);

            cfg.srv[i]->addr  = cfg_get_str(srv_ent, "address");
            cfg.srv[i]->port  = cfg_get_int(srv_ent, "port");
            cfg.srv[i]->pwd   = cfg_get_str(srv_ent, "password");
            cfg.srv[i]->type  = cfg_get_int(srv_ent, "type");
            cfg.srv[i]->mount = cfg_get_str(srv_ent, "mount");

            if(cfg.srv[i]->type == -1)
                cfg.srv[i]->type = SHOUTCAST;

            if(!strcmp(cfg.srv[i]->name, cfg.main.srv))
                cfg.selected_srv = i;

            srv_ent = strtok(NULL, ";");
        }
    }// if(cfg.main.num_of_srv > 0)

    cfg.main.num_of_icy = cfg_get_int("main", "num_of_icy");

    if(cfg.main.num_of_icy > 0)
    {
        cfg.main.icy     = cfg_get_str("main", "icy");
        cfg.main.icy_ent = cfg_get_str("main", "icy_ent");          //icy entries

        cfg.icy = (icy_t**)malloc(sizeof(icy_t*) * cfg.main.num_of_icy);

        for(i = 0; i < cfg.main.num_of_icy; i++)
            cfg.icy[i] = (icy_t*)malloc(sizeof(icy_t));

        icy_ent = (char*)malloc(MAX_SECTION_LENGTH * sizeof(char)+1);
        strtok_buf = strdup(cfg.main.icy_ent);
        icy_ent = strtok(strtok_buf, ";");

        for(i = 0; icy_ent != NULL; i++)
        {
            cfg.icy[i]->name = (char*)malloc(MAX_SECTION_LENGTH * sizeof(char)+1);
            snprintf(cfg.icy[i]->name, MAX_SECTION_LENGTH, icy_ent);

            cfg.icy[i]->desc  = cfg_get_str(icy_ent, "description");
            cfg.icy[i]->genre = cfg_get_str(icy_ent, "genre");
            cfg.icy[i]->url   = cfg_get_str(icy_ent, "url");
            cfg.icy[i]->irc   = cfg_get_str(icy_ent, "irc");
            cfg.icy[i]->icq   = cfg_get_str(icy_ent, "icq");
            cfg.icy[i]->aim   = cfg_get_str(icy_ent, "aim");
            cfg.icy[i]->pub   = cfg_get_str(icy_ent, "pub");

            if(!strcmp(cfg.icy[i]->name, icy_ent))
                cfg.selected_icy = i;

            icy_ent = strtok(NULL, ";");
        }
    }//if(cfg.main.num_of_icy > 0)

    cfg.main.song_path = cfg_get_str("main", "song_path");

    cfg.main.song_update = cfg_get_int("main", "song_update");
    if(cfg.main.song_update == -1)
        cfg.main.song_update = 0; //song update from file is default off

	cfg.main.connect_at_startup = cfg_get_int("main", "connect_at_startup");
	if(cfg.main.connect_at_startup == -1)
		cfg.main.connect_at_startup = 0;

    //read GUI stuff 
    cfg.gui.attach = cfg_get_int("gui", "attach");
    cfg.gui.ontop = cfg_get_int("gui", "ontop");

    if(cfg.gui.attach == -1)
        cfg.gui.attach = 0;

    if(cfg.gui.ontop == -1)
        cfg.gui.ontop = 0;

    //read FLTK related stuff
#if HAVE_FLTK
    cfg.main.bg_color = cfg_get_int("main", "bg_color");
    if(cfg.main.bg_color == -1)
        cfg.main.bg_color = 151540480; //dark blue

    cfg.main.txt_color = cfg_get_int("main", "txt_color");
    if(cfg.main.txt_color == -1)
        cfg.main.txt_color = -256; //white
#endif

    return 0;
}
示例#27
0
int download(char* file) {
	CURL* curl;
	CURLcode result;
	struct data config;
	FILE* fp;
	char bufferError[CURL_ERROR_SIZE];
	char url[URL_MAX];
	char tmp[PATH_MAX];
	int returnval = 0;
	int retries = 0;
	int success = 0;
	char fullpath[PATH_MAX];
	config.trace_ascii = 1;

	while (!success && retries < upstream_count) {
		sprintf(url, "http://%s/%s", getupstream(), file);
		sprintf(tmp, "%s/%s.tmp", cfg_get_str("cache_store"), file);
		sprintf(fullpath, "%s/%s", cfg_get_str("cache_store"), file);
		curl = curl_easy_init();
		if (curl) {
			fp = fopen(tmp, "wb");
			curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, bufferError);
			curl_easy_setopt(curl, CURLOPT_URL, url);
			curl_easy_setopt(curl, CURLOPT_HEADER, 0);
			curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
			curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
			curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
			curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
			curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
					curl_progress_func);
			curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
			curl_easy_setopt(curl, CURLOPT_TIMEOUT,
					cfg_get_int("curl_timeout"));
			curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,
					cfg_get_int("curl_connect_timeout"));
			if (cfg_get_int("log_level") >= 3) {
				curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_trace);
				curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &config);
				curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
			}
			result = curl_easy_perform(curl);
			curl_easy_cleanup(curl);
			fclose(fp);
		}
		if (result == CURLE_OK) {
			if (rename(tmp, fullpath) == 0) {
				download_ok(file, cfg_get_int("fe_id"));
				error_log(WARN, "Successfully downloaded: %s", fullpath);
				returnval = 0;
				success = 1;
			} else {
				remove(tmp);
				error_log(ERROR, "Rename failure: %s to %s", tmp, fullpath);
				returnval = -1;
			}
		} else {
			retries++;
			remove(tmp);
			if (curl_handle_error(result, bufferError)) {
				returnval = -1;
				error_log(WARN, "Curl error: %s", bufferError);
			} else {
				returnval = -1;
				success = 1;
				error_log(WARN, "Curl error: %s", bufferError);
			}
		}
	}
	return returnval;
}
示例#28
0
static void mysql_parse_config(DICT_MYSQL *dict_mysql, const char *mysqlcf)
{
    const char *myname = "mysql_parse_config";
    CFG_PARSER *p = dict_mysql->parser;
    VSTRING *buf;
    char   *hosts;

    dict_mysql->username = cfg_get_str(p, "user", "", 0, 0);
    dict_mysql->password = cfg_get_str(p, "password", "", 0, 0);
    dict_mysql->dbname = cfg_get_str(p, "dbname", "", 1, 0);
    dict_mysql->result_format = cfg_get_str(p, "result_format", "%s", 1, 0);
    dict_mysql->option_file = cfg_get_str(p, "option_file", NULL, 0, 0);
    dict_mysql->option_group = cfg_get_str(p, "option_group", NULL, 0, 0);
#if defined(MYSQL_VERSION_ID) && MYSQL_VERSION_ID >= 40000
    dict_mysql->tls_key_file = cfg_get_str(p, "tls_key_file", NULL, 0, 0);
    dict_mysql->tls_cert_file = cfg_get_str(p, "tls_cert_file", NULL, 0, 0);
    dict_mysql->tls_CAfile = cfg_get_str(p, "tls_CAfile", NULL, 0, 0);
    dict_mysql->tls_CApath = cfg_get_str(p, "tls_CApath", NULL, 0, 0);
    dict_mysql->tls_ciphers = cfg_get_str(p, "tls_ciphers", NULL, 0, 0);
#if MYSQL_VERSION_ID >= 50023
    dict_mysql->tls_verify_cert = cfg_get_bool(p, "tls_verify_cert", -1);
#endif
#endif

    /*
     * XXX: The default should be non-zero for safety, but that is not
     * backwards compatible.
     */
    dict_mysql->expansion_limit = cfg_get_int(dict_mysql->parser,
					      "expansion_limit", 0, 0, 0);

    if ((dict_mysql->query = cfg_get_str(p, "query", NULL, 0, 0)) == 0) {

	/*
	 * No query specified -- fallback to building it from components (old
	 * style "select %s from %s where %s")
	 */
	buf = vstring_alloc(64);
	db_common_sql_build_query(buf, p);
	dict_mysql->query = vstring_export(buf);
    }

    /*
     * Must parse all templates before we can use db_common_expand()
     */
    dict_mysql->ctx = 0;
    (void) db_common_parse(&dict_mysql->dict, &dict_mysql->ctx,
			   dict_mysql->query, 1);
    (void) db_common_parse(0, &dict_mysql->ctx, dict_mysql->result_format, 0);
    db_common_parse_domain(p, dict_mysql->ctx);

    /*
     * Maps that use substring keys should only be used with the full input
     * key.
     */
    if (db_common_dict_partial(dict_mysql->ctx))
	dict_mysql->dict.flags |= DICT_FLAG_PATTERN;
    else
	dict_mysql->dict.flags |= DICT_FLAG_FIXED;
    if (dict_mysql->dict.flags & DICT_FLAG_FOLD_FIX)
	dict_mysql->dict.fold_buf = vstring_alloc(10);

    hosts = cfg_get_str(p, "hosts", "", 0, 0);

    dict_mysql->hosts = argv_split(hosts, " ,\t\r\n");
    if (dict_mysql->hosts->argc == 0) {
	argv_add(dict_mysql->hosts, "localhost", ARGV_END);
	argv_terminate(dict_mysql->hosts);
	if (msg_verbose)
	    msg_info("%s: %s: no hostnames specified, defaulting to '%s'",
		     myname, mysqlcf, dict_mysql->hosts->argv[0]);
    }
    myfree(hosts);
}