Esempio n. 1
0
File: main.c Progetto: rosedu/cspay
int
main(void)
{
	void *ret = NULL;


	conn = mysql_init(NULL);
	ret = mysql_real_connect(
		conn,
		"localhost", "cspay", "cspay_passwd",
		"cspay",
		0, NULL, 0);

	if (!ret) {
		printf("%s\n", mysql_error(conn));
		return EXIT_FAILURE;
	}

	#define	Q1	"select * from users"
	do_query(Q1);

	#define	Q2	"select id from users"
	do_query(Q2);

	#define	Q3	"select * from users where id=2"
	do_query(Q3);

	mysql_close(conn);
	return 0;
}
Esempio n. 2
0
BWKV::BWKV( const char * fn ) : BWDB(fn) {
	if (!table_exists("kv")) {
		do_query(_bwkv_drop_sql);
		do_query(_bwkv_create_table_sql);
		do_query(_bwkv_create_trigger_sql);
		do_query(_bwkv_insert_sql);
	}
}
Esempio n. 3
0
static gint
do_queryv(struct meta1_service_url_s *surl)
{
	gint rc;
	gchar **pq;
	struct gridd_client_s *client;

	GRID_DEBUG("Contacting SHARD[%"G_GINT64_FORMAT"] at [%s][%s]",
			surl->seq, surl->host, surl->args);

	client = gridd_client_create_idle(surl->host);
	gridd_client_set_keepalive(client, TRUE);
	gridd_client_start(client);

	rc = 1;
	for (pq=query; *pq ;pq++) {
		if (!do_query(client, surl, *pq)) {
			rc = 0;
			break;
		}
	}

	gridd_client_free(client);
	return rc;
}
Esempio n. 4
0
void do_query(const SOCKET sock, const char *query)
{
    char buf[2000];
    int i = 0, hide = hide_discl;

    if (send(sock, query, (int) strlen(query), 0) == SOCKET_ERROR)
	err_exit("send");
/* Using shutdown breaks the buggy RIPE server.
    if (shutdown(sock, 1) == SOCKET_ERROR)
	err_exit("shutdown");
*/
    for (;;) {
        if (LineRecv((HANDLE)sock, buf, sizeof(buf), 60000) == 0)
            if (win_errno != ERROR_SUCCESS)
	        if (win_errno == ERROR_HANDLE_EOF)
	            break;
	        else
	            err_exit("Receive error");

        if (hide == 1) {
	    if (strncmp(buf, hide_strings[i+1], strlen(hide_strings[i+1]))==0)
		hide = 2;	/* stop hiding */
	    continue;		/* hide this line */
	}
	if (hide == 0) {
	    for (i = 0; hide_strings[i] != NULL; i += 2) {
		if (strncmp(buf, hide_strings[i], strlen(hide_strings[i]))==0){
		    hide = 1;	/* start hiding */
		    break;
		}
	    }
	    if (hide == 1)
		continue;	/* hide the first line */
	}
#ifdef EXT_6BONE
	/* % referto: whois -h whois.arin.net -p 43 as 1 */
	if (strncmp(buf, "% referto:", 10) == 0) {
	    char nh[256], np[16], nq[1024];

	    if (sscanf(buf, REFERTO_FORMAT, nh, np, nq) == 3) {
		SOCKET fd;

		if (verb)
		    printf(_("Detected referral to %s on %s.\n"), nq, nh);
		strcat(nq, "\r\n");
		fd = openconn(nh, np);
		do_query(fd, nq);
		continue;
	    }
	}
#endif
	
	CharToOem(buf, buf);
	puts(buf);
    }

    if (hide == 1)
	err_quit(_("Catastrophic error: disclaimer text has been changed.\r\n"
		   "Please upgrade this program.\r\n"));
}
Esempio n. 5
0
int Indexer::query(const string& keyWord) //This user interface can be redefine to support different indexing method, such as simple bool methnd.
{
	POSTING_INDEX::iterator postingIndexIter = do_query(keyWord);

	if(postingIndexIter == m_postingIndex.end())
	{
		return -1;
	}
	
	POSTING_LIST::iterator postingListIter;
	DOC_SET::iterator docSetIter;

	cout<<"Qeury Result: The following URL contained the key word -"<<keyWord<<endl;
	
	size_t countUrl = 0;
	for(postingListIter = (postingIndexIter->second).begin(); postingListIter != (postingIndexIter->second).end(); postingListIter++)
	{
		docSetIter = m_docSet.find(postingListIter->first);

		countUrl++;
		cout<<countUrl<<": "<<(docSetIter->second).first<<endl;
	}

	return (postingIndexIter->second).size();
}
Esempio n. 6
0
File: score.c Progetto: JMCQ87/MyPA
table * get_score_table (MYSQL *mysql, const char *q)
{
  MYSQL_RES *res;
  MYSQL_ROW row;
  int num;
  table *ret = NULL, *table_ptr;
  
  res = do_query (mysql, q);

  if (res && (num = mysql_num_rows(res))) {
    ret = calloc (sizeof(table), num+1);
    assert (ret);

    table_ptr = ret;
    while ((row = mysql_fetch_row (res)) ) {
      table_ptr->id = atoi(row[0]);
      table_ptr->score = atoll(row[1]);
      table_ptr++;
    }

    check_error (mysql);
    mysql_free_result(res);
  }

  return ret;
}
Esempio n. 7
0
void do_choice(int choice)
{
	printf("is in the process of the first %d a choice \n", choice);

	switch (choice)
	{
		case INSERT :
			do_insert();
			break;
		case QUERY:
			do_query();
			break;
		case UPDATE:
			do_update();
			break;
		case DELETE:
			do_delete();
			break;
		case LIST:
			do_list_all();
			break;
		case QUIT:
			do_quit();
			break;
		default:
			break;
	}
}
Esempio n. 8
0
void
load_configuration ()
{
    l_debug ("Loading configuration for Profile:%s",profile);

    if (config != NULL)
        g_hash_table_remove_all (config);
    config = g_hash_table_new (g_str_hash, g_str_equal);
    MYSQL_ROW row;
    MYSQL_RES *result;
    int res =
      do_query (FALSE, lyricDb, "SELECT config_key,config_value FROM config WHERE profile='%s'", profile);
    if (res != 0) {
        return;
    }
    result = mysql_store_result (lyricDb);
    gboolean conf_found = FALSE;
    while ((row = mysql_fetch_row (result))) {
        conf_found = TRUE;
        g_hash_table_insert (config, g_strdup (row[0]), g_strdup (row[1]));
        l_debug ("Config \"%s\" set to \"%s\"", row[0], row[1]);
    }
    if (!conf_found) {
        l_debug ("No configuration found - load lyricue to setup");
        exit (1);
    }
    load_font_defaults ();
    mysql_free_result (result);
}
Esempio n. 9
0
void BWKV::del( const char * key ) {
	if (value(key)) {
		BWString q = "DELETE FROM kv WHERE key = ?";
		std::vector<BWString> p({key});
		do_query(q, p);
	}
}
Esempio n. 10
0
enum piglit_result
piglit_display(void)
{
	enum piglit_result ret = do_query(queries, ARRAY_SIZE(queries));
#ifdef DISPLAY
	piglit_present_results();
#endif
	return ret;
}
Esempio n. 11
0
bool BWKV::value( const char * k, const char * v ) {
	BWString q;
	if (value(k)) {
		q = "UPDATE kv SET value = ? WHERE key = ?";
	} else {
		q = "INSERT INTO kv (value, key) VALUES (?, ?)";
	}
	std::vector<BWString> p({BWString(v), BWString(k)});
	return do_query(q, p);
}
Esempio n. 12
0
void do_query(const int sock, const char *query)
{
    char buf[2000], *p;
    int i = 0, hide = hide_discl;

    if (send(sock, query, strlen(query), 0) == SOCKET_ERROR)
	h_perror("send");
/* Using shutdown breaks the buggy RIPE server.
    if (shutdown(sock, 1) == SOCKET_ERROR)
	h_perror("shutdown");
*/
    while (BufRecv((HANDLE)sock, buf, 1, 60000) == 1) {
        LineRecv((HANDLE)sock, buf+1, sizeof(buf)-1, 60000);
	
        if (hide == 1) {
	    if (strncmp(buf, hide_strings[i+1], strlen(hide_strings[i+1]))==0)
		hide = 2;	/* stop hiding */
	    continue;		/* hide this line */
	}
	if (hide == 0) {
	    for (i = 0; hide_strings[i] != NULL; i += 2) {
		if (strncmp(buf, hide_strings[i], strlen(hide_strings[i]))==0){
		    hide = 1;	/* start hiding */
		    break;
		}
	    }
	    if (hide == 1)
		continue;	/* hide the first line */
	}
#ifdef EXT_6BONE
	/* % referto: whois -h whois.arin.net -p 43 as 1 */
	if (strncmp(buf, "% referto:", 10) == 0) {
	    char nh[256], np[16], nq[1024];

	    if (sscanf(buf, REFERTO_FORMAT, nh, np, nq) == 3) {
		int fd;

		if (verb)
		    printf(_("Detected referral to %s on %s.\n"), nq, nh);
		strcat(nq, "\r\n");
		fd = openconn(nh, np);
		do_query(fd, nq);
		continue;
	    }
	}
#endif
	for (p = buf; *p && *p != '\r' && *p != '\n'; p++);
	*p = '\0';
	fprintf(stdout, "%s\n", buf);
    }

    if (hide == 1)
	err_quit(_("Catastrophic error: disclaimer text has been changed.\n"
		   "Please upgrade this program.\n"));
}
Esempio n. 13
0
local void * work_thread(void *dummy)
{
	struct db_cmd *cmd;

	mydb = mysql_init(NULL);

	if (mydb == NULL)
	{
		if (lm) lm->Log(L_WARN, "<hscore_mysql> init failed: %s", mysql_error(mydb));
		return NULL;
	}

	pthread_cleanup_push(close_db, mydb);

	connected = 0;

	/* try to connect */
	if (lm)
		lm->Log(L_INFO, "<hscore_mysql> connecting to mysql db on %s, user %s, db %s", host, user, dbname);
	while (mysql_real_connect(mydb, host, user, pw, dbname, 0, NULL, 0) == NULL)
	{
		if (lm) lm->Log(L_WARN, "<hscore_mysql> connect failed: %s", mysql_error(mydb));
		pthread_testcancel();
		sleep(10);
		pthread_testcancel();
	}

	connected = 1;

	/* now serve requests */
	for (;;)
	{
		/* the pthread_cond_wait inside MPRemove is a cancellation point */
		cmd = MPRemove(&dbq);
		if (!cmd) break;

		switch (cmd->type)
		{
			case CMD_NULL:
				if (cmd->cb)
					cmd->cb(0, NULL, cmd->clos);
				break;

			case CMD_QUERY:
				do_query(cmd);
				break;
		}

		afree(cmd);
	}

	pthread_cleanup_pop(1);

	return NULL;
}
Esempio n. 14
0
/*
 * See documentation in README file.
 */
