예제 #1
0
파일: krpc.cpp 프로젝트: Outurnate/krpc
  Client connect(const std::string& name, const std::string& address,
                 unsigned int rpc_port, unsigned int stream_port) {
    if (rpc_port == stream_port) {
      BOOST_THROW_EXCEPTION(
        ConnectionFailed()
        << error_description("RPC and Stream port numbers are the same"));
    }

    // Connect to RPC server
    boost::shared_ptr<Connection> rpc_connection(new Connection(address, rpc_port));
    rpc_connection->connect(10, 0.1);
    rpc_connection->send(encoder::RPC_HELLO_MESSAGE, encoder::RPC_HELLO_MESSAGE_LENGTH);
    rpc_connection->send(encoder::client_name(name));
    std::string client_identifier = rpc_connection->receive(decoder::GUID_LENGTH);

    // Connect to Stream server
    boost::shared_ptr<Connection> stream_connection;
    if (stream_port != 0) {
      stream_connection = boost::shared_ptr<Connection>(new Connection(address, stream_port));
      stream_connection->connect(10, 0.1);
      stream_connection->send(encoder::STREAM_HELLO_MESSAGE, encoder::STREAM_HELLO_MESSAGE_LENGTH);
      stream_connection->send(client_identifier);
      std::string ok_message = stream_connection->receive(decoder::OK_MESSAGE_LENGTH);
      std::string expected(decoder::OK_MESSAGE);
      if (!std::equal(ok_message.begin(), ok_message.end(), expected.begin())) {
        BOOST_THROW_EXCEPTION(
          ConnectionFailed()
          << error_description("Did not receive OK message from server"));
      }
    }

    return Client(rpc_connection, stream_connection);
  }
예제 #2
0
void wtss::tl::server_manager::changeStatusCoverage(const QString &server_uri,
                                                    const QString &cv_name)
{
  QJsonDocument j_doc = loadSettings();
  QJsonObject j_object = j_doc.object();

  QJsonObject j_servers = j_object.find("servers").value().toObject();

  if(!j_servers.contains(server_uri))
  {
    boost::format err_msg("Could not find the server: %1%");
    throw out_of_range_exception()
        << error_description((err_msg % server_uri.toUtf8().data()).str());
  }

  QJsonObject j_server = j_servers.find(server_uri).value().toObject();

  if(!j_server.contains("coverages"))
  {
    boost::format err_msg("The server %1% has no coverages");
    throw out_of_range_exception()
        << error_description((err_msg % server_uri.toUtf8().data()).str());
  }

  QJsonObject j_coverages = j_server.find("coverages").value().toObject();
  QJsonObject j_coverage = j_coverages.find(cv_name).value().toObject();
  bool active = j_coverage.find("active").value().toBool();
  j_coverage["active"] = !active;
  if(!active)
  {
    for(QJsonObject::iterator it = j_coverages.begin(); it != j_coverages.end();
        ++it)
    {
      if(it.key() != cv_name)
      {
        QJsonObject j_cv = it.value().toObject();
        j_cv["active"] = QJsonValue(false);
        j_coverages[it.key()] = j_cv;
      }
    }
  }
  if(!j_coverages.contains(cv_name))
  {
    boost::format err_msg("The server %1% has no coverage named: %2%");
    throw out_of_range_exception() << error_description(
        (err_msg % server_uri.toUtf8().data() % cv_name.toUtf8().data()).str());
  }

  j_coverages[cv_name] = j_coverage;
  j_server["coverages"] = j_coverages;
  j_servers[server_uri] = j_server;

  j_object["servers"] = j_servers;
  j_doc.setObject(j_object);

  saveSettings(j_doc);
}
예제 #3
0
QJsonObject wtss::tl::server_manager::getAttribute(const QString &server_uri,
                                                   const QString &cv_name,
                                                   const QString &attribute)
{
  QJsonDocument j_doc = loadSettings();
  QJsonObject j_object = j_doc.object();

  QJsonObject j_servers = j_object.find("servers").value().toObject();

  if(!j_servers.contains(server_uri))
  {
    boost::format err_msg("Could not find the server: %1%");
    throw out_of_range_exception()
        << error_description((err_msg % server_uri.toUtf8().data()).str());
  }

  QJsonObject j_server = j_servers.find(server_uri).value().toObject();

  if(!j_server.contains("coverages"))
  {
    boost::format err_msg("The server %1% has no coverages");
    throw out_of_range_exception()
        << error_description((err_msg % server_uri.toUtf8().data()).str());
  }

  if(!j_server["coverages"].toObject().contains(cv_name))
  {
    boost::format err_msg("The server %1% has no coverage named: %2%");
    throw out_of_range_exception() << error_description(
        (err_msg % server_uri.toUtf8().data() % cv_name.toUtf8().data()).str());
  }

  QJsonObject j_coverage =
      j_server["coverages"].toObject().find(cv_name).value().toObject();

  if(!j_coverage.contains("attributes"))
  {
    boost::format err_msg("The coverage %1% has no attributes.");
    throw out_of_range_exception()
        << error_description((err_msg % cv_name.toUtf8().data()).str());
  }

  QJsonObject j_attributes = j_coverage.find("attributes").value().toObject();

  if(!j_attributes.contains(attribute))
  {
    boost::format err_msg("The coverage %1% has no attribute named: %2%.");
    throw out_of_range_exception() << error_description(
        (err_msg % cv_name.toUtf8().data() % attribute.toUtf8().data()).str());
  }

  return j_attributes.find(attribute).value().toObject();
}
예제 #4
0
 /**
  * Wait for the future to resolve itself
  *
  * @param assert_ok True if error code for future should be asserted
  *                  CASS_OK; false otherwise (default: true)
  */
 void wait(bool assert_ok = true) {
   CassError wait_code = error_code();
   if (assert_ok) {
     ASSERT_EQ(CASS_OK, wait_code)
       << error_description() << ": " << error_message();
   }
 }
예제 #5
0
 /**
  * Wait for the future to resolve itself or timeout after the specified
  * duration
  *
  * @param timeout Timeout (in milliseconds) for the future to resolve
  *                itself
  * @param assert_true True if error code for future should be asserted
  *                    CASS_OK; false otherwise (default: true)
  */
 void wait(cass_duration_t timeout, bool assert_true = true) {
   cass_bool_t timed_out = cass_future_wait_timed(get(), timeout);
   if (assert_true) {
     ASSERT_EQ(cass_true, timed_out)
       << error_description() << ": " << error_message();
   }
 }
예제 #6
0
파일: strerror.c 프로젝트: mariuz/haiku
char *
strerror(int error)
{
	static char unknown[48];
	uint32 i;

	char *description = error_description(error);
	if (description != NULL)
		return description;

	if (error < B_OK) {
		const char *system = "";
		for (i = 0; i < kNumErrorBases; i++) {
			if (kErrorBases[i].base <= error
				&& ((i + 1 < kNumErrorBases && kErrorBases[i + 1].base > error)
					|| i + 1 == kNumErrorBases)) {
				system = kErrorBases[i].name;
				break;
			}
		}
		sprintf(unknown, "Unknown %sError (%d)", system, error);
	} else
		sprintf(unknown, "No Error (%d)", error);

	return unknown;
}
예제 #7
0
void wtss::tl::server_manager::addServer(const QString &server_uri)
{
  QJsonDocument j_doc = loadSettings();
  QJsonObject j_object = j_doc.object();

  QJsonObject j_servers = j_object.find("servers").value().toObject();

  if(!j_servers.contains(server_uri))
  {
    QJsonObject j_coverages;
    QJsonObject j_server;

    wtss::cxx::client remote(server_uri.toStdString());
    try
    {
      std::vector<std::string> result = remote.list_coverages();

      for(std::string cv_name : result)
      {
        wtss::cxx::geoarray_t g_array = remote.describe_coverage(cv_name);

        QJsonObject j_attributes;
        QJsonObject j_coverage;

        for(wtss::cxx::attribute_t attribute : g_array.attributes)
        {
          QJsonObject j_attribute;
          j_attribute["active"] = QJsonValue(false);
          j_attribute["scale_factor"] = attribute.scale_factor;
          j_attribute["missing_value"] = attribute.missing_value;
          j_attributes[QString::fromStdString(attribute.name)] = j_attribute;
        }
        j_coverage["active"] = QJsonValue(false);
        j_coverage["attributes"] = j_attributes;
        j_coverages[QString::fromStdString(cv_name)] = j_coverage;
      }

      j_server["active"] = QJsonValue(false);
      j_server["coverages"] = j_coverages;
      j_servers[server_uri] = j_server;

      j_object["servers"] = j_servers;
      j_doc.setObject(j_object);
      saveSettings(j_doc);
    }
    catch(const std::exception &e)
    {
      boost::format err_msg(
          "The server %1% could not be added.\n"
          "Due to the following error: %2%");

      throw exception() << error_description(
          (err_msg % server_uri.toUtf8().data() % e.what()).str());
    }
  }
}
예제 #8
0
파일: termin.unx.c 프로젝트: nysan/alpine
/*----------------------------------------------------------------------
     This checks whether or not a character			(UNIX)
     is ready to be read, or it times out.

    Args:  time_out --  number of seconds before it will timeout

  Result: Returns a NO_OP_IDLE or a NO_OP_COMMAND if the timeout expires
	  before input is available, or a KEY_RESIZE if a resize event
	  occurs, or READY_TO_READ if input is available before the timeout.
  ----*/
UCS
check_for_timeout(int time_out)
{
    UCS res = NO_OP_COMMAND;

    fflush(stdout);

#if	defined(SIGWINCH) && defined(TIOCGWINSZ)
    if(!winch_occured){
	if(setjmp(winch_state) != 0){
	    winch_occured = 1;
	    ready_for_winch = 0;

	    /*
	     * Need to unblock signal after longjmp from handler, because
	     * signal is normally unblocked upon routine exit from the handler.
	     */
	    our_sigunblock(SIGWINCH);
	}
	else
	  ready_for_winch = 1;
    }

    if(winch_occured){
	winch_occured = ready_for_winch = 0;
	fix_windsize(ps_global);
	return(KEY_RESIZE);
    }
#endif /* SIGWINCH */

    switch(res = input_ready(time_out)){
      case BAIL_OUT:
	read_bail();			/* non-tragic exit */
	/* NO RETURN */

      case PANIC_NOW:
	panic1("Select error: %s\n", error_description(errno));
	/* NO RETURN */

      case READ_INTR:
	res = NO_OP_COMMAND;
	/* fall through */

      case NO_OP_IDLE:
      case NO_OP_COMMAND:
      case READY_TO_READ:
#if	defined(SIGWINCH) && defined(TIOCGWINSZ)
	ready_for_winch = 0;
#endif
	return(res);
    }

    /* not reachable */
    return(res);
}
예제 #9
0
파일: strerror.c 프로젝트: mariuz/haiku
int
strerror_r(int error, char *buffer, size_t bufferSize)
{
	char *description = error_description(error);
	if (description == NULL)
		return EINVAL;

	strlcpy(buffer, description, bufferSize);
	return 0;
		// TODO: could return ERANGE if buffer is too small
}
예제 #10
0
파일: init.c 프로젝트: RsrchBoy/dpkg-alpine
/*----------------------------------------------------------------------
    Make sure the alpine folders directory exists, with proper folders

   Args: ps -- alpine structure to get mail directory and contexts from

  Result: returns 0 if it exists or it is created and all is well
                  1 if it is missing and can't be created.
  ----*/
