Exemple #1
0
QString Adb::getVersion()
{
    Process::Result r = exec("version");
    QRegularExpression rgx(REGEX_ADB_VERSION);
    for (const QString &l : r.output)
    {
        QRegularExpressionMatch m = rgx.match(l);
        if (m.hasMatch())
        {
            QString v("%1.%2.%3");
            for (int i = 1; i <= 3; i++)
            {
                v = v.arg(m.captured(i));
            }
            return v;
        }
    }
    return QString();
}
bool CCssSoap::GetUsernameForUsernameOrCallsign(char * szCharacterName, char * szUsername, char * szReason)
{
	char szHdrs[512];
	sprintf(szHdrs, "Content-Type: text/xml;charset=UTF-8\r\nSOAPAction: \"http://tempuri.org/IClientService/GetUsernameFromCallsignOrUsername\"");

	char soapBody[4092];
	sprintf(soapBody, 
		"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"> \
		   <soapenv:Header/> \
		   <soapenv:Body> \
			  <tem:GetUsernameFromCallsignOrUsername> \
				 <tem:callsignOrUsername><![CDATA[%s]]></tem:callsignOrUsername> \
			  </tem:GetUsernameFromCallsignOrUsername> \
		   </soapenv:Body> \
		</soapenv:Envelope>", szCharacterName);

	int soapLength = strlen(soapBody);

	ZString Response = UTL::DoHTTP(szHdrs, m_szCssServerDomain, "POST", m_szCssClientServicePath, soapBody, soapLength, true);

	char * szToken;
	char * szResponse = (char*)_alloca(10000);
	Strcpy(szResponse, (PCC)Response);

	// Parse results
	std::tr1::regex rgx("<GetUsernameFromCallsignOrUsernameResult.*?>.*?<a:Username>(.*?)</a:Username>.*?</GetUsernameFromCallsignOrUsernameResult>");
	std::tr1::smatch result;
	std::string strResponse(szResponse);

	if (std::tr1::regex_search(strResponse, result, rgx) == true && result.size() > 1)
	{
		sprintf(szUsername, result[1].str().c_str());
		return true;
	}
	else
	{
		sprintf(szReason, "Your primary login couldn't be found from this callsign. Please log in with your main account. Please visit www.freeallegiance.org to request help in the forums.");
		return false;
	}

	sprintf(szReason, "A general sign in error occurred. Please visit www.freeallegiance.org to request help in the forums.");
	return false;
}
        string extract_domain_from_url(string* url) {
                if (NULL == url || url->length() == 0)
                        return "";

                int  start_pos = 0;
                int  tmp_pos = url->find("://");
                if (tmp_pos != -1)
                        start_pos = tmp_pos + 3;


#if 0
                boost::regex rgx("^([0-9A-Za-z.-]+)[^0-9A-Za-z.-]?");
                boost::match_results<std::string::iterator> match;
                boost::match_flag_type flags = boost::match_default;
                if (regex_search(url->begin() + start_pos, url->end(), match, rgx, flags))
                        return std::string(match[1].first, match[1].second);
#endif

                int  end_pos = min(url->find("/", start_pos), url->size());
                return url->substr(0, end_pos);
        }
Exemple #4
0
QString _parseSetImageUrl(Site* site, QString setting, QString ret, QMap<QString,QString> *d, bool replaces = true)
{
	if (site->contains(setting) && replaces)
    {
        if (site->value(setting).contains("->"))
        {
            QStringList replaces = site->value(setting).split('&');
			for (QString rep : replaces)
            {
                QRegExp rgx(rep.left(rep.indexOf("->")));
                ret.replace(rgx, rep.right(rep.size() - rep.indexOf("->") - 2));
			}
        }
        else
        {
            ret = site->value(setting);
            ret.replace("{id}", d->value("id"))
            .replace("{md5}", d->value("md5"))
            .replace("{ext}", d->value("ext"));
        }
    }
	return site->fixUrl(ret).toString();
}
bool CCssSoap::ValidateUserLogin(char *username, char *password, char * szReason, int & iID)
{
	char szHdrs[512];
	sprintf(szHdrs, "Content-Type: text/xml;charset=UTF-8\r\nSOAPAction: \"http://tempuri.org/IClientService/LauncherSignIn\"");

	char soapBody[4092];
	sprintf(soapBody, 
		"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\" xmlns:all=\"http://schemas.datacontract.org/2004/07/Allegiance.CommunitySecuritySystem.Server.Contracts\"> \
		   <soapenv:Header/> \
		   <soapenv:Body> \
			  <tem:LauncherSignIn> \
				 <tem:data> \
				 	<all:Password><![CDATA[%s]]></all:Password> \
				 	<all:Username><![CDATA[%s]]></all:Username> \
				 </tem:data> \
			  </tem:LauncherSignIn> \
		   </soapenv:Body> \
		   		</soapenv:Envelope>", password, username);

	

	int soapLength = strlen(soapBody);

	ZString Response = UTL::DoHTTP(szHdrs, m_szCssServerDomain, "POST", m_szCssClientServicePath, soapBody, soapLength, true);

	char * szToken;
	char * szResponse = (char*)_alloca(10000);
	Strcpy(szResponse, (PCC)Response);

	puts(szHdrs);
	puts("\r\n");
	puts(soapBody);
	puts("\r\n");
	puts(szResponse);
	puts("\r\n");

	// Parse results
	std::tr1::regex rgx("<LauncherSignInResult.*?>.*?<a:Status>(.*?)</a:Status>.*?</LauncherSignInResult>");
	std::tr1::regex rgxLoginID("<LauncherSignInResult.*?>.*?<a:LoginID>(.*?)</a:LoginID>.*?</LauncherSignInResult>");
	std::tr1::smatch result;
	std::string strResponse(szResponse);

	if (std::tr1::regex_search(strResponse, result, rgxLoginID) == true && result.size() > 1)
	{
		char szLoginID[50];
		sprintf(szLoginID, result[1].str().c_str());
		iID = atoi(szLoginID);
	}

	if (std::tr1::regex_search(strResponse, result, rgx) == true && result.size() > 1)
	{
		char status[50];
		sprintf(status, result[1].str().c_str());

		if (stricmp(status, "Ok") == 0)
		{
			return true;
		}
		else if (stricmp(status, "InvalidCredentials") == 0)
		{
			sprintf(szReason, "Your user name or password are invalid. Go to acss.alleg.net to create an account, or reset a forgotten password.");
			return false;
		}
		else if (stricmp(status, "AccountLinked") == 0)
		{
			sprintf(szReason, "Your account has been linked to another user's account. Please log in with your main account. Please visit www.freeallegiance.org to request help in the forums.");
			return false;
		}
		else if (stricmp(status, "PermissionDenied") == 0)
		{
			sprintf(szReason, "Your account access has been denied. Please visit www.freeallegiance.org to request help in the forums.");
			return false;
		}
		else if (stricmp(status, "AccountLocked") == 0)
		{
			sprintf(szReason, "Your account has been locked. Please visit www.freeallegiance.org to request help in the forums.");
			return false;
		}
		else
		{
			sprintf(szReason, "Login failed with status: %s. Please visit www.freeallegiance.org to request help in the forums.", status);
			return false;
		}
	}

	sprintf(szReason, "A general sign in error occurred. Please visit www.freeallegiance.org to request help in the forums.");
	return false;
}
Exemple #6
0
void client_connection(ConexaoPtr conexao) {
	bool logado = false;
	bool lista_foi_preparada = false;
	std::vector<UsuarioPtr> copia_lista_usuarios;
	
	std::string comando, arg1, arg2;

	UsuarioPtr usuario;
	PartidaPtr partida;

	/* Armazena linhas recebidas do cliente */
	char    recvline[MAXLINE + 1];
	/* Armazena o tamanho da string lida do cliente */
	ssize_t  n;

	while ((n=conexao->recebe_mensagem(recvline)) > 0) {

		recvline[n] = '\0';

		printf ("Recebeu: %s\n", recvline);
		std::string recvline_string(recvline);

		std::regex rgx("([A-Z_]*)(\\s+(\\w*))?(\\s+(\\w*))?");
		std::smatch resultado;
		std::regex_search(recvline_string, resultado, rgx);
		comando = resultado[1];
		arg1 = resultado[3];
		arg2 = resultado[5];
		std::string stringaux;

		if (logado)
		{
			if (usuario->esta_em_jogo())
			{
				if (comando == "PLAY")
				{
					comando_play(usuario, arg1, arg2);
				}
				else if (comando == "FINISH")
				{
					comando_finish(usuario);
				}
				else if (comando == "LOGOUT")
				{
					logado = false;
					comando_logout(usuario);
				}
				else
					conexao->envia_mensagem("REPLY 099\n"); // comando inválido
			}
			else // quando não está em jogo
			{
				if (comando == "PREPARE_LIST")
				{	
					lista_foi_preparada = true;
					comando_prepare_list(copia_lista_usuarios, usuario);
				}
				else if (comando == "LIST")
				{
					if(lista_foi_preparada) {
						comando_list(copia_lista_usuarios, usuario);
						lista_foi_preparada = false;
					}
					else 
						usuario->escreve("REPLY 032\n");
				}
				else if (comando == "LOGOUT")
				{
					logado = false;
					comando_logout(usuario);
				}
				else if (comando == "QUIT")
				{
					break;
				}
				else if (comando == "REQUEST")
				{
					comando_request(usuario, arg1);
				}
				else if (comando == "ANSWER")
				{
					comando_answer(usuario, arg1, arg2);
				}
				else
					conexao->envia_mensagem("REPLY 098\n"); // comando inválido
			}
		}
		else // comandos quando não está logado
		{
			if (comando == "LOGIN")
			{
				usuario = comando_login(conexao, arg1, arg2);
				if (usuario == nullptr) {
					logado = false;
				}
				else { 
					logado = true; 
				}
			}
			else if (comando == "NEWUSR")
			{
				usuario = comando_newusr(conexao, arg1, arg2);
				if (usuario == nullptr) {
					logado = false;
				}
				else { 
					logado = true; 
				}
			}
			else 
			{
				conexao->envia_mensagem("REPLY 097\n"); // comando inválido
			}
		}
		strcpy (recvline, "");
	}	

	if (logado)
		usuario->desconecta();
}
std::string DescriptionParser::prepare_item(const std::string& item) const {
  // no space around '='
  std::regex rgx("\\s*=\\s*");
  std::string filtered = std::regex_replace(item, rgx, "=");
  return filtered;
}
std::string DescriptionParser::restore_space_in_quote(const std::string& param) const {
  std::regex rgx(spaceReplacement);
  return std::regex_replace(param, rgx, " ");
}
DescriptionParser::DescriptionParser(const std::string& description,
                                     const std::vector<std::string>& valid_types)
    : is_valid_(parse_description(description, valid_types)) {
  if (!is_valid_) return;

  // check if placeholders in connections_ refer to existing quiddity
  for (auto& it : connections_) {
    std::string placeholder;
    if (!it.src.empty() && *it.src.begin() == '.') {
      // removing the '.'
      placeholder = std::string(it.src.begin() + 1, it.src.end());
      // saving appropriate name instead of placeholder
      it.src = placeholder;
    } else if (!it.sink.empty() && *it.sink.begin() == '.') {
      // removing the '.'
      placeholder = std::string(it.sink.begin() + 1, it.sink.end());
      // saving appropriate name instead of placeholder
      it.sink = placeholder;
    }
    if (placeholder.empty()) continue;
    if (quiddities_.cend() ==
        std::find_if(quiddities_.begin(), quiddities_.end(), [&](const quiddity_spec_t& quid_spec) {
          if (quid_spec.name == placeholder) return true;
          return false;
        })) {
      parsing_error_ =
          std::string("placeholder name ") + placeholder + " is not a valid quiddity name";
      is_valid_ = false;
      return;
    }
  }

  // read connections_ and feed data into quiddities_
  for (auto& it : connections_) {
    auto quid = std::find_if(quiddities_.begin(),
                             quiddities_.end(),
                             [&](const quiddity_spec_t& quid) { return it.src == quid.name; });
    if (quid == quiddities_.end()) {
      parsing_error_ = "BUG during analysis of connections";
      is_valid_ = false;
      return;
    }
    quid->connects_to_.push_back(it.sink);
  }

  // check params, build blacklist and remove prefixed '_' if found
  std::regex rgx("_.+");
  for (auto& it : quiddities_) {
    std::vector<std::pair<std::string, std::string>> tmp_params;
    for (auto& prop : it.params) {
      std::string actual_param_name;
      if (std::regex_match(prop.first, rgx)) {  // blacklist '_' if properties are exposed
        actual_param_name = std::string(prop.first.begin() + 1, prop.first.end());
        if (it.expose_prop)
          it.blacklisted_params.push_back(actual_param_name);
        else
          it.whitelisted_params.push_back(actual_param_name);
      } else {
        actual_param_name = std::string(prop.first.begin(), prop.first.end());
      }
      tmp_params.push_back(std::make_pair(actual_param_name, prop.second));
    }
    std::swap(it.params, tmp_params);
  }
}
bool DescriptionParser::parse_item(const std::string& raw_item,
                                   const std::vector<std::string>& valid_types) {
  // start with some filtering
  std::string item = prepare_item(raw_item);
  item = protect_space_in_quote(item);
  // split by space' ', but can be escaped with '\\ '
  std::regex rgx("\\s");
  std::sregex_token_iterator iter(item.begin(), item.end(), rgx, -1);
  bool type_found = false;
  static const std::string shmr("<shmr");
  static const std::string shmw("<shmw");
  static const std::string noprop("<no_prop");
  static const std::string addtostart("<add_to_start");
  static const std::string top_level("<top_level");
  quiddity_spec_t quid;
  for (; iter != std::sregex_token_iterator(); ++iter) {
    if (static_cast<std::string>(*iter).empty()) continue;
    // first thing to do is to find quiddity type
    if (!type_found) {
      const auto& str = static_cast<std::string>(*iter);
      if (*str.begin() == '.') {
        if (str.size() == 1) {
          parsing_error_ = "wrong placeholder name (\".\")";
          return false;
        }
        // save the name with the '.' for later check
        if (!previous_quid_.empty()) {
          if (*previous_quid_.begin() == '.') {
            parsing_error_ = "placeholders cannot be connected to each others (" + previous_quid_ +
                             " and " + str + ")";
            return false;
          }
          connections_.push_back(shm_connection_t(previous_quid_, str));
        }
        previous_quid_ = str;
        return true;
      } else {
        if (!valid_types.empty() &&
            valid_types.end() == std::find(valid_types.begin(), valid_types.end(), *iter)) {
          parsing_error_ = static_cast<std::string>(*iter) + " is not a valid quiddity type";
          return false;
        }
        quid.type = *iter;
      }
      type_found = true;
      continue;
    }
    if (*iter == shmr) {
      if (!reader_quid_.empty()) {
        std::string current = quid.name.empty() ? "an other unknown quiddity" : quid.name;
        parsing_error_ = std::string("bundle description can get only one shmdata reader (") +
                         reader_quid_ + " and " + current + " are labelled as shmreader)";
        return false;
      }
      quid.expose_shmr = true;
      continue;
    }
    if (*iter == shmw) {
      quid.expose_shmw = true;
      continue;
    }
    if (*iter == noprop) {
      quid.expose_prop = false;
      continue;
    }
    if (*iter == addtostart) {
      quid.expose_start = true;
      continue;
    }
    if (*iter == top_level) {
      quid.top_level = true;
      continue;
    }
    if (!parse_param(*iter, quid)) return false;
  }

  if (quiddities_.end() !=
      std::find_if(quiddities_.begin(), quiddities_.end(), [&](const quiddity_spec_t& quiddity) {
        return quiddity.name == quid.name;
      })) {
    parsing_error_ =
        std::string("quiddity name ") + quid.name + " is not unique in bundle description";
    return false;
  }
  if (std::string::npos != quid.name.find('_')) {
    parsing_error_ = std::string("underscores are not allowed in quiddity names ") + quid.name;
    return false;
  }

  if (quid.name.empty()) {
    parsing_error_ =
        std::string("quiddity name is missing for quiddity specified with type ") + quid.type;
    return false;
  }
  if (!previous_quid_.empty()) connections_.push_back(shm_connection_t(previous_quid_, quid.name));
  if (quid.expose_shmr) reader_quid_ = quid.name;
  previous_quid_ = quid.name;
  quiddities_.push_back(quid);
  return true;
}
Exemple #11
0
void gerbil::Application::parseParams(const int &argc, char** argv) {
	uint i;
	for (i = 1; i < argc && argv[i][0] == '-'; i++) {
		switch (argv[i][1]) {
		case 'k':
			_k = atoi(argv[++i]);
			break;
		case 'm':
			_m = atoi(argv[++i]);
			break;
		case 'f':
			_tempFilesNumber = atoi(argv[++i]);
			break;
		case 'l':
			_thresholdMin = atoi(argv[++i]);
			break;
		case 't':
			_threadsNumber = atoi(argv[++i]);
			break;
		case 'e': {
			std::string s(argv[++i]);
			boost::regex rgx("(0*[1-9][0-9]*)(M|G)B?");
			boost::smatch match;
			if (!boost::regex_match(s, match, rgx)) {
				std::cout
						<< "invalid value for parameter -e\nuse -h for help\n";
				exit(0);
			}
			_memSize = atoi(match.str(1).c_str());
			if (match.str(2) == "G")
				_memSize *= 1024;
			break;
		}
		case 'd':
			_norm = false;
			break;
		case 'i':
			verbose = true;
			break;
		case 'o': {
			std::string s(argv[++i]);
			if (s == "fasta")
				_outputFormat = of_fasta;
			else if (s == "none")
				_outputFormat = of_none;
			else
				_outputFormat = of_gerbil;
			break;
		}
		case 'x':
			switch(argv[++i][0]) {
			case '1': _singleStep = 1; break;
			case '2': _singleStep = 2; break;
			case 'b': _leaveBinStat = true; break;
			case 'h': _histogram = true; break;
			}
			break;
#ifdef GPU
		case 'g': {
			// determine number of gpus to use
			int num;
			auto err = cudaGetDeviceCount(&num);
			if (err != cudaSuccess) {
				std::cerr << "Error while searching for GPU's: " << cudaGetErrorString(err) << std::endl;
				std::cerr << "Disabling GPU support." << std::endl;
				_numGPUs = 0;
			} else {
				_numGPUs = (uint8_t) std::min(num, 2);
			}
			break;
		}
#endif
		case 's':
			checkSystem();
			exit(0);
		case 'v':
			std::cout << VERSION_MAJOR << "." << VERSION_MINOR << std::endl;
			exit(0);
		case 'h':
			printf("_________________________________________________________________\n");
			printf("Gerbil version %i.%i\n", VERSION_MAJOR, VERSION_MINOR);
			printf("-----------------------------------------------------------------\n");
			printf("usage: gerbil [<option>|<flag>]* <input> <temp> <output>\n");
			printf("<option>:\n");
			printf("  -k <size>             size of kmers (default: 28)\n");
			printf("  -m <size>             size of minimizers (default: auto)\n");
			printf("  -e <size>(M|G)B       size of ram usage (default: auto)\n");
			printf("  -f <number>           number of temporary files (default: %u)\n",
					DEF_TEMPFILES_NUMBER);
			printf("  -t <number>           number of threads (default: auto)\n");
			printf("  -l <count>            minimal count of k-mers (default: %u)\n",
					DEF_THRESHOLD_MIN);
			printf("<flag>:\n");
			printf("  -h                    show help\n");
			printf("  -v                    version\n");
			printf("  -h                    help\n");
			printf("  -d                    disable normalization\n");
			printf("  -i                    verbose output\n");
			printf("  -s                    system check\n");
			printf("  -o <outputFormat>     output format\n");
			printf("      outputFormat:\n");
			printf("         gerbil         gerbil format\n");
			printf("         fasta          fasta format\n");
			printf("         none           no output\n");
#ifdef GPU
			printf("  -g                    enable gpu\n");
#endif
			printf("  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  \n");
			printf("  -x <mode>             Debugging and testing purposes\n");
			printf("                        (can be specified multiple times)\n");
			printf("     modes:\n");
			printf("        1               only step 1, leaves temporary files and a\n");
			printf("                        binStatFile (with statistical stuff)\n");
			printf("                        !Watch out: no <output>\n");
			printf("        2               only step 2, requires temporary files and\n");
			printf("                        the binStatFile\n");
			printf("                        !Watch out: no <input>\n");
			printf("        b               leaves the binStatFile\n");
			printf("        h               saves the data for a histogram of the\n");
			printf("                        uk-mers in the output folder\n");
			printf("-----------------------------------------------------------------\n");
			exit(0);
		}
	}
	IF_REL(if (argc < 4) {
		std::cout << "missing parameters\nuse -h for help\n"
		;
		exit(0)
		;
	});