int isn_query_2(struct sip_msg* _msg, char* _suffix, char* _service)
{
	char *user_s = NULL;
	int user_len, i, j;
	char name[MAX_DOMAIN_SIZE] = {0};
	char string[17] = {0};
	char szItad[17] = {0};
	size_t nItlen = 0;

	str *suffix, *service;

	suffix = (str*)_suffix;
	service = (str*)_service;

	if (parse_sip_msg_uri(_msg) < 0) {
		LM_ERR("Parsing of R-URI failed\n");
		return -1;
	}

	user_s = _msg->parsed_uri.user.s;
	user_len = _msg->parsed_uri.user.len;

	memcpy(&(string[0]), user_s, user_len);
	string[user_len] = (char)0;

	/* Do primitive test for correct ISN format, */
	/* and set szItad to the ISN ITAD (RFC 3872/2871). */
	/* Correct ISN format guessed from freenum.org and IANA */
	/* doc http://www.iana.org/assignments/trip-parameters/ */
	{
		char *pAster = strchr(string, '*');
		if (pAster && (nItlen = strspn(pAster + sizeof(char), "0123456789")))
			strncpy(szItad, pAster + sizeof(char), nItlen);
		else {
			LM_ERR("R-URI user does not contain a valid ISN\n");
			return -1;
		}
	}

	/* Ammend the original ENUM E.164 string logic to process */
	/* ISN numbers instead, which include a nonreversed ITAD. */
	i = user_len - nItlen - sizeof(char); /* Ex: *1212 */
	j = 0;
	while (i--) {
		name[j] = user_s[i];
		name[j + 1] = '.';
		j = j + 2;
	}

	strcat(name + j, szItad);  /* Copy the unreversed ITAD, */
	name[j + nItlen] = '.';    /* and append a trailing dot. */
	memcpy(name + j + nItlen + sizeof(char), suffix->s, suffix->len + 1);

	return do_query(_msg, string, name, service);
}
Esempio n. 15
0
int DB_CONN::insert_id() {
    int retval;
    MYSQL_ROW row;
    MYSQL_RES* rp;

    retval = do_query("select LAST_INSERT_ID()");
    if (retval) return retval;
    rp = mysql_store_result(mysql);
    row = mysql_fetch_row(rp);
    int x = atoi(row[0]);
    mysql_free_result(rp);
    return x;
}
Esempio n. 16
0
static int query_hook(int argc, char *argv[])
{
	switch (argc) {
	case 1:
		do_unquery();
		break;
	case 2:
		do_query(argv[1]);
		break;
	default:
		assert(!"code should never get here");
	}
	return 0;
}
Esempio n. 17
0
void
system_server(DiscoverFnTy fn_discovery, int fd1, int fd2)
{
  struct syserv_mesg mesg;

  fdin = fd1;
  fdout = fd2;

  inbuf_size = INIT_INBUF_SIZE;
  inbuf = (char *) malloc(inbuf_size);
  if (inbuf == NULL) {
    err(1, "malloc for inbuf failed");
  }
  signal_handler_init();

  for (;;) {
    int ret = read_mesg(&mesg);

    // failure on read from pipe
    if (ret == FAILURE) {
      err(1, "read from fdin failed");
    }

    // exit
    if (ret == END_OF_FILE || mesg.type == SYSERV_EXIT) {
      break;
    }

    // ack
    if (mesg.type == SYSERV_ACK) {
      write_mesg(SYSERV_ACK, 0);
    }

    // query
    else if (mesg.type == SYSERV_QUERY) {
      write_mesg(SYSERV_ACK, 0);
      do_query(fn_discovery, &mesg);
    }

    // unknown message
    else {
      err(1, "unknown mesg type from client: %d", mesg.type);
    }
  }

  exit(0);
}
Esempio n. 18
0
int
main (void)
{
  mongo_sync_connection *conn;

  conn = mongo_sync_connect ("localhost", 27017, FALSE);
  if (!conn)
    {
      fprintf (stderr, "Connection failed: %s\n", strerror (errno));
      return 1;
    }

  do_inserts (conn);
  do_query (conn);

  mongo_sync_disconnect (conn);
  return 0;
}
Esempio n. 19
0
int DB_CONN::get_double(const char* query, double& x) {
    int retval;
    MYSQL_ROW row;
    MYSQL_RES* resp;

    retval = do_query(query);
    if (retval) return retval;
    resp = mysql_store_result(mysql);
    if (!resp) return ERR_DB_NOT_FOUND;
    row = mysql_fetch_row(resp);
    if (!row || !row[0]) {
        retval = ERR_DB_NOT_FOUND;
    } else {
        x = atof(row[0]);
    }
    mysql_free_result(resp);
    return retval;
}
Esempio n. 20
0
//*********************************************************************
// Do function for regrw, called when the terminating carriage return
// is received.
//*********************************************************************
void do_regrw ( void )
{
    uint8_t reg_num ;
#if defined(__CODEVISIONAVR__)
    flash register_defs_t * ptr_reg_def ;
#elif defined(__GNUC__)
    register_defs_t * ptr_reg_def ;
#endif
    void (*fp)(uint8_t arg);

    reg_num = cmd_wks . regrw_cmd . reg_offset ;

    // Find the register information.    
    ptr_reg_def = regrw_find_reg_group ( reg_num ) ;
    if ( ptr_reg_def == NULL )
    {
        return ;
    }
    
    // Call the appropriate read or write handler
    // Get the offset of the register in its group
    if ( reg_num < 32 )
    {
        // Registers 0-31 are all offset 0
        reg_num = 0 ;
    }
    reg_num &= 0x1F;

    // Call the appropriate read or write handler
    if ( cmd_wks . regrw_cmd . write )
    {
	fp = (void (*)(uint8_t))pgm_word(ptr_reg_def->ptr_write_handler);
	fp( reg_num ) ;
    }
    else
    {
        fp = (void (*)(uint8_t))pgm_word(ptr_reg_def->ptr_read_handler);
	fp( reg_num ) ;
        do_query ( ) ;
    }
}
Esempio n. 21
0
/*
 * See documentation in README file.
 */
