Esempio n. 1
0
int index_directory(request * req, char *dest_filename)
{
    DIR *request_dir;
    FILE *fdstream;
    struct dirent *dirbuf;
    int bytes = 0;
    char *escname = NULL;

    if (chdir(req->pathname) == -1) {
        if (errno == EACCES || errno == EPERM) {
            send_r_forbidden(req);
        } else {
            log_error_doc(req);
            perror("chdir");
            send_r_bad_request(req);
        }
        return -1;
    }

    request_dir = opendir(".");
    if (request_dir == NULL) {
        int errno_save = errno;
        send_r_error(req);
        log_error_time();
        fprintf(stderr, "directory \"%s\": ", req->pathname);
        errno = errno_save;
        perror("opendir");
        return -1;
    }

    fdstream = fopen(dest_filename, "w");
    if (fdstream == NULL) {
        boa_perror(req, "dircache fopen");
        closedir(request_dir);
        return -1;
    }

    bytes += fprintf(fdstream,
                     "<HTML><HEAD>\n<TITLE>Index of %s</TITLE>\n</HEAD>\n\n",
                     req->request_uri);
    bytes += fprintf(fdstream, "<BODY>\n\n<H2>Index of %s</H2>\n\n<PRE>\n",
                     req->request_uri);

    while ((dirbuf = readdir(request_dir))) {
        if (!strcmp(dirbuf->d_name, "."))
            continue;

        if (!strcmp(dirbuf->d_name, "..")) {
            bytes += fprintf(fdstream,
                             " [DIR] <A HREF=\"../\">Parent Directory</A>\n");
            continue;
        }

        if ((escname = escape_string(dirbuf->d_name, NULL)) != NULL) {
            bytes += fprintf(fdstream, " <A HREF=\"%s\">%s</A>\n",
                             escname, dirbuf->d_name);
            free(escname);
            escname = NULL;
        }
    }
    closedir(request_dir);
    bytes += fprintf(fdstream, "</PRE>\n\n</BODY>\n</HTML>\n");

    fclose(fdstream);

    chdir(server_root);

    req->filesize = bytes;      /* for logging transfer size */
    return 0;                   /* success */
}
Esempio n. 2
0
/* displays services on a host */
void display_host_services(void) {
	service *temp_service;
	servicestatus *temp_servicestatus;

	/**** MAIN SCREEN (CARD 1) ****/
	printf("<card id='card1' title='Host Services'>\n");
	printf("<p align='center' mode='nowrap'>\n");
	printf("<b>Host <anchor title='%s'>", url_encode(host_name));
	printf("'%s'<go href='%s' method='post'><postfield name='host' value='%s'/></go></anchor> Services</b><br/>\n", host_name, STATUSWML_CGI, escape_string(host_name));

	printf("<table columns='2' align='LL'>\n");

	/* check all services */
	for(temp_service = service_list; temp_service != NULL; temp_service = temp_service->next) {

		if(strcmp(temp_service->host_name, host_name))
			continue;

		if(is_authorized_for_service(temp_service, &current_authdata) == FALSE)
			continue;

		temp_servicestatus = find_servicestatus(temp_service->host_name, temp_service->description);
		if(temp_servicestatus == NULL)
			continue;

		printf("<tr><td><anchor title='%s'>", temp_service->description);
		if(temp_servicestatus->status == SERVICE_OK)
			printf("OK");
		else if(temp_servicestatus->status == SERVICE_PENDING)
			printf("PND");
		else if(temp_servicestatus->status == SERVICE_WARNING)
			printf("WRN");
		else if(temp_servicestatus->status == SERVICE_UNKNOWN)
			printf("UNK");
		else if(temp_servicestatus->status == SERVICE_CRITICAL)
			printf("CRI");
		else
			printf("???");

		printf("<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='service' value='%s'/></go></anchor></td>", STATUSWML_CGI, temp_service->host_name, temp_service->description);
		printf("<td>%s</td></tr>\n", temp_service->description);
		}

	printf("</table>\n");

	printf("</p>\n");

	printf("</card>\n");

	return;
	}
Esempio n. 3
0
/* displays hostgroup status overview */
void display_hostgroup_overview(void) {
	hostgroup *temp_hostgroup;
	hostsmember *temp_member;
	host *temp_host;
	hoststatus *temp_hoststatus;


	/**** MAIN SCREEN (CARD 1) ****/
	printf("<card id='card1' title='Status Overview'>\n");
	printf("<p align='center' mode='nowrap'>\n");

	printf("<b><anchor title='Status Overview'>Status Overview<go href='%s' method='post'><postfield name='hostgroup' value='%s'/><postfield name='style' value='summary'/></go></anchor></b><br/><br/>\n", STATUSWML_CGI, escape_string(hostgroup_name));

	/* check all hostgroups */
	for(temp_hostgroup = hostgroup_list; temp_hostgroup != NULL; temp_hostgroup = temp_hostgroup->next) {

		if(show_all_hostgroups == FALSE && strcmp(temp_hostgroup->group_name, hostgroup_name))
			continue;

		if(is_authorized_for_hostgroup(temp_hostgroup, &current_authdata) == FALSE)
			continue;

		printf("<b>%s</b>\n", temp_hostgroup->alias);

		printf("<table columns='2' align='LL'>\n");

		/* check all hosts in this hostgroup */
		for(temp_member = temp_hostgroup->members; temp_member != NULL; temp_member = temp_member->next) {

			temp_host = find_host(temp_member->host_name);
			if(temp_host == NULL)
				continue;

			if(is_host_member_of_hostgroup(temp_hostgroup, temp_host) == FALSE)
				continue;

			temp_hoststatus = find_hoststatus(temp_host->name);
			if(temp_hoststatus == NULL)
				continue;

			printf("<tr><td><anchor title='%s'>", temp_host->name);
			if(temp_hoststatus->status == SD_HOST_UP)
				printf("UP");
			else if(temp_hoststatus->status == HOST_PENDING)
				printf("PND");
			else if(temp_hoststatus->status == SD_HOST_DOWN)
				printf("DWN");
			else if(temp_hoststatus->status == SD_HOST_UNREACHABLE)
				printf("UNR");
			else
				printf("???");
			printf("<go href='%s' method='post'><postfield name='host' value='%s'/></go></anchor></td>", STATUSWML_CGI, temp_host->name);
			printf("<td>%s</td></tr>\n", temp_host->name);
			}

		printf("</table>\n");

		printf("<br/>\n");
		}

	if(show_all_hostgroups == FALSE)
		printf("<b><anchor title='View All Hostgroups'>View All Hostgroups<go href='%s' method='post'><postfield name='hostgroup' value='all'/><postfield name='style' value='overview'/></go></anchor></b>\n", STATUSWML_CGI);

	printf("</p>\n");
	printf("</card>\n");

	return;
	}
Esempio n. 4
0
static int meta_data_to_json (char *buffer, size_t buffer_size, /* {{{ */
    meta_data_t *meta)
{
  size_t offset = 0;
  char **keys = NULL;
  int keys_num;
  int status;
  int i;

  buffer[0] = 0;

  if (meta == NULL)
    return (EINVAL);

#define BUFFER_ADD(...) do { \
  status = ssnprintf (buffer + offset, buffer_size - offset, \
      __VA_ARGS__); \
  if (status < 1) \
    return (-1); \
  else if (((size_t) status) >= (buffer_size - offset)) \
    return (-ENOMEM); \
  else \
    offset += ((size_t) status); \
} while (0)

  keys_num = meta_data_toc (meta, &keys);
  if (keys_num == 0)
  {
    sfree (keys);
    return (0);
  }

  for (i = 0; i < keys_num; ++i)
  {
    int type;
    char *key = keys[i];

    type = meta_data_type (meta, key);
    if (type == MD_TYPE_STRING)
    {
      char *value = NULL;
      if (meta_data_get_string (meta, key, &value) == 0)
      {
        char temp[512] = "";
        escape_string (temp, sizeof (temp), value);
        sfree (value);
        BUFFER_ADD (",\"%s\":%s", key, temp);
      }
    }
    else if (type == MD_TYPE_SIGNED_INT)
    {
      int64_t value = 0;
      if (meta_data_get_signed_int (meta, key, &value) == 0)
        BUFFER_ADD (",\"%s\":%"PRIi64, key, value);
    }
    else if (type == MD_TYPE_UNSIGNED_INT)
    {
      uint64_t value = 0;
      if (meta_data_get_unsigned_int (meta, key, &value) == 0)
        BUFFER_ADD (",\"%s\":%"PRIu64, key, value);
    }
    else if (type == MD_TYPE_DOUBLE)
    {
      double value = 0.0;
      if (meta_data_get_double (meta, key, &value) == 0)
        BUFFER_ADD (",\"%s\":%f", key, value);
    }
    else if (type == MD_TYPE_BOOLEAN)
    {
      _Bool value = 0;
      if (meta_data_get_boolean (meta, key, &value) == 0)
        BUFFER_ADD (",\"%s\":%s", key, value ? "true" : "false");
    }

    free (key);
  } /* for (keys) */
  free (keys);

  if (offset <= 0)
    return (ENOENT);

  buffer[0] = '{'; /* replace leading ',' */
  BUFFER_ADD ("}");

