Beispiel #1
0
liAction *li_plugin_config_action(liServer *srv, liWorker *wrk, const gchar *name, liValue *val) {
	liAction *a = NULL;
	liServerAction *sa;
	liServerOption *sopt;
	liServerOptionPtr *soptptr;

	if (NULL != (sa = (liServerAction*) g_hash_table_lookup(srv->actions, name))) {
		if (NULL == (a = sa->create_action(srv, wrk, sa->p, val, sa->userdata))) {
			ERROR(srv, "Action '%s' creation failed", name);
		}
	} else if (NULL != (sopt = find_option(srv, name))) {
		liOptionSet setting;

		if (!li_parse_option(srv, wrk, sopt, name, option_value(val), &setting)) goto exit;

		a = li_action_new_setting(setting);
	} else if (NULL != (soptptr = find_optionptr(srv, name))) {
		liOptionPtrSet setting;

		if (!li_parse_optionptr(srv, wrk, soptptr, name, option_value(val), &setting)) goto exit;

		a = li_action_new_settingptr(setting);
	} else if (NULL != g_hash_table_lookup(srv->setups, name)) {
		ERROR(srv, "'%s' can only be called in a setup block", name);
	} else {
		ERROR(srv, "unknown action %s", name);
	}

exit:
	li_value_free(val);
	return a;
}
Beispiel #2
0
gboolean li_plugin_config_setup(liServer *srv, const char *name, liValue *val) {
	gboolean result = FALSE;
	liServerSetup *ss;
	liServerOption *sopt;
	liServerOptionPtr *soptptr;

	if (NULL != (ss = (liServerSetup*) g_hash_table_lookup(srv->setups, name))) {
		if (!ss->setup(srv, ss->p, val, ss->userdata)) {
			ERROR(srv, "Setup '%s' failed", name);
			goto exit;
		}
		result = TRUE;
	} else if (NULL != (sopt = find_option(srv, name))) {
		liOptionSet setting;

		if (!li_parse_option(srv, srv->main_worker, sopt, name, option_value(val), &setting)) goto exit;

		g_array_index(srv->option_def_values, liOptionValue, sopt->index) = setting.value;
		result = TRUE;
	} else if (NULL != (soptptr = find_optionptr(srv, name))) {
		liOptionPtrSet setting;

		if (!li_parse_optionptr(srv, srv->main_worker, soptptr, name, option_value(val), &setting)) goto exit;

		li_release_optionptr(srv, g_array_index(srv->optionptr_def_values, liOptionPtrValue*, soptptr->index));
		g_array_index(srv->optionptr_def_values, liOptionPtrValue*, soptptr->index) = setting.value;
		result = TRUE;
	} else if (NULL != g_hash_table_lookup(srv->setups, name)) {
    void option_target::assign(const std::string& value) {
        if (this->empty()) {
            throw option_parse_error{error_type::futile_value, value};
        }

        auto& r = (*this->result)[this->name];
        switch (this->container) {
            case json::content_type::null: {
                r = option_value(this->element, value);
                this->clear();
                break;
            }
            case json::content_type::array: {
                r.as_array().emplace_back(option_value(this->element, value));
                break;
            }
            case json::content_type::object: {
                auto p = value.find('=');
                if (p == std::string::npos) {
                    throw option_parse_error{error_type::not_kv, value};
                }
                auto v = option_value(this->element, value.substr(p + 1));
                r.as_object().emplace(
                  std::make_pair(value.substr(0, p), std::move(v))
                );
                break;
            }
            default: {
                throw this->container;
            }
        }
        this->assigned = true;
    }
Beispiel #4
0
static void TB_rank_root_moves(Pos *pos, RootMoves *rm)
{
  TB_RootInTB = 0;
  TB_UseRule50 = option_value(OPT_SYZ_50_MOVE);
  TB_ProbeDepth = option_value(OPT_SYZ_PROBE_DEPTH) * ONE_PLY;
  TB_Cardinality = option_value(OPT_SYZ_PROBE_LIMIT);
  int dtz_available = 1, dtm_available = 0;

  if (TB_Cardinality > TB_MaxCardinality) {
    TB_Cardinality = TB_MaxCardinality;
    TB_ProbeDepth = DEPTH_ZERO;
  }

  TB_CardinalityDTM =  option_value(OPT_SYZ_USE_DTM)
                     ? min(TB_Cardinality, TB_MaxCardinalityDTM)
                     : 0;

  if (TB_Cardinality >= popcount(pieces()) && !can_castle_any()) {
    // Try to rank moves using DTZ tables.
    TB_RootInTB = TB_root_probe_dtz(pos, rm);

    if (!TB_RootInTB) {
      // DTZ tables are missing.
      dtz_available = 0;

      // Try to rank moves using WDL tables as fallback.
      TB_RootInTB = TB_root_probe_wdl(pos, rm);
    }

    // If ranking was successful, try to obtain mate values from DTM tables.
    if (TB_RootInTB && TB_CardinalityDTM >= popcount(pieces()))
      dtm_available = TB_root_probe_dtm(pos, rm);
  }

  if (TB_RootInTB) { // Ranking was successful.
    // Sort moves according to TB rank.
    stable_sort(rm->move, rm->size);

    // Only probe during search if DTM and DTZ are not available
    // and we are winning.
    if (dtm_available || dtz_available || rm->move[0].tbRank <= 0)
      TB_Cardinality = 0;
  }
  else // Ranking was not successful.
    for (int i = 0; i < rm->size; i++)
      rm->move[i].tbRank = 0;
}
Beispiel #5
0
static void uci_print_pv(Pos *pos, Depth depth, Value alpha, Value beta)
{
  TimePoint elapsed = time_elapsed() + 1;
  RootMoves *rm = pos->rootMoves;
  int pvIdx = pos->pvIdx;
  int multiPV = min(option_value(OPT_MULTI_PV), rm->size);
  uint64_t nodes_searched = threads_nodes_searched();
  uint64_t tbhits = threads_tb_hits();
  char buf[16];

  flockfile(stdout);
  for (int i = 0; i < multiPV; i++) {
    int updated = (i <= pvIdx && rm->move[i].score != -VALUE_INFINITE);

    if (depth == ONE_PLY && !updated)
        continue;

    Depth d = updated ? depth : depth - ONE_PLY;
    Value v = updated ? rm->move[i].score : rm->move[i].previousScore;

    int tb = TB_RootInTB && abs(v) < VALUE_MATE - MAX_MATE_PLY;
    if (tb)
      v = rm->move[i].tbScore;

    // An incomplete mate PV may be caused by cutoffs in qsearch() and
    // by TB cutoffs. We try to complete the mate PV if we may be in the
    // latter case.
    if (   abs(v) > VALUE_MATE - MAX_MATE_PLY
        && rm->move[i].pvSize < VALUE_MATE - abs(v)
        && TB_MaxCardinalityDTM > 0)
      TB_expand_mate(pos, &rm->move[i]);

    printf("info depth %d seldepth %d multipv %d score %s",
           d / ONE_PLY, rm->move[i].selDepth, i + 1,
           uci_value(buf, v));

    if (!tb && i == pvIdx)
      printf("%s", v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");

    printf(" nodes %"PRIu64" nps %"PRIu64, nodes_searched,
                              nodes_searched * 1000 / elapsed);

    if (elapsed > 1000)
      printf(" hashfull %d", tt_hashfull());

    printf(" tbhits %"PRIu64" time %"PRIi64" pv", tbhits, elapsed);

    for (int idx = 0; idx < rm->move[i].pvSize; idx++)
      printf(" %s", uci_move(buf, rm->move[i].pv[idx], is_chess960()));
    printf("\n");
  }
  fflush(stdout);
  funlockfile(stdout);
}
Beispiel #6
0
// removed from libzmq3
SEXP set_mcast_loop(SEXP socket_, SEXP option_value_) {

  zmq::socket_t* socket = reinterpret_cast<zmq::socket_t*>(checkExternalPointer(socket_,"zmq::socket_t*"));
  if(!socket) { REprintf("bad socket object.\n");return R_NilValue; }
  if(TYPEOF(option_value_)!=LGLSXP) { REprintf("option value must be a logical.\n");return R_NilValue; }
  SEXP ans; PROTECT(ans = allocVector(LGLSXP,1)); LOGICAL(ans)[0] = 1;

  int64_t option_value(LOGICAL(option_value_)[0]);
  try {
    socket->setsockopt(ZMQ_MCAST_LOOP, &option_value, sizeof(int64_t));
  } catch(std::exception& e) {
    REprintf("%s\n",e.what());
    LOGICAL(ans)[0] = 0;
  }
  UNPROTECT(1);
  return ans;
}
Beispiel #7
0
// removed from libzmq3
SEXP set_recovery_ivl_msec(SEXP socket_, SEXP option_value_) {

  zmq::socket_t* socket = reinterpret_cast<zmq::socket_t*>(checkExternalPointer(socket_,"zmq::socket_t*"));
  if(!socket) { REprintf("bad socket object.\n");return R_NilValue; }
  if(TYPEOF(option_value_)!=INTSXP) { REprintf("option value must be an int.\n");return R_NilValue; }
  SEXP ans; PROTECT(ans = allocVector(LGLSXP,1)); LOGICAL(ans)[0] = 1;

  int64_t option_value(INTEGER(option_value_)[0]);
  try {
    socket->setsockopt(ZMQ_RECOVERY_IVL_MSEC, &option_value, sizeof(int64_t));
  } catch(std::exception& e) {
    REprintf("%s\n",e.what());
    LOGICAL(ans)[0] = 0;
  }
  UNPROTECT(1);
  return ans;
}
void SetOptionsFromStreamNode::set_options( const OptionsFromStream& options )
{
  OptionsFromStream::options_group_t optgrp = options.options_group( name_map_.name() );
  if( !OptionsFromStream::options_group_exists( optgrp ) ) {
    TEST_FOR_EXCEPTION(
      !exists_optional_, std::invalid_argument
      ,"SetOptionsFromStreamNode::set_options(...) : "
      << "Error, The options group " << name_map_.name()
      << " does not exist" );
    if(exists_optional_)
      return;
  }
    
  OptionsFromStream::options_group_t::const_iterator itr = optgrp.begin();
  for( ; itr != optgrp.end(); ++itr ) {
    setOption( name_map_( option_name(itr) ), option_value(itr).c_str() );
  }
}
Beispiel #9
0
int main(void) {
    volatile int i;

    // stop watchdog timer or the the mcu will keep resetting.
    WDTCTL = WDTPW | WDTHOLD;
    // Set P1.0 and P1.6 as Output pins and make sure they
    // start out set low.
    P1DIR = 0x41;
    P1OUT = 0x00;

    // Blink on and off periodically.
    for (;;) {
        P1OUT |= option_value("RED");
        for (i = 0; i < 0x6000; i++);
        P1OUT &= ~option_value("GREEN");
        for (i = 0; i < 0x6000; i++);
    }
}
Beispiel #10
0
int main(void) {
	volatile int i;

	// stop watchdog timer
	WDTCTL = WDTPW | WDTHOLD;
	// set up bit 0 and 6 of P1 as output
	P1DIR = 0x41;
	// intialize P1 to 0
	P1OUT = 0x00;

	// loop forever
	for (;;) {
		P1OUT |= option_value("GREEN");
		// delay for a while
		for (i = 0; i < 0x6000; i++);
		P1OUT &= ~option_value("GREEN");
		for (i = 0; i < 0x6000; i++);
	}
}
Beispiel #11
0
void thread_search(Pos *pos)
{
  Value bestValue, alpha, beta, delta;
  Move pv[MAX_PLY + 1];
  Move lastBestMove = 0;
  Depth lastBestMoveDepth = DEPTH_ZERO;
  double timeReduction = 1.0;

  Stack *ss = pos->st; // At least the seventh element of the allocated array.
  for (int i = -7; i < 3; i++)
    memset(SStackBegin(ss[i]), 0, SStackSize);
  (ss-1)->endMoves = pos->moveList;

  for (int i = -7; i < 0; i++)
    ss[i].history = &(*pos->counterMoveHistory)[0][0]; // Use as sentinel

  for (int i = 0; i <= MAX_PLY; i++)
    ss[i].ply = i;
  ss->pv = pv;

  bestValue = delta = alpha = -VALUE_INFINITE;
  beta = VALUE_INFINITE;
  pos->completedDepth = DEPTH_ZERO;

  if (pos->threadIdx == 0)
    mainThread.bestMoveChanges = 0;

  int multiPV = option_value(OPT_MULTI_PV);
#if 0
  Skill skill(option_value(OPT_SKILL_LEVEL));

  // When playing with strength handicap enable MultiPV search that we will
  // use behind the scenes to retrieve a set of possible moves.
  if (skill.enabled())
      multiPV = std::max(multiPV, (size_t)4);
#endif

  RootMoves *rm = pos->rootMoves;
  multiPV = min(multiPV, rm->size);

  // Iterative deepening loop until requested to stop or the target depth
  // is reached.
  while (   (pos->rootDepth += ONE_PLY) < DEPTH_MAX
         && !Signals.stop
         && !(   Limits.depth
              && pos->threadIdx == 0
              && pos->rootDepth / ONE_PLY > Limits.depth))
  {
    // Age out PV variability metric
    if (pos->threadIdx == 0)
      mainThread.bestMoveChanges *= 0.517;

    // Save the last iteration's scores before first PV line is searched and
    // all the move scores except the (new) PV are set to -VALUE_INFINITE.
    for (int idx = 0; idx < rm->size; idx++)
      rm->move[idx].previousScore = rm->move[idx].score;

    pos->contempt = pos_stm() == WHITE ?  make_score(base_ct, base_ct / 2)
                                       : -make_score(base_ct, base_ct / 2);

    int pvFirst = 0, pvLast = 0;

    // MultiPV loop. We perform a full root search for each PV line
    for (int pvIdx = 0; pvIdx < multiPV && !Signals.stop; pvIdx++) {
      pos->pvIdx = pvIdx;
      if (pvIdx == pvLast) {
        pvFirst = pvLast;
        for (pvLast++; pvLast < rm->size; pvLast++)
          if (rm->move[pvLast].tbRank != rm->move[pvFirst].tbRank)
            break;
        pos->pvLast = pvLast;
      }

      pos->selDepth = 0;

      // Skip the search if we have a mate value from DTM tables.
      if (abs(rm->move[pvIdx].tbRank) > 1000) {
        bestValue = rm->move[pvIdx].score = rm->move[pvIdx].tbScore;
        alpha = -VALUE_INFINITE;
        beta = VALUE_INFINITE;
        goto skip_search;
      }

      // Reset aspiration window starting size
      if (pos->rootDepth >= 5 * ONE_PLY) {
        Value previousScore = rm->move[pvIdx].previousScore;
        delta = 20;
        alpha = max(previousScore - delta, -VALUE_INFINITE);
        beta  = min(previousScore + delta,  VALUE_INFINITE);

        // Adjust contempt based on root move's previousScore
        int ct = base_ct + 88 * previousScore / (abs(previousScore) + 200);
        pos->contempt = pos_stm() == WHITE ?  make_score(ct, ct / 2)
                                           : -make_score(ct, ct / 2);
      }

      // Start with a small aspiration window and, in the case of a fail
      // high/low, re-search with a bigger window until we're not failing
      // high/low anymore.
      int failedHighCnt = 0;
      while (true) {
        Depth adjustedDepth = max(ONE_PLY, pos->rootDepth - failedHighCnt * ONE_PLY);
        bestValue = search_PV(pos, ss, alpha, beta, adjustedDepth);

        // Bring the best move to the front. It is critical that sorting
        // is done with a stable algorithm because all the values but the
        // first and eventually the new best one are set to -VALUE_INFINITE
        // and we want to keep the same order for all the moves except the
        // new PV that goes to the front. Note that in case of MultiPV
        // search the already searched PV lines are preserved.
        stable_sort(&rm->move[pvIdx], pvLast - pvIdx);

        // If search has been stopped, we break immediately. Sorting and
        // writing PV back to TT is safe because RootMoves is still
        // valid, although it refers to the previous iteration.
        if (Signals.stop)
          break;

        // When failing high/low give some update (without cluttering
        // the UI) before a re-search.
        if (   pos->threadIdx == 0
            && multiPV == 1
            && (bestValue <= alpha || bestValue >= beta)
            && time_elapsed() > 3000)
          uci_print_pv(pos, pos->rootDepth, alpha, beta);

        // In case of failing low/high increase aspiration window and
        // re-search, otherwise exit the loop.
        if (bestValue <= alpha) {
          beta = (alpha + beta) / 2;
          alpha = max(bestValue - delta, -VALUE_INFINITE);

          if (pos->threadIdx == 0) {
            failedHighCnt = 0;
            Signals.stopOnPonderhit = 0;
          }
        } else if (bestValue >= beta) {
          beta = min(bestValue + delta, VALUE_INFINITE);
          if (pos->threadIdx == 0)
            failedHighCnt++;
        } else
          break;

        delta += delta / 4 + 5;

        assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
      }

      // Sort the PV lines searched so far and update the GUI
      stable_sort(&rm->move[pvFirst], pvIdx - pvFirst + 1);

skip_search:
      if (    pos->threadIdx == 0
          && (Signals.stop || pvIdx + 1 == multiPV || time_elapsed() > 3000))
        uci_print_pv(pos, pos->rootDepth, alpha, beta);
    }

    if (!Signals.stop)
      pos->completedDepth = pos->rootDepth;

    if (rm->move[0].pv[0] != lastBestMove) {
      lastBestMove = rm->move[0].pv[0];
      lastBestMoveDepth = pos->rootDepth;
    }

    // Have we found a "mate in x"?
    if (   Limits.mate
        && bestValue >= VALUE_MATE_IN_MAX_PLY
        && VALUE_MATE - bestValue <= 2 * Limits.mate)
      Signals.stop = 1;

    if (pos->threadIdx != 0)
      continue;

#if 0
    // If skill level is enabled and time is up, pick a sub-optimal best move
    if (skill.enabled() && skill.time_to_pick(thread->rootDepth))
      skill.pick_best(multiPV);
#endif

    // Do we have time for the next iteration? Can we stop searching now?
    if (    use_time_management()
        && !Signals.stop
        && !Signals.stopOnPonderhit) {
      // Stop the search if only one legal move is available, or if all
      // of the available time has been used.
      double fallingEval = (306 + 9 * (mainThread.previousScore - bestValue)) / 581.0;
      fallingEval = max(0.5, min(1.5, fallingEval));

      // If the best move is stable over several iterations, reduce time
      // accordingly
      timeReduction =  lastBestMoveDepth + 10 * ONE_PLY < pos->completedDepth
                     ? 1.95 : 1.0;
      double reduction = pow(mainThread.previousTimeReduction, 0.528) / timeReduction;

      // Use part of the gained time from a previous stable move for this move
      double bestMoveInstability = 1.0 + mainThread.bestMoveChanges;

      if (   rm->size == 1
          || time_elapsed() > time_optimum() * fallingEval * reduction * bestMoveInstability)
      {
        // If we are allowed to ponder do not stop the search now but
        // keep pondering until the GUI sends "ponderhit" or "stop".
        if (Limits.ponder)
          Signals.stopOnPonderhit = 1;
        else
          Signals.stop = 1;
      }
    }
  }

  if (pos->threadIdx != 0)
    return;

  mainThread.previousTimeReduction = timeReduction;

#if 0
  // If skill level is enabled, swap best PV line with the sub-optimal one
  if (skill.enabled())
    std::swap(rm[0], *std::find(rm.begin(),
              rm.end(), skill.best_move(multiPV)));
#endif
}
Beispiel #12
0
void mainthread_search(void)
{
  Pos *pos = Threads.pos[0];
  int us = pos_stm();
  time_init(us, pos_game_ply());
  tt_new_search();
  char buf[16];
  bool playBookMove = false;

  base_ct = option_value(OPT_CONTEMPT) * PawnValueEg / 100;

  const char *s = option_string_value(OPT_ANALYSIS_CONTEMPT);
  if (Limits.infinite || option_value(OPT_ANALYSE_MODE))
    base_ct =  strcmp(s, "off") == 0 ? 0
             : strcmp(s, "white") == 0 && us == BLACK ? -base_ct
             : strcmp(s, "black") == 0 && us == WHITE ? -base_ct
             : base_ct;

  if (pos->rootMoves->size > 0) {
    Move bookMove = 0;

    if (!Limits.infinite && !Limits.mate)
      bookMove = pb_probe(pos);

    for (int i = 0; i < pos->rootMoves->size; i++)
      if (pos->rootMoves->move[i].pv[0] == bookMove) {
        RootMove tmp = pos->rootMoves->move[0];
        pos->rootMoves->move[0] = pos->rootMoves->move[i];
        pos->rootMoves->move[i] = tmp;
        playBookMove = true;
        break;
      }

    if (!playBookMove) {
      for (int idx = 1; idx < Threads.numThreads; idx++)
        thread_wake_up(Threads.pos[idx], THREAD_SEARCH);

      thread_search(pos); // Let's start searching!
    }
  }

  // When we reach the maximum depth, we can arrive here without a raise
  // of Signals.stop. However, if we are pondering or in an infinite
  // search, the UCI protocol states that we shouldn't print the best
  // move before the GUI sends a "stop" or "ponderhit" command. We
  // therefore simply wait here until the GUI sends one of those commands
  // (which also raises Signals.stop).
  LOCK(Signals.lock);
  if (!Signals.stop && (Limits.ponder || Limits.infinite)) {
    Signals.sleeping = 1;
    UNLOCK(Signals.lock);
    thread_wait(pos, &Signals.stop);
  } else
    UNLOCK(Signals.lock);

  // Stop the threads if not already stopped
  Signals.stop = 1;

  // Wait until all threads have finished
  if (pos->rootMoves->size > 0) {
    if (!playBookMove) {
      for (int idx = 1; idx < Threads.numThreads; idx++)
        thread_wait_until_sleeping(Threads.pos[idx]);
    }
  } else {
    pos->rootMoves->move[0].pv[0] = 0;
    pos->rootMoves->move[0].pvSize = 1;
    pos->rootMoves->size++;
    printf("info depth 0 score %s\n",
           uci_value(buf, pos_checkers() ? -VALUE_MATE : VALUE_DRAW));
    fflush(stdout);
  }

  // When playing in 'nodes as time' mode, subtract the searched nodes from
  // the available ones before exiting.
  if (Limits.npmsec)
    Time.availableNodes += Limits.inc[us] - threads_nodes_searched();

  // Check if there are threads with a better score than main thread
  Pos *bestThread = pos;
  if (    option_value(OPT_MULTI_PV) == 1
      && !playBookMove
      && !Limits.depth
//      && !Skill(option_value(OPT_SKILL_LEVEL)).enabled()
      &&  pos->rootMoves->move[0].pv[0] != 0)
  {
    int i, num = 0, maxNum = min(pos->rootMoves->size, Threads.numThreads);
    Move mvs[maxNum];
    int64_t votes[maxNum];
    Value minScore = pos->rootMoves->move[0].score;
    for (int idx = 1; idx < Threads.numThreads; idx++)
      minScore = min(minScore, Threads.pos[idx]->rootMoves->move[0].score);
    for (int idx = 0; idx < Threads.numThreads; idx++) {
      Pos *p = Threads.pos[idx];
      Move m = p->rootMoves->move[0].pv[0];
      for (i = 0; i < num; i++)
        if (mvs[i] == m) break;
      if (i == num) {
        num++;
        mvs[i] = m;
        votes[i] = 0;
      }
      int64_t diff = p->rootMoves->move[0].score - minScore + 1;
      votes[i] += 200 + (diff * diff) * p->completedDepth;
    }
    int64_t bestVote = votes[0];
    for (int idx = 1; idx < Threads.numThreads; idx++) {
      Pos *p = Threads.pos[idx];
      for (i = 0; mvs[i] != p->rootMoves->move[0].pv[0]; i++);
      if (votes[i] > bestVote) {
        bestVote = votes[i];
        bestThread = p;
      }
    }
  }

  mainThread.previousScore = bestThread->rootMoves->move[0].score;

  // Send new PV when needed
  if (bestThread != pos)
    uci_print_pv(bestThread, bestThread->completedDepth,
                 -VALUE_INFINITE, VALUE_INFINITE);

  flockfile(stdout);
  printf("bestmove %s", uci_move(buf, bestThread->rootMoves->move[0].pv[0], is_chess960()));

  if (bestThread->rootMoves->move[0].pvSize > 1 || extract_ponder_from_tt(&bestThread->rootMoves->move[0], pos))
    printf(" ponder %s", uci_move(buf, bestThread->rootMoves->move[0].pv[1], is_chess960()));

  printf("\n");
  fflush(stdout);
  funlockfile(stdout);
}
Beispiel #13
0
/**
 * parse_options
 */
static void parse_options(int argc, char *argv[])
{
	long long ll;
	char *s, *s2;
	int c;

	opt_alloc_len = 0;
	opt_alloc_offs = 0;
	if (argc && *argv)
		EXEC_NAME = *argv;
	fprintf(stderr, "%s v%s (libntfs-3g)\n", EXEC_NAME, VERSION);
	while ((c = getopt_long(argc, argv, "fh?no:qvVl:", lopt, NULL)) != EOF) {
		switch (c) {
		case 'f':
			opts.force = 1;
			break;
		case 'n':
			opts.no_size_change = 1;
			break;
		case 'N':		/* Not proposed as a short option */
			opts.no_action = 1;
			break;
		case 'q':
			opts.quiet = 1;
			ntfs_log_clear_levels(NTFS_LOG_LEVEL_QUIET);
			break;
		case 'v':
			opts.verbose++;
			ntfs_log_set_levels(NTFS_LOG_LEVEL_VERBOSE);
			break;
		case 'V':
			/* Version number already printed */
			license();
			exit(0);
		case 'l':
			ll = option_value(argv[optind - 1]);
			if ((ll <= 0)
			    || (ll >= LLONG_MAX && errno == ERANGE))
				err_usage("Invalid length : %s\n",
					argv[optind - 1]);
			opt_alloc_len = ll;
			break;
		case 'o':
			ll = option_value(argv[optind - 1]);
			if ((ll < 0)
			    || (ll >= LLONG_MAX && errno == ERANGE))
				err_usage("Invalid offset : %s\n",
					argv[optind - 1]);
			opt_alloc_offs = ll;
			break;
		case 'h':
			usage(0);
		case '?':
		default:
			usage(1);
		}
	}
	if (!opt_alloc_len) {
		err_usage("Missing allocation length\n");
	}

	ntfs_log_verbose("length = %lli = 0x%llx\n",
			(long long)opt_alloc_len, (long long)opt_alloc_len);
	ntfs_log_verbose("offset = %lli = 0x%llx\n",
			(long long)opt_alloc_offs, (long long)opt_alloc_offs);

	if (optind == argc)
		usage(1);

	if (opts.verbose > 1)
		ntfs_log_set_levels(NTFS_LOG_LEVEL_DEBUG | NTFS_LOG_LEVEL_TRACE |
			NTFS_LOG_LEVEL_VERBOSE | NTFS_LOG_LEVEL_QUIET);

	/* Get the device. */
	dev_name = argv[optind++];
	ntfs_log_verbose("device name = %s\n", dev_name);

	if (optind == argc)
		usage(1);

	/* Get the file name. */
	file_name = argv[optind++];
	ntfs_log_verbose("file name = \"%s\"\n", file_name);

	/* Get the attribute type, if specified. */
	if (optind == argc) {
		attr_type = AT_DATA;
		attr_name = AT_UNNAMED;
		attr_name_len = 0;
	} else {
		unsigned long ul;

		s = argv[optind++];
		ul = strtoul(s, &s2, 0);
		if (*s2 || !ul || (ul >= ULONG_MAX && errno == ERANGE))
			err_usage("Invalid attribute type %s: %s\n", s,
					strerror(errno));
		attr_type = cpu_to_le32(ul);

		/* Get the attribute name, if specified. */
		if (optind != argc) {
			s = argv[optind++];
			/* Convert the string to little endian Unicode. */
			attr_name_len = ntfs_mbstoucs(s, &attr_name);
			if ((int)attr_name_len < 0)
				err_usage("Invalid attribute name "
						"\"%s\": %s\n",
						s, strerror(errno));

			/* Keep hold of the original string. */
			s2 = s;

			s = argv[optind++];
			if (optind != argc)
				usage(1);
		} else {
			attr_name = AT_UNNAMED;
			attr_name_len = 0;
		}
	}
	ntfs_log_verbose("attribute type = 0x%lx\n",
					(unsigned long)le32_to_cpu(attr_type));
	if (attr_name == AT_UNNAMED)
		ntfs_log_verbose("attribute name = \"\" (UNNAMED)\n");
	else
		ntfs_log_verbose("attribute name = \"%s\" (length %u "
				"Unicode characters)\n", s2,
				(unsigned int)attr_name_len);
}
Beispiel #14
0
void Kernel::collectExtraOptions()
{

    for (const auto& o : m_extra_options)
    {

        typedef boost::tokenizer<boost::char_separator<char>> tokenizer;

        // if we don't have --, we're not an option we
        // even care about
        if (!boost::algorithm::find_first(o, "--")) continue;

        // Find the dimensions listed and put them on the id list.
        boost::char_separator<char> equal("=");
        boost::char_separator<char> dot(".");
        // boost::erase_all(o, " "); // Wipe off spaces
        tokenizer option_tokens(o, equal);
        std::vector<std::string> option_split;
        for (auto ti = option_tokens.begin(); ti != option_tokens.end(); ++ti)
            option_split.push_back(boost::lexical_cast<std::string>(*ti));
        if (!(option_split.size() == 2))
        {
            std::ostringstream oss;
            oss << "option '" << o << "' did not split correctly. Is it in the form --readers.las.option=foo?";
            throw app_usage_error(oss.str());
        }

        std::string option_value(option_split[1]);
        std::string stage_value(option_split[0]);
        boost::algorithm::erase_all(stage_value, "--");

        tokenizer name_tokens(stage_value, dot);
        std::vector<std::string> stage_values;
        for (auto ti = name_tokens.begin(); ti != name_tokens.end(); ++ti)
        {
            stage_values.push_back(*ti);
        }

        std::string option_name = *stage_values.rbegin();
        std::ostringstream stage_name_ostr;
        bool bFirst(true);
        for (auto s = stage_values.begin(); s != stage_values.end()-1; ++s)
        {
            auto s2 = boost::algorithm::erase_all_copy(*s, " ");

            if (bFirst)
            {
                bFirst = false;
            }
            else
                stage_name_ostr <<".";
            stage_name_ostr << s2;
        }
        std::string stage_name(stage_name_ostr.str());

        auto found = m_extra_stage_options.find(stage_name);
        if (found == m_extra_stage_options.end())
            m_extra_stage_options.insert(std::make_pair(stage_name, Option(option_name, option_value, "")));
        else
            found->second.add(Option(option_name, option_value, ""));
    }
}
Beispiel #15
0
int
main (int argc, char **argv)
{
  char *args;
  char *logfile;
  char *passphrasefile;
  char *passphrase;

  /* We get our options via PINENTRY_USER_DATA.  */
  (void) argc, (void) argv;

  setvbuf (stdin, NULL, _IOLBF, BUFSIZ);
  setvbuf (stdout, NULL, _IOLBF, BUFSIZ);

  args = getenv ("PINENTRY_USER_DATA");
  if (! args)
    args = "";

  logfile = option_value (args, "--logfile");
  if (logfile)
    {
      char *p = logfile, more;
      while (*p && ! spacep (p))
        p++;
      more = !! *p;
      *p = 0;
      args = more ? p+1 : p;

      log_stream = fopen (logfile, "a");
      if (! log_stream)
        {
          perror (logfile);
          return 1;
        }
    }

  passphrasefile = option_value (args, "--passphrasefile");
  if (passphrasefile)
    {
      char *p = passphrasefile, more;
      while (*p && ! spacep (p))
        p++;
      more = !! *p;
      *p = 0;
      args = more ? p+1 : p;

      passphrase = get_passphrase (passphrasefile);
      if (! passphrase)
        {
          reply ("# Passphrasefile '%s' is empty.  Terminating.\n",
                 passphrasefile);
          return 1;
        }

      p = passphrase + strlen (passphrase) - 1;
      if (*p == '\n')
        *p = 0;
    }
  else
    passphrase = skip_options (args);

  reply ("# fake-pinentry started.  Passphrase='%s'.\n", passphrase);
  reply ("OK - what's up?\n");

  while (! feof (stdin))
    {
      char buffer[1024];

      if (fgets (buffer, sizeof buffer, stdin) == NULL)
	break;

      if (log_stream)
        fprintf (log_stream, "< %s", buffer);

      if (strncmp (buffer, "GETPIN", 6) == 0)
        reply ("D %s\n", passphrase);
      else if (strncmp (buffer, "BYE", 3) == 0)
	{
	  reply ("OK\n");
	  break;
	}

      reply ("OK\n");
    }

  reply ("# Connection terminated.\n");
  if (log_stream)
    fclose (log_stream);

  return 0;
}