int enum_query_2(struct sip_msg* _msg, char* _suffix, char* _service)
{
	char *user_s;
	int user_len, i, j;
	char name[MAX_DOMAIN_SIZE];
	char string[17];

	str *suffix, *service;

	suffix = (str*)_suffix;
	service = (str*)_service;

	if (parse_sip_msg_uri(_msg) < 0) {
		LM_ERR("Parsing of R-URI failed\n");
		return -1;
	}

	if (is_e164(&(_msg->parsed_uri.user)) == -1) {
		LM_ERR("R-URI user is not an E164 number\n");
		return -1;
	}

	user_s = _msg->parsed_uri.user.s;
	user_len = _msg->parsed_uri.user.len;

	memcpy(&(string[0]), user_s, user_len);
	string[user_len] = (char)0;

	j = 0;
	for (i = user_len - 1; i > 0; i--) {
		name[j] = user_s[i];
		name[j + 1] = '.';
		j = j + 2;
	}

	memcpy(name + j, suffix->s, suffix->len + 1);

	return do_query(_msg, string, name, service);
}
Esempio n. 22
0
/*
 * See documentation in README file.
 */
int enum_query(struct sip_msg* _msg, str* suffix, str* service)
{
	char *user_s;
	int user_len, i, j;
	char name[MAX_DOMAIN_SIZE];
	char string[MAX_NUM_LEN];

	LM_DBG("enum_query on suffix <%.*s> service <%.*s>\n",
	       suffix->len, suffix->s, service->len, service->s);

	if (parse_sip_msg_uri(_msg) < 0) {
		LM_ERR("Parsing of R-URI failed\n");
		return -1;
	}

	user_s = _msg->parsed_uri.user.s;
	user_len = _msg->parsed_uri.user.len;

	if (is_e164(&(_msg->parsed_uri.user)) == -1) {
		LM_ERR("R-URI user '<%.*s>' is not an E164 number\n",
		user_len, user_s);
		return -1;
	}

	memcpy(&(string[0]), user_s, user_len);
	string[user_len] = (char)0;

	j = 0;
	for (i = user_len - 1; i > 0; i--) {
		name[j] = user_s[i];
		name[j + 1] = '.';
		j = j + 2;
	}

	memcpy(name + j, suffix->s, suffix->len + 1);

	return do_query(_msg, string, name, service);
}
Esempio n. 23
0
int DB_CONN::set_isolation_level(ISOLATION_LEVEL level) {
    const char* level_str;
    char query[256];

    switch(level) {
    case READ_UNCOMMITTED:
        level_str = "READ UNCOMMITTED";
        break;
    case READ_COMMITTED:
        level_str = "READ COMMITTED";
        break;
    case REPEATABLE_READ:
        level_str = "REPEATABLE READ";
        break;
    case SERIALIZABLE:
        level_str = "SERIALIZABLE";
        break;
    default:
        return -1;
    }
    sprintf(query, "SET SESSION TRANSACTION ISOLATION LEVEL %s", level_str);
    return do_query(query);
}
Esempio n. 24
0
/*
void client::command_manager::parse_query(const std::string &prefix, const std::string &default_command, const std::string &cmd, client::configuration &config, const Plugin::QueryRequestMessage::Request &request, Plugin::QueryResponseMessage::Response &response, const Plugin::QueryRequestMessage &request_message) {
	boost::program_options::variables_map vm;
	std::string real_command;
	try {
		command_type::const_iterator cit = commands.find(cmd);
		boost::program_options::variables_map vm;
		if (cit == commands.end()) {
			real_command = parse_command(cmd, prefix);
			if (real_command == "forward") {
				for (int i=0;i<request_message.header().metadata_size();i++) {
					if (request_message.header().metadata(i).key() == "command")
						config.data->command = request_message.header().metadata(i).value();
				}
				for (int i=0;i<request.arguments_size();i++) {
					config.data->arguments.push_back(request.arguments(i));
				}
			} else {
				po::options_description desc = create_descriptor(real_command, default_command, config);
				if (!nscapi::program_options::process_arguments_from_request(vm, desc, request, response)) 
					return;
			}
		} else {
			std::vector<std::string> args;
			real_command = parse_command(cit->second.command, prefix);
			po::options_description desc = create_descriptor(real_command, default_command, config);
			BOOST_FOREACH(std::string argument, cit->second.arguments) {
				for (int i=0;i<request.arguments_size();i++) {
					strEx::replace(argument, "$ARG" + strEx::s::xtos(i+1) + "$", request.arguments(i));
				}
				args.push_back(argument);
			}
			if (!nscapi::program_options::process_arguments_from_vector(vm, desc, request.command(), args, response)) 
				return;
		}
	} catch (const std::exception &e) {
		return nscapi::protobuf::functions::set_response_bad(response, "Exception processing command line: " + utf8::utf8_from_native(e.what()));
	}

	if (!config.data->target_id.empty()) {
		if (!config.targets.has_object(config.data->target_id))
			return nscapi::protobuf::functions::set_response_bad(response, "Target not found: " + config.data->target_id);
		//TODO: config.data->recipient.import(config.target_lookup->lookup_target(config.data->target_id));
	}
	if (real_command == "query" || (real_command.empty() && default_command == "query")) {
		do_query(config, request_message.header(), response);
	} else if (real_command == "exec" || (real_command.empty() && default_command == "exec")) {
		return nscapi::protobuf::functions::set_response_bad(response, "Paradigm shift currently not supported");
	} else if (real_command == "submit" || (real_command.empty() && default_command == "submit")) {
		return nscapi::protobuf::functions::set_response_bad(response, "Paradigm shift currently not supported");
	} else {
		return nscapi::protobuf::functions::set_response_bad(response, "Invalid command: "  +real_command);
	}
}
*/
void client::configuration::parse_query(const Plugin::QueryRequestMessage &request, Plugin::QueryResponseMessage &response) {

	std::string command = "";

	for (int i = 0; i<request.header().metadata_size(); i++) {
		if (request.header().metadata(i).key() == "command")
			command = request.header().metadata(i).value();
	}
	for (int i = 0; i < request.payload_size(); i++) {
		::Plugin::QueryRequestMessage::Request *reqp = request.mutable_payload(0);
		if (!command.empty()) {
			command = reqp->command();
		}
		// Check pre populated commands
		if (reqp->arguments_size() > 0) {

			boost::program_options::variables_map vm;
			std::string real_command = "query";
			try {
				po::options_description desc = create_descriptor(real_command, real_command, config);
				if (!nscapi::program_options::process_arguments_from_vector(vm, desc, real_command, args, response))
					return;
			}
			catch (const std::exception &e) {
				return nscapi::protobuf::functions::set_response_bad(response, "Exception processing command line: " + utf8::utf8_from_native(e.what()));
			}

			if (real_command == "query") {
				const ::Plugin::Common::Header header;
				do_query(config, header, response);
			}
			else {
				return nscapi::protobuf::functions::set_response_bad(response, "Invalid command: " + real_command);
			}
		}
	}
}
Esempio n. 25
0
int i_enum_query_2(struct sip_msg* _msg, char* _suffix, char* _service)
{
	char *user_s;
	int user_len, i, j;
	char name[MAX_DOMAIN_SIZE];
	char apex[MAX_COMPONENT_SIZE + 1];
	char separator[MAX_COMPONENT_SIZE + 1];
	int sdl = 0;    /* subdomain location: infrastructure enum offset */
	int cc_len;
	struct rdata* head;

	char string[17];

	str *suffix, *service;

	suffix = (str*)_suffix;
	service = (str*)_service;

	if (parse_sip_msg_uri(_msg) < 0) {
		LM_ERR("Parsing of R-URI failed\n");
		return -1;
	}

	if (is_e164(&(_msg->parsed_uri.user)) == -1) {
		LM_ERR("R-URI user is not an E164 number\n");
		return -1;
	}

	user_s = _msg->parsed_uri.user.s;
	user_len = _msg->parsed_uri.user.len;

	/* make sure we don't run out of space in strings */
	if (( 2*user_len + MAX_COMPONENT_SIZE + MAX_COMPONENT_SIZE + 4) > MAX_DOMAIN_SIZE) {
		LM_ERR("Strings too long\n");
		return -1;
	}
	if ( i_branchlabel.len > MAX_COMPONENT_SIZE ) {
		LM_ERR("i_branchlabel too long\n");
		return -1;
	}
	if ( suffix->len > MAX_COMPONENT_SIZE ) {
		LM_ERR("Suffix too long\n");
		return -1;
	}


	memcpy(&(string[0]), user_s, user_len);
	string[user_len] = (char)0;

	/* Set up parameters as for user-enum */
	memcpy(apex,  suffix->s , suffix->len);
	apex[suffix->len] = (char)0;
	sdl = 0;		/* where to insert i-enum separator */
	separator[0] = 0;	/* don't insert anything */

	cc_len = cclen(string + 1);

	if (!strncasecmp(i_bl_alg.s,"ebl",i_bl_alg.len)) {
		sdl = cc_len; /* default */

		j = 0;
		memcpy(name, i_branchlabel.s, i_branchlabel.len);
		j += i_branchlabel.len;
		name[j++] = '.';

		for (i = cc_len ; i > 0; i--) {
			name[j++] = user_s[i];
			name[j++] = '.';
		}
		memcpy(name + j, suffix->s, suffix->len + 1);

		LM_DBG("Looking for EBL record for %s.\n", name); 
		head = get_record(name, T_EBL);
		if (head == 0) {
			LM_DBG("No EBL found for %s. Defaulting to user ENUM.\n",name);
		} else {
		    	struct ebl_rdata* ebl;
			ebl = (struct ebl_rdata *) head->rdata;

			LM_DBG("EBL record for %s is %d / %.*s / %.*s.\n",
			       name, ebl->position, (int)ebl->separator_len,
			       ebl->separator,(int)ebl->apex_len, ebl->apex);

			if ((ebl->apex_len > MAX_COMPONENT_SIZE) || (ebl->separator_len > MAX_COMPONENT_SIZE)) {
				LM_ERR("EBL strings too long\n"); 
				return -1;
			}

			if (ebl->position > 15)  {
				LM_ERR("EBL position too large (%d)\n",
				       ebl->position); 
				return -1;
			}

			sdl = ebl->position;

			memcpy(separator, ebl->separator, ebl->separator_len);
			separator[ebl->separator_len] = 0;

			memcpy(apex, ebl->apex, ebl->apex_len);
			apex[ebl->apex_len] = 0;
			free_rdata_list(head);
		}
	} else if (!strncasecmp(i_bl_alg.s,"txt",i_bl_alg.len)) {
		sdl = cc_len; /* default */
		memcpy(separator, i_branchlabel.s, i_branchlabel.len);
		separator[i_branchlabel.len] = 0;
		/* no change to apex */

		j = 0;
		memcpy(name, i_branchlabel.s, i_branchlabel.len);
		j += i_branchlabel.len;
		name[j++] = '.';

		for (i = cc_len ; i > 0; i--) {
			name[j++] = user_s[i];
			name[j++] = '.';
		}
		memcpy(name + j, suffix->s, suffix->len + 1);

		head = get_record(name, T_TXT);
		if (head == 0) {
			LM_DBG("TXT found for %s. Defaulting to %d\n",
			       name, cc_len);
		} else {
			sdl = atoi(((struct txt_rdata*)head->rdata)->txt);
			LM_DBG("TXT record for %s is %d.\n", name, sdl);

			if ((sdl < 0) || (sdl > 10)) {
				LM_ERR("Sdl %d out of bounds. Set back to cc_len.\n", sdl);
				sdl = cc_len;
			}
			free_rdata_list(head);
		}
	} else {	/* defaults to CC */
		sdl = cc_len;
		memcpy(separator, i_branchlabel.s, i_branchlabel.len);
		separator[i_branchlabel.len] = 0;
		/* no change to apex */
	}

	j = 0;
	sdl++; /* to avoid comparing i to (sdl+1) */
	for (i = user_len - 1; i > 0; i--) {
		name[j] = user_s[i];
		name[j + 1] = '.';
		j = j + 2;
		if (separator[0] && (i == sdl)) { /* insert the I-ENUM separator here? */
			strcpy(name + j, separator);  /* we've checked string sizes. */
			j += strlen(separator);
			name[j++] = '.';
		}
	}

	memcpy(name + j, apex, strlen(apex)+1);

	return do_query(_msg, string, name, service);
}
Esempio n. 26
0
/*
 * Get or return cached transaction isolation mode
 */