#undef BUFFER_ADD

  return (0);
} /* }}} int meta_data_to_json */
Esempio n. 5
0
// Figure out which of the results the host currently has
// should be aborted outright, or aborted if not started yet
//
int send_result_abort() {
    int aborts_sent = 0;
    int retval = 0;
    DB_IN_PROGRESS_RESULT result;
    std::string result_names;
    unsigned int i;

    if (g_request->other_results.size() == 0) {
        return 0;
    }

    // build list of result names
    //
    for (i=0; i<g_request->other_results.size(); i++) {
        OTHER_RESULT& orp=g_request->other_results[i];
        orp.abort = true;
            // if the host has a result not in the DB, abort it
        orp.abort_if_not_started = false;
        orp.reason = ABORT_REASON_NOT_FOUND;
        if (i > 0) result_names.append(", ");
        result_names.append("'");
        char buf[1024];
        strcpy(buf, orp.name);
        escape_string(buf, 1024);
        result_names.append(buf);
        result_names.append("'");
    }

    // look up selected fields from the results and their WUs,
    // and decide if they should be aborted
    //
    while (!(retval = result.enumerate(g_reply->host.id, result_names.c_str()))) {
        for (i=0; i<g_request->other_results.size(); i++) {
            OTHER_RESULT& orp = g_request->other_results[i];
            if (!strcmp(orp.name, result.result_name)) {
                if (result.error_mask&WU_ERROR_CANCELLED ) {
                    // if the WU has been canceled, abort the result
                    //
                    orp.abort = true;
                    orp.abort_if_not_started = false;
                    orp.reason = ABORT_REASON_WU_CANCELLED;
                } else if (result.assimilate_state == ASSIMILATE_DONE) {
                    // if the WU has been assimilated, abort if not started
                    //
                    orp.abort = false;
                    orp.abort_if_not_started = true;
                    orp.reason = ABORT_REASON_ASSIMILATED;
                } else if (result.server_state == RESULT_SERVER_STATE_OVER
                    && result.outcome == RESULT_OUTCOME_NO_REPLY
                ) {
                    // if timed out, abort if not started
                    //
                    orp.abort = false;
                    orp.abort_if_not_started = true;
                    orp.reason = ABORT_REASON_TIMED_OUT;
                } else {
                    // all is good with the result - let it process
                    orp.abort = false;
                    orp.abort_if_not_started = false;
                }
                break;
            }
        }
    }

    // If enumeration returned an error, don't send any aborts
    //
    if (retval && (retval != ERR_DB_NOT_FOUND)) {
        return retval;
    }

    // loop through the results and send the appropriate message (if any)
    //
    for (i=0; i<g_request->other_results.size(); i++) {
        OTHER_RESULT& orp = g_request->other_results[i];
        if (orp.abort) {
            g_reply->result_aborts.push_back(orp.name);
            log_messages.printf(MSG_NORMAL,
                "[HOST#%d]: Send result_abort for result %s; reason: %s\n",
                g_reply->host.id, orp.name, reason_str(orp.reason)
            );
            // send user message
            char buf[256];
            sprintf(buf, "Result %s is no longer usable", orp.name);
            g_reply->insert_message(buf, "low");
        } else if (orp.abort_if_not_started) {
            g_reply->result_abort_if_not_starteds.push_back(orp.name);
            log_messages.printf(MSG_NORMAL,
                "[HOST#%d]: Send result_abort_if_unstarted for result %s; reason %d\n",
                g_reply->host.id, orp.name, orp.reason
            );
        }
    }

    return aborts_sent;
}
int format_graphite (char *buffer, size_t buffer_size,
    data_set_t const *ds, value_list_t const *vl,
    char const *prefix, char const *postfix, char const escape_char,
    unsigned int flags)
{
    int status = 0;
    int i;
    int buffer_pos = 0;

    gauge_t *rates = NULL;
    if (flags & GRAPHITE_STORE_RATES)
      rates = uc_get_rate (ds, vl);

    for (i = 0; i < ds->ds_num; i++)
    {
        char const *ds_name = NULL;
        char        key[10*DATA_MAX_NAME_LEN];
        char        values[512];
        size_t      message_len;
        char        message[1024];

        if ((flags & GRAPHITE_ALWAYS_APPEND_DS)
            || (ds->ds_num > 1))
          ds_name = ds->ds[i].name;

        /* Copy the identifier to `key' and escape it. */
        status = gr_format_name (key, sizeof (key), vl, ds_name,
                    prefix, postfix, escape_char, flags);
        if (status != 0)
        {
            ERROR ("format_graphite: error with gr_format_name");
            sfree (rates);
            return (status);
        }

        escape_string (key, sizeof (key));
        /* Convert the values to an ASCII representation and put that into
         * `values'. */
        status = gr_format_values (values, sizeof (values), i, ds, vl, rates);
        if (status != 0)
        {
            ERROR ("format_graphite: error with gr_format_values");
            sfree (rates);
            return (status);
        }

        /* Compute the graphite command */
        message_len = (size_t) ssnprintf (message, sizeof (message),
                "%s %s %u\r\n",
                key,
                values,
                (unsigned int) CDTIME_T_TO_TIME_T (vl->time));
        if (message_len >= sizeof (message)) {
            ERROR ("format_graphite: message buffer too small: "
                    "Need %zu bytes.", message_len + 1);
            sfree (rates);
            return (-ENOMEM);
        }

        /* Append it in case we got multiple data set */
        if ((buffer_pos + message_len) >= buffer_size)
        {
            ERROR ("format_graphite: target buffer too small");
            sfree (rates);
            return (-ENOMEM);
        }
        memcpy((void *) (buffer + buffer_pos), message, message_len);
        buffer_pos += message_len;
    }
    sfree (rates);
    return (status);
} /* int format_graphite */
Esempio n. 7
0
	void http_tracker_connection::start()
	{
		std::string url = tracker_req().url;

		if (tracker_req().kind == tracker_request::scrape_request)
		{
			// find and replace "announce" with "scrape"
			// in request

			std::size_t pos = url.find("announce");
			if (pos == std::string::npos)
			{
				tracker_connection::fail(error_code(errors::scrape_not_available));
				return;
			}
			url.replace(pos, 8, "scrape");
		}
		
#if TORRENT_USE_I2P
		bool i2p = is_i2p_url(url);
#else
		static const bool i2p = false;
#endif

		aux::session_settings const& settings = m_man.settings();

		// if request-string already contains
		// some parameters, append an ampersand instead
		// of a question mark
		size_t arguments_start = url.find('?');
		if (arguments_start != std::string::npos)
			url += "&";
		else
			url += "?";
		
		if (tracker_req().kind == tracker_request::announce_request)
		{
			const char* event_string[] = {"completed", "started", "stopped", "paused"};

			char str[1024];
			const bool stats = tracker_req().send_stats;
			snprintf(str, sizeof(str)
				, "info_hash=%s"
				"&peer_id=%s"
				"&port=%d"
				"&uploaded=%" PRId64
				"&downloaded=%" PRId64
				"&left=%" PRId64
				"&corrupt=%" PRId64
				"&key=%08X"
				"%s%s" // event
				"&numwant=%d"
				"&compact=1"
				"&no_peer_id=1"
				, escape_string((const char*)&tracker_req().info_hash[0], 20).c_str()
				, escape_string((const char*)&tracker_req().pid[0], 20).c_str()
				// the i2p tracker seems to verify that the port is not 0,
				// even though it ignores it otherwise
				, i2p ? 1 : tracker_req().listen_port
				, stats ? tracker_req().uploaded : 0
				, stats ? tracker_req().downloaded : 0
				, stats ? tracker_req().left : 0
				, stats ? tracker_req().corrupt : 0
				, tracker_req().key
				, (tracker_req().event != tracker_request::none) ? "&event=" : ""
				, (tracker_req().event != tracker_request::none) ? event_string[tracker_req().event - 1] : ""
				, tracker_req().num_want);
			url += str;
#if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS)
			if (settings.get_int(settings_pack::in_enc_policy) != settings_pack::pe_disabled
				&& settings.get_bool(settings_pack::announce_crypto_support))
				url += "&supportcrypto=1";
#endif
			if (stats && settings.get_bool(settings_pack::report_redundant_bytes))
			{
				url += "&redundant=";
				url += to_string(tracker_req().redundant).elems;
			}
			if (!tracker_req().trackerid.empty())
			{
				std::string id = tracker_req().trackerid;
				url += "&trackerid=";
				url += escape_string(id.c_str(), id.length());
			}

#if TORRENT_USE_I2P
			if (i2p && tracker_req().i2pconn)
			{
				url += "&ip=";
				url += escape_string(tracker_req().i2pconn->local_endpoint().c_str()
					, tracker_req().i2pconn->local_endpoint().size());
				url += ".i2p";
			}
			else
#endif
			if (!settings.get_bool(settings_pack::anonymous_mode))
			{
				std::string announce_ip = settings.get_str(settings_pack::announce_ip);
				if (!announce_ip.empty())
				{
					url += "&ip=" + escape_string(announce_ip.c_str(), announce_ip.size());
				}
// TODO: support this somehow
/*				else if (settings.get_bool(settings_pack::announce_double_nat)
					&& is_local(m_ses.listen_address()))
				{
					// only use the global external listen address here
					// if it turned out to be on a local network
					// since otherwise the tracker should use our
					// source IP to determine our origin
					url += "&ip=" + print_address(m_ses.listen_address());
				}
*/
			}
		}

		m_tracker_connection.reset(new http_connection(get_io_service(), m_man.host_resolver()
			, boost::bind(&http_tracker_connection::on_response, shared_from_this(), _1, _2, _3, _4)
			, true, settings.get_int(settings_pack::max_http_recv_buffer_size)
			, boost::bind(&http_tracker_connection::on_connect, shared_from_this(), _1)
			, boost::bind(&http_tracker_connection::on_filter, shared_from_this(), _1, _2)
#ifdef TORRENT_USE_OPENSSL
			, tracker_req().ssl_ctx
#endif
			));

		int timeout = tracker_req().event==tracker_request::stopped
			?settings.get_int(settings_pack::stop_tracker_timeout)
			:settings.get_int(settings_pack::tracker_completion_timeout);

		// when sending stopped requests, prefer the cached DNS entry
		// to avoid being blocked for slow or failing responses. Chances
		// are that we're shutting down, and this should be a best-effort
		// attempt. It's not worth stalling shutdown.
		proxy_settings ps(settings);
		m_tracker_connection->get(url, seconds(timeout)
			, tracker_req().event == tracker_request::stopped ? 2 : 1
			, &ps, 5, settings.get_bool(settings_pack::anonymous_mode)
				? "" : settings.get_str(settings_pack::user_agent)
			, bind_interface()
			, tracker_req().event == tracker_request::stopped
				? resolver_interface::prefer_cache
				: resolver_interface::abort_on_shutdown
			, tracker_req().auth
#if TORRENT_USE_I2P
			, tracker_req().i2pconn
#endif
			);

		// the url + 100 estimated header size
		sent_bytes(url.size() + 100);

#if defined TORRENT_LOGGING

		boost::shared_ptr<request_callback> cb = requester();
		if (cb)
		{
			cb->debug_log("==> TRACKER_REQUEST [ url: %s ]", url.c_str());
		}
#endif
	}
Esempio n. 8
0
 ostream& json::to_stream( ostream& out, const fc::string& str )
 {
      escape_string( str, out );
      return out;
 }
