Ejemplo n.º 1
0
static void parse_uri(req_parser *r, const char *data, size_t len)
{
	int mode = MODE_URI_PATH;

	const char *end = data + len;
	const char *token_start = data;
	const char *i;
	for (i = data; (i < end) && *i; i = g_utf8_next_char(i))
	{
		gunichar c = g_utf8_get_char(i);

		if (token_start == NULL)
		{
			token_start = i;
		}

		switch (mode)
		{
		case MODE_URI_PATH:
			if (c == '?')
			{
				r->path = g_string_new_len(token_start, (i - token_start));
				token_start = NULL;
				mode = MODE_URI_QUERY;
			}
			break;

		case MODE_URI_QUERY:
			if (c == '#')
			{
				r->query = parse_query(token_start, (i - token_start));
				token_start = NULL;
				mode = MODE_URI_FRAGMENT;
				break;
			}
			break;
		}
	}

	switch (mode)
	{
	case MODE_URI_PATH:
		r->path = g_string_new_len(data, len);
		break;

	case MODE_URI_QUERY:
		r->query = parse_query(token_start, len - (token_start - data));
		break;

	case MODE_URI_FRAGMENT:
		i = g_utf8_next_char(i);
		r->fragment = g_string_new_len(token_start, len - (token_start - data));
		break;
	}
}
Ejemplo n.º 2
0
    static std::vector<query_t> parse_queries(const std::string& collection_dir,
                                            const std::string& query_file,bool only_complete = false) 
    {
        std::vector<query_t> queries;

        /* load the mapping */
        auto mapping = load_dictionary(collection_dir);

        /* parse queries */
        std::ifstream qfs(query_file); 
        if(!qfs.is_open()) {
            std::cerr << "cannot load query file.";
            exit(EXIT_FAILURE);
        }

        std::string query_str;
        while( std::getline(qfs,query_str) ) {
            auto parsed_qry = parse_query(mapping,query_str,only_complete);
            if(parsed_qry.first) {
                queries.emplace_back(parsed_qry.second);
            }
        }

        return queries;
    }
Ejemplo n.º 3
0
static int fulltext_query(fulltext_vtab *v, const char *zQuery,
                          DocList **pResult){
  Query q;
  int phrase_start = -1;
  int i;
  sqlite3_stmt *pSelect = NULL;
  DocList *d = NULL;

  int rc = parse_query(v, zQuery, &q);
  if( rc!=SQLITE_OK ) return rc;

  
  for(i = 0 ; i < q.nTerms ; ++i){
    int need_positions = i<q.nTerms-1 && !q.pTerm[i+1].is_phrase;
    DocList *next = docListNew(need_positions ? DL_POSITIONS : DL_DOCIDS);
    if( q.pTerm[i].is_phrase ){
      phrase_start = i;
    }
    rc = query_merge(v, &pSelect, q.pTerm[i].zTerm, d, i - phrase_start, next);
    if( rc!=SQLITE_OK ) break;
    if( d!=NULL ){
      docListDelete(d);
    }
    d = next;
  }

  sqlite3_finalize(pSelect);
  query_free(&q);
  *pResult = d;
  return rc;
}
Ejemplo n.º 4
0
/* Perform a full-text query; return a list of documents in [pResult]. */
static int fulltext_query(fulltext_vtab *v, const char *zQuery,
                          DocList **pResult){
  Query q;
  int phrase_start = -1;
  int i;
  sqlite3_stmt *pSelect = NULL;
  DocList *d = NULL;

  int rc = parse_query(v, zQuery, &q);
  if( rc!=SQLITE_OK ) return rc;

  /* Merge terms. */
  for(i = 0 ; i < q.nTerms ; ++i){
    /* In each merge step, we need to generate positions whenever we're
     * processing a phrase which hasn't ended yet. */
    int need_positions = i<q.nTerms-1 && !q.pTerm[i+1].is_phrase;
    DocList *next = docListNew(need_positions ? DL_POSITIONS : DL_DOCIDS);
    if( q.pTerm[i].is_phrase ){
      phrase_start = i;
    }
    rc = query_merge(v, &pSelect, q.pTerm[i].zTerm, d, i - phrase_start, next);
    if( rc!=SQLITE_OK ) break;
    if( d!=NULL ){
      docListDelete(d);
    }
    d = next;
  }

  sqlite3_finalize(pSelect);
  query_free(&q);
  *pResult = d;
  return rc;
}
Ejemplo n.º 5
0
/*
Procedure exposed in Python to expose "parse_query"
*/
PyObject *py_parse_query(PyObject *self, PyObject *args)
{
    char *uri;

    if (!PyArg_ParseTuple(args, "s", &uri))
        return NULL;
    return parse_query(uri);
}
Ejemplo n.º 6
0
static void
find_answer(DNS_query *query)
{
	DNS_rr query_rr;

	parse_query(query, &query_rr);
	if (get_value(&query_rr) || append_answer(query, &query_rr))
		set_no_answer(query);
}
Ejemplo n.º 7
0
/**
 * The routeQuery entry point. This is passed the query buffer
 * to which the filter should be applied. Once applied the
 * query should normally be passed to the downstream component
 * (filter or router) in the filter chain.
 *
 * If the regular expressed configured in the match parameter of the
 * filter definition matches the SQL text then add the hint
 * "Route to named server" with the name defined in the server parameter
 *
 * @param instance	The filter instance data
 * @param session	The filter session
 * @param queue		The query data
 */