int
init_mail_dir(struct pine *ps)
{

/* MAIL_LIST: can we use imap4 CREATE? */
    /*
     * We don't really care if mail_dir exists if it isn't 
     * part of the first folder collection specified.  If this
     * is the case, it must have been created external to us, so
     * just move one...
     */
    if(ps->VAR_FOLDER_SPEC && ps->VAR_FOLDER_SPEC[0]){
	char *p  = context_string(ps->VAR_FOLDER_SPEC[0]);
	int   rv = strncmp(p, ps->VAR_MAIL_DIRECTORY,
			   strlen(ps->VAR_MAIL_DIRECTORY));
	fs_give((void **)&p);
	if(rv)
	  return(0);
    }

    switch(is_writable_dir(ps->folders_dir)){
      case 0:
        /* --- all is well --- */
	return(0);

      case 1:
	snprintf(tmp_20k_buf, SIZEOF_20KBUF, init_md_exists, ps->folders_dir);
	display_init_err(tmp_20k_buf, 1);
	return(-1);

      case 2:
	snprintf(tmp_20k_buf, SIZEOF_20KBUF, init_md_file, ps->folders_dir);
	display_init_err(tmp_20k_buf, 1);
	return(-1);

      case 3:
	snprintf(tmp_20k_buf, SIZEOF_20KBUF, init_md_create, ps->folders_dir);
	display_init_err(tmp_20k_buf, 0);
#ifndef	_WINDOWS
    	sleep(4);
#endif
        if(create_mail_dir(ps->folders_dir) < 0){
            snprintf(tmp_20k_buf, SIZEOF_20KBUF, "Error creating subdirectory \"%s\" : %s",
		    ps->folders_dir, error_description(errno));
	    display_init_err(tmp_20k_buf, 1);
            return(-1);
        }
    }

    return(0);
}
예제 #11
0
파일: wtss.cpp 프로젝트: e-sensing/wtss.cxx
std::vector<std::string> wtss::cxx::client::list_coverages() const
{

  rapidjson::Document doc;
  doc.Parse<0>(wtss::cxx::request(
    wtss::cxx::client::server_uri + "/list_coverages").c_str());

  if (doc.HasParseError())
  {
    boost::format err_msg("Error parsing requested document '%1%/list_coverages: %2%.");

    throw parse_error() << error_description(
      (err_msg % server_uri %doc.GetParseError()).str());
  }

  if (!doc.IsObject())
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a object!");

  if (!doc.HasMember("coverages"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"coverages\"!");

  const rapidjson::Value& j_coverages = doc["coverages"];

  if (!j_coverages.IsArray())
    throw parse_error() << error_description(
        "Invalid JSON document: member named \"coverages\" must be an array!");

  std::vector<std::string> result;

  for (rapidjson::Value::ConstValueIterator itr = j_coverages.Begin();
       itr != j_coverages.End(); ++itr)
    result.push_back(itr->GetString());

  return result;
}
예제 #12
0
파일: utils.hpp 프로젝트: raphaelrpl/tws
    /*!
      \exception tws::parser_error If a parser error occurs during decomposition of query string.
     */
    inline query_string_t expand(const std::string& query_str)
    {
      query_string_t result;

      boost::char_separator<char> kvp_sep("&");

      boost::tokenizer<boost::char_separator<char> > key_value_pairs(query_str, kvp_sep);

      boost::tokenizer<boost::char_separator<char> >::iterator ikv_pair = key_value_pairs.begin();

      while(ikv_pair != key_value_pairs.end())
      {
        std::string kv = *ikv_pair;

        boost::char_separator<char> kv_sep("=");

        boost::tokenizer<boost::char_separator<char> > key_value_pair(kv, kv_sep);

        boost::tokenizer<boost::char_separator<char> >::iterator ikv = key_value_pair.begin();

        if(ikv == key_value_pair.end())
          throw tws::parser_error() << tws::error_description("invalid key-value pair format in query string!");

        std::string k = *ikv;

        ++ikv;

        if(ikv == key_value_pair.end())
          throw tws::parser_error() << error_description("invalid key-value pair format in query string!");

        std::string v = *ikv;

        //std::string decoded_k;
        //std::string decoded_v;

        //boost::network::uri::decode(k.begin(), k.end(), std::back_inserter(decoded_k));
        //boost::network::uri::decode(v.begin(), v.end(), std::back_inserter(decoded_v));

        //result[decoded_k] = decoded_v;
        result[k] = v;

        ++ikv_pair;
      }

      return result;
    }
예제 #13
0
파일: signal.c 프로젝트: ctubio/alpine
/*----------------------------------------------------------------------
    Return all signal handling back to normal
  ----------------------------------------------------------------------*/
void
end_signals(int blockem)
{
#ifdef	_WINDOWS

    signal(SIGHUP,  blockem ? SIG_IGN : SIG_DFL);

#else
#ifndef	SIG_ERR
#define	SIG_ERR	(RETSIGTYPE (*)())-1
#endif

    dprint((5, "end_signals(%d)\n", blockem));
    if(signal(SIGILL,  blockem ? SIG_IGN : SIG_DFL) == SIG_ERR) {
        fprintf(stderr, "Error resetting signals: %s\n",
                error_description(errno));
        exit(-1);
    }

    signal(SIGTRAP, blockem ? SIG_IGN : SIG_DFL);
#ifdef	SIGEMT
    signal(SIGEMT,  blockem ? SIG_IGN : SIG_DFL);
#endif
    signal(SIGBUS,  blockem ? SIG_IGN : SIG_DFL);
    signal(SIGSEGV, blockem ? SIG_IGN : SIG_DFL);
    signal(SIGSYS,  blockem ? SIG_IGN : SIG_DFL);
#if	defined(SIGWINCH) && defined(TIOCGWINSZ)
    signal(SIGWINCH, blockem ? SIG_IGN : SIG_DFL);
#endif
    signal(SIGQUIT, blockem ? SIG_IGN : SIG_DFL);
#ifdef SIGTSTP
    signal(SIGTSTP, blockem ? SIG_IGN : SIG_DFL);
#endif /* SIGTSTP */
    signal(SIGHUP,  blockem ? SIG_IGN : SIG_DFL);
    signal(SIGTERM, blockem ? SIG_IGN : SIG_DFL);
    signal(SIGINT,  blockem ? SIG_IGN : SIG_DFL);

#endif	/* !_WINDOWS */
}
예제 #14
0
파일: wtss.cpp 프로젝트: e-sensing/wtss.cxx
wtss::cxx::geoarray_t wtss::cxx::client::describe_coverage(
    const std::string& cv_name) const
{


  std::string query_string("/describe_coverage?name=" + cv_name);
  rapidjson::Document doc;
  doc.Parse<0>(wtss::cxx::request(
    wtss::cxx::client::server_uri + query_string).c_str());

  if (doc.HasParseError())
  {
    boost::format err_msg("Error parsing requested document '%1%%2%': %3%.");

    throw parse_error() << error_description(
      (err_msg % server_uri % query_string %doc.GetParseError()).str());
  }

  if (!doc.IsObject())
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a object!");

  wtss::cxx::geoarray_t result;

  if (!doc.HasMember("name"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"coverage\"!");

  result.name = doc["name"].GetString();

  if (!doc.HasMember("description"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"description\"!");

  result.description = doc["description"].GetString();

  if (!doc.HasMember("detail"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"detail\"!");

  result.detail = doc["detail"].GetString();

  if (!doc.HasMember("dimensions"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"dimensions\"!");

  const rapidjson::Value& j_dimensions = doc["dimensions"];

  if (!doc.HasMember("attributes"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"attributes\"!");

  const rapidjson::Value& j_attributes = doc["attributes"];

  if (!j_dimensions.IsArray())
    throw parse_error() << error_description(
        "Invalid JSON document: member named \"dimensions\" must be an array!");

  if (!j_attributes.IsArray())
    throw parse_error() << error_description(
        "Invalid JSON document: member named \"attributes\" must be an array!");

  for (rapidjson::Value::ConstValueIterator itr = j_dimensions.Begin();
       itr != j_dimensions.End(); ++itr)
  {
    wtss::cxx::dimension_t dimension;

    dimension.name = (*itr)["name"].GetString();
    dimension.description = (*itr)["description"].GetString();
    dimension.max_idx = (*itr)["max_idx"].GetInt64();
    dimension.min_idx = (*itr)["min_idx"].GetInt64();

    result.dimensions.push_back(dimension);
  }

  for (rapidjson::Value::ConstValueIterator itr = j_attributes.Begin();
       itr != j_attributes.End(); ++itr)
  {
    wtss::cxx::attribute_t attribute;

    attribute.name = (*itr)["name"].GetString();
    attribute.description = (*itr)["description"].GetString();
    attribute.scale_factor = (*itr)["scale_factor"].GetDouble();
    attribute.missing_value = (*itr)["missing_value"].GetDouble();
    attribute.datatype =
        wtss::cxx::datatype_t::from_string((*itr)["datatype"].GetString());
    attribute.valid_range.max_val = (*itr)["valid_range"]["max"].GetDouble();
    attribute.valid_range.min_val = (*itr)["valid_range"]["min"].GetDouble();

    result.attributes.push_back(attribute);
  }

  const rapidjson::Value& j_geo_extent = doc["geo_extent"];

  wtss::cxx::spatial_extent_t spatial_extent;

  spatial_extent.extent.xmin =
      j_geo_extent["spatial"]["extent"]["xmin"].GetDouble();
  spatial_extent.extent.xmax =
      j_geo_extent["spatial"]["extent"]["xmax"].GetDouble();
  spatial_extent.extent.ymin =
      j_geo_extent["spatial"]["extent"]["ymin"].GetDouble();
  spatial_extent.extent.ymax =
      j_geo_extent["spatial"]["extent"]["ymax"].GetDouble();
  spatial_extent.resolution.x =
      j_geo_extent["spatial"]["resolution"]["x"].GetDouble();
  spatial_extent.resolution.y =
      j_geo_extent["spatial"]["resolution"]["y"].GetDouble();

  result.geo_extent.spatial = spatial_extent;

  wtss::cxx::temporal_extent_t temporal_extent;

  temporal_extent.resolution =
      j_geo_extent["temporal"]["resolution"].GetInt64();
  temporal_extent.time_interval.start =
      j_geo_extent["temporal"]["start"].GetString();
  temporal_extent.time_interval.end =
      j_geo_extent["temporal"]["end"].GetString();
  temporal_extent.unit = wtss::cxx::unit_t::from_string(
      j_geo_extent["temporal"]["unit"].GetString());

  result.geo_extent.temporal = temporal_extent;

  return result;
}
예제 #15
0
파일: wtss.cpp 프로젝트: e-sensing/wtss.cxx
wtss::cxx::timeseries_query_result_t wtss::cxx::client::time_series(
    const timeseries_query_t& query) const
{
  timeseries_query_result_t result;
  queried_attribute_t attribute;
  std::string attributes;
  attributes =
      std::accumulate(query.attributes.begin(), query.attributes.end(), attributes,
                 [](const std::string& a, const std::string& b) -> std::string {
                   return a.empty() ? b : a + "," + b;
                 });

  std::ostringstream strs;
  strs << query.latitude;
  std::string latitude = strs.str();
  strs.str("");
  strs << query.longitude;
  std::string longitude = strs.str();

  std::string query_string = "/time_series?coverage=" + query.coverage_name +
                             "&attributes=" + attributes + "&longitude=" +
                             longitude + "&latitude=" +latitude;

  result.coverage.name = query.coverage_name;
  result.query = query;

  if (!query.start_date.empty())
    query_string.append("&start=" + query.start_date);

  if (!query.end_date.empty()) query_string.append("&end=" + query.start_date);

  rapidjson::Document doc;
  doc.Parse<0>(wtss::cxx::request(
      wtss::cxx::client::server_uri + query_string).c_str());

  if (doc.HasParseError())
  {
    boost::format err_msg("Error parsing requested document '%1%%2%': %3%.");

    throw parse_error() << error_description(
      (err_msg % server_uri % query_string %doc.GetParseError()).str());
  }

  if (!doc.HasMember("result"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"result\"!");
  

  const rapidjson::Value& j_result = doc["result"];

  if (!j_result.HasMember("attributes"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"attributes\"!");

  const rapidjson::Value& j_attributes = j_result["attributes"];

  for (rapidjson::Value::ConstValueIterator itr = j_attributes.Begin();
       itr != j_attributes.End(); ++itr)
  {
    attribute.name = (*itr)["attribute"].GetString();
    attribute.values.clear();
    if (!(*itr)["values"].IsNull())
      if ((*itr)["values"].IsArray())
        for (rapidjson::Value::ConstValueIterator itr_v =
                 (*itr)["values"].Begin();
             itr_v != (*itr)["values"].End(); ++itr_v)
          attribute.values.push_back(itr_v->GetDouble());

    result.coverage.queried_attributes.push_back(attribute);
  }

  if (!j_result.HasMember("timeline"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"timeline\"!");

  const rapidjson::Value& j_timeline = j_result["timeline"];

  if (!j_timeline.IsArray())
    throw parse_error() << error_description(
        "Invalid JSON document: member named \"timeline\" must be an array!");

  for (rapidjson::Value::ConstValueIterator itr = j_timeline.Begin();
       itr != j_timeline.End(); ++itr)
  {
    const rapidjson::Value& j_date = (*itr);
    std::vector<std::string> date_split;
    std::string timeline = j_date.GetString();
    std::string delimiter = "-";
    size_t pos = 0;
    std::string token;
    while ((pos = timeline.find(delimiter)) != std::string::npos)
    {
      token = timeline.substr(0, pos);
      date_split.push_back(token);
      timeline.erase(0, pos + delimiter.length());
    }
    date_split.push_back(timeline);
    date d;

    if(date_split.size() > 0) d.year = std::stoi(date_split[0]);
    if(date_split.size() > 1) d.month = std::stoi(date_split[1]);
    if(date_split.size() > 2) d.day = std::stoi(date_split[2]);

    result.coverage.timeline.push_back(d);
  }

  return result;
}
예제 #16
0
파일: ldap.c 프로젝트: RsrchBoy/dpkg-alpine
/*
 * Do an LDAP lookup to the server described in the info argument.
 *
 * Args      info -- LDAP info for server.
 *         string -- String to lookup.
 *           cust -- Possible custom filter description.
 *         wp_err -- We set this is we get a white pages error.
 *  name_in_error -- Caller sets this if they want us to include the server
 *                   name in error messages.
 *
 * Returns  Results of lookup, NULL if lookup failed.
 */
LDAP_SERV_RES_S *
ldap_lookup(LDAP_SERV_S *info, char *string, CUSTOM_FILT_S *cust,
	    WP_ERR_S *wp_err, int name_in_error)
{
    char     ebuf[900];
    char     buf[900];
    char    *serv, *base, *serv_errstr;
    char    *mailattr, *snattr, *gnattr, *cnattr;
    int      we_cancel = 0, we_turned_on = 0;
    LDAP_SERV_RES_S *serv_res = NULL;
    LDAP *ld;
    long  pwdtrial = 0L;
    int   ld_errnum;
    char *ld_errstr;


    if(!info)
      return(serv_res);

    serv = cpystr((info->serv && *info->serv) ? info->serv : "?");

    if(name_in_error)
      snprintf(ebuf, sizeof(ebuf), " (%s)",
	      (info->nick && *info->nick) ? info->nick : serv);
    else
      ebuf[0] = '\0';

    serv_errstr = cpystr(ebuf);
    base = cpystr(info->base ? info->base : "");

    if(info->port < 0)
      info->port = LDAP_PORT;

    if(info->type < 0)
      info->type = DEF_LDAP_TYPE;

    if(info->srch < 0)
      info->srch = DEF_LDAP_SRCH;
	
    if(info->time < 0)
      info->time = DEF_LDAP_TIME;

    if(info->size < 0)
      info->size = DEF_LDAP_SIZE;

    if(info->scope < 0)
      info->scope = DEF_LDAP_SCOPE;

    mailattr = (info->mailattr && info->mailattr[0]) ? info->mailattr
						     : DEF_LDAP_MAILATTR;
    snattr = (info->snattr && info->snattr[0]) ? info->snattr
						     : DEF_LDAP_SNATTR;
    gnattr = (info->gnattr && info->gnattr[0]) ? info->gnattr
						     : DEF_LDAP_GNATTR;
    cnattr = (info->cnattr && info->cnattr[0]) ? info->cnattr
						     : DEF_LDAP_CNATTR;

    /*
     * We may want to keep ldap handles open, but at least for
     * now, re-open them every time.
     */

    dprint((3, "ldap_lookup(%s,%d)\n", serv ? serv : "?", info->port));

    snprintf(ebuf, sizeof(ebuf), "Searching%s%s%s on %s",
	    (string && *string) ? " for \"" : "",
	    (string && *string) ? string : "",
	    (string && *string) ? "\"" : "",
	    serv);
    we_turned_on = intr_handling_on();		/* this erases keymenu */
    we_cancel = busy_cue(ebuf, NULL, 0);
    if(wp_err->mangled)
      *(wp_err->mangled) = 1;

#ifdef _SOLARIS_SDK
    if(info->tls || info->tlsmust)
      ldapssl_client_init(NULL, NULL);
    if((ld = ldap_init(serv, info->port)) == NULL)
#else
#if (LDAPAPI >= 11)
    if((ld = ldap_init(serv, info->port)) == NULL)
#else
    if((ld = ldap_open(serv, info->port)) == NULL)
#endif
#endif
    {
      /* TRANSLATORS: All of the three args together are an error message */
      snprintf(ebuf, sizeof(ebuf), _("Access to LDAP server failed: %s%s(%s)"),
	      errno ? error_description(errno) : "",
	      errno ? " " : "",
	      serv);
      wp_err->wp_err_occurred = 1;
      if(wp_err->error)
	fs_give((void **)&wp_err->error);

      wp_err->error = cpystr(ebuf);
      if(we_cancel)
        cancel_busy_cue(-1);

      q_status_message(SM_ORDER, 3, 5, wp_err->error);
      display_message('x');
      dprint((2, "%s\n", ebuf));
    }
    else if(!ps_global->intr_pending){
      int proto = 3, tlsmustbail = 0;
      char pwd[NETMAXPASSWD], user[NETMAXUSER];
      char *passwd = NULL;
      char hostbuf[1024];
      NETMBX mb;
#ifndef _WINDOWS
      int rc;
#endif

      memset(&mb, 0, sizeof(mb));

#ifdef _SOLARIS_SDK
      if(info->tls || info->tlsmust)
	rc = ldapssl_install_routines(ld);
#endif

      if(ldap_v3_is_supported(ld) &&
	 our_ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &proto) == 0){
	dprint((5, "ldap: using version 3 protocol\n"));
      }

      /*
       * If we don't set RESTART then the select() waiting for the answer
       * in libldap will be interrupted and stopped by our busy_cue.
       */
      our_ldap_set_option(ld, LDAP_OPT_RESTART, LDAP_OPT_ON);

      /*
       * If we need to authenticate, get the password. We are not
       * supporting SASL authentication, just LDAP simple.
       */
      if(info->binddn && info->binddn[0]){
	  char pmt[500];
	  char *space;

	  snprintf(hostbuf, sizeof(hostbuf), "{%s}dummy", info->serv ? info->serv : "?");

	  /*
	   * We don't handle multiple space-delimited hosts well.
	   * We don't know which we're asking for a password for.
	   * We're not connected yet so we can't know.
	   */
	  if((space=strindex(hostbuf, ' ')) != NULL)
	    *space = '\0';

	  mail_valid_net_parse_work(hostbuf, &mb, "ldap");
	  mb.port = info->port;
	  mb.tlsflag = (info->tls || info->tlsmust) ? 1 : 0;

try_password_again:

	  if(mb.tlsflag
	     && (pwdtrial > 0 || 
#ifndef _WINDOWS
#ifdef _SOLARIS_SDK
		 (rc == LDAP_SUCCESS)
#else /* !_SOLARIS_SDK */
		 ((rc=ldap_start_tls_s(ld, NULL, NULL)) == LDAP_SUCCESS)
#endif /* !_SOLARIS_SDK */
#else /* _WINDOWS */
		 0  /* TODO: find a way to do this in Windows */
#endif /* _WINDOWS */
		 ))
	    mb.tlsflag = 1;
	  else
	    mb.tlsflag = 0;

	  if((info->tls || info->tlsmust) && !mb.tlsflag){
	    q_status_message(SM_ORDER, 3, 5, "Not able to start TLS encryption for LDAP server");
	    if(info->tlsmust)
	      tlsmustbail++;
	  }

	  if(!tlsmustbail){
	      snprintf(pmt, sizeof(pmt), "  %s", (info->nick && *info->nick) ? info->nick : serv);
	      mm_login_work(&mb, user, pwd, pwdtrial, pmt, info->binddn);
	      if(pwd && pwd[0])
		passwd = pwd;
	  }
      }


      /*
       * LDAPv2 requires the bind. v3 doesn't require it but we want
       * to tell the server we're v3 if the server supports v3, and if the
       * server doesn't support v3 the bind is required.
       */
      if(tlsmustbail || ldap_simple_bind_s(ld, info->binddn, passwd) != LDAP_SUCCESS){
	wp_err->wp_err_occurred = 1;

	ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr);

        if(!tlsmustbail && info->binddn && info->binddn[0] && pwdtrial < 2L
	   && ld_errnum == LDAP_INVALID_CREDENTIALS){
	  pwdtrial++;
          q_status_message(SM_ORDER, 3, 5, _("Invalid password"));
	  goto try_password_again;
	}

	snprintf(ebuf, sizeof(ebuf), _("LDAP server failed: %s%s%s%s"),
		ldap_err2string(ld_errnum),
		serv_errstr,
		(ld_errstr && *ld_errstr) ? ": " : "",
		(ld_errstr && *ld_errstr) ? ld_errstr : "");

        if(wp_err->error)
	  fs_give((void **)&wp_err->error);

        if(we_cancel)
          cancel_busy_cue(-1);

	ldap_unbind(ld);
        wp_err->error = cpystr(ebuf);
        q_status_message(SM_ORDER, 3, 5, wp_err->error);
        display_message('x');
	dprint((2, "%s\n", ebuf));
      }
      else if(!ps_global->intr_pending){
	int          srch_res, args, slen, flen;
#define TEMPLATELEN 512
	char         filt_template[TEMPLATELEN + 1];
	char         filt_format[2*TEMPLATELEN + 1];
	char         filter[2*TEMPLATELEN + 1];
	char         scp[2*TEMPLATELEN + 1];
	char        *p, *q;
	LDAPMessage *res = NULL;
	int intr_happened = 0;
	int tl;

	tl = (info->time == 0) ? info->time : info->time + 10;

	our_ldap_set_option(ld, LDAP_OPT_TIMELIMIT, &tl);
	our_ldap_set_option(ld, LDAP_OPT_SIZELIMIT, &info->size);

	/*
	 * If a custom filter has been passed in and it doesn't include a
	 * request to combine it with the configured filter, then replace
	 * any configured filter with the passed in filter.
	 */
	if(cust && cust->filt && !cust->combine){
	    if(info->cust)
	      fs_give((void **)&info->cust);
	    
	    info->cust = cpystr(cust->filt);
	}

	if(info->cust && *info->cust){	/* use custom filter if present */
	    strncpy(filt_template, info->cust, sizeof(filt_template));
	    filt_template[sizeof(filt_template)-1] = '\0';
	}
	else{				/* else use configured filter */
	    switch(info->type){
	      case LDAP_TYPE_SUR:
		snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", snattr);
		break;
	      case LDAP_TYPE_GIVEN:
		snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", gnattr);
		break;
	      case LDAP_TYPE_EMAIL:
		snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", mailattr);
		break;
	      case LDAP_TYPE_CN_EMAIL:
		snprintf(filt_template, sizeof(filt_template), "(|(%s=%%s)(%s=%%s))", cnattr,
			mailattr);
		break;
	      case LDAP_TYPE_SUR_GIVEN:
		snprintf(filt_template, sizeof(filt_template), "(|(%s=%%s)(%s=%%s))",
			snattr, gnattr);
		break;
	      case LDAP_TYPE_SEVERAL:
		snprintf(filt_template, sizeof(filt_template),
			"(|(%s=%%s)(%s=%%s)(%s=%%s)(%s=%%s))",
			cnattr, mailattr, snattr, gnattr);
		break;
	      default:
	      case LDAP_TYPE_CN:
		snprintf(filt_template, sizeof(filt_template), "(%s=%%s)", cnattr);
		break;
	    }
	}

	/* just copy if custom */
	if(info->cust && *info->cust)
	  info->srch = LDAP_SRCH_EQUALS;

	p = filt_template;
	q = filt_format;
	memset((void *)filt_format, 0, sizeof(filt_format));
	args = 0;
	while(*p && (q - filt_format) + 4 < sizeof(filt_format)){
	    if(*p == '%' && *(p+1) == 's'){
		args++;
		switch(info->srch){
		  /* Exact match */
		  case LDAP_SRCH_EQUALS:
		    *q++ = *p++;
		    *q++ = *p++;
		    break;

		  /* Append wildcard after %s */
		  case LDAP_SRCH_BEGINS:
		    *q++ = *p++;
		    *q++ = *p++;
		    *q++ = '*';
		    break;

		  /* Insert wildcard before %s */
		  case LDAP_SRCH_ENDS:
		    *q++ = '*';
		    *q++ = *p++;
		    *q++ = *p++;
		    break;

		  /* Put wildcard before and after %s */
		  default:
		  case LDAP_SRCH_CONTAINS:
		    *q++ = '*';
		    *q++ = *p++;
		    *q++ = *p++;
		    *q++ = '*';
		    break;
		}
	    }
	    else
	      *q++ = *p++;
	}

	if(q - filt_format < sizeof(filt_format))
	  *q = '\0';

	filt_format[sizeof(filt_format)-1] = '\0';

	/*
	 * If combine is lit we put the custom filter and the filt_format
	 * filter and combine them with an &.
	 */
	if(cust && cust->filt && cust->combine){
	    char *combined;
	    size_t l;

	    l = strlen(filt_format) + strlen(cust->filt) + 3;
	    combined = (char *) fs_get((l+1) * sizeof(char));
	    snprintf(combined, l+1, "(&%s%s)", cust->filt, filt_format);
	    strncpy(filt_format, combined, sizeof(filt_format));
	    filt_format[sizeof(filt_format)-1] = '\0';
	    fs_give((void **) &combined);
	}

	/*
	 * Ad hoc attempt to make "Steve Hubert" match
	 * Steven Hubert but not Steven Shubert.
	 * We replace a <SPACE> with * <SPACE> (not * <SPACE> *).
	 */
	memset((void *)scp, 0, sizeof(scp));
	if(info->nosub)
	  strncpy(scp, string, sizeof(scp));
	else{
	    p = string;
	    q = scp;
	    while(*p && (q - scp) + 1 < sizeof(scp)){
		if(*p == SPACE && *(p+1) != SPACE){
		    *q++ = '*';
		    *q++ = *p++;
		}
		else
		  *q++ = *p++;
	    }
	}

	scp[sizeof(scp)-1] = '\0';

	slen = strlen(scp);
	flen = strlen(filt_format);
	/* truncate string if it will overflow filter */
	if(args*slen + flen - 2*args > sizeof(filter)-1)
	  scp[(sizeof(filter)-1 - flen)/args] = '\0';

	/*
	 * Replace %s's with scp.
	 */
	switch(args){
	  case 0:
	    snprintf(filter, sizeof(filter), "%s", filt_format);
	    break;
	  case 1:
	    snprintf(filter, sizeof(filter), filt_format, scp);
	    break;
	  case 2:
	    snprintf(filter, sizeof(filter), filt_format, scp, scp);
	    break;
	  case 3:
	    snprintf(filter, sizeof(filter), filt_format, scp, scp, scp);
	    break;
	  case 4:
	    snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp);
	    break;
	  case 5:
	    snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp);
	    break;
	  case 6:
	    snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp);
	    break;
	  case 7:
	    snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp);
	    break;
	  case 8:
	    snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp,
		    scp);
	    break;
	  case 9:
	    snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp,
		    scp, scp);
	    break;
	  case 10:
	  default:
	    snprintf(filter, sizeof(filter), filt_format, scp, scp, scp, scp, scp, scp, scp,
		    scp, scp, scp);
	    break;
	}

	/* replace double *'s with single *'s in filter */
	for(p = q = filter; *p; p++)
	  if(*p != '*' || p == filter || *(p-1) != '*')
	    *q++ = *p;

	*q = '\0';

	(void) removing_double_quotes(base);
	dprint((5, "about to ldap_search(\"%s\", %s)\n",
	       base ? base : "?", filter ? filter : "?"));
        if(ps_global->intr_pending)
	  srch_res = LDAP_PROTOCOL_ERROR;
	else{
	  int msgid;
	  time_t start_time;

	  start_time = time((time_t *)0);

	  dprint((6, "ldap_lookup: calling ldap_search\n"));
	  msgid = ldap_search(ld, base, info->scope, filter, NULL, 0);

	  if(msgid == -1)
	    srch_res = our_ldap_get_lderrno(ld, NULL, NULL);
	  else{
	    int lres;
	    /*
	     * Warning: struct timeval is not portable. However, since it is
	     * part of LDAP api it must be portable to all platforms LDAP
	     * has been ported to.
	     */
	    struct timeval t;

	    t.tv_sec  = 1; t.tv_usec = 0;
	      
	    do {
	      if(ps_global->intr_pending)
		intr_happened = 1;

	      dprint((6, "ldap_result(id=%d): ", msgid));
	      if((lres=ldap_result(ld, msgid, LDAP_MSG_ALL, &t, &res)) == -1){
	        /* error */
		srch_res = our_ldap_get_lderrno(ld, NULL, NULL);
	        dprint((6, "error (-1 returned): ld_errno=%d\n",
			   srch_res));
	      }
	      else if(lres == 0){  /* timeout, no results available */
		if(intr_happened){
		  ldap_abandon(ld, msgid);
		  srch_res = LDAP_PROTOCOL_ERROR;
		  if(our_ldap_get_lderrno(ld, NULL, NULL) == LDAP_SUCCESS)
		    our_ldap_set_lderrno(ld, LDAP_PROTOCOL_ERROR, NULL, NULL);

	          dprint((6, "timeout, intr: srch_res=%d\n",
			     srch_res));
		}
		else if(info->time > 0 &&
			((long)time((time_t *)0) - start_time) > info->time){
		  /* try for partial results */
		  t.tv_sec  = 0; t.tv_usec = 0;
		  lres = ldap_result(ld, msgid, LDAP_MSG_RECEIVED, &t, &res);
		  if(lres > 0 && lres != LDAP_RES_SEARCH_RESULT){
		    srch_res = LDAP_SUCCESS;
		    dprint((6, "partial result: lres=0x%x\n", lres));
		  }
		  else{
		    if(lres == 0)
		      ldap_abandon(ld, msgid);

		    srch_res = LDAP_TIMEOUT;
		    if(our_ldap_get_lderrno(ld, NULL, NULL) == LDAP_SUCCESS)
		      our_ldap_set_lderrno(ld, LDAP_TIMEOUT, NULL, NULL);

	            dprint((6,
			       "timeout, total_time (%d), srch_res=%d\n",
			       info->time, srch_res));
		  }
		}
		else{
	          dprint((6, "timeout\n"));
		}
	      }
	      else{
		srch_res = ldap_result2error(ld, res, 0);
	        dprint((6, "lres=0x%x, srch_res=%d\n", lres,
			   srch_res));
	      }
	    }while(lres == 0 &&
		    !(intr_happened ||
		      (info->time > 0 &&
		       ((long)time((time_t *)0) - start_time) > info->time)));
	  }
	}

	if(intr_happened){
	  wp_exit = 1;
          if(we_cancel)
            cancel_busy_cue(-1);

	  if(wp_err->error)
	    fs_give((void **)&wp_err->error);
	  else{
	    q_status_message(SM_ORDER, 0, 1, "Interrupt");
	    display_message('x');
	    fflush(stdout);
	  }

	  if(res)
	    ldap_msgfree(res);
	  if(ld)
	    ldap_unbind(ld);
	  
	  res = NULL; ld  = NULL;
	}
	else if(srch_res != LDAP_SUCCESS &&
	   srch_res != LDAP_TIMELIMIT_EXCEEDED &&
	   srch_res != LDAP_RESULTS_TOO_LARGE &&
	   srch_res != LDAP_TIMEOUT &&
	   srch_res != LDAP_SIZELIMIT_EXCEEDED){
	  wp_err->wp_err_occurred = 1;

	  ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr);

	  snprintf(ebuf, sizeof(ebuf), _("LDAP search failed: %s%s%s%s"),
		  ldap_err2string(ld_errnum),
		  serv_errstr,
		  (ld_errstr && *ld_errstr) ? ": " : "",
		  (ld_errstr && *ld_errstr) ? ld_errstr : "");

          if(wp_err->error)
	    fs_give((void **)&wp_err->error);

          wp_err->error = cpystr(ebuf);
          if(we_cancel)
            cancel_busy_cue(-1);

          q_status_message(SM_ORDER, 3, 5, wp_err->error);
          display_message('x');
	  dprint((2, "%s\n", ebuf));
	  if(res)
	    ldap_msgfree(res);
	  if(ld)
	    ldap_unbind(ld);
	  
	  res = NULL; ld  = NULL;
	}
	else{
	  int cnt;

	  cnt = ldap_count_entries(ld, res);

	  if(cnt > 0){

	    if(srch_res == LDAP_TIMELIMIT_EXCEEDED ||
	       srch_res == LDAP_RESULTS_TOO_LARGE ||
	       srch_res == LDAP_TIMEOUT ||
	       srch_res == LDAP_SIZELIMIT_EXCEEDED){
	      wp_err->wp_err_occurred = 1;
	      ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr);

	      snprintf(ebuf, sizeof(ebuf), _("LDAP partial results: %s%s%s%s"),
		      ldap_err2string(ld_errnum),
		      serv_errstr,
		      (ld_errstr && *ld_errstr) ? ": " : "",
		      (ld_errstr && *ld_errstr) ? ld_errstr : "");
	      dprint((2, "%s\n", ebuf));
	      if(wp_err->error)
		fs_give((void **)&wp_err->error);

	      wp_err->error = cpystr(ebuf);
	      if(we_cancel)
		cancel_busy_cue(-1);

	      q_status_message(SM_ORDER, 3, 5, wp_err->error);
	      display_message('x');
	    }

	    dprint((5, "Matched %d entries on %s\n",
	           cnt, serv ? serv : "?"));

	    serv_res = (LDAP_SERV_RES_S *)fs_get(sizeof(LDAP_SERV_RES_S));
	    memset((void *)serv_res, 0, sizeof(*serv_res));
	    serv_res->ld   = ld;
	    serv_res->res  = res;
	    serv_res->info_used = copy_ldap_serv_info(info);
	    /* Save by reference? */
	    if(info->ref){
		snprintf(buf, sizeof(buf), "%s:%s", serv, comatose(info->port));
		serv_res->serv = cpystr(buf);
	    }
	    else
	      serv_res->serv = NULL;

	    serv_res->next = NULL;
	  }
	  else{
	    if(srch_res == LDAP_TIMELIMIT_EXCEEDED ||
	       srch_res == LDAP_RESULTS_TOO_LARGE ||
	       srch_res == LDAP_TIMEOUT ||
	       srch_res == LDAP_SIZELIMIT_EXCEEDED){
	      wp_err->wp_err_occurred = 1;
	      wp_err->ldap_errno      = srch_res;

	      ld_errnum = our_ldap_get_lderrno(ld, NULL, &ld_errstr);

	      snprintf(ebuf, sizeof(ebuf), _("LDAP search failed: %s%s%s%s"),
		      ldap_err2string(ld_errnum),
		      serv_errstr,
		      (ld_errstr && *ld_errstr) ? ": " : "",
		      (ld_errstr && *ld_errstr) ? ld_errstr : "");

	      if(wp_err->error)
		fs_give((void **)&wp_err->error);

	      wp_err->error = cpystr(ebuf);
	      if(we_cancel)
		cancel_busy_cue(-1);

	      q_status_message(SM_ORDER, 3, 5, wp_err->error);
	      display_message('x');
	      dprint((2, "%s\n", ebuf));
	    }

	    dprint((5, "Matched 0 entries on %s\n",
		   serv ? serv : "?"));
	    if(res)
	      ldap_msgfree(res);
	    if(ld)
	      ldap_unbind(ld);

	    res = NULL; ld  = NULL;
	  }
	}
      }
    }

    if(we_cancel)
      cancel_busy_cue(-1);

    if(we_turned_on)
      intr_handling_off();

    if(serv)
      fs_give((void **)&serv);
    if(base)
      fs_give((void **)&base);
    if(serv_errstr)
      fs_give((void **)&serv_errstr);

    return(serv_res);
}
예제 #17
0
파일: pipe.c 프로젝트: RsrchBoy/dpkg-alpine
/*----------------------------------------------------------------------
     Spawn a child process and optionally connect read/write pipes to it

  Args: command -- string to hand the shell
	outfile -- address of pointer containing file to receive output
	errfile -- address of pointer containing file to receive error output
	mode -- mode for type of shell, signal protection etc...
  Returns: pointer to alloc'd PIPE_S on success, NULL otherwise

  The outfile is either NULL, a pointer to a NULL value, or a pointer
  to the requested name for the output file.  In the pointer-to-NULL case
  the caller doesn't care about the name, but wants to see the pipe's
  results so we make one up.  It's up to the caller to make sure the
  free storage containing the name is cleaned up.

  Mode bits serve several purposes.
    PIPE_WRITE tells us we need to open a pipe to write the child's
	stdin.
    PIPE_READ tells us we need to open a pipe to read from the child's
	stdout/stderr.  *NOTE*  Having neither of the above set means 
	we're not setting up any pipes, just forking the child and exec'ing
	the command.  Also, this takes precedence over any named outfile.
    PIPE_STDERR means we're to tie the childs stderr to the same place
	stdout is going.  *NOTE* This only makes sense then if PIPE_READ
	or an outfile is provided.  Also, this takes precedence over any
	named errfile.
    PIPE_RESET means we reset the terminal mode to what it was before
	we started pine and then exec the command. In PC-Pine, _RESET
	was a shortcut for just executing a command.  We'll try to pay
	attention to the above flags to make sure we do the right thing.
    PIPE_PROT means to protect the child from the usual nasty signals
	that might cause premature death.  Otherwise, the default signals are
	set so the child can deal with the nasty signals in its own way.
	NOT USED UNDER WINDOWS
    PIPE_NOSHELL means we're to exec the command without the aid of
	a system shell.  *NOTE* This negates the affect of PIPE_USER.
	NOT USED UNDER WINDOWS
    PIPE_USER means we're to try executing the command in the user's
	shell.  Right now we only look in the environment, but that may get
	more sophisticated later.
	NOT USED UNDER WINDOWS
    PIPE_RUNNOW was added for WINDOWS for the case pipe is called to run
        a shell program (like for url viewing).  This is the only option
	where we don't wait for child termination, and is only obeyed if
	PIPE_WRITE and PIPE_READ aren't set
 ----*/
