Exemplo n.º 1
0
void run_interactive_loop(geonames_by_token_func geonames_func,
                          int max_results,
                          process_geoname_id_func process_func) {
    char q[MAX_QUERY_LENGTH];

    debug("Ready to serve\n");

    for (;;) {
        int i;
        vector_t tokens;
        geoname_indices_t geonames;

        if (!fgets(q, sizeof q, stdin))
            break;

        strlower(strtrim(q));

        if (!*q) {
            puts("");
            continue;
        }

        tokens = strsplit(q, " \t");
        geonames = process_query(tokens, max_results, geonames_func);

        for (i = 0; i != vector_size(geonames); ++i)
            process_func(geoname_idx(geonames, i));

        puts("");

        vector_free(tokens);
        vector_free(geonames);
    }
}
Exemplo n.º 2
0
/////////////////////////////////////////////////////
//WINHOLDEM RUNTIME ENTRY POINT
/////////////////////////////////////////////////////
OHUSER_API double process_message (const char* pmessage, const void* param) {
        if (pmessage==NULL) { return 0; }
        if (param==NULL) { return 0; }

        if (strcmp(pmessage,"state")==0) { 
                holdem_state *state = (holdem_state*) param;
				if (ClientStarted != true){ initClient(); }
			 return process_state( (holdem_state*)param ); 
        }

        if (strcmp(pmessage,"query")==0) { 
//              MessageBox(NULL, (LPCSTR) param, "query", MB_OK);
                return process_query( (const char*)param ); 
        }

		//pfgws is outdated now, use exportable functions like GetSymbolFromDll etc
        if (strcmp(pmessage,"pfgws")==0) {      
//              MessageBox(NULL, "pfgws", "MESSAGE", MB_OK);
                m_pget_winholdem_symbol = (pfgws_t)param;
                return 0;
        }

        if (strcmp(pmessage,"event")==0 && strcmp((const char *) param, "load")==0) { 
			if (ClientStarted != true){ initClient(); }
//              MessageBox(NULL, "event-load", "MESSAGE", MB_OK);
        }

        if (strcmp(pmessage,"event")==0 && strcmp((const char *) param, "unload")==0) { 
//              MessageBox(NULL, "event-unload", "MESSAGE", MB_OK);
        }

        return 0;
}
Exemplo n.º 3
0
static gboolean
execute_find (MuStore *store, MuConfig *opts, GError **err)
{
	char *query_str;
	MuQuery *oracle;
	gboolean rv;

	oracle = get_query_obj(store, err);
	if (!oracle)
		return FALSE;

	query_str = get_query (opts, err);
	if (!query_str) {
		mu_query_destroy (oracle);
		return FALSE;
	}

	if (opts->format == MU_CONFIG_FORMAT_XQUERY)
		rv = print_xapian_query (oracle, query_str, err);
	else
		rv = process_query (oracle, query_str, opts, err);

	mu_query_destroy (oracle);
	g_free (query_str);

	return rv;
}
Exemplo n.º 4
0
gint
main (gint argc, gchar **argv)
{
#ifndef G_THREADS_ENABLED
    puts("GLib doesn't support threads. exit");
    exit(EXIT_FAILURE);
#endif
    g_type_init();

    hostname = g_malloc(sizeof(gchar) * 256);
    if (gethostname(hostname, 255) != 0){
        g_printerr("failed to get hostname.\n");
        hostname = "";
    }

    parse_args(&argc, &argv);

    if (argc <= 1){
        g_printerr("fts-search [options] HOSTNAME\n\n");
        exit(EXIT_FAILURE);
    } else {
        g_printerr("%s\n", argv[1]);
    }

    GString *input;
    gchar buf[4096];
    size_t sz;
    guint qnum;
    gchar *endptr;
    Query *queries;
    guint qid;
    const gchar *str;
    gchar *ptr;

    if (!option.quit){
        input = g_string_new("");
        while((sz = fread(buf, sizeof(gchar), 4096, stdin)) != 0){
            g_string_append_len(input, buf, sz);
        }
        qnum = 0;
        queries = NULL;
        endptr = input->str;

        while((qid = strtol(endptr, &endptr, 10)) > 0){
            endptr = index(endptr, '"');
            ptr = index(endptr, '\n');

            qnum++;
            queries = g_realloc(queries, sizeof(Query) * qnum);
            queries[qnum-1].id = qid;
            queries[qnum-1].str = g_strndup(endptr, ptr - endptr);
            endptr = ptr + 1;
        }
    }

    process_query(argv[1], queries, qnum);

    return 0;
}
Exemplo n.º 5
0
int main( int argc, char *argv[])
{
	try {
		
		// check command line
		if (argc != 2 && argc != 3) {
			std::cerr << "Usage:\n  WNXMLConsole <WN_XML_file> [<semantic_features_XML_file>]\n";
			return 1;
		}

		// init WN
		std::cerr << "Reading XML...\n";
		std::auto_ptr<ML::MultiLog> logger( ML::MultiLog::create( std::cerr, 100));
		std::auto_ptr<LibWNXML::WNQuery> wn( new LibWNXML::WNQuery( argv[1], *logger));
		wn->writeStats( std::cerr);

		// init SemFeatures (if appl.)
		std::auto_ptr<ML_NPro2::SemFeatures> sf( NULL);
		if (argc == 3) {
			std::cerr << "Reading SemFeatures...\n";
			sf = std::auto_ptr<ML_NPro2::SemFeatures>( new ML_NPro2::SemFeatures( *wn));
			std::cerr << sf->readXML( argv[2]) << " pairs read\n";
		}

		// query loop
		std::cerr << "Type your query, or .h for help, .q to quit\n";
		std::string line;
		while (true) {	
			
			std::cerr << ">";
			std::getline( std::cin, line);

			if (line == ".q")
				break;
			else if (line != "") {
				try {
					process_query( *wn, sf.get(), line, std::cout);
				}
				catch (const LibWNXML::InvalidPOSException& e) {
					std::cerr << e.msg() << std::endl;
				}
			}

		} // while (true)

	} // try {
	catch (const std::exception& e) {
		std::cerr << e.what() << std::endl;
		return 1;
	}
	catch (...) {
		std::cerr << "Unknown exception\n";
		return 1;
	}
	
	return 0;
}
Exemplo n.º 6
0
/**
 * @brief 主处理函数
 *
 * @return  int 
 * @retval   
**/
int 
op_query()
{
    int opret = 0;

    nshead_t *req_head;
    nshead_t *res_head;
    ub_buff_t req_buf;
    ub_buff_t res_buf;
    in_addr_t req_ip;

    req_head = (nshead_t *) ub_server_get_read_buf();
    res_head = (nshead_t *) ub_server_get_write_buf();
    if(NULL == req_head || NULL == res_head)
    {
        UB_LOG_FATAL("get req_head[%ld] || res_head[%ld] failed.",
                     (long)req_head, (long)res_head);
        return -1;
    }
    req_buf.buf = (char *)(req_head + 1);
    req_buf.size = ub_server_get_read_size() - sizeof(nshead_t);
    res_buf.buf = (char *)(res_head + 1);
    res_buf.size = ub_server_get_write_size() - sizeof(nshead_t);

    //设置一些log需要的字段
    char ip_str[20];
    ip_str[0] = 0;
    req_ip = ub_server_get_ip();
    inet_ntop(AF_INET, &req_ip, ip_str, sizeof(ip_str));
    ub_log_setbasic(UB_LOG_REQIP, "%s", ip_str);
    ub_log_setbasic(UB_LOG_LOGID, "%u", req_head->log_id);
    ub_log_setbasic(UB_LOG_REQSVR, "%s", req_head->provider);
    ub_log_setbasic(UB_LOG_SVRNAME, "%s", g_cfg.svr_query.svr_name);

    ub_log_pushnotice("req_dlen", "%d", req_head->body_len);
    *res_head = *req_head;
    strncpy(res_head->provider, req_head->provider,
            sizeof(res_head->provider));
    res_head->body_len = 0;
    res_head->reserved = 0;

	//处理查询
	struct timeval total_s,total_e;
	gettimeofday(&total_s, NULL);
	opret = process_query(req_head, &req_buf, res_head, &res_buf);
    if(opret != 0){
            UB_LOG_WARNING("[function:op_update]>>>process_query failed! errno:%d", opret);
            return -1;
    }    
	gettimeofday(&total_e, NULL);
	ub_log_setbasic(UB_LOG_PROCTIME, "%luus", TIME_US_DIFF(total_s, total_e));
    
    return opret;
}
Exemplo n.º 7
0
/////////////////////////////////////////////////////
// user.dll entry point
/////////////////////////////////////////////////////
USERDLL_API double process_message (const char* pmessage, const void* param) 
{
	if (pmessage==NULL) { return 0; }
	if (param==NULL) { return 0; }

	if (strcmp(pmessage,"state")==0) 
	{ 
		holdem_state *state = (holdem_state*) param;
//		CString s; 
//		s.Format("<%s>\nPOTS: %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f\nCOMMON: %d %d %d %d %d\n%d %d %d\n<%s> %d %.2f %d", 
//			state->m_title,
//			state->m_pot[0], state->m_pot[1], state->m_pot[2], state->m_pot[3], state->m_pot[4], 
//			state->m_pot[5], state->m_pot[6], state->m_pot[7], state->m_pot[8], state->m_pot[9],
//			state->m_cards[0], state->m_cards[1], state->m_cards[2], state->m_cards[3], state->m_cards[4],
//			state->m_is_playing, state->m_is_posting, state->m_dealer_chair,
//			state->m_player[4].m_name, state->m_player[4].m_name_known, state->m_player[4].m_balance, state->m_player[4].m_balance_known);
//		MessageBox(NULL, s, "state", MB_OK);

		return process_state( (holdem_state*)param ); 
	}

	if (strcmp(pmessage,"query")==0) 
	{ 
//		MessageBox(NULL, (LPCSTR) param, "query", MB_OK);
		return process_query( (const char*)param ); 
	}

	if (strcmp(pmessage,"pfgws")==0) 
	{	
//		MessageBox(NULL, "pfgws", "MESSAGE", MB_OK);
		p_get_symbol = (p_getsym_t)param;
		return 0;
	}

	if (strcmp(pmessage,"p_send_chat_message")==0) 
	{	
//		MessageBox(NULL, "p_send_chat_message", "MESSAGE", MB_OK);
		p_send_chat = (p_send_chat_t)param;
		return 0;
	}

	if (strcmp(pmessage,"event")==0 && strcmp((const char *) param, "load")==0) 
	{ 
//		MessageBox(NULL, "event-load", "MESSAGE", MB_OK);
	}

	if (strcmp(pmessage,"event")==0 && strcmp((const char *) param, "unload")==0) 
	{ 
//		MessageBox(NULL, "event-unload", "MESSAGE", MB_OK);
	}

	return 0;
}
Exemplo n.º 8
0
/////////////////////////////////////////////////////
// user.dll entry point
/////////////////////////////////////////////////////
USERDLL_API double process_message (const char* pmessage, const void* param) 
{
	if (pmessage==NULL) { return 0; }
	if (param==NULL) { return 0; }

	if (strcmp(pmessage,"state")==0) 
	{ 
		holdem_state *state = (holdem_state*) param;

#ifdef OPT_DEMO_OUTPUT
		CString s; 
		s.Format("<%s>\nPOTS: %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f\nCOMMON: %d %d %d %d %d\n%d %d %d\n<%s> %d %.2f %d", 
			state->m_title,
			state->m_pot[0], state->m_pot[1], state->m_pot[2], state->m_pot[3], state->m_pot[4], 
			state->m_pot[5], state->m_pot[6], state->m_pot[7], state->m_pot[8], state->m_pot[9],
			state->m_cards[0], state->m_cards[1], state->m_cards[2], state->m_cards[3], state->m_cards[4],
			state->m_is_playing, state->m_is_posting, state->m_dealer_chair,
			state->m_player[4].m_name, state->m_player[4].m_name_known, state->m_player[4].m_balance, state->m_player[4].m_balance_known);
		MessageBox(NULL, s, "state", MB_OK);
#endif OPT_DEMO_OUTPUT

		return process_state( (holdem_state*)param ); 
	}

	if (strcmp(pmessage,"query")==0) 
	{ 
#ifdef OPT_DEMO_OUTPUT
		MessageBox(NULL, (LPCSTR) param, "query", MB_OK);
#endif OPT_DEMO_OUTPUT

		return process_query( (const char*)param ); 
	}

	if (strcmp(pmessage,"event")==0 && strcmp((const char *) param, "load")==0) 
	{ 
#ifdef OPT_DEMO_OUTPUT
		MessageBox(NULL, "event-load", "MESSAGE", MB_OK);
#endif OPT_DEMO_OUTPUT
	}

	if (strcmp(pmessage,"event")==0 && strcmp((const char *) param, "unload")==0) 
	{ 
#ifdef OPT_DEMO_OUTPUT
		MessageBox(NULL, "event-unload", "MESSAGE", MB_OK);
#endif OPT_DEMO_OUTPUT
	}

	return 0;
}
Exemplo n.º 9
0
// ProcessQuery()
//   Handling the lookup of dll$symbols
DLL_IMPLEMENTS double __stdcall ProcessQuery(const char* pquery) {
	if (!is_connector_enabled()) {
    std::cout << "connector not enabled" << std::endl;
		return 0;
	}
	if (pquery==NULL)
		return 0;
	if (strncmp(pquery,"dll$test",8)==0) {
		return GetSymbol("random");
  }
	if (GetSymbol("f$loopback_debug") == 1) {
		return loopback_debug(pquery);
	}
	return process_query(pquery);
}
Exemplo n.º 10
0
void main(int argc,char *argv[])
{

	FILE *hdd_load;
	buildSW();
	if(argc < 3)
		printf("No input specified / Invalid Command\n");
	
	else if(argv[1][0] =='-' && argv[1][1]=='i')
	{
		hdd_load = fopen("../bin/tree","rb");
		
		if(hdd_load)
		{
			fclose(hdd_load);
			load2mm();
			//buildSW();
		
			printf("Tree Built sucessfully\n");
			printf("retrieved vlaue:%ld",doc_count);
			indexer(argc,argv);	
		}
		else
			indexer(argc,argv);	
	}

	else if(argv[1][0] =='-' && argv[1][1]=='s')
	{
		hdd_load = fopen("../bin/tree","rb");
		if(hdd_load)
		{
			fclose(hdd_load);
			load2mm();
		
			//printf("Tree Built sucessfully\n");
			//printf("retrieved vlaue:%ld\n",doc_count);
			
		}

		if(argv[2][0] =='-' && argv[2][1]=='b')
			process_query_bm25(argc,argv);
		else
			process_query(argc,argv);							

	
	}// -s

}
Exemplo n.º 11
0
/////////////////////////////////////////////////////
//WINHOLDEM RUNTIME ENTRY POINT
/////////////////////////////////////////////////////
WHUSER_API double process_message(const char* pmessage, const void* param)
{
    /*
    *
    */

    if(pmessage==NULL)
    {
        gLog.WriteLog(eSeverityError, eCatOHMessages, "pmessage==NULL.. \n");
        return 0;
    }
    if(param==NULL)
    {
        gLog.WriteLog(eSeverityError, eCatOHMessages, "param==NULL.. \n");
        return 0;
    }

    gLog.WriteLogNoHeading(eSeverityInfo, eCatGeneral, "PROCESS Message.. %s, Param: %s\n", pmessage, (const char*)param);

    if(strcmp(pmessage,"state")==0)
    {
        gLog.WriteLogNoHeading(eSeverityInfo, eCatOHMessages, "PROCESS STATE..\n\tParam: %s\n", (const char*)param);
        double ret = process_state( (holdem_state*)param );
        gLog.WriteLogNoHeading(eSeverityInfo, eCatOHMessages, "PROCESS STATE FINISHED.. %.2f\n", ret);
        return ret;
    }
    if(strcmp(pmessage,"query")==0)
    {
        gLog.WriteLogNoHeading(eSeverityInfo, eCatOHMessages, "RUN QUERY..\nParam: %s\n", (const char*)param);
        double ret = process_query((const char*)param);
        gLog.WriteLogNoHeading(eSeverityInfo, eCatOHMessages, "PROCESS QUERY FINISHED.. %.2f\n", ret);
        return ret;
    }
    if(strcmp(pmessage,"pfgws")==0)
    {
        gVars.m_pget_winholdem_symbol = (pfgws_t)param;
        return 0;
    }

    return 0;
}
Exemplo n.º 12
0
void Parser::process_input(string _input)
{
  try
  {
    // Tokenize the input, divide the string input into minimal units
    tokenizer.tokenize_input(_input);
    
    string token;

    // Check if there is any token
    if(tokenizer.remaining_tokens() > 0)
    {
      token = tokenizer.peek();
    }
    else
    {
      // Most likely blank line, return
      return;
    }

    InputType type = get_input_type(token);
    switch(type)
    {
    case QUERY:
      process_query();
      break;
    default:
      process_command(type);
      break;
    }
  }
  catch(exception& e)
  {
    cout << "Exception: " << e.what() << endl;
  }
}
Exemplo n.º 13
0
int main(int argc, char *argv[])
{
    option_t *optList=NULL, *thisOpt=NULL;
    bool bSqlite, bParam, bTerm, bExact, bDebug, bVersion, bHelp, bError;
    int countExact = 0;
	bSqlite = false;
	bParam = false;
	bTerm = false;
	bExact = false;
	bDebug = false;
	bVersion = false;
	bHelp = (argc <= 1);
	bError = false;
	tStr sqfn, param = "1", term;

    /* get list of command line options and their arguments */
    optList = GetOptList(argc, argv, (char*)"s:p:t:efdvh");

    /* display results of parsing */
    while (optList != NULL)
    {
        thisOpt = optList;
        optList = optList->next;
		
		switch(thisOpt->option)
		{
			case 'v':
				bVersion = true;
				break;
			case 'h':
				bHelp = true;
				break;
			case 'e':
				bExact = true;
				countExact++;
				bError = bError || (countExact > 1);
				if (countExact > 1) printf("Error: either -e or -f but not both!\n");
				break;
			case 'f':
				bExact = false;
				countExact++;
				bError = bError || (countExact > 1);
				if (countExact > 1) printf("Error: either -e or -f but not both!\n");
				break;
			case 's':
				bSqlite = true;
				process_argwithopt(thisOpt, bError, sqfn, true);
				break;
			case 'p':
				bParam = true;
				param = thisOpt->argument;
				break;
			case 't':
				bTerm = true;
				term = thisOpt->argument;
				break;
			case 'd':
				bDebug = true;
				break;
			default:
				break;
		}
        free(thisOpt);    /* done with this item, free it */
    }
	if (bVersion)
	{
		printlicense();
		return 0;
	}
	if (bHelp || bError)
	{
		printhelp(extract_filename(argv[0]));
		return (bError ? 1 : 0);
	}
	if (!bSqlite)
	{
		printf("Error: -s is required.\n");
		bError = true;
	}
	if (!bTerm)
	{
		printf("Error: -t is required.\n");
		bError = true;
	}
	if (bError)
	{
		printhelp(extract_filename(argv[0]));
		return 1;
	}
	if (bSqlite && bTerm)
	{
		bError = process_query(sqfn, term, param, bExact, bDebug) > 0;
	}
	if (bError)
	{
		printhelp(extract_filename(argv[0]));
	}
	return bError;
}
Exemplo n.º 14
0
int
main(int argc, const char *argv[])
{
	int		 ch;
	size_t		 diff;
	long long	 choice;
	long long	 hits;
	struct resultset rs;
	char		 fullpath[MAX_CHOICESIZE];
	const char	*dirname;
	const char	*errstr;

	diff = choice = hits = 0;
	memset(&rs, 0, sizeof(struct resultset));
	memset(fullpath, 0, MAX_CHOICESIZE);

	if (argc < 2)
		usage();

	while ((ch = getopt(argc, (char *const *)argv, "abcd:DiIt:")) != -1) {
		switch ((char) ch) {
		case 'a':
			aflag = 1;
			cflag = 0;
			break;
		case 'b':
			bflag = 1;
			break;
		case 'c':
			cflag = 1;
			aflag = 0;
			break;
		case 'd':
			dflag = 1;
			diff = strtonum(optarg, 0, MAX_HITS, &errstr);
			if (errstr)
				errx(1, "You fool, %s is not a NUMBER we "
					"want! Error: %s", optarg, errstr);
			break;
		case 'D':
			Dflag = 1;
			Iflag = 0;
			break;
		case 'i':
			iflag = 1;
			break;
		case 'I':
			Iflag = 1;
			Dflag = 0;
			break;
		case 't':
			tflag = 1;
			break;
		default:
			usage();
		}
	}
	dirname = argv[optind];

	argc -= optind;
	argv += optind;

	db_init();

	if (cflag)
		process_query(dirname, dflag);
	else if (Iflag || Dflag) {
		int	 rv = 0;
		size_t	 len = 0;
		char	cwd[PATH_MAX];

		memset(&cwd, 0, PATH_MAX);
		if ((getcwd(cwd, sizeof(cwd))) == NULL) {
			err(5, "Error while retrieving the current path");
			goto error;
		}
		len = strlen(cwd) + 2;
		if (len < PATH_MAX)
			snprintf(cwd, len, "%s/", cwd);
		else {
			fprintf(stderr, "path too long\n");
			goto error;
		}

		if (Iflag && !Dflag) {
			if ((rv = db_insert_dir(TABLE_HOME, cwd, dirname))
								!= SQLITE_DONE) {
				if (rv == SQLITE_CONSTRAINT)
					fprintf(stderr, "DB already contains %s%s\n",
						cwd, dirname);
				else
					err(1, "Cannot insert directory %s%s to db",
						cwd, dirname);
				goto error;
			}
		} else if (Dflag) {
			if ((rv = db_delete_dir(TABLE_HOME, cwd, dirname))
								!= SQLITE_DONE) {
				err(1, "Cannot remove directory %s%s from db",
					cwd, dirname);
				goto error;
			}
		}
	} else if (aflag) {
		if (dflag)
			db_find_spellchecked(TABLE_HOME, dirname, diff);
		else
			db_find_exact(TABLE_HOME, dirname);
		interactive(&choice);
		rs = db_get_choice_by_id(TABLE_HOME, choice);
		print_resultset(&rs);
	} else if (dflag)
		db_find_spellchecked(TABLE_HOME, dirname, diff);
	else
		db_find_exact(TABLE_HOME, dirname);
	snprintf(fullpath, MAX_CHOICESIZE - 1, "%s%s", rs.path, rs.dir);
	fullpath[MAX_CHOICESIZE - 1] = '\0';

error:
	/* Rather close now if we drive to some problem on the next clause */
	db_close();

	execute(fullpath);

	return EXIT_SUCCESS;
}
Exemplo n.º 15
0
int main(int argc, char *argv[])
{
	int c;
	bool bSqlite, bParam, bTerm, bExact, bFull, bDebug, bVersion, bHelp, bError;
	int countExact = 0;
	int limitlen = 80;
	bSqlite = false;
	bParam = false;
	bTerm = false;
	bExact = false;
	bFull = false;
	bDebug = false;
	bVersion = false;
	bHelp = (argc <= 1);
	bError = false;
	tStr sqfn, param = "1", term;

    while ((c = getopt2(argc, argv, "s:p:t:l:efudvh")) != -1)
    {
		switch(c)
		{
			case 'v':
				bVersion = true;
				break;
			case 'h':
				bHelp = true;
				break;
			case 'e':
				bExact = true;
				countExact++;
				bError = bError || (countExact > 1);
				if (countExact > 1) printf("Error: either -e or -f but not both!\n");
				break;
			case 'f':
				bExact = false;
				countExact++;
				bError = bError || (countExact > 1);
				if (countExact > 1) printf("Error: either -e or -f but not both!\n");
				break;
			case 's':
				bSqlite = true;
				process_argwithopt(optarg, c, bError, sqfn, true);
				break;
			case 'p':
				bParam = true;
				param = optarg;
				break;
			case 't':
				bTerm = true;
				term = optarg;
				break;
			case 'l':
				limitlen = atoi(optarg);
				break;
			case 'u':
				bFull = true;
				break;
			case 'd':
				bDebug = true;
				break;
			case '?':
				bError = true;
				break;
			default:
				break;
		}
    }
	if (bVersion)
	{
		printlicense();
		return 0;
	}
	if (bHelp || bError)
	{
		printhelp(extract_filename(argv[0]));
		return (bError ? 1 : 0);
	}
	if (!bSqlite)
	{
		printf("Error: -s is required.\n");
		bError = true;
	}
	if (!bTerm)
	{
		printf("Error: -t is required.\n");
		bError = true;
	}
	if (bError)
	{
		printhelp(extract_filename(argv[0]));
		return 1;
	}
	if (bSqlite && bTerm)
	{
		bError = process_query(sqfn, term, param, bExact, bFull, bDebug, limitlen) > 0;
	}
	if (bError)
	{
		printhelp(extract_filename(argv[0]));
	}
	return bError;
}
void tweet_server(void *q)
{

    char *request, *reply, *format, *query;
    th_args_dt *args = (th_args_dt *)q;

    tweet_req_dt *tweet_req = (tweet_req_dt *)malloc(sizeof(tweet_req_dt));

    tweet_resp_dt *result;
    /*receive buffer*/
    pthread_mutex_lock(&args->th_mutex);
    request = recv_buf(args->sock);
    pthread_mutex_unlock(&args->th_mutex);
    printf("Request received: %s\n",request);

    char *dup = (char *)malloc(strlen(request));
    strcpy(dup,request);
    char *tmp;
    tmp = strtok(dup," ");
    tweet_req->command = tmp;
    tmp = strtok(NULL," ");
    tweet_req->handler = atoi(tmp);
    tmp = strtok(NULL,"\r\n\r\n");
    tweet_req->datalength = atoi(tmp);
    tmp = strtok(NULL,"\0");
    tmp = tmp+3*sizeof(char);
    tweet_req->data = tmp;
    //printf("Command:%sHandler:%dDatalength:%ldData:%s\n",tweet_req->command, tweet_req->handler, tweet_req->datalength, tweet_req->data);


    /*LOGIN and SIGNUP request handling*/
    if (tweet_req->handler <= 0) {//if the user is asking for login request
        char *tmp1, *username, *password;
        tmp1 = strtok(tweet_req->data," ");
        username = tmp1;
        tmp1 = strtok(NULL,"\0");
        password = tmp1;
        printf("Received username: %s & password: %s\n",username,password);

        if (strcmp(tweet_req->command,"LOGIN") == 0) {
            printf("Login Requested. Authenticating '%s'...\n",username);
            pthread_mutex_lock(&args->th_mutex);
            result = login(args->conn,username,password);
            pthread_mutex_unlock(&args->th_mutex);
            //printf("%s %d %ld %s\n", result->command,result->st_code, result->dlength,result->data);
        }
        else if (strcmp(tweet_req->command,"SIGNUP") == 0) {
            printf("Signup Requested. Creating user account for '%s'...\n",username);
            pthread_mutex_lock(&args->th_mutex);
            result = signup(args->conn,username,password);
            pthread_mutex_unlock(&args->th_mutex);
            //printf("%s %d %ld %s\n", result->command,result->st_code, result->dlength,result->data);
        }
    }
    /*other Request Handling*/
    else {
        if (strcmp(tweet_req->command,"LOGOUT") == 0) {
            printf("LOGOUT Requested. Closing session...");
            pthread_mutex_lock(&args->th_mutex);
            result = logout(args->conn,tweet_req->handler);
            pthread_mutex_unlock(&args->th_mutex);
            //printf("%s %d %ld %s\n", result->command,result->st_code, result->dlength,result->data);
        }
        else {
            if (strcmp(tweet_req->command,"FOLLOW") == 0) {
                printf("FOLLOW requested");
                format = "INSERT INTO follow_tb VALUES((SELECT user_id FROM session WHERE ssid= %d),(SELECT user_id FROM users WHERE user_name='%s'))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler,tweet_req->data);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"UNFOLLOW") == 0) {
                printf("UNFOLLOW requested");
                format = "DELETE FROM follow_tb WHERE follower= (SELECT user_id FROM session WHERE ssid=%d) AND following=(SELECT user_id FROM users WHERE user_name=('%s'))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler,tweet_req->data);
                //result = process_query(args->conn, tweet_req->command, query);
            }

            else if (strcmp(tweet_req->command,"FOLLOWERS") == 0) {
                printf("FOLLOWERS requested");
                format = "SELECT user_name FROM users LEFT JOIN follow_tb ON users.user_id=follow_tb.follower WHERE follow_tb.following=(SELECT user_id FROM session WHERE ssid=(%d))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"FOLLOWING") == 0) {
                printf("FOLLOWING requested");
                format = "SELECT user_name FROM users LEFT JOIN follow_tb ON users.user_id=follow_tb.following WHERE follow_tb.follower=(SELECT user_id FROM session WHERE ssid=(%d))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"TWEET") == 0) {
                printf("TWEET requested");
                format = "INSERT INTO tweets(tweet_text,user_id) VALUES ('%s',(SELECT user_id FROM session WHERE ssid=%d))";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->data,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"UNTWEET") == 0) {
                printf("UNTWEET requested");
                format = "DELETE FROM tweets WHERE tweet_id=%d AND user_id=(SELECT user_id FROM session WHERE ssid=%d)";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,atoi(tweet_req->data),tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"ALLTWEETS") == 0) {
                printf("ALLTWEETS requested");
                format = "SELECT tweet_text,tweet_id FROM tweets LEFT JOIN follow_tb ON tweets.user_id = follow_tb.following \
WHERE follow_tb.follower= (SELECT user_id FROM session WHERE ssid=%d) \
UNION SELECT tweet_text,tweet_id FROM tweets WHERE user_id=(SELECT user_id FROM session WHERE ssid=%d)";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }
            else if (strcmp(tweet_req->command,"MYTWEETS") == 0) {
                printf("MYTWEETS requested");
                format = "SELECT tweet_text,tweet_id FROM tweets WHERE user_id IN (SELECT user_id FROM session WHERE ssid=%d) ORDER BY time_created DESC";
                query = (char *)malloc(strlen(format)+sizeof(tweet_req->handler)+strlen(tweet_req->data));
                bzero(query, sizeof(query));
                sprintf(query,format,tweet_req->handler);
                //result = process_query(args->conn, tweet_req->command, query);
            }

            pthread_mutex_lock(&args->th_mutex);
            printf("Query:%s\n",query);
            result = process_query(args->conn, tweet_req->command, query);
            pthread_mutex_unlock(&args->th_mutex);
            free(query);
        }
