Beispiel #1
0
/**
 * Convert an operation name into an actual operation enum value
 * @param value the value to convert
 * @return an operation enum value
 */
operation operation_value( const char *value )
{
    int N = (int)sizeof(table)/sizeof(const char*);
    char *vcopy = strdup(value);
    if ( vcopy != NULL )
    {
        int top = 0;
        int bottom = N-1;
        str_to_upper( vcopy );
        while ( top <= bottom )
        {
            int mid = (top+bottom)/2;
            int res = strcmp(vcopy,table[mid]);
            if ( res==0 )
                return (operation)mid;
            else if ( res < 0 )
                bottom = mid-1;
            else
                top = mid+1;
        }
        free( vcopy );
    }
    else
        fprintf(stderr,"operation: failed to copy string %s\n",value);
    return EMPTY;
}
Beispiel #2
0
RowPtr
QtSqlCursorBackend::fetch_row()
{
    if (!stmt_->next())
        return RowPtr();
    if (!rec_.get())
        rec_.reset(new QSqlRecord(stmt_->record()));
    int col_count = rec_->count();
    RowPtr row(new Row);
    for (int i = 0; i < col_count; ++i) {
        String name = str_to_upper(rec_->fieldName(i));
        Value v;
        if (!stmt_->value(i).isNull()) {
            QVariant::Type t = rec_->field(i).type();
            if (t == QVariant::Bool || t == QVariant::Int ||
                    t == QVariant::UInt)
                v = Value(stmt_->value(i).toInt());
            else if (t == QVariant::LongLong || t == QVariant::ULongLong)
                v = Value(stmt_->value(i).toLongLong());
            else if (t == QVariant::DateTime || t == QVariant::Date)
                v = Value(stmt_->value(i).toDateTime());
            else if (t == QVariant::Double || (int)t == (int)QMetaType::Float)
                v = Value(stmt_->value(i).toDouble());
            else
                v = Value(stmt_->value(i).toString());
        }
        row->push_back(RowItem(name, v));
    }
    return row;
}
   /*
     Takes a variable name and a variable, converts the name to upper case, inserts        
     the variable into the variable table using the name as a key, and returns an OK value
   */
int
var_table_add( char*       var_name,
               variable*   value,
               GHashTable* var_table ) {
  str_to_upper( var_name );
  g_hash_table_insert( var_table, var_name, value );

  return VAR_OK;
}
   /*
     Takes a bel name and a bel, converts the name to upper case, inserts the bel 
     into the bel table using the name as a key, and returns an OK value
   */
int
bel_table_add( char*         bel_name,
               beam_element* value,
               GHashTable*   bel_table ) {
  str_to_upper( bel_name );
  g_hash_table_insert( bel_table, bel_name, value );

  return BEL_OK;
}
Beispiel #5
0
int DBFGetFieldIndex(DBFHandle psDBF, const char *pszFieldName)