PIPE_S *
open_system_pipe(char *command, char **outfile, char **errfile, int mode,
		 int timeout, void (*pipecb_f)(PIPE_S *, int, void *),
		 void (*piperr_f)(char *))
{
    PIPE_S *syspipe = NULL;
#ifdef	_WINDOWS
    int exit_code = 0;
    char cmdbuf[1024];
    unsigned flags = 0;
#else
    char    shellpath[MAXPATH+1], *shell;
    int     p[2], oparentd = -1, ochildd = -1, iparentd = -1, ichildd = -1;
#endif

#ifdef	_WINDOWS
    if(mode & PIPE_STDERR)
      flags |= MSWIN_EAW_CAPT_STDERR;
    /* 
     * It'll be a lot more difficult to support READing and WRITing.
     * This was never supported, and there don't look to be any cases
     * that set both of these flags anymore for win32.
     *
     * errfile could probably be supported pretty easily
     */

    if(errfile){
	if(piperr_f)
	  (*piperr_f)("Pipe arg not yet supported: Error File");

	return(NULL);
    }


    if((mode & PIPE_RUNNOW)
       && !(mode & (PIPE_WRITE | PIPE_READ | PIPE_STDERR))){
	if(mswin_shell_exec(command, NULL) == 0
	   && (syspipe = (PIPE_S *) malloc(sizeof(PIPE_S))) != NULL){
	    memset(syspipe, 0, sizeof(PIPE_S));
	    return(syspipe);
	}

	return(NULL);
    }

    strncpy(cmdbuf, command, sizeof(cmdbuf));
    cmdbuf[sizeof(cmdbuf)-1] = '\0';

    if((syspipe = (PIPE_S *) malloc(sizeof(PIPE_S))) == NULL)
      return(NULL);

    memset(syspipe, 0, sizeof(PIPE_S));
    syspipe->mode = mode;
    if(!outfile){
	syspipe->deloutfile = 1;
	if(mode & PIPE_READ){
	    syspipe->outfile = temp_nam(NULL, "po");
	    our_unlink(syspipe->outfile);
	}
    }
    else{
	if(!*outfile) /* asked for, but not named? */
	  *outfile = temp_nam(NULL, "po");

	our_unlink(*outfile);
	syspipe->outfile = (char *) malloc((strlen(*outfile)+1)*sizeof(char));
	snprintf(syspipe->outfile, strlen(*outfile)+1, "%s", *outfile);
    }

    if(mode & PIPE_WRITE){
	/*
	 * Create tmp file to write, spawn child in close_pipe
	 * after tmp file's written...
	 */
	syspipe->infile = temp_nam(NULL, "pw");
	syspipe->out.f = our_fopen(syspipe->infile, "wb");
	syspipe->command = (char *) malloc((strlen(cmdbuf)+1)*sizeof(char));
	snprintf(syspipe->command, strlen(cmdbuf)+1, "%s", cmdbuf);
	dprint((1, "pipe write: %s", cmdbuf));
    }
    else if(mode & PIPE_READ){
	/* 
	 * Create a tmp file for command result, exec the command
	 * here into temp file, and return file pointer to it...
	 */
	syspipe->command = (char *) malloc((strlen(cmdbuf)+1)*sizeof(char));
	snprintf(syspipe->command, strlen(cmdbuf)+1, "%s", cmdbuf);
	dprint((1, "pipe read: %s", cmdbuf));
	if(pipe_mswin_exec_wrapper("pipe command", syspipe,
				   flags, pipecb_f, piperr_f)){
	    if(syspipe->outfile){
		free((void *) syspipe->outfile);
		syspipe->outfile = NULL;
	    }

	    zot_pipe(&syspipe);
	}
	else{
	  syspipe->in.f = our_fopen(syspipe->outfile, "rb");
	  syspipe->exit_code = exit_code;
	}
    }
    else{
	/* we just run the command taking outfile into account */
	syspipe->command = (char *) malloc((strlen(cmdbuf)+1)*sizeof(char));
	snprintf(syspipe->command, strlen(cmdbuf)+1, "%s", cmdbuf);
	if(pipe_mswin_exec_wrapper("pipe command", syspipe,
				   flags, pipecb_f, piperr_f)){
	    if(syspipe->outfile){
		free((void *) syspipe->outfile);
		syspipe->outfile = NULL;
	    }

	    zot_pipe(&syspipe);
	}
	else
	  syspipe->exit_code = exit_code;
    }

#else /* !_WINDOWS */

    if((syspipe = (PIPE_S *) malloc(sizeof(PIPE_S))) == NULL)
      return(NULL);

    memset(syspipe, 0, sizeof(PIPE_S));

    syspipe->mode = mode;

    /*
     * If we're not using the shell's command parsing smarts, build
     * argv by hand...
     */
    if(mode & PIPE_NOSHELL){
	char   **ap, *p;
	size_t   n;

	/* parse the arguments into argv */
	for(p = command; *p && isspace((unsigned char)(*p)); p++)
	  ;					/* swallow leading ws */

	if(*p){
	    int l = strlen(p);

	    if((syspipe->args = (char *) malloc((l + 1) * sizeof(char))) != NULL){
		strncpy(syspipe->args, p, l);
		syspipe->args[l] = '\0';
	    }
	    else{
		if(piperr_f)
		  (*piperr_f)(pipe_error_msg("<null>", "execute",
					     "Can't allocate command string"));
		zot_pipe(&syspipe);
		return(NULL);
	    }
	}
	else{
	    if(piperr_f)
	      (*piperr_f)(pipe_error_msg("<null>", "execute",
					 "No command name found"));
	    zot_pipe(&syspipe);
	    return(NULL);
	}

	for(p = syspipe->args, n = 2; *p; p++)	/* count the args */
	  if(isspace((unsigned char)(*p))
	     && *(p+1) && !isspace((unsigned char)(*(p+1))))
	    n++;

	if ((syspipe->argv = ap = (char **)malloc(n * sizeof(char *))) == NULL){
	    zot_pipe(&syspipe);
	    return(NULL);
	}

	memset(syspipe->argv, 0, n * sizeof(char *));

	for(p = syspipe->args; *p; ){		/* collect args */
	    while(*p && isspace((unsigned char)(*p)))
	      *p++ = '\0';

	    *ap++ = (*p) ? p : NULL;
	    while(*p && !isspace((unsigned char)(*p)))
	      p++;
	}

	/* make sure argv[0] exists in $PATH */
	if(can_access_in_path(getenv("PATH"), syspipe->argv[0],
			      EXECUTE_ACCESS) < 0){
	    if(piperr_f)
	      (*piperr_f)(pipe_error_msg(syspipe->argv[0], "access",
					 error_description(errno)));
	    zot_pipe(&syspipe);
	    return(NULL);
	}
    }

    /* fill in any output filenames */
    if(!(mode & PIPE_READ)){
	if(outfile && !*outfile)
	  *outfile = temp_nam(NULL, "pine_p"); /* asked for, but not named? */

	if(errfile && !*errfile)
	  *errfile = temp_nam(NULL, "pine_p"); /* ditto */
    }

    /* create pipes */
    if(mode & (PIPE_WRITE | PIPE_READ)){
	if(mode & PIPE_WRITE){
	    pipe(p);				/* alloc pipe to write child */
	    oparentd = p[STDOUT_FILENO];
	    ichildd  = p[STDIN_FILENO];
	}

	if(mode & PIPE_READ){
	    pipe(p);				/* alloc pipe to read child */
	    iparentd = p[STDIN_FILENO];
	    ochildd  = p[STDOUT_FILENO];
	}
    }

    if(pipecb_f)				/* let caller prep display */
      (*pipecb_f)(syspipe, OSB_PRE_OPEN, NULL);


    if((syspipe->pid = vfork()) == 0){
 	/* reset child's handlers in requested fashion... */
	(void)signal(SIGINT,  (mode & PIPE_PROT) ? SIG_IGN : SIG_DFL);
	(void)signal(SIGQUIT, (mode & PIPE_PROT) ? SIG_IGN : SIG_DFL);
	(void)signal(SIGHUP,  (mode & PIPE_PROT) ? SIG_IGN : SIG_DFL);
#ifdef	SIGCHLD
	(void) signal(SIGCHLD,  SIG_DFL);
#endif

	/* if parent isn't reading, and we have a filename to write */
	if(!(mode & PIPE_READ) && outfile){	/* connect output to file */
	    int output = our_creat(*outfile, 0600);
	    dup2(output, STDOUT_FILENO);
	    if(mode & PIPE_STDERR)
	      dup2(output, STDERR_FILENO);
	    else if(errfile)
	      dup2(our_creat(*errfile, 0600), STDERR_FILENO);
	}

	if(mode & PIPE_WRITE){			/* connect process input */
	    close(oparentd);
	    dup2(ichildd, STDIN_FILENO);	/* tie stdin to pipe */
	    close(ichildd);
	}

	if(mode & PIPE_READ){			/* connect process output */
	    close(iparentd);
	    dup2(ochildd, STDOUT_FILENO);	/* tie std{out,err} to pipe */
	    if(mode & PIPE_STDERR)
	      dup2(ochildd, STDERR_FILENO);
	    else if(errfile)
	      dup2(our_creat(*errfile, 0600), STDERR_FILENO);

	    close(ochildd);
	}

	if(mode & PIPE_NOSHELL){
	    execvp(syspipe->argv[0], syspipe->argv);
	}
	else{
	    if(mode & PIPE_USER){
		char *env, *sh;
		if((env = getenv("SHELL")) && (sh = strrchr(env, '/'))){
		    shell = sh + 1;
		    strncpy(shellpath, env, sizeof(shellpath)-1);
		    shellpath[sizeof(shellpath)-1] = '\0';
		}
		else{
		    shell = "csh";
		    strncpy(shellpath, "/bin/csh", sizeof(shellpath)-1);
		    shellpath[sizeof(shellpath)-1] = '\0';
		}
	    }
	    else{
		shell = "sh";
		strncpy(shellpath, "/bin/sh", sizeof(shellpath)-1);
		shellpath[sizeof(shellpath)-1] = '\0';
	    }

	    execl(shellpath, shell, command ? "-c" : (char *)NULL, fname_to_locale(command), (char *)NULL);
	}

	fprintf(stderr, "Can't exec %s\nReason: %s",
		command, error_description(errno));
	_exit(-1);
    }

    if((child_pid = syspipe->pid) > 0){
	syspipe->isig = signal(SIGINT,  SIG_IGN); /* Reset handlers to make */
	syspipe->qsig = signal(SIGQUIT, SIG_IGN); /* sure we don't come to  */
	syspipe->hsig = signal(SIGHUP,  SIG_IGN); /* a premature end...     */
	if((syspipe->timeout = timeout) != 0){
	    syspipe->alrm      = signal(SIGALRM,  pipe_alarm);
	    syspipe->old_timeo = alarm(timeout);
	}

	if(mode & PIPE_WRITE){
	    close(ichildd);
	    if(mode & PIPE_DESC)
	      syspipe->out.d = oparentd;
	    else
	      syspipe->out.f = fdopen(oparentd, "w");
	}

	if(mode & PIPE_READ){
	    close(ochildd);
	    if(mode & PIPE_DESC)
	      syspipe->in.d = iparentd;
	    else
	      syspipe->in.f = fdopen(iparentd, "r");
	}
    }
    else{
	if(mode & (PIPE_WRITE | PIPE_READ)){
	    if(mode & PIPE_WRITE){
		close(oparentd);
		close(ichildd);
	    }

	    if(mode & PIPE_READ){
		close(iparentd);
		close(ochildd);
	    }
	}

	if(pipecb_f)				/* let caller fixup display */
	  (*pipecb_f)(syspipe, OSB_POST_OPEN, NULL);

	if(outfile && *outfile){
	    our_unlink(*outfile);
	    free((void *) *outfile);
	    *outfile = NULL;
	}

	if(errfile && *errfile){
	    our_unlink(*errfile);
	    free((void *) *errfile);
	    *errfile = NULL;
	}

	if(piperr_f)
	  (*piperr_f)(pipe_error_msg(command, "fork",
				     error_description(errno)));
	zot_pipe(&syspipe);
    }

#endif /* UNIX */

    return(syspipe);
}
예제 #18
0
wtss::cxx::geoarray_t wtss::cxx::client::describe_coverage(
    const std::string& cv_name) const
{


  std::string query_string("/describe_coverage?name=" + cv_name);
  rapidjson::Document doc;
  doc.Parse<0>(wtss::cxx::request(
    wtss::cxx::client::server_uri + query_string).c_str());

  if (doc.HasParseError())
  {
    boost::format err_msg("Error parsing requested document '%1%%2%': %3%.");

    throw parse_error() << error_description(
      (err_msg % server_uri % query_string %doc.GetParseError()).str());
  }

  if (!doc.IsObject())
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a object!");

  wtss::cxx::geoarray_t result;

  if (!doc.HasMember("name"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"coverage\"!");

  result.name = doc["name"].GetString();

  if (!doc.HasMember("description"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"description\"!");

  result.description = doc["description"].GetString();

  if (!doc.HasMember("detail"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"detail\"!");

  result.detail = doc["detail"].GetString();

  if (!doc.HasMember("dimensions"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"dimensions\"!");

  const rapidjson::Value& j_dimensions = doc["dimensions"];

  if (!doc.HasMember("attributes"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"attributes\"!");

  const rapidjson::Value& j_attributes = doc["attributes"];

  if (!j_dimensions.IsObject())
    throw parse_error() << error_description(
        "Invalid JSON document: member named \"dimensions\" must be an object!");

  if (!j_attributes.IsArray())
    throw parse_error() << error_description(
        "Invalid JSON document: member named \"attributes\" must be an array!");

  for (rapidjson::Value::ConstMemberIterator itr = j_dimensions.MemberBegin();
       itr != j_dimensions.MemberEnd(); ++itr)
  {
    wtss::cxx::dimension_t dimension;

    dimension.name = itr->value["name"].GetString();
    dimension.max_idx = itr->value["max_idx"].GetInt64();
    dimension.min_idx = itr->value["min_idx"].GetInt64();

    result.dimensions.push_back(dimension);
  }

  for (rapidjson::Value::ConstValueIterator itr = j_attributes.Begin();
       itr != j_attributes.End(); ++itr)
  {
    wtss::cxx::attribute_t attribute;

    attribute.name = (*itr)["name"].GetString();
    attribute.description = (*itr)["description"].GetString();
    attribute.scale_factor = (*itr)["scale_factor"].GetDouble();
    attribute.missing_value = (*itr)["missing_value"].GetDouble();
    attribute.datatype =
        wtss::cxx::datatype_t::from_string((*itr)["datatype"].GetString());
    attribute.valid_range.max_val = (*itr)["valid_range"]["max"].GetDouble();
    attribute.valid_range.min_val = (*itr)["valid_range"]["min"].GetDouble();

    result.attributes.push_back(attribute);
  }

  wtss::cxx::spatial_extent_t spatial_extent;

  spatial_extent.extent.xmin =
      doc["spatial_extent"]["xmin"].GetDouble();
  spatial_extent.extent.xmax =
       doc["spatial_extent"]["xmax"].GetDouble();
  spatial_extent.extent.ymin =
      doc["spatial_extent"]["ymin"].GetDouble();
  spatial_extent.extent.ymax =
       doc["spatial_extent"]["ymax"].GetDouble();
  spatial_extent.resolution.x =
      doc["spatial_resolution"]["x"].GetDouble();
  spatial_extent.resolution.y =
      doc["spatial_resolution"]["y"].GetDouble();

  result.spatial_extent = spatial_extent;

  if (!doc.HasMember("crs"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"crs\"!");

  result.crs.proj4 = doc["crs"]["proj4"].GetString();
  result.crs.wkt = doc["crs"]["wkt"].GetString();

  if (!doc.HasMember("timeline"))
    throw parse_error() << error_description(
        "Invalid JSON document: expecting a member named \"timeline\"!");

  const rapidjson::Value& j_timeline = doc["timeline"];

  if (!j_timeline.IsArray())
    throw parse_error() << error_description(
        "Invalid JSON document: member named \"timeline\" must be an array!");

  for (rapidjson::Value::ConstValueIterator itr = j_timeline.Begin();
       itr != j_timeline.End(); ++itr)
  {
    const rapidjson::Value& j_date = (*itr);
    std::vector<std::string> date_split;
    std::string timeline = j_date.GetString();
    std::string delimiter = "-";
    size_t pos = 0;
    std::string token;
    while ((pos = timeline.find(delimiter)) != std::string::npos)
    {
      token = timeline.substr(0, pos);
      date_split.push_back(token);
      timeline.erase(0, pos + delimiter.length());
    }
    date_split.push_back(timeline);
    date d;

    if(date_split.size() > 0) d.year = std::stoi(date_split[0]);
    if(date_split.size() > 1) d.month = std::stoi(date_split[1]);
    if(date_split.size() > 2) d.day = std::stoi(date_split[2]);

    result.timeline.push_back(d);
  }

  return result;
}
예제 #19
0
파일: print.c 프로젝트: nysan/alpine
/*----------------------------------------------------------------------
       Open the printer

  Args: desc -- Description of item to print. Should have one trailing blank.

  Return value: < 0 is a failure.
		0 a success.

This does most of the work of popen so we can save the standard output of the
command we execute and send it back to the user.
  ----*/
int
open_printer(char *desc)
{
#ifndef _WINDOWS
    char command[201], prompt[200];
    int  cmd, rc, just_one;
    char *p, *init, *nick;
    char aname[100], wname[100];
    char *printer;
    int	 done = 0, i, lastprinter, cur_printer = 0;
    HelpType help;
    char   **list;
    static ESCKEY_S ekey[] = {
	/* TRANSLATORS: these are command labels for printing screen */
	{'y', 'y', "Y", N_("Yes")},
	{'n', 'n', "N", N_("No")},
	/* TRANSLATORS: go to Previous Printer in list */
	{ctrl('P'), 10, "^P", N_("Prev Printer")},
	{ctrl('N'), 11, "^N", N_("Next Printer")},
	{-2,   0,   NULL, NULL},
	/* TRANSLATORS: use Custom Print command */
	{'c', 'c', "C", N_("CustomPrint")},
	{KEY_UP,    10, "", ""},
	{KEY_DOWN,  11, "", ""},
	{-1, 0, NULL, NULL}};
#define PREV_KEY   2
#define NEXT_KEY   3
#define CUSTOM_KEY 5
#define UP_KEY     6
#define DOWN_KEY   7

    trailer      = NULL;
    init         = NULL;
    nick         = NULL;
    command[sizeof(command)-1] = '\0';

    if(ps_global->VAR_PRINTER == NULL){
        q_status_message(SM_ORDER | SM_DING, 3, 5,
	"No printer has been chosen.  Use SETUP on main menu to make choice.");
	return(-1);
    }

    /* Is there just one print command available? */
    just_one = (ps_global->printer_category!=3&&ps_global->printer_category!=2)
	       || (ps_global->printer_category == 2
		   && !(ps_global->VAR_STANDARD_PRINTER
			&& ps_global->VAR_STANDARD_PRINTER[0]
			&& ps_global->VAR_STANDARD_PRINTER[1]))
	       || (ps_global->printer_category == 3
		   && !(ps_global->VAR_PERSONAL_PRINT_COMMAND
			&& ps_global->VAR_PERSONAL_PRINT_COMMAND[0]
			&& ps_global->VAR_PERSONAL_PRINT_COMMAND[1]));

    if(F_ON(F_CUSTOM_PRINT, ps_global))
      ekey[CUSTOM_KEY].ch = 'c'; /* turn this key on */
    else
      ekey[CUSTOM_KEY].ch = -2;  /* turn this key off */

    if(just_one){
	ekey[PREV_KEY].ch = -2;  /* turn these keys off */
	ekey[NEXT_KEY].ch = -2;
	ekey[UP_KEY].ch   = -2;
	ekey[DOWN_KEY].ch = -2;
    }
    else{
	ekey[PREV_KEY].ch = ctrl('P'); /* turn these keys on */
	ekey[NEXT_KEY].ch = ctrl('N');
	ekey[UP_KEY].ch   = KEY_UP;
	ekey[DOWN_KEY].ch = KEY_DOWN;
	/*
	 * count how many printers in list and find the default in the list
	 */
	if(ps_global->printer_category == 2)
	  list = ps_global->VAR_STANDARD_PRINTER;
	else
	  list = ps_global->VAR_PERSONAL_PRINT_COMMAND;

	for(i = 0; list[i]; i++)
	  if(strcmp(ps_global->VAR_PRINTER, list[i]) == 0)
	    cur_printer = i;
	
	lastprinter = i - 1;
    }

    help = NO_HELP;
    ps_global->mangled_footer = 1;

    while(!done){
	if(init)
	  fs_give((void **)&init);

	if(trailer)
	  fs_give((void **)&trailer);

	if(just_one)
	  printer = ps_global->VAR_PRINTER;
	else
	  printer = list[cur_printer];

	parse_printer(printer, &nick, &p, &init, &trailer, NULL, NULL);
	strncpy(command, p, sizeof(command)-1);
	command[sizeof(command)-1] = '\0';
	fs_give((void **)&p);
	/* TRANSLATORS: Print something1 using something2.
	   For example, Print configuration using printer three. */
	snprintf(prompt, sizeof(prompt), _("Print %s using \"%s\" ? "),
		desc ? desc : "",
		*nick ? nick : command);
	prompt[sizeof(prompt)-1] = '\0';

	fs_give((void **)&nick);
	
	cmd = radio_buttons(prompt, -FOOTER_ROWS(ps_global),
				 ekey, 'y', 'x', help, RB_NORM);
	
	switch(cmd){
	  case 'y':
	    q_status_message1(SM_ORDER, 0, 9,
		"Printing with command \"%s\"", command);
	    done++;
	    break;

	  case 10:
	    cur_printer = (cur_printer>0)
				? (cur_printer-1)
				: lastprinter;
	    break;

	  case 11:
	    cur_printer = (cur_printer<lastprinter)
				? (cur_printer+1)
				: 0;
	    break;

	  case 'n':
	  case 'x':
	    done++;
	    break;

	  case 'c':
	    done++;
	    break;

	  default:
	    break;
	}
    }

    if(cmd == 'c'){
	if(init)
	  fs_give((void **)&init);

	if(trailer)
	  fs_give((void **)&trailer);

	snprintf(prompt, sizeof(prompt), "Enter custom command : ");
	prompt[sizeof(prompt)-1] = '\0';
	command[0] = '\0';
	rc = 1;
	help = NO_HELP;
	while(rc){
	    int flags = OE_APPEND_CURRENT;

	    rc = optionally_enter(command, -FOOTER_ROWS(ps_global), 0,
		sizeof(command), prompt, NULL, help, &flags);
	    
	    if(rc == 1){
		cmd = 'x';
		rc = 0;
	    }
	    else if(rc == 3)
	      help = (help == NO_HELP) ? h_custom_print : NO_HELP;
	    else if(rc == 0){
		removing_trailing_white_space(command);
		removing_leading_white_space(command);
		q_status_message1(SM_ORDER, 0, 9,
		    "Printing with command \"%s\"", command);
	    }
	}
    }

    if(cmd == 'x' || cmd == 'n'){
	q_status_message(SM_ORDER, 0, 2, "Print cancelled");
	if(init)
	  fs_give((void **)&init);

	if(trailer)
	  fs_give((void **)&trailer);

	return(-1);
    }

    display_message('x');

    ps_global->print = (PRINT_S *)fs_get(sizeof(PRINT_S));
    memset(ps_global->print, 0, sizeof(PRINT_S));

    strncpy(aname, ANSI_PRINTER, sizeof(aname)-1);
    aname[sizeof(aname)-1] = '\0';
    strncat(aname, "-no-formfeed", sizeof(aname)-strlen(aname)-1);
    strncpy(wname, WYSE_PRINTER, sizeof(wname)-1);
    wname[sizeof(wname)-1] = '\0';
    strncat(wname, "-no-formfeed", sizeof(wname)-strlen(wname)-1);
    if(strucmp(command, ANSI_PRINTER) == 0
       || strucmp(command, aname) == 0
       || strucmp(command, WYSE_PRINTER) == 0
       || strucmp(command, wname) == 0){
        /*----------- Attached printer ---------*/
        q_status_message(SM_ORDER, 0, 9,
	    "Printing to attached desktop printer...");
        display_message('x');
	xonxoff_proc(1);			/* make sure XON/XOFF used */
	crlf_proc(1);				/* AND LF->CR xlation */
	if(strucmp(command, ANSI_PRINTER) == 0
	   || strucmp(command, aname) == 0){
	    fputs("\033[5i", stdout);
	    ansi_off = 1;
	}
	else{
	    ansi_off = 0;
	    printf("%c", 18); /* aux on for wyse60,
			         Chuck Everett <*****@*****.**> */
	}

        ps_global->print->fp = stdout;
        if(strucmp(command, ANSI_PRINTER) == 0
	   || strucmp(command, WYSE_PRINTER) == 0){
	    /* put formfeed at the end of the trailer string */
	    if(trailer){
		int len = strlen(trailer);

		fs_resize((void **)&trailer, len+2);
		trailer[len] = '\f';
		trailer[len+1] = '\0';
	    }
	    else
	      trailer = cpystr("\f");
	}
    }
    else{
        /*----------- Print by forking off a UNIX command ------------*/
        dprint((4, "Printing using command \"%s\"\n",
	       command ? command : "?"));
	ps_global->print->result = temp_nam(NULL, "pine_prt");
	if(ps_global->print->result &&
	   (ps_global->print->pipe = open_system_pipe(command,
						      &ps_global->print->result, NULL,
						      PIPE_WRITE | PIPE_STDERR, 0,
						      pipe_callback, NULL))){
	    ps_global->print->fp = ps_global->print->pipe->out.f;
	}
	else{
	    if(ps_global->print->result){
		our_unlink(ps_global->print->result);
		fs_give((void **)&ps_global->print->result);
	    }

            q_status_message1(SM_ORDER | SM_DING, 3, 4,
			      "Error opening printer: %s",
                              error_description(errno));
            dprint((2, "Error popening printer \"%s\"\n",
                      error_description(errno)));
	    if(init)
	      fs_give((void **)&init);

	    if(trailer)
	      fs_give((void **)&trailer);
	    
	    return(-1);
        }
    }

    ps_global->print->err = 0;
    if(init){
	if(*init)
	  fputs(init, ps_global->print->fp);

	fs_give((void **)&init);
    }

    cb.cbuf[0] = '\0';
    cb.cbufp   = cb.cbuf;
    cb.cbufend = cb.cbuf;
#else /* _WINDOWS */
    int status;
    LPTSTR desclpt = NULL;

    if(desc)
      desclpt = utf8_to_lptstr(desc);

    if (status = mswin_print_ready (0, desclpt)) {
        q_status_message1(SM_ORDER | SM_DING, 3, 4,
			  "Error starting print job: %s",
			  mswin_print_error(status));
	if(desclpt)
	  fs_give((void **) &desclpt);

        return(-1);
    }

    if(desclpt)
      fs_give((void **) &desclpt);

    q_status_message(SM_ORDER, 0, 9, "Printing to windows printer...");
    display_message('x');

    /* init print control structure */
    ps_global->print = (PRINT_S *)fs_get(sizeof(PRINT_S));
    memset(ps_global->print, 0, sizeof(PRINT_S));

    ps_global->print->err = 0;
#endif /* _WINDOWS */

    return(0);
}
예제 #20
0
void wtss::tl::server_manager::changeStatusAttribute(const QString &server_uri,
                                                     const QString &cv_name,
                                                     const QString &attribute)
{
  QJsonDocument j_doc = loadSettings();
  QJsonObject j_object = j_doc.object();

  QJsonObject j_servers = j_object.find("servers").value().toObject();

  if(!j_servers.contains(server_uri))
  {
    boost::format err_msg("Could not find the server: %1%");
    throw out_of_range_exception()
        << error_description((err_msg % server_uri.toUtf8().data()).str());
  }

  QJsonObject j_server = j_servers.find(server_uri).value().toObject();

  if(!j_server.contains("coverages"))
  {
    boost::format err_msg("The server %1% has no coverages");
    throw out_of_range_exception()
        << error_description((err_msg % server_uri.toUtf8().data()).str());
  }

  QJsonObject j_coverages = j_server.find("coverages").value().toObject();

  if(!j_coverages.contains(cv_name))
  {
    boost::format err_msg("The server %1% has no coverage named: %2%");
    throw out_of_range_exception() << error_description(
        (err_msg % server_uri.toUtf8().data() % cv_name.toUtf8().data()).str());
  }

  QJsonObject j_coverage = j_coverages.find(cv_name).value().toObject();

  if(!j_coverage.contains("attributes"))
  {
    boost::format err_msg("The coverage %1% has no attributes.");
    throw out_of_range_exception()
        << error_description((err_msg % cv_name.toUtf8().data()).str());
  }

  QJsonObject j_attributes = j_coverage.find("attributes").value().toObject();

  if(!j_attributes.contains(attribute))
  {
    boost::format err_msg("The coverage %1% has no attribute named: %2%.");
    throw out_of_range_exception() << error_description(
        (err_msg % cv_name.toUtf8().data() % attribute.toUtf8().data()).str());
  }

  QJsonObject j_attribute = j_attributes.find(attribute).value().toObject();

  if(!j_attribute.contains("active"))
  {
    boost::format err_msg("The coverage %1% has no attribute named: %2%.");
    throw out_of_range_exception() << error_description(
        (err_msg % cv_name.toUtf8().data() % attribute.toUtf8().data()).str());
  }

  j_attribute["active"] = !j_attribute.find("active").value().toBool();

  j_attributes[attribute] = j_attribute;
  j_coverage["attributes"] = j_attributes;

  j_coverages[cv_name] = j_coverage;
  j_server["coverages"] = j_coverages;

  j_servers[server_uri] = j_server;
  j_object["servers"] = j_servers;

  j_doc.setObject(j_object);
  saveSettings(j_doc);
}
예제 #21
0
UINT CDropbox::RequestAccessTokenAsync(void *owner, void *param)
{
	HWND hwndDlg = (HWND)param;
	CDropbox *instance = (CDropbox*)owner;

	EnableWindow(GetDlgItem(hwndDlg, IDC_AUTHORIZE), FALSE);
	SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("in process..."));

	if (instance->HasAccessToken())
		instance->DestroyAccessToken();

	char requestToken[128];
	GetDlgItemTextA(hwndDlg, IDC_REQUEST_CODE, requestToken, _countof(requestToken));

	GetAccessTokenRequest request(requestToken);
	NLHR_PTR response(request.Send(instance->hNetlibConnection));

	if (response == NULL || response->resultCode != HTTP_STATUS_OK) {
		Netlib_Logf(instance->hNetlibConnection, "%s: %s", MODULE, HttpStatusToText(HTTP_STATUS_ERROR));
		if (hwndDlg)
			SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("server does not respond"));
		/*else
			ShowNotification(TranslateT("server does not respond"), MB_ICONERROR);*/
		return 0;
	}

	JSONNode root = JSONNode::parse(response->pData);
	if (root.empty()) {
		Netlib_Logf(instance->hNetlibConnection, "%s: %s", MODULE, HttpStatusToText((HTTP_STATUS)response->resultCode));
		if (hwndDlg)
			SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("server does not respond"));
		/*else
			ShowNotification((TCHAR*)error_description, MB_ICONERROR);*/
		return 0;
	}

	JSONNode node = root.at("error_description");
	if (node != JSONNULL) {
		ptrT error_description(mir_a2t_cp(node.as_string().c_str(), CP_UTF8));
		Netlib_Logf(instance->hNetlibConnection, "%s: %s", MODULE, HttpStatusToText((HTTP_STATUS)response->resultCode));
		if (hwndDlg)
			SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, error_description);
		/*else
			ShowNotification((TCHAR*)error_description, MB_ICONERROR);*/
		return 0;
	}

	node = root.at("access_token");
	db_set_s(NULL, MODULE, "TokenSecret", node.as_string().c_str());
	ProtoBroadcastAck(MODULE, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)ID_STATUS_OFFLINE, (WPARAM)ID_STATUS_ONLINE);

	MCONTACT hContact = instance->GetDefaultContact();
	if (hContact) {
		if (db_get_w(hContact, MODULE, "Status", ID_STATUS_OFFLINE) != ID_STATUS_ONLINE)
			db_set_w(hContact, MODULE, "Status", ID_STATUS_ONLINE);
	}

	try {
		RequestAccountInfo(instance);
	}
	catch (DropboxException &ex) {
		Netlib_Logf(instance->hNetlibConnection, "%s: %s", MODULE, ex.what());
		return 0;
	}

	if (hwndDlg)
		SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("you have been authorized"));
	/*else
		ShowNotification(TranslateT("you have been authorized"), MB_ICONINFORMATION);*/

	SetDlgItemTextA(hwndDlg, IDC_REQUEST_CODE, "");

	return 0;
}
예제 #22
0
파일: text.c 프로젝트: mavit/alpine
/*----------------------------------------------------------------------
   Handle fetching and filtering a text message segment to be displayed
   by scrolltool or printed or exported or piped.

Args: att   -- segment to fetch
      msgno -- message number segment is a part of
      pc    -- function to write characters from segment with
      style -- Indicates special handling for error messages
      flags -- Indicates special necessary handling

Returns: 1 if errors encountered, 0 if everything went A-OK

 ----*/     
