bool LexicsCutter::Read_Innormative_Words(std::string& FileName)
{
    FILE *ma_file;
    char line[1024];
    unsigned int pos;
    std::string line_s;
    std::string lchar;

    ma_file = fopen(FileName.c_str(), "rb");

    if (!ma_file)
    {
        sLog.outError("Chat lexics cutter disabled. Reason: LexicsCutterWordsFile file does not exist in the server directory.");
        return false;
    }

    while (!feof(ma_file))
    {
        line[0] = 0x0;
        fgets(line, 1020, ma_file);

        // check for UTF8 prefix and comment
        if (strlen(line) >= 3)
        {
            if (line[0] == '\xEF' && line[1] == '\xBB' && line[2] == '\xBF')
            {
                strncpy(&line[0], &line[3], strlen(line) - 3);
            }
        }

        if (strlen(line) >= 2)
        {
            if (line[0] == '/' && line[1] == '/') continue;
        }

        // check for empty string
        line_s = line;
        line_s = trim(line_s, "\x0A\x0D\x20");
        if (line_s == "") continue;

        // process line without CR/LF
        line_s = line;
        line_s = trim(line_s, "\x0A\x0D");

        // create word vector of vectors
        LC_WordVector vw;
        pos = 0;
        while (ReadUTF8(line_s, lchar, pos))
        {
            // create letter set
            LC_LetterSet vl;

            // initialize letter set with letter read
            vl.insert(lchar);

            // find letter analogs and push them onto the vector
            LC_AnalogMap::iterator itr = AnalogMap.find(lchar);
            if (itr != AnalogMap.end())
            {
                // analogs present, iterate
                for (LC_AnalogVector::iterator itr2 = itr->second.begin(); itr2 != itr->second.end(); itr2++)
                {
                    vl.insert(*itr2);
                }
            }

            // add letter vector to word vector
            vw.push_back(vl);
        }

        // push new word to words list
        WordList.push_back(vw);
    }

    fclose(ma_file);

    return true;
}
Beispiel #2
0
/**
 * Check/authentication of a connection.
 * @param sd: string (atm:md5key or dbpass)
 * @param isServer: string (atm:md5key or dbpass)
 * @return :
 *	-1: success
 *	0: unregistered id;
 *	1: incorrect pass;
 *	2: expired id
 *	3: blacklisted (or registration limit exceeded if new acc);
 *	5: invalid client_version|hash;
 *	6: banned
 *	x: acc state (TODO document me deeper)
 */
int login_mmo_auth(struct login_session_data* sd, bool isServer) {
	struct mmo_account acc;
	int len;

	char ip[16];
	ip2str(session[sd->fd]->client_addr, ip);

	// DNS Blacklist check
	if( login_config.use_dnsbl ) {
		char r_ip[16];
		char ip_dnsbl[256];
		char* dnsbl_serv;
		uint8* sin_addr = (uint8*)&session[sd->fd]->client_addr;

		sprintf(r_ip, "%u.%u.%u.%u", sin_addr[0], sin_addr[1], sin_addr[2], sin_addr[3]);

		for( dnsbl_serv = strtok(login_config.dnsbl_servs,","); dnsbl_serv != NULL; dnsbl_serv = strtok(NULL,",") ) {
			sprintf(ip_dnsbl, "%s.%s", r_ip, trim(dnsbl_serv));
			if( host2ip(ip_dnsbl) ) {
				ShowInfo("DNSBL: (%s) Blacklisted. User Kicked.\n", r_ip);
				return 3;
			}
		}

	}

	//Client Version check
	if( login_config.check_client_version && sd->version != login_config.client_version_to_connect ){
		ShowNotice("Invalid version (account: '%s', auth_vers: '%d', received version: '%d', ip: %s)\n",
			sd->userid, login_config.client_version_to_connect, sd->version, ip);
		return 5;
	}

	len = strnlen(sd->userid, NAME_LENGTH);

	// Account creation with _M/_F
	if( login_config.new_account_flag ) {
		if( len > 2 && strnlen(sd->passwd, NAME_LENGTH) > 0 && // valid user and password lengths
			sd->passwdenc == 0 && // unencoded password
			sd->userid[len-2] == '_' && memchr("FfMm", sd->userid[len-1], 4) ) // _M/_F suffix
		{
			int result;
			// remove the _M/_F suffix
			len -= 2;
			sd->userid[len] = '\0';

			result = login_mmo_auth_new(sd->userid, sd->passwd, TOUPPER(sd->userid[len+1]), ip);
			if( result != -1 )
				return result;// Failed to make account. [Skotlex].
		}
	}

	if( !accounts->load_str(accounts, &acc, sd->userid) ) {
		ShowNotice("Unknown account (account: %s, received pass: %s, ip: %s)\n", sd->userid, sd->passwd, ip);
		return 0; // 0 = Unregistered ID
	}

	if( !login_check_password(sd->md5key, sd->passwdenc, sd->passwd, acc.pass) ) {
		ShowNotice("Invalid password (account: '%s', pass: '******', received pass: '******', ip: %s)\n", sd->userid, acc.pass, sd->passwd, ip);
		return 1; // 1 = Incorrect Password
	}

	if( acc.expiration_time != 0 && acc.expiration_time < time(NULL) ) {
		ShowNotice("Connection refused (account: %s, pass: %s, expired ID, ip: %s)\n", sd->userid, sd->passwd, ip);
		return 2; // 2 = This ID is expired
	}

	if( acc.unban_time != 0 && acc.unban_time > time(NULL) ) {
		char tmpstr[24];
		timestamp2string(tmpstr, sizeof(tmpstr), acc.unban_time, login_config.date_format);
		ShowNotice("Connection refused (account: %s, pass: %s, banned until %s, ip: %s)\n", sd->userid, sd->passwd, tmpstr, ip);
		return 6; // 6 = Your are Prohibited to log in until %s
	}

	if( acc.state != 0 ) {
		ShowNotice("Connection refused (account: %s, pass: %s, state: %d, ip: %s)\n", sd->userid, sd->passwd, acc.state, ip);
		return acc.state - 1;
	}

	if( login_config.client_hash_check && !isServer ) {
		struct client_hash_node *node = NULL;
		bool match = false;

		for( node = login_config.client_hash_nodes; node; node = node->next ) {
			if( acc.group_id < node->group_id )
				continue;
			if( *node->hash == '\0' // Allowed to login without hash
			 || (sd->has_client_hash && memcmp(node->hash, sd->client_hash, 16) == 0 ) // Correct hash
			) {
				match = true;
				break;
			}
		}

		if( !match ) {
			char smd5[33];
			int i;

			if( !sd->has_client_hash ) {
				ShowNotice("Client didn't send client hash (account: %s, pass: %s, ip: %s)\n", sd->userid, sd->passwd, acc.state, ip);
				return 5;
			}

			for( i = 0; i < 16; i++ )
				sprintf(&smd5[i * 2], "%02x", sd->client_hash[i]);

			ShowNotice("Invalid client hash (account: %s, pass: %s, sent md5: %d, ip: %s)\n", sd->userid, sd->passwd, smd5, ip);
			return 5;
		}
	}

	ShowNotice("Authentication accepted (account: %s, id: %d, ip: %s)\n", sd->userid, acc.account_id, ip);

	// update session data
	sd->account_id = acc.account_id;
	sd->login_id1 = rnd() + 1;
	sd->login_id2 = rnd() + 1;
	safestrncpy(sd->lastlogin, acc.lastlogin, sizeof(sd->lastlogin));
	sd->sex = acc.sex;
	sd->group_id = acc.group_id;

	// update account data
	timestamp2string(acc.lastlogin, sizeof(acc.lastlogin), time(NULL), "%Y-%m-%d %H:%M:%S");
	safestrncpy(acc.last_ip, ip, sizeof(acc.last_ip));
	acc.unban_time = 0;
	acc.logincount++;

	accounts->save(accounts, &acc);

	if( sd->sex != 'S' && sd->account_id < START_ACCOUNT_NUM )
		ShowWarning("Account %s has account id %d! Account IDs must be over %d to work properly!\n", sd->userid, sd->account_id, START_ACCOUNT_NUM);

	return -1; // account OK
}
 static int
server(char **argv, char *pname[2], int p[2])
{
	Engine *ep;
	FILE *f;
	char buf[4096], buf1[4096], *msg, *s, *t;
	int rc;
#if 0/*def SERVER_DEBUG*/
	printf("Server got\tpname[0] = \"%s\"\nand\t\tpname[1] = \"%s\"\n",
		pname[0], pname[1]);
	if (*argv) {
		int i;
		printf("Args for MATLAB to interpret:\n");
		for(i = 0; argv[i]; i++)
			printf("\t\"%s\"\n", argv[i]);
		}
#endif
	if (exists(pname[0], 1) || exists(pname[1], 1))
		return 1;
	if (mkfifo(pname[0], 0600))
		return mkfifo_fail(pname[0]);
	if (mkfifo(pname[1], 0600)) {
		unlink(pname[0]);
		return mkfifo_fail(pname[1]);
		}
	s = *argv;
        //if(s){ printf("%s\n",s); fflush(stdout);}
	ep = engOpen(s ? s : "matlab -logfile engine.log");
	if (!ep) {
		Squawk("could not start MATLAB\n");
		return 1;
		}
	/*DEBUG*/engOutputBuffer(ep, mbuf, sizeof(mbuf)-1);
	if (s)
		while(s = *++argv)
			engEvalString(ep, s);
	if (p[1] >= 0) {
		close(p[0]);
		write(p[1], "OK\n", 3);
		close(p[1]);
		}
	rc = 1;
	for(;;) {
		f = fopen(pname[0], "r");
		if (!f)
			break;
		s = fgets(buf, sizeof(buf), f);
		if (!s) {
			fclose(f);
			break;
			}
		trim(s);
		if (!*s) {
			Squawk("server: empty parameters_file name\n");\
 bailout:
			fclose(f);
			break;
			}
		if (!strcmp(s,"quit")) {
			rc = 0;
			goto bailout;
			}
		t = fgets(buf1, sizeof(buf1), f);
		fclose(f);
		if (!t) {
			Squawk("server expected 2 lines from \"%s\"; only got 1.\n",
				pname[0]);
			break;
			}
		trim(t);
		msg = process(ep, s, t) ? "evaluation error" : "results_file written";
		f = fopen(pname[1],"w");
		if (!f) {
			Squawk("Could not open pipe2 file \"%s\"\n", pname[1]);
			break;
			}
		fprintf(f, "%s\n", msg);
		fclose(f);
		}
	engClose(ep);
	unlink(pname[0]);
	unlink(pname[1]);
	return rc;
	}
Beispiel #4
0
void RequestHandler :: handleClient( int fd ){
	Connection conn( fd );
	HttpMessage request, response;
	
	std::string content;
	std::vector< std::string > parts;
	std::string body;
	
	
	bool done = false;
	
	size_t request_counter = 0;
	
	conn.set_timeout( 15 );
	
	while( !done ){
		
		try{
			//std::cerr << "Handler " << *ptr_fd << " receiving..." << std::endl;
			while( content.find( "\r\n\r\n" ) == std::string::npos ){
				content += conn.receive( 1024 );
				}
			} catch( std::string error ){
				//std::cerr << "RH: ERROR: " << error << std::endl;
				done = true;
				continue;
				}
		//std::cerr << "Handler " << *ptr_fd << " done receiving..." << std::endl;
			
		//std::cerr << "content: '" << content << "'" << std::endl;
		parts = split_string( content, "\r\n\r\n" );
		if( parts.size() > 1 ){
			for( size_t i = 1 ; i < parts.size() - 1 ; ++i ){
				body += parts[i] + std::string( "\r\n\r\n" );
				}
			body += parts[parts.size()-1];
			}
		content.clear();
		std::vector<std::string> header_lines = split_string( parts[0], "\r\n" );
		std::vector< std::string > request_line = split_string( header_lines[0], " " );
		//std::cerr << "request_line: '" << header_lines[0] << "' and header_lines.size() = " << header_lines.size() << "request_line.size() = " <<  << std::endl;
		if( header_lines.size() < 2 || request_line.size() != 3 ){
			// return error response
			//conn.disconnect();
			std::cerr << "RH: ERROR: " << "Invalid request line!" << std::endl;
			done = true;
			continue;
			}
		
		request.set_method( request_line[0] );
		request.set_path( request_line[1] );
		request.set_version( request_line[2] );

		for( size_t i = 1 ; i < header_lines.size() ; ++i ){
			std::vector<std::string> tmp = split_string( header_lines[i], ":" );
			if( tmp.size() > 2 ){
				std::string str;
				for( size_t i = 1 ; i < tmp.size() - 1 ; ++i ){
					str += tmp[i] + std::string( ":" );
					}
				str += tmp[tmp.size()-1];
				request.set_header_field( trim(tmp[0] ), trim( str ) );
				}
			else{
				request.set_header_field( trim( tmp[0] ), trim( tmp[1] ) );
				}
			}
		
		
		if( ( request_line[0] == "PUT" ) || ( request_line[0] == "POST" ) ){
			size_t content_length = 0;
			
			if( request.has_header_field( "Content-Length" ) ){
				content_length = string_to_integer( request.get_header_field( "Content-Length" ) );
				}
			if( request.has_header_field( "Transfer-Encoding" ) ){
				if( request.get_header_field( "Transfer-Encoding" ) == "chunked" ){
					bool chunks_done = false;
					size_t chunk_size = 0, pos;
					content = body;
					body.clear();
					
					while( !chunks_done ){
						pos = content.find( "\r\n" );
						if( pos != std::string::npos ){
							std::string hex = content.substr( 0, pos );
							chunk_size = hex_string_to_integer( trim( hex ) );
							content = content.substr( pos+2 );
							if( chunk_size == 0 ){ chunks_done = true; continue; }
							}
						
						try{
							while( content.size() < chunk_size+2 ){
								content += conn.receive( chunk_size - content.size() + 2 );
								}
							} catch( std::string error ){
								//std::cerr << "RH: ERROR: " << error << std::endl;
								 
								done = true;
								continue;
								}
						body += content.substr( 0, chunk_size );
						content = content.substr( chunk_size + 2 );
						
						try{
							while( content.find( "\r\n" ) == std::string::npos ){
								content += conn.receive( 1 );
								}
							} catch( std::string error ){
								//std::cerr << "RH: ERROR:" << error << std::endl;
								done = true;
								break;
								}
						}
					
					}
				}
			else{
				try{
					while( body.size() < content_length ){
						body += conn.receive( content_length - content.size() );
						}
					} catch( std::string error ){
						std::cerr << "RH: ERROR:" << error << std::endl;
						done = true;
						continue;
						}
				}
		
			request.set_body( body );
			
			}
		
		
		//std::cerr << "Request: " << request.serialize() << std::endl;
		try{
			response = RequestHandler::handleRequest( request );
			
			conn.send( response.serialize() );
			} catch( std::string error ){
				//std::cerr << "RH: ERROR: " << error << std::endl;
				}
		
		done = true;
		if( request.has_header_field( "Connection" ) ){
			if( ( request.get_header_field( "Connection" ) == "Keep-Alive" ) || 
				( request.get_header_field( "Connection" ) == "keep-alive" ) ){
				done = false;
				}
			}
		++request_counter;
		if( request_counter > 15 ){
			done = true;
			}	
		}
	
	//printf( "Disconnecting %i \n", conn.get_fd() );
	//gconn_unmark( conn.get_fd() );
	conn.disconnect();
	
	--global_connection_count;
	
	//delete (int*)arg;
	
	//pthread_exit( NULL );
	}