{
    char          name[12], name1[12], name2[12];
    int           i;

    strncpy(name1, pszFieldName,11);
    name1[11] = '\0';
    str_to_upper(name1);

    for( i = 0; i < DBFGetFieldCount(psDBF); i++ )
    {
        DBFGetFieldInfo( psDBF, i, name, NULL, NULL );
        strncpy(name2,name,11);
        str_to_upper(name2);

        if(!strncmp(name1,name2,10))
            return(i);
    }
    return(-1);
}
Beispiel #6
0
void test_css_util_stringx()
{
	char *str;
	assert(1 == str_contains("hello word","wor"));
	assert(0 == str_contains("hello word","worw"));
	assert(2 == str_index_of("hello word","ll"));
	assert(-1 == str_index_of("hello word","lldd"));

	COPY_STR(str,"2abc123");
	str_to_upper(str);
	assert(strcmp(str,"2ABC123") == 0);
	str_to_lower(str);
	assert(strcmp(str,"2abc123") == 0);
}
Beispiel #7
0
void run_server::process(socket_type ssock,
                         pfi::lang::shared_ptr<cgi> cc)
{
  for (;;){
    pfi::lang::shared_ptr<stream_socket> sock(ssock->accept());
    if (!sock) continue;

    if (ssock->timeout()>0 && !sock->set_timeout(ssock->timeout()))
      continue;

    try{
      http::request req(sock);
      stringstream sout;

      map<string, string> env;

      for (http::header::iterator p=req.head().begin();
           p!=req.head().end(); p++)
        env["HTTP_"+str_to_upper(p->first)]=p->second;

      env["REQUEST_METHOD"]=req.method();
      env["REQUEST_URI"]=req.path().path();
      if (req.path().query()!="")
        env["REQUEST_URI"]+="?"+req.path().query();
      env["SCRIPT_NAME"]=req.path().path();
      env["QUERY_STRING"]=req.path().query();

      env["REMOTE_ADDR"]=sock->remote_addr().to_string();
      env["REMOTE_PORT"]=lexical_cast<string>(sock->remote_port());

      env["SERVER_PORT"]=lexical_cast<string>(ssock->port());
      env["SERVER_NAME"]="localhost";
      env["SERVER_PROTOCOL"]="HTTP/1.1";
      env["SERVER_SIGNATURE"]="pficommon/" PFICOMMON_VERSION " standalone web server";
      env["SERVER_SOFTWARE"]="pficommon/" PFICOMMON_VERSION;

      env["CONTENT_LENGTH"]=req.head()["Content-Length"];
      env["CONTENT_TYPE"]=req.head()["Content-Type"];

      cc->exec(req.body(), sout, cerr, env);

      pfi::lang::shared_ptr<http::response> resp=gen_resp(sout);
      resp->send(sock);
    }
    catch(exception&){
    }
  }
}
Beispiel #8
0
void
SOCICursorBackend::prepare(const String &sql)
{
    close();
    sql_ = NARROW(sql);
    is_select_ = starts_with(
            str_to_upper(trim_trailing_space(sql)), _T("SELECT"));
    try {
        stmt_ = new soci::statement(*conn_);
        stmt_->alloc();
        stmt_->prepare(sql_);
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}
Beispiel #9
0
void E8C_LogTitleInit(void)
{
    int     len;
    char    buf[256], *b, *e;
    char    eqid[32], mac[32], laser[32], eqvid[32];
    
    GetParam("EepMfgLaserSerial", laser); 
    GetParam("EepMfgMac1", mac); 
    GetParam("EepEqID", eqid); 
    GetParam("EepEqVersionID", eqvid); 

    str_to_upper(mac);

    memset(buf, 0, sizeof(buf));
    VOS_CfgParamGetByName("EepEqVendorID", buf, sizeof(buf)-1);
    sprintf(e8c_log_title[0], "Manufacturer: %s", buf);

    b = eqid;
    while(*b == '_') {
        b++;
    }
    len = strlen(eqid);
    e = eqid + (len - 1);
    while(*e == '_') {
        e--;
    }
    *(e+1) = 0;
    sprintf(e8c_log_title[1], "ProductClass: %s", b);

    memset(buf, 0, sizeof(buf));
    memcpy(buf, mac, 6);
    strcat(buf, "-");
    memcpy(buf+7, laser+5, 5);
    strcat(buf, mac);
    sprintf(e8c_log_title[2], "SerialNumber: %s", buf);

    memset(buf, 0, sizeof(buf));
    VOS_CfgParamGetByName("EepSwIpAddr", buf, sizeof(buf)-1);
    sprintf(e8c_log_title[3], "IP: %s", buf);

    sprintf(e8c_log_title[4], "HWVer: %s", eqvid);

    memset(buf, 0, sizeof(buf));
    VOS_CfgParamGetByName("SWVER", buf, sizeof(buf)-1);
    sprintf(e8c_log_title[5], "SWVer: %s", buf);
}
Beispiel #10
0
	int split(string filename, string *outbackfile, string *outfilename, bool dir=false)
	{
		string path = str_to_upper(filename);
		if (m_ext == NULL || strlen(m_ext) == 0)
		{
			if(dir)
			{
				size_t pos = path.rfind("/");
				if(pos == string::npos)
				{
					*outbackfile = MAGIC_PATH;
					*outbackfile += "./";
					*outfilename = filename;
				} else {
					*outbackfile = filename.substr(0, pos);
					if(filename.size() >= pos + 1)
						*outfilename = filename.substr(pos + 1);
					else
						outfilename->clear();
				}
			}else
			{
				*outbackfile = filename;
			}
			return 0;
		}

		string ext = m_ext;
		if(!dir)
			ext += "/";
		size_t pos = path.rfind(ext);
		if (pos == string::npos)
		{
			set_last_err_string("can't find ext name in path");
			return -1;
		}

		*outbackfile = filename.substr(0, pos + strlen(m_ext));

		if(filename.size() >= pos + strlen(m_ext) + 1)
			*outfilename = filename.substr(pos + strlen(m_ext) + 1);
		else
			outfilename->clear();
		return 0;
	}
Beispiel #11
0
RowPtr SQLiteCursorBackend::fetch_row()
{
    if (SQLITE_DONE == last_code_ || SQLITE_OK == last_code_)
        return RowPtr();
    if (SQLITE_ROW != last_code_)
        throw DBError(WIDEN(sqlite3_errmsg(conn_)));
    int col_count = sqlite3_column_count(stmt_);
    RowPtr row(new Row(col_count));
    for (int i = 0; i < col_count; ++i) {
        String name = str_to_upper(WIDEN(sqlite3_column_name(stmt_, i)));
        int type = sqlite3_column_type(stmt_, i);
        (*row)[i].first = name;
        if (SQLITE_NULL != type)
            (*row)[i].second = Value(
                    WIDEN((const char *)sqlite3_column_text(stmt_, i)));
    }
    last_code_ = sqlite3_step(stmt_);
    return row;
}
Beispiel #12
0
// principal
int main_echoc(const char *progname, const int argc, const char **argv){
	// variaveis
	register int outlen = 0;

	// texto e opcoes
	char *_output_string = NULL;

	//varivel para cor da fonte
	int  txtcolor = 0;

	// variavel para cor de fundo
	int bgcolor = 0;

	// flags especiais de cores de letra
	// -b = negrito
	// -s = sublinhado
	// -p = piscante
	int _text_effect = 0;
	int _light = 0;


	// quebrar linha apos exibir texto
	int _do_break = 1;

	// resetar cores do terminal apos terminar
	int _do_reset = 1;

	// espacamento
	int _left_space = 0;
	int _right_space = 0;

	// conversao de strings
	int _convert_case = 0; 	// 0 = nao alterar case, 1=upper, 2=lower

	// conversao para formato numerico
	int _to_number_format = 0;		// 0=nao interpretar numero, 2=converter para formato numerico, exemplo: 123456 para 123.456


	// processar argumentos do usuario
	#define TEST_COLOR(TEXT, VALUE)			if(strcmp(TEXT, argv[argn])==0){ argn++; if(cl) bgcolor = VALUE; else txtcolor = VALUE; continue; }

	int argn = 1;
	int cl = 0;
	while( argn < argc){

		// recebe argumentos
		cl = 0;

		// opcoes multi-parametros
		if( argn +1 < argc && (0==strcmp(argv[argn],"-c") || 0==strcmp(argv[argn],"-b")) ){
			if(0==strcmp(argv[argn],"-b")) cl=1;

			if(argn < argc) argn++; else continue;

			TEST_COLOR("blue", 5);
			TEST_COLOR("azul", 5);

			TEST_COLOR("red", 2);
			TEST_COLOR("vermelho", 2);

			TEST_COLOR("green", 3);
			TEST_COLOR("verde", 3);

			TEST_COLOR("magenta", 7);
			TEST_COLOR("celeste", 7);
			TEST_COLOR("cyan", 7);
			TEST_COLOR("cian", 7);

			TEST_COLOR("pink", 6);
			TEST_COLOR("rosa", 6);

			TEST_COLOR("yellow", 4);
			TEST_COLOR("amarelo", 4);

			TEST_COLOR("white", 8);
			TEST_COLOR("light", 9);
			TEST_COLOR("black", 1);

			TEST_COLOR("gray", 10);
			TEST_COLOR("cinza", 10);

			argn++;
		}

		// evitar sair do espaco de memoria
		if(argn >= argc) break;

		// definicao de espacamento
		// ESQUERDA
		if(strcmp(argv[argn],"-L") ==0 ){
			if(argn < argc) argn++; else continue;	
			// tamanho do espaco para alinhar a esquerda
			_left_space = atoi(argv[argn++]);
			if(_left_space < 0) _left_space = 0;
			continue;
		}
		// DIREITA
		if(strcmp(argv[argn],"-R") ==0 ){
			if(argn < argc) argn++; else continue;	
			// tamanho do espaco para alinhar a esquerda
			_right_space = atoi(argv[argn++]);
			if(_right_space < 0) _right_space = 0;
			continue;
		}

		// opcoes singulares
		if(0==strcmp(argv[argn],"-h") || 0==strcmp(argv[argn],"--help")){ help_echoc(); }
		if(0==strcmp(argv[argn],"-B")){ _text_effect = 1; ++argn; continue; }
		if(0==strcmp(argv[argn],"-s")){ _text_effect = 2; ++argn; continue; }
		if(0==strcmp(argv[argn],"-p")){ _text_effect = 3; ++argn; continue; }
		if(0==strcmp(argv[argn],"-l")){ _light = 1; ++argn; continue; }

		if(0==strcmp(argv[argn],"-n")){ _do_break = 2; ++argn; continue; }
		if(0==strcmp(argv[argn],"-k")){ _do_reset = 0; ++argn; continue; }

		// number
		if(0==strcmp(argv[argn],"-N")){ _to_number_format = 1; ++argn; continue; }

		// upper
		if(0==strcmp(argv[argn],"-Y")){ _convert_case = 1; ++argn; continue; }

		// lower
		if(0==strcmp(argv[argn],"-W")){ _convert_case = 2; ++argn; continue; }

		// texto
		if(strlen(argv[argn])) _output_string = strdup(argv[argn]);

		++argn;
	}
	if ( argn != argc ) help_echoc();



	//------------- argumentos prontos



	// evitar apontar para espaco nulo
	if(_output_string==NULL) _output_string = strdup("");

	// Definir coloracao
	if(txtcolor <= 9 && _light) txtcolor+= 9;
	printf("%s%s%s",background_colors[bgcolor], effects[_text_effect], text_colors[txtcolor]);

	// Processar texto de entrada
	if(_output_string) outlen = strlen(_output_string);

	// formatar case?
	if(outlen && _convert_case){
		if(_convert_case == 1) str_to_upper(_output_string);	// Maiusculas
		if(_convert_case == 2) str_to_lower(_output_string);	// Minusculas
	}

	// apenas numeros? formatar
	if(_to_number_format){
		_output_string = str_number_format(_output_string);		// de 1234 para 1.234
		outlen = strlen(_output_string);
	}

	// fazer padding?
	if(_left_space){
		_output_string = str_pad_left(_output_string, _left_space);
	}else if(_right_space){
		_output_string = str_pad_right(_output_string, _right_space);
	}

// FINALIZAR -------------------------------------------------------------------------

	// jogar saida
	printf("%s", _output_string);

	// resetar cor
	if(_do_reset)
		printf("%s%s",background_colors[0],text_colors[0]);
	//-

	// quebra final de linha
	if(1==_do_break)
		printf("\n");
	//-

	// liberar memoria alocada nas formatacoes
	// MY_FREE();

	return 0;




}
   /*
     Take a bel name, converts it to upper case, and returns the pointer to
     the bel if it's found or NULL if the bel is not found
   */
gpointer
bel_table_lookup( char*       bel_name,
                  GHashTable* bel_table ) {
  str_to_upper( bel_name );
  return g_hash_table_lookup( bel_table, bel_name );
}
Beispiel #14
0
/* process a line from the log and store it accordingly */
static int
process_log (GLog * logger, char *line, int test)
{
  GLogItem *glog;
  char buf[DATE_LEN];
  char *qmark = NULL, *req_key = NULL;
  int not_found = 0;            /* 404s */

  /* make compiler happy */
  memset (buf, 0, sizeof (buf));

  if ((line == NULL) || (*line == '\0')) {
    logger->invalid++;
    return 0;
  }

  /* ignore comments */
  if (*line == '#' || *line == '\n')
    return 0;

  if (parsing_spinner != NULL && parsing_spinner->state == SPN_RUN)
    pthread_mutex_lock (&parsing_spinner->mutex);

  logger->process++;

#ifdef TCB_BTREE
  process_generic_data (ht_general_stats, "total_requests");
#endif

  if (parsing_spinner != NULL && parsing_spinner->state == SPN_RUN)
    pthread_mutex_unlock (&parsing_spinner->mutex);

  glog = init_log_item (logger);
  if (parse_format (glog, conf.log_format, conf.date_format, line) == 1) {
    logger->invalid++;

#ifdef TCB_BTREE
    process_generic_data (ht_general_stats, "failed_requests");
#endif
    goto cleanup;
  }

  /* must have the following fields */
  if (glog->host == NULL || glog->date == NULL || glog->status == NULL ||
      glog->req == NULL) {
    logger->invalid++;
    goto cleanup;
  }

  if (test)
    goto cleanup;

  convert_date (buf, glog->date, conf.date_format, "%Y%m%d", DATE_LEN);
  if (buf == NULL)
    goto cleanup;

  /* ignore host */
  if (conf.ignore_ip_idx && ip_in_range (glog->host)) {
    logger->exclude_ip++;
#ifdef TCB_BTREE
    process_generic_data (ht_general_stats, "exclude_ip");
#endif
    goto cleanup;
  }
  /* ignore crawlers */
  if (conf.ignore_crawlers && is_crawler (glog->agent))
    goto cleanup;

  /* agent will be null in cases where %u is not specified */
  if (glog->agent == NULL)
    glog->agent = alloc_string ("-");
  /* process visitors, browsers, and OS */
  process_unique_data (glog->host, buf, glog->agent);

  /* process agents that are part of a host */
  if (conf.list_agents)
    process_host_agents (glog->host, glog->agent);

  /* is this a 404? */
  if (!memcmp (glog->status, "404", 3)) {
    not_found = 1;
  }
  /* treat 444 as 404? */
  else if (!memcmp (glog->status, "444", 3) && conf.code444_as_404) {
    not_found = 1;
  }
  /* check if we need to remove the request's query string */
  else if (conf.ignore_qstr) {
    if ((qmark = strchr (glog->req, '?')) != NULL) {
      if ((qmark - glog->req) > 0)
        *qmark = '\0';
    }
  }

  req_key = xstrdup (glog->req);
  /* include HTTP method/protocol to request */
  if (conf.append_method && glog->method) {
    str_to_upper (glog->method);
    append_method_to_request (&req_key, glog->method);
  }
  if (conf.append_protocol && glog->protocol) {
    str_to_upper (glog->protocol);
    append_protocol_to_request (&req_key, glog->protocol);
  }
  if ((conf.append_method) || (conf.append_protocol))
    req_key = deblank (req_key);

  /* process 404s */
  if (not_found)
    process_request (ht_not_found_requests, req_key, glog);
  /* process static files */
  else if (verify_static_content (glog->req))
    process_request (ht_requests_static, req_key, glog);
  /* process regular files */
  else
    process_request (ht_requests, req_key, glog);

  /* process referrers */
  process_referrers (glog->ref);
  /* process status codes */
  process_generic_data (ht_status_code, glog->status);
  /* process hosts */
  process_generic_data (ht_hosts, glog->host);
  /* process bandwidth  */
  process_request_meta (ht_date_bw, buf, glog->resp_size);
  process_request_meta (ht_file_bw, req_key, glog->resp_size);
  process_request_meta (ht_host_bw, glog->host, glog->resp_size);
  /* process time taken to serve the request, in microseconds */
  process_request_meta (ht_file_serve_usecs, req_key, glog->serve_time);
  process_request_meta (ht_host_serve_usecs, glog->host, glog->serve_time);
  logger->resp_size += glog->resp_size;
#ifdef TCB_BTREE
  process_request_meta (ht_general_stats, "bandwidth", glog->resp_size);
#endif

cleanup:
  free_logger (glog);
  if (req_key != NULL)
    free (req_key);

  return 0;
}
Beispiel #15
0
static char *
parse_req (char *line, GLogItem * glog)
{
  const char *lookfor = NULL;
  char *req, *request, *req_l = NULL, *req_r = NULL;
  char *method = NULL, *protocol = NULL;
  ptrdiff_t req_len;

  if ((lookfor = "OPTIONS ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "GET ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "HEAD ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "POST ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "PUT ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "DELETE ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "TRACE ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "CONNECT ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "PATCH", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "options ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "get ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "head ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "post ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "put ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "delete ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "trace ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "connect ", req_l = strstr (line, lookfor)) != NULL ||
      (lookfor = "patch", req_l = strstr (line, lookfor)) != NULL) {
    /* didn't find it - weird  */
    if ((req_r = strstr (line, " HTTP/1.0")) == NULL &&
        (req_r = strstr (line, " HTTP/1.1")) == NULL)
      return alloc_string ("-");

    req_l += strlen (lookfor);
    req_len = req_r - req_l;

    /* make sure we don't have some weird requests */
    if (req_len <= 0)
      return alloc_string ("-");

    req = xmalloc (req_len + 1);
    strncpy (req, req_l, req_len);
    req[req_len] = 0;

    if (conf.append_method) {
      method = trim_str (xstrdup (lookfor));
      str_to_upper (method);
      glog->method = method;
    }

    if (conf.append_protocol) {
      protocol = xstrdup (++req_r);
      str_to_upper (protocol);
      glog->protocol = protocol;
    }
  } else
    req = alloc_string (line);

  request = decode_url (req);
  if (request != NULL && *request != '\0') {
    free (req);
    return request;
  }

  return req;
}
   /*
     Takes a variable name, converts it to upper case, and returns the pointer to
     the variable if it's found or NULL if the variable is not found
   */
gpointer
var_table_lookup( char*       var_name,
                  GHashTable* var_table ) {
  str_to_upper( var_name );
  return g_hash_table_lookup( var_table, var_name );
}
Beispiel #17
0
/* ����ֵΪ0��ʾ�Ѽ�¼��δ���ڣ���1��ʾ�Ѵ��� */
int write_pop_user(char *user, char *userid, char *pop_name)
{	
	FILE *fp;
	char buf[256];
	char path[256];
	int isprivilege = 0; 

	char username[USER_LEN + 2];
	sprintf(username, "%s\n", user);

	// ���Ƚ�����Ȩ�û���privilege������
	sprintf(path, MY_BBS_HOME "/etc/pop_register/%s_privilege" , pop_name);

	fp = fopen(path, "r");
	if (fp != NULL)
	{
		while(fgets(buf, 256, fp) != NULL)
		{
			if (strcmp(str_to_upper(username), str_to_upper(buf)) == 0)
			{
				isprivilege = 1;
				break;
			}
		}
			
		fclose(fp);
	}


	// ���½�����ͨ�û�����
	sprintf(path, MY_BBS_HOME "/etc/pop_register/%s", pop_name);

	int lockfd = openlockfile(".lock_new_register", O_RDONLY, LOCK_EX); // ��������֤�������
	
	fp = fopen(path, "a+");

	if (fp == NULL) 
	{	
		close(lockfd);
		return 0;
	}

	if (isprivilege == 0)
	{
		fseek(fp, 0, SEEK_SET);
		while(fgets(buf, 256, fp) != NULL)
		{
			if (strcmp(str_to_upper(username), str_to_upper(buf)) == 0)
			{
				fclose(fp);
				close(lockfd);
				return 1;
			}
			fgets(buf, 256, fp);
		}
	}

	fseek(fp, 0, SEEK_END);
	fputs(user, fp);

	time_t t;
	time(&t);

	sprintf(buf, "\n%s : %s : %s", userid, fromhost, ctime(&t));
	fputs(buf, fp);

	fclose(fp);
	close(lockfd);
	return 0;
}
Beispiel #18
0
//判断参数携带的值(存放在*optarg中)是否合法,并对全局变量opts进行赋值
//返回;成功:0   失败:-1;
int set_value_from_cmd(char *optarg, int *option_index, Cmd_Opt opts[]) {
  //把所有show_usage放在GetCommondLine中
  int ret = -1;
  long value = -1;  //参数携带的值

  //(1)要根据携带的参数进行合法检验,避免出现./bcsniffer --protocol --interval的情况!!!
  //如:如果参数需要是数字,则遍历参数,判断是否在字符0~9的范围内,能否转换为合法数字;否则非法
  //option_index为0时,不进行数字验证,因为是协议名称字符串
  if (*option_index != 0 && optarg != NULL ) {
    ret = convert_to_digital(optarg, strlen(optarg), &value);
    if (ret == -1) {       //不能转化为合法数字
      printf("\n convert to digital result =%c or %d\n", ret, ret);
      return -1;
    }
  }
  // This is for -x, since no value request, so optarg should NULL
  else if (*option_index == 3 && optarg == NULL ) {
    opts[3].status = TRUE;
    opts[3].rightopt.print_data = TRUE;
    return 0;
  }

  //对传入的参数进行赋值
  //同时:(2)避免出现相同意义的选项以长选项和短选项的方式同时出现,
  //处理方法:设置数据结构中的status元素.
  //其实,对于本程序每个参数都要带数值参数来说,步骤(1)已经避免了(2)需要预防的情况
  //只有当所跟的参数值不要求是数字,而可能与-或者--混淆时,第二点才显示出他的作用
  str_to_upper(optarg); // This is just for string value. Like -p tcp.
  switch (*option_index) {
  case 0:
    if (FALSE == opts[0].status) {
      if (!strncmp("TCP", optarg, strlen("TCP"))) {
        opts[0].rightopt.protocol = TCP;
      }
      else if (!strncmp("UDP", optarg, strlen("UDP"))) {
        opts[0].rightopt.protocol = UDP;
      }
      else if (!strncmp("ICMP", optarg, strlen("ICMP"))) {
        opts[0].rightopt.protocol = ICMP;
      }
      else if (!strncmp("ALLPROTOCOL", optarg, strlen("ALLPROTOCOL"))) {
        opts[0].rightopt.protocol = ALLPROTOCOL;
      }
      else {
        return -1;
      }
    }
    else {
      printf("protocol: maybe the long opt and short opt appearence both\n");
      return -1;
    }
    break;
  case 1:
    if (FALSE == opts[1].status) {
      opts[1].rightopt.interval = value;    }
    else {
      printf("interval: maybe the long opt and short opt appearance both\n");
      return -1;
    }
    break;
  case 2:
    if (FALSE == opts[2].status) {
      opts[2].rightopt.endcount = value;
    }
    else {
      printf("count: maybe the long opt and short opt appearance both\n");
      return -1;
    }
    break;
  default:
    printf("option_index err!option_index=%d\n", *option_index);
    return -1;
  }
  opts[*option_index].status = TRUE;

  //(3)还需要处理这种情况:
  //比如一个程序接受两种合法的参数:
  // 1. ./progname -D 或者./progname -d 或者./progname --delrecord
  // 2. ./progname -A 12 或者./progname -a 123 或者./progname --addrecord  123

  //(4)处理短字符与长字符的第一个字母相同,会把-delrecor认为是-d(-D)的情况

  return 0;
}
Beispiel #19
0
RowPtr SOCICursorBackend::fetch_row()
{
    try {
        if (!stmt_->fetch()) {
#ifdef YB_SOCI_DEBUG
            cerr << "fetch(): false" << endl;
#endif
            return RowPtr();
        }
        RowPtr result(new Row);
        int col_count = row_.size();
#ifdef YB_SOCI_DEBUG
        cerr << "fetch(): col_count=" << col_count << endl;
#endif
        for (int i = 0; i < col_count; ++i) {
            const soci::column_properties &props = row_.get_properties(i);
            String name = str_to_upper(WIDEN(props.get_name()));
            Value v;
            if (row_.get_indicator(i) != soci::i_null) {
                std::tm when;
                unsigned long long x;
                switch (props.get_data_type()) {
                case soci::dt_string:
                    v = Value(WIDEN(row_.get<string>(i)));
                    break;
                case soci::dt_double:
                    v = Value(row_.get<double>(i));
                    break;
                case soci::dt_integer:
                    v = Value(row_.get<int>(i));
                    break;
#if 0
                case soci::dt_unsigned_long:
                    x = row_.get<unsigned long>(i);
                    v = Value((LongInt)x);
                    break;
#endif
                case soci::dt_long_long:
                    x = row_.get<long long>(i);
                    v = Value((LongInt)x);
                    break;
                case soci::dt_unsigned_long_long:
                    x = row_.get<unsigned long long>(i);
                    v = Value((LongInt)x);
                    break;
                case soci::dt_date:
                    when = row_.get<std::tm>(i);
                    v = Value(dt_make(when.tm_year + 1900, when.tm_mon + 1,
                                when.tm_mday, when.tm_hour,
                                when.tm_min, when.tm_sec));
                    break;
                }
            }
#ifdef YB_SOCI_DEBUG
            cerr << "fetch(): col[" << i << "]: name=" << props.get_name()
                << " type=" << props.get_data_type()
                << " value=" << NARROW(v.sql_str()) << endl;
#endif
            result->push_back(make_pair(name, v));
        }
        return result;
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}