int
decode_text(ATTACH_S	    *att,
	    long int	     msgno,
	    gf_io_t	     pc,
	    HANDLE_S	   **handlesp,
	    DetachErrStyle   style,
	    int		     flags)
{
    FILTLIST_S	filters[14];
    char       *err, *charset;
    int		filtcnt = 0, error_found = 0, column, wrapit;
    int         is_in_sig = OUT_SIG_BLOCK;
    int         is_flowed_msg = 0, add_me = 1, doraw = RAWSTRING;
    int         is_delsp_yes = 0;
    int         filt_only_c0 = 0;
    char       *parmval;
    char       *free_this = NULL;
    STORE_S    *warn_so = NULL;
    DELQ_S      dq;
    URL_HILITE_S uh;

    column = (flags & FM_DISPLAY) ? ps_global->ttyo->screen_cols : 80;

    if(!(flags & FM_DISPLAY))
      flags |= FM_NOINDENT;

    wrapit = column;

    memset(filters, 0, sizeof(filters));

    /* charset the body part is in */
    charset = parameter_val(att->body->parameter, "charset");

    /* determined if it's flowed, affects wrapping and quote coloring */
    if(att->body->type == TYPETEXT
       && !strucmp(att->body->subtype, "plain")
       && (parmval = parameter_val(att->body->parameter, "format"))){
	if(!strucmp(parmval, "flowed"))
	  is_flowed_msg = 1;
	fs_give((void **) &parmval);

	if(is_flowed_msg){
	    if((parmval = parameter_val(att->body->parameter, "delsp")) != NULL){
		if(!strucmp(parmval, "yes"))
		  is_delsp_yes = 1;

		fs_give((void **) &parmval);
	    }
	}
    }

    if(!ps_global->pass_ctrl_chars){
	filters[filtcnt++].filter = gf_escape_filter;
	filters[filtcnt].filter = gf_control_filter;

	filt_only_c0 = 1;
	filters[filtcnt++].data = gf_control_filter_opt(&filt_only_c0);
    }

    if(flags & FM_DISPLAY)
      filters[filtcnt++].filter = gf_tag_filter;

    /*
     * if it's just plain old text, look for url's
     */
    if(!(att->body->subtype && strucmp(att->body->subtype, "plain"))){
	struct variable *vars = ps_global->vars;

	if((F_ON(F_VIEW_SEL_URL, ps_global)
	    || F_ON(F_VIEW_SEL_URL_HOST, ps_global)
	    || F_ON(F_SCAN_ADDR, ps_global))
	   && handlesp){

	    /*
	     * The url_hilite filter really ought to come
	     * after flowing, because flowing with the DelSp=yes parameter
	     * can reassemble broken urls back into identifiable urls.
	     * We add the preflow filter to do only the reassembly part
	     * of the flowing so that we can spot the urls.
	     * At this time (2005-03-29) we know that Apple Mail does
	     * send mail like this sometimes. This filter removes the
	     * sequence  SP CRLF  if that seems safe.
	     */
	    if(ps_global->full_header != 2 && is_delsp_yes)
              filters[filtcnt++].filter = gf_preflow;

	    filters[filtcnt].filter = gf_line_test;
	    filters[filtcnt++].data = gf_line_test_opt(url_hilite,
						       gf_url_hilite_opt(&uh,handlesp,0));
	}

	if((flags & FM_DISPLAY)
           && !(flags & FM_NOCOLOR)
           && pico_usingcolor()
           && VAR_SPECIAL_TEXT_FORE_COLOR 
           && VAR_SPECIAL_TEXT_BACK_COLOR){
            filters[filtcnt].filter = gf_line_test;
            filters[filtcnt++].data = gf_line_test_opt(color_this_text, NULL);
        }

	/*
	 * First, paint the signature.
	 * Disclaimers noted below for coloring quotes apply here as well.
	 */
	if((flags & FM_DISPLAY)
	   && !(flags & FM_NOCOLOR)
	   && pico_usingcolor()
	   && VAR_SIGNATURE_FORE_COLOR
	   && VAR_SIGNATURE_BACK_COLOR){
	    filters[filtcnt].filter = gf_quote_test;
	    filters[filtcnt++].data = gf_line_test_opt(color_signature,
						       &is_in_sig);
	}

	/*
	 * Gotta be careful with this. The color_a_quote filter adds color
	 * to the beginning and end of the line. This will break some
	 * line_test-style filters which come after it. For example, if they
	 * are looking for something at the start of a line (like color_a_quote
	 * itself). I guess we could fix that by ignoring tags at the
	 * beginning of the line when doing the search.
	 */
	if((flags & FM_DISPLAY)
	   && !(flags & FM_NOCOLOR)
	   && pico_usingcolor()
	   && VAR_QUOTE1_FORE_COLOR
	   && VAR_QUOTE1_BACK_COLOR){
	    add_me = 0;
	    filters[filtcnt].filter = gf_quote_test;
	    filters[filtcnt++].data = gf_line_test_opt(color_a_quote, &is_flowed_msg);
	}
    }
    else if(!strucmp(att->body->subtype, "richtext")){
	int plain_opt;

	plain_opt = !(flags&FM_DISPLAY);

	/* maybe strip everything! */
	filters[filtcnt].filter = gf_rich2plain;
	filters[filtcnt++].data = gf_rich2plain_opt(&plain_opt);
	/* width to use for file or printer */
	if(wrapit - 5 > 0)
	  wrapit -= 5;
    }
    else if(!strucmp(att->body->subtype, "enriched")){
	int plain_opt;

	plain_opt = !(flags&FM_DISPLAY);

	filters[filtcnt].filter = gf_enriched2plain;
	filters[filtcnt++].data = gf_enriched2plain_opt(&plain_opt);
	/* width to use for file or printer */
	if(wrapit - 5 > 0)
	  wrapit -= 5;
    }
    else if(!strucmp(att->body->subtype, "html") && ps_global->full_header < 2){
/*BUG:	    sniff the params for "version=2.0" ala draft-ietf-html-spec-01 */
	int	 opts = 0;

	clear_html_risk();

	if(flags & FM_DISPLAY){
	    gf_io_t	 warn_pc;

	    if(handlesp){		/* pass on handles awareness */
		opts |= GFHP_HANDLES;

		if(F_OFF(F_QUELL_HOST_AFTER_URL, ps_global) && !(flags & FM_HIDESERVER))
		  opts |= GFHP_SHOW_SERVER;
	    }

	    if(!(flags & FM_NOEDITORIAL)){
		warn_so = so_get(CharStar, NULL, EDIT_ACCESS);
		gf_set_so_writec(&warn_pc, warn_so);
		format_editorial(HTML_WARNING, column, flags, handlesp, warn_pc);
		gf_clear_so_writec(warn_so);
		so_puts(warn_so, "\015\012");
		so_writec('\0', warn_so);
	    }
	}
	else
	  opts |= GFHP_STRIPPED;	/* don't embed anything! */

	if(flags & FM_NOHTMLREL)
	  opts |= GFHP_NO_RELATIVE;

	if(flags & FM_HTMLRELATED)
	  opts |= GFHP_RELATED_CONTENT;

	if(flags & FM_HTML)
	  opts |= GFHP_HTML;

	if(flags & FM_HTMLIMAGES)
	  opts |= GFHP_HTML_IMAGES;

	wrapit = 0;		/* wrap already handled! */
	filters[filtcnt].filter = gf_html2plain;
	filters[filtcnt++].data = gf_html2plain_opt(NULL, column,
						    (flags & (FM_NOINDENT | FM_HTML))
						      ? 0
						      : format_view_margin(),
						    handlesp, set_html_risk, opts);

	if(warn_so){
	    filters[filtcnt].filter = gf_prepend_editorial;
	    filters[filtcnt++].data = gf_prepend_editorial_opt(get_html_risk,
							       (char *) so_text(warn_so));
	}
    }

    if (add_me){
      filters[filtcnt].filter = gf_quote_test;
      filters[filtcnt++].data = gf_line_test_opt(select_quote, &doraw);
    }

    /*
     * If the message is not flowed, we do the quote suppression before
     * the wrapping, because the wrapping does not preserve the quote
     * characters at the beginnings of the lines in that case.
     * Otherwise, we defer until after the wrapping.
     *
     * Also, this is a good place to do quote-replacement on nonflowed
     * messages because no other filters depend on the "> ".
     * Quote-replacement is easier in the flowed case and occurs
     * automatically in the flowed wrapping filter.
     */
    if(!is_flowed_msg
       && ps_global->full_header == 0
       && !(att->body->subtype && strucmp(att->body->subtype, "plain"))
       && (flags & FM_DISPLAY)){
	if(ps_global->quote_suppression_threshold != 0){
	    memset(&dq, 0, sizeof(dq));
	    dq.lines = ps_global->quote_suppression_threshold;
	    dq.is_flowed = is_flowed_msg;
	    dq.indent_length = 0;		/* indent didn't happen yet */
	    dq.saved_line = &free_this;
	    dq.handlesp   = handlesp;
	    dq.do_color   = (!(flags & FM_NOCOLOR) && pico_usingcolor());

	    filters[filtcnt].filter = gf_quote_test;
	    filters[filtcnt++].data = gf_line_test_opt(delete_quotes, &dq);
	}
	if(ps_global->VAR_QUOTE_REPLACE_STRING
	    && F_ON(F_QUOTE_REPLACE_NOFLOW, ps_global)){
	    filters[filtcnt].filter = gf_line_test;
	    filters[filtcnt++].data = gf_line_test_opt(replace_quotes, NULL);
	}
    }

    if(wrapit && !(flags & FM_NOWRAP)){
	int wrapflags = (flags & FM_DISPLAY) ? (GFW_HANDLES|GFW_SOFTHYPHEN)
					     : GFW_NONE;

	if(flags & FM_DISPLAY
	   && !(flags & FM_NOCOLOR)
	   && pico_usingcolor())
	  wrapflags |= GFW_USECOLOR;

	/* text/flowed (RFC 2646 + draft)? */
	if(ps_global->full_header != 2 && is_flowed_msg){
	    wrapflags |= GFW_FLOWED;

	    if(is_delsp_yes)
	      wrapflags |= GFW_DELSP;
	}

	filters[filtcnt].filter = gf_wrap;
	filters[filtcnt++].data = gf_wrap_filter_opt(wrapit, column,
						     (flags & FM_NOINDENT)
						       ? 0
						       : format_view_margin(),
						     0, wrapflags);
    }

    /*
     * This has to come after wrapping has happened because the user tells
     * us how many quoted lines to display, and we want that number to be
     * the wrapped lines, not the pre-wrapped lines. We do it before the
     * wrapping if the message is not flowed, because the wrapping does not
     * preserve the quote characters at the beginnings of the lines in that
     * case.
     */
    if(is_flowed_msg
       && ps_global->full_header == 0
       && !(att->body->subtype && strucmp(att->body->subtype, "plain"))
       && (flags & FM_DISPLAY)
       && ps_global->quote_suppression_threshold != 0){
	memset(&dq, 0, sizeof(dq));
	dq.lines = ps_global->quote_suppression_threshold;
	dq.is_flowed = is_flowed_msg;
	dq.indent_length = (wrapit && !(flags & FM_NOWRAP)
			    && !(flags & FM_NOINDENT))
			       ? format_view_margin()[0]
			       : 0;
	dq.saved_line = &free_this;
	dq.handlesp   = handlesp;
	dq.do_color   = (!(flags & FM_NOCOLOR) && pico_usingcolor());

	filters[filtcnt].filter = gf_quote_test;
	filters[filtcnt++].data = gf_line_test_opt(delete_quotes, &dq);
    }

    if(charset){
	if(F_OFF(F_QUELL_CHARSET_WARNING, ps_global)
	   && !(flags & FM_NOEDITORIAL)){
	    int rv = TRUE;
	    CONV_TABLE *ct = NULL;

	    /*
	     * Need editorial if message charset is not ascii
	     * and the display charset is not either the same
	     * as the message charset or UTF-8.
	     */
	    if(strucmp(charset, "us-ascii")
	       && !((ps_global->display_charmap
		     && !strucmp(charset, ps_global->display_charmap))
	            || !strucmp("UTF-8", ps_global->display_charmap))){

		/*
		 * This is probably overkill. We're just using this
		 * conversion_table routine to get at the quality.
		 */
		if(ps_global->display_charmap)
		  ct = conversion_table(charset, ps_global->display_charmap);

		rv = charset_editorial(charset, msgno, handlesp, flags,
				       ct ? ct->quality : CV_NO_TRANSLATE_POSSIBLE,
				       column, pc);
	    }
	    if(!rv)
	      goto write_error;
	}

	fs_give((void **) &charset);
    }

    /* Format editorial comment about unknown encoding */
    if(att->body->encoding > ENCQUOTEDPRINTABLE){
	char buf[2048];

	snprintf(buf, sizeof(buf), ENCODING_DISCLAIMER, body_encodings[att->body->encoding]);

	if(!(format_editorial(buf, column, flags, handlesp, pc) == NULL
	     && gf_puts(NEWLINE, pc) && gf_puts(NEWLINE, pc)))
	  goto write_error;
    }

    err = detach(ps_global->mail_stream, msgno, att->number, 0L,
		 NULL, pc, filtcnt ? filters : NULL, 0);
    
    delete_unused_handles(handlesp);
    
    if(free_this)
      fs_give((void **) &free_this);

    if(warn_so)
      so_give(&warn_so);
    
    if(err) {
	error_found++;
	if(style == QStatus) {
	    q_status_message1(SM_ORDER, 3, 4, "%.200s", err);
	} else if(style == InLine) {
	    char buftmp[MAILTMPLEN];

	    snprintf(buftmp, sizeof(buftmp), "%s",
		    att->body->description ? att->body->description : "");
	    snprintf(tmp_20k_buf, SIZEOF_20KBUF, "%s   [Error: %s]  %c%s%c%s%s",
		    NEWLINE, err,
		    att->body->description ? '\"' : ' ',
		    att->body->description ? buftmp : "",
		    att->body->description ? '\"' : ' ',
		    NEWLINE, NEWLINE);
	    if(!gf_puts(tmp_20k_buf, pc))
	      goto write_error;
	}
    }

    if(att->body->subtype
       && (!strucmp(att->body->subtype, "richtext")
	   || !strucmp(att->body->subtype, "enriched"))
       && !(flags & FM_DISPLAY)){
	if(!gf_puts(NEWLINE, pc) || !gf_puts(NEWLINE, pc))
	  goto write_error;
    }

    return(error_found);

  write_error:
    if(style == QStatus)
      q_status_message1(SM_ORDER, 3, 4, "Error writing message: %.200s", 
			error_description(errno));

    return(1);
}
예제 #23
0
UINT CDropbox::RequestAcceessTokenAsync(void *owner, void* param)
{
	HWND hwndDlg = (HWND)param;
	CDropbox *instance = (CDropbox*)owner;

	EnableWindow(GetDlgItem(hwndDlg, IDC_AUTHORIZE), FALSE);
	SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("in process..."));

	if (instance->HasAccessToken())
		instance->DestroyAcceessToken();

	char requestToken[128];
	GetDlgItemTextA(hwndDlg, IDC_REQUEST_CODE, requestToken, SIZEOF(requestToken));

	char data[1024];
	mir_snprintf(
		data,
		SIZEOF(data),
		"grant_type=authorization_code&code=%s",
		requestToken);

	HttpRequest *request = new HttpRequest(instance->hNetlibUser, REQUEST_POST, DROPBOX_API_URL "/oauth2/token");
	request->AddBasicAuthHeader(DROPBOX_API_KEY, DROPBOX_API_SECRET);
	request->AddHeader("Content-Type", "application/x-www-form-urlencoded");
	request->pData = mir_strdup(data);
	request->dataLength = (int)strlen(data);

	mir_ptr<NETLIBHTTPREQUEST> response(request->Send());

	delete request;

	MCONTACT hContact = instance->GetDefaultContact();

	if (response)
	{
		JSONROOT root(response->pData);
		if (root)
		{
			if (response->resultCode == HTTP_STATUS_OK)
			{
				JSONNODE *node = json_get(root, "access_token");
				ptrA access_token = ptrA(mir_u2a(json_as_string(node)));
				db_set_s(NULL, MODULE, "TokenSecret", access_token);

				if (hContact)
				{
					if (db_get_w(hContact, MODULE, "Status", ID_STATUS_OFFLINE) == ID_STATUS_OFFLINE)
						db_set_w(hContact, MODULE, "Status", ID_STATUS_ONLINE);
				}

				instance->RequestAccountInfo();

				if (hwndDlg)
					SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("you have been authorized"));
				/*else
					ShowNotification(TranslateT("you have been authorized"), MB_ICONINFORMATION);*/
			}
			else
			{
				JSONNODE *node = json_get(root, "error_description");
				ptrW error_description(json_as_string(node));

				if (hwndDlg)
					SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, error_description);
				/*else
					ShowNotification((wchar_t*)error_description, MB_ICONERROR);*/
			}
		}
	}
	else
	{
		if (hwndDlg)
			SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("server does not respond"));

		HandleHttpResponseError(instance->hNetlibUser, response);
	}

	SetDlgItemTextA(hwndDlg, IDC_REQUEST_CODE, "");

	return 0;
}
예제 #24
0
char *
rd_metadata_name(void)
{
    char        *p, *q, *metafile;
    char         path[MAXPATH], pinerc_dir[MAXPATH];
    struct variable *vars = ps_global->vars;

    dprint((9, "rd_metadata_name\n"));

    pinerc_dir[0] = '\0';
    if(ps_global->pinerc){
	char *prcn = ps_global->pinerc;
	char *lc;

	if((lc = last_cmpnt(prcn)) != NULL){
	    int to_copy;

	    to_copy = (lc - prcn > 1) ? (lc - prcn - 1) : 1;
	    strncpy(pinerc_dir, prcn, MIN(to_copy, sizeof(pinerc_dir)-1));
	    pinerc_dir[MIN(to_copy, sizeof(pinerc_dir)-1)] = '\0';
	}
	else{
	    pinerc_dir[0] = '.';
	    pinerc_dir[1] = '\0';
	}
    }

    /*
     * If there is no metadata file specified in the pinerc, create a filename.
     */
    if(!(VAR_REMOTE_ABOOK_METADATA && VAR_REMOTE_ABOOK_METADATA[0])){
	if(pinerc_dir[0] && (p = tempfile_in_same_dir(ps_global->pinerc,
						      meta_prefix, NULL))){
	    /* fill in the pinerc variable */
	    q = p + strlen(pinerc_dir) + 1;
	    set_variable(V_REMOTE_ABOOK_METADATA, q, 1, 0, Main);
	    dprint((2, "creating name for metadata file: %s\n",
		   q ? q : "?"));

	    /* something's broken, return NULL rab */
	    if(!VAR_REMOTE_ABOOK_METADATA || !VAR_REMOTE_ABOOK_METADATA[0]){
		our_unlink(p);
		fs_give((void **)&p);
		return(NULL);
	    }

	    fs_give((void **)&p);
	}
	else{
	    q_status_message(SM_ORDER, 3, 5,
		"can't create metadata file in pinerc directory, continuing");
	    return(NULL);
	}
    }

    build_path(path, pinerc_dir ? pinerc_dir : NULL,
	       VAR_REMOTE_ABOOK_METADATA, sizeof(path));
    metafile = path;

    /*
     * If the metadata file doesn't exist, create it.
     */
    if(can_access(metafile, ACCESS_EXISTS) != 0){
	int fd;

	if((fd = our_open(metafile, O_CREAT|O_EXCL|O_WRONLY|O_BINARY, 0600)) < 0){

	    set_variable(V_REMOTE_ABOOK_METADATA, NULL, 1, 0, Main);

	    q_status_message2(SM_ORDER, 3, 5,
		       "can't create cache file %.200s, continuing (%.200s)",
		       metafile, error_description(errno));

	    dprint((2, "can't create metafile %s: %s\n",
		       metafile ? metafile : "?", error_description(errno)));

	    return(NULL);
	}

	dprint((2, "created metadata file: %s\n",
	       metafile ? metafile : "?"));

	(void)close(fd);
    }

    return(cpystr(metafile));;
}
예제 #25
0
파일: Script.cpp 프로젝트: hugs/Selenium2
int Script::Execute() {
  VARIANT result;
  if (this->script_engine_host_ == NULL) {
    return ENOSUCHDOCUMENT;
  }
  CComVariant temp_function;
  if (!this->CreateAnonymousFunction(&temp_function)) {
    // Debug level since this is normally the point we find out that 
    // a page refresh has occured. *sigh*
    // LOG(DEBUG) << "Cannot create anonymous function: " << _bstr_t(script) << endl;
    return EUNEXPECTEDJSERROR;
  }

  if (temp_function.vt != VT_DISPATCH) {
    // No return value that we care about
    return SUCCESS;
  }

  // Grab the "call" method out of the returned function
  DISPID call_member_id;
  OLECHAR FAR* call_member_name = L"call";
  HRESULT hr = temp_function.pdispVal->GetIDsOfNames(IID_NULL,
                                                     &call_member_name,
                                                     1,
                                                     LOCALE_USER_DEFAULT,
                                                     &call_member_id);
  if (FAILED(hr)) {
//		LOGHR(DEBUG, hr) << "Cannot locate call method on anonymous function: " << _bstr_t(script) << endl;
    return EUNEXPECTEDJSERROR;
  }

  DISPPARAMS call_parameters = { 0 };
  memset(&call_parameters, 0, sizeof call_parameters);

  long lower = 0;
  ::SafeArrayGetLBound(this->argument_array_, 1, &lower);
  long upper = 0;
  ::SafeArrayGetUBound(this->argument_array_, 1, &upper);
  long nargs = 1 + upper - lower;
  call_parameters.cArgs = nargs + 1;

  CComPtr<IHTMLWindow2> win;
  hr = this->script_engine_host_->get_parentWindow(&win);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Cannot get parent window";
    return EUNEXPECTEDJSERROR;
  }
  _variant_t* vargs = new _variant_t[nargs + 1];
  hr = ::VariantCopy(&(vargs[nargs]), &CComVariant(win));

  long index;
  for (int i = 0; i < nargs; i++) {
    index = i;
    CComVariant v;
    ::SafeArrayGetElement(this->argument_array_,
                          &index,
                          reinterpret_cast<void*>(&v));
    hr = ::VariantCopy(&(vargs[nargs - 1 - i]), &v);
  }

  call_parameters.rgvarg = vargs;
  int return_code = SUCCESS;
  EXCEPINFO exception;
  memset(&exception, 0, sizeof exception);
  hr = temp_function.pdispVal->Invoke(call_member_id,
                                      IID_NULL,
                                      LOCALE_USER_DEFAULT,
                                      DISPATCH_METHOD,
                                      &call_parameters, 
                                      &result,
                                      &exception,
                                      0);

  if (FAILED(hr)) {
    if (DISP_E_EXCEPTION == hr) {
      CComBSTR error_description(exception.bstrDescription ? exception.bstrDescription : L"EUNEXPECTEDJSERROR");
      LOG(INFO) << "Exception message was: " << error_description;
    } else {
      // LOGHR(DEBUG, hr) << "Failed to execute: " << _bstr_t(script);
    }

    ::VariantClear(&result);
    result.vt = VT_USERDEFINED;
    if (exception.bstrDescription != NULL) {
      result.bstrVal = ::SysAllocStringByteLen(reinterpret_cast<char*>(exception.bstrDescription),
                                               ::SysStringByteLen(exception.bstrDescription));
    } else {
      result.bstrVal = ::SysAllocStringByteLen(NULL, 0);
    }
    return_code = EUNEXPECTEDJSERROR;
  }

  // If the script returned an IHTMLElement, we need to copy it to make it valid.
  if(VT_DISPATCH == result.vt) {
    CComQIPtr<IHTMLElement> element(result.pdispVal);
    if(element) {
      IHTMLElement* &dom_element = *(reinterpret_cast<IHTMLElement**>(&result.pdispVal));
      hr = element.CopyTo(&dom_element);
    }
  }

  this->result_ = result;

  delete[] vargs;

  return return_code;
}
예제 #26
0
/*
 * dfilter - pipe the data from the given storage object thru the
 *	     global display filter and into whatever the putchar's
 *	     function points to.
 *
 *	     Input is assumed to be UTF-8.
 *	     That's converted to user's locale and passed to rawcmd.
 *	     That's converted back to UTF-8 and passed through aux_filters.
 */