POOL_TRANSACTION_ISOLATION pool_get_transaction_isolation(void)
{
	POOL_STATUS status;
	POOL_SELECT_RESULT *res;
	POOL_TRANSACTION_ISOLATION ret;

	if (!session_context)
	{
		pool_error("pool_get_transaction_isolation: session context is not initialized");
		return POOL_UNKNOWN;
	}

	/* It seems cached result is usable. Return it. */
	if (session_context->transaction_isolation != POOL_UNKNOWN)
		return session_context->transaction_isolation;

	/* No cached data is available. Ask backend. */
	status = do_query(MASTER(session_context->backend),
					  "SELECT current_setting('transaction_isolation')", &res, MAJOR(session_context->backend));

	if (res->numrows <= 0)
	{
		pool_error("pool_get_transaction_isolation: do_query returns no rows");
		free_select_result(res);
		return POOL_UNKNOWN;
	}
	if (res->data[0] == NULL)
	{
		pool_error("pool_get_transaction_isolation: do_query returns no data");
		free_select_result(res);
		return POOL_UNKNOWN;
	}
	if (res->nullflags[0] == -1)
	{
		pool_error("pool_get_transaction_isolation: do_query returns NULL");
		free_select_result(res);
		return POOL_UNKNOWN;
	}

	if (!strcmp(res->data[0], "read uncommitted"))
		ret = POOL_READ_UNCOMMITTED;
	else if (!strcmp(res->data[0], "read committed"))
		ret = POOL_READ_COMMITTED;
	else if (!strcmp(res->data[0], "repeatable read"))
		ret = POOL_REPEATABLE_READ;
	else if (!strcmp(res->data[0], "serializable"))
		ret = POOL_SERIALIZABLE;
	else
	{
		pool_error("pool_get_transaction_isolation: unknown transaction isolation level:%s",
				   res->data[0]);
		ret = POOL_UNKNOWN;
	}   

	free_select_result(res);

	if (ret != POOL_UNKNOWN)
		session_context->transaction_isolation = ret;

	return ret;
}
Esempio n. 27
0
void parse_opts(int argc, char** argv){
  int longIndex;
  int mode=MODE_ATTACK;
  int i;
  unsigned int f;
  int t=0;
  int recent=0;
  int code=0;
  int query_all=0;
  char *post_key=NULL;
  char *url=NULL;
  char *mime=NULL;
  char *trigger=NULL;
  char *feature=NULL;
  char *description="";
  char *upload_file=NULL;
  unsigned int flags=0;
  struct option long_options[] = {        /* long options array. Items are all caSe SensiTivE! */
    { "add-url", no_argument, &mode, MODE_ADD_URL   }, 
    { "add-trigger", no_argument, &mode, MODE_ADD_TRIGGER},
    { "brute-backup", required_argument, NULL, MODE_BRUTE_BACKUP},
    { "brute-backup-days", required_argument, NULL, BRUTE_BACKUP_DAYS},
    { "brute-backup-pattern", required_argument, NULL, BRUTE_BACKUP_PATTERN},
    { "brute-backup-no-stop", no_argument, &backup_bruteforce_stop, 0},
    { "brute-backup-no-slash", no_argument, &backup_bruteforce_slash, 0},
    { "store-successes", no_argument, NULL, 'S'},
    { "query", no_argument, &mode, MODE_QUERY}, 
    { "all", no_argument, &query_all, 1}, 
    { "code", required_argument, NULL, CODE}, 
    { "post-key", required_argument, NULL, POST_KEY}, 
    { "mime-type", required_argument, NULL, MIME}, 
    { "recent", required_argument, NULL, RECENT}, 
    { "no-async-resolve", no_argument, &async_dns, 0}, 
    { "trigger", required_argument,NULL, TRIGGER},
    { "max-hosts", required_argument,NULL, 'n'},
    { "idle-timeout", required_argument,NULL, RESP_TIMEOUT},
    { "rw-timeout", required_argument,NULL, RW_TIMEOUT},
    { "conn-timeout", required_argument,NULL, CONN_TIMEOUT},
    { "max-connections", required_argument,NULL, 'c'},
    { "max-requests", required_argument,NULL, 'r'},
    { "max-time", required_argument,NULL, MAX_TIME},
    { "progress", required_argument, NULL, 'P' },
    { "file", required_argument, NULL, 'f' },
    { "statistics", no_argument, NULL, STATISTICS },
    { "browser", required_argument, NULL, 'B' },
    { "train",  optional_argument, NULL, 'T' },
    { "feature", required_argument,NULL, FEATURE},
    { "url", required_argument, NULL, URL },
    { "flags", required_argument, NULL, FLAGS },
    { "help", required_argument, NULL, 'h' },
    { "skip-sig", no_argument, &skip_sig, 1},
    { "skip-other-probes", no_argument, &skip_other_probes, 1},
    { "skip-blacklist-success", no_argument, &blacklist_success, 0},
    { "force-save", no_argument, &force_save, 1},
    { "analyze", no_argument, &mode, MODE_ANALYZE},
    { "find-uploaded-file", required_argument, NULL, MODE_FIND_UPLOAD },
    { 0,    0,    0,    0   }       /* terminating -0 item */
  };
  int opt;
  struct t_list *target;
  while((opt=getopt_long( argc, argv, "-n:Sf:P:c:B:h:r:T::", long_options, &longIndex ))!=-1){
    switch(opt){
      case 1:
        target=calloc(sizeof(struct t_list),1);
        target->host=(unsigned char *) optarg;
        unqueued_hosts++;
        LL_APPEND(target_list,target);
        t++;
        break;
      case MODE_BRUTE_BACKUP:
        backup_bruteforce_url=optarg;
        mode=MODE_BRUTE_BACKUP;
        break;
      case BRUTE_BACKUP_DAYS:
        backup_bruteforce_days_back=atoi(optarg);
        break;
      case RESP_TIMEOUT:
        resp_tmout=atoi(optarg);
        break;
      case RW_TIMEOUT:
        rw_tmout=atoi(optarg);
        break;
      case MAX_TIME:
        max_time=atoi(optarg);
        break;
      case CONN_TIMEOUT:
        idle_tmout=atoi(optarg);
        break;
      case BRUTE_BACKUP_PATTERN:
        backup_bruteforce_pattern=optarg;
        break;
      case 'B':
        if (!strcasecmp("metal",optarg)) browser_type=BROWSER_METAL;
        else if (!strcasecmp("minimal",optarg)) browser_type=BROWSER_FAST;
        else if (!strcasecmp("firefox",optarg)) browser_type=BROWSER_FFOX;
        else if (!strcasecmp("explorer",optarg)) browser_type=BROWSER_MSIE;
        else if (!strcasecmp("iphone",optarg)) browser_type=BROWSER_PHONE;
        else {
          printf("ERROR: Browser type '%s' is not supported.\n",optarg);
          exit(1);
        }
        break;
      case 'h':
        usage();
        exit(0);
      case 'S':
        store_successes=1;
        break;
      case URL:
        url=optarg;
        break;
      case 'c':
        max_conn_host=atoi(optarg);
        break;
      case 'f':
        if(!strcmp("-",optarg)) file=stdin;
        else{
          if(!(file=fopen(optarg,"r"))){
            printf("Can't open '%s' for reading!",optarg);
            exit(1);
          }
        }
        int fd = fileno(file);
        int fflags = fcntl(fd, F_GETFL, 0);
        fflags |= O_NONBLOCK;
        fcntl(fd, F_SETFL, fflags);
        t++;
      case 'r':
        max_requests=atoi(optarg);
        break;
      case 'P':
        progress=atoi(optarg);
        break;
      case STATISTICS:
        load_tests();
        load_features();
        show_feature_predictive_values();
        exit(0);
        break;
      case 'T':
        train=1;
        if(optarg) max_train_count=atoi(optarg);
        break;
      case 'n':
        max_hosts=atoi(optarg);
        break;
      case FEATURE:
        feature=optarg;
        break;
      case POST_KEY:
        post_key=optarg;
        break;
      case MIME:
        mime=optarg;
        break;
      case CODE:
        code=atoi(optarg);
        break;
      case RECENT:
        recent=atoi(optarg);
        break;
      case TRIGGER:
        trigger=optarg;
        break;
      case FLAGS:
        for(i=0; i<strlen(optarg); i++){
          f=tolower(optarg[i]);
          switch(f){
            case 'c':
              flags|=F_CRITICAL;
              break;
            case 'i':
              flags|=F_INFO;
              break;
            case 'd':
              flags|=F_DIRECTORY;
              break;
            case 'g':
              flags|=F_CGI;
              break;
            default:
              fprintf (stderr, "Unknown flag: '%c'",f ); 
              exit(1);
          }
        }
        break;
      case MODE_FIND_UPLOAD:
        mode=MODE_FIND_UPLOAD;
        upload_file=optarg;
        break;
    }
  
  }

  if(train){

    /* force aggressive 404 pruning */

    max_requests=0;
    blacklist_success=1;
    skip_other_probes=0;
  }

  switch(mode){
    case MODE_FIND_UPLOAD:
      do {
        struct target *tar;
        if(!t){
          fprintf(stderr, "You must specify a host\n");
          exit(1);
        }
        skip_other_probes=1;
        tar=add_target(target_list->host) ; /* first target only */
        no_add_from_queue=1;
        if(!tar){
          fprintf(stderr,"Couldn't create target '%s'\n",target_list->host);
          exit(1);
        }

        tar->upload_file=upload_file;
        tar->after_probes=start_find_uploaded_file;
        do_scan();
      } while(0);
      break;
    case MODE_ADD_URL:
      add_or_update_url(url, description, flags);
      exit(0);
      break;
    case MODE_ATTACK:
      if(!t){
        usage();
        exit(0);
      }
      max_connections=max_hosts * max_conn_host;
      scan_flags=flags;
      do_scan();
      exit(0);
      break;
    case MODE_ADD_TRIGGER:
      add_aho_corasick_trigger(trigger, feature);
      exit(0);
      break;
    case MODE_QUERY:
      do {
        if(!url && !code && !mime && !flags && !recent && !post_key && !query_all){
          fprintf(stderr,"You must specify at least one attribute to search on (or --all)\n");
          exit(1);
        }
        struct query *q=ck_alloc(sizeof(struct query));
        q->url=url;
        q->code=code;
        q->mime=mime;
        q->flags=flags;
        q->recent=recent;
        q->post_key=post_key;
        store_successes=0;
        do_query(q);
        exit(0);
      break;
      } while(0);
    case MODE_ANALYZE:
      load_tests();
      load_features();
      info("performing feature selection...");
      do_feature_selection();
      exit(0);
    case MODE_BRUTE_BACKUP:
      do {
      struct target *tar;
      skip_other_probes=1;
      tar=add_target(backup_bruteforce_url);
      if(!tar) exit(1);
      tar->after_probes=start_bruteforce_backup;
      do_scan();
      } while(0);
      break;
  }

}
Esempio n. 28
0
static void solve(int retry, int timeout, int cname, const ruli_list_t *server_list)
{
  oop_source_sys      *source_sys; /* System event source */
  oop_source          *source;     /* Event registration interface */
  ruli_res_t          res_ctx;
  int                 result;
  ruli_conf_handler_t handler;

  /*
   * Create event source
   */
  create_oop_source(&source_sys, &source);

  /*
   * Initialize resolver
   */

  handler.opaque          = server_list;
  handler.search_loader   = load_search_list;
  handler.search_unloader = unload_search_list;
  handler.ns_loader       = load_ns_list;
  handler.ns_unloader     = unload_ns_list;

  res_ctx.res_conf_handler = &handler;
  res_ctx.res_source       = source;
  res_ctx.res_retry        = retry;
  res_ctx.res_timeout      = timeout;

  result = ruli_res_new(&res_ctx);
  if (result) {
    fprintf(stderr, 
	    "%s: can't create ruli resolver: %s [%d]\n", 
	    prog_name, ruli_res_errstr(result), result);
    exit(1);
  }

  /*
   * main solve loop
   */
  for (;;) {
    const int INBUFSZ = 1024;
    char      inbuf[INBUFSZ];

    /*
     * Read stdin
     */
    if (!fgets(inbuf, INBUFSZ, stdin)) {
      if (feof(stdin))
	break;
      
      fprintf(stderr, 
	      "%s: reading from stdin: %s\n", 
	      prog_name, strerror(errno));
      
      continue;
    }
    
    /*
     * Scan tokens
     */
    {
      const char *SEP = "\r\n\t ";
      char       *ptr;
      char       *tok;
      
      tok = strtok_r(inbuf, SEP, &ptr);
      if (!tok)
	continue;
      
      for (;;) {
	
	/*
	 * Submit query for token
	 */
	do_query(&res_ctx, tok, cname);
	
	tok = strtok_r(0, SEP, &ptr);
	if (!tok)
	  break;
      } /* for */

    } /* Scan tokens */

    /*
     * Run event loop (send queries, receive answers)
     */
    {
      void *oop_result = run_event_loop(source_sys);
      if (oop_result != OOP_CONTINUE)
	break;
    }

  } /* main solve loop */

  /*
   * Destroy resolver
   */
  ruli_res_delete(&res_ctx);

  /*
   * Destroy event source
   */
  oop_sys_delete(source_sys);
}
Esempio n. 29
0
File: sized.c Progetto: Tolchi/misc
int main(int argc, char * argv[]) {
  int opt, rc=0, ifd=-1,efd=-1,er,mask,wd;
 
  while ( (opt = getopt(argc, argv, "v+s:ocdqh")) != -1) {
    switch (opt) {
      case 'v': cf.verbose++; break;
      case 'q': cf.query=1; break;
      case 'c': cf.continuous=1; break;
      case 'o': cf.once=1; break;
      case 's': cf.sz=strdup(optarg); break;
      case 'd': cf.dry_run=1; break;
      case 'h': default: usage(argv[0]); break;
    }
  }
  if (optind < argc) cf.dir=argv[optind++];
  if (!cf.dir) usage(argv[0]);
  if (cf.query + cf.once + cf.continuous != 1) usage(argv[0]); /* exclusive */
  if ( (cf.sz_bytes=sztobytes()) == -1) usage(argv[0]);
  if (cf.query) { do_query(); goto done; }

  openlog("sized",LOG_PERROR,LOG_DAEMON);

  if ( (rc=do_attrition()) == -1) goto done;
  if (!cf.continuous) goto done;

  /* continuous mode */
  if ( (ifd = inotify_init()) == -1) {
    syslog(LOG_ERR,"inotify_init failed: %s", strerror(errno));
    goto done;
  }
  mask = IN_CLOSE_WRITE|IN_UNMOUNT;
  if ( (wd = inotify_add_watch(ifd, cf.dir, mask)) == -1) {
    syslog(LOG_ERR,"inotify_add_watch failed");
    goto done;
  }
  /* wait for file events or periodic attrition */
  if ( (efd = epoll_create(5)) == -1) {
    syslog(LOG_ERR,"epoll_create failed: %s", strerror(errno));
    goto done;
  }
  struct epoll_event ev = {.events = EPOLLIN, .data.fd=ifd};
  if (epoll_ctl(efd, EPOLL_CTL_ADD, ifd, &ev) == -1) {
    syslog(LOG_ERR,"epoll_ctl failed: %s", strerror(errno));
    goto done;
  }
  do {
    er = epoll_wait(efd, &ev, 1, PERIODIC_SCAN_INTERVAL);
    switch(er) {
      case -1: syslog(LOG_ERR,"epoll_wait error: %s", strerror(errno)); break;
      case 1: if (clear_file_event(ifd) < 0) goto done; break;
      case 0: /* got timeout */; break;
      default: assert(0); break;
    }
    do_attrition();
  } while(er != -1);


 done:
  if (ifd != -1) close(ifd);
  if (efd != -1) close(efd);
  return rc;
}
Esempio n. 30
0
static void
show_control_dialog (GbWidgetNewData *data)
{
  GtkWidget *dialog, *vbox, *label, *list, *scroll;
  GtkListStore *store;
  GtkCellRenderer *ren;

  dialog = glade_util_create_dialog (_("New Bonobo Control"), data->parent,
				     GTK_SIGNAL_FUNC (on_control_dialog_ok),
				     data, &vbox);
  g_object_set (G_OBJECT (dialog),
		"resizable", TRUE,
		"default-width", 400,
		"default-height", 300,
		NULL);
  gtk_dialog_set_response_sensitive (GTK_DIALOG (dialog),
				     GTK_RESPONSE_OK, FALSE);
  g_signal_connect (dialog, "destroy",
		    G_CALLBACK (on_control_dialog_destroy), data);

  label = gtk_label_new (_("Select a Bonobo Control"));  
  gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);

  scroll = g_object_new (GTK_TYPE_SCROLLED_WINDOW,
			 "hadjustment",       NULL,
			 "vadjustment",       NULL,
			 "shadow-type",       GTK_SHADOW_ETCHED_IN,
			 "vscrollbar-policy", GTK_POLICY_AUTOMATIC,
			 "hscrollbar-policy", GTK_POLICY_AUTOMATIC,
			 NULL);
  gtk_box_pack_start (GTK_BOX (vbox), scroll, TRUE, TRUE, 0);

  store = do_query ();

  list = g_object_new (GTK_TYPE_TREE_VIEW,
		       "model",           store,
		       "headers-visible", FALSE,
		       NULL);
  g_signal_connect (gtk_tree_view_get_selection (GTK_TREE_VIEW (list)),
		    "changed",
		    G_CALLBACK (on_list_selection_changed), dialog);

  g_object_unref (store);

  ren = gtk_cell_renderer_text_new ();
  
#if 0
  gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (list),
					       -1, _("OAFIID"), ren,
					       "text", COL_OBJID,
					       NULL);
#endif
  gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (list),
					       -1, _("Description"), ren,
					       "text", COL_DESC,
					       NULL);

  gtk_container_add (GTK_CONTAINER (scroll), list);

  g_object_set_data (G_OBJECT (dialog), "tree_view", list);

  gtk_widget_show_all (dialog);
  gtk_grab_add (dialog);
}