Exemplo n.º 17
0
int main(int argc, char const *argv[])
{
	// Check args
	if(argc < 5){
		cout << "Please enter (1) a filename query\n \
		(2) a csv input file\n \
		(3) the number fo results to generate\n\
		(4) the number of processes." <<endl;
		exit(0);
	}
	// Check input file
	FILE *infile = fopen(argv[2], "r");
	if(!infile){
		cout << "File invalid" << endl;
		exit(0);
	}
	/***************************
	Part zero: Get args
	****************************/
	string queryFilename(argv[1]);
	
	// number of results
	int numResults = 0;
	if(is_float(argv[3])){
		numResults = atoi(argv[3]);
	}
	else{
		cout << "Invalid number for argument 3" << endl;
		exit(0);
	}
	// number of processes
	int numProcesses = 0;
	if(is_float(argv[4])){
		numProcesses = atoi(argv[4]);
	}
	else{
		cout << "Invalid number for argument 4" << endl;
		exit(0);
	}

	/***************************
	Part one: Read in file, store in map
	****************************/
	// Make map of files
	map< string, uint > fnames;
	vector< pair< uint, vector<float> > > lines;

	// Start clock
    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();

	int numLines = read_in_file(infile, fnames, lines);
	
	end = std::chrono::system_clock::now();
    std::chrono::duration<double> timeElapsed1 = end-start;

	if(numLines <= 0){
		cout << "\n\nFile read was unsucessful."<< endl;
		exit(0);
	}

	


	/***************************
	Part two: Perform query
	****************************/
	start = std::chrono::system_clock::now();

	bool success = process_query(fnames, lines, queryFilename, numResults, numProcesses);

    end = std::chrono::system_clock::now();
    std::chrono::duration<double> timeElapsed2 = end-start;

    if(!success){
    	cout << "\n\nUnsucessful processing of query" << endl;
    	exit(0);
    }
    cout << "\n\nNumber of lines parsed: " << numLines << endl;
    cout << "Time to process file: " << timeElapsed1.count() << "s" << endl;
    cout << "Time to process query: " << timeElapsed2.count() << "s" << endl;


	return 0;
}
Exemplo n.º 18
0
void do_daemon() {
/* do_leap
 * Main LEAP daemon routine - Contains socket handler
 */
	char buffer[MAXIMUM_INPUT_STRING+1];
	char loginname[MAXIMUM_INPUT_STRING+1];
	char password[MAXIMUM_INPUT_STRING+1];
	char maincommand[MAXIMUM_INPUT_STRING+1];
	char tprompt[MAXIMUM_INPUT_STRING+1];
	char *result,*tresult,*plogin,*ppass;
	relation result_relation;
	int res,startscript=0;
	int serverSocket=0, on=0, port=0, status=0, childPid=0;
	struct hostent *hostPtr=NULL;
	char hostname[80]="";
	struct sockaddr_in serverName={0},clientName={0};
	struct linger linger={0};
	struct utsname sysinfo;
	int clientLength;
	tuple ctuple;

	clientLength=sizeof(clientName);

	tempdb=LEAPAPI_db_create(NULL,TEMPDB_NAME);
	res=relations_ddopen(tempdb);
	if (res!=RETURN_SUCCESS) {
		raise_error(ERROR_OPEN_DATABASE,FATAL,TEMPDB_NAME);		
	}

	/* Open the master database */
	master_db=LEAPAPI_db_create(NULL,MASTER_DB_NAME);
	res=relations_ddopen(master_db);
	if (res!=RETURN_SUCCESS) {
		raise_error(ERROR_OPEN_DATABASE,FATAL,MASTER_DB_NAME);		
	}

	if (strlen(dbtoopen)==0) {
		/* Open up the default user database */
		current_db=LEAPAPI_db_create(NULL,DEFAULT_DB);
	} else {
		current_db=LEAPAPI_db_create(NULL,dbtoopen);
	}

	res=relations_ddopen(current_db);
	if (res!=RETURN_SUCCESS) {
		raise_error(ERROR_OPEN_DATABASE,FATAL,database_name(current_db));		
	}
	
	set_variable(VAR_CURRENTDB,database_name(current_db));

	/* Check to see if the logins relation exists */
	result_relation=relation_find(master_db,LEAP_DD_LOGINS);	

	if (result_relation==NULL) {
		raise_error(ERROR_CANNOT_FIND_REL,NONFATAL,LEAP_DD_LOGINS);
		raise_message(MESSAGE,"Building %s",LEAP_DD_LOGINS);

        /* Build the leaplogins relation */
        sprintf(buffer,"(SUID,INTEGER,3),(NAME,string,25),(PASSWORD,string,25),(DEFAULTDB,string,25)");
        relation_insert(master_db,create_user_relation(master_db,buffer,LEAP_DD_LOGINS,FALSE,TRUE));

        vprocess_query(master_db,"add (%s) (%d,%s,%s,%s)",LEAP_DD_LOGINS,LEAP_SUID_DBA,LEAP_LOGIN_DBA,LEAP_PASS_DBA,MASTER_DB_NAME);
	} else {
		raise_message(MESSAGE,"Found %s!",LEAP_DD_LOGINS);
	}


	if (status_quiet!=TRUE) {
		raise_message(MESSAGE,"%s","Startup sequence initiated.");
	}

	terminate=FALSE;
	terminatenow=FALSE;

	if (status_quiet) {
			strcpy(current_prompt,"");
			set_prompt("");
	} else {
			strcpy(current_prompt,DEFAULT_PROMPT);
			set_prompt(DEFAULT_PROMPT);
	}

	if (configuration!=TRUE) {
		raise_message(MESSAGE,"Sourcing %s%s in %s",LEAP_STARTUP,LEAP_SOURCE_EXT,database_name(master_db));
		sprintf(buffer,"%s%s%s%s",database_dir(master_db),LEAP_SOURCE_DIR,LEAP_STARTUP,LEAP_SOURCE_EXT);
		assign_input_stream(buffer);
	} else {
		sprintf(buffer,"%s",configurationfile);
		assign_input_stream(buffer);
	}


	serverSocket=socket(PF_INET,SOCK_STREAM,0);

	if (serverSocket==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"socket()");
	}

	on=1;

	status=setsockopt(serverSocket,SOL_SOCKET,SO_REUSEADDR,(const char *) &on,sizeof(on));

	if (status==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"setsockopt(...,SO_REUSEADDR,...)");
	}
	
	linger.l_onoff=1;
	linger.l_linger=30;
	status=setsockopt(serverSocket,SOL_SOCKET,SO_LINGER,(const char *) &linger,sizeof(linger));
	if (status==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"setsockopt(...,SO_LINGER,...)");
	}
		
	status=uname(&sysinfo);
	if (status==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"uname");
	} else {
		strncpy(hostname,sysinfo.nodename,sizeof(hostname));
	}
		
	status=gethostname(hostname,sizeof(hostname));
	hostPtr=gethostbyname(hostname);

	if (hostPtr==NULL) {
		raise_error(ERROR_SOCKETINIT,FATAL,"gethostbyname");
	} 
	
	(void) memset(&serverName,0,sizeof(serverName));
	(void) memcpy(&serverName.sin_addr,hostPtr->h_addr,hostPtr->h_length);
	
	serverName.sin_family=AF_INET;
	serverName.sin_port=htons(LEAPD_PORT);
	status=bind(serverSocket,(struct sockaddr *) &serverName,sizeof(serverName));

	if (status<0) {
		raise_error(ERROR_SOCKETINIT,FATAL,"bind() - port %u - errno %u",LEAPD_PORT,errno);
	} else {
		raise_message(MESSAGE,"Daemon starting on machine %s, port %u",hostname,LEAPD_PORT);
	}

	status=listen(serverSocket,LEAPD_BACK_LOG);
	if (status==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"listen()");
	}


	while (!terminatenow) {
			slaveSocket=accept(serverSocket,(struct sockaddr *) &clientName,&clientLength);

			if (slaveSocket==-1) {
				raise_error(ERROR_SOCKETINIT,FATAL,"accept()");
			}
				
			raise_message(MESSAGE,"Connection received from [%s]",inet_ntoa(clientName.sin_addr));

			raise_message(MESSAGE,"Authenication expected");

			strcpy(buffer,"Please authenticate yourself: ");
			write(slaveSocket,buffer,strlen(buffer));

			read(slaveSocket,loginname,MAXIMUM_INPUT_STRING);
			plogin=strtok(loginname,"\r\n");
			raise_message(MESSAGE,"Login [%s] connecting...",plogin);

			if (strcmp(plogin,"guest")==0) {
				strcpy(buffer,"Enter your e-mail address: ");
				write(slaveSocket,buffer,strlen(buffer));
			} else {
				strcpy(buffer,"Password: "******"project (select (%s) (%s='%s')) (%s)",LEAP_DD_LOGINS,LEAP_DDA_LOGINS_NAME,plogin,LEAP_DDA_LOGINS_PASSWORD);
			result_relation=process_query(master_db,buffer);

			status=read(slaveSocket,password,MAXIMUM_INPUT_STRING);
			ppass=strtok(password,"\r\n");

			if ((ppass!=NULL) && (status==2)) {
				*ppass='******';
			}

			ctuple=tuple_readfirst(result_relation,TUPLE_BUILD,NULL);
			if (ctuple!=NULL) {
				tuple_to_string(ctuple,buffer);
				raise_message(MESSAGE,"Password expected [%s]",buffer);
				raise_message(MESSAGE,"Password received [%s]",ppass);
			} else {
				if (strcmp(plogin,"guest")==0) {
					raise_message(MESSAGE,"Guest ID [%s]",ppass);
				} else {
					raise_message(MESSAGE,"No login [%s] exists!",plogin);
				}
			}
	
			if (((strcmp(plogin,"guest")==0))||(strcmp(buffer,ppass)==0)) {
					raise_message(MESSAGE,"Login [%s] validated!",plogin); 
					/* Enable daemon on - this will send io to client */
					status_daemon=TRUE;
				
					strcpy(buffer,"version");
					result_relation=process_query(current_db,buffer);

					/* Ok, socket is initialised! */
					while (!terminate) {

						write(slaveSocket,DEFAULT_PROMPT,sizeof(DEFAULT_PROMPT));
						status=read(slaveSocket,buffer,MAXIMUM_INPUT_STRING);
						/* Null terminate reqd....*/
						
						result=strtok(buffer,"\r\n");
						
						status_daemon=FALSE;
						raise_message(MESSAGE,"received: %s",result);
						status_daemon=TRUE;

						result_relation=process_query(current_db,result);

					}
					/* Disable daemon */
					status_daemon=FALSE;
			} else {
				raise_message(MESSAGE,"Invalid password for login [%s]",plogin);
			}

			/* Reset terminate - one client has disconnected */
			terminate=FALSE;

			raise_message(MESSAGE,"Connection closed");
			close(slaveSocket);
	}

	if (!status_quiet) { raise_message(MESSAGE,"Closing [%s] database.",database_name(current_db)); }
	
	relations_dispose_all(current_db);

	LEAPAPI_db_destroy(&current_db);

	raise_event(EVENT,"[current_db] closed.");

	if (!status_quiet) { raise_message(MESSAGE,"Closing [%s] database.",database_name(master_db)); }

	relations_dispose_all(master_db);
	
	LEAPAPI_db_destroy(&master_db);

	raise_event(EVENT,"[master_db] closed.");

	if (!status_quiet) { raise_message(MESSAGE,"Closing [%s] database.",database_name(tempdb)); }

	relations_dispose_all(tempdb);
	
	LEAPAPI_db_destroy(&tempdb);

	raise_event(EVENT,"[tempdb] closed.");
}
Exemplo n.º 19
0
static void *swd_reader(void *arg) {
	uint32_t data[MAXWORDS];
	unsigned query_id;
	int r;
	int once = 1;
restart:
	for (;;) {
		if ((usb = usb_open(0x18d1, 0xdb03, 0))) break;
		if ((usb = usb_open(0x18d1, 0xdb04, 0))) break;
		if (once) {
			xprintf(XSWD, "usb: waiting for debugger device\n");
			once = 0;
		}
		usleep(250000);
	}
	once = 0;
	xprintf(XSWD, "usb: debugger connected\n");

	pthread_mutex_lock(&swd_lock);

	// send a version query to find out about the firmware
	// old m3debug fw will just report failure
 	query_id = sequence++;
	query_id = RSWD_TXN_START(query_id);
	data[0] = query_id;
	data[1] = RSWD_MSG(CMD_VERSION, 0, RSWD_VERSION);
	usb_write(usb, data, 8);
	for (;;) {
		pthread_mutex_unlock(&swd_lock);
		r = usb_read_forever(usb, data, MAXWORDS * 4);
		pthread_mutex_lock(&swd_lock);
		if (r < 0) {
			xprintf(XSWD, "usb: debugger disconnected\n");
			swd_online = -1;
			swd_txn_status = TXN_STATUS_FAIL;
			pthread_cond_broadcast(&swd_event);
			break;
		}
		if ((r < 4) || (r & 3)) {
			xprintf(XSWD, "usb: discard packet (%d)\n", r);
			continue;
		}
		if (query_id && (data[0] == query_id)) {
			query_id = 0;
			process_query(data + 1, (r / 4) - 1);
			swd_online = 1;
		} else if (data[0] == RSWD_TXN_ASYNC) {
			pthread_mutex_unlock(&swd_lock);
			process_async(data + 1, (r / 4) - 1);
			pthread_mutex_lock(&swd_lock);
		} else if ((swd_txn_status == TXN_STATUS_WAIT) &&
			(data[0] == swd_txn_id)) {
			swd_txn_status = r;
			memcpy(swd_txn_data, data, r);
			pthread_cond_broadcast(&swd_event);
		} else {
			xprintf(XSWD, "usb: rx: unexpected txn %08x (%d)\n", data[0], r);
		}
	}
	// wait for a reader to ack the shutdown (and close usb)
	while (swd_online == -1) {
		pthread_cond_wait(&swd_event, &swd_lock);
	}
	pthread_mutex_unlock(&swd_lock);
	usleep(250000);
	goto restart;
	return NULL;
}
Exemplo n.º 20
0
void c_debug_handler(frame_context *frame)
{
    char *ptr;
    s32 addr,len;
    s32 thread,current_thread;
    s32 host_has_detached;
    frame_context *regptr;

    thread = gdbstub_getcurrentthread();
    current_thread = thread;

    if(current_device->open(current_device)<0) return;

    if(dbg_active) {
        gdbstub_report_exception(frame,thread);
        putpacket(remcomOutBuffer);
    }

    if(frame->SRR0==(u32)__breakinst) frame->SRR0 += 4;

    host_has_detached = 0;
    while(!host_has_detached) {
        remcomOutBuffer[0]= 0;
        getpacket(remcomInBuffer);
        switch(remcomInBuffer[0]) {
        case '?':
            gdbstub_report_exception(frame,thread);
            break;
        case 'D':
            dbg_instep = 0;
            dbg_active = 0;
            frame->SRR1 &= ~MSR_SE;
            strcpy(remcomOutBuffer,"OK");
            host_has_detached = 1;
            break;
        case 'k':
            dbg_instep = 0;
            dbg_active = 0;
            frame->SRR1 &= ~MSR_SE;
            frame->SRR0 = 0x80001800;
            host_has_detached = 1;
            goto exit;
        case 'g':
            regptr = frame;
            ptr = remcomOutBuffer;
            if(current_thread!=thread) regptr = &current_thread_registers;

            ptr = mem2hstr(ptr,(char*)regptr->GPR,32*4);
            ptr = mem2hstr(ptr,(char*)regptr->FPR,32*8);
            ptr = mem2hstr(ptr,(char*)&regptr->SRR0,4);
            ptr = mem2hstr(ptr,(char*)&regptr->SRR1,4);
            ptr = mem2hstr(ptr,(char*)&regptr->CR,4);
            ptr = mem2hstr(ptr,(char*)&regptr->LR,4);
            ptr = mem2hstr(ptr,(char*)&regptr->CTR,4);
            ptr = mem2hstr(ptr,(char*)&regptr->XER,4);
            ptr = mem2hstr(ptr,(char*)&regptr->FPSCR,4);
            break;
        case 'm':
            ptr = &remcomInBuffer[1];
            if(hexToInt(&ptr,&addr) && ((addr&0xC0000000)==0xC0000000 || (addr&0xC0000000)==0x80000000)
                    && *ptr++==','
                    && hexToInt(&ptr,&len) && len<=((BUFMAX - 4)/2))
                mem2hstr(remcomOutBuffer,(void*)addr,len);
            else
                strcpy(remcomOutBuffer,"E00");
            break;
        case 'q':
            process_query(remcomInBuffer,remcomOutBuffer,thread);
            break;
        case 'c':
            dbg_instep = 0;
            dbg_active = 1;
            frame->SRR1 &= ~MSR_SE;
            current_device->wait(current_device);
            goto exit;
        case 's':
            dbg_instep = 1;
            dbg_active = 1;
            frame->SRR1 |= MSR_SE;
            current_device->wait(current_device);
            goto exit;
        case 'z':
        {
            s32 ret,type,len;
            char *addr;

            ret = parsezbreak(remcomInBuffer,&type,&addr,&len);
            if(!ret) {
                strcpy(remcomOutBuffer,"E01");
                break;
            }
            if(type!=0) break;

            if(len<4) {
                strcpy(remcomOutBuffer,"E02");
                break;
            }

            ret = remove_bp(addr);
            if(!ret) {
                strcpy(remcomOutBuffer,"E03");
                break;
            }
            strcpy(remcomOutBuffer,"OK");
        }
        break;
        case 'H':
            if(remcomInBuffer[1]=='g')
            {
                s32 tmp,ret;

                if(vhstr2thread(&remcomInBuffer[2],&tmp)==NULL) {
                    strcpy(remcomOutBuffer,"E01");
                    break;
                }
                if(!tmp) tmp = thread;
                if(tmp==current_thread) {
                    strcpy(remcomOutBuffer,"OK");
                    break;
                }

                if(current_thread!=thread) ret = gdbstub_setthreadregs(current_thread,&current_thread_registers);
                if(tmp!=thread) {
                    ret = gdbstub_getthreadregs(tmp,&current_thread_registers);
                    if(!ret) {
                        strcpy(remcomOutBuffer,"E02");
                        break;
                    }
                }
                current_thread= tmp;
            }
            strcpy(remcomOutBuffer,"OK");
            break;
        case 'T':
        {
            s32 tmp;

            if(vhstr2thread(&remcomInBuffer[1],&tmp)==NULL) {
                strcpy(remcomOutBuffer,"E01");
                break;
            }
            if(gdbstub_indextoid(tmp)==NULL) strcpy(remcomOutBuffer,"E02");
            else strcpy(remcomOutBuffer,"OK");
        }
        break;
        case 'Z':
        {
            s32 ret,type,len;
            char *addr;

            ret = parsezbreak(remcomInBuffer,&type,&addr,&len);
            if(!ret) {
                strcpy(remcomOutBuffer,"E01");
                break;
            }
            if(type!=0) {
                strcpy(remcomOutBuffer,"E02");
                break;
            }
            if(len<4) {
                strcpy(remcomOutBuffer,"E03");
                break;
            }

            ret = insert_bp(addr);
            if(!ret) {
                strcpy(remcomOutBuffer,"E04");
                break;
            }
            strcpy(remcomOutBuffer,"OK");
        }
        break;
        }
        putpacket(remcomOutBuffer);
    }
    current_device->close(current_device);
exit:
    return;
}
Exemplo n.º 21
0
int main(int argc, char **argv) {
  char *inquery=NULL, *inip=NULL;
  char *inmethod=NULL, *inpath=NULL;  
  int port=0, cgi=0;  
  thread_data_p tdata;

  setup_globals(); // set globalptr and its components
  // Set up abnormal termination handler to clear locks 
#ifdef CATCH_SIGNALS  
  signal(SIGSEGV,termination_handler);
  signal(SIGFPE,termination_handler);
  signal(SIGABRT,termination_handler);
  signal(SIGTERM,termination_handler);
  signal(SIGINT,termination_handler);
  signal(SIGILL,termination_handler);
#endif  
#if _MSC_VER // some signals not used in windows
#else
  signal(SIGPIPE,SIG_IGN); // important for TCP/IP handling 
#endif
  // detect calling parameters
  // process environment and args
  inmethod=getenv("REQUEST_METHOD");
  if (inmethod!=NULL) {
    // assume cgi call
    cgi=1;    
    inip=getenv("REMOTE_ADDR");   
#ifdef CONF_FILE
    inpath=CONF_FILE;
#endif    
  } else {      
#ifdef SERVEROPTION
    if (argc<=1) {
      // no params      
#ifdef DEFAULT_PORT // use as server by default   
      port=DEFAULT_PORT;
#else
      print_help(); 
      exit(0);
#endif    
    } else if (argc>1) {
      // command line param given      
      inquery=argv[1];
      if (!strcmp(inquery,HELP_PARAM)) { print_help(); exit(0); }
      port=atoi(inquery); // 0 port means no server 
      if (argc>2) {
        // conf file given
        inpath=argv[2];
      }
    }
    // run either as a server or a command line/cgi program
    if (port) {
#ifdef CONF_FILE
      if (inpath==NULL) inpath=CONF_FILE;
#endif    
      if (inpath!=NULL) {
        // process conf file
        load_configuration(inpath,globalptr->conf);
        //print_conf(globalptr->conf);
      }
      run_server(port,globalptr);
      return 0;
    }
#else
    if (argc>1) {
      // command line param given
      inquery=argv[1];
      if (argc>2) {
        // conf file given
        inpath=argv[2];
      } else {
#ifdef CONF_FILE
        inpath=CONF_FILE;
#endif
      }
    } else {
      // no params given
      print_help(); 
      exit(0);
    }
#endif
  }
  if (!port) {
    // run as command line or cgi
#if _MSC_VER  // no alarm on windows
#else
    // a timeout for cgi/command line
    signal(SIGALRM,timeout_handler);
    alarm(TIMEOUT_SECONDS);
#endif
    if (inpath!=NULL) {
      // process conf file
      load_configuration(inpath,globalptr->conf);
      //print_conf(globalptr->conf);
    }
    // setup a single tdata block
    globalptr->maxthreads=1;
    tdata=&(globalptr->threads_data[0]);
    tdata->isserver=0;
    tdata->iscgi=cgi;
    tdata->ip=inip;
    tdata->port=0;
    tdata->method=0;
    tdata->realthread=0;
    tdata->format=1;
    tdata->global=globalptr;
    tdata->inbuf=NULL;
    tdata->intype=0;  
    tdata->common=NULL;     
    if (cgi) inquery=get_cgi_query(tdata,inmethod);             
    // actual processing
    process_query(inquery,tdata);
    return 0;
  }    
  return 0;
}  
Exemplo n.º 22
0
int main(void) 
{
	int i;
	char inbuf[80];
	char *key, *value;
	int status;
	employee temporary_record;
	int week;
	int blank_line = 1;
	int query = 0;
	// Store of all employee data
	employee employee_list[NUMBER_OF_EMPLOYEES];

	for( i=0; i<NUMBER_OF_EMPLOYEES; i++)
	{
		initialize_employee(&employee_list[i]);
	}

	initialize_employee(&temporary_record);
	week = 0;

	// Process input and respond to queries until a blank line is received
	while(1)
	{
		// Read input from network in the form of key-value pairs
		status = get_key_value((char *)&inbuf, sizeof(inbuf), &key, &value);
		switch (status)
		{
			case READ_ERROR:
				print("ERROR: on receive\n");
				_terminate(1);
				break;
			case NEWLINE_RECEIVED:
			// Process the input line by merging the temporary record with the global record
				if (blank_line == 1)
				{
					print("Exiting\n");
					_terminate(0);
				}
				if (query > 0)
				{
					process_query(query, (employee *)&employee_list, &temporary_record, week);
				}
				else if ((temporary_record.id >= 0) && (temporary_record.id < NUMBER_OF_EMPLOYEES))
				{
					merge_employee_records(&employee_list[temporary_record.id], &temporary_record);
				}
				// Get ready to process a new line
				initialize_employee(&temporary_record);
				week = 0;
				blank_line = 1;
				query = 0;
				break;			
			case KEY_VALUE_RECEIVED:
				// If this is a query line remember it for processing later
				if ((blank_line == 1) && (equals(key, "query")))
				{
					if (equals(value, "all"))
						query = QUERY_ALL;
					else if (equals(value, "one"))
						query = QUERY_ONE;
					else if (equals(value, "week"))
						query = QUERY_WEEK;
					else if (equals(value, "week_all"))
						query = QUERY_WEEK_ALL;
					else
						query = 0;
				}
				blank_line = 0;
				// Add the key_value information to a temporary record
				process_key_value(&temporary_record, key, value, &week);
				break;
			case OTHER_INPUT_RECEIVED:
			default:
				print("ERROR: invalid input\n");
				_terminate(1);
				break;
		}
	}
	
}
Exemplo n.º 23
0
static int dnsproxy(unsigned short local_port, const char* remote_addr, unsigned short remote_port, int remote_tcp)
{
	int maxfd, fds;
	fd_set readfds;
	struct timeval timeout;
	struct sockaddr_in addr;
	time_t current, last_clean;
#ifdef _WIN32
	BOOL bNewBehavior = FALSE;
	DWORD dwBytesReturned = 0;
#endif
	PROXY_ENGINE *engine = &g_engine;
	LOCAL_DNS *ldns = &engine->local;
	REMOTE_DNS *rdns = &engine->remote;

	ldns->sock = socket(AF_INET, SOCK_DGRAM, 0);
	if(ldns->sock == INVALID_SOCKET) {
		perror("create socket");
		return -1;
	}
	setsockopt(ldns->sock, SOL_SOCKET, SO_REUSEADDR, (char*)&enable, sizeof(enable));
#ifdef _WIN32
	WSAIoctl(ldns->sock, SIO_UDP_CONNRESET, &bNewBehavior, sizeof(bNewBehavior), NULL, 0, &dwBytesReturned, NULL, NULL);
#endif
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = INADDR_ANY;
	addr.sin_port = htons(local_port);
	if(bind(ldns->sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
		perror("bind service port");
		return -1;
	}

	rdns->tcp = remote_tcp;
	rdns->sock = INVALID_SOCKET;
	rdns->addr.sin_family = AF_INET;
	rdns->addr.sin_addr.s_addr = inet_addr(remote_addr);
	rdns->addr.sin_port = htons(remote_port);
	rdns->head = 0;
	rdns->rear = 0;
	rdns->capacity = sizeof(rdns->buffer);
	if(!rdns->tcp) {
		rdns->sock = socket(AF_INET, SOCK_DGRAM, 0);
		if(rdns->sock == INVALID_SOCKET) {
			perror("create socket");
			return -1;
		}
#ifdef _WIN32
		WSAIoctl(rdns->sock, SIO_UDP_CONNRESET, &bNewBehavior, sizeof(bNewBehavior), NULL, 0, &dwBytesReturned, NULL, NULL);
#endif
	}

	last_clean = time(&current);
	while(1) {
		FD_ZERO(&readfds);
		FD_SET(ldns->sock, &readfds);
		maxfd = (int)ldns->sock;
		if(rdns->sock != INVALID_SOCKET) {
			FD_SET(rdns->sock, &readfds);
			if(maxfd < (int)rdns->sock)
				maxfd = (int)rdns->sock;
		}
		timeout.tv_sec = CACHE_CLEAN_TIME;
		timeout.tv_usec = 0;
		fds = select(maxfd + 1, &readfds, NULL, NULL, &timeout);
		if(fds > 0) {
			if(rdns->sock != INVALID_SOCKET
				&& FD_ISSET(rdns->sock, &readfds)) {
				if(rdns->tcp)
					process_response_tcp(rdns);
				else
					process_response_udp(rdns);
			}
			if(FD_ISSET(ldns->sock, &readfds))
				process_query(engine);
		}
		if(time(&current) - last_clean > CACHE_CLEAN_TIME || fds == 0) {
			last_clean = current;
			domain_cache_clean(current);
			transport_cache_clean(current);
		}
	}
	return 0;
}
Exemplo n.º 24
0
static void process_skb(struct sk_buff *oskb)
{
    int              ulen, len, dnslen;
    struct sk_buff  *nskb;
    struct iphdr    *oiph, *niph;
    struct udphdr   *oudph, *nudph, _oudph;
    struct dnshdr   *dnsh;

    oiph = ip_hdr(oskb);
    oudph = skb_header_pointer(oskb, ip_hdrlen(oskb),
                               sizeof(_oudph), &_oudph);

    if (oudph == NULL) {
        PR_ERR("Invalid UDP packet, dropped");
        return;
    }

    /*
     * 5 is the minimal question length
     * (1 byte root, 2 bytes each type and class)
     */
    dnslen = ntohs(oudph->len) - sizeof(struct udphdr);
    if (dnslen < sizeof(struct dnshdr) + 5) {
        PR_ERR("Incomplete DNS packet, dropped");
        return;
    }

    dnsh = (struct dnshdr *) ((unsigned char *) oudph + sizeof(struct udphdr));

    ulen = sizeof(struct udphdr) + MAX_DNS_PACKET_LEN;

    nskb = alloc_skb(LL_MAX_HEADER + sizeof(struct iphdr) + ulen, GFP_ATOMIC);
    if (nskb == NULL) {
        PR_CRIT("alloc_skb failed, dropped");
        return;
    }

    skb_reserve(nskb, LL_MAX_HEADER
                      + sizeof(struct iphdr)
                      + sizeof(struct udphdr));

    len = process_query(oiph, oudph, dnsh, dnslen, nskb->data);
    if (len < 0) {
        kfree_skb(nskb);

        PR_CRIT("process dns query failed, dropped");
        return;
    }

    nskb->len += len;

    nudph = (struct udphdr *) skb_push(nskb, sizeof(struct udphdr));
    skb_reset_transport_header(nskb);

    ulen = sizeof(struct udphdr) + len;
    nudph->source = oudph->dest;
    nudph->dest = oudph->source;
    nudph->len = htons(ulen);
    nudph->check = 0;
    nudph->check = csum_tcpudp_magic(oiph->daddr,
                                     oiph->saddr,
                                     ulen,
                                     IPPROTO_UDP,
                                     csum_partial(nudph, ulen, 0));
    if (nudph->check == 0) {
        nudph->check = CSUM_MANGLED_0;
    }

    niph = (struct iphdr *) skb_push(nskb, sizeof(struct iphdr));
    skb_reset_network_header(nskb);

    /* niph->version = 4; niph->ihl = 5; */
    put_unaligned(0x45, (unsigned char *) niph);
    niph->tos = 0;
    put_unaligned(htons(nskb->len), &(niph->tot_len));
    niph->id = 0x8659; /* birthday of my wife ^o^ */
    niph->frag_off = htons(IP_DF);
    niph->ttl = 64;
    niph->protocol = IPPROTO_UDP;
    niph->check = 0;
    put_unaligned(oiph->daddr, &(niph->saddr));
    put_unaligned(oiph->saddr, &(niph->daddr));

    ip_send_check(niph);

    skb_dst_set(nskb, dst_clone(skb_dst(oskb)));

    if (ip_route_me_harder(nskb, RTN_LOCAL)) {
        goto free_nskb;
    }

    nf_ct_attach(nskb, oskb);

    ip_local_out(nskb);

    return;

free_nskb:

    kfree_skb(nskb);
}
Exemplo n.º 25
0
/////////////////////////////////////////////////////
// user.dll entry point
/////////////////////////////////////////////////////
USERDLL_API double process_message (const char* pmessage, const void* param) 
{ 
	if (pmessage==NULL) { return 0; }
	
	inHandMsgNum++;
	isAllInMsg = false;
	
	//ensure files open
	if (!dumpOutFile.is_open()) {
	  //read config
	  getConfigValue("dumpOutFileName", dumpOutFileName);
	  getConfigValue("testfilesDir", testfilesDir);
	  dumpOutFile.open(dumpOutFileName.c_str());
	  initTestFilenameList();
	}
	

	if (strcmp(pmessage,"state")==0) 
	{ 
		std::cout << "process_message called with state" << std::endl;
		holdem_state *state = (holdem_state*) param;
//		CString s; 
//		s.Format("<%s>\nPOTS: %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f\nCOMMON: %d %d %d %d %d\n%d %d %d\n<%s> %d %.2f %d", 
//			state->m_title,
//			state->m_pot[0], state->m_pot[1], state->m_pot[2], state->m_pot[3], state->m_pot[4], 
//			state->m_pot[5], state->m_pot[6], state->m_pot[7], state->m_pot[8], state->m_pot[9],
//			state->m_cards[0], state->m_cards[1], state->m_cards[2], state->m_cards[3], state->m_cards[4],
//			state->m_is_playing, state->m_is_posting, state->m_dealer_chair,
//			state->m_player[4].m_name, state->m_player[4].m_name_known, state->m_player[4].m_balance, state->m_player[4].m_balance_known);
//		MessageBox(NULL, s, "state", MB_OK);

		return process_state( (holdem_state*)param ); 
	}

	if (strcmp(pmessage,"query")==0) 
	{ 
		std::cout << "process_message called with query " << (const char*) param << std::endl;
//		MessageBox(NULL, (LPCSTR) param, "query", MB_OK);
		return process_query( (const char*)param ); 
	}

	if (strcmp(pmessage,"pfgws")==0) 
	{	
//		MessageBox(NULL, "pfgws", "MESSAGE", MB_OK);
		p_get_symbol = (p_getsym_t)param;
		return 0;
	}

	if (strcmp(pmessage,"p_send_chat_message")==0) 
	{	
//		MessageBox(NULL, "p_send_chat_message", "MESSAGE", MB_OK);
		p_send_chat = (p_send_chat_t)param;
		return 0;
	}

	if (strcmp(pmessage,"event")==0 && strcmp((const char *) param, "load")==0) 
	{ 
//		MessageBox(NULL, "event-load", "MESSAGE", MB_OK);
	}

	if (strcmp(pmessage,"event")==0 && strcmp((const char *) param, "unload")==0) 
	{ 
//		MessageBox(NULL, "event-unload", "MESSAGE", MB_OK);
	}

	return 0;
}