char *
dfilter(char *rawcmd, STORE_S *input_so, gf_io_t output_pc, FILTLIST_S *aux_filters)
{
    char *status = NULL, *cmd, *resultf = NULL, *tmpfile = NULL;
    int   key = 0, silent = 0;

    if((cmd = expand_filter_tokens(rawcmd,NULL,&tmpfile,&resultf,NULL,&key,NULL, &silent)) != NULL){
	suspend_busy_cue();
#ifndef	_WINDOWS
	if(!silent){
	  ps_global->mangled_screen = 1;
	  ClearScreen();
	}
	fflush(stdout);
#endif

	/*
	 * If it was requested that the interaction take place via
	 * a tmpfile, fill it with text from our input_so, and let
	 * system_pipe handle the rest.  Session key and tmp file
	 * mode support additions based loosely on a patch 
	 * supplied by Thomas Stroesslin <*****@*****.**>
	 */
	if(tmpfile){
	    PIPE_S	  *filter_pipe;
	    FILE          *fp;
	    gf_io_t	   gc, pc;
	    STORE_S       *tmpf_so;

	    /* write the tmp file */
	    so_seek(input_so, 0L, 0);
	    if((tmpf_so = so_get(FileStar, tmpfile, WRITE_ACCESS|OWNER_ONLY|WRITE_TO_LOCALE)) != NULL){
	        if(key){
		    so_puts(tmpf_so, filter_session_key());
                    so_puts(tmpf_so, NEWLINE);
		}
	        /* copy input to tmp file */
		gf_set_so_readc(&gc, input_so);
		gf_set_so_writec(&pc, tmpf_so);
		gf_filter_init();
		status = gf_pipe(gc, pc);
		gf_clear_so_readc(input_so);
		gf_clear_so_writec(tmpf_so);
		if(so_give(&tmpf_so) != 0 && status == NULL)
		  status = error_description(errno);

		/* prepare the terminal in case the filter uses it */
		if(status == NULL){
		    if((filter_pipe = open_system_pipe(cmd, NULL, NULL,
						PIPE_USER | (silent ? PIPE_SILENT : 
						(F_ON(F_DISABLE_TERM_RESET_DISP, ps_global) ? 0 : PIPE_RESET)),
						      0, pipe_callback, NULL)) != NULL){
			if(close_system_pipe(&filter_pipe, NULL, pipe_callback) == 0){
			    /* pull result out of tmp file */
			    if((fp = our_fopen(tmpfile, "rb")) != NULL){
				gf_set_readc(&gc, fp, 0L, FileStar, READ_FROM_LOCALE);
				gf_filter_init();
				if(aux_filters)
				  for( ; aux_filters->filter; aux_filters++)
				    gf_link_filter(aux_filters->filter,
						   aux_filters->data);

				status = gf_pipe(gc, output_pc);
				fclose(fp);
			    }
			    else
			      status = "Can't read result of display filter";
			}
			else
			  status = "Filter command returned error.";
		    }
		    else
		      status = "Can't open pipe for display filter";
		}

		our_unlink(tmpfile);
	    }
	    else
	      status = "Can't open display filter tmp file";
	}
	else if((status = gf_filter(cmd, key ? filter_session_key() : NULL,
				   input_so, output_pc, aux_filters, silent,
				   F_ON(F_DISABLE_TERM_RESET_DISP, ps_global),
				   pipe_callback)) != NULL){
	    unsigned long ch;

	    fprintf(stdout,"\r\n%s  Hit return to continue.", status);
	    fflush(stdout);
	    while((ch = read_char(300)) != ctrl('M') && ch != NO_OP_IDLE)
	      putchar(BELL);
	}

	if(resultf){
	    if(name_file_size(resultf) > 0L)
	      display_output_file(resultf, "Filter", NULL, DOF_BRIEF);

	    fs_give((void **)&resultf);
	}

	resume_busy_cue(0);
#ifndef	_WINDOWS
	if(!silent)
	  ClearScreen();
#endif
	fs_give((void **)&cmd);
    }

    return(status);
}