Beispiel #5
0
int mme_app_config_init(char* lib_config_file_name_pP, mme_app_config_t* config_pP) {

  config_t          cfg;
  config_setting_t *setting_sgw                          = NULL;
  char             *sgw_interface_name_for_S1u_S12_S4_up = NULL;
  char             *sgw_ipv4_address_for_S1u_S12_S4_up   = NULL;
  char             *sgw_interface_name_for_S5_S8_up      = NULL;
  char             *sgw_ipv4_address_for_S5_S8_up        = NULL;
  char             *sgw_interface_name_for_S11           = NULL;
  char             *sgw_ipv4_address_for_S11             = NULL;

  config_setting_t *setting_pgw                  = NULL;
  config_setting_t *subsetting                   = NULL;
  config_setting_t *sub2setting                  = NULL;
  char             *pgw_interface_name_for_S5_S8 = NULL;
  char             *pgw_ipv4_address_for_S5_S8   = NULL;
  char             *pgw_interface_name_for_SGI   = NULL;
  char             *pgw_ipv4_address_for_SGI     = NULL;

  char             *delimiters=NULL;
  char             *saveptr1= NULL;
  char             *astring = NULL;
  char             *atoken  = NULL;
  char             *atoken2 = NULL;
  char             *address = NULL;
  char             *cidr    = NULL;
  char             *mask    = NULL;
  int               num     = 0;
  int               i       = 0;
  int               jh, jn;
  unsigned char     buf_in6_addr[sizeof(struct in6_addr)];
  struct in6_addr   addr6_start;
  struct in6_addr   addr6_mask;
  int               prefix_mask;
  uint64_t          counter64;
  unsigned char     buf_in_addr[sizeof(struct in_addr)];
  struct in_addr    addr_start;
  struct in_addr    addr_end;


  memset((char*)config_pP, 0 , sizeof(mme_app_config_t));

  config_init(&cfg);

  if(lib_config_file_name_pP != NULL)
  {
      /* Read the file. If there is an error, report it and exit. */
      if(! config_read_file(&cfg, lib_config_file_name_pP))
      {
          MME_APP_ERROR("%s:%d - %s\n", lib_config_file_name_pP, config_error_line(&cfg), config_error_text(&cfg));
          config_destroy(&cfg);
          AssertFatal (1 == 0, "Failed to parse eNB configuration file %s!\n", lib_config_file_name_pP);
      }
  }
  else
  {
      SPGW_APP_ERROR("No SP-GW configuration file provided!\n");
      config_destroy(&cfg);
      AssertFatal (0, "No SP-GW configuration file provided!\n");
  }

  setting_sgw = config_lookup(&cfg, SGW_CONFIG_STRING_SGW_CONFIG);
  if(setting_sgw != NULL) {
      subsetting = config_setting_get_member (setting_sgw, SGW_CONFIG_STRING_NETWORK_INTERFACES_CONFIG);
      if(subsetting != NULL) {
          if(  (
                     config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_INTERFACE_NAME_FOR_S1U_S12_S4_UP, (const char **)&sgw_interface_name_for_S1u_S12_S4_up)
                  && config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_IPV4_ADDRESS_FOR_S1U_S12_S4_UP,   (const char **)&sgw_ipv4_address_for_S1u_S12_S4_up)
                  && config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_INTERFACE_NAME_FOR_S5_S8_UP,      (const char **)&sgw_interface_name_for_S5_S8_up)
                  && config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_IPV4_ADDRESS_FOR_S5_S8_UP,        (const char **)&sgw_ipv4_address_for_S5_S8_up)
                  && config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_INTERFACE_NAME_FOR_S11,           (const char **)&sgw_interface_name_for_S11)
                  && config_setting_lookup_string( subsetting, SGW_CONFIG_STRING_SGW_IPV4_ADDRESS_FOR_S11,             (const char **)&sgw_ipv4_address_for_S11)
                )
            ) {
              config_pP->sgw_config.ipv4.sgw_interface_name_for_S1u_S12_S4_up = strdup(sgw_interface_name_for_S1u_S12_S4_up);
              cidr = strdup(sgw_ipv4_address_for_S1u_S12_S4_up);
              address = strtok(cidr, "/");
              mask    = strtok(NULL, "/");
              IPV4_STR_ADDR_TO_INT_NWBO ( address, config_pP->sgw_config.ipv4.sgw_ipv4_address_for_S1u_S12_S4_up, "BAD IP ADDRESS FORMAT FOR S1u_S12_S4 !\n" )
              config_pP->sgw_config.ipv4.sgw_ip_netmask_for_S1u_S12_S4_up = atoi(mask);
              free(cidr);

              config_pP->sgw_config.ipv4.sgw_interface_name_for_S5_S8_up = strdup(sgw_interface_name_for_S5_S8_up);
              cidr = strdup(sgw_ipv4_address_for_S5_S8_up);
              address = strtok(cidr, "/");
              mask    = strtok(NULL, "/");
              IPV4_STR_ADDR_TO_INT_NWBO ( address, config_pP->sgw_config.ipv4.sgw_ipv4_address_for_S5_S8_up, "BAD IP ADDRESS FORMAT FOR S5_S8 !\n" )
              config_pP->sgw_config.ipv4.sgw_ip_netmask_for_S5_S8_up = atoi(mask);
              free(cidr);

              config_pP->sgw_config.ipv4.sgw_interface_name_for_S11 = strdup(sgw_interface_name_for_S11);
              cidr = strdup(sgw_ipv4_address_for_S11);
              address = strtok(cidr, "/");
              mask    = strtok(NULL, "/");
              IPV4_STR_ADDR_TO_INT_NWBO ( address, config_pP->sgw_config.ipv4.sgw_ipv4_address_for_S11, "BAD IP ADDRESS FORMAT FOR S11 !\n" )
              config_pP->sgw_config.ipv4.sgw_ip_netmask_for_S11 = atoi(mask);
              free(cidr);
          }
      }
  }

  setting_pgw = config_lookup(&cfg, PGW_CONFIG_STRING_PGW_CONFIG);
  if(setting_pgw != NULL)
  {
      subsetting = config_setting_get_member (setting_pgw, SGW_CONFIG_STRING_NETWORK_INTERFACES_CONFIG);
      if(subsetting != NULL) {
          if(  (
                  config_setting_lookup_string(subsetting,
                          PGW_CONFIG_STRING_PGW_INTERFACE_NAME_FOR_S5_S8,
                          (const char **)&pgw_interface_name_for_S5_S8)
                  && config_setting_lookup_string(subsetting,
                          PGW_CONFIG_STRING_PGW_IPV4_ADDRESS_FOR_S5_S8,
                          (const char **)&pgw_ipv4_address_for_S5_S8)
                  && config_setting_lookup_string(subsetting,
                          PGW_CONFIG_STRING_PGW_INTERFACE_NAME_FOR_SGI,
                          (const char **)&pgw_interface_name_for_SGI)
                  && config_setting_lookup_string(subsetting,
                          PGW_CONFIG_STRING_PGW_IPV4_ADDR_FOR_SGI,
                          (const char **)&pgw_ipv4_address_for_SGI)
                )
            ) {
              config_pP->pgw_config.ipv4.pgw_interface_name_for_S5_S8 = strdup(pgw_interface_name_for_S5_S8);
              cidr = strdup(pgw_ipv4_address_for_S5_S8);
              address = strtok(cidr, "/");
              mask    = strtok(NULL, "/");
              IPV4_STR_ADDR_TO_INT_NWBO ( address, config_pP->pgw_config.ipv4.pgw_ipv4_address_for_S5_S8, "BAD IP ADDRESS FORMAT FOR S5_S8 !\n" )
              config_pP->pgw_config.ipv4.pgw_ip_netmask_for_S5_S8 = atoi(mask);
              free(cidr);

              config_pP->pgw_config.ipv4.pgw_interface_name_for_SGI = strdup(pgw_interface_name_for_SGI);
              cidr = strdup(pgw_ipv4_address_for_SGI);
              address = strtok(cidr, "/");
              mask    = strtok(NULL, "/");
              IPV4_STR_ADDR_TO_INT_NWBO ( address, config_pP->pgw_config.ipv4.pgw_ipv4_address_for_SGI, "BAD IP ADDRESS FORMAT FOR SGI !\n" )
              config_pP->pgw_config.ipv4.pgw_ip_netmask_for_SGI = atoi(mask);
              free(cidr);
          }
      }
      subsetting = config_setting_get_member (setting_pgw, PGW_CONFIG_STRING_IP_ADDRESS_POOL);
      if(subsetting != NULL) {
          sub2setting = config_setting_get_member (subsetting, PGW_CONFIG_STRING_IPV4_ADDRESS_LIST);
          if(sub2setting != NULL) {
              num     = config_setting_length(sub2setting);
              for (i = 0; i < num; i++) {
                  astring = config_setting_get_string_elem(sub2setting,i);
                  if (astring != NULL) {
                      trim(astring, strlen(astring)+1);
                      if (inet_pton(AF_INET, astring, buf_in_addr) < 1) {
                          // failure, test if there is a range specified in the string
                          atoken = strtok(astring, PGW_CONFIG_STRING_IP_ADDRESS_RANGE_DELIMITERS);
                          if (inet_pton(AF_INET, astring, buf_in_addr) == 1) {
                              memcpy (&addr_start, buf_in_addr, sizeof(struct in_addr));
                              // valid address
                              atoken2 = strtok(NULL, PGW_CONFIG_STRING_IP_ADDRESS_RANGE_DELIMITERS);
                              if (inet_pton(AF_INET, atoken2, buf_in_addr) == 1) {
                                  memcpy (&addr_end, buf_in_addr, sizeof(struct in_addr));
                                  // valid address
                                  for (jh = ntohl(addr_start.s_addr); jh <= ntohl(addr_end.s_addr); jh++) {
                                      DevAssert(PGW_MAX_ALLOCATED_PDN_ADDRESSES > config_pP->pgw_config.pool_pdn_addresses.num_ipv4_addresses);
                                      jn = htonl(jh);
                                      if (IN_CLASSA(addr_start.s_addr)) {
                                          if ((jh & 0xFF) && (jh & 0xFF) != 0xFF) {
                                              config_pP->pgw_config.pool_pdn_addresses.ipv4_addresses[config_pP->pgw_config.pool_pdn_addresses.num_ipv4_addresses++].s_addr = jn;
                                          }
                                      } else if (IN_CLASSB(addr_start.s_addr)) {
                                          if ((jh & 0xFF) && (jh & 0xFF) != 0xFF) {
                                              config_pP->pgw_config.pool_pdn_addresses.ipv4_addresses[config_pP->pgw_config.pool_pdn_addresses.num_ipv4_addresses++].s_addr = jn;
                                          }
                                      } else if (IN_CLASSC(addr_start.s_addr)) {
                                          if ((jh & 0xFF) && (jh & 0xFF) != 0xFF) {
                                              config_pP->pgw_config.pool_pdn_addresses.ipv4_addresses[config_pP->pgw_config.pool_pdn_addresses.num_ipv4_addresses++].s_addr = jn;
                                          }
                                      } else {
                                          printf("ERROR ON ADDRESS CLASS %d.%d.%d.%d\n", NIPADDR(jn));
                                      }
                                  }
                              }
                          }
                      } else {
                          DevAssert(PGW_MAX_ALLOCATED_PDN_ADDRESSES > config_pP->pgw_config.pool_pdn_addresses.num_ipv4_addresses);
                          memcpy (&addr_start, buf_in_addr, sizeof(struct in_addr));
                          config_pP->pgw_config.pool_pdn_addresses.ipv4_addresses[config_pP->pgw_config.pool_pdn_addresses.num_ipv4_addresses++].s_addr = addr_start.s_addr;
                      }
                  }
              }
          }
          sub2setting = config_setting_get_member (subsetting, PGW_CONFIG_STRING_IPV6_ADDRESS_LIST);
          if(sub2setting != NULL) {
              num     = config_setting_length(sub2setting);
              for (i = 0; i < num; i++) {
                  astring = config_setting_get_string_elem(sub2setting,i);
                  if (astring != NULL) {
                      trim(astring, strlen(astring)+1);
                      if (inet_pton(AF_INET6, astring, buf_in6_addr) < 1) {
                          // failure, test if there is a range specified in the string
                          atoken = strtok(astring, PGW_CONFIG_STRING_IPV6_PREFIX_DELIMITER);
                          if (inet_pton(AF_INET6, astring, buf_in6_addr) == 1) {
                              atoken2 = strtok(NULL, PGW_CONFIG_STRING_IPV6_PREFIX_DELIMITER);
                              prefix_mask = atoi(atoken2);
                              // arbitrary values
                              DevAssert((prefix_mask < 128) && (prefix_mask >= 64));

                              memcpy (&addr6_start, buf_in6_addr, sizeof(struct in6_addr));
                              memcpy (&addr6_mask,  buf_in6_addr, sizeof(struct in6_addr));
                              sgw_ipv6_mask_in6_addr(&addr6_mask, prefix_mask);

                              if (memcmp(&addr6_start, &addr6_mask, sizeof(struct in6_addr)) != 0) {
                                  AssertFatal(0, "BAD IPV6 ADDR CONFIG/MASK PAIRING %s/%d\n", astring, prefix_mask);
                              }

                              counter64 = 0xFFFFFFFFFFFFFFFF >> prefix_mask; // address Prefix_mask/0..0 not valid
                              do {
                                  addr6_start.s6_addr32[3] = addr6_start.s6_addr32[3] + htonl(1);
                                  if (addr6_start.s6_addr32[3] == 0) {
                                      addr6_start.s6_addr32[2] = addr6_start.s6_addr32[2] + htonl(1);
                                      if (addr6_start.s6_addr32[2] == 0) {
                                          // should not happen since mask is no less than 64
                                          addr6_start.s6_addr32[1] = addr6_start.s6_addr32[1] + htonl(1);
                                          if (addr6_start.s6_addr32[1] == 0) {
                                              addr6_start.s6_addr32[0] = addr6_start.s6_addr32[0] + htonl(1);
                                          }
                                      }
                                  }
                                  memcpy (&config_pP->pgw_config.pool_pdn_addresses.ipv6_addresses[config_pP->pgw_config.pool_pdn_addresses.num_ipv6_addresses++],
                                          &addr6_start,
                                          sizeof(struct in6_addr));
                                  counter64 = counter64 - 1;
                              } while (counter64 > 0);
                          }
                      } else {
Beispiel #6
0
void
copy(int prompt, FILE *fin)
{
	FILE *fout, *f;
	char s[200], t[200], s1[200], *r, *tod;
	char nm[100];
	int *p;
	time_t tval;
	int nmatch = 0;

	if (subdir[0] == 0)
		snprintf(subdir, sizeof subdir, "%s/%s", _PATH_LLIB, sname);
	for (;;) {
		if (pgets(s, sizeof s, prompt, fin) == 0) {
			if (fin == stdin) {
				/* fprintf(stderr, "Don't type control-D\n"); */
				/* this didn't work out very well */
				wrapup(1);	/* ian */
				continue;
			} else
				break;
		}
		trim(s);
		/* change the sequence %s to lesson directory */
		/* if needed */
		for (r = s; *r; r++)
			if (*r == '%') {
				snprintf(s1, sizeof s1, s,
				    subdir, subdir, subdir);
				strlcpy(s, s1, sizeof s);
				break;
			}
		r = wordb(s, t);
		p = action(t);
		/* some actions done only once per script */
		if (p && *p == ONCE) {
			if (wrong) {	/* we are on 2nd time */
				scopy(fin, NULL);
				continue;
			}
			strlcpy(s, r, sizeof s);
			r = wordb(s, t);
			p = action(t);
		}
		if (p == 0) {
			if (comfile >= 0) {
				write(comfile, s, strlen(s));
				write(comfile, "\n", 1);
			}
			else {
				signal(SIGINT, SIG_IGN);
				status = mysys(s);
				signal(SIGINT, signal_intrpt);
			}
			if (incopy) {
				fprintf(incopy, "%s\n", s);
				strlcpy(last, s, sizeof last);
			}
			continue;
		}
		switch (*p) {
		case READY:
			if (incopy && r) {
				fprintf(incopy, "%s\n", r);
				strlcpy(last, r, sizeof last);
			}
			return;
		case PRINT:
			if (wrong)
				scopy(fin, NULL);	/* don't repeat msg */
			else if (r)
				list(r);
			else
				scopy(fin, stdout);
			break;
		case NOP:
			break;
		case MATCH:
			if (nmatch > 0)	/* we have already passed */
				scopy(fin, NULL);
			/* did we pass this time? */
			else if ((status = strcmp(r, last)) == 0) {
				nmatch++;
				scopy(fin, stdout);
			} else
				scopy(fin, NULL);
			break;
		case BAD:
			if (strcmp(r, last) == 0)
				scopy(fin, stdout);
			else
				scopy(fin, NULL);
			break;
		case SUCCEED:
			scopy(fin, (status == 0) ? stdout : NULL);
			break;
		case FAIL:
			scopy(fin, (status != 0) ? stdout : NULL);
			break;
		case CREATE:
			fout = fopen(r, "w");
			scopy(fin, fout);
			fclose(fout);
			break;
		case CMP:
			status = cmp(r);	/* contains two file names */
			break;
		case MV:
			snprintf(nm, sizeof nm, "%s/L%s.%s", subdir, todo, r);
			fcopy(r, nm);
			break;
		case USER:
		case NEXT:
			more = 1;
			return;
		case COPYIN:
			incopy = fopen(".copy", "w");
			break;
		case UNCOPIN:
			fclose(incopy);
			incopy = NULL;
			break;
		case COPYOUT:
			maktee();
			break;
		case UNCOPOUT:
			untee();
			break;
		case PIPE:
			comfile = makpipe();
			break;
		case UNPIPE:
			close(comfile);
			wait(0);
			comfile = -1;
			break;
		case YES:
		case NO:
			if (incopy) {
				fprintf(incopy, "%s\n", s);
				strlcpy(last, s, sizeof last);
			}
			return;
		case WHERE:
			printf("You are in lesson %s\n", todo);
			fflush(stdout);
			break;
		case BYE:
			more = 0;
			return;
		case CHDIR:
			printf("cd not allowed\n");
			fflush(stdout);
			break;
		case LEARN:
			printf("You are already in learn.\n");
			fflush(stdout);
			break;
		case LOG:
			if (!logging)
				break;
			if (logfile[0] == 0) {
				snprintf(logfile, sizeof logfile,
				    "%s/log/%s", direct, sname);
			}
			f = fopen((r ? r : logfile), "a");
			if (f == NULL)
				break;
			time(&tval);
			tod = ctime(&tval);
			tod[24] = 0;
			fprintf(f, "%s L%-6s %s %2d %s\n", tod,
			    todo, status? "fail" : "pass", speed, pwline);
			fclose(f);
			break;
		}
	}
	return;
}
Beispiel #7
0
void
selunit(void)
{
	char fnam[1024], s[1024];
	static char dobuff[50];
	char posslev[20][20];
	int diff[20], i, k, m, n, best, alts;
	FILE *f;
	char zb[200];
	static char saved[20];

	while (ask) {
		printf("What lesson? ");
		fflush(stdout);
		if (fgets(dobuff, sizeof dobuff, stdin) == NULL)
			errx(1, "could not read input");
		trim(dobuff);
		if (strcmp(dobuff, "bye") == 0)
			wrapup(0);
		level = todo = dobuff;
		snprintf(s, sizeof s, "%s/%s/L%s", _PATH_LLIB, sname, dobuff);
		if (access(s, R_OK) == 0)
			return;
		printf("no such lesson\n");
	}
	alts = 0;
retry:
	f = scrin;
	if (f == NULL) {
		snprintf(fnam, sizeof fnam, "%s/%s/L%s",
		    _PATH_LLIB, sname, level);
		f = fopen(fnam, "r");
		if (f == NULL) {
			fprintf(stderr, "No script for lesson %s.\n", level);
			err(1, "%s", fnam);
			wrapup(1);
		}
		while (fgets(zb, sizeof zb, f)) {
			trim(zb);
			if (strcmp(zb, "#next") == 0)
				break;
		}
	}
	if (feof(f)) {
		printf("Congratulations; you have finished this sequence.\n");
		fflush(stdout);
		todo = 0;
		return;
	}
	for (i = 0; fgets(s, 50, f); i++)
		sscanf(s, "%s %d", posslev[i], &diff[i]);
	best = -1;
	/*
	 * cycle through lessons from random start
	 * first try the current place, failing that back up to
	 * last place there are untried alternatives (but only one backup)
	 */
	n = arc4random_uniform(077777) % i;
	for (k = 0; k < i; k++) {
		m = (n + k) % i;
		if (already(posslev[m]))
			continue;
		if (best < 0)
			best = m;
		/* real alternatives */
		alts++;
		if (abs(diff[m] - speed) < abs(diff[best] - speed))
			best = m;
	}
	if (best < 0 && nsave) {
		nsave--;
		strlcpy(level, saved, sizeof level);
		goto retry;
	}
	if (best < 0) {
		/* lessons exhausted or missing */
		printf("Sorry, there are no other lessons at this stage.\n");
		printf("See someone for help.\n");
		fflush(stdout);
		todo = 0;
		return;
	}
	strlcpy(dobuff, posslev[best], sizeof dobuff);
	if (alts > 1) {
		nsave = 1;
		strlcpy(saved, level, sizeof saved);
	}
	todo = dobuff;
	fclose(f);
}
string
NancyBot::askNancy(string msg_input)
{
	string msg_out = "PCManX-NancyBot";  // init msg_out
	if( (BOT_RUN_LEVEL & USE_TEACH )&& (BOT_RUN_LEVEL & USE_AUTO_LEARN))
	{
		unsigned int get_here;
		if( (get_here = msg_input.find_first_of('=')) != string::npos ) // found
		{
			string str_first = msg_input.substr(0,get_here);
			string str_second = msg_input.substr(get_here+1);
			str_first = trim(str_first);
			str_second = trim(str_second);
			if(!(str_first.empty() || str_second.empty()))
			{
				pMyMsgData->learning(str_first, str_second);
				return "Got it!";
			}
		}
	}
	if (BOT_RUN_LEVEL & USE_USER_DEFINED_USAGES)
	{
		unsigned int get_here;
		if( (get_here = msg_input.find_first_of('|')) != string::npos ) // found
		{
			string str_first = msg_input.substr(0,get_here);
			string str_second = msg_input.substr(get_here+1);
			str_first = trim(str_first);
			str_second = trim(str_second);
			if(!(str_first.empty() || str_second.empty()))
			{
				if(pMyMsgData->getUserDefinedUsages(str_first, str_second, msg_out ))
					return msg_out;
			}
		}
	}
	BOT_STATUS = 0;
	add_to_unknow = true;
	string unknow_msg;

	if(level__add_to_unknow_msg_changed)
	{
		pMyMsgData->setLevel__AddToUnknowMsg(LEVEL__ADD_TO_UNKNOW_MSG);
		level__add_to_unknow_msg_changed = false;
	}
	if(level__re_learning_changed)
	{
		pMyMsgData->setLevel__ReLearning(LEVEL__RE_LEARNING);
		level__re_learning_changed = false;
	}
	
	if(just_asked) // AUTO_LEARN
	{
		pMyMsgData->learning(just_asked_unknow_msg, msg_input);
		just_asked = false;
		add_to_unknow = false;
	}
	
	if( BOT_RUN_LEVEL & USE_AUTO_LEARN)
	{
		if( (unsigned int) (rand()%100 ) < LEVEL__ASK_UNKNOW_MSG )
			BOT_STATUS = 3; // Auto learn;
		if(BOT_STATUS == 3)
		{
			if(pMyMsgData->getSpecialMsg(BOT_STATUS, msg_out ) == 0){
				// should not here
			}
			else
			{
				// get a msg that bot unknow to ask
				
				if(pMyMsgData->getUnknowMsgToAsk(unknow_msg)) // got it
				{
					replaceString(msg_out, ask_flag, unknow_msg);
					just_asked = true;
					just_asked_unknow_msg = unknow_msg;
					
					if( BOT_RUN_LEVEL & USE_LOG )
					{
						writeLog(msg_input, msg_out);
					}
					return msg_out;	
				}
			}
		} // end (BOT_STATUS = 3)
	} // end (USE_AUTO_LEARN)
	
	

	if( BOT_RUN_LEVEL & USE_ANGRY )
	{
		if( checkMsgRepeat(msg_input) > 3)
		{
			BOT_STATUS = 1;   // anacy is angry
			if(pMyMsgData->getSpecialMsg(BOT_STATUS, msg_out ) == 0){
				//should not run here
			}
		}
	}
		
	if( (BOT_RUN_LEVEL & USE_BASE ) && BOT_STATUS != 1 ) // use_base and nancy not angry
	{
		if(pMyMsgData->getCommonMsg(msg_input, msg_out, add_to_unknow) == 0) // not found
		{
			if(BOT_RUN_LEVEL & USE_UNKNOW)
			{
				BOT_STATUS = 2; // BOT UNKNOW
			}
		}
		if(BOT_STATUS == 2) // UNKNOW MSG
		{
			pMyMsgData->getSpecialMsg(BOT_STATUS, msg_out );
			//if( BOT_RUN_LEVEL & USE_AUTO_LEARN)
			//	pMyMsgData->addUnknowMsgToAsk(msg_input);
		}
	}
	
	if( BOT_RUN_LEVEL & USE_LOG )
	{
		writeLog(msg_input, msg_out);
	}
	
	return msg_out;
}
SimulateOptions::SimulateOptions(const std::string &fname)
:
steps(50),
start(0),
duration(5),
absolute(MaxAbsolute),
relative(MaxRelative),
flags(0),
integrator(CVODE),
integratorOpt(0)
{

    if(!fname.size())
    {
        Log(lError)<<"Empty file name for setings file";
    }
    else
    {
        map<string, string> settings;
        map<string, string>::iterator it;
        //Read each line in the settings file
        vector<string> lines = getLinesInFile(fname);
        for(int i = 0; i < lines.size(); i++)
        {
            vector<string> line = splitString(lines[i], ":");
            if(line.size() == 2)
            {
                settings.insert( pair<string, string>(line[0], line[1]));
            }
            else
            {
                Log(lDebug2)<<"Empty line in settings file: "<<lines[i];
            }
        }

        Log(lDebug3)<<"Settings File =============";
        for (it = settings.begin() ; it != settings.end(); it++ )
        {
            Log(lDebug) << (*it).first << " => " << (*it).second;
        }
        Log(lDebug)<<"===========================";

        //Assign values
        it = settings.find("start");
        start = (it != settings.end())   ? toDouble((*it).second) : 0;

        it = settings.find("duration");
        duration = (it != settings.end())    ? toDouble((*it).second) : 0;

        it = settings.find("steps");
        steps = (it != settings.end())       ? toInt((*it).second) : 50;

        it = settings.find("absolute");
        absolute = (it != settings.end())    ? toDouble((*it).second) : 1.e-7;

        it = settings.find("relative");
        relative = (it != settings.end())    ? toDouble((*it).second) : 1.e-4;

        it = settings.find("variables");
        if(it != settings.end())
        {
            vector<string> vars = splitString((*it).second, ",");
            for(int i=0; i < vars.size(); i++)
            {
                variables.push_back(trim(vars[i]));
            }
        }

        it = settings.find("amount");
        if(it != settings.end())
        {
            vector<string> vars = splitString((*it).second, ",");
            for(int i=0; i < vars.size(); i++)
            {
                string rec = trim(vars[i]);
                if(rec.size())
                {
                    amounts.push_back(rec);
                }
            }
        }

        it = settings.find("concentration");
        if(it != settings.end())
        {
            vector<string> vars = splitString((*it).second, ",");
            for(int i=0; i < vars.size(); i++)
            {
                string rec = trim(vars[i]);
                if(rec.size())
                {
                    concentrations.push_back(rec);
                }
            }
        }
    }

    if (absolute > MaxAbsolute) {
        absolute = MaxAbsolute;
    }

    if (relative > MaxRelative) {
        relative = MaxRelative;
    }
}
Beispiel #10
0
MSNServerMessage::~MSNServerMessage()
{
    KEY_MAP values;
    QString msg = QString::fromUtf8(m_msg.c_str());
    for (;!msg.isEmpty();){
        QString line;
        int n = msg.find("\r\n");
        if (n >= 0){
            line = msg.left(n);
            msg  = msg.mid(n + 2);
        }else{
            line = msg;
            msg  = "";
        }
        n = line.find(":");
        if (n < 0)
            continue;
        values.insert(KEY_MAP::value_type(line.left(n), trim(line.mid(n + 1))));
    }
    KEY_MAP::iterator it = values.find("ClientIP");
    if (it != values.end())
        set_ip(&m_client->data.owner.IP, inet_addr((*it).second.latin1()));
    it = values.find("Content-Type");
    if (it != values.end()){
        QString content_type = (*it).second;
        content_type = getToken(content_type, ';');
        if (content_type == "text/x-msmsgsinitialemailnotification"){
            m_client->m_init_mail = "";
            it = values.find("Post-URL");
            if (it != values.end())
                m_client->m_init_mail = (*it).second.latin1();
            it = values.find("Inbox-URL");
            if (it != values.end())
                m_client->m_init_mail += (*it).second.latin1();
            it = values.find("Inbox-Unread");
            if (it == values.end())
                return;
            unsigned nUnread = (*it).second.toUInt();
            if (nUnread){
                clientErrorData data;
                data.client		= m_client;
                data.err_str	= "%1";
                data.options	= NULL;
                data.args		= strdup(i18n("You have %n unread message", "You have %n unread messages", nUnread).utf8());
                data.code		= 0;
                data.flags		= ERR_INFO;
                data.id			= static_cast<MSNPlugin*>(m_client->protocol()->plugin())->MSNInitMail;
                Event e(EventShowError, &data);
                e.process();
            }
        }
        if (content_type == "text/x-msmsgsemailnotification"){
            m_client->m_new_mail = "";
            it = values.find("Post-URL");
            if (it != values.end())
                m_client->m_new_mail = (*it).second.latin1();
            it = values.find("Message-URL");
            if (it != values.end())
                m_client->m_new_mail += (*it).second.latin1();
            QString from;
            it = values.find("From-Addr");
            if (it != values.end())
                from = (*it).second;
            QString msg = i18n("You have new mail");
            if (!from.isEmpty())
                msg = i18n("%1 from %2") .arg(msg) .arg(from);
            clientErrorData data;
            data.client		= m_client;
            data.err_str	= "%1";
            data.options	= NULL;
            data.args		= strdup(msg.utf8());
            data.code		= 0;
            data.flags		= ERR_INFO;
            data.id			= static_cast<MSNPlugin*>(m_client->protocol()->plugin())->MSNNewMail;
            Event e(EventShowError, &data);
            e.process();
        }
    }
}
Beispiel #11
0
void on_xiphos_web_listener_ready_callback (SoupSession *session, SoupMessage *msg, gpointer user_data)
{
	if (SOUP_STATUS_IS_SUCCESSFUL (msg->status_code)) {
		// Get the response body.
		string body (msg->response_body->data);
		body = trim (body);
		// Log it.
    //printf ("%s\n", body.c_str());
    //fflush (stdout);
    ParseLine parseline (body);
    if (parseline.lines.size() >= 3) {
      // It retrieves the message ID and uses this to ask for a higher ID next poll.
      // Update GUI.
      last_message_id = parseline.lines[0];
      gtk_label_set_text (GTK_LABEL (label_id), last_message_id.c_str());
      string command = parseline.lines[1];
      gtk_label_set_text (GTK_LABEL (label_command), command.c_str());
      string body = parseline.lines[2];
      gtk_label_set_text (GTK_LABEL (label_body), body.c_str());
      // Handle "quit" command.
      if (command == "quit") {
        gtk_main_quit ();
      }
      // Handle "focus" command.
      if (command == "focus") {
        Parse parse (body, false, ".");
        if (parse.words.size() == 3) {
          string book;
          switch (convert_to_int (parse.words[0])) {
            case 1: book = "Gen"; break;
            case 2: book = "Exod"; break;
            case 3: book = "Lev"; break;
            case 4: book = "Num"; break;
            case 5: book = "Deut"; break;
            case 6: book = "Josh"; break;
            case 7: book = "Judg"; break;
            case 8: book = "Ruth"; break;
            case 9: book = "1Sam"; break;
            case 10: book = "2Sam"; break;
            case 11: book = "1Kgs"; break;
            case 12: book = "2Kgs"; break;
            case 13: book = "1Chr"; break;
            case 14: book = "2Chr"; break;
            case 15: book = "Ezra"; break;
            case 16: book = "Neh"; break;
            case 17: book = "Esth"; break;
            case 18: book = "Job"; break;
            case 19: book = "Ps"; break;
            case 20: book = "Prov"; break;
            case 21: book = "Eccl"; break;
            case 22: book = "Song"; break;
            case 23: book = "Isa"; break;
            case 24: book = "Jer"; break;
            case 25: book = "Lam"; break;
            case 26: book = "Ezek"; break;
            case 27: book = "Dan"; break;
            case 28: book = "Hos"; break;
            case 29: book = "Joel"; break;
            case 30: book = "Amos"; break;
            case 31: book = "Obad"; break;
            case 32: book = "Jonah"; break;
            case 33: book = "Mic"; break;
            case 34: book = "Nah"; break;
            case 35: book = "Hab"; break;
            case 36: book = "Zeph"; break;
            case 37: book = "Hag"; break;
            case 38: book = "Zech"; break;
            case 39: book = "Mal"; break;
            case 40: book = "Matt"; break;
            case 41: book = "Mark"; break;
            case 42: book = "Luke"; break;
            case 43: book = "John"; break;
            case 44: book = "Acts"; break;
            case 45: book = "Rom"; break;
            case 46: book = "1Cor"; break;
            case 47: book = "2Cor"; break;
            case 48: book = "Gal"; break;
            case 49: book = "Eph"; break;
            case 50: book = "Phil"; break;
            case 51: book = "Col"; break;
            case 52: book = "1Thess"; break;
            case 53: book = "2Thess"; break;
            case 54: book = "1Tim"; break;
            case 55: book = "2Tim"; break;
            case 56: book = "Titus"; break;
            case 57: book = "Phlm"; break;
            case 58: book = "Heb"; break;
            case 59: book = "Jas"; break;
            case 60: book = "1Pet"; break;
            case 61: book = "2Pet"; break;
            case 62: book = "1John"; break;
            case 63: book = "2John"; break;
            case 64: book = "3John"; break;
            case 65: book = "Jude"; break;
            case 66: book = "Rev"; break;
          }
          if (!book.empty()) {
            string reference = "sword://" + book + "." + parse.words[1] + "." + parse.words[2];
            send_to_xiphos (xiphos_dbus_object (), xiphos_dbus_interface (), "setCurrentReference", reference);
            reference.insert (0, "setCurrentReference ");
            gtk_label_set_text (GTK_LABEL (label_xiphos), reference.c_str());
          }
        }
      }
    } 
	} else {
		// If the message was cancelled, do not start it again, just quit.
		if (msg->status_code == 1) {
		  return;
		}
    // If it needs to quit, just quit.
    if (quit) return;
    // Handle error.
		printf ("Xiphos web listener failure, code: %d, reason: %s\n", msg->status_code, msg->reason_phrase);
    fflush (stdout);
    for (unsigned int i = 0; i < 10; i++) {
      while (gtk_events_pending()) gtk_main_iteration();
  		g_usleep (100000);
    }
	}
	g_usleep (100000);
	start_xiphos_web_listener ();
}
Beispiel #12
0
void PathInfo::Update(const float destX, const float destY, const float destZ)
{
    float x, y, z;

    // update start and end
    m_sourceObject->GetPosition(x, y, z);
    setStartPosition(x, y, z);
    setEndPosition(destX, destY, destZ);

    // make sure navMesh works
    if(!m_navMesh)
    {
        m_sourceObject->GetPosition(x, y, z);
        m_navMesh = m_sourceObject->GetMap()->GetNavMesh();

        if(!m_navMesh)
        {
            // can't pathfind if navmesh doesn't exist
            shortcut();
            return;
        }
    }

    if(!m_pathPolyRefs)
    {
        // path was not built before, most likely because navmesh wasn't working
        // start from scratch, then return
        Build();
        return;
    }

    // should be safe to update path now

    bool startOffPath = false;
    bool endOffPath = false;

    // find start and end poly
    // navMesh.findNearestPoly is expensive, so first we check just the current path
    getStartPosition(x, y, z);
    dtPolyRef startPoly = getPathPolyByPosition(x, y, z);
    getEndPosition(x, y, z);
    dtPolyRef endPoly = getPathPolyByPosition(x, y, z);

    if(startPoly != 0 && endPoly != 0)
        trim(startPoly, endPoly);
    else
    {
        // start or end is off the path, need to find the polygon

        float extents[3] = {2.f, 4.f, 2.f};      // bounds of poly search area
        dtQueryFilter filter = dtQueryFilter();     // filter for poly search

        if(!startPoly)
        {
            getStartPosition(x, y, z);
            float startPos[3] = {y, z, x};
            startOffPath = true;
            startPoly = m_navMesh->findNearestPoly(startPos, extents, &filter, 0);
        }
        if(!endPoly)
        {
            getEndPosition(x, y, z);
            float endPos[3] = {y, z, x};
            endOffPath = true;
            endPoly = m_navMesh->findNearestPoly(endPos, extents, &filter, 0);
        }

        if(startPoly == 0 || endPoly == 0)
        {
            // source or dest not near navmesh polygons:
            // flying, falling, swimming, or navmesh has a hole

            // ignore obstacles/terrain is better than giving up
            // PATHFIND TODO: prevent walking/swimming mobs from flying into the air
            shortcut();
            return;
        }
    }

    if(startPoly == endPoly)
    {
        // start and end are on same polygon
        // just need to move in straight line

        // PATHFIND TODO: prevent walking/swimming mobs from flying into the air

        clear();
        m_pathPolyRefs = new dtPolyRef[1];
        m_pathPolyRefs[0] = startPoly;
        m_length = 1;
        getEndPosition(x, y, z);
        setNextPosition(x, y, z);
        m_type = PathType(m_type | PATHFIND_NORMAL);
        return;
    }

    if(startOffPath)
    {
        bool adjacent = false;
        int i;
        for(i = 0; i < DT_VERTS_PER_POLYGON; ++i)
            if(startPoly == m_navMesh->getPolyByRef(m_pathPolyRefs[0])->neis[i])
            {
                adjacent = true;
                break;
            }

        if(adjacent)
        {
            // startPoly is adjacent to the path, we can add it to the start of the path
            // 50th poly will fall off of path, shouldn't be an issue because most paths aren't that long
            m_length = m_length < MAX_PATH_LENGTH ? m_length + 1 : m_length;
            dtPolyRef* temp = new dtPolyRef[m_length];
            temp[0] = startPoly;

            for(i = 1; i < m_length; ++i)
                temp[i] = m_pathPolyRefs[i - 1];

            delete [] m_pathPolyRefs;
            m_pathPolyRefs = temp;
        }
        else
        {
            // waste of time to optimize, just find brand new path
            Build(startPoly, endPoly);
            return;
        }
    }

    if(endOffPath)
    {
        bool adjacent = false;
        int i;
        for(i = 0; i < DT_VERTS_PER_POLYGON; ++i)
            if(startPoly == m_navMesh->getPolyByRef(m_pathPolyRefs[0])->neis[i])
            {
                adjacent = true;
                break;
            }

        if(adjacent)
        {
            if(m_length < MAX_PATH_LENGTH)
            {
                // endPoly is adjacent to the path, and we have enough room to add it to the end
                dtPolyRef* temp = new dtPolyRef[m_length + 1];
                for(i = 0; i < m_length; ++i)
                    temp[i] = m_pathPolyRefs[i];

                temp[i] = endPoly;

                delete [] m_pathPolyRefs;
                m_pathPolyRefs = temp;
            }
            //else
            //    ;   // endPoly is adjacent to the path, we just don't have room to store it
        }
        else
        {
            // waste of time to optimize, just find brand new path
            Build(startPoly, endPoly);
            return;
        }
    }

    updateNextPosition();
}
Beispiel #13
0
int main(int argc, char* argv[], char *envp[]) {
   
    // If you use execvp() without a fork, it'll take over the main system.
    // This is why you need to fork a process, then call execvp()

    list<char**> arguments;
    list<char*> connectors;

    // Grabs host name
    char* login;
    char host[127];

    login = getlogin();
    if (gethostname(host, 127) != 0) {
        perror("failed to gethostname");
        exit(EXIT_FAILURE);
    }
   
    string command = "";

    printInfo(login, host);
    cout << "$ ";
    while (getline(cin, command)) {

        while (command.length() == 0) {
            printInfo(login, host);
            cout << "$ ";
            getline(cin,command);
        }

        char* cstrcmd = '\0';
        list<char*> tokens;
        list<char*> data;

        cstrcmd = new char[command.size() + 1]; 
        // This data is universal. It will be used until deallocated.

        strcpy(cstrcmd, command.c_str());
        data.push_back(cstrcmd);
        // This is to hold locations of the data to deallocate later
        
        tokens = parse(cstrcmd);

        /*if (isDblConnector(tokens.back())) {
            tokens.pop_back();
            cout << "Terminated without command -- ignoring leading connector."
                 << endl;
        }*/

        while (isDblConnector(tokens.back())) { 
            // If the stupid user ended with a connector
            list<char*> tmpCmds;

            cout << "> ";
            getline(cin, command);

            cstrcmd = new char[command.size() + 1];
            strcpy(cstrcmd, command.c_str());
            data.push_back(cstrcmd);

            tmpCmds = parse(cstrcmd);
            while (!tmpCmds.empty()) {
                tokens.push_back(tmpCmds.front());
                tmpCmds.pop_front();
            }
        }

        // Creating the two argument and connector lists
        int last; // There definitely has to be a better way to do this.
        char* cmd[128][256]; 
        // cmd is a list of pointers to the beginning of each token of the 
        // universal data
        int n = 0;
        for (int i = 0; !tokens.empty(); ++i) {
            cutEndSpaces(tokens.front());
            if (isQuoteBegin(tokens.front())) { // Quote parsing
                trim(tokens.front());
                while (!isQuoteEnd(tokens.front())) { 
                // Input clause should prevent infinite loop
                    cmd[n][i] = tokens.front();
                    tokens.pop_front();
                    ++i;
                }
                truncate(tokens.front()); // Cuts off the quotation mark
                if (isAttached(tokens.front())) { // Same clause as below 
                    truncate(tokens.front()); 
                    // This one should cut off the semicolon 
                    cmd[n][i] = tokens.front(); 
                    tokens.front() = new char[1]; 
                    data.push_back(tokens.front());
                    strcpy(tokens.front(), ";\0"); 
                    tokens.push_front(NULL); // Phony Value
                }
                else {
                    cmd[n][i] = tokens.front(); // Throws it into the list
                }
                ++i;
            }
            else if (isComment(tokens.front())) break;
            else if (isConnector(tokens.front())) {
                if (isAttached(tokens.front())) { 
                    // Pesky semicolons being attached...
                    truncate(tokens.front()); 
                    // Cuts out the semicolon, leaves rest of stack 
                    cmd[n][i] = tokens.front(); 
                    tokens.front() = new char[1]; 
                    data.push_back(tokens.front());
                    strcpy(tokens.front(), ";\0"); 
                    ++i; // Progressing to the next value of cmd
                }
                cmd[n][i] = '\0'; // Null terminating cmd
                arguments.push_back(cmd[n]); 
                // If we ran into a connector, means we have a full argument.
                connectors.push_back(tokens.front());
              
                ++n;
                i = -1; // Reset argc
            }
            else if (isTestBegin(tokens.front()) && i == 0) { 
                // Essentially converting "[" to "test"
                cmd[n][0] = new char[4];
                strcpy(cmd[n][0], "test");
                data.push_back(cmd[n][0]); // potential glibc
                tokens.pop_front(); // Killing "[" from tokens.
                for (i = 1; !isTestEnd(tokens.front()); ++i) {
                    cmd[n][i] = tokens.front();
                    tokens.pop_front();
                }
            }
            else {
                cmd[n][i] = tokens.front(); 
                // Assigns cmd[i] to pointer at tokens.front(). 
                // Tokens contains cstrings
            }
            tokens.pop_front(); // Should take care of "]"
            last = i;
        }
        if (cmd[n][0] != '\0') { // Push in the last argument
            cmd[n][last + 1] = '\0';
            arguments.push_back(cmd[n]);
        }

        Connector* head = NULL;
        head = buildTree(arguments, connectors);
        head->run();

        while (!connectors.empty()) connectors.pop_front();
        while (!arguments.empty()) arguments.pop_front(); 
        // If, for some reason, these two are not empty.
        while (!data.empty()) {
            delete[] data.front();
            // This deallocates the entire command string.
            data.pop_front();
        }
        head->destroyBranch(head);
        printInfo(login, host);
        cout << "$ ";
    }
    return 0;
}
bool LexicsCutter::Read_Letter_Analogs(std::string& FileName)
{
    FILE *ma_file;
    char line[1024];
    unsigned int pos;
    std::string line_s;
    std::string lchar;
    std::string lanalog;

    ma_file = fopen(FileName.c_str(), "rb");

    if (!ma_file)
    {
        sLog.outError("Chat lexics cutter disabled. Reason: LexicsCutterAnalogsFile file does not exist in the server directory.");
        return false;
    }

    while (!feof(ma_file))
    {
        line[0] = 0x0;
        fgets(line, 1020, ma_file);

        // check for UTF8 prefix and comments
        if (strlen(line) >= 3)
        {
            if (line[0] == '\xEF' && line[1] == '\xBB' && line[2] == '\xBF')
            {
                strncpy(&line[0], &line[3], strlen(line) - 3);
            }
        }

        if (strlen(line) >= 2)
        {
            if (line[0] == '/' && line[1] == '/') continue;
        }

        // check for empty string
        line_s = line;
        line_s = trim(line_s, "\x0A\x0D\x20");
        if (line_s == "") continue;

        // process line without CR/LF
        line_s = line;
        line_s = trim(line_s, "\x0A\x0D");

        pos = 0;
        if (ReadUTF8(line_s, lchar, pos))
        {
            // create analogs vector
            LC_AnalogVector av;
            while (ReadUTF8(line_s, lanalog, pos))
            {
                av.push_back(lanalog);
            }

            // store vector in hash map
            AnalogMap[lchar] = av;
        }
    }

    fclose(ma_file);

    return true;
}
Beispiel #15
0
int skinRead( char * dname )
{
 unsigned char   tmp[255];
 unsigned char * ptmp;
 unsigned char   command[32];
 unsigned char   param[256];
 int             c,i;

 setname( skinDirInHome,dname );
 if ( ( skinFile = fopen( fn,"rt" ) ) == NULL )
  {
   setname( skinMPlayerDir,dname );
   if ( ( skinFile = fopen( fn,"rt" ) ) == NULL )
    {
     setname( skinDirInHome_obsolete,dname );
     if ( ( skinFile = fopen( fn,"rt" ) ) == NULL )
      {
       setname( skinMPlayerDir_obsolete,dname );
       if ( ( skinFile = fopen( fn,"rt" ) ) == NULL )
        {
         setname( skinMPlayerDir,dname );
         mp_msg( MSGT_GPLAYER,MSGL_STATUS,MSGTR_SKIN_SkinFileNotFound,fn );
         return -1;
        }
      }
    }
  }

 mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"[skin] file: %s\n",fn );

 appInitStruct( skinAppMPlayer );

 linenumber=0;
 while (fgets(tmp, 255, skinFile))
  {
   linenumber++;

   c=tmp[ strlen( tmp ) - 1 ]; if ( c == '\n' || c == '\r' ) tmp[ strlen( tmp ) - 1 ]=0;
   c=tmp[ strlen( tmp ) - 1 ]; if ( c == '\n' || c == '\r' ) tmp[ strlen( tmp ) - 1 ]=0;
   for ( c=0;c<(int)strlen( tmp );c++ )
    if ( tmp[c] == ';' )
     {
      tmp[c]=0;
      break;
     }
   if ( strlen( tmp ) == 0 ) continue;
   ptmp=trimleft( tmp );
   if ( strlen( ptmp ) == 0 ) continue;
   ptmp=strswap( ptmp,'\t',' ' );
   ptmp=trim( ptmp );

   cutItem( ptmp,command,'=',0 ); cutItem( ptmp,param,'=',1 );
   strlower( command );
   for( i=0;i<ITEMS;i++ )
    if ( !strcmp( command,skinItem[i].name ) )
     if ( skinItem[i].func( param ) ) return -2;
  }
 if (linenumber == 0) {
   mp_msg(MSGT_GPLAYER, MSGL_FATAL, MSGTR_SKIN_SkinFileNotReadable, fn);
   return -1;
 }
 return 0;
}
Beispiel #16
0
void dlg_bridge_tm_callback(struct cell *t, int type, struct tmcb_params *ps)
{
	struct sip_msg *msg = NULL;
	dlg_transfer_ctx_t *dtc = NULL;
	struct dlg_cell *dlg = NULL;
	str s;
	str cseq;
	str empty = {"", 0};

	if(ps->param==NULL || *ps->param==0)
	{
		LM_DBG("message id not received\n");
		return;
	}
	dtc = *((dlg_transfer_ctx_t**)ps->param);
	if(dtc==NULL)
		return;
	LM_DBG("completed with status %d\n", ps->code);
	if(ps->code>=300)
		goto error;

	/* 2xx - build dialog/send refer */
	msg = ps->rpl;
	if(parse_headers(msg, HDR_EOH_F, 0) < 0) {
		LM_ERR("failed to parse the reply headers\n");
		goto error;
	}
	if((msg->cseq==NULL || parse_headers(msg,HDR_CSEQ_F,0)<0)
			|| msg->cseq==NULL || msg->cseq->parsed==NULL)
	{
			LM_ERR("bad sip message or missing CSeq hdr :-/\n");
			goto error;
	}
	cseq = (get_cseq(msg))->number;

	if((msg->to==NULL && parse_headers(msg, HDR_TO_F,0)<0) || msg->to==NULL)
	{
		LM_ERR("bad request or missing TO hdr\n");
		goto error;
	}
	if(parse_from_header(msg))
	{
		LM_ERR("bad request or missing FROM hdr\n");
		goto error;
	}
	if((msg->callid==NULL && parse_headers(msg,HDR_CALLID_F,0)<0)
			|| msg->callid==NULL){
		LM_ERR("bad request or missing CALLID hdr\n");
		goto error;
	}
	s = msg->callid->body;
	trim(&s);

	/* some sanity checks */
	if (s.len==0 || get_from(msg)->tag_value.len==0) {
		LM_ERR("invalid request -> callid (%d) or from TAG (%d) empty\n",
			s.len, get_from(msg)->tag_value.len);
		goto error;
	}

	dlg = build_new_dlg(&s /*callid*/, &(get_from(msg)->uri) /*from uri*/,
		&(get_to(msg)->uri) /*to uri*/,
		&(get_from(msg)->tag_value)/*from_tag*/,
		&(get_to(msg)->uri) /*use to as r-uri*/ );
	if (dlg==0) {
		LM_ERR("failed to create new dialog\n");
		goto error;
	}
	dtc->dlg = dlg;
	if (dlg_set_leg_info(dlg, &(get_from(msg)->tag_value),
				&empty, &dlg_bridge_controller, &cseq, DLG_CALLER_LEG)!=0) {
		LM_ERR("dlg_set_leg_info failed\n");
		goto error;
	}

	if (populate_leg_info(dlg, msg, t, DLG_CALLEE_LEG,
			&(get_to(msg)->tag_value)) !=0)
	{
		LM_ERR("could not add further info to the dialog\n");
		shm_free(dlg);
		goto error;
	}

	if(dlg_refer_callee(dtc)!=0)
		goto error;
	return;

error:
	dlg_transfer_ctx_free(dtc);
	return;
}
Beispiel #17
0
static int pv_parse_mongodb_name(pv_spec_p sp, str *in)
{
	mongodbc_pv_t *rpv=NULL;
	str pvs;
	int i;

	if(in->s==NULL || in->len<=0)
		return -1;

	rpv = (mongodbc_pv_t*)pkg_malloc(sizeof(mongodbc_pv_t));
	if(rpv==NULL)
		return -1;

	memset(rpv, 0, sizeof(mongodbc_pv_t));

	pvs = *in;
	trim(&pvs);

	rpv->rname.s = pvs.s;
	for(i=0; i<pvs.len-2; i++)
	{
		if(isspace(pvs.s[i]) || pvs.s[i]=='=') {
			rpv->rname.len = i;
			break;
		}
	}
	rpv->rname.len = i;

	if(rpv->rname.len==0)
		goto error_var;

	while(i<pvs.len-2 && isspace(pvs.s[i]))
		i++;

	if(pvs.s[i]!='=')
		goto error_var;

	if(pvs.s[i+1]!='>')
		goto error_var;

	i += 2;
	while(i<pvs.len && isspace(pvs.s[i]))
		i++;

	if(i>=pvs.len)
		goto error_key;

	rpv->rkey.s   = pvs.s + i;
	rpv->rkey.len = pvs.len - i;

	if(rpv->rkey.len>=5 && strncmp(rpv->rkey.s, "value", 5)==0) {
		rpv->rkeyid = 1;
	} else if(rpv->rkey.len>=4 && strncmp(rpv->rkey.s, "type", 4)==0) {
		rpv->rkeyid = 0;
	} else if(rpv->rkey.len==4 && strncmp(rpv->rkey.s, "info", 4)==0) {
		rpv->rkeyid = 2;
	} else if(rpv->rkey.len==4 && strncmp(rpv->rkey.s, "size", 4)==0) {
		rpv->rkeyid = 3;
	} else {
		goto error_key;
	}

	sp->pvp.pvn.u.dname = (void*)rpv;
	sp->pvp.pvn.type = PV_NAME_OTHER;
	return 0;

error_var:
	LM_ERR("invalid var spec [%.*s]\n", in->len, in->s);
	pkg_free(rpv);
	return -1;

error_key:
	LM_ERR("invalid key spec in [%.*s]\n", in->len, in->s);
	pkg_free(rpv);
	return -1;
}
Beispiel #18
0
int32_t init_sidtab(void)
{
	FILE *fp = open_config_file(cs_sidt);
	if(!fp)
		{ return 1; }

	int32_t nr, nro, nrr;
	char *value, *token;
	if(!cs_malloc(&token, MAXLINESIZE))
		{ return 1; }
	struct s_sidtab *ptr;
	struct s_sidtab *sidtab = (struct s_sidtab *)0;

	for(nro = 0, ptr = cfg.sidtab; ptr; nro++)
	{
		struct s_sidtab *ptr_next;
		ptr_next = ptr->next;
		free_sidtab(ptr);
		ptr = ptr_next;
	}
	nr = 0;
	nrr = 0;
	while(fgets(token, MAXLINESIZE, fp))
	{
		int32_t l;
		if((l = strlen(trim(token))) < 3) { continue; }
		if((token[0] == '[') && (token[l - 1] == ']'))
		{
			token[l - 1] = 0;
			if(nr > MAX_SIDBITS)
			{
				fprintf(stderr, "Warning: Service No.%d - '%s' ignored. Max allowed Services %d\n", nr, strtolower(token + 1), MAX_SIDBITS);
				nr++;
				nrr++;
			}
			else
			{
				if(!cs_malloc(&ptr, sizeof(struct s_sidtab)))
				{
					NULLFREE(token);
					return (1);
				}
				if(sidtab)
					{ sidtab->next = ptr; }
				else
					{ cfg.sidtab = ptr; }
				sidtab = ptr;
				nr++;
				cs_strncpy(sidtab->label, strtolower(token + 1), sizeof(sidtab->label));
				continue;
			}
		}
		if(!sidtab) { continue; }
		if(!(value = strchr(token, '='))) { continue; }
		*value++ = '\0';
		chk_sidtab(trim(strtolower(token)), trim(strtolower(value)), sidtab);
	}
	NULLFREE(token);
	fclose(fp);

	show_sidtab(cfg.sidtab);
	++cfg_sidtab_generation;
	cs_log("services reloaded: %d services freed, %d services loaded, rejected %d", nro, nr, nrr);
	return (0);
}
Beispiel #19
0
void
selsub(int argc, char *argv[])
{
	char ans1[100], *cp;
	static char ans2[30];
	static char subname[20];

	if (argc > 1 && argv[1][0] == '-') {
		direct = argv[1] + 1;
		argc--;
		argv++;
	}
	chknam(direct);
	if (chdir(direct) != 0) {
		fprintf(stderr, "can't cd to %s\n", direct);
		exit(1);
	}
	sname = argc > 1 ? argv[1] : 0;
	if (argc > 2)
		strlcpy(level = ans2, argv[2], sizeof ans2);
	else
		level = 0;
	if (argc > 3 )
		speed = atoi(argv[3]);
	if (!sname) {
		printf("These are the available courses:\n");
		list("Linfo");
		printf("If you want more information about the courses,\n");
		printf("or if you have never used 'learn' before,\n");
		printf("type 'return'; otherwise type the name of\n");
		printf("the course you want, followed by 'return'.\n");
		fflush(stdout);
		if (fgets(sname = subname, sizeof subname, stdin) == NULL)
			errx(1, "could not read input");
		trim(sname);
		if (sname[0] == '\0') {
			list("Xinfo");
			do {
				printf("\nWhich subject?  ");
				fflush(stdout);
				if (fgets(sname = subname, sizeof subname,
				    stdin) == NULL)
					errx(1, "could not read input");
				trim(sname);
			} while (sname[0] == '\0');
		}
	}
	chknam(sname);
	if (!level) {
		printf("If you were in the middle of this subject\n");
		printf("and want to start where you left off, type\n");
		printf("the last lesson number the computer printed.\n");
		printf("To start at the beginning, just hit return.\n");
		fflush(stdout);
		if (fgets(ans2, sizeof ans2, stdin) == NULL)
			errx(1, "could not read input");
		trim(ans2);
		if (ans2[0] == 0)
			strlcpy(ans2, "0", sizeof ans2);
		for (cp = ans2; *cp; cp++) {
			if (*cp == '(' || *cp == ' ')
				*cp = 0;
		}
		level = ans2;
	}

	/* make new directory for user to play in */
	if ((playdir = mkdtemp(strdup("/tmp/plXXXXXX"))) == NULL ||
	     chdir(playdir) < 0) {
		fprintf(stderr, "Couldn't create playpen directory %s.\n",
		    playdir);
		fprintf(stderr, "Bye.\n");
		exit(1);
	}

	/*
	 * after this point, we have a working directory.
	 * have to call wrapup to clean up
	 */
	snprintf(ans1, sizeof ans1, "%s/%s/Init", direct, sname);
	if (access(ans1, R_OK) == 0) {
		snprintf(ans1, sizeof ans1, "%s/%s/Init %s",
		    direct, sname, level);
		if (system(ans1) != 0) {
			printf("Leaving learn.\n");
			wrapup(1);
		}
	}
	if (level[0] == '-')	/* no lesson names start with - */
		ask = 1;
	start(level);
}
Beispiel #20
0
int32_t init_provid(void)
{
	FILE *fp = open_config_file(cs_provid);
	if(!fp)
		{ return 0; }

	int32_t nr;
	char *payload, *saveptr1 = NULL, *token;
	if(!cs_malloc(&token, MAXLINESIZE))
		{ return 0; }
	struct s_provid *provid_ptr = NULL;
	struct s_provid *new_cfg_provid = NULL, *last_provid;

	nr = 0;
	while(fgets(token, MAXLINESIZE, fp))
	{
		int32_t i, l;
		struct s_provid *new_provid = NULL;
		char *tmp, *ptr1;
		
		tmp = trim(token);

		if(tmp[0] == '#') { continue; }
		if((l = strlen(tmp)) < 11) { continue; }
		if(!(payload = strchr(token, '|'))) { continue; }

		*payload++ = '\0';
		
		if(!cs_malloc(&new_provid, sizeof(struct s_provid)))
		{
			NULLFREE(token);
			fclose(fp);
			return (1);
		}
				
		new_provid->nprovid = 0;
		for(i = 0, ptr1 = strtok_r(token, ":@", &saveptr1); ptr1; ptr1 = strtok_r(NULL, ":@", &saveptr1), i++)
		{
			if(i==0)
			{
				new_provid->caid = a2i(ptr1, 3);
				continue;	
			}
			
			new_provid->nprovid++;
		}

		if(!cs_malloc(&new_provid->provid, sizeof(uint32_t) * new_provid->nprovid))
		{
			NULLFREE(new_provid);
			NULLFREE(token);
			fclose(fp);
			return (1);
		}

		ptr1 = token + strlen(token) + 1;
		for(i = 0; i < new_provid->nprovid ; i++)
		{
			new_provid->provid[i] = a2i(ptr1, 3);
			
			ptr1 = ptr1 + strlen(ptr1) + 1;
		}
		
		for(i = 0, ptr1 = strtok_r(payload, "|", &saveptr1); ptr1; ptr1 = strtok_r(NULL, "|", &saveptr1), i++)
		{
			switch(i)
			{
			case 0:
				cs_strncpy(new_provid->prov, trim(ptr1), sizeof(new_provid->prov));
				break;
			case 1:
				cs_strncpy(new_provid->sat, trim(ptr1), sizeof(new_provid->sat));
				break;
			case 2:
				cs_strncpy(new_provid->lang, trim(ptr1), sizeof(new_provid->lang));
				break;
			}
		}
		
		if(strlen(new_provid->prov) == 0)
		{
			NULLFREE(new_provid->provid);
			NULLFREE(new_provid);
			continue;
		}
		
		nr++;
				
		if(provid_ptr)
		{
			provid_ptr->next = new_provid;
		}
		else
		{ 
			new_cfg_provid = new_provid;
		}	
		provid_ptr = new_provid;
	}
	
	NULLFREE(token);
	fclose(fp);
	
	if(nr > 0)
		{ cs_log("%d provid's loaded", nr); }
	
	if(new_cfg_provid == NULL)
	{
		if(!cs_malloc(&new_cfg_provid, sizeof(struct s_provid)))
		{
			return (1);
		}		
	}
	
	cs_writelock(__func__, &config_lock);
	
	//this allows reloading of provids, so cleanup of old data is needed:
	last_provid = cfg.provid; //old data
	cfg.provid = new_cfg_provid; //assign after loading, so everything is in memory

	cs_writeunlock(__func__, &config_lock);

	struct s_client *cl;
	for(cl = first_client->next; cl ; cl = cl->next)
		{ cl->last_providptr = NULL; }

	struct s_provid *ptr, *nptr;
	
	if(last_provid)
	{
		ptr = last_provid;
		while(ptr)    //cleanup old data:
		{
			add_garbage(ptr->provid);
			nptr = ptr->next;
			add_garbage(ptr);
			ptr = nptr;
		}
	}
			
	return (0);
}
Beispiel #21
0
void CApplication::PrintError(const tstring& sText)
{
	tstring sTrimmedText = trim(sText);

	GetConsole()->PrintConsole(tstring("[color=FF0000]ERROR: ") + sTrimmedText + "[/color]" + (sText.endswith("\n")?"\n":""));
}
Beispiel #22
0
int32_t init_srvid(void)
{
	int8_t new_syntax = 1;
	FILE *fp = open_config_file("oscam.srvid2");
	if(!fp)
	{ 
		fp = open_config_file(cs_srid);
		if(fp)
		{
			new_syntax = 0;
		}
	}

	if(!fp)
	{ 
		fp = create_config_file("oscam.srvid2");
		if(fp)
		{
			flush_config_file(fp, "oscam.srvid2");
		}
		
		return 0;
	}

	int32_t nr = 0, i, j;
	char *payload, *saveptr1 = NULL, *saveptr2 = NULL, *token;
	const char *tmp;
	if(!cs_malloc(&token, MAXLINESIZE))
		{ return 0; }
	struct s_srvid *srvid = NULL, *new_cfg_srvid[16], *last_srvid[16];
	// A cache for strings within srvids. A checksum is calculated which is the start point in the array (some kind of primitive hash algo).
	// From this point, a sequential search is done. This greatly reduces the amount of string comparisons.
	const char **stringcache[1024];
	int32_t allocated[1024] = { 0 };
	int32_t used[1024] = { 0 };
	struct timeb ts, te;
	cs_ftime(&ts);

	memset(last_srvid, 0, sizeof(last_srvid));
	memset(new_cfg_srvid, 0, sizeof(new_cfg_srvid));

	while(fgets(token, MAXLINESIZE, fp))
	{
		int32_t l, len = 0, len2, srvidtmp;
		uint32_t k;
		uint32_t pos;
		char *srvidasc, *prov;
		tmp = trim(token);

		if(tmp[0] == '#') { continue; }
		if((l = strlen(tmp)) < 6) { continue; }
		if(!(srvidasc = strchr(token, ':'))) { continue; }
		if(!(payload = strchr(token, '|'))) { continue; }
		*payload++ = '\0';
		
		if(!cs_malloc(&srvid, sizeof(struct s_srvid)))
		{
			NULLFREE(token);
			fclose(fp);
			return (1);
		}

		char tmptxt[128];

		int32_t offset[4] = { -1, -1, -1, -1 };
		char *ptr1 = NULL, *ptr2 = NULL;
		const char *searchptr[4] = { NULL, NULL, NULL, NULL };
		const char **ptrs[4] = { &srvid->prov, &srvid->name, &srvid->type, &srvid->desc };
		uint32_t max_payload_length = MAXLINESIZE - (payload - token);
		
		if(new_syntax)
		{
			ptrs[0] = &srvid->name;
			ptrs[1] = &srvid->type;
			ptrs[2] = &srvid->desc;
			ptrs[3] = &srvid->prov;
		}
		
		// allow empty strings as "||"
		if(payload[0] == '|' && (strlen(payload)+2 < max_payload_length))
		{
			memmove(payload+1, payload, strlen(payload)+1);
			payload[0] = ' ';
		}
		
		for(k=1; ((k < max_payload_length) && (payload[k] != '\0')); k++)
		{
			if(payload[k-1] == '|' && payload[k] == '|')
			{
				if(strlen(payload+k)+2 < max_payload_length-k)
				{
					memmove(payload+k+1, payload+k, strlen(payload+k)+1);
					payload[k] = ' ';
				}
				else
				{
					break;
				}	
			}
		}
	
		for(i = 0, ptr1 = strtok_r(payload, "|", &saveptr1); ptr1 && (i < 4) ; ptr1 = strtok_r(NULL, "|", &saveptr1), ++i)
		{
			// check if string is in cache
			len2 = strlen(ptr1);
			pos = 0;
			for(j = 0; j < len2; ++j) { pos += (uint8_t)ptr1[j]; }
			pos = pos % 1024;
			for(j = 0; j < used[pos]; ++j)
			{
				if(!strcmp(stringcache[pos][j], ptr1))
				{
					searchptr[i] = stringcache[pos][j];
					break;
				}
			}
			if(searchptr[i]) { continue; }

			offset[i] = len;
			cs_strncpy(tmptxt + len, trim(ptr1), sizeof(tmptxt) - len);
			len += strlen(ptr1) + 1;
		}

		char *tmpptr = NULL;
		if(len > 0 && !cs_malloc(&tmpptr, len))
			{ continue; }

		srvid->data = tmpptr;
		if(len > 0) { memcpy(tmpptr, tmptxt, len); }

		for(i = 0; i < 4; i++)
		{
			if(searchptr[i])
			{
				*ptrs[i] = searchptr[i];
				continue;
			}
			if(offset[i] > -1)
			{
				*ptrs[i] = tmpptr + offset[i];
				// store string in stringcache
				tmp = *ptrs[i];
				len2 = strlen(tmp);
				pos = 0;
				for(j = 0; j < len2; ++j) { pos += (uint8_t)tmp[j]; }
				pos = pos % 1024;
				if(used[pos] >= allocated[pos])
				{
					if(allocated[pos] == 0)
					{
						if(!cs_malloc(&stringcache[pos], 16 * sizeof(char *)))
							{ break; }
					}
					else
					{
						if(!cs_realloc(&stringcache[pos], (allocated[pos] + 16) * sizeof(char *)))
							{ break; }
					}
					allocated[pos] += 16;
				}
				stringcache[pos][used[pos]] = tmp;
				used[pos] += 1;
			}
		}

		*srvidasc++ = '\0';
		if(new_syntax)
			{ srvidtmp = dyn_word_atob(token) & 0xFFFF; }
		else
			{ srvidtmp = dyn_word_atob(srvidasc) & 0xFFFF; }
			
		if(srvidtmp < 0)
		{
			NULLFREE(tmpptr);
			NULLFREE(srvid);
			continue;
		}
		else
		{
			srvid->srvid = srvidtmp;
		}		
		
		srvid->ncaid = 0;
		for(i = 0, ptr1 = strtok_r(new_syntax ? srvidasc : token, ",", &saveptr1); (ptr1); ptr1 = strtok_r(NULL, ",", &saveptr1), i++)
		{
			srvid->ncaid++;
		}
		
		if(!cs_malloc(&srvid->caid, sizeof(struct s_srvid_caid) * srvid->ncaid))
		{
			NULLFREE(tmpptr);
			NULLFREE(srvid);
			return 0;
		}
		
		ptr1 = new_syntax ? srvidasc : token;
		for(i = 0; i < srvid->ncaid; i++)
		{
			prov = strchr(ptr1,'@');
						
			srvid->caid[i].nprovid = 0;
			
			if(prov)
			{
				if(prov[1] != '\0')
				{
					for(j = 0, ptr2 = strtok_r(prov+1, "@", &saveptr2); (ptr2); ptr2 = strtok_r(NULL, "@", &saveptr2), j++)
					{
						srvid->caid[i].nprovid++;
					}
		    		
					if(!cs_malloc(&srvid->caid[i].provid, sizeof(uint32_t) * srvid->caid[i].nprovid))
					{
						for(j = 0; j < i; j++)
							{ NULLFREE(srvid->caid[j].provid); } 
						NULLFREE(srvid->caid);
						NULLFREE(tmpptr);
						NULLFREE(srvid);
						return 0;
					}
					
					ptr2 = prov+1;
					for(j = 0;  j < srvid->caid[i].nprovid; j++)
					{
						srvid->caid[i].provid[j] = dyn_word_atob(ptr2) & 0xFFFFFF;
						ptr2 = ptr2 + strlen(ptr2) + 1;
					}
				}
				else
				{
					ptr2 = prov+2;
				}
				
				prov[0] = '\0';
			}

			srvid->caid[i].caid = dyn_word_atob(ptr1) & 0xFFFF;
			if(prov)
				{ ptr1 = ptr2; }
			else 
				{ ptr1 = ptr1 + strlen(ptr1) + 1; }
		}
			
		nr++;

		if(new_cfg_srvid[srvid->srvid >> 12])
			{ last_srvid[srvid->srvid >> 12]->next = srvid; }
		else
			{ new_cfg_srvid[srvid->srvid >> 12] = srvid; }

		last_srvid[srvid->srvid >> 12] = srvid;
	}
Beispiel #23
0
void GetMcdBlockInfo(int mcd, int block, McdBlock *Info) {
	unsigned char *data = NULL, *ptr, *str, *sstr;
	unsigned short clut[16];
	unsigned short c;
	int i, x;

	memset(Info, 0, sizeof(McdBlock));

	if (mcd == 1) data = Mcd1Data;
	if (mcd == 2) data = Mcd2Data;

	ptr = data + block * 8192 + 2;

	Info->IconCount = *ptr & 0x3;

	ptr += 2;

	x = 0;

	str = Info->Title;
	sstr = Info->sTitle;

	for (i = 0; i < 48; i++) {
		c = *(ptr) << 8;
		c |= *(ptr + 1);
		if (!c) break;

		// Convert ASCII characters to half-width
		if (c >= 0x8281 && c <= 0x829A)
			c = (c - 0x8281) + 'a';
		else if (c >= 0x824F && c <= 0x827A)
			c = (c - 0x824F) + '0';
		else if (c == 0x8140) c = ' ';
		else if (c == 0x8143) c = ',';
		else if (c == 0x8144) c = '.';
		else if (c == 0x8146) c = ':';
		else if (c == 0x8147) c = ';';
		else if (c == 0x8148) c = '?';
		else if (c == 0x8149) c = '!';
		else if (c == 0x815E) c = '/';
		else if (c == 0x8168) c = '"';
		else if (c == 0x8169) c = '(';
		else if (c == 0x816A) c = ')';
		else if (c == 0x816D) c = '[';
		else if (c == 0x816E) c = ']';
		else if (c == 0x817C) c = '-';
		else {
			str[i] = ' ';
			sstr[x++] = *ptr++; sstr[x++] = *ptr++;
			continue;
		}

		str[i] = sstr[x++] = c;
		ptr += 2;
	}

	trim(str);
	trim(sstr);

	ptr = data + block * 8192 + 0x60; // icon palette data

	for (i = 0; i < 16; i++) {
		clut[i] = *((unsigned short *)ptr);
		ptr += 2;
	}

	for (i = 0; i < Info->IconCount; i++) {
		short *icon = &Info->Icon[i * 16 * 16];

		ptr = data + block * 8192 + 128 + 128 * i; // icon data

		for (x = 0; x < 16 * 16; x++) {
			icon[x++] = clut[*ptr & 0xf];
			icon[x] = clut[*ptr >> 4];
			ptr++;
		}
	}

	ptr = data + block * 128;

	Info->Flags = *ptr;

	ptr += 0xa;
	strncpy(Info->ID, ptr, 12);
	ptr += 12;
	strncpy(Info->Name, ptr, 16);
}
/**
 Read data from clients
 @param data data to be read
 */
void* ReadClient(void *data) {
	TuxLogger_Debug("Start ReadClient()",NULL);
	
	if (data == NULL)
		return NULL;

	tux_client client = (tux_client) data;

	if (client == NULL) {
		return NULL;
	}

	char *buff = (char *) malloc(sizeof(char) * 2048);

	int iResult;
	int isAlive = 0;

	TuxLogger_Debug("ReadClient() varible are initialized",NULL);

	TuxLogger_Debug("Start reading data from the client %d",
		client->id);

	do {
		TuxLogger_Debug("Reading looping for client %d",
			client->id);
		
		iResult = recv(client->sock, buff, 2048, 0);

		if (iResult > 0) {
			TuxLogger_Debug("Receiving data !",NULL);

			isAlive = 1;

			TuxLogger_Debug(
					"Allocating memory for the command",NULL);
			char *cmd = (char *) malloc(sizeof(char) * (iResult + 1));
			TuxLogger_Debug( "Allocation OK",NULL);
			TuxLogger_Debug( "Copy data in cmd",NULL);
			snprintf(cmd, iResult + 1, "%s", buff);

			TuxLogger_Debug( "Raw data received: %s", cmd);

			if (buff != NULL) {
				/*free(buff);
				 buff=NULL;*/
			}

			ParseCommand(client, trim(cmd));

			if (cmd != NULL) {
				/*free(cmd);
				 cmd=NULL;*/
			}

		} else
			isAlive = 0;

		break;
	} while (iResult > 0);

	if (isAlive == 1) {
		TuxLogger_Debug(
				"Client is still alive. Keep watching data coming from him",NULL);
				
		ReadClient(data);
	} else {
		TuxLogger_Debug(
				"Connection with the client %d has been closed by him. Closing the socket..",
				client->id);
		
		removeUniqueID(client->pID);
		
		close(client->sock);
		TuxLogger_Debug( "Socket closed", client->id);
	
		int i;
		for(i = 0; i < plugins->count; i++)
		{
			if(plugins->plugins[i]->delClient != NULL)
				plugins->plugins[i]->delClient(client);
		}
	}

	if (client->uKey != NULL) {
		/*free(client->uKey);
		 client->uKey = NULL;*/
	}

	if (client->username != NULL) {
		/*free(client->username);
		 client->username=NULL;*/
	}

	if (client != NULL) {
		/*free(client);
		 client=NULL;*/
	}

	if (data != NULL) {
		/*free(data);
		 data=NULL;*/
	}

	return 0;
}
int F847124(TRUSERID *handle,int iRequest,ST_PACK *rPack,int *pRetCode,char *szMsg)
{
	int	hi_custid = 0;											//客户ID
	int	hi_custtype = 0;										//客户类型
	int i=0;
	int ret = 0;
	int len = 0;
	char h_showcardid[11] = "";						//显示卡号
	char h_password[7] = "";							//卡密码
	double h_temp_Card_id = 0;						//卡号
	char seed_key[17] = "";							//种子密钥
	char card_endtime[8 + 1] = "";						//卡的有效截至日期
	char logicdate[11]="";								//业务日期
	char sysdate[11]="";
	char systime[9]="";
	char sMsg[256]="";
	char sMaxCardBalance[20]="";
	double dMaxCardBalance=0;
	int 	type=0;										//充值类型
	T_t_card tCard;
	T_t_customer tCustomer;
	T_t_aif_account  tAccount;
	T_t_tif_tradeserial  tradeserial;
	T_t_tif_savdtl		tSavdtl;
	T_t_spefee 	tSpeFee;
	double h_temp_Serial_no = 0;
	InAcc	IA;
	ST_CPACK aPack;
	ST_PACK *out_pack = &(aPack.pack);

	memset(&IA,0,sizeof(IA));
	memset(&tCard, 0, sizeof(tCard));
	memset(&tAccount,0,sizeof(tAccount));
	memset(&tradeserial,0,sizeof(tradeserial));
	memset(&tSpeFee,0,sizeof(tSpeFee));
	memset(&tCustomer,0,sizeof(tCustomer));
	memset(&tSavdtl,0,sizeof(tSavdtl));

#ifdef DEBUG
	writelog(LOG_DEBUG,"rPack->scust_auth2[%s]",rPack->scust_auth2);
#endif
	ResetNormalCPack(&aPack,0,1);
	SetCol(handle,F_LVOL0,F_LVOL1,F_LVOL5,
				F_SCUST_NO,	F_SCUST_NO2,F_SCUST_AUTH,F_SCUST_AUTH2,
				F_SDATE0,F_SNAME,F_SNAME2,
				F_SOPEN_EMP,F_SSTATUS0,
				F_DAMT2,F_LSERIAL1,F_VSMESS,0);

	hi_custid = rPack->lvol0;									//客户ID
	hi_custtype = rPack->lvol3;									//客户类别
	des2src(h_showcardid,rPack->scust_no);					//显示卡号
	getsysdate(sysdate);
	getsystime(systime);
	ret=GetLogicDate(logicdate);								//业务日期
	if(ret)
	{
		*pRetCode=ret;
		goto L_RETU;
	}
	//检查客户信息,判断是否可以发行卡
	des2src(tCard.cardphyid, rPack->sbank_acc);				//物理卡号
	trim(h_showcardid);
	if(strlen(h_showcardid))
	{
		ret=IsExistShowCardNo(h_showcardid);
		if(ret)
		{
			*pRetCode = ret;
			goto L_RETU;
		}
	}
	ret=IsExistCardByPhyCardNo(tCard.cardphyid);
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	ret=IsExistCardByCustomId(hi_custid);
	if (ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	ret=DB_t_customer_read_lock_by_cur_and_custid(hi_custid, &tCustomer);
	if(ret)
	{
		writelog(LOG_ERR,"custid[%d]",hi_custid);
		if(DB_NOTFOUND==ret)
			*pRetCode= E_CUSTOMER_NOT_EXIST;
		else
			*pRetCode= E_DB_CUSTOMER_R;
		goto L_RETU;
	}
	//得到收费类别
	if(tCustomer.feetype<1)
	{
		ret=DB_t_spefee_read_by_deptcode_and_custtype(tCustomer.deptcode, tCustomer.custtype,&tSpeFee);
		if(ret)
		{
			if(DB_NOTFOUND==ret)
			{
				tCustomer.feetype=tCustomer.custtype;
			}
			else
			{
				DB_t_customer_free_lock_cur();
				*pRetCode=E_DB_SPEFEE_R;
				goto L_RETU;
			}
		}
		else
		{
			tCustomer.feetype=tSpeFee.feetype;
		}
		//更新客户表的收费类别字段
		ret=DB_t_customer_update_lock_by_cur(&tCustomer);
		if(ret)
		{
			if(DB_NOTFOUND==ret)
				*pRetCode= E_CUSTOMER_NOT_EXIST;
			else
				*pRetCode= E_DB_CUSTOMER_U;
			goto L_RETU;
		}
	}
	DB_t_customer_free_lock_cur();

	tradeserial.trade_fee =rPack->damt0;

	//检查金额是否超过最大额度
	ret=GetParameter(GLOBE_MAXCARDBALANCE,sMaxCardBalance);
	if(ret)
	{
		*pRetCode=ret;
		goto L_RETU;
	}
	dMaxCardBalance=atof(sMaxCardBalance);

	if(amtcmp(tradeserial.trade_fee,dMaxCardBalance)>0)
	{
		writelog(LOG_ERR,"tradeserial.trade_fee[%lf]",tradeserial.trade_fee);
		*pRetCode=E_AMT_EXCEED_MAX;
		goto L_RETU;
	}
	//	准备数据插入卡信息表
	memcpy(seed_key,STATIC_SEED_KEY,sizeof(seed_key));			//读种子密钥
	ret=IsInvalidDateTime(rPack->sdate0,"YYYYMMDD");
	if(ret)
	{
		*pRetCode = E_INPUT_DATE;
		goto L_RETU;
	}
	if(strncmp(rPack->sdate0,sysdate,8)<=0)
	{
		*pRetCode=E_INPUT_DATE;
		goto L_RETU;
	}
	des2src(card_endtime,rPack->sdate0);
/*
	ret = GetCardValiddate(hi_custtype,logicdate,card_endtime);				//计算卡的有效期
	if (ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
*/
	//	默认密码, 初始取身份证的后6位, 没有身份证号用默认密码
	trim(rPack->sname2);
	len=strlen(rPack->sname2) ;
	if (len >= 6)
	{
		strncpy(h_password,&(rPack->sname2[len-6]),6);
		if(h_password[5]>'9'||h_password[5]<'0')
			h_password[5]='0';
	}
	else
	{
		strcpy(h_password,DEFAULT_CUST_PWD);
	}
	ret = getNewUniqNo(KEYTYPE_CARD_ID,&h_temp_Card_id);						//获取最大卡号
	if(ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	tCard.cardno = D2I(h_temp_Card_id);											//卡号
	des2src(tCard.showid,h_showcardid);										//显示卡号
	des2src(tCard.is_main,TYPE_YES);  											//是否为主卡
	des2src(tCard.cardattr,CARDSTAT_REG);										//卡状态
	tCard.type_id = CT_TEMP_NAME;													//卡类别
	EncodePwd(seed_key,h_password,tCard.password,0);							//卡密码
	tCard.custid = hi_custid;													//客户标识
	tCard.account_count = ACCOUNT_COUNT_ONE;									//卡对应帐户个数
	des2src(tCard.begintime,logicdate);											//注册时间
	des2src(tCard.endtime, card_endtime);										//截至时间

	tCard.phytype = PHYTYPE_NO_ONE;											//设备物理型号;默认为1
	//	插入卡信息
	ret = DB_t_card_add(&tCard);
	if (ret)
	{
		if(DB_REPEAT==ret)
			*pRetCode = E_DB_CARD_E;
		else
			*pRetCode = E_DB_CARD_I;
		goto L_RETU;
	}
	//	准备数据插入帐户信息表
	ret = getNewActno(tAccount.account_id);  	    									//获得最大帐号
	if (ret)
	{
		*pRetCode = ret;
		goto L_RETU;
	}
	des2src(tAccount.open_date,sysdate);		   									//开户时间
	des2src(tAccount.open_time,systime);
	tAccount.current_state = ACCOUNTSTAT_REGIST;      								//当前状态
	tAccount.act_type = ACCTYPE_PERMAIN;				        						//帐号类别
	tAccount.custid = rPack->lvol0;				        						//客户号
	des2src(tAccount.custname,rPack->sname);										//客户名称
	tAccount.custtype = hi_custtype;													//客户类别
	des2src(tAccount.stuempno,rPack->scust_auth2); 								//客户学号或员工号
	tAccount.cardno = tCard.cardno;		 										//关联卡号
	tAccount.purseno = PURSE_NO_ONE;											//关联卡钱包号
	tAccount.card_type = CT_TEMP_NAME;												//卡类别
	des2src(tAccount.subno,SUBJECT_INDIVIDUALSAVING);							//所属科目
	des2src(tAccount.isautotra,TYPE_NO); 											//是否自动转帐
	//	插入帐户信息表
	ret = DB_t_aif_account_add(&tAccount);
	if (ret)
	{
		writelog(LOG_ERR,"ret [%d]",ret);
		if(DB_REPEAT==ret)
			*pRetCode = E_DB_ACCOUNT_E;
		else
			*pRetCode = E_DB_ACCOUNT_I;
		goto L_RETU;
	}

	ret = getNewUniqNo(KEYTYPE_TRADESERIAL,&h_temp_Serial_no);  						//获得最大流水号
	if(ret)
	{
		*pRetCode = ret;
		writelog(LOG_ERR,"ret [%d]",ret);
		goto L_RETU;
	}

	tradeserial.serial_no = D2I(h_temp_Serial_no);											//流水号
	tradeserial.other_seri_no = 0;														//上传端流水号
	tradeserial.serial_type=TXCODE_CARD_OPEN_TMP_CASH;								//交易码
	tradeserial.serial_state = SERISTAT_DEBT;												//流水状态
	des2src(tradeserial.operate_date,sysdate);											//发生日期
	des2src(tradeserial.operate_time,systime);											//发生时间
	des2src(tradeserial.collect_date,sysdate);												//采集日期
	des2src(tradeserial.collect_time,systime);												//采集时间
	des2src(tradeserial.enteract_date,logicdate);											//处理日期
	des2src(tradeserial.enteract_time,systime);											//处理时间

	tradeserial.maindeviceid = rPack->lvol6;												//上传工作站标识
	tradeserial.deviceid = rPack->lvol7;													//采集设备标识
	tradeserial.cardno = tCard.cardno;													//卡号
	des2src(tradeserial.showid,tCard.showid);												//显示卡号
	tradeserial.purseno = PURSE_NO_ONE;												//钱包号
	tradeserial.custid = hi_custid;													//客户标识

	des2src(tradeserial.opercode , rPack->scust_limit);									//操作员代码
	tradeserial.sys_id = 0;																//外部系统标识
	tradeserial.trade_count=1;															//当前卡交易次数
	type=rPack->lvol4;																//交易类型
	IA.dArrInAmt[0]=tradeserial.trade_fee;
	switch(type)
	{
		case TYPE_CASH:	//现金
			IA.iArrInFeeSwitch[1]=1;
			break;
		case TYPE_BILL:	//支票
			IA.iArrInFeeSwitch[2]=1;
			break;
		case TYPE_FUNDBOOK:	//经费本
			IA.iArrInFeeSwitch[3]=1;
			break;
		default:
			*pRetCode=E_INPUT_DEPOSIT_TYPE;
			goto L_RETU;
	}
	switch(type)
	{
		case TYPE_CASH:		//现金
			break;
 		case TYPE_BILL:		//支票
		case TYPE_FUNDBOOK:	//经费本
 			tSavdtl.amount=rPack->damt0;				//发生额
 			if(amtcmp(tSavdtl.amount,0)<=0)
				break;
			des2src(tSavdtl.billno,rPack->sphone);		//票据号码
			if(strlen(tSavdtl.billno)<1)
			{
				*pRetCode=E_INPUT_BILLNO;
				goto L_RETU;
			}
			tSavdtl.cardno=tCard.cardno;				//卡号
			des2src(tSavdtl.oper_no,rPack->scust_limit);	//操作员
			tSavdtl.seqno=tradeserial.serial_no;			//流水号
			des2src(tSavdtl.tx_date,logicdate);			//发生日期
			des2src(tSavdtl.tx_time,systime);			//发生时间
			tSavdtl.cnt=1;								//票据数量
			tSavdtl.billtype=type;						//票据类型
			tSavdtl.tx_code=tradeserial.serial_type;		//交易码
			ret=DB_t_tif_savdtl_add(&tSavdtl);
			if(ret)
			{
				if(DB_REPEAT==ret)
					*pRetCode = E_DB_SAVDTL_E;
				else
					*pRetCode = E_DB_SAVDTL_I;
				goto L_RETU;
			}
			break;
		default:
			*pRetCode=E_TXCODE_NOT_EXIST;
			goto L_RETU;
	}
	des2src(IA.sArrInActno[0],tAccount.account_id);						//帐户
	IA.iCardNo=tCard.cardno;
	IA.iFeeType=tCustomer.feetype;

	//调用入账子模块
	ret=process(&IA,&tradeserial);
	if(ret)
	{
		*pRetCode=ret;
		writelog(LOG_ERR,"process ret[%d]",ret);
		goto L_RETU;
	}
	sprintf(out_pack->vsmess,"流水号:%d 卡号:%d ",IA.iSerialNo,IA.iCardNo);
	for(i=1;i<=IA.iOutTxTypeCnt;i++)
	{
		switch(IA.iArrOutTxType[i])
		{
			case TXTYPE_TOLL_DEPOSIT:
			case TXTYPE_TOLL_DEPOSIT_BILL:
			case TXTYPE_TOLL_DEPOSIT_FUNDBOOK:
			case TXTYPE_DEDUCT_DEPOSIT:
			case TXTYPE_RETURN_DEPOSIT:
				tradeserial.depositfee=IA.dArrOutAmt[i];
				break;
			case TXTYPE_PRE_TOLL_BOARD:
			case TXTYPE_PRE_TOLL_BOARD_BILL:
			case TXTYPE_PRE_TOLL_BOARD_FUNDBOOK:
			case TXTYPE_TOLL_BOARD:
			case TXTYPE_DEDUCT_BOARD:
			case TXTYPE_RETURN_BOARD:
			case TXTYPE_RETURN_BOARD_BILL:
			case TXTYPE_RETURN_BOARD_FUNDBOOK:
				tradeserial.managefee=IA.dArrOutAmt[i];
				break;
			case TXTYPE_TOLL_CHARGE:
			case TXTYPE_TOLL_CHARGE_BILL:
			case TXTYPE_TOLL_CHARGE_FUNDBOOK:
				tradeserial.in_fee=IA.dArrOutAmt[i];
				break;
			case TXTYPE_TOLL_CARDCOST:
			case TXTYPE_TOLL_CARDCOST_BILL:
			case TXTYPE_TOLL_CARDCOST_FUNDBOOK:
				tradeserial.cost_fee=IA.dArrOutAmt[i];
				break;
			default:
				break;
		}
		if(amtcmp(IA.dArrOutAmt[i],0)!=0)
		{
			sprintf(sMsg,"%s:%.2lf元 ",IA.sArrOutTxName[i],IA.dArrOutAmt[i]);
			strcat(out_pack->vsmess,sMsg);
		}
	}
	sprintf(sMsg,"卡当前余额:%.2lf元",tradeserial.out_balance);
	strcat(out_pack->vsmess,sMsg);
	writelog(LOG_DEBUG,out_pack->vsmess);
	// 插入交易流水表
	ret = DB_t_tif_tradeserial_add(&tradeserial);
	if (ret)
	{
		writelog(LOG_ERR,"ret[%d]",ret);
		if(DB_REPEAT==ret)
			*pRetCode = E_DB_TRADESERIAL_E;
		else
			*pRetCode = E_DB_TRADESERIAL_I;
		goto L_RETU;
	}
	if(amtcmp(tradeserial.out_balance,0)<0)
	{
		*pRetCode=E_ENTER_ACCOUNT;
		goto L_RETU;
	}
	//	返回卡号\密码\显示卡号\客户类型\图书证号\有效截至日期
	out_pack->lvol0 = (int)h_temp_Card_id;						//交易卡号
	out_pack->lvol1 = tCustomer.custtype;						//客户类别
	out_pack->lvol5 = tCustomer.feetype;						//收费类别
	des2src(out_pack->scust_no,h_showcardid);					//显示卡号
	des2src(out_pack->scust_no2,tCustomer.deptcode);			//部门号
	des2src(out_pack->scust_auth,tCustomer.stuempno);			//学号
	des2src(out_pack->scust_auth2,tCustomer.man_id);			//身份证号
	des2src(out_pack->sname,tCustomer.custname);				//客户姓名
	des2src(out_pack->sname2,tCustomer.lib_cardid);				//图书证号
	des2src(out_pack->sstatus0,tCustomer.sex);					//性别
	des2src(out_pack->sopen_emp,h_password);					//卡密码
	des2src(out_pack->sdate0,card_endtime);					//有效截至日期

	out_pack->damt2=tradeserial.out_balance;					//出卡值
	out_pack->lserial1=tradeserial.serial_no;						//流水号

	PutRow(handle,out_pack,pRetCode,szMsg);
	return 0;
L_RETU:
	return -1;
}
Beispiel #26
0
/** Read item group data
* Structure: GroupID,ItemID,Rate{,Amount,isMust,isAnnounced,Duration,GUID,isBound,isNamed}
*/
static void itemdb_read_itemgroup_sub(const char* filename, bool silent)
{
	FILE *fp;
	int ln = 0, entries = 0;
	char line[1024];

	if ((fp=fopen(filename,"r")) == NULL) {
		if(silent == 0) ShowError("Can't read %s\n", filename);
		return;
	}
	
	while (fgets(line,sizeof(line),fp)) {
		DBData data;
		int group_id = -1;
		unsigned int j, prob = 1;
		uint8 rand_group = 1;
		char *str[10], *p;
		struct s_item_group_random *random = NULL;
		struct s_item_group_db *group = NULL;
		struct s_item_group_entry entry;
		bool found = false;

		ln++;
		if (line[0] == '/' && line[1] == '/')
			continue;
		if (strstr(line,"import")) {
			char w1[16], w2[64];

			if (sscanf(line,"%15[^:]: %63[^\r\n]",w1,w2) == 2 &&
				strcmpi(w1,"import") == 0)
			{
				itemdb_read_itemgroup_sub(w2, 0);
				continue;
			}
		}
		memset(str,0,sizeof(str));
		for (j = 0, p = line; j < 9 && p;j++) {
			str[j] = p;
			p = strchr(p,',');
			if (p) *p++=0;
		}
		if (str[0] == NULL) //Empty Group ID
			continue;
		if (j < 3) {
			if (j > 1) // Or else it barks on blank lines...
				ShowWarning("itemdb_read_itemgroup: Insufficient fields for entry at %s:%d\n", filename, ln);
			continue;
		}

		memset(&entry, 0, sizeof(entry));
		entry.amount = 1;
		entry.bound = BOUND_NONE;

		// Checking group_id
		trim(str[0]);
		if (ISDIGIT(str[0][0]))
			group_id = atoi(str[0]);
		else // Try reads group id by const
			script_get_constant(trim(str[0]), &group_id);

		if (group_id < 0) {
			ShowWarning("itemdb_read_itemgroup: Invalid Group ID '%s' (%s:%d)\n", str[0], filename, ln);
			continue;
		}

		// Remove from DB
		if (strcmpi(str[1], "clear") == 0 && itemdb_group->remove(itemdb_group, db_ui2key(group_id), &data)) {
			itemdb_group_free(db_ui2key(group_id), &data, 0);
			ShowNotice("Item Group '%s' has been cleared.\n", str[0]);
			continue;
		}

		// Checking sub group
		prob = atoi(str[2]);
		if (str[4] != NULL)
			rand_group = atoi(str[4]);
		if (rand_group < 0 || rand_group > MAX_ITEMGROUP_RANDGROUP) {
			ShowWarning("itemdb_read_itemgroup: Invalid sub group '%d' for group '%s' in %s:%d\n", rand_group, str[0], filename, ln);
			continue;
		}

		if (rand_group != 0 && prob < 1) {
			ShowWarning("itemdb_read_itemgroup: Random item must has probability. Group '%s' in %s:%d\n", str[0], filename, ln);
			continue;
		}

		// Checking item
		trim(str[1]);
		if (ISDIGIT(str[1][0]) && ISDIGIT(str[1][1]) && itemdb_exists((entry.nameid = atoi(str[1]))))
			found = true;
		else {
			struct item_data *id = itemdb_searchname(str[1]);
			if (id) {
				entry.nameid = id->nameid;
				found = true;
			}
		}

		if (!found) {
			ShowWarning("itemdb_read_itemgroup: Non-existant item '%s' in %s:%d\n", str[1], filename, ln);
			continue;
		}

		if (str[3] != NULL) entry.amount = cap_value(atoi(str[3]),1,MAX_AMOUNT);
		if (str[5] != NULL) entry.isAnnounced= atoi(str[5]);
		if (str[6] != NULL) entry.duration = cap_value(atoi(str[6]),0,UINT16_MAX);
		if (str[7] != NULL) entry.GUID = atoi(str[7]);
		if (str[8] != NULL) entry.bound = cap_value(atoi(str[8]),BOUND_NONE,BOUND_MAX-1);
		if (str[9] != NULL) entry.isNamed = atoi(str[9]);

		if (!(group = (struct s_item_group_db *) uidb_get(itemdb_group, group_id))) {
			CREATE(group, struct s_item_group_db, 1);
			group->id = group_id;
			uidb_put(itemdb_group, group->id, group);
		}

		// Must item (rand_group == 0), place it here
		if (!rand_group) {
			RECREATE(group->must, struct s_item_group_entry, group->must_qty+1);
			group->must[group->must_qty++] = entry;

			// If 'must' item isn't set as random item, skip the next process
			if (!prob) {
				entries++;
				continue;
			}
			rand_group = 0;
		}
Beispiel #27
0
void MsgEdit::makeMessage()
{
    if (msg == NULL) return;
    switch (msg->Type()){
    case ICQ_MSGxMSG:{
            ICQMsg *m = static_cast<ICQMsg*>(msg);
            m->Message = edit->text().local8Bit();
            if (edit->colorChanged()){
                m->BackColor = (edit->background().rgb() & 0xFFFFFF);
                m->ForeColor = (edit->foreground().rgb() & 0xFFFFFF);
                pMain->MessageBgColor = m->BackColor();
                pMain->MessageFgColor = m->ForeColor();
            }
            break;
        }
    case ICQ_MSGxURL:{
            ICQUrl *m = static_cast<ICQUrl*>(msg);
            m->Message = edit->text().local8Bit();
            m->URL = urlEdit->text().local8Bit();
            break;
        }
    case ICQ_MSGxFILE:{
            ICQFile *m = static_cast<ICQFile*>(msg);
            m->Description = edit->text().local8Bit();
            m->Name = fileEdit->text().local8Bit();
            break;
        }
    case ICQ_MSGxCHAT:{
            ICQChat *m = static_cast<ICQChat*>(msg);
            m->Reason = edit->text().local8Bit();
            break;
        }
    case ICQ_MSGxSMS:{
            ICQSMS *m = static_cast<ICQSMS*>(msg);
            string s;
            s = edit->text().local8Bit();
            s = pClient->clearHTML(s.c_str());
            msgTail = trim(QString::fromLocal8Bit(s.c_str()));
            m->Message = smsChunk();
            m->Phone = phoneEdit->lineEdit()->text().local8Bit();
            break;
        }
    case ICQ_MSGxCONTACTxLIST:{
            ICQContacts *m = static_cast<ICQContacts*>(msg);
            users->fillList(m->Contacts);
            break;
        }
    case ICQ_MSGxAUTHxREQUEST:{
            ICQAuthRequest *m = static_cast<ICQAuthRequest*>(msg);
            m->Message = edit->text().local8Bit();
            break;
        }
    case ICQ_MSGxAUTHxREFUSED:{
            ICQAuthRefused *m = static_cast<ICQAuthRefused*>(msg);
            m->Message = edit->text().local8Bit();
            break;
        }
    case ICQ_MSGxAUTHxGRANTED:
        break;
    default:
        log(L_WARN, "Bad message type %u", msg->Type());
        return;
    }
    if (bMultiply){
        msg->Uin.clear();
        UserBox *box = static_cast<UserBox*>(topLevelWidget());
        if (box->users){
            UserView *users = box->users;
            if (users) users->fillChecked(msg);
        }
    }
    realSend();
}
Beispiel #28
0
/*!
 * \brief Create a new dialog from a sip message
 *
 * Create a new dialog from a SIP message, register a callback
 * to keep track of the dialog with help of the tm module.
 * This function is either called from the request callback, or
 * from the dlg_manage function in the configuration script.
 * \see dlg_onreq
 * \see w_dlg_manage
 * \param msg SIP message
 * \param t transaction
 * \return 0 on success, -1 on failure
 */
int dlg_new_dialog(struct sip_msg *req, struct cell *t, const int run_initial_cbs) {
    struct dlg_cell *dlg;
    str s;
    str callid;
    str ftag;
    str ttag;
    str req_uri;
    unsigned int dir;

    LM_DBG("starting dlg_new_dialog and method is [%.*s]\n", req->first_line.u.request.method.len, req->first_line.u.request.method.s);

    if (current_dlg_pointer != NULL)
        return -1;

    if (req->first_line.u.request.method_value == METHOD_CANCEL)
        return -1;

    if (pre_match_parse(req, &callid, &ftag, &ttag, 0) < 0) {
        LM_WARN("pre-matching failed\n");
        return -1;
    }

    if (ttag.s != 0 && ttag.len != 0)
        return -1;

    if (pv_printf_s(req, ruri_param_model, &req_uri) < 0) {
        LM_ERR("error - cannot print the r-uri format\n");
        return -1;
    }
    trim(&req_uri);

    if (detect_spirals) {
        if (spiral_detected == 1)
            return 0;

        dir = DLG_DIR_NONE;

        dlg = get_dlg(&callid, &ftag, &ttag, &dir);
        if (dlg) {
            LM_DBG("Callid '%.*s' found, must be a spiraled request\n",
                    callid.len, callid.s);
            spiral_detected = 1;

            if (run_initial_cbs)
                run_dlg_callbacks(DLGCB_SPIRALED, dlg, req, NULL, DLG_DIR_DOWNSTREAM, 0);

            //Add did to rr header for all spiralled requested INVITEs
            if (req->first_line.u.request.method_value == METHOD_INVITE) {
                if (add_dlg_rr_param(dlg, req, dlg->h_entry, dlg->h_id) < 0) {
                    LM_ERR("failed to add RR param\n");

                }
            }

            // get_dlg has incremented the ref count by 1
            unref_dlg(dlg, 1);
            goto finish;
        }
    }
    spiral_detected = 0;


    LM_DBG("Building new Dialog for call-id %.*s\n", callid.len, callid.s);
    LM_DBG("SIP Method: %.*s  \n", req->first_line.u.request.method.len, req->first_line.u.request.method.s);
    dlg = build_new_dlg(&callid /*callid*/,
            &(get_from(req)->uri) /*from uri*/,
            &ftag/*from_tag*/,
            &req_uri /*r-uri*/);

    if (dlg == 0) {
        LM_ERR("failed to create new dialog\n");
        return -1;
    }

    /* save caller's tag, cseq, contact and record route*/
    if (populate_leg_info(dlg, req, t, DLG_CALLER_LEG,
            &(get_from(req)->tag_value)) != 0) {
        LM_ERR("could not add further info to the dialog\n");
        shm_free(dlg);
        lock_destroy(dlg->dlg_out_entries_lock);
        lock_dealloc(dlg->dlg_out_entries_lock);
        return -1;
    }

    dlg->transaction = t;

    /* Populate initial varlist: */
    dlg->vars = get_local_varlist_pointer(req, 1);

    link_dlg(dlg, 0);
    if (run_initial_cbs) run_create_callbacks(dlg, req);

    //Dialog will *always* use DID cookie so no need for match mode anymore
    if (add_dlg_rr_param(dlg, req, dlg->h_entry, dlg->h_id) < 0) {
        LM_ERR("failed to add RR param\n");
        goto error;
    }

    if (d_tmb.register_tmcb(req, t,
            TMCB_RESPONSE_READY | TMCB_RESPONSE_FWDED | TMCB_RESPONSE_OUT,
            dlg_onreply, (void*) dlg, unref_new_dialog) < 0) {
        LM_ERR("failed to register TMCB\n");
        goto error;
    }
    // increase reference counter because of registered callback
    ref_dlg(dlg, 1);

    dlg->lifetime = get_dlg_timeout(req);
    s.s = _dlg_ctx.to_route_name;
    s.len = strlen(s.s);
    dlg_set_toroute(dlg, &s);
    dlg->sflags |= _dlg_ctx.flags;

    if (_dlg_ctx.to_bye != 0)
        dlg->dflags |= DLG_FLAG_TOBYE;

finish:
    if (t) {
        // transaction exists ==> keep ref counter large enough to
        // avoid premature cleanup and ensure proper dialog referencing
        if (store_dlg_in_tm(req, t, dlg) < 0) {
            LM_ERR("failed to store dialog in transaction\n");
            goto error;
        }
    } else {
        // no transaction exists ==> postpone work until we see the
        // request being forwarded statefully
        if (d_tmb.register_tmcb(req, NULL, TMCB_REQUEST_FWDED,
                store_dlg_in_tm_cb, (void*) dlg, NULL) < 0) {
            LM_ERR("failed to register callback for storing dialog in transaction\n");
            goto error;
        }
    }

    LM_DBG("Setting current dialog\n");
    set_current_dialog(req, dlg);
    _dlg_ctx.dlg = dlg;
    ref_dlg(dlg, 1);
    return 0;

error:
    LM_DBG("Error in build_new_dlg");
    if (!spiral_detected)
        unref_dlg(dlg, 1); // undo ref regarding linking
    return -1;
}
void InteractiveSMTPServerWindow::slotReadyRead()
{
  while ( mSocket->canReadLine() )
    slotDisplayClient( trim( mSocket->readLine() ) );
}
Beispiel #30
0
static int b_not (lua_State *L) {
  lua_Unsigned r = ~checkunsigned(L, 1);
  pushunsigned(L, trim(r));
  return 1;
}