static	int	
routeQuery(FILTER *instance, void *session, GWBUF *queue)
{
LAG_INSTANCE	*my_instance = (LAG_INSTANCE *)instance;
LAG_SESSION	*my_session = (LAG_SESSION *)session;
char			*sql;
time_t now = time(NULL);

	if (modutil_is_SQL(queue))
	{
	    if (queue->next != NULL)
	    {
		queue = gwbuf_make_contiguous(queue);
	    }

	    if(!query_is_parsed(queue))
	    {
		parse_query(queue);
	    }

	    if(query_classifier_get_operation(queue) & (QUERY_OP_DELETE|QUERY_OP_INSERT|QUERY_OP_UPDATE))
	    {
		if((sql = modutil_get_SQL(queue)) != NULL)
		{
		    if(my_instance->nomatch == NULL||(my_instance->nomatch && regexec(&my_instance->nore,sql,0,NULL,0) != 0))
		    {
			if(my_instance->match == NULL||
			 (my_instance->match && regexec(&my_instance->re,sql,0,NULL,0) == 0))
			{
			    my_session->hints_left = my_instance->count;
			    my_session->last_modification = now;
			    my_instance->stats.n_modified++;
			}
		    }
		    free(sql);
		}
	    }
	    else if(my_session->hints_left > 0)
	    {
		queue->hint = hint_create_route(queue->hint,
					 HINT_ROUTE_TO_MASTER,
					 NULL);
		my_session->hints_left--;
		my_instance->stats.n_add_count++;
	    }
	    else if(difftime(now,my_session->last_modification) < my_instance->time)
	    {
		queue->hint = hint_create_route(queue->hint,
					 HINT_ROUTE_TO_MASTER,
					 NULL);
		my_instance->stats.n_add_time++;
	    }
	}
	return my_session->down.routeQuery(my_session->down.instance,
			my_session->down.session, queue);
}
Ejemplo n.º 8
0
int main(int argc, char *argv[])
{
	int argi;
	char *envarea = NULL;
	char *critconfig = NULL;
	char *hffile = "critical";

	for (argi = 1; (argi < argc); argi++) {
		if (argnmatch(argv[argi], "--env=")) {
			char *p = strchr(argv[argi], '=');
			loadenv(p+1, envarea);
		}
		else if (argnmatch(argv[argi], "--area=")) {
			char *p = strchr(argv[argi], '=');
			envarea = strdup(p+1);
		}
		else if (strcmp(argv[argi], "--debug") == 0) {
			debug = 1;
		}
		else if (strcmp(argv[argi], "--tooltips") == 0) {
			usetooltips = 1;
		}
		else if (argnmatch(argv[argi], "--acklevel=")) {
			char *p = strchr(argv[argi], '=');
			critacklevel = atoi(p+1);
		}
		else if (argnmatch(argv[argi], "--config=")) {
			char *p = strchr(argv[argi], '=');
			critconfig = strdup(p+1);
		}
		else if (argnmatch(argv[argi], "--hffile=")) {
			char *p = strchr(argv[argi], '=');
			hffile = strdup(p+1);
		}
	}

	redirect_cgilog("criticalview");

	setdocurl(hostsvcurl("%s", xgetenv("INFOCOLUMN"), 1));

	parse_query();
	load_hostnames(xgetenv("HOSTSCFG"), NULL, get_fqdn());
	load_critconfig(critconfig);
	load_all_links();
	fprintf(stdout, "Content-type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));

	if (loadstatus(maxprio, maxage, mincolor, wantacked) == 0) {
		use_recentgifs = 1;
		generate_critpage(stdout, hffile);
	}
	else {
		fprintf(stdout, "Cannot load Xymon status\n");
	}

	return 0;
}
Ejemplo n.º 9
0
QR_t * parse_querystring( const char *query_string)
{
  QR_t *qr;

  qr = (QR_t *)opj_malloc( sizeof(QR_t));
    
  qr->query = parse_query( query_string);
  qr->msgqueue = NULL;
  qr->channel = NULL;

  return qr;
}
Ejemplo n.º 10
0
/**
 * queryで与えられた文字列(ローマ字)を日本語検索のための正規表現へ変換する。
 * 戻り値は変換された結果の文字列(正規表現)で、使用後は#migemo_release()関数
 * へ渡すことで解放しなければならない。
 * @param object Migemoオブジェクト
 * @param query 問い合わせ文字列
 * @returns 正規表現文字列。#migemo_release() で解放する必要有り。
 */
    EXPORTS unsigned char* MIGEMO_CALLTYPE
migemo_query(migemo* object, const unsigned char* query)
{
    unsigned char *retval = NULL;
    wordlist_p querylist = NULL;
    wordbuf_p outbuf = NULL;

    if (object && object->rx && query)
    {
	wordlist_p p;

	querylist = parse_query(object, query);
	if (querylist == NULL)
	    goto MIGEMO_QUERY_END; /* 空queryのためエラー */
	outbuf = wordbuf_open();
	if (outbuf == NULL)
	    goto MIGEMO_QUERY_END; /* 出力用のメモリ領域不足のためエラー */

	/* 単語群をrxgenオブジェクトに入力し正規表現を得る */
	object->addword = (MIGEMO_PROC_ADDWORD)addword_rxgen;
	rxgen_reset(object->rx);
	for (p = querylist; p; p = p->next)
	{
	    unsigned char* answer;

	    /*printf("query=%s\n", p->ptr);*/
	    query_a_word(object, p->ptr);
	    /* 検索パターン(正規表現)生成 */
	    answer = rxgen_generate(object->rx);
	    rxgen_reset(object->rx);
	    wordbuf_cat(outbuf, answer);
	    rxgen_release(object->rx, answer);
	}
    }

MIGEMO_QUERY_END:
    if (outbuf)
    {
	retval = outbuf->buf;
	outbuf->buf = NULL;
	wordbuf_close(outbuf);
    }
    if (querylist)
	wordlist_close(querylist);

    return retval;
}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
	int argi;
	char *envarea = NULL;

	for (argi = 1; (argi < argc); argi++) {
		if (argnmatch(argv[argi], "--env=")) {
			char *p = strchr(argv[argi], '=');
			loadenv(p+1, envarea);
		}
		else if (argnmatch(argv[argi], "--area=")) {
			char *p = strchr(argv[argi], '=');
			envarea = strdup(p+1);
		}
		else if (strcmp(argv[argi], "--debug") == 0) {
			debug = 1;
		}
	}

	redirect_cgilog("hobbit-notifylog");
	load_hostnames(xgetenv("BBHOSTS"), NULL, get_fqdn());

	fprintf(stdout, "Content-type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));

	cgidata = cgi_request();
	if (cgidata == NULL) {
		/* Present the query form */
		sethostenv("", "", "", colorname(COL_BLUE), NULL);
		showform(stdout, "notify", "notify_form", COL_BLUE, getcurrenttime(NULL), NULL, NULL);
		return 0;
	}

	parse_query();

	/* Now generate the webpage */
	headfoot(stdout, "notify", "", "header", COL_GREEN);
	fprintf(stdout, "<center>\n");
	do_notifylog(stdout, maxcount, maxminutes, fromtime, totime, 
			pageregex, expageregex, 
			hostregex, exhostregex, 
			testregex, extestregex,
			rcptregex, exrcptregex);
	fprintf(stdout, "</center>\n");
	headfoot(stdout, "notify", "", "footer", COL_GREEN);

	return 0;
}
Ejemplo n.º 12
0
int main(int argc, char** argv)
{

	unsigned int psize;
	GWBUF* qbuff;
	char *tok;
	char readbuff[4092];
	FILE* infile;
	FILE* outfile;
	
	if(argc != 3){
		printf("Usage: canonizer <input file> <output file>\n");
		return 1;
	} 

	if(mysql_library_init(num_elements, server_options, server_groups)){
		printf("Embedded server init failed.\n");
		return 1;
	}
	
	infile = fopen(argv[1],"rb");
	outfile = fopen(argv[2],"wb");
	
	if(infile == NULL || outfile == NULL){
		printf("Opening files failed.\n");
		return 1;
	}

	while(!feof(infile))
		{
			fgets(readbuff,4092,infile);
			psize = strlen(readbuff);
			if(psize < 4092){
				qbuff = gwbuf_alloc(psize + 7);
				*(qbuff->sbuf->data + 0) = (unsigned char)psize;
				*(qbuff->sbuf->data + 1) = (unsigned char)(psize>>8);
				*(qbuff->sbuf->data + 2) = (unsigned char)(psize>>16);
				*(qbuff->sbuf->data + 4) = 0x03;
				memcpy(qbuff->start + 5,readbuff,psize + 1);
				parse_query(qbuff);
				tok = skygw_get_canonical(qbuff);
				fprintf(outfile,"%s\n",tok);
				free(tok);
				gwbuf_free(qbuff);
			}			
		}
Ejemplo n.º 13
0
Archivo: isql.c Proyecto: nevali/libsql
int
main(int argc, char **argv)
{
	EditLine *el;
	History *hist;
	const char *buf;
	int num, state;
	
	check_args(argc, argv);
	if(connect_uri)
	{
		sql_conn = sql_connect(connect_uri);
		if(!sql_conn)
		{
			fprintf(stderr, "%s: [%s] %s\n", short_program_name, sql_sqlstate(NULL), sql_error(NULL));
			exit(EXIT_FAILURE);
		}
	}
	fprintf(stderr, "%s interactive SQL shell (%s)\n\n", PACKAGE, VERSION);
	fprintf(stderr, 
		"Type:  \\c URI to establish a new connection\n"
		"       \\g or ; to execute query\n"
		"       \\G to execute the query showing results in long format\n"
		"       \\q to end the SQL session\n"
		"\n"
		);
	hist = history_init();
	el = el_init(argv[0], stdin, stdout, stderr);
	el_set(el, EL_EDITOR, "emacs");
	el_set(el, EL_SIGNAL, 1);
	el_set(el, EL_PROMPT, prompt);
	el_set(el, EL_HIST, history, hist);
	el_source(el, NULL);
	while((buf = el_gets(el, &num)) != NULL && num != 0)
	{
		state = parse_query(buf);
		if(state == 0)
		{
			exec_queries(hist);
		}
	}
	return 0;
}
Ejemplo n.º 14
0
	bool	URL::parse(const std::string& str)
	{
		clear();

		
		bytebuffer buff(str.c_str(),str.length());
		bool continue_hand=true;

		// now ====> http://www.example.com:8080/login/auth.do?user=test&pass=12344321
#ifdef _DEBUG
		//std::cout<<"parse URL = >"<< buff.as_string()<< std::endl;
#endif // _DEBUG

		if(continue_hand) continue_hand=parse_protocol(buff,m_url_protocol);
		// now ====> www.example.com:8080/login/auth.do?user=test&pass=12344321
#ifdef _DEBUG
		//std::cout<<"parse_protocol = >"<< buff.as_string()<< std::endl;
#endif // _DEBUG

		if(continue_hand) continue_hand=parse_host(buff,m_url_host);
		// now ====> :8080/login/auth.do?user=test&pass=12344321
#ifdef _DEBUG
		//std::cout<<"parse_host = >"<< buff.as_string()<< std::endl;
#endif // _DEBUG

		if(continue_hand) continue_hand=parse_port(buff,m_url_port);
		// now ====> /login/auth.do?user=test&pass=12344321
#ifdef _DEBUG
		//std::cout<<"parse_port = >"<< buff.as_string()<< std::endl;
#endif // _DEBUG

		if(continue_hand) continue_hand=parse_path(buff,m_url_path);
		// now ====> ?user=test&pass=12344321
#ifdef _DEBUG
		//std::cout<<"parse_path = >"<< buff.as_string()<< std::endl;
#endif // _DEBUG

		if(continue_hand) continue_hand=parse_query(buff,m_url_query_list);
		// now ====> [empty]
		
		
		return continue_hand;
	}
Ejemplo n.º 15
0
int
query_objects(isns_client_t *clnt, int argc, char **argv)
{
	isns_attr_list_t query_key = ISNS_ATTR_LIST_INIT;
	isns_attr_list_t oper_attrs = ISNS_ATTR_LIST_INIT;
	isns_object_list_t objects = ISNS_OBJECT_LIST_INIT;
	uint32_t	status;
	isns_simple_t	*qry;
	unsigned int	i;

	if (!parse_query(argv, argc, &query_key, &oper_attrs))
		isns_fatal("Unable to parse query\n");

	qry = isns_create_query(clnt, &query_key);
	isns_attr_list_destroy(&query_key);

	/* Add the list of attributes we request */
	for (i = 0; i < oper_attrs.ial_count; ++i)
		isns_query_request_attr(qry, oper_attrs.ial_data[i]);
	isns_attr_list_destroy(&oper_attrs);

	status = isns_client_call(clnt, &qry);
	if (status != ISNS_SUCCESS) {
		isns_error("Query failed: %s\n", isns_strerror(status));
		return status;
	}

	status = isns_query_response_get_objects(qry, &objects);
	if (status) {
		isns_error("Unable to extract object list from query response: %s\n",
				isns_strerror(status), status);
		return status;
	}

	isns_object_list_print(&objects, isns_print_stdout);
	isns_object_list_destroy(&objects);
	isns_simple_free(qry);

	return status;
}
Ejemplo n.º 16
0
static int bmx_handler(request_rec *r)
{
    apr_status_t rv;
    struct bmx_objectname *query = NULL;

    /* Determine if we are the handler for this request. */
    if (r->handler && strcmp(r->handler, BMX_HANDLER)) {
        return DECLINED;
    }

    /* Disallow any method except GET */
    if (r->method_number != M_GET) {
        return DECLINED;
    }

    /* FIXME: check that the Accept: header has a mime-type we can accept */
    /* FIXME: if no valid types in Accept: header, return code 415 */
    /* FIXME: return the correct mime-type */
    ap_set_content_type(r, "text/plain");

    if (r->header_only) {
        return OK;
    }

    rv = parse_query(r, &query);
    if (rv != APR_SUCCESS) {
        ap_log_rerror(APLOG_MARK, APLOG_CRIT, rv, r, "Failed to parse query");
        return HTTP_BAD_REQUEST;
    }

    /* FIXME: allow other bmx_bean_print functions other than text/plain */
    rv = bmx_run_query_hook(r, query, bmx_bean_print_text_plain);
    if (rv != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_CRIT, rv, r, "Error running "
                      "bmx_run_query_hook, BMX Query failed");
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    return OK;
}
Ejemplo n.º 17
0
int
main(int argc, char **argv)
{
    char *qs[] = {
        "select count(*) from users.events group_by user_email,time(1h) where time>now()-1d;",
        "explain select users.events group_by user_email,time(1h) where time>now()-1d;",
        "select * from foo where time < -1s",
        "select * from merge(/.*/) where time < -1s",
        "list series /",
        "select count(*) from users.events group_by user_email,time(1h) where time >> now()-1d;",
        "select value from t where c == 5 and b == 6;",
        "select value from t where c == '5';",
        "select value from cpu.idle where value > 90 and (time > now() - 1d or value > 80) and time < now() - 1w;",
        "select email from users.events where email =~ /gmail\\\\.com/i and time>now()-2d;",
        "select email from users.events where email in ('*****@*****.**')",
        "select * from foobar limit",
        "list continuous queries;",
        "list series /foo/ bar",
        "select -1 * value from t where c == 5 and b == 6;",
        "select value from cpu.idle where value > 90 and (time > now() - 1d or value > 80) and time < now() - 1w last 10;",
        "drop series foobar",
        "drop continuous query 5;",
        "select count(bar) as the_count from users.events group_by user_email,time(1h);",
        "select email from users.events as events where email === /gmail\\\\.com/i and time>now()-2d;",
        "select value from t where c = '5';",
        "select * from foo into bar;",
        "list queries;",
    };

    int i;
    for (i = 0; i < sizeof(qs) / sizeof(char*); i++) {
        // test freeing on close for different types of queries
        queries q = parse_query(qs[i]);
        close_queries(&q);
    }

    printf("Checked %d queries for memory leak\n", i);

    return 0;
}
Ejemplo n.º 18
0
//uri = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
TextCursor parse_uri(TextCursor cursor)
{
    cursor = parse_scheme(cursor);
    if(get_char(cursor) != ':')
        throw ParseError();
    cursor = parse_hier_part(cursor);
    try
    {
        cursor = parse_query(cursor);
    }
    catch(ParseError)
    {
    }
    try
    {
        cursor = parse_fragment(cursor);
    }
    catch(ParseError)
    {
    }
    return cursor;
}
Ejemplo n.º 19
0
		void query(const std::string& q)
		{
			if (q == query_)return;
			parse_query(q.c_str(), &query_, query_map_);
		}
Ejemplo n.º 20
0
int
cgi_main (OCState * state)
{
    int err = 0;
    char * path_info;
    char * path_translated;
    char * query_string;
    char * if_modified_since;
    time_t since_time, last_time;
    struct stat statbuf;
    int built_path_translated=0;

    httpdate_init ();

    path_info = getenv ("PATH_INFO");
    path_translated = getenv ("PATH_TRANSLATED");
    query_string = getenv ("QUERY_STRING");
    if_modified_since = getenv ("HTTP_IF_MODIFIED_SINCE");

    memset (state, 0, sizeof(*state));
    state->end = -1.0;
    state->do_skeleton = 1;

    if (path_translated == NULL) {
        if (path_info == NULL)
            return path_undefined ("PATH_TRANSLATED and PATH_INFO");

        path_translated = prepend_document_root (path_info);
        if (path_translated == NULL)
            return path_undefined ("PATH_TRANSLATED");

        built_path_translated = 1;
    }

    state->infilename = path_translated;

    /* Get Last-Modified time */
    if (stat (path_translated, &statbuf) == -1) {
        switch (errno) {
        case ENOENT:
            return 0;
        default:
            fprintf (stderr, "oggz-chop: %s: %s\n", path_translated, strerror(errno));
            return -1;
        }
    }

    last_time = statbuf.st_mtime;

    if (if_modified_since != NULL) {
        int len;

        fprintf (stderr, "If-Modified-Since: %s\n", if_modified_since);

        len = strlen (if_modified_since) + 1;
        since_time = httpdate_parse (if_modified_since, len);

        if (last_time <= since_time) {
            header_not_modified();
            header_end();
            return 1;
        }
    }

    header_content_type_ogg ();

    header_last_modified (last_time);

    header_accept_timeuri_ogg ();

    parse_query (state, query_string);

    header_end();

    err = 0;
    err = chop (state);

    if (built_path_translated && path_translated != NULL)
        free (path_translated);

    return err;
}
Ejemplo n.º 21
0
int main(int argc, char *argv[])
{
	char dirid[PATH_MAX];
	char outdir[PATH_MAX];
	char xymonwebenv[PATH_MAX];
	char xymongencmd[PATH_MAX];
	char xymongentimeopt[100];
	char csvdelimopt[100];
	char *xymongen_argv[20];
	pid_t childpid;
	int childstat;
	char htmldelim[100];
	char startstr[30], endstr[30];
	int cleanupoldreps = 1;
	int argi, newargi;
	char *envarea = NULL;
	char *useragent = NULL;
	int usemultipart = 1;

	newargi = 0;
	xymongen_argv[newargi++] = xymongencmd;
	xymongen_argv[newargi++] = xymongentimeopt;

	for (argi=1; (argi < argc); argi++) {
		if (argnmatch(argv[argi], "--env=")) {
			char *p = strchr(argv[argi], '=');
			loadenv(p+1, envarea);
		}
		else if (argnmatch(argv[argi], "--area=")) {
			char *p = strchr(argv[argi], '=');
			envarea = strdup(p+1);
		}
		else if (strcmp(argv[1], "--noclean") == 0) {
			cleanupoldreps = 0;
		}
		else {
			xymongen_argv[newargi++] = argv[argi];
		}
	}

	redirect_cgilog("report");

	cgidata = cgi_request();
	if (cgidata == NULL) {
		/* Present the query form */
		sethostenv("", "", "", colorname(COL_BLUE), NULL);
		printf("Content-type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));
		showform(stdout, "report", "report_form", COL_BLUE, getcurrenttime(NULL)-86400, NULL, NULL);
		return 0;
	}

	useragent = getenv("HTTP_USER_AGENT");
	if (useragent && strstr(useragent, "KHTML")) {
		/* KHTML (Konqueror, Safari) cannot handle multipart documents. */
		usemultipart = 0;
	}

	envcheck(reqenv);
	parse_query();

	/*
	 * We need to set these variables up AFTER we have put them into the xymongen_argv[] array.
	 * We cannot do it before, because we need the environment that the command-line options 
	 * might provide.
	 */
	if (xgetenv("XYMONGEN")) sprintf(xymongencmd, "%s", xgetenv("XYMONGEN"));
	else sprintf(xymongencmd, "%s/bin/xymongen", xgetenv("XYMONHOME"));

	snprintf(xymongentimeopt, sizeof(xymongentimeopt)-1,"--reportopts=%u:%u:1:%s", (unsigned int)starttime, (unsigned int)endtime, style);

	sprintf(dirid, "%u-%u", (unsigned int)getpid(), (unsigned int)getcurrenttime(NULL));
	if (!csvoutput) {
		sprintf(outdir, "%s/%s", xgetenv("XYMONREPDIR"), dirid);
		mkdir(outdir, 0755);
		xymongen_argv[newargi++] = outdir;
		sprintf(xymonwebenv, "XYMONWEB=%s/%s", xgetenv("XYMONREPURL"), dirid);
		putenv(xymonwebenv);
	}
	else {
		sprintf(outdir, "--csv=%s/%s.csv", xgetenv("XYMONREPDIR"), dirid);
		xymongen_argv[newargi++] = outdir;
		sprintf(csvdelimopt, "--csvdelim=%c", csvdelim);
		xymongen_argv[newargi++] = csvdelimopt;
	}

	xymongen_argv[newargi++] = NULL;

	if (usemultipart) {
		/* Output the "please wait for report ... " thing */
		snprintf(htmldelim, sizeof(htmldelim)-1, "xymonrep-%u-%u", (int)getpid(), (unsigned int)getcurrenttime(NULL));
		printf("Content-type: multipart/mixed;boundary=%s\n", htmldelim);
		printf("\n");
		printf("--%s\n", htmldelim);
		printf("Content-type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));

		/* It's ok with these hardcoded values, as they are not used for this page */
		sethostenv("", "", "", colorname(COL_BLUE), NULL);
		sethostenv_report(starttime, endtime, 97.0, 99.995);
		headfoot(stdout, "repnormal", "", "header", COL_BLUE);

		strftime(startstr, sizeof(startstr), "%b %d %Y", localtime(&starttime));
		strftime(endstr, sizeof(endstr), "%b %d %Y", localtime(&endtime));
		printf("<CENTER><A NAME=begindata>&nbsp;</A>\n");
		printf("<BR><BR><BR><BR>\n");
		printf("<H3>Generating report for the period: %s", htmlquoted(startstr));
		printf(" - %s ", htmlquoted(endstr));
		printf("(%s)<BR>\n", htmlquoted(style));
		printf("<P><P>\n");
		fflush(stdout);
	}

	/* Go do the report */
	childpid = fork();
	if (childpid == 0) {
		execv(xymongencmd, xymongen_argv);
	}
	else if (childpid > 0) {
		wait(&childstat);

		/* Ignore SIGHUP so we dont get killed during cleanup of XYMONREPDIR */
		signal(SIGHUP, SIG_IGN);

		if (WIFEXITED(childstat) && (WEXITSTATUS(childstat) != 0) ) {
			char msg[4096];

			if (usemultipart) printf("--%s\n\n", htmldelim);
			sprintf(msg, "Could not generate report.<br>\nCheck that the %s/www/rep/ directory has permissions '-rwxrwxr-x' (775)<br>\n and that is is set to group %d", xgetenv("XYMONHOME"), (int)getgid());
			errormsg(msg);
		}
		else {
			/* Send the browser off to the report */
			if (usemultipart) {
				printf("Done...Report is <A HREF=\"%s/%s/%s\">here</a>.</P></BODY></HTML>\n", xgetenv("XYMONREPURL"), dirid, suburl);
				fflush(stdout);
				printf("--%s\n\n", htmldelim);
			}
			printf("Content-Type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));
			printf("<HTML><HEAD>\n");
			if (!csvoutput) {
				printf("<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"0; URL=%s/%s/%s\"\n", 
					xgetenv("XYMONREPURL"), dirid, suburl);
				printf("</HEAD><BODY>Report is available <a href=\"%s/%s/%s\">here</a></BODY></HTML>\n",
					xgetenv("XYMONREPURL"), dirid, suburl);
			}
			else {
				printf("<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"0; URL=%s/%s.csv\"\n", 
					xgetenv("XYMONREPURL"), dirid);
				printf("</HEAD><BODY>Report is available <a href=\"%s/%s.csv\">here</a></BODY></HTML>\n",
					xgetenv("XYMONREPURL"), dirid);
			}
			if (usemultipart) printf("\n--%s\n", htmldelim);
			fflush(stdout);
		}

		if (cleanupoldreps) cleandir(xgetenv("XYMONREPDIR"));
	}
	else {
		if (usemultipart) printf("--%s\n\n", htmldelim);
		printf("Content-Type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));
		errormsg("Fork failed");
	}

	return 0;
}
Ejemplo n.º 22
0
/**
 * The routeQuery entry point. This is passed the query buffer
 * to which the filter should be applied. Once processed the
 * query is passed to the downstream component
 * (filter or router) in the filter chain.
 *
 * The function checks whether required logging trigger conditions are met and if so, 
 * tries to extract a SQL query out of the query buffer, canonize the query, add 
 * a timestamp to it and publish the resulting string on the exchange.
 * The message is tagged with an unique identifier and the clientReply will
 * use the same identifier for the reply from the backend to form a query-reply pair.
 * 
 * @param instance	The filter instance data
 * @param session	The filter session
 * @param queue		The query data
 */
static	int	
routeQuery(FILTER *instance, void *session, GWBUF *queue)
{
  MQ_SESSION	*my_session = (MQ_SESSION *)session;
  MQ_INSTANCE	*my_instance = (MQ_INSTANCE *)instance;
  char		*ptr, t_buf[128], *combined,*canon_q,*sesshost,*sessusr;
  bool		success = false, src_ok = false,schema_ok = false,obj_ok = false;
  int		length, i, j,dbcount = 0;
  char**	sesstbls;
  unsigned int	plen = 0;
  amqp_basic_properties_t *prop;  

  /**The user is changing databases*/
  if(*((char*)(queue->start + 4)) == 0x02){
    if(my_session->db){
      free(my_session->db);
    }
    plen = pktlen(queue->start);
    my_session->db = calloc(plen,sizeof(char));
    memcpy(my_session->db,queue->start + 5,plen - 1);
  }

  if(modutil_is_SQL(queue)){

    /**Parse the query*/
   
    if (!query_is_parsed(queue)){
      success = parse_query(queue);
    }

    if(!success){
      skygw_log_write(LOGFILE_ERROR,"Error: Parsing query failed.");      
      goto send_downstream;
    }

    if(!my_instance->log_all){
      if(!skygw_is_real_query(queue)){
	goto send_downstream;
      }
    } 

    if(my_instance->trgtype == TRG_ALL){
      skygw_log_write_flush(LOGFILE_TRACE,"Trigger is TRG_ALL");
      schema_ok = true;
      src_ok = true;
      obj_ok = true;
      goto validate_triggers;
    }
    
    if(my_instance->trgtype & TRG_SOURCE && my_instance->src_trg){
      
      if(session_isvalid(my_session->session)){
	
        sessusr = session_getUser(my_session->session);
	sesshost = session_get_remote(my_session->session);
	
	/**Username was configured*/
	if(my_instance->src_trg->usize > 0){
	  for(i = 0;i<my_instance->src_trg->usize;i++){

	    if(strcmp(my_instance->src_trg->user[i],sessusr) == 0)
	      {
		skygw_log_write_flush(LOGFILE_TRACE,"Trigger is TRG_SOURCE: user: %s = %s",my_instance->src_trg->user[i],sessusr);
		src_ok = true;
		break;
	      }
	    
	  }

	  
	}

	/**If username was not matched, try to match hostname*/

	if(!src_ok && my_instance->src_trg->hsize > 0){

	  for(i = 0;i<my_instance->src_trg->hsize;i++){
	    
	    if(strcmp(my_instance->src_trg->host[i],sesshost) == 0)
	      {
		skygw_log_write_flush(LOGFILE_TRACE,"Trigger is TRG_SOURCE: host: %s = %s",my_instance->src_trg->host[i],sesshost);
		src_ok = true;
		break;
	      }
	  
	  }

	}

      }

      if(src_ok && !my_instance->strict_logging){
	schema_ok = true;
	obj_ok = true;
	goto validate_triggers;
      }

    }else{
      src_ok = true;
    }



    if(my_instance->trgtype & TRG_SCHEMA && my_instance->shm_trg){
      int tbsz = 0,z;
      char** tblnames = skygw_get_table_names(queue,&tbsz,true);
      char* tmp;
      bool all_remotes = true;

      for(z = 0;z<tbsz;z++){
	if((tmp = strchr(tblnames[z],'.')) != NULL){
	  char *lasts;
	  tmp = strtok_r(tblnames[z],".",&lasts);
	  for(i = 0; i<my_instance->shm_trg->size; i++){
	    
	    if(strcmp(tmp,my_instance->shm_trg->objects[i]) == 0){
	      
	      skygw_log_write_flush(LOGFILE_TRACE,"Trigger is TRG_SCHEMA: %s = %s",tmp,my_instance->shm_trg->objects[i]);
	      
	      schema_ok = true;
	      break;
	    }
	  } 
	}else{
	  all_remotes = false;
	}
	free(tblnames[z]);
      }
      free(tblnames);

      if(!schema_ok && !all_remotes && my_session->db && strlen(my_session->db)>0){

	for(i = 0; i<my_instance->shm_trg->size; i++){
	  
	  if(strcmp(my_session->db,my_instance->shm_trg->objects[i]) == 0){
	    
	    skygw_log_write_flush(LOGFILE_TRACE,"Trigger is TRG_SCHEMA: %s = %s",my_session->db,my_instance->shm_trg->objects[i]);
	    
	    schema_ok = true;
	    break;
	  }
	}
      }

      if(schema_ok && !my_instance->strict_logging){
	src_ok = true;
	obj_ok = true;
	goto validate_triggers;
      }

    }else{
      schema_ok = true;
    }


    if(my_instance->trgtype & TRG_OBJECT && my_instance->obj_trg){

      sesstbls = skygw_get_table_names(queue,&dbcount,false);

      for(j = 0; j<dbcount; j++){      
	char* tbnm = NULL;

	if((strchr(sesstbls[j],'.')) != NULL){
	  char *lasts;
	  tbnm = strtok_r(sesstbls[j],".",&lasts);
	  tbnm = strtok_r(NULL,".",&lasts);
	}else{
	  tbnm = sesstbls[j];
	}
	

	for(i = 0; i<my_instance->obj_trg->size; i++){
	  

	  if(!strcmp(tbnm,my_instance->obj_trg->objects[i])){
	    obj_ok = true;
	    skygw_log_write_flush(LOGFILE_TRACE,"Trigger is TRG_OBJECT: %s = %s",my_instance->obj_trg->objects[i],sesstbls[j]);
	    break;
	  }

	}

      }
      if(dbcount > 0){
	for(j = 0; j<dbcount; j++){
	  free(sesstbls[j]);
	}
	free(sesstbls);
	dbcount = 0;
      }

      if(obj_ok && !my_instance->strict_logging){
	src_ok = true;
	schema_ok = true;
	goto validate_triggers;
      }

    }else{
      obj_ok = true;
    }


  validate_triggers:

    if(src_ok&&schema_ok&&obj_ok){

      /**
       * Something matched the trigger, log the query
       */

      skygw_log_write_flush(LOGFILE_TRACE,"Routing message to: %s:%d %s as %s/%s, exchange: %s<%s> key:%s queue:%s",
			    my_instance->hostname,my_instance->port,
			    my_instance->vhost,my_instance->username,
			    my_instance->password,my_instance->exchange,
			    my_instance->exchange_type,my_instance->key,
			    my_instance->queue);

      if(my_session->uid == NULL){

	my_session->uid = calloc(33,sizeof(char));

	if(!my_session->uid){
	  skygw_log_write(LOGFILE_ERROR,"Error : Out of memory.");
	}else{
	  genkey(my_session->uid,32);
	}

      }
    
      if (queue->next != NULL)
      {
        queue = gwbuf_make_contiguous(queue);
      }
      
      if(modutil_extract_SQL(queue, &ptr, &length)){

	my_session->was_query = true;
      
	if((prop = malloc(sizeof(amqp_basic_properties_t)))){
	  prop->_flags = AMQP_BASIC_CONTENT_TYPE_FLAG |
	    AMQP_BASIC_DELIVERY_MODE_FLAG |
	    AMQP_BASIC_MESSAGE_ID_FLAG | 
	    AMQP_BASIC_CORRELATION_ID_FLAG;
	  prop->content_type = amqp_cstring_bytes("text/plain");
	  prop->delivery_mode = AMQP_DELIVERY_PERSISTENT;
	  prop->correlation_id = amqp_cstring_bytes(my_session->uid);
	  prop->message_id = amqp_cstring_bytes("query");
	}

   

	if(success){
      
	  /**Try to convert to a canonical form and use the plain query if unsuccessful*/
	  if((canon_q = skygw_get_canonical(queue)) == NULL){
	    skygw_log_write_flush(LOGFILE_ERROR,
				  "Error: Cannot form canonical query.");	
	  }

	}
 
	memset(t_buf,0,128);      
	sprintf(t_buf, "%lu|",(unsigned long)time(NULL));

	int qlen = strnlen(canon_q,length) + strnlen(t_buf,128);
	if((combined = malloc((qlen+1)*sizeof(char))) == NULL){
	  skygw_log_write_flush(LOGFILE_ERROR,
				"Error: Out of memory");
	}
	strcpy(combined,t_buf);
	strncat(combined,canon_q,length);
      
	pushMessage(my_instance,prop,combined);
	free(canon_q);
      }

    } 

    /** Pass the query downstream */
  }
 send_downstream:
  return my_session->down.routeQuery(my_session->down.instance,
				     my_session->down.session, queue);
}
Ejemplo n.º 23
0
int main(int argc, char **argv) {
  int i=0;
  char* inquery=NULL;
  char query[MAXQUERYLEN];
  int pcount=0;
  int ql,found;
  char* res=NULL;
  char* database=DEFAULT_DATABASE;
  char* params[MAXPARAMS];
  char* values[MAXPARAMS];
  int hformat=1; // for header 0: csv, 1: json: reset later after reading params

  // Set up timeout signal and abnormal termination handlers:
  // the termination handler clears the read lock and detaches database.
  // This may fail, however, for some lock strategies and in case
  // nontrivial operations are taken in the handler.
#if _MSC_VER  // no signals on windows
#else
  signal(SIGSEGV,termination_handler);
  signal(SIGINT,termination_handler);
  signal(SIGFPE,termination_handler);
  signal(SIGABRT,termination_handler);
  signal(SIGTERM,termination_handler);
  signal(SIGALRM,timeout_handler);
  alarm(TIMEOUT_SECONDS);
#endif

  // for debugging print the plain content-type immediately
  // printf("content-type: text/plain\r\n");

  // get the cgi query: passed by server or given on the command line
  inquery=getenv("QUERY_STRING");
  if (inquery==NULL && argc>1) inquery=argv[1];
  // or use your own query string for testing a la
  // inquery="db=1000&op=search&field=1&value=2&compare=equal&type=record&from=0&count=3";

  // parse the query

  if (inquery==NULL || inquery[0]=='\0') errhalt(NOQUERY_ERR);
  ql=strlen(inquery);
  if (ql>MAXQUERYLEN) errhalt(LONGQUERY_ERR);
  strcpy((char*)query,inquery);
  //printf("query: %s\n",query);

  pcount=parse_query(query,ql,params,values);
  if (pcount<=0) errhalt(MALFQUERY_ERR);

  //for(i=0;i<pcount;i++) {
  //  printf("param %s val %s\n",params[i],values[i]);
  //}

  // query is now successfully parsed: find the database

  for(i=0;i<pcount;i++) {
    if (strncmp(params[i],"db",MAXQUERYLEN)==0) {
      if ((values[i]!=NULL) && (values[i][0]!='\0')) {
        if (atoi(values[i])==0 && !(values[i][0]=='0' && values[i][1]=='\0')) {
          errhalt(DB_PARAM_ERR);
        }
        database=values[i];
        break;
      }
    }
  }

  //find the operation and dispatch

  found=0;
  for(i=0;i<pcount;i++) {
    if (strncmp(params[i],"op",MAXQUERYLEN)==0) {
      if (strncmp(values[i],"search",MAXQUERYLEN)==0) {
        found=1;
        res=search(database,params,values,pcount,&hformat);
        // here the locks should be freed and database detached
        break;
      } else if (strncmp(values[i],"recids",MAXQUERYLEN)==0) {
        found=1;
        res=recids(database,params,values,pcount,&hformat);
        // here the locks should be freed and database detached
        break;
      } else {
        errhalt(UNKNOWN_OP_ERR);
      }
    }
  }
  if (!found) errhalt(NO_OP_ERR);
  print_final(res,hformat);
  if (res!=NULL) free(res); // not really necessary and wastes time: process exits
  return 0;
}
Ejemplo n.º 24
0
int main(int argc, char *argv[])
{
	void *hostwalk, *clonewalk;
	int argi;
	char *envarea = NULL;

	strbuffer_t *outbuf;
	char msgline[4096];
	char oneurl[10240];
	int gotany = 0;
	enum { OP_INITIAL, OP_YES, OP_NO } gotonepage = OP_INITIAL; /* Tracks if all matches are on one page */
	char *onepage = NULL;	/* If gotonepage==OP_YES, then this is the page */

	/*[wm] regex support */
	#define BUFSIZE		256
	regex_t re;
	char    re_errstr[BUFSIZE];
	int 	re_status;

	for (argi=1; (argi < argc); argi++) {
		if (argnmatch(argv[argi], "--env=")) {
			char *p = strchr(argv[argi], '=');
			loadenv(p+1, envarea);
		}
		else if (argnmatch(argv[argi], "--area=")) {
			char *p = strchr(argv[argi], '=');
			envarea = strdup(p+1);
		}
	}

	redirect_cgilog("findhost");

	cgidata = cgi_request();
	if (cgidata == NULL) {
		/* Present the query form */
		sethostenv("", "", "", colorname(COL_BLUE), NULL);
		printf("Content-type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));
		showform(stdout, "findhost", "findhost_form", COL_BLUE, getcurrenttime(NULL), NULL, NULL);
		return 0;
	}

	parse_query();

	if ( (re_status = regcomp(&re, pSearchPat, re_flag)) != 0 ) {
		regerror(re_status, &re, re_errstr, BUFSIZE);

		print_header();
		printf("<tr><td align=left><font color=red>%s</font></td>\n",  pSearchPat);
		printf("<td align=left><font color=red>%s</font></td></tr>\n", re_errstr);
		print_footer();

		return 0;
	}

	outbuf = newstrbuffer(0);
	load_hostnames(xgetenv("HOSTSCFG"), NULL, get_fqdn());
	hostwalk = first_host();
	while (hostwalk) {
		/* 
		 * [wm] - Allow the search to be done on the hostname
		 * 	also on the "displayname" and the host comment
		 *	Maybe this should be implemented by changing the HTML form, but until than..
		 * we're supposing that hostname will NEVER be null	
		 */
		char *hostname, *displayname, *comment, *ip;

		hostname = xmh_item(hostwalk, XMH_HOSTNAME);
		displayname = xmh_item(hostwalk, XMH_DISPLAYNAME);
		comment = xmh_item(hostwalk, XMH_COMMENT);
		ip = xmh_item(hostwalk, XMH_IP);

       		if ( regexec (&re, hostname, (size_t)0, NULL, 0) == 0  ||
			(regexec(&re, ip, (size_t)0, NULL, 0) == 0)    ||
       			(displayname && regexec (&re, displayname, (size_t)0, NULL, 0) == 0) ||
			(comment     && regexec (&re, comment, 	   (size_t)0, NULL, 0) == 0)   ) {
	
			/*  match */
			addtobuffer(outbuf, "<tr>\n");
			sprintf(msgline, "<td align=left> %s </td>\n", displayname ? displayname : hostname);
			addtobuffer(outbuf, msgline);
			sprintf(oneurl, "%s/%s/#%s",
				xgetenv("XYMONWEB"), xmh_item(hostwalk, XMH_PAGEPATH), hostname);
			sprintf(msgline, "<td align=left> <a href=\"%s\">%s</a>\n",
				oneurl, xmh_item(hostwalk, XMH_PAGEPATHTITLE));
			addtobuffer(outbuf, msgline);
			gotany++;

			/* See if all of the matches so far are on one page */
			switch (gotonepage) {
			  case OP_INITIAL:
				gotonepage = OP_YES;
				onepage = xmh_item(hostwalk, XMH_PAGEPATH);
				break;

			  case OP_YES:
				if (strcmp(onepage, xmh_item(hostwalk, XMH_PAGEPATH)) != 0) gotonepage = OP_NO;
				break;

			  case OP_NO:
				break;
			}

			clonewalk = next_host(hostwalk, 1);
			while (clonewalk && (strcmp(xmh_item(hostwalk, XMH_HOSTNAME), xmh_item(clonewalk, XMH_HOSTNAME)) == 0)) {
				sprintf(msgline, "<br><a href=\"%s/%s/#%s\">%s</a>\n",
					xgetenv("XYMONWEB"), 
					xmh_item(clonewalk, XMH_PAGEPATH),
					xmh_item(clonewalk, XMH_HOSTNAME),
					xmh_item(clonewalk, XMH_PAGEPATHTITLE));
				addtobuffer(outbuf, msgline);
				clonewalk = next_host(clonewalk, 1);
				gotany++;
			}

			addtobuffer(outbuf, "</td>\n</tr>\n");
	
			hostwalk = clonewalk;
		}
		else {
			hostwalk = next_host(hostwalk, 0);
		}
	}
	regfree (&re); 	/*[wm] - free regex compiled patern */
	
	if (dojump) {
		if (gotany == 1) {
			printf("Location: %s%s\n\n", xgetenv("XYMONWEBHOST"), oneurl);
			return 0;
		}
		else if ((gotany > 1) && (gotonepage == OP_YES)) {
			printf("Location: %s%s/%s/\n\n", 
			       xgetenv("XYMONWEBHOST"), xgetenv("XYMONWEB"), onepage);
			return 0;
		}
	}

	print_header();
	if (!gotany) {
		printf("<tr><td align=left>%s</td><td align=left>Not found</td></tr>\n", pSearchPat);
	}
	else {
		printf("%s", grabstrbuffer(outbuf));
	}
	print_footer();

	/* [wm] - Free the strdup allocated memory */
	if (pSearchPat) xfree(pSearchPat);

	return 0;
}
Ejemplo n.º 25
0
int main(int argc, char *argv[])
{
	int argi;
	char *envarea = NULL;
	char **critconfig = NULL;
	int cccount = 0;
	char *hffile = "critical";

	critconfig = (char **)calloc(1, sizeof(char *));

	for (argi = 1; (argi < argc); argi++) {
		if (argnmatch(argv[argi], "--env=")) {
			char *p = strchr(argv[argi], '=');
			loadenv(p+1, envarea);
		}
		else if (argnmatch(argv[argi], "--area=")) {
			char *p = strchr(argv[argi], '=');
			envarea = strdup(p+1);
		}
		else if (strcmp(argv[argi], "--debug") == 0) {
			debug = 1;
		}
		else if (strcmp(argv[argi], "--tooltips") == 0) {
			usetooltips = 1;
		}
		else if (argnmatch(argv[argi], "--acklevel=")) {
			char *p = strchr(argv[argi], '=');
			critacklevel = atoi(p+1);
		}
		else if (argnmatch(argv[argi], "--config=")) {
			char *p = strchr(argv[argi], '=');

			critconfig[cccount] = strdup(p+1);
			cccount++;
			critconfig = (char **)realloc(critconfig, (1 + cccount)*sizeof(char *));
			critconfig[cccount] = NULL;
		}
		else if (argnmatch(argv[argi], "--hffile=")) {
			char *p = strchr(argv[argi], '=');
			hffile = strdup(p+1);
		}
	}

	if (!critconfig[0]) {
		critconfig = (char **)realloc(critconfig, 2*sizeof(char *));
		critconfig[0] = (char *)malloc(strlen(xgetenv("XYMONHOME")) + strlen(DEFAULT_CRITCONFIGFN) + 2);
		sprintf(critconfig[0], "%s/%s", xgetenv("XYMONHOME"), DEFAULT_CRITCONFIGFN);
		critconfig[1] = NULL;
	}

	redirect_cgilog("criticalview");

	setdocurl(hostsvcurl("%s", xgetenv("INFOCOLUMN"), 1));

	parse_query();
	load_hostnames(xgetenv("HOSTSCFG"), NULL, get_fqdn());
	load_all_links();
	fprintf(stdout, "Content-type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));

	use_recentgifs = 1;

	if (getboard(mincolor) == 0) {
		int i;
		char *oneconfig, *onename;
		int *partcolor = NULL, *partprio = NULL;
		xtreePos_t hhandle;

		for (i=0; (critconfig[i]); i++) {
			oneconfig = strchr(critconfig[i], ':');
			load_critconfig(oneconfig ? oneconfig+1 : critconfig[i]);
			loadstatus(maxprio, maxage, mincolor, wantacked);

			/* Determine background color and max. priority */
			if (i == 0) {
				partcolor = (int *)malloc(sizeof(int));
				partprio = (int *)malloc(sizeof(int));
			}
			else {
				partcolor = (int *)realloc(partcolor, (i+1)*sizeof(int));
				partprio = (int *)realloc(partprio, (i+1)*sizeof(int));
			}
			partcolor[i] = COL_GREEN;
			partprio[i] = 0;

			for (hhandle = xtreeFirst(rbstate[i]); (hhandle != xtreeEnd(rbstate[i])); hhandle = xtreeNext(rbstate[i], hhandle)) {
				hstatus_t *itm;

				itm = (hstatus_t *)xtreeData(rbstate[i], hhandle);

				if (itm->color > partcolor[i]) partcolor[i] = itm->color;
				if (itm->config->priority > partprio[i]) partprio[i] = itm->config->priority;
			}

			if (partcolor[i] > pagecolor) pagecolor = partcolor[i];
		}

		for (i=0; (critconfig[i]); i++) {
			oneconfig = strchr(critconfig[i], ':'); 
			if (oneconfig) {
				*oneconfig = '\0';
				oneconfig++;
				onename = (char *)malloc(strlen("DIVIDERTEXT=") + strlen(critconfig[i]) + 1);
				sprintf(onename, "DIVIDERTEXT=%s", critconfig[i]);
				putenv(onename);
			}
			else {
				oneconfig = critconfig[i];
				putenv("DIVIDERTEXT=");
			}

			generate_critpage(rbstate[i], hostsonpage[i], stdout, 
					  (i == 0) ? (critconfig[1] ? "critmulti" : hffile) : "divider", 
					  (critconfig[i+1] == NULL) ? hffile : "divider",
					  partcolor[i], partprio[i]);
		}
	}
	else {
		fprintf(stdout, "Cannot load Xymon status\n");
	}

	return 0;
}
Ejemplo n.º 26
0
int do_request(void)
{
	int color = 0;
	char timesincechange[100];
	time_t logtime = 0, acktime = 0, disabletime = 0;
	char *log = NULL, *firstline = NULL, *sender = NULL, *clientid = NULL, *flags = NULL;	/* These are free'd */
	char *restofmsg = NULL, *ackmsg = NULL, *dismsg = NULL, *acklist=NULL;	/* These are just used */
	int ishtmlformatted = 0;
	int clientavail = 0;
	char *ip, *displayname;

	if (parse_query() != 0) return 1;

	{
		char *s;
		
		s = xgetenv("CLIENTLOGS"); 
		if (s) {
			hostdatadir = (char *)malloc(strlen(s) + strlen(hostname) + 12);
			sprintf(hostdatadir, "%s/%s", s, hostname);
		}
		else {
			s = xgetenv("BBVAR");
			hostdatadir = (char *)malloc(strlen(s) + strlen(hostname) + 12);
			sprintf(hostdatadir, "%s/hostdata/%s", s, hostname);
		}
	}

	if (outform == FRM_CLIENT) {
		if (source == SRC_HOBBITD) {
			char *hobbitdreq;
			int hobbitdresult;

			hobbitdreq = (char *)malloc(1024 + strlen(hostname) + (service ? strlen(service) : 0));
			sprintf(hobbitdreq, "clientlog %s", hostname);
			if (service && *service) sprintf(hobbitdreq + strlen(hobbitdreq), " section=%s", service);

			hobbitdresult = sendmessage(hobbitdreq, NULL, NULL, &log, 1, BBTALK_TIMEOUT);
			if (hobbitdresult != BB_OK) {
				char errtxt[4096];
				sprintf(errtxt, "Status not available: Req=%s, result=%d\n", hobbitdreq, hobbitdresult);
				errormsg(errtxt);
				return 1;
			}
		}
		else if (source == SRC_HISTLOGS) {
			char logfn[PATH_MAX];
			FILE *fd;

			sprintf(logfn, "%s/%s", hostdatadir, tstamp);
			fd = fopen(logfn, "r");
			if (fd) {
				struct stat st;
				int n;

				fstat(fileno(fd), &st);
				log = (char *)malloc(st.st_size + 1);
				n = fread(log, 1, st.st_size, fd);
				if (n >= 0) *(log+n) = '\0'; else *log = '\0';
				fclose(fd);
			}
		}

		restofmsg = (log ? log : strdup("<No data>\n"));
	}
	else if ((strcmp(service, xgetenv("TRENDSCOLUMN")) == 0) || (strcmp(service, xgetenv("INFOCOLUMN")) == 0)) {
		loadhostdata(hostname, &ip, &displayname);
		ishtmlformatted = 1;
		sethostenv(displayname, ip, service, colorname(COL_GREEN), hostname);
		sethostenv_refresh(600);
		color = COL_GREEN;
		logtime = time(NULL);
		strcpy(timesincechange, "0 minutes");

		if (strcmp(service, xgetenv("TRENDSCOLUMN")) == 0) {
			log = restofmsg = generate_trends(hostname);
		}
		else if (strcmp(service, xgetenv("INFOCOLUMN")) == 0) {
			log = restofmsg = generate_info(hostname);
		}
	}
	else if (source == SRC_HOBBITD) {
		char hobbitdreq[1024];
		int hobbitdresult;
		char *items[20];
		int icount;
		time_t logage, clntstamp;
		char *sumline, *msg, *p;

		sprintf(hobbitdreq, "hobbitdlog host=%s test=%s fields=hostname,testname,color,flags,lastchange,logtime,validtime,acktime,disabletime,sender,cookie,ackmsg,dismsg,client,acklist,BBH_IP,BBH_DISPLAYNAME,clntstamp", hostname, service);
		hobbitdresult = sendmessage(hobbitdreq, NULL, NULL, &log, 1, BBTALK_TIMEOUT);
		if ((hobbitdresult != BB_OK) || (log == NULL) || (strlen(log) == 0)) {
			errormsg("Status not available\n");
			return 1;
		}

		sumline = log; p = strchr(log, '\n'); *p = '\0';
		msg = (p+1); p = strchr(msg, '\n');
		if (!p) {
			firstline = strdup(msg);
			restofmsg = NULL;
		}
		else { 
			*p = '\0'; 
			firstline = strdup(msg); 
			restofmsg = (p+1);
			*p = '\n'; 
		}

		memset(items, 0, sizeof(items));
		p = gettok(sumline, "|"); icount = 0;
		while (p && (icount < 20)) {
			items[icount++] = p;
			p = gettok(NULL, "|");
		}

		/*
		 * hostname,		[0]
		 * testname,		[1]
		 * color,		[2]
		 * flags,		[3]
		 * lastchange,		[4]
		 * logtime,		[5]
		 * validtime,		[6]
		 * acktime,		[7]
		 * disabletime,		[8]
		 * sender,		[9]
		 * cookie,		[10]
		 * ackmsg,		[11]
		 * dismsg,		[12]
		 * client,		[13]
		 * acklist		[14]
		 * BBH_IP		[15]
		 * BBH_DISPLAYNAME	[16]
		 * clienttstamp         [17]
		 */
		color = parse_color(items[2]);
		flags = strdup(items[3]);
		logage = time(NULL) - atoi(items[4]);
		timesincechange[0] = '\0'; p = timesincechange;
		if (logage > 86400) p += sprintf(p, "%d days,", (int) (logage / 86400));
		p += sprintf(p, "%d hours, %d minutes", (int) ((logage % 86400) / 3600), (int) ((logage % 3600) / 60));
		logtime = atoi(items[5]);
		if (items[7] && strlen(items[7])) acktime = atoi(items[7]);
		if (items[8] && strlen(items[8])) disabletime = atoi(items[8]);
		sender = strdup(items[9]);

		if (items[11] && strlen(items[11])) ackmsg = items[11];
		if (ackmsg) nldecode(ackmsg);

		if (items[12] && strlen(items[12])) dismsg = items[12];
		if (dismsg) nldecode(dismsg);

		if (items[13]) clientavail = (*items[13] == 'Y');

		acklist = ((items[14] && *items[14]) ? strdup(items[14]) : NULL);

		ip = (items[15] ? items[15] : "");
		displayname = ((items[16]  && *items[16]) ? items[16] : hostname);
		clntstamp = ((items[17]  && *items[17]) ? atol(items[17]) : 0);

		sethostenv(displayname, ip, service, colorname(COL_GREEN), hostname);
		sethostenv_refresh(60);
	}
	else if (source == SRC_HISTLOGS) {
		char logfn[PATH_MAX];
		struct stat st;
		int fd;
		/*
		 * Some clients (Unix disk reports) dont have a newline before the
		 * "Status unchanged in ..." text. Most do, but at least Solaris and
		 * AIX do not. So just look for the text, not the newline.
		 */
		char *statusunchangedtext = "Status unchanged in ";
		char *receivedfromtext = "Message received from ";
		char *clientidtext = "Client data ID ";
		char *p, *unchangedstr, *receivedfromstr, *clientidstr, *hostnamedash;
		int n;

		if (!tstamp) errormsg("Invalid request");

		loadhostdata(hostname, &ip, &displayname);
		hostnamedash = strdup(hostname);
		p = hostnamedash; while ((p = strchr(p, '.')) != NULL) *p = '_';
		p = hostnamedash; while ((p = strchr(p, ',')) != NULL) *p = '_';
		sprintf(logfn, "%s/%s/%s/%s", xgetenv("BBHISTLOGS"), hostnamedash, service, tstamp);
		xfree(hostnamedash);
		p = tstamp; while ((p = strchr(p, '_')) != NULL) *p = ' ';
		sethostenv_histlog(tstamp);

		if (stat(logfn, &st) == -1) {
			errormsg("Historical status log not available\n");
			return 1;
		}

		fd = open(logfn, O_RDONLY);
		if (fd < 0) {
			errormsg("Unable to access historical logfile\n");
			return 1;
		}
		log = (char *)malloc(st.st_size+1);
		n = read(fd, log, st.st_size);
		if (n >= 0) *(log+n) = '\0'; else *log = '\0';
		close(fd);

		p = strchr(log, '\n'); 
		if (!p) {
			firstline = strdup(log);
			restofmsg = NULL;
		}
		else { 
			*p = '\0'; 
			firstline = strdup(log); 
			restofmsg = (p+1);
			*p = '\n'; 
		}


		color = parse_color(log);

		p = strstr(log, "<!-- [flags:"); 
		if (p) {
			p += strlen("<!-- [flags:");
			n = strspn(p, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
			flags = (char *)malloc(n+1);
			strncpy(flags, p, n);
			*(flags + n) = '\0';
		}

		timesincechange[0] = '\0';

		p = clientidstr = strstr(restofmsg, clientidtext);
		if (p) {
			p += strlen(clientidtext);
			n = strspn(p, "0123456789");
			clientid = (char *)malloc(n+1);
			strncpy(clientid, p, n);
			*(clientid+n) = '\0';
		}

		p = unchangedstr = strstr(restofmsg, statusunchangedtext);
		if (p) {
			p += strlen(statusunchangedtext);
			n = strcspn(p, "\n"); if (n >= sizeof(timesincechange)) n = sizeof(timesincechange);
			strncpy(timesincechange, p, n);
			timesincechange[n] = '\0';
		}

		p = receivedfromstr = strstr(restofmsg, receivedfromtext); 
		if (p) {
			p += strlen(receivedfromtext);
			n = strspn(p, "0123456789.");
			sender = (char *)malloc(n+1);
			strncpy(sender, p, n);
			*(sender+n) = '\0';
		}

		/* Kill the "Status unchanged ..." and "Message received ..." lines */
		if (unchangedstr) *unchangedstr = '\0';
		if (receivedfromstr) *receivedfromstr = '\0';
	}

	if (outform == FRM_CLIENT) {
		fprintf(stdout, "Content-type: text/plain\n\n");
		fprintf(stdout, "%s", restofmsg);
	}
	else {
		if (clientid && (source == SRC_HISTLOGS)) {
			char logfn[PATH_MAX];
			struct stat st;

			sprintf(logfn, "%s/%s", hostdatadir, clientid);
			clientavail = (stat(logfn, &st) == 0);

			if (clientavail) {
				sprintf(clienturi + strlen(clienturi), "&amp;TIMEBUF=%s", clientid);
			}
		}

		fprintf(stdout, "Content-type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));
		generate_html_log(hostname, 
			  displayname,
			  service, 
			  ip,
		          color, 
			  (sender ? sender : "Hobbit"), 
			  (flags ? flags : ""),
		          logtime, timesincechange, 
		          (firstline ? firstline : ""), 
			  (restofmsg ? restofmsg : ""), 
			  acktime, ackmsg, acklist,
			  disabletime, dismsg,
		          (source == SRC_HISTLOGS), 
			  wantserviceid, 
			  ishtmlformatted,
			  (source == SRC_HOBBITD),
			  multigraphs, (clientavail ? clienturi : NULL),
			  nkprio, nkttgroup, nkttextra,
			  stdout);
	}

	/* Cleanup CGI params */
	if (hostname) xfree(hostname);
	if (service) xfree(service);
	if (tstamp) xfree(tstamp);

	/* Cleanup main vars */
	if (clientid) xfree(clientid);
	if (sender) xfree(sender);
	if (flags) xfree(flags);
	if (firstline) xfree(firstline);
	if (log) xfree(log);

	return 0;
}
Ejemplo n.º 27
0
int httpp_parse(http_parser_t *parser, const char *http_data, unsigned long len)
{
    char *data, *tmp;
    char *line[MAX_HEADERS]; /* limited to 32 lines, should be more than enough */
    int i;
    int lines;
    char *req_type = NULL;
    char *uri = NULL;
    char *version = NULL;
    int whitespace, where, slen;

    if (http_data == NULL)
        return 0;

    /* make a local copy of the data, including 0 terminator */
    data = (char *)amalloc(len+1);
    memcpy(data, http_data, len);
    data[len] = 0;

    lines = split_headers(data, len, line);

    /* parse the first line special
    ** the format is:
    ** REQ_TYPE URI VERSION
    ** eg:
    ** GET /index.html HTTP/1.0
    */
    where = 0;
    whitespace = 0;
    slen = strlen(line[0]);
    req_type = line[0];
    for (i = 0; i < slen; i++) {
        if (line[0][i] == ' ') {
            whitespace = 1;
            line[0][i] = '\0';
        } else {
            /* we're just past the whitespace boundry */
            if (whitespace) {
                whitespace = 0;
                where++;
                switch (where) {
                case 1:
                    uri = &line[0][i];
                    break;
                case 2:
                    version = &line[0][i];
                    break;
                }
            }
        }
    }

    if (strcasecmp("GET", req_type) == 0) {
        parser->req_type = httpp_req_get;
    } else if (strcasecmp("POST", req_type) == 0) {
        parser->req_type = httpp_req_post;
    } else if (strcasecmp("HEAD", req_type) == 0) {
        parser->req_type = httpp_req_head;
    } else if (strcasecmp("SOURCE", req_type) == 0) {
        parser->req_type = httpp_req_source;
    } else if (strcasecmp("PLAY", req_type) == 0) {
        parser->req_type = httpp_req_play;
    } else if (strcasecmp("STATS", req_type) == 0) {
        parser->req_type = httpp_req_stats;
    } else {
        parser->req_type = httpp_req_unknown;
    }

    if (uri != NULL && strlen(uri) > 0) {
        char *query;
        if((query = strchr(uri, '?')) != NULL) {
            httpp_setvar(parser, HTTPP_VAR_RAWURI, uri);
            httpp_setvar(parser, HTTPP_VAR_QUERYARGS, query);
            *query = 0;
            query++;
            parse_query(parser, query);
        }

        parser->uri = strdup(uri);
    } else {
        free(data);
        return 0;
    }

    if ((version != NULL) && ((tmp = strchr(version, '/')) != NULL)) {
        tmp[0] = '\0';
        if ((strlen(version) > 0) && (strlen(&tmp[1]) > 0)) {
            httpp_setvar(parser, HTTPP_VAR_PROTOCOL, version);
            httpp_setvar(parser, HTTPP_VAR_VERSION, &tmp[1]);
        } else {
            free(data);
            return 0;
        }
    } else {
        free(data);
        return 0;
    }

    if (parser->req_type != httpp_req_none && parser->req_type != httpp_req_unknown) {
        switch (parser->req_type) {
        case httpp_req_get:
            httpp_setvar(parser, HTTPP_VAR_REQ_TYPE, "GET");
            break;
        case httpp_req_post:
            httpp_setvar(parser, HTTPP_VAR_REQ_TYPE, "POST");
            break;
        case httpp_req_head:
            httpp_setvar(parser, HTTPP_VAR_REQ_TYPE, "HEAD");
            break;
        case httpp_req_source:
            httpp_setvar(parser, HTTPP_VAR_REQ_TYPE, "SOURCE");
            break;
        case httpp_req_play:
            httpp_setvar(parser, HTTPP_VAR_REQ_TYPE, "PLAY");
            break;
        case httpp_req_stats:
            httpp_setvar(parser, HTTPP_VAR_REQ_TYPE, "STATS");
            break;
        default:
            break;
        }
    } else {
        free(data);
        return 0;
    }

    if (parser->uri != NULL) {
        httpp_setvar(parser, HTTPP_VAR_URI, parser->uri);
    } else {
        free(data);
        return 0;
    }

    parse_headers(parser, line, lines);

    free(data);

    return 1;
}
Ejemplo n.º 28
0
int main(int argc, char *argv[])
{
	char dirid[PATH_MAX];
	char outdir[PATH_MAX];
	char xymongencmd[PATH_MAX];
	char xymonwebenv[PATH_MAX];
	char xymongentimeopt[100];
	char *xymongen_argv[20];
	pid_t childpid;
	int childstat;
	char htmldelim[100];
	char startstr[20];
	int argi, newargi;
	char *envarea = NULL;
	char *useragent;
	int usemultipart = 1;

	newargi = 0;
	xymongen_argv[newargi++] = xymongencmd;
	xymongen_argv[newargi++] = xymongentimeopt;

	for (argi=1; (argi < argc); argi++) {
		if (argnmatch(argv[argi], "--env=")) {
			char *p = strchr(argv[argi], '=');
			loadenv(p+1, envarea);
		}
		else if (argnmatch(argv[argi], "--area=")) {
			char *p = strchr(argv[argi], '=');
			envarea = strdup(p+1);
		}
		else {
			xymongen_argv[newargi++] = argv[argi];
		}
	}
	xymongen_argv[newargi++] = outdir;
	xymongen_argv[newargi++] = NULL;

	redirect_cgilog("snapshot");

	cgidata = cgi_request();
	if (cgidata == NULL) {
		/* Present the query form */
		sethostenv("", "", "", colorname(COL_BLUE), NULL);
		printf("Content-type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));
		showform(stdout, "snapshot", "snapshot_form", COL_BLUE, getcurrenttime(NULL), NULL, NULL);
		return 0;
	}

	parse_query();

	useragent = getenv("HTTP_USER_AGENT");
	if (useragent && strstr(useragent, "KHTML")) {
		/* KHTML (Konqueror, Safari) cannot handle multipart documents. */
		usemultipart = 0;
	}

	/*
	 * Need to set these up AFTER putting them into xymongen_argv, since we
	 * need to have option parsing done first.
	 */
	if (xgetenv("XYMONGEN")) sprintf(xymongencmd, "%s", xgetenv("XYMONGEN"));
	else sprintf(xymongencmd, "%s/bin/xymongen", xgetenv("XYMONHOME"));

	snprintf(xymongentimeopt, sizeof(xymongentimeopt), "--snapshot=%u", (unsigned int)starttime);

	sprintf(dirid, "%lu-%u", (unsigned long)getpid(), (unsigned int)getcurrenttime(NULL));
	sprintf(outdir, "%s/%s", xgetenv("XYMONSNAPDIR"), dirid);
	if (mkdir(outdir, 0755) == -1) errormsg("Cannot create output directory");

	sprintf(xymonwebenv, "XYMONWEB=%s/%s", xgetenv("XYMONSNAPURL"), dirid);
	putenv(xymonwebenv);

	if (usemultipart) {
		/* Output the "please wait for report ... " thing */
		snprintf(htmldelim, sizeof(htmldelim)-1, "xymonrep-%lu-%u", (unsigned long)getpid(), (unsigned int)getcurrenttime(NULL));
		printf("Content-type: multipart/mixed;boundary=%s\n", htmldelim);
		printf("\n");
		printf("%s\n", htmldelim);
		printf("Content-type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));

		/* It's ok with these hardcoded values, as they are not used for this page */
		sethostenv("", "", "", colorname(COL_BLUE), NULL);
		sethostenv_report(starttime, starttime, 97.0, 99.995);
		headfoot(stdout, "snapshot", "", "header", COL_BLUE);

		strftime(startstr, sizeof(startstr), "%b %d %Y", localtime(&starttime));
		printf("<CENTER><A NAME=begindata>&nbsp;</A>\n");
		printf("<BR><BR><BR><BR>\n");
		printf("<H3>Generating snapshot: %s<BR>\n", htmlquoted(startstr));
		printf("<P><P>\n");
		fflush(stdout);
	}


	/* Go do the report */
	childpid = fork();
	if (childpid == 0) {
		execv(xymongencmd, xymongen_argv);
	}
	else if (childpid > 0) {
		wait(&childstat);

		/* Ignore SIGHUP so we don't get killed during cleanup of XYMONSNAPDIR */
		signal(SIGHUP, SIG_IGN);

		if (WIFEXITED(childstat) && (WEXITSTATUS(childstat) != 0) ) {
			if (usemultipart) printf("%s\n\n", htmldelim);
			printf("Content-Type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));
			errormsg("Could not generate report");
		}
		else {
			/* Send the browser off to the report */
			if (usemultipart) {
				printf("Done...<P></BODY></HTML>\n");
				fflush(stdout);
				printf("%s\n\n", htmldelim);
			}
			printf("Content-Type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));
			printf("<HTML><HEAD>\n");
			printf("<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"0; URL=%s/%s/\"\n", 
					xgetenv("XYMONSNAPURL"), dirid);
			printf("</HEAD><BODY BGCOLOR=\"000000\"></BODY></HTML>\n");
			if (usemultipart) printf("\n%s\n", htmldelim);
			fflush(stdout);
		}

		cleandir(xgetenv("XYMONSNAPDIR"));
	}
	else {
		if (usemultipart) printf("%s\n\n", htmldelim);
		printf("Content-Type: %s\n\n", xgetenv("HTMLCONTENTTYPE"));
		errormsg("Fork failed");
	}

	return 0;
}
Ejemplo n.º 29
0
int
cgi_main (fastphoto_t * params)
{
  int err = 0;
  char * path_info;
  char * path_translated;
  char * query_string;
  char * if_modified_since;
  time_t since_time;

  httpdate_init ();

  path_info = getenv ("PATH_INFO");
  path_translated = getenv ("PATH_TRANSLATED");
  query_string = getenv ("QUERY_STRING");
  if_modified_since = getenv ("HTTP_IF_MODIFIED_SINCE");

  photo_init (&params->in, path_translated);

  if (if_modified_since != NULL) {
    int len;

    fprintf (stderr, "If-Modified-Since: %s\n", if_modified_since);

    len = strlen (if_modified_since) + 1;
    since_time = httpdate_parse (if_modified_since, len);

    if (params->in.mtime <= since_time) {
      header_not_modified();
      header_end();
      return 1;
    }
  }

  header_content_type_jpeg ();

  config_init (params);

  parse_query (params, query_string);

  if (params->x || params->y || params->scale || params->gray ||
      params->quality) {
    cache_init (params, path_info);
  } else {
    params->nochange = 1;
  }

  err = 0;
  if (!(params->nochange || params->cached)) {
    err = resize (params);
  }
  
  if (!err) {
    cgi_send (params);
  }

  if (params->out.name) {
    free (params->out.name);
  }

  return err;
}
Ejemplo n.º 30
0
static rb_item*
parse_item (const char *field, char *uri, config_ctx *ctx)
{
	rb_item *item;
	enum snmp_version version;
	const char *msg;
	char *copy;
	char *scheme, *host, *user, *path, *query, *port;

	/* Parse the SNMP URI */
	copy = strdup (uri);
	msg = cfg_parse_uri (uri, &scheme, &host, &port, &user, &path, &query);
	if (msg)
		errx(2, "%s: %s: %s", ctx->confname, msg, copy);
	free (copy);

	ASSERT (host && path);

	/* Currently we only support SNMP pollers */
	msg = cfg_parse_scheme (scheme, &version);
	if (msg)
		errx (2, "%s: %s: %s", ctx->confname, msg, scheme);

	/* Make a new item */
	item = (rb_item*)xcalloc (sizeof (*item));

	/* And parse the main field OID */
	if (mib_parse (path, &(item->field_oid)) == -1) {
		log_warnx ("%s: ignorning invalid MIB: %s", ctx->confname, path);
		free (item);
		return NULL;
	}

	if (item->field_oid.len >= ASN_MAXOIDLEN) {
		log_warnx ("%s: ignoring OID that is too long: %s", ctx->confname, path);
		free (item);
		return NULL;
	}

	/* Setup the basics */
	item->field = field;
	item->community = user ? user : "******";
	item->version = version;

	item->poller = NULL; /* Set later in config_done */
	item->vtype = VALUE_UNSET;
	item->portnum = port ? port : "161";

	/* Parse the hosts, query */
	parse_hosts (item, host, ctx);
	parse_query (item, query, ctx);

	log_debug ("parsed MIB into oid: %s -> %s", path,
	           asn_oid2str (&item->field_oid));

	/* And add it to the list */
	item->next = ctx->items;
	ctx->items = item;

	return item;
}