Esempio n. 9
0
int main(int argc , char * argv[]){
  struct abctune * tunes, * tune;
  struct abcsym * sym;
  int n_tunes = 1, debug_flag=1, i;
  char info_type;

  abc_init((void *(*)(int sz)) malloc,
           free, 
           0,
           sizeof (struct SYMBOL) - sizeof (struct abcsym),
           1);

  if(argc == 2) { tunes = abc_parse(fslurp(argv[1])) ; }
  else          { tunes = abc_parse(fslurp("x.abc")) ; }

/* short lengthx[4]; */
/* printf("\n>>>>>>>>>>>>>%d\n",sizeof lengthx[0]); */
  printf("{"); // begin of structure
  printf("deco_tb => {"); // begin of deco_tb
  int o=0, first_deco=1;
  for(o=0; o<128; o++) {
    if (deco_tb[o]) { 
      if (first_deco) { first_deco = 0; }
      else            { printf(","); }
      printf("%d=>\"%s\"", o, deco_tb[o]); 
    }
  }
  printf("},"); // end of deco_tb
  if (debug_flag) printf("\n");

  printf("tunes => {"); // begin of tunes
  if (debug_flag) printf("\n");
  for (tune = tunes; tune != 0; tune = tune->next){

    printf("%d => {", n_tunes); // begin of tune
    if (debug_flag) printf("\n");

    printf("abc_vers=>%d,",tune->abc_vers);  
    if (tune->client_data)
      printf("client_data=>%s,",(char *)tune->client_data);  
    else
      printf("client_data=>\"\",");  
    printf("micro_tb=>[");
    for (i=0; i<MAXMICRO; i++) {
      if (i>0) printf(",");
      printf("%d",tune->micro_tb[i]); 
    }
    printf("],");
    if (debug_flag) printf("\n");
    printf("symbols=>["); // begin of symbols

    for (sym = tune->first_sym; sym != 0; sym = sym->next){
      printf("{"); // begin of symbol

      printf("type=>%d,"        ,sym->type);  
      printf("state=>%d,"       ,sym->state);
      printf("colnum=>%d,"      ,sym->colnum);  
      printf("flags=>%d,"       ,sym->flags);
      printf("linenum=>%d,"     ,sym->linenum);  
      printf("text=>\"%s\","    ,escape_string(sym->text));   
      printf("comment=>\"%s\"," ,escape_string(sym->comment));
      printf("info=>{"); // begin of info

      if (sym->type == 1) { // symbols of type 1 (Info)
        info_type = sym->text[0];
        switch (info_type) {
          case 'K': // Key
            printf("sf=>%d,"      ,sym->u.key.sf);
            printf("empty=>%d,"   ,sym->u.key.empty); 
            printf("exp=>%d,"     ,sym->u.key.exp); 
            printf("mode=>%d,"    ,sym->u.key.mode); 
            printf("nacc=>%d,"    ,sym->u.key.nacc); 
            printf("octave=>%d,"  ,sym->u.key.octave); 
            printf("pits=>[");
            for (i=0; i<8; i++) {
              if (i>0) printf(",");
              printf("%d",sym->u.key.pits[i]); 
            }
            printf("],");
            printf("accs=>[");
            for (i=0; i<8; i++) {
              if (i>0) printf(",");
              printf("%d",sym->u.key.accs[i]); 
            }
            printf("]");
            break;
          case 'L': // Length
            printf("base_length=>%d",sym->u.length.base_length);
            break;
          case 'M': // Meter
            printf("wmeasure=>%d,"  ,sym->u.meter.wmeasure); 
            printf("nmeter=>%d,"    ,sym->u.meter.nmeter); 
            printf("expdur=>%d,"    ,sym->u.meter.expdur); 
            printf("meter=>[");
            for (i=0; i<sym->u.meter.nmeter; i++){
              if (i>0) printf(",");
              printf("{");
              printf("top=>\"%s\"," ,escape_string(sym->u.meter.meter[i].top)); 
              printf("bot=>\"%s\""  ,escape_string(sym->u.meter.meter[i].bot));
              printf("}");
            }
            printf("]");
            break;
          case 'Q': // Tempo
            printf("str1=>\"%s\","  ,escape_string(sym->u.tempo.str1));
            printf("length=>[");
            for (i=0; i<4; i++) {
              if (i>0) printf(",");
              printf("%d",sym->u.tempo.length[i]);
/* printf("\n\n\n\n\tlength:%d\n\n\n\n",sym->u.tempo.length[i]); */
            }
            printf("],");
/* printf("\n\n\n\n\tvalue:%s\n\n\n\n",sym->u.tempo.value); */
            printf("value=>\"%s\"," ,escape_string(sym->u.tempo.value)); 
            printf("str2=>\"%s\""   ,escape_string(sym->u.tempo.str2)); 
            break;
          case 'V': // Voice
/* printf("\n\n\n\n\tvoice_id:%s\n\n\n\n",sym->u.voice.id); */
            printf("id=>\"%s\","    ,escape_string(sym->u.voice.id));
            printf("fname=>\"%s\"," ,escape_string(sym->u.voice.fname));
            printf("nname=>\"%s\"," ,escape_string(sym->u.voice.nname));
            printf("voice=>%d,"     ,sym->u.voice.voice); 
            printf("octave=>%d,"    ,sym->u.voice.octave); 
            printf("scale=>%f,"     ,sym->u.voice.scale); 
            printf("merge=>%d,"     ,sym->u.voice.merge); 
            printf("stem=>%d,"      ,sym->u.voice.stem); 
            printf("gstem=>%d,"     ,sym->u.voice.gstem); 
            printf("dyn=>%d,"       ,sym->u.voice.dyn); 
            printf("lyrics=>%d,"    ,sym->u.voice.lyrics); 
            printf("gchord=>%d"     ,sym->u.voice.gchord); 
            break;
          case 'U': // Symbols Redefition
            printf("symbol=>%d,"    ,sym->u.user.symbol); 
            printf("value=>%d"      ,sym->u.user.value); 
            break;
        }
      } // end of type 1

      if (sym->type == 3) { // symbols of type 3 (Clef)
        printf("name=>\"%s\",",escape_string(sym->u.clef.name)); 
        printf("staffscale=>%f,",sym->u.clef.staffscale); 
        printf("stafflines=>%d,",sym->u.clef.stafflines); 
        printf("type=>%d,",sym->u.clef.type); 
        printf("line=>%d,",sym->u.clef.line); 
        printf("octave=>%d,",sym->u.clef.octave); 
        printf("transpose=>%d,",sym->u.clef.transpose); 
        printf("invis=>%d,",sym->u.clef.invis); 
        printf("check_pitch=>%d",sym->u.clef.check_pitch); 
      } // end of type 3

      if (sym->type == 4 || sym->type == 5) { // symbols of type 4 and 5 (Note, Rest)
        printf("pits=>[");
        for (i=0; i<MAXHD; i++) {
          if (i>0) printf(",");
          printf("%d",sym->u.note.pits[i]); 
        }
        printf("],");
        printf("lens=>[");
        for (i=0; i<MAXHD; i++) {
          if (i>0) printf(",");
          printf("%d",sym->u.note.lens[i]); 
        }
        printf("],");
        printf("accs=>[");
        for (i=0; i<MAXHD; i++) {
          if (i>0) printf(",");
          printf("%d",sym->u.note.accs[i]); 
        }
        printf("],");
        printf("sl1=>[");
        for (i=0; i<MAXHD; i++) {
          if (i>0) printf(",");
          printf("%d",sym->u.note.sl1[i]); 
        }
        printf("],");
        printf("sl2=>[");
        for (i=0; i<MAXHD; i++) {
          if (i>0) printf(",");
          printf("%d",sym->u.note.sl2[i]); 
        }
        printf("],");
        printf("ti1=>[");
        for (i=0; i<MAXHD; i++) {
          if (i>0) printf(",");
          printf("%d",sym->u.note.ti1[i]); 
        }
        printf("],");
        printf("decs=>[");
        for (i=0; i<MAXHD; i++) {
          if (i>0) printf(",");
          printf("%d",sym->u.note.decs[i]); 
        }
        printf("],");
        printf("chlen=>%d,",sym->u.note.chlen); 
        printf("nhd=>%d,",sym->u.note.nhd); 
        printf("slur_st=>%d,",sym->u.note.slur_st); 
        printf("slur_end=>%d,",sym->u.note.slur_end); 
        printf("brhythm=>%d,",sym->u.note.brhythm); 
        printf("dc=>{");
        printf("n=>%d," ,sym->u.note.dc.n); 
        printf("h=>%d," ,sym->u.note.dc.h); 
        printf("s=>%d," ,sym->u.note.dc.s); 
        printf("t=>[");
        for (i=0; i<MAXDC; i++) {
          if (i>0) printf(",");
          printf("%d",sym->u.note.dc.t[i]); 
        }
        printf("]");
        printf("}"); // end of dc
      } // end of type 4, 5

      if (sym->type == 6 || sym->type == 8 || sym->type == 9) { // symbols of type 6, 8, 9 (Bar, Multi-measure Rest (mrest) and Measure Repeat (mrep))
        printf("type=>%d,",sym->u.bar.type); 
        printf("repeat_bar=>%d,",sym->u.bar.repeat_bar); 
        printf("len=>%d,",sym->u.bar.len); 
        printf("dotted=>%d,",sym->u.bar.dotted); 
        printf("dc=>{");
        printf("n=>%d," ,sym->u.bar.dc.n); 
        printf("h=>%d," ,sym->u.bar.dc.h); 
        printf("s=>%d," ,sym->u.bar.dc.s); 
        printf("t=>[");
        for (i=0; i<MAXDC; i++) {
          if (i>0) printf(",");
          printf("%d",sym->u.bar.dc.t[i]); 
        }
        printf("]");
        printf("}");
      } // end of type 6, 8, 9

      if (sym->type == 7) { // symbols of type 7 (End of Line (eoln))
        printf("type=>%d",sym->u.eoln.type); 
      } // end of type 7

      if (sym->type == 10) { // symbols of type 10 (Voice Overlay (v_over))
        printf("type=>%d,",sym->u.v_over.type); 
        printf("voice=>%d",sym->u.v_over.voice); 
      } // end of type 10

      if (sym->type == 11) { // symbols of type 11 (Tuplet)
        printf("p_plet=>%d,",sym->u.tuplet.p_plet); 
        printf("q_plet=>%d,",sym->u.tuplet.q_plet); 
        printf("r_plet=>%d",sym->u.tuplet.r_plet); 
      } // end of type 11

      printf("}"); // end of info

      printf("}"); // end of symbol
      if (sym->next != 0) printf(",");  
      if (debug_flag) printf("\n");
    }

    printf("]"); // end of symbols
    printf("}"); // end of tune
    if (tune->next != 0) printf(",");  
    n_tunes++;
  }
  printf("}");  // end of tunes
  printf("}");  // end of structure

  return 0;
}
Esempio n. 10
0
char* sexp_opts(struct opts* opt) {
  void* ret=q("");
  for(;opt;opt=opt->next)
    ret=s_cat(ret,q("(\""),q(opt->name),q("\"\""),escape_string((char*)opt->value),q("\")"),NULL);
  return ret;
}
Esempio n. 11
0
static void drawpage(fz_context *ctx, fz_document *doc, int pagenum)
{
	fz_page *page;
	fz_display_list *list = NULL;
	fz_device *dev = NULL;
	int start;
	fz_cookie cookie = { 0 };
	int needshot = 0;

	fz_var(list);
	fz_var(dev);

	if (showtime)
	{
		start = gettime();
	}

	fz_try(ctx)
	{
		page = fz_load_page(doc, pagenum - 1);
	}
	fz_catch(ctx)
	{
		fz_rethrow_message(ctx, "cannot load page %d in file '%s'", pagenum, filename);
	}

	if (mujstest_file)
	{
		pdf_document *inter = pdf_specifics(doc);
		pdf_widget *widget = NULL;

		if (inter)
			widget = pdf_first_widget(inter, (pdf_page *)page);

		if (widget)
		{
			fprintf(mujstest_file, "GOTO %d\n", pagenum);
			needshot = 1;
		}
		for (;widget; widget = pdf_next_widget(widget))
		{
			fz_rect rect;
			int w, h, len;
			int type = pdf_widget_get_type(widget);

			pdf_bound_widget(widget, &rect);
			w = (rect.x1 - rect.x0);
			h = (rect.y1 - rect.y0);
			++mujstest_count;
			switch (type)
			{
			default:
				fprintf(mujstest_file, "%% UNKNOWN %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case PDF_WIDGET_TYPE_PUSHBUTTON:
				fprintf(mujstest_file, "%% PUSHBUTTON %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case PDF_WIDGET_TYPE_CHECKBOX:
				fprintf(mujstest_file, "%% CHECKBOX %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case PDF_WIDGET_TYPE_RADIOBUTTON:
				fprintf(mujstest_file, "%% RADIOBUTTON %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case PDF_WIDGET_TYPE_TEXT:
			{
				int maxlen = pdf_text_widget_max_len(inter, widget);
				int texttype = pdf_text_widget_content_type(inter, widget);

				/* If height is low, assume a single row, and base
				 * the width off that. */
				if (h < 10)
				{
					w = (w+h-1) / (h ? h : 1);
					h = 1;
				}
				/* Otherwise, if width is low, work off height */
				else if (w < 10)
				{
					h = (w+h-1) / (w ? w : 1);
					w = 1;
				}
				else
				{
					w = (w+9)/10;
					h = (h+9)/10;
				}
				len = w*h;
				if (len < 2)
					len = 2;
				if (len > maxlen)
					len = maxlen;
				fprintf(mujstest_file, "%% TEXT %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				switch (texttype)
				{
				default:
				case PDF_WIDGET_CONTENT_UNRESTRAINED:
					fprintf(mujstest_file, "TEXT %d ", mujstest_count);
					escape_string(mujstest_file, len-3, lorem);
					fprintf(mujstest_file, "\n");
					break;
				case PDF_WIDGET_CONTENT_NUMBER:
					fprintf(mujstest_file, "TEXT %d\n", mujstest_count);
					break;
				case PDF_WIDGET_CONTENT_SPECIAL:
#ifdef __MINGW32__
					fprintf(mujstest_file, "TEXT %I64d\n", 46702919800LL + mujstest_count);
#else
					fprintf(mujstest_file, "TEXT %lld\n", 46702919800LL + mujstest_count);
#endif
					break;
				case PDF_WIDGET_CONTENT_DATE:
					fprintf(mujstest_file, "TEXT Jun %d 1979\n", 1 + ((13 + mujstest_count) % 30));
					break;
				case PDF_WIDGET_CONTENT_TIME:
					++mujstest_count;
					fprintf(mujstest_file, "TEXT %02d:%02d\n", ((mujstest_count/60) % 24), mujstest_count % 60);
					break;
				}
				break;
			}
			case PDF_WIDGET_TYPE_LISTBOX:
				fprintf(mujstest_file, "%% LISTBOX %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case PDF_WIDGET_TYPE_COMBOBOX:
				fprintf(mujstest_file, "%% COMBOBOX %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			}
			fprintf(mujstest_file, "CLICK %0.2f %0.2f\n", (rect.x0+rect.x1)/2, (rect.y0+rect.y1)/2);
		}
	}

	if (uselist)
	{
		fz_try(ctx)
		{
			list = fz_new_display_list(ctx);
			dev = fz_new_list_device(ctx, list);
			fz_run_page(doc, page, dev, &fz_identity, &cookie);
		}
		fz_always(ctx)
		{
			fz_free_device(dev);
			dev = NULL;
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_free_page(doc, page);
			fz_rethrow_message(ctx, "cannot draw page %d in file '%s'", pagenum, filename);
		}
	}

	if (showxml)
	{
		fz_try(ctx)
		{
			dev = fz_new_trace_device(ctx);
			if (list)
				fz_run_display_list(list, dev, &fz_identity, &fz_infinite_rect, &cookie);
			else
				fz_run_page(doc, page, dev, &fz_identity, &cookie);
		}
		fz_always(ctx)
		{
			fz_free_device(dev);
			dev = NULL;
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_free_page(doc, page);
			fz_rethrow(ctx);
		}
	}

	if (showtext)
	{
		fz_text_page *text = NULL;

		fz_var(text);

		fz_try(ctx)
		{
			text = fz_new_text_page(ctx);
			dev = fz_new_text_device(ctx, sheet, text);
			if (showtext == TEXT_HTML)
				fz_disable_device_hints(dev, FZ_IGNORE_IMAGE);
			if (list)
				fz_run_display_list(list, dev, &fz_identity, &fz_infinite_rect, &cookie);
			else
				fz_run_page(doc, page, dev, &fz_identity, &cookie);
			fz_free_device(dev);
			dev = NULL;
			if (showtext == TEXT_XML)
			{
				fz_print_text_page_xml(ctx, out, text);
			}
			else if (showtext == TEXT_HTML)
			{
				fz_analyze_text(ctx, sheet, text);
				fz_print_text_page_html(ctx, out, text);
			}
			else if (showtext == TEXT_PLAIN)
			{
				fz_print_text_page(ctx, out, text);
				fz_printf(out, "\f\n");
			}
		}
		fz_always(ctx)
		{
			fz_free_device(dev);
			dev = NULL;
			fz_free_text_page(ctx, text);
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_free_page(doc, page);
			fz_rethrow(ctx);
		}
	}

	if (showmd5 || showtime)
		printf("page %s %d", filename, pagenum);

	if (pdfout)
	{
		fz_matrix ctm;
		fz_rect bounds, tbounds;
		pdf_page *newpage;

		fz_bound_page(doc, page, &bounds);
		fz_rotate(&ctm, rotation);
		tbounds = bounds;
		fz_transform_rect(&tbounds, &ctm);

		newpage = pdf_create_page(pdfout, bounds, 72, 0);

		fz_try(ctx)
		{
			dev = pdf_page_write(pdfout, newpage);
			if (list)
				fz_run_display_list(list, dev, &ctm, &tbounds, &cookie);
			else
				fz_run_page(doc, page, dev, &ctm, &cookie);
			fz_free_device(dev);
			dev = NULL;
		}
		fz_always(ctx)
		{
			fz_free_device(dev);
			dev = NULL;
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_free_page(doc, page);
			fz_rethrow(ctx);
		}
		pdf_insert_page(pdfout, newpage, INT_MAX);
		pdf_free_page(pdfout, newpage);
	}

	if (output && output_format == OUT_SVG)
	{
		float zoom;
		fz_matrix ctm;
		fz_rect bounds, tbounds;
		char buf[512];
		FILE *file;
		fz_output *out;

		if (!strcmp(output, "-"))
			file = stdout;
		else
		{
			sprintf(buf, output, pagenum);
			file = fopen(buf, "wb");
			if (file == NULL)
				fz_throw(ctx, FZ_ERROR_GENERIC, "cannot open file '%s': %s", buf, strerror(errno));
		}

		out = fz_new_output_with_file(ctx, file);

		fz_bound_page(doc, page, &bounds);
		zoom = resolution / 72;
		fz_pre_rotate(fz_scale(&ctm, zoom, zoom), rotation);
		tbounds = bounds;
		fz_transform_rect(&tbounds, &ctm);

		fz_try(ctx)
		{
			dev = fz_new_svg_device(ctx, out, tbounds.x1-tbounds.x0, tbounds.y1-tbounds.y0);
			if (list)
				fz_run_display_list(list, dev, &ctm, &tbounds, &cookie);
			else
				fz_run_page(doc, page, dev, &ctm, &cookie);
			fz_free_device(dev);
			dev = NULL;
		}
		fz_always(ctx)
		{
			fz_free_device(dev);
			dev = NULL;
			fz_close_output(out);
			if (file != stdout)
				fclose(file);
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_free_page(doc, page);
			fz_rethrow(ctx);
		}
	}
Esempio n. 12
0
void
g_log_default_handler (const gchar   *log_domain,
		       GLogLevelFlags log_level,
		       const gchar   *message,
		       gpointer	      unused_data)
{
  gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
  gchar level_prefix[STRING_BUFFER_SIZE], *string;
  GString *gstring;
  int fd;

  /* we can be called externally with recursion for whatever reason */
  if (log_level & G_LOG_FLAG_RECURSION)
    {
      _g_log_fallback_handler (log_domain, log_level, message, unused_data);
      return;
    }

  g_messages_prefixed_init ();

  fd = mklevel_prefix (level_prefix, log_level);

  gstring = g_string_new (NULL);
  if (log_level & ALERT_LEVELS)
    g_string_append (gstring, "\n");
  if (!log_domain)
    g_string_append (gstring, "** ");

  if ((g_log_msg_prefix & log_level) == log_level)
    {
      const gchar *prg_name = g_get_prgname ();
      
      if (!prg_name)
	g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
      else
	g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
    }

  if (log_domain)
    {
      g_string_append (gstring, log_domain);
      g_string_append_c (gstring, '-');
    }
  g_string_append (gstring, level_prefix);

  g_string_append (gstring, ": ");
  if (!message)
    g_string_append (gstring, "(NULL) message");
  else
    {
      GString *msg;
      const gchar *charset;

      msg = g_string_new (message);
      escape_string (msg);

      if (g_get_charset (&charset))
	g_string_append (gstring, msg->str);	/* charset is UTF-8 already */
      else
	{
	  string = strdup_convert (msg->str, charset);
	  g_string_append (gstring, string);
	  g_free (string);
	}

      g_string_free (msg, TRUE);
    }
  if (is_fatal)
    g_string_append (gstring, "\naborting...\n");
  else
    g_string_append (gstring, "\n");

  string = g_string_free (gstring, FALSE);

  write_string (fd, string);
  g_free (string);
}
Esempio n. 13
0
/* displays host status */
void display_host(void) {
	host *temp_host;
	hoststatus *temp_hoststatus;
	char last_check[MAX_DATETIME_LENGTH];
	int days;
	int hours;
	int minutes;
	int seconds;
	time_t current_time;
	time_t t;
	char state_duration[48];
	int found;

	/**** MAIN SCREEN (CARD 1) ****/
	printf("<card id='card1' title='Host Status'>\n");
	printf("<p align='center' mode='nowrap'>\n");
	printf("<b>Host '%s'</b><br/>\n", host_name);

	/* find the host */
	temp_host = find_host(host_name);
	temp_hoststatus = find_hoststatus(host_name);
	if (temp_host == NULL || temp_hoststatus == NULL) {

		printf("<b>Error: Could not find host!</b>\n");
		printf("</p>\n");
		printf("</card>\n");
		return;
	}

	/* check authorization */
	if (is_authorized_for_host(temp_host, &current_authdata) == FALSE) {

		printf("<b>Error: Not authorized for host!</b>\n");
		printf("</p>\n");
		printf("</card>\n");
		return;
	}


	printf("<table columns='2' align='LL'>\n");

	printf("<tr><td>Status:</td><td>");
	if (temp_hoststatus->status == HOST_UP)
		printf("UP");
	else if (temp_hoststatus->status == HOST_PENDING)
		printf("PENDING");
	else if (temp_hoststatus->status == HOST_DOWN)
		printf("DOWN");
	else if (temp_hoststatus->status == HOST_UNREACHABLE)
		printf("UNREACHABLE");
	else
		printf("?");
	printf("</td></tr>\n");

	printf("<tr><td>Info:</td><td>%s</td></tr>\n", temp_hoststatus->plugin_output);

	get_time_string(&temp_hoststatus->last_check, last_check, sizeof(last_check) - 1, SHORT_DATE_TIME);
	printf("<tr><td>Last Check:</td><td>%s</td></tr>\n", last_check);

	current_time = time(NULL);
	if (temp_hoststatus->last_state_change == (time_t)0)
		t = current_time - program_start;
	else
		t = current_time - temp_hoststatus->last_state_change;
	get_time_breakdown((unsigned long)t, &days, &hours, &minutes, &seconds);
	snprintf(state_duration, sizeof(state_duration) - 1, "%2dd %2dh %2dm %2ds%s", days, hours, minutes, seconds, (temp_hoststatus->last_state_change == (time_t)0) ? "+" : "");
	printf("<tr><td>Duration:</td><td>%s</td></tr>\n", state_duration);

	printf("<tr><td>Properties:</td><td>");
	found = 0;
	if (temp_hoststatus->checks_enabled == FALSE) {
		printf("%sChecks disabled", (found == 1) ? ", " : "");
		found = 1;
	}
	if (temp_hoststatus->notifications_enabled == FALSE) {
		printf("%sNotifications disabled", (found == 1) ? ", " : "");
		found = 1;
	}
	if (temp_hoststatus->problem_has_been_acknowledged == TRUE) {
		printf("%sProblem acknowledged", (found == 1) ? ", " : "");
		found = 1;
	}
	if (temp_hoststatus->scheduled_downtime_depth > 0) {
		printf("%sIn scheduled downtime", (found == 1) ? ", " : "");
		found = 1;
	}
	if (found == 0)
		printf("N/A");
	printf("</td></tr>\n");

	printf("</table>\n");
	printf("<br/>\n");
	printf("<b><anchor title='View Services'>View Services<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='style' value='servicedetail'/></go></anchor></b>\n", STATUSWML_CGI, escape_string(host_name));
	printf("<b><anchor title='Host Commands'>Host Commands<go href='#card2'/></anchor></b>\n");
	printf("</p>\n");

	printf("</card>\n");


	/**** COMMANDS SCREEN (CARD 2) ****/
	printf("<card id='card2' title='Host Commands'>\n");
	printf("<p align='center' mode='nowrap'>\n");
	printf("<b>Host Commands</b><br/>\n");

	printf("<b><anchor title='Ping Host'>Ping Host<go href='%s' method='post'><postfield name='ping' value='%s'/></go></anchor></b>\n", STATUSWML_CGI, temp_host->address);
	printf("<b><anchor title='Ping6 Host'>Ping6 Host<go href='%s' method='post'><postfield name='ping6' value='%s'/></go></anchor></b>\n", STATUSWML_CGI, temp_host->address6);
	printf("<b><anchor title='Traceroute'>Traceroute<go href='%s' method='post'><postfield name='traceroute' value='%s'/></go></anchor></b>\n", STATUSWML_CGI, temp_host->address);
	printf("<b><anchor title='Traceroute6'>Traceroute6<go href='%s' method='post'><postfield name='traceroute6' value='%s'/></go></anchor></b>\n", STATUSWML_CGI, temp_host->address6);

	if (temp_hoststatus->status != HOST_UP && temp_hoststatus->status != HOST_PENDING)
		printf("<b><anchor title='Acknowledge Problem'>Acknowledge Problem<go href='#card3'/></anchor></b>\n");

	if (temp_hoststatus->checks_enabled == FALSE)
		printf("<b><anchor title='Enable Host Checks'>Enable Host Checks<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", CMD_CGI, escape_string(host_name), CMD_ENABLE_HOST_CHECK, CMDMODE_COMMIT);
	else
		printf("<b><anchor title='Disable Host Checks'>Disable Host Checks<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", CMD_CGI, escape_string(host_name), CMD_DISABLE_HOST_CHECK, CMDMODE_COMMIT);

	if (temp_hoststatus->notifications_enabled == FALSE)
		printf("<b><anchor title='Enable Host Notifications'>Enable Host Notifications<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", CMD_CGI, escape_string(host_name), CMD_ENABLE_HOST_NOTIFICATIONS, CMDMODE_COMMIT);
	else
		printf("<b><anchor title='Disable Host Notifications'>Disable Host Notifications<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", CMD_CGI, escape_string(host_name), CMD_DISABLE_HOST_NOTIFICATIONS, CMDMODE_COMMIT);


	printf("<b><anchor title='Enable All Service Checks'>Enable All Service Checks<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", CMD_CGI, escape_string(host_name), CMD_ENABLE_HOST_SVC_CHECKS, CMDMODE_COMMIT);

	printf("<b><anchor title='Disable All Service Checks'>Disable All Service Checks<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", CMD_CGI, escape_string(host_name), CMD_DISABLE_HOST_SVC_CHECKS, CMDMODE_COMMIT);

	printf("<b><anchor title='Enable All Service Notifications'>Enable All Service Notifications<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", CMD_CGI, escape_string(host_name), CMD_ENABLE_HOST_SVC_NOTIFICATIONS, CMDMODE_COMMIT);

	printf("<b><anchor title='Disable All Service Notifications'>Disable All Service Notifications<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", CMD_CGI, escape_string(host_name), CMD_DISABLE_HOST_SVC_NOTIFICATIONS, CMDMODE_COMMIT);

	printf("</p>\n");

	printf("</card>\n");


	/**** ACKNOWLEDGEMENT SCREEN (CARD 3) ****/
	printf("<card id='card3' title='Acknowledge Problem'>\n");
	printf("<p align='center' mode='nowrap'>\n");
	printf("<b>Acknowledge Problem</b><br/>\n");
	printf("</p>\n");

	printf("<p align='center' mode='wrap'>\n");
	printf("<b>Your Name:</b><br/>\n");
	printf("<input name='name' value='%s' /><br/>\n", ((use_ssl_authentication) ? (getenv("SSL_CLIENT_S_DN_CN")) : (getenv("REMOTE_USER"))));
	printf("<b>Comment:</b><br/>\n");
	printf("<input name='comment' value='acknowledged by WAP'/>\n");

	printf("<do type='accept'>\n");
	printf("<go href='%s' method='post'><postfield name='host' value='%s'/><postfield name='com_author' value='$(name)'/><postfield name='com_data' value='$(comment)'/><postfield name='persistent' value=''/><postfield name='send_notification' value=''/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go>\n", CMD_CGI, escape_string(host_name), CMD_ACKNOWLEDGE_HOST_PROBLEM, CMDMODE_COMMIT);
	printf("</do>\n");

	printf("</p>\n");

	printf("</card>\n");

	return;
}
Esempio n. 14
0
/** @brief Yes we need a main function **/
int main(void) {
	int result = OK;

	/* get the variables passed to us */
	process_cgivars();

	/* reset internal CGI variables */
	reset_cgi_vars();

	/* read the CGI configuration file */
	result = read_cgi_config_file(get_cgi_config_location());
	if (result == ERROR) {
		document_header(CGI_ID, FALSE, "Error");
		print_error(get_cgi_config_location(), ERROR_CGI_CFG_FILE);
		document_footer(CGI_ID);
		return ERROR;
	}

	/* read the main configuration file */
	result = read_main_config_file(main_config_file);
	if (result == ERROR) {
		document_header(CGI_ID, FALSE, "Error");
		print_error(main_config_file, ERROR_CGI_MAIN_CFG);
		document_footer(CGI_ID);
		return ERROR;
	}

	/* read all object configuration data */
	result = read_all_object_configuration_data(main_config_file, READ_ALL_OBJECT_DATA);
	if (result == ERROR) {
		document_header(CGI_ID, FALSE, "Error");
		print_error(NULL, ERROR_CGI_OBJECT_DATA);
		document_footer(CGI_ID);
		return ERROR;
	}

	/* overwrite config value with amount we got via GET */
	result_limit = (get_result_limit != -1) ? get_result_limit : result_limit;

	document_header(CGI_ID, TRUE, "History");

	/* get authentication information */
	get_authentication_information(&current_authdata);

	/* calculate timestamps for reading logs */
	convert_timeperiod_to_times(TIMEPERIOD_SINGLE_DAY, &ts_start, &ts_end);

	if (display_header == TRUE) {

		/* begin top table */
		printf("<table border=0 width=100%%>\n");
		printf("<tr>\n");

		/* left column of the first row */
		printf("<td align=left valign=top width=33%%>\n");

		if (display_type == DISPLAY_HOSTS)
			display_info_table("Host Alert History", &current_authdata, daemon_check);
		else if (display_type == DISPLAY_SERVICES)
			display_info_table("Service Alert History", &current_authdata, daemon_check);
		else if (display_type == DISPLAY_HOSTGROUPS)
			display_info_table("Host Group Alert History", &current_authdata, daemon_check);
		else if (display_type == DISPLAY_SERVICEGROUPS)
			display_info_table("Service Group Alert History", &current_authdata, daemon_check);
		else
			display_info_table("Alert History", &current_authdata, daemon_check);

		printf("<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 CLASS='linkBox'>\n");
		printf("<TR><TD CLASS='linkBox'>\n");
		if (display_type == DISPLAY_HOSTS) {
			printf("<a href='%s?host=%s'>View <b>Service Status Detail</b> For <b>%s</b></a><br>\n", STATUS_CGI, (show_all_hosts == TRUE) ? "all" : url_encode(host_name), (show_all_hosts == TRUE) ? "All Hosts" : "This Host");
			printf("<a href='%s?host=%s'>View <b>Notifications</b> For <b>%s</b></a><br>\n", NOTIFICATIONS_CGI, (show_all_hosts == TRUE) ? "all" : url_encode(host_name), (show_all_hosts == TRUE) ? "All Hosts" : "This Host");
			printf("<a href='%s?type=%d&host=%s'>View <b>Information</b> For <b>This Host</b></a><br>\n", EXTINFO_CGI, DISPLAY_HOST_INFO, url_encode(host_name));
#ifdef USE_TRENDS
			if (show_all_hosts == FALSE)
				printf("<a href='%s?host=%s'>View <b>Trends</b> For <b>This Host</b></a>\n", TRENDS_CGI, url_encode(host_name));
#endif
		} else if (display_type == DISPLAY_SERVICES) {
			printf("<a href='%s?host=%s&service=%s'>View <b>Notifications</b> For <b>This Service</b></a><br>\n", NOTIFICATIONS_CGI, url_encode(host_name), url_encode(service_desc));
			printf("<a href='%s?type=%d&host=%s&service=%s'>View <b>Information</b> For <b>This Service</b></a><br>\n", EXTINFO_CGI, DISPLAY_SERVICE_INFO, url_encode(host_name), url_encode(service_desc));
#ifdef USE_TRENDS
			printf("<a href='%s?host=%s&service=%s'>View <b>Trends</b> For <b>This Service</b></a><br>\n", TRENDS_CGI, url_encode(host_name), url_encode(service_desc));
#endif
			printf("<a href='%s?host=%s'>View <b>Alert History</b> For <b>This Host</b></a>\n", HISTORY_CGI, url_encode(host_name));
		} else if (display_type == DISPLAY_HOSTGROUPS) {
			printf("<a href='%s?hostgroup=%s&style=hostdetail'>View <b>Host Status Detail</b> For <b>This Hostgroup</b></a><br>\n", STATUS_CGI, url_encode(hostgroup_name));
			printf("<a href='%s?hostgroup=%s&style=detail'>View <b>Service Status Detail</b> For <b>This Hostgroup</b></a><br>\n", STATUS_CGI, url_encode(hostgroup_name));
			printf("<a href='%s?hostgroup=%s'>View <b>Notifications</b> For <b>This Hostgroup</b></a>\n", NOTIFICATIONS_CGI, url_encode(hostgroup_name));
		} else if (display_type == DISPLAY_SERVICEGROUPS) {
			printf("<a href='%s?servicegroup=%s&style=hostdetail'>View <b>Host Status Detail</b> For <b>This Servicegroup</b></a><br>\n", STATUS_CGI, url_encode(servicegroup_name));
			printf("<a href='%s?servicegroup=%s&style=detail'>View <b>Service Status Detail</b> For <b>This Servicegroup</b></a><br>\n", STATUS_CGI, url_encode(servicegroup_name));
			printf("<a href='%s?servicegroup=%s'>View <b>Notifications</b> For <b>This Servicegroup</b></a>\n", NOTIFICATIONS_CGI, url_encode(servicegroup_name));
		}
		printf("</TD></TR>\n");
		printf("</TABLE>\n");

		printf("</td>\n");

		/* middle column of top row */
		printf("<td align=center valign=top width=33%%>\n");

		printf("<DIV ALIGN=CENTER CLASS='dataTitle'>\n");
		if (display_type == DISPLAY_SERVICES)
			printf("Service '%s' On Host '%s'", html_encode(service_desc, TRUE), html_encode(host_name, TRUE));
		else if (display_type == DISPLAY_HOSTS) {
			if (show_all_hosts == TRUE)
				printf("All Hosts and Services");
			else
				printf("Host '%s'", html_encode(host_name, TRUE));
		} else if (display_type == DISPLAY_HOSTGROUPS)
			printf("Host Group '%s'", html_encode(hostgroup_name, TRUE));
		else if (display_type == DISPLAY_SERVICEGROUPS)
			printf("Service Group '%s'", html_encode(servicegroup_name, TRUE));
		printf("</DIV>\n");
		printf("<BR />\n");

		display_nav_table(ts_start, ts_end);

		printf("</td>\n");

		/* right hand column of top row */
		printf("<td align=right valign=top width=33%%>\n");

		printf("<form method=\"GET\" action=\"%s\">\n", HISTORY_CGI);
		printf("<input type='hidden' name='ts_start' value='%lu'>\n", ts_start);
		printf("<input type='hidden' name='ts_end' value='%lu'>\n", ts_end);
		printf("<input type='hidden' name='limit' value='%d'>\n", result_limit);

		if (display_type == DISPLAY_HOSTGROUPS)
			printf("<input type='hidden' name='hostgroup' value='%s'>\n", escape_string(hostgroup_name));
		else if (display_type == DISPLAY_SERVICEGROUPS)
			printf("<input type='hidden' name='servicegroup' value='%s'>\n", escape_string(servicegroup_name));
		else {
			printf("<input type='hidden' name='host' value='%s'>\n", (show_all_hosts == TRUE) ? "all" : escape_string(host_name));
			if (display_type == DISPLAY_SERVICES)
				printf("<input type='hidden' name='service' value='%s'>\n", escape_string(service_desc));
		}
		printf("<table border=0 CLASS='optBox'>\n");

		printf("<tr>\n");
		printf("<td align=left CLASS='optBoxItem'>State type options:</td>\n");
		printf("</tr>\n");

		printf("<tr>\n");
		printf("<td align=left CLASS='optBoxItem'><select name='statetype'>\n");
		printf("<option value=%d %s>All state types</option>\n", STATE_ALL, (state_options == STATE_ALL) ? "selected" : "");
		printf("<option value=%d %s>Soft states</option>\n", STATE_SOFT, (state_options == STATE_SOFT) ? "selected" : "");
		printf("<option value=%d %s>Hard states</option>\n", STATE_HARD, (state_options == STATE_HARD) ? "selected" : "");
		printf("</select></td>\n");
		printf("</tr>\n");

		printf("<tr>\n");
		printf("<td align=left CLASS='optBoxItem'>History detail level for ");
		if (display_type == DISPLAY_HOSTGROUPS || display_type == DISPLAY_SERVICEGROUPS)
			printf("this %sgroup", (display_type == DISPLAY_HOSTGROUPS) ? "host" : "service");
		else if (display_type == DISPLAY_HOSTS)
			printf("%s host%s", (show_all_hosts == TRUE) ? "all" : "this", (show_all_hosts == TRUE) ? "s" : "");
		else
			printf("service");
		printf(":</td>\n");
		printf("</tr>\n");
		printf("<tr>\n");
		printf("<td align=left CLASS='optBoxItem'><select name='type'>\n");
		if (display_type == DISPLAY_HOSTS || display_type == DISPLAY_HOSTGROUPS)
			printf("<option value=%d %s>All alerts</option>\n", HISTORY_ALL, (history_options == HISTORY_ALL) ? "selected" : "");
		printf("<option value=%d %s>All service alerts</option>\n", HISTORY_SERVICE_ALL, (history_options == HISTORY_SERVICE_ALL) ? "selected" : "");
		if (display_type == DISPLAY_HOSTS || display_type == DISPLAY_HOSTGROUPS)
			printf("<option value=%d %s>All host alerts</option>\n", HISTORY_HOST_ALL, (history_options == HISTORY_HOST_ALL) ? "selected" : "");
		printf("<option value=%d %s>Service warning</option>\n", HISTORY_SERVICE_WARNING, (history_options == HISTORY_SERVICE_WARNING) ? "selected" : "");
		printf("<option value=%d %s>Service unknown</option>\n", HISTORY_SERVICE_UNKNOWN, (history_options == HISTORY_SERVICE_UNKNOWN) ? "selected" : "");
		printf("<option value=%d %s>Service critical</option>\n", HISTORY_SERVICE_CRITICAL, (history_options == HISTORY_SERVICE_CRITICAL) ? "selected" : "");
		printf("<option value=%d %s>Service recovery</option>\n", HISTORY_SERVICE_RECOVERY, (history_options == HISTORY_SERVICE_RECOVERY) ? "selected" : "");
		if (display_type == DISPLAY_HOSTS || display_type == DISPLAY_HOSTGROUPS) {
			printf("<option value=%d %s>Host down</option>\n", HISTORY_HOST_DOWN, (history_options == HISTORY_HOST_DOWN) ? "selected" : "");
			printf("<option value=%d %s>Host unreachable</option>\n", HISTORY_HOST_UNREACHABLE, (history_options == HISTORY_HOST_UNREACHABLE) ? "selected" : "");
			printf("<option value=%d %s>Host recovery</option>\n", HISTORY_HOST_RECOVERY, (history_options == HISTORY_HOST_RECOVERY) ? "selected" : "");
		}
		printf("</select></td>\n");
		printf("</tr>\n");

		printf("<tr>\n");
		printf("<td align=left valign=bottom CLASS='optBoxItem'><input type='checkbox' name='noflapping' %s> Hide Flapping Alerts</td>", (display_flapping_alerts == FALSE) ? "checked" : "");
		printf("</tr>\n");
		printf("<tr>\n");
		printf("<td align=left valign=bottom CLASS='optBoxItem'><input type='checkbox' name='nodowntime' %s> Hide Downtime Alerts</td>", (display_downtime_alerts == FALSE) ? "checked" : "");
		printf("</tr>\n");

		printf("<tr>\n");
		printf("<td align=left valign=bottom CLASS='optBoxItem'><input type='checkbox' name='nosystem' %s> Hide Process Messages</td>", (display_system_messages == FALSE) ? "checked" : "");
		printf("</tr>\n");
		printf("<tr>\n");
		printf("<td align=left valign=bottom CLASS='optBoxItem'><input type='checkbox' name='order' value='old2new' %s> Older Entries First</td>", (reverse == TRUE) ? "checked" : "");
		printf("</tr>\n");

		printf("<tr>\n");
		printf("<td align=left CLASS='optBoxItem'><input type='submit' value='Update'></td>\n");
		printf("</tr>\n");

		printf("</table>\n");
		printf("</form>\n");
		printf("</td>\n");

		/* end of top table */
		printf("</tr>\n");
		printf("</table>\n");

	}

	/* display history */
	show_history();

	document_footer(CGI_ID);

	/* free allocated memory */
	free_memory();

	return OK;
}
Esempio n. 15
0
static void drawpage(fz_context *ctx, fz_document *doc, int pagenum)
{
	fz_page *page;
	fz_display_list *list = NULL;
	fz_device *dev = NULL;
	int start;
	fz_cookie cookie = { 0 };
	int needshot = 0;

	fz_var(list);
	fz_var(dev);

	if (showtime)
	{
		start = gettime();
	}

	fz_try(ctx)
	{
		page = fz_load_page(doc, pagenum - 1);
	}
	fz_catch(ctx)
	{
		fz_throw(ctx, "cannot load page %d in file '%s'", pagenum, filename);
	}

	if (mujstest_file)
	{
		fz_interactive *inter = fz_interact(doc);
		fz_widget *widget = NULL;

		if (inter)
			widget = fz_first_widget(inter, page);

		if (widget)
		{
			fprintf(mujstest_file, "GOTO %d\n", pagenum);
			needshot = 1;
		}
		for (;widget; widget = fz_next_widget(inter, widget))
		{
			fz_rect rect;
			int w, h, len;
			int type = fz_widget_get_type(widget);

			fz_bound_widget(widget, &rect);
			w = (rect.x1 - rect.x0);
			h = (rect.y1 - rect.y0);
			++mujstest_count;
			switch (type)
			{
			default:
				fprintf(mujstest_file, "%% UNKNOWN %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case FZ_WIDGET_TYPE_PUSHBUTTON:
				fprintf(mujstest_file, "%% PUSHBUTTON %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case FZ_WIDGET_TYPE_CHECKBOX:
				fprintf(mujstest_file, "%% CHECKBOX %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case FZ_WIDGET_TYPE_RADIOBUTTON:
				fprintf(mujstest_file, "%% RADIOBUTTON %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case FZ_WIDGET_TYPE_TEXT:
			{
				int maxlen = fz_text_widget_max_len(inter, widget);
				int texttype = fz_text_widget_content_type(inter, widget);

				/* If height is low, assume a single row, and base
				 * the width off that. */
				if (h < 10)
				{
					w = (w+h-1) / (h ? h : 1);
					h = 1;
				}
				/* Otherwise, if width is low, work off height */
				else if (w < 10)
				{
					h = (w+h-1) / (w ? w : 1);
					w = 1;
				}
				else
				{
					w = (w+9)/10;
					h = (h+9)/10;
				}
				len = w*h;
				if (len < 2)
					len = 2;
				if (len > maxlen)
					len = maxlen;
				fprintf(mujstest_file, "%% TEXT %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				switch (texttype)
				{
				default:
				case FZ_WIDGET_CONTENT_UNRESTRAINED:
					fprintf(mujstest_file, "TEXT %d ", mujstest_count);
					escape_string(mujstest_file, len-3, lorem);
					fprintf(mujstest_file, "\n");
					break;
				case FZ_WIDGET_CONTENT_NUMBER:
					fprintf(mujstest_file, "TEXT %d\n", mujstest_count);
					break;
				case FZ_WIDGET_CONTENT_SPECIAL:
					fprintf(mujstest_file, "TEXT %lld\n", 46702919800LL + mujstest_count);
					break;
				case FZ_WIDGET_CONTENT_DATE:
					fprintf(mujstest_file, "TEXT Jun %d 1979\n", 1 + ((13 + mujstest_count) % 30));
					break;
				case FZ_WIDGET_CONTENT_TIME:
					++mujstest_count;
					fprintf(mujstest_file, "TEXT %02d:%02d\n", ((mujstest_count/60) % 24), mujstest_count % 60);
					break;
				}
				break;
			}
			case FZ_WIDGET_TYPE_LISTBOX:
				fprintf(mujstest_file, "%% LISTBOX %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			case FZ_WIDGET_TYPE_COMBOBOX:
				fprintf(mujstest_file, "%% COMBOBOX %0.2f %0.2f %0.2f %0.2f\n", rect.x0, rect.y0, rect.x1, rect.y1);
				break;
			}
			fprintf(mujstest_file, "CLICK %0.2f %0.2f\n", (rect.x0+rect.x1)/2, (rect.y0+rect.y1)/2);
		}
	}

	if (uselist)
	{
		fz_try(ctx)
		{
			list = fz_new_display_list(ctx);
			dev = fz_new_list_device(ctx, list);
			fz_run_page(doc, page, dev, &fz_identity, &cookie);
		}
		fz_always(ctx)
		{
			fz_free_device(dev);
			dev = NULL;
		}
		fz_catch(ctx)
		{
			fz_free_display_list(ctx, list);
			fz_free_page(doc, page);
			fz_throw(ctx, "cannot draw page %d in file '%s'", pagenum, filename);
		}
	}

	if (showxml)
	{
		fz_try(ctx)
		{
			dev = fz_new_trace_device(ctx);
			fz_printf(out, "<page number=\"%d\">\n", pagenum);
			if (list)
				fz_run_display_list(list, dev, &fz_identity, &fz_infinite_rect, &cookie);
			else
				fz_run_page(doc, page, dev, &fz_identity, &cookie);
			fz_printf(out, "</page>\n");
		}
		fz_always(ctx)
		{
			fz_free_device(dev);
			dev = NULL;
		}
		fz_catch(ctx)
		{
			fz_free_display_list(ctx, list);
			fz_free_page(doc, page);
			fz_rethrow(ctx);
		}
	}

	if (showtext)
	{
		fz_text_page *text = NULL;

		fz_var(text);

		fz_try(ctx)
		{
			fz_rect bounds;
			text = fz_new_text_page(ctx, fz_bound_page(doc, page, &bounds));
			dev = fz_new_text_device(ctx, sheet, text);
			if (list)
				fz_run_display_list(list, dev, &fz_identity, &fz_infinite_rect, &cookie);
			else
				fz_run_page(doc, page, dev, &fz_identity, &cookie);
			fz_free_device(dev);
			dev = NULL;
			if (showtext == TEXT_XML)
			{
				fz_print_text_page_xml(ctx, out, text);
			}
			else if (showtext == TEXT_HTML)
			{
				fz_text_analysis(ctx, sheet, text);
				fz_print_text_page_html(ctx, out, text);
			}
			else if (showtext == TEXT_PLAIN)
			{
				fz_print_text_page(ctx, out, text);
				fz_printf(out, "\f\n");
			}
		}
		fz_always(ctx)
		{
			fz_free_device(dev);
			dev = NULL;
			fz_free_text_page(ctx, text);
		}
		fz_catch(ctx)
		{
			fz_free_display_list(ctx, list);
			fz_free_page(doc, page);
			fz_rethrow(ctx);
		}
	}

	if (showmd5 || showtime)
		printf("page %s %d", filename, pagenum);

#ifdef GDI_PLUS_BMP_RENDERER
	// hack: use -G0 to "enable GDI+" when saving as TGA
	if (output && (strstr(output, ".bmp") || strstr(output, ".tga") && !gamma_value))
		drawbmp(ctx, doc, page, list, pagenum, &cookie);
	else
#endif
	if (output || showmd5 || showtime)
	{
		float zoom;
		fz_matrix ctm;
		fz_rect bounds, tbounds;
		fz_irect ibounds;
		fz_pixmap *pix = NULL;
		int w, h;

		fz_var(pix);

		fz_bound_page(doc, page, &bounds);
		zoom = resolution / 72;
		fz_pre_scale(fz_rotate(&ctm, rotation), zoom, zoom);
		tbounds = bounds;
		fz_round_rect(&ibounds, fz_transform_rect(&tbounds, &ctm));

		/* Make local copies of our width/height */
		w = width;
		h = height;

		/* If a resolution is specified, check to see whether w/h are
		 * exceeded; if not, unset them. */
		if (res_specified)
		{
			int t;
			t = ibounds.x1 - ibounds.x0;
			if (w && t <= w)
				w = 0;
			t = ibounds.y1 - ibounds.y0;
			if (h && t <= h)
				h = 0;
		}

		/* Now w or h will be 0 unless they need to be enforced. */
		if (w || h)
		{
			float scalex = w / (tbounds.x1 - tbounds.x0);
			float scaley = h / (tbounds.y1 - tbounds.y0);
			fz_matrix scale_mat;

			if (fit)
			{
				if (w == 0)
					scalex = 1.0f;
				if (h == 0)
					scaley = 1.0f;
			}
			else
			{
				if (w == 0)
					scalex = scaley;
				if (h == 0)
					scaley = scalex;
			}
			if (!fit)
			{
				if (scalex > scaley)
					scalex = scaley;
				else
					scaley = scalex;
			}
			fz_scale(&scale_mat, scalex, scaley);
			fz_concat(&ctm, &ctm, &scale_mat);
			tbounds = bounds;
			fz_transform_rect(&tbounds, &ctm);
		}
		fz_round_rect(&ibounds, &tbounds);
		fz_rect_from_irect(&tbounds, &ibounds);

		/* TODO: banded rendering and multi-page ppm */

		fz_try(ctx)
		{
			pix = fz_new_pixmap_with_bbox(ctx, colorspace, &ibounds);

			if (savealpha)
				fz_clear_pixmap(ctx, pix);
			else
				fz_clear_pixmap_with_value(ctx, pix, 255);

			dev = fz_new_draw_device(ctx, pix);
			if (list)
				fz_run_display_list(list, dev, &ctm, &tbounds, &cookie);
			else
				fz_run_page(doc, page, dev, &ctm, &cookie);
			fz_free_device(dev);
			dev = NULL;

			if (invert)
				fz_invert_pixmap(ctx, pix);
			if (gamma_value != 1)
				fz_gamma_pixmap(ctx, pix, gamma_value);

			if (savealpha)
				fz_unmultiply_pixmap(ctx, pix);

			if (output)
			{
				char buf[512];
				sprintf(buf, output, pagenum);
				if (strstr(output, ".pgm") || strstr(output, ".ppm") || strstr(output, ".pnm"))
					fz_write_pnm(ctx, pix, buf);
				else if (strstr(output, ".pam"))
					fz_write_pam(ctx, pix, buf, savealpha);
				else if (strstr(output, ".png"))
					fz_write_png(ctx, pix, buf, savealpha);
				else if (strstr(output, ".pbm")) {
					fz_bitmap *bit = fz_halftone_pixmap(ctx, pix, NULL);
					fz_write_pbm(ctx, bit, buf);
					fz_drop_bitmap(ctx, bit);
				}
				/* SumatraPDF: support TGA as output format */
				else if (strstr(output, ".tga"))
					fz_write_tga(ctx, pix, buf, savealpha);
			}

			if (showmd5)
			{
				unsigned char digest[16];
				int i;

				fz_md5_pixmap(pix, digest);
				printf(" ");
				for (i = 0; i < 16; i++)
					printf("%02x", digest[i]);
			}
		}
		fz_always(ctx)
		{
			fz_free_device(dev);
			dev = NULL;
			fz_drop_pixmap(ctx, pix);
		}
		fz_catch(ctx)
		{
			fz_free_display_list(ctx, list);
			fz_free_page(doc, page);
			fz_rethrow(ctx);
		}
	}
Esempio n. 16
0
inline std::string to_printable_boolish(const signed char *s) {
  if(!s) return detail::null_str();
  return escape_string(reinterpret_cast<const char*>(s));
}
Esempio n. 17
0
static Z_AttributesPlusTerm *rpn_term(struct yaz_pqf_parser *li, ODR o,
                                      int num_attr, Odr_int *attr_list,
                                      char **attr_clist, Odr_oid **attr_set)
{
    Z_AttributesPlusTerm *zapt;
    Odr_oct *term_octet;
    Z_Term *term;
    Z_AttributeElement **elements;

    zapt = (Z_AttributesPlusTerm *)odr_malloc (o, sizeof(*zapt));
    term_octet = (Odr_oct *)odr_malloc (o, sizeof(*term_octet));
    term = (Z_Term *)odr_malloc (o, sizeof(*term));

    if (!num_attr)
        elements = (Z_AttributeElement**)odr_nullval();
    else
    {
        int i, k = 0;
        Odr_int *attr_tmp;

        elements = (Z_AttributeElement**)
            odr_malloc (o, num_attr * sizeof(*elements));

        attr_tmp = (Odr_int *)odr_malloc(o, num_attr * 2 * sizeof(*attr_tmp));
        memcpy(attr_tmp, attr_list, num_attr * 2 * sizeof(*attr_tmp));
        for (i = num_attr; --i >= 0; )
        {
            int j;
            for (j = i+1; j<num_attr; j++)
                if (attr_tmp[2*j] == attr_tmp[2*i])
                    break;
            if (j < num_attr)
                continue;
            elements[k] =
                (Z_AttributeElement*)odr_malloc (o,sizeof(**elements));
            elements[k]->attributeType = &attr_tmp[2*i];
            elements[k]->attributeSet = attr_set[i];

            if (attr_clist[i])
            {
                elements[k]->which = Z_AttributeValue_complex;
                elements[k]->value.complex = (Z_ComplexAttribute *)
                    odr_malloc (o, sizeof(Z_ComplexAttribute));
                elements[k]->value.complex->num_list = 1;
                elements[k]->value.complex->list =
                    (Z_StringOrNumeric **)
                    odr_malloc (o, 1 * sizeof(Z_StringOrNumeric *));
                elements[k]->value.complex->list[0] =
                    (Z_StringOrNumeric *)
                    odr_malloc (o, sizeof(Z_StringOrNumeric));
                elements[k]->value.complex->list[0]->which =
                    Z_StringOrNumeric_string;
                elements[k]->value.complex->list[0]->u.string =
                    attr_clist[i];
                elements[k]->value.complex->semanticAction = 0;
                elements[k]->value.complex->num_semanticAction = 0;
            }
            else
            {
                elements[k]->which = Z_AttributeValue_numeric;
                elements[k]->value.numeric = &attr_tmp[2*i+1];
            }
            k++;
        }
        num_attr = k;
    }
    zapt->attributes = (Z_AttributeList *)
        odr_malloc (o, sizeof(*zapt->attributes));
    zapt->attributes->num_attributes = num_attr;
    zapt->attributes->attributes = elements;

    zapt->term = term;

    term_octet->buf = (unsigned char *)odr_malloc (o, 1 + li->lex_len);
    term_octet->size = term_octet->len =
        escape_string ((char *) (term_octet->buf), li->lex_buf, li->lex_len);
    term_octet->buf[term_octet->size] = 0;  /* null terminate */
    
    switch (li->term_type)
    {
    case Z_Term_general:
        term->which = Z_Term_general;
        term->u.general = term_octet;
        break;
    case Z_Term_characterString:
        term->which = Z_Term_characterString;
        term->u.characterString = (char*) term_octet->buf; 
                                    /* null terminated above */
        break;
    case Z_Term_numeric:
        term->which = Z_Term_numeric;
        term->u.numeric = odr_intdup (o, atoi((char*) (term_octet->buf)));
        break;
    case Z_Term_null:
        term->which = Z_Term_null;
        term->u.null = odr_nullval();
        break;
    case Z_Term_external:
        term->which = Z_Term_external;
        term->u.external = 0;
        break;
    default:
        term->which = Z_Term_null;
        term->u.null = odr_nullval();
        break;
    }
    return zapt;
}
Esempio n. 18
0
inline std::string to_printable_boolish(const char32_t *s) {
  if(!s) return detail::null_str();
  return escape_string(string_convert(s));
}
Esempio n. 19
0
	void http_tracker_connection::start()
	{
		// TODO: authentication
		std::string url = tracker_req().url;

		if (tracker_req().kind == tracker_request::scrape_request)
		{
			// find and replace "announce" with "scrape"
			// in request

			std::size_t pos = url.find("announce");
			if (pos == std::string::npos)
			{
				m_ios.post(boost::bind(&http_tracker_connection::fail_disp, self()
					, error_code(errors::scrape_not_available)));
				return;
			}
			url.replace(pos, 8, "scrape");
		}
		
#if TORRENT_USE_I2P
		bool i2p = is_i2p_url(url);
#else
		static const bool i2p = false;
#endif

		session_settings const& settings = m_ses.settings();

		// if request-string already contains
		// some parameters, append an ampersand instead
		// of a question mark
		size_t arguments_start = url.find('?');
		if (arguments_start != std::string::npos)
			url += "&";
		else
			url += "?";

		url += "info_hash=";
		url += escape_string((const char*)&tracker_req().info_hash[0], 20);
		
		if (tracker_req().kind == tracker_request::announce_request)
		{
			char str[1024];
			const bool stats = tracker_req().send_stats;
			snprintf(str, sizeof(str), "&peer_id=%s&port=%d&uploaded=%"PRId64
				"&downloaded=%"PRId64"&left=%"PRId64"&corrupt=%"PRId64"&redundant=%"PRId64
				"&compact=1&numwant=%d&key=%x&no_peer_id=1"
				, escape_string((const char*)&tracker_req().pid[0], 20).c_str()
				// the i2p tracker seems to verify that the port is not 0,
				// even though it ignores it otherwise
				, i2p ? 1 : tracker_req().listen_port
				, stats ? tracker_req().uploaded : 0
				, stats ? tracker_req().downloaded : 0
				, stats ? tracker_req().left : 0
				, stats ? tracker_req().corrupt : 0
				, stats ? tracker_req().redundant: 0
				, tracker_req().num_want
				, tracker_req().key);
			url += str;
#ifndef TORRENT_DISABLE_ENCRYPTION
			if (m_ses.get_pe_settings().in_enc_policy != pe_settings::disabled)
				url += "&supportcrypto=1";
#endif
			if (!tracker_req().trackerid.empty())
			{
				std::string id = tracker_req().trackerid;
				url += "&trackerid=";
				url += escape_string(id.c_str(), id.length());
			}

			if (tracker_req().event != tracker_request::none)
			{
				const char* event_string[] = {"completed", "started", "stopped", "paused"};
				url += "&event=";
				url += event_string[tracker_req().event - 1];
			}

#if TORRENT_USE_I2P
			if (i2p)
			{
				url += "&ip=";
				url += escape_string(m_i2p_conn->local_endpoint().c_str()
					, m_i2p_conn->local_endpoint().size());
				url += ".i2p";
			}
			else
#endif
			if (!m_ses.settings().anonymous_mode)
			{
				if (!settings.announce_ip.empty())
				{
					url += "&ip=" + escape_string(
						settings.announce_ip.c_str(), settings.announce_ip.size());
				}
				else if (m_ses.settings().announce_double_nat
					&& is_local(m_ses.listen_address()))
				{
					// only use the global external listen address here
					// if it turned out to be on a local network
					// since otherwise the tracker should use our
					// source IP to determine our origin
					url += "&ip=" + print_address(m_ses.listen_address());
				}
   
				if (!tracker_req().ipv6.empty() && !i2p)
				{
					url += "&ipv6=";
					url += tracker_req().ipv6;
				}
   
				if (!tracker_req().ipv4.empty() && !i2p)
				{
					url += "&ipv4=";
					url += tracker_req().ipv4;
				}
			}
		}

		m_tracker_connection.reset(new http_connection(m_ios, m_cc
			, boost::bind(&http_tracker_connection::on_response, self(), _1, _2, _3, _4)
			, true
			, boost::bind(&http_tracker_connection::on_connect, self(), _1)
			, boost::bind(&http_tracker_connection::on_filter, self(), _1, _2)
#ifdef TORRENT_USE_OPENSSL
			, tracker_req().ssl_ctx
#endif
			));

		int timeout = tracker_req().event==tracker_request::stopped
			?settings.stop_tracker_timeout
			:settings.tracker_completion_timeout;

		m_tracker_connection->get(url, seconds(timeout)
			, tracker_req().event == tracker_request::stopped ? 2 : 1
			, &m_ps, 5, settings.anonymous_mode ? "" : settings.user_agent
			, bind_interface()
#if TORRENT_USE_I2P
			, m_i2p_conn
#endif
			);

		// the url + 100 estimated header size
		sent_bytes(url.size() + 100);

#if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING)

		boost::shared_ptr<request_callback> cb = requester();
		if (cb)
		{
			cb->debug_log("==> TRACKER_REQUEST [ url: %s ]", url.c_str());
		}
#endif
	}
Esempio n. 20
0
inline std::string
to_printable(const std::basic_string<Char, Traits, Alloc> &s) {
  return escape_string(string_convert(s));
}
Esempio n. 21
0
static int
sasl_map_check(sasl_map_data *dp, char *sasl_user_and_realm, char **ldap_search_base, char **ldap_search_filter)
{
	Slapi_Regex *re = NULL;
	int ret = 0;
	int matched = 0;
	const char *recomp_result = NULL;

	slapi_log_err(SLAPI_LOG_TRACE, "sasl_map_check", "=>\n");
	/* Compiles the regex */
	re = slapi_re_comp(dp->regular_expression, &recomp_result);
	if (NULL == re) {
		slapi_log_err(SLAPI_LOG_ERR,
			"sasl_map_check", "slapi_re_comp failed for expression (%s): %s\n",
			dp->regular_expression, recomp_result?recomp_result:"unknown");
	} else {
		/* Matches the compiled regex against sasl_user_and_realm */
		matched = slapi_re_exec(re, sasl_user_and_realm, -1 /* no timelimit */);
		slapi_log_err(SLAPI_LOG_TRACE, "sasl_map_check", "regex: %s, id: %s, %s\n",
			dp->regular_expression, sasl_user_and_realm,
			matched ? "matched" : "didn't match" );
	}
	if (matched) {
		if (matched == 1) {
			char escape_base[BUFSIZ];
			char escape_filt[BUFSIZ];
			int ldap_search_base_len, ldap_search_filter_len;
			int rc = 0;

			/* Allocate buffers for the returned strings */
			/* We already computed this, so we could pass it in to speed up
			 * a little */
			size_t userrealmlen = strlen(sasl_user_and_realm); 
			/* These lengths could be precomputed and stored in the dp */
			ldap_search_base_len =
					userrealmlen + strlen(dp->template_base_dn) + 1;
			ldap_search_filter_len =
					userrealmlen + strlen(dp->template_search_filter) + 1;
			*ldap_search_base = (char *)slapi_ch_malloc(ldap_search_base_len);
			*ldap_search_filter =
					(char *)slapi_ch_malloc(ldap_search_filter_len);
			/* Substitutes '&' and/or "\#" in template_base_dn */
			rc = slapi_re_subs(re, sasl_user_and_realm, dp->template_base_dn,
					ldap_search_base, ldap_search_base_len);
			if (0 != rc) {
				slapi_log_err(SLAPI_LOG_ERR,
					"sasl_map_check", "slapi_re_subs failed: "
					"subject: %s, subst str: %s (%d)\n",
					sasl_user_and_realm, dp->template_base_dn, rc);
				slapi_ch_free_string(ldap_search_base);
				slapi_ch_free_string(ldap_search_filter);
			} else {
				/* Substitutes '&' and/or "\#" in template_search_filter */
				rc = slapi_re_subs_ext(re, sasl_user_and_realm,
					dp->template_search_filter, ldap_search_filter,
					ldap_search_filter_len, 1);
				if (0 != rc) {
					slapi_log_err(SLAPI_LOG_ERR,
						"sasl_map_check", "slapi_re_subs failed: "
						"subject: %s, subst str: %s (%d)\n",
						sasl_user_and_realm, dp->template_search_filter, rc);
					slapi_ch_free_string(ldap_search_base);
					slapi_ch_free_string(ldap_search_filter);
				} else {
					/* these values are internal regex representations with
					 * lots of unprintable control chars - escape for logging */
					slapi_log_err(SLAPI_LOG_TRACE,
						"sasl_map_check", "mapped base dn: %s, filter: %s\n",
						escape_string( *ldap_search_base, escape_base ),
						escape_string( *ldap_search_filter, escape_filt ));
					ret = 1;
				}
			}
		} else {
			slapi_log_err(SLAPI_LOG_ERR,
				"sasl_map_check", "slapi_re_exec failed: "
				"regex: %s, subject: %s (%d)\n",
				dp->regular_expression, sasl_user_and_realm, matched);
		}
	}
	slapi_re_free(re);
	slapi_log_err(SLAPI_LOG_TRACE, "sasl_map_check", "<= %d\n", ret);
	return ret;
}
Esempio n. 22
0
inline std::string
to_printable(const METTLE_STRING_VIEW<Char, Traits> &s) {
  return escape_string(string_convert(s));
}
Esempio n. 23
0
// Based on the info in the request message,
// look up the host and its user, and make sure the authenticator matches.
// Some special cases:
//  1) If no host ID is supplied, or if RPC seqno mismatch,
//     create a new host record
//  2) If the host record specified by g_request->hostid is a "zombie"
//     (i.e. it was merged with another host via the web site)
//     then follow links to find the proper host
//
// POSTCONDITION:
// If this function returns zero, then:
// - reply.host contains a valid host record (possibly new)
// - reply.user contains a valid user record
// - if user belongs to a team, reply.team contains team record
//
int authenticate_user() {
    int retval;
    char buf[256];
    DB_HOST host;
    DB_USER user;
    DB_TEAM team;

    if (g_request->hostid) {
        retval = host.lookup_id(g_request->hostid);
        while (!retval && host.userid==0) {
            // if host record is zombie, follow link to new host
            //
            retval = host.lookup_id(host.rpc_seqno);
            if (!retval) {
                g_reply->hostid = host.id;
                log_messages.printf(MSG_NORMAL,
                    "[HOST#%d] forwarding to new host ID %d\n",
                    g_request->hostid, host.id
                );
            }
        }
        if (retval) {
            g_reply->insert_message("Can't find host record", "low");
            log_messages.printf(MSG_NORMAL,
                "[HOST#%d?] can't find host\n",
                g_request->hostid
            );
            g_request->hostid = 0;
            goto lookup_user_and_make_new_host;
        }

        g_reply->host = host;

        // look up user based on the ID in host record,
        // and see if the authenticator matches (regular or weak)
        //
        g_request->using_weak_auth = false;
        sprintf(buf, "where id=%d", host.userid);
        retval = user.lookup(buf);
        if (!retval && !strcmp(user.authenticator, g_request->authenticator)) {
            // req auth matches user auth - go on
        } else {
            if (!retval) {
                // user for host.userid exists - check weak auth
                //
                get_weak_auth(user, buf);
                if (!strcmp(buf, g_request->authenticator)) {
                    g_request->using_weak_auth = true;
                    log_messages.printf(MSG_DEBUG,
                        "[HOST#%d] accepting weak authenticator\n",
                        host.id
                    );
                }
            }
            if (!g_request->using_weak_auth) {
                // weak auth failed - look up user based on authenticator
                //
                strlcpy(
                    user.authenticator, g_request->authenticator, sizeof(user.authenticator)
                );
                sprintf(buf, "where authenticator='%s'", user.authenticator);
                retval = user.lookup(buf);
                if (retval) {
                    g_reply->insert_message(
                        _("Invalid or missing account key.  To fix, remove and add this project."),
                        "notice"
                    );
                    g_reply->set_delay(DELAY_MISSING_KEY);
                    g_reply->nucleus_only = true;
                    log_messages.printf(MSG_CRITICAL,
                        "[HOST#%d] [USER#%d] Bad authenticator '%s'\n",
                        host.id, user.id, g_request->authenticator
                    );
                    return ERR_AUTHENTICATOR;
                }
            }
        }

        g_reply->user = user;

        if (host.userid != user.id) {
            // If the request's host ID isn't consistent with the authenticator,
            // create a new host record.
            //
            log_messages.printf(MSG_NORMAL,
                "[HOST#%d] [USER#%d] inconsistent host ID; creating new host\n",
                host.id, user.id
            );
            goto make_new_host;
        }


        // If the seqno from the host is less than what we expect,
        // the user must have copied the state file to a different host.
        // Make a new host record.
        //
        if (!batch && g_request->rpc_seqno < g_reply->host.rpc_seqno) {
            g_request->hostid = 0;
            log_messages.printf(MSG_NORMAL,
                "[HOST#%d] [USER#%d] RPC seqno %d less than expected %d; creating new host\n",
                g_reply->host.id, user.id, g_request->rpc_seqno, g_reply->host.rpc_seqno
            );
            goto make_new_host;
        }

    } else {
        // Here no hostid was given, or the ID was bad.
        // Look up the user, then create a new host record
        //
lookup_user_and_make_new_host:
        // if authenticator contains _, it's a weak auth
        //
        if (strchr(g_request->authenticator, '_')) {
            int userid = atoi(g_request->authenticator);
            retval = user.lookup_id(userid);
            if (!retval) {
                get_weak_auth(user, buf);
                if (strcmp(buf, g_request->authenticator)) {
                    retval = ERR_AUTHENTICATOR;
                }
            }
        } else {
            strlcpy(
                user.authenticator, g_request->authenticator,
                sizeof(user.authenticator)
            );
            sprintf(buf, "where authenticator='%s'", user.authenticator);
            retval = user.lookup(buf);
        }
        if (retval) {
            g_reply->insert_message(
                "Invalid or missing account key.  To fix, remove and add this project .",
                "low"
            );
            g_reply->set_delay(DELAY_MISSING_KEY);
            log_messages.printf(MSG_CRITICAL,
                "[HOST#<none>] Bad authenticator '%s': %s\n",
                g_request->authenticator, boincerror(retval)
            );
            return ERR_AUTHENTICATOR;
        }
        g_reply->user = user;

        // If host CPID is present,
        // scan backwards through this user's hosts,
        // looking for one with the same host CPID.
        // If we find one, it means the user detached and reattached.
        // Use the existing host record,
        // and mark in-progress results as over.
        //
        if (strlen(g_request->host.host_cpid)) {
            if (find_host_by_cpid(user, g_request->host.host_cpid, host)) {
                log_messages.printf(MSG_CRITICAL,
                    "[HOST#%d] [USER#%d] User has another host with same CPID.\n",
                    host.id, host.userid
                );
                if ((g_request->allow_multiple_clients != 1)
                    && (g_request->other_results.size() == 0)
                ) {
                    mark_results_over(host);
                }
                goto got_host;
            }
        }

make_new_host:
        // One final attempt to locate an existing host record:
        // scan backwards through this user's hosts,
        // looking for one with the same host name,
        // IP address, processor and amount of RAM.
        // If found, use the existing host record,
        // and mark in-progress results as over.
        //
        // NOTE: If the client was run with --allow_multiple_clients, skip this.
        //
        if ((g_request->allow_multiple_clients != 1)
            && find_host_by_other(user, g_request->host, host)
        ) {
            log_messages.printf(MSG_NORMAL,
                "[HOST#%d] [USER#%d] Found similar existing host for this user - assigned.\n",
                host.id, host.userid
            );
            mark_results_over(host);
            goto got_host;
        }
        // either of the above cases,
        // or host ID didn't match user ID,
        // or RPC seqno was too low.
        //
        // Create a new host.
        // g_reply->user is filled in and valid at this point
        //
        host = g_request->host;
        host.id = 0;
        host.create_time = time(0);
        host.userid = g_reply->user.id;
        host.rpc_seqno = 0;
        host.expavg_time = time(0);
        strcpy(host.venue, g_reply->user.venue);
        host.fix_nans();
        retval = host.insert();
        if (retval) {
            g_reply->insert_message(
                "Couldn't create host record in database", "low"
            );
            boinc_db.print_error("host.insert()");
            log_messages.printf(MSG_CRITICAL, "host.insert() failed\n");
            return retval;
        }
        host.id = boinc_db.insert_id();

got_host:
        g_reply->host = host;
        g_reply->hostid = g_reply->host.id;
        // this tells client to updates its host ID
        g_request->rpc_seqno = 0;
            // this value eventually gets written to host DB record;
            // for new hosts it must be zero.
            // This kludge forces this.
    }

    // have user record in g_reply->user at this point
    //

    if (g_reply->user.teamid) {
        retval = team.lookup_id(g_reply->user.teamid);
        if (!retval) g_reply->team = team;
    }

    // compute email hash
    //
    md5_block(
        (unsigned char*)g_reply->user.email_addr,
        strlen(g_reply->user.email_addr),
        g_reply->email_hash
    );

    // if new user CPID, update user record
    //
    if (!g_request->using_weak_auth && strlen(g_request->cross_project_id)) {
        if (strcmp(g_request->cross_project_id, g_reply->user.cross_project_id)) {
            user.id = g_reply->user.id;
            escape_string(g_request->cross_project_id, sizeof(g_request->cross_project_id));
            sprintf(buf, "cross_project_id='%s'", g_request->cross_project_id);
            unescape_string(g_request->cross_project_id, sizeof(g_request->cross_project_id));
            user.update_field(buf);
        }
    }

    return 0;
}
Esempio n. 24
0
inline std::string to_printable(signed char c) {
  return escape_string(std::string(1, c), '\'');
}
Esempio n. 25
0
// 1) Decide which global prefs to use for sched decisions: either
// - <working_global_prefs> from request msg
// - <global_prefs> from request message
// - prefs from user DB record
// and parse them into g_request->global_prefs.
// 2) update prefs in user record if needed
// 2) send global prefs in reply msg if needed
//
int handle_global_prefs() {
    char buf[BLOB_SIZE];
    g_reply->send_global_prefs = false;
    bool have_working_prefs = (strlen(g_request->working_global_prefs_xml)>0);
    bool have_master_prefs = (strlen(g_request->global_prefs_xml)>0);
        // absent if the host has host-specific prefs
    bool have_db_prefs = (strlen(g_reply->user.global_prefs)>0);
    bool same_account = !strcmp(
        g_request->global_prefs_source_email_hash, g_reply->email_hash
    );
    double master_mod_time=0, db_mod_time=0, working_mod_time=0;
    if (have_master_prefs) {
        parse_double(g_request->global_prefs_xml, "<mod_time>", master_mod_time);
        if (master_mod_time > dtime()) master_mod_time = dtime();
    }
    if (have_working_prefs) {
        parse_double(g_request->working_global_prefs_xml, "<mod_time>", working_mod_time);
        if (working_mod_time > dtime()) working_mod_time = dtime();
    }
    if (have_db_prefs) {
        parse_double(g_reply->user.global_prefs, "<mod_time>", db_mod_time);
        if (db_mod_time > dtime()) db_mod_time = dtime();
    }

    if (config.debug_prefs) {
        log_messages.printf(MSG_NORMAL,
            "[prefs] have_master:%d have_working: %d have_db: %d\n",
            have_master_prefs, have_working_prefs, have_db_prefs
        );
    }

    // decide which prefs to use for sched decisions,
    // and parse them into g_request->global_prefs
    //
    if (have_working_prefs) {
        g_request->global_prefs.parse(g_request->working_global_prefs_xml, "");
        if (config.debug_prefs) {
            log_messages.printf(MSG_NORMAL, "[prefs] using working prefs\n");
        }
    } else {
        if (have_master_prefs) {
            if (have_db_prefs && db_mod_time > master_mod_time) {
                g_request->global_prefs.parse(g_reply->user.global_prefs, g_reply->host.venue);
                if (config.debug_prefs) {
                    log_messages.printf(MSG_NORMAL,
                        "[prefs] using db prefs - more recent\n"
                    );
                }
            } else {
                g_request->global_prefs.parse(g_request->global_prefs_xml, g_reply->host.venue);
                if (config.debug_prefs) {
                    log_messages.printf(MSG_NORMAL,
                        "[prefs] using master prefs\n"
                    );
                }
            }
        } else {
            if (have_db_prefs) {
                g_request->global_prefs.parse(g_reply->user.global_prefs, g_reply->host.venue);
                if (config.debug_prefs) {
                    log_messages.printf(MSG_NORMAL, "[prefs] using db prefs\n");
                }
            } else {
                g_request->global_prefs.defaults();
                if (config.debug_prefs) {
                    log_messages.printf(MSG_NORMAL, "[prefs] using default prefs\n");
                }
            }
        }
    }

    // decide whether to update DB
    //
    if (!g_request->using_weak_auth && have_master_prefs) {
        bool update_user_record = false;
        if (have_db_prefs) {
            if (master_mod_time > db_mod_time && same_account) {
                update_user_record = true;
            }
        } else {
            if (same_account) update_user_record = true;
        }
        if (update_user_record) {
            if (config.debug_prefs) {
                log_messages.printf(MSG_NORMAL, "[prefs] updating db prefs\n");
            }
            strcpy(g_reply->user.global_prefs, g_request->global_prefs_xml);
            DB_USER user;
            user.id = g_reply->user.id;
            escape_string(g_request->global_prefs_xml, sizeof(g_request->global_prefs_xml));
            sprintf(buf, "global_prefs='%s'", g_request->global_prefs_xml);
            unescape_string(g_request->global_prefs_xml, sizeof(g_request->global_prefs_xml));
            int retval = user.update_field(buf);
            if (retval) {
                log_messages.printf(MSG_CRITICAL,
                    "user.update_field() failed: %s\n", boincerror(retval)
                );
            }
        }
    }

    // decide whether to send DB prefs in reply msg
    //
    if (config.debug_prefs) {
        log_messages.printf(MSG_NORMAL,
            "[prefs] have DB prefs: %d; dbmod %f; global mod %f; working mod %f\n",
            have_db_prefs, db_mod_time, g_request->global_prefs.mod_time, working_mod_time
        );
    }
    if (have_db_prefs && db_mod_time > master_mod_time && db_mod_time > working_mod_time) {
        if (config.debug_prefs) {
            log_messages.printf(MSG_DEBUG,
                "[prefs] sending DB prefs in reply\n"
            );
        }
        g_reply->send_global_prefs = true;
    }
    return 0;
}
Esempio n. 26
0
inline std::string to_printable(wchar_t c) {
  return escape_string(string_convert(std::wstring(1, c)), '\'');
}
Esempio n. 27
0
/* displays service status */
void display_service(void) {
	service *temp_service;
	servicestatus *temp_servicestatus;
	char last_check[MAX_DATETIME_LENGTH];
	int days;
	int hours;
	int minutes;
	int seconds;
	time_t current_time;
	time_t t;
	char state_duration[48];
	int found;

	/**** MAIN SCREEN (CARD 1) ****/
	printf("<card id='card1' title='Service Status'>\n");
	printf("<p align='center' mode='nowrap'>\n");
	printf("<b>Service '%s' on host '%s'</b><br/>\n", service_desc, host_name);

	/* find the service */
	temp_service = find_service(host_name, service_desc);
	temp_servicestatus = find_servicestatus(host_name, service_desc);
	if(temp_service == NULL || temp_servicestatus == NULL) {

		printf("<b>Error: Could not find service!</b>\n");
		printf("</p>\n");
		printf("</card>\n");
		return;
		}

	/* check authorization */
	if(is_authorized_for_service(temp_service, &current_authdata) == FALSE) {

		printf("<b>Error: Not authorized for service!</b>\n");
		printf("</p>\n");
		printf("</card>\n");
		return;
		}


	printf("<table columns='2' align='LL'>\n");

	printf("<tr><td>Status:</td><td>");
	if(temp_servicestatus->status == SERVICE_OK)
		printf("OK");
	else if(temp_servicestatus->status == SERVICE_PENDING)
		printf("PENDING");
	else if(temp_servicestatus->status == SERVICE_WARNING)
		printf("WARNING");
	else if(temp_servicestatus->status == SERVICE_UNKNOWN)
		printf("UNKNOWN");
	else if(temp_servicestatus->status == SERVICE_CRITICAL)
		printf("CRITICAL");
	else
		printf("?");
	printf("</td></tr>\n");

	printf("<tr><td>Info:</td><td>%s</td></tr>\n", temp_servicestatus->plugin_output);

	get_time_string(&temp_servicestatus->last_check, last_check, sizeof(last_check) - 1, SHORT_DATE_TIME);
	printf("<tr><td>Last Check:</td><td>%s</td></tr>\n", last_check);

	current_time = time(NULL);
	if(temp_servicestatus->last_state_change == (time_t)0)
		t = current_time - program_start;
	else
		t = current_time - temp_servicestatus->last_state_change;
	get_time_breakdown((unsigned long)t, &days, &hours, &minutes, &seconds);
	snprintf(state_duration, sizeof(state_duration) - 1, "%2dd %2dh %2dm %2ds%s", days, hours, minutes, seconds, (temp_servicestatus->last_state_change == (time_t)0) ? "+" : "");
	printf("<tr><td>Duration:</td><td>%s</td></tr>\n", state_duration);

	printf("<tr><td>Properties:</td><td>");
	found = 0;
	if(temp_servicestatus->checks_enabled == FALSE) {
		printf("%sChecks disabled", (found == 1) ? ", " : "");
		found = 1;
		}
	if(temp_servicestatus->notifications_enabled == FALSE) {
		printf("%sNotifications disabled", (found == 1) ? ", " : "");
		found = 1;
		}
	if(temp_servicestatus->problem_has_been_acknowledged == TRUE) {
		printf("%sProblem acknowledged", (found == 1) ? ", " : "");
		found = 1;
		}
	if(temp_servicestatus->scheduled_downtime_depth > 0) {
		printf("%sIn scheduled downtime", (found == 1) ? ", " : "");
		found = 1;
		}
	if(found == 0)
		printf("N/A");
	printf("</td></tr>\n");

	printf("</table>\n");
	printf("<br/>\n");
	printf("<b><anchor title='View Host'>View Host<go href='%s' method='post'><postfield name='host' value='%s'/></go></anchor></b>\n", STATUSWML_CGI, escape_string(host_name));
	printf("<b><anchor title='Service Commands'>Svc. Commands<go href='#card2'/></anchor></b>\n");
	printf("</p>\n");

	printf("</card>\n");


	/**** COMMANDS SCREEN (CARD 2) ****/
	printf("<card id='card2' title='Service Commands'>\n");
	printf("<p align='center' mode='nowrap'>\n");
	printf("<b>Service Commands</b><br/>\n");

	if(temp_servicestatus->status != SERVICE_OK && temp_servicestatus->status != SERVICE_PENDING)
		printf("<b><anchor title='Acknowledge Problem'>Acknowledge Problem<go href='#card3'/></anchor></b>\n");

	if(temp_servicestatus->checks_enabled == FALSE) {
		printf("<b><anchor title='Enable Checks'>Enable Checks<go href='%s' method='post'><postfield name='host' value='%s'/>", COMMAND_CGI, escape_string(host_name));
		printf("<postfield name='service' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", escape_string(service_desc), CMD_ENABLE_SVC_CHECK, CMDMODE_COMMIT);
		}
	else {
		printf("<b><anchor title='Disable Checks'>Disable Checks<go href='%s' method='post'><postfield name='host' value='%s'/>", COMMAND_CGI, escape_string(host_name));
		printf("<postfield name='service' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", escape_string(service_desc), CMD_DISABLE_SVC_CHECK, CMDMODE_COMMIT);

		printf("<b><anchor title='Schedule Immediate Check'>Schedule Immediate Check<go href='%s' method='post'><postfield name='host' value='%s'/>", COMMAND_CGI, escape_string(host_name));
		printf("<postfield name='service' value='%s'/><postfield name='start_time' value='%llu'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", escape_string(service_desc), (unsigned long long)current_time, CMD_SCHEDULE_SVC_CHECK, CMDMODE_COMMIT);
		}

	if(temp_servicestatus->notifications_enabled == FALSE) {
		printf("<b><anchor title='Enable Notifications'>Enable Notifications<go href='%s' method='post'><postfield name='host' value='%s'/>", COMMAND_CGI, escape_string(host_name));
		printf("<postfield name='service' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", escape_string(service_desc), CMD_ENABLE_SVC_NOTIFICATIONS, CMDMODE_COMMIT);
		}
	else {
		printf("<b><anchor title='Disable Notifications'>Disable Notifications<go href='%s' method='post'><postfield name='host' value='%s'/>", COMMAND_CGI, escape_string(host_name));
		printf("<postfield name='service' value='%s'/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go></anchor></b><br/>\n", escape_string(service_desc), CMD_DISABLE_SVC_NOTIFICATIONS, CMDMODE_COMMIT);
		}

	printf("</p>\n");

	printf("</card>\n");


	/**** ACKNOWLEDGEMENT SCREEN (CARD 3) ****/
	printf("<card id='card3' title='Acknowledge Problem'>\n");
	printf("<p align='center' mode='nowrap'>\n");
	printf("<b>Acknowledge Problem</b><br/>\n");
	printf("</p>\n");

	printf("<p align='center' mode='wrap'>\n");
	printf("<b>Your Name:</b><br/>\n");
	printf("<input name='name' value='%s' /><br/>\n", ((use_ssl_authentication) ? (getenv("SSL_CLIENT_S_DN_CN")) : (getenv("REMOTE_USER"))));
	printf("<b>Comment:</b><br/>\n");
	printf("<input name='comment' value='acknowledged by WAP'/>\n");

	printf("<do type='accept'>\n");
	printf("<go href='%s' method='post'><postfield name='host' value='%s'/>", COMMAND_CGI, escape_string(host_name));
	printf("<postfield name='service' value='%s'/><postfield name='com_author' value='$(name)'/><postfield name='com_data' value='$(comment)'/><postfield name='persistent' value=''/><postfield name='send_notification' value=''/><postfield name='cmd_typ' value='%d'/><postfield name='cmd_mod' value='%d'/><postfield name='content' value='wml'/></go>\n", escape_string(service_desc), CMD_ACKNOWLEDGE_SVC_PROBLEM, CMDMODE_COMMIT);
	printf("</do>\n");

	printf("</p>\n");

	printf("</card>\n");

	return;
	}
Esempio n. 28
0
inline std::string to_printable(char32_t c) {
  return escape_string(string_convert(std::u32string(1, c)), '\'');
}
Esempio n. 29
0
/* displays hostgroup status summary */
void display_hostgroup_summary(void) {
	hostgroup *temp_hostgroup;
	hostsmember *temp_member;
	host *temp_host;
	hoststatus *temp_hoststatus;
	service *temp_service;
	servicestatus *temp_servicestatus;
	int hosts_unreachable = 0;
	int hosts_down = 0;
	int hosts_up = 0;
	int hosts_pending = 0;
	int services_critical = 0;
	int services_unknown = 0;
	int services_warning = 0;
	int services_ok = 0;
	int services_pending = 0;
	int found = 0;


	/**** MAIN SCREEN (CARD 1) ****/
	printf("<card id='card1' title='Status Summary'>\n");
	printf("<p align='center' mode='nowrap'>\n");

	printf("<b><anchor title='Status Summary'>Status Summary<go href='%s' method='post'><postfield name='hostgroup' value='%s'/><postfield name='style' value='overview'/></go></anchor></b><br/><br/>\n", STATUSWML_CGI, escape_string(hostgroup_name));

	/* check all hostgroups */
	for(temp_hostgroup = hostgroup_list; temp_hostgroup != NULL; temp_hostgroup = temp_hostgroup->next) {

		if(show_all_hostgroups == FALSE && strcmp(temp_hostgroup->group_name, hostgroup_name))
			continue;

		if(is_authorized_for_hostgroup(temp_hostgroup, &current_authdata) == FALSE)
			continue;

		printf("<b><anchor title='%s'>%s<go href='%s' method='post'><postfield name='hostgroup' value='%s'/><postfield name='style' value='overview'/></go></anchor></b>\n", temp_hostgroup->group_name, temp_hostgroup->alias, STATUSWML_CGI, temp_hostgroup->group_name);

		printf("<table columns='2' align='LL'>\n");

		hosts_up = 0;
		hosts_pending = 0;
		hosts_down = 0;
		hosts_unreachable = 0;

		services_ok = 0;
		services_pending = 0;
		services_warning = 0;
		services_unknown = 0;
		services_critical = 0;

		/* check all hosts in this hostgroup */
		for(temp_member = temp_hostgroup->members; temp_member != NULL; temp_member = temp_member->next) {

			temp_host = find_host(temp_member->host_name);
			if(temp_host == NULL)
				continue;

			if(is_host_member_of_hostgroup(temp_hostgroup, temp_host) == FALSE)
				continue;

			temp_hoststatus = find_hoststatus(temp_host->name);
			if(temp_hoststatus == NULL)
				continue;

			if(temp_hoststatus->status == SD_HOST_UNREACHABLE)
				hosts_unreachable++;
			else if(temp_hoststatus->status == SD_HOST_DOWN)
				hosts_down++;
			else if(temp_hoststatus->status == HOST_PENDING)
				hosts_pending++;
			else
				hosts_up++;

			/* check all services on this host */
			for(temp_service = service_list; temp_service != NULL; temp_service = temp_service->next) {

				if(strcmp(temp_service->host_name, temp_host->name))
					continue;

				if(is_authorized_for_service(temp_service, &current_authdata) == FALSE)
					continue;

				temp_servicestatus = find_servicestatus(temp_service->host_name, temp_service->description);
				if(temp_servicestatus == NULL)
					continue;

				if(temp_servicestatus->status == SERVICE_CRITICAL)
					services_critical++;
				else if(temp_servicestatus->status == SERVICE_UNKNOWN)
					services_unknown++;
				else if(temp_servicestatus->status == SERVICE_WARNING)
					services_warning++;
				else if(temp_servicestatus->status == SERVICE_PENDING)
					services_pending++;
				else
					services_ok++;
				}
			}

		printf("<tr><td>Hosts:</td><td>");
		found = 0;
		if(hosts_unreachable > 0) {
			printf("%d UNR", hosts_unreachable);
			found = 1;
			}
		if(hosts_down > 0) {
			printf("%s%d DWN", (found == 1) ? ", " : "", hosts_down);
			found = 1;
			}
		if(hosts_pending > 0) {
			printf("%s%d PND", (found == 1) ? ", " : "", hosts_pending);
			found = 1;
			}
		printf("%s%d UP", (found == 1) ? ", " : "", hosts_up);
		printf("</td></tr>\n");
		printf("<tr><td>Services:</td><td>");
		found = 0;
		if(services_critical > 0) {
			printf("%d CRI", services_critical);
			found = 1;
			}
		if(services_warning > 0) {
			printf("%s%d WRN", (found == 1) ? ", " : "", services_warning);
			found = 1;
			}
		if(services_unknown > 0) {
			printf("%s%d UNK", (found == 1) ? ", " : "", services_unknown);
			found = 1;
			}
		if(services_pending > 0) {
			printf("%s%d PND", (found == 1) ? ", " : "", services_pending);
			found = 1;
			}
		printf("%s%d OK", (found == 1) ? ", " : "", services_ok);
		printf("</td></tr>\n");

		printf("</table>\n");

		printf("<br/>\n");
		}

	if(show_all_hostgroups == FALSE)
		printf("<b><anchor title='View All Hostgroups'>View All Hostgroups<go href='%s' method='post'><postfield name='hostgroup' value='all'/><postfield name='style' value='summary'/></go></anchor></b>\n", STATUSWML_CGI);

	printf("</p>\n");

	printf("</card>\n");

	return;
	}
Esempio n. 30
0
/*
=================
CG_ConsoleCommand

The string has been tokenized and can be retrieved with
Cmd_Argc() / Cmd_Argv()
=================
*/
qboolean CG_ConsoleCommand( void ) {
	const char	*cmd;
	int		i;

	// Arnout - don't allow console commands until a snapshot is present
	if ( !cg.snap ) {
		return qfalse;
	}

	cmd = CG_Argv(0);

	//mcwf
	if (!Q_stricmp(cmd,"m")) { 
		if (need_escape(ConcatArgs(1))) {
		trap_SendClientCommand(va("m \"%s\"\n",escape_string(ConcatArgs(1))));  // say private
		return -1;
		}
	}

	if (!Q_stricmp(cmd,"priv")) { 
		if (need_escape(ConcatArgs(1))) {
		trap_SendClientCommand(va("priv \"%s\"\n",escape_string(ConcatArgs(1))));  // say private clone
		return -1;
		}
	}

	if (!Q_stricmp(cmd,"mt")) { 
		if (need_escape(ConcatArgs(1))) {
		trap_SendClientCommand(va("mt \"%s\"\n",escape_string(ConcatArgs(1))));  // say private team
		return -1;
		}
	}

	if (!Q_stricmp(cmd,"ma")) { 
		if (need_escape(ConcatArgs(1))) {
		trap_SendClientCommand(va("ma \"%s\"\n",escape_string(ConcatArgs(1))));  // admin chat
		return -1;
		}
	}

	if (!Q_stricmp(cmd,"say")) {
		if (need_escape(ConcatArgs(1))) {
		trap_SendClientCommand(va("say \"%s\"\n",escape_string(ConcatArgs(1))));  // say normal
		return -1;
		}
	}

	if (!Q_stricmp(cmd,"say_team")) {
		if (need_escape(ConcatArgs(1))) {
		trap_SendClientCommand(va("say_team \"%s\"\n",escape_string(ConcatArgs(1)))); // say team
		return -1;
		}
	}

	if (!Q_stricmp(cmd,"say_teamnl")) {
		if (need_escape(ConcatArgs(1))) {
		trap_SendClientCommand(va("say_teamnl \"%s\"\n",escape_string(ConcatArgs(1)))); // say team no pos
		return -1;
		}
	}

	if (!Q_stricmp(cmd,"say_buddy")) {
		if (need_escape(ConcatArgs(1))) {
		trap_SendClientCommand(va("say_buddy \"%s\"\n",escape_string(ConcatArgs(1)))); // say fireteam
		return -1;
		}
	}
	//mcwf

	// TODO just for testing, remove me later
	if (!Q_stricmp(cmd,"cyclechar")) {
		trap_SendClientCommand( "cyclechar" );
		return -1;
	}

	// TODO just for testing, remove me later
	if (!Q_stricmp(cmd,"setchar")) {
		trap_SendClientCommand( "setchar" );
		return -1;
	}

	for ( i = 0 ; i < sizeof( commands ) / sizeof( commands[0] ) ; i++ ) {
		if ( !Q_stricmp( cmd, commands[i].cmd ) ) {
			commands[i].function();
			return qtrue;
		}
	}

	return qfalse;
}