Exemplo n.º 1
0
    std::shared_ptr<Response> request(const std::string& request_type, const std::string& path = "/", boost::string_ref content = "",
      const std::map<std::string, std::string>& header = std::map<std::string, std::string>()) {
      std::string corrected_path = path;
      if (corrected_path == "")
        corrected_path = "/";

      boost::asio::streambuf write_buffer;
      std::ostream write_stream(&write_buffer);
      write_stream << request_type << " " << corrected_path << " HTTP/1.1\r\n";
      write_stream << "Host: " << host << "\r\n";
      for (auto& h : header) {
        write_stream << h.first << ": " << h.second << "\r\n";
      }
      if (content.size()>0)
        write_stream << "Content-Length: " << content.size() << "\r\n";
      write_stream << "\r\n";

      try {
        connect();

        boost::asio::write(*socket, write_buffer);
        if (content.size()>0)
          boost::asio::write(*socket, boost::asio::buffer(content.data(), content.size()));

      }
      catch (const std::exception& e) {
        socket_error = true;
        throw std::invalid_argument(e.what());
      }

      return request_read();
    }
void CInfixExpressionCalculator::SkipSpaces(boost::string_ref &ref)
{
    size_t i = 0;
    while (i < ref.size() && std::isspace(ref[i]))
        ++i;
    ref.remove_prefix(i);
}
Exemplo n.º 3
0
Protocol CHttpUrl::CheckProtocol(boost::string_ref const &url, size_t &index)
{
	Protocol protocol;
	auto pos = url.find("://");
	if (pos != url.size())
	{
		if (url.substr(0, pos) == "https")
		{	
			protocol = Protocol::HTTPS;
		}
		else if (url.substr(0, pos) == "http")
		{
			protocol = Protocol::HTTP;
		}
		else
		{
			throw std::invalid_argument("Protocol uncorrect.");
		}
		if (index == url.size())
		{
			throw std::invalid_argument("Invalid url was introduced");
		}
	}
	index = pos + 3;
	return protocol;
}
double CInfixExpressionCalculator::ParseExprSum(boost::string_ref &ref)
{
    double value = ParseExprMul(ref);
    while (true)
    {
        SkipSpaces(ref);

        if (!ref.empty() && ref[0] == '+')
        {
            ref.remove_prefix(1);
            value += ParseExprMul(ref);
        }
        else if (!ref.empty() && ref[0] == '-')
        {
            ref.remove_prefix(1);
            value -= ParseExprMul(ref);
        }
        else
        {
            break;
        }
    }

    return value;
}
Exemplo n.º 5
0
			std::vector<std::pair<boost::string_ref, boost::string_ref>>::const_iterator find(const boost::string_ref key) const
			{
				return std::find_if(m_collection.begin(), m_collection.end(),
					[key](const std::pair<boost::string_ref, boost::string_ref>& str)-> bool
				{
					auto oneSize = str.first.size();
					auto twoSize = key.size();

					if (oneSize != twoSize)
					{
						return false;
					}

					if (oneSize >= 4)
					{
						if ((str.first[0] == key[0]) && 
							(str.first[1] == key[1]) && 
							(str.first[oneSize - 1] == key[oneSize - 1]) && 
							(str.first[oneSize - 2] == key[oneSize - 2]))
						{
							return std::memcmp(str.first.begin(), key.begin(), oneSize) == 0;
						}
					}
					else
					{
						return std::memcmp(str.first.begin(), key.begin(), oneSize) == 0;
					}

					return false;
				}
				);
			}
Exemplo n.º 6
0
 void print_string(boost::string_ref str, std::ostream& out)
 {
     for (boost::string_ref::const_iterator cur = str.begin();
         cur != str.end(); ++cur)
     {
         print_char(*cur, out);
     }
 }
Exemplo n.º 7
0
	void DatabaseImpl::checkSimpleArgumentFor(const boost::string_ref& key, partNum_t partNum) const
	{
		RAISE_INVALID_ARGUMENT_IF(key.size() > MAX_KEY_SIZE, "key too long");
		RAISE_INVALID_ARGUMENT_IF(key.empty(), "empty key is not allowed");
		RAISE_INVALID_ARGUMENT_IF(partNum > MAX_PARTNUM, "partNum is too large");
		RAISE_INVALID_ARGUMENT_IF(partNum == ALL_PARTS, "partNum ALL_PARTS is not allowed");
		RAISE_INVALID_ARGUMENT_IF(partNum < 0, "negative partNum is not allowed");
	}
Exemplo n.º 8
0
  inline boost::string_ref remove_leading_spaces(boost::string_ref string, const char* spaces = " \t\r\n")
  {
    auto pos = string.find_first_not_of(spaces);
    if (pos == std::string::npos) pos = string.size();

    string.remove_prefix(pos);
    return string;
  }
Exemplo n.º 9
0
std::string codegen_base::cpp_name(boost::string_ref name)
{
  std::string result;
  if (!std::isalpha(name[0]))
    result = "_";
  std::transform(name.begin(), name.end(), std::back_inserter(result),
                 [] (char c) { return std::isalnum(c) ? c : '_'; });
  return result;
}
Exemplo n.º 10
0
  inline boost::string_ref extract_word(boost::string_ref string)
  {
    const char spaces[] = " \t\r\n";
    string = remove_leading_spaces(string, spaces);

    auto new_size = string.find_first_of(spaces);
    if (new_size == boost::string_ref::npos) new_size = string.size();

    return boost::string_ref(string.data(), new_size);
  }
Exemplo n.º 11
0
	inline bool is_emm_file(boost::string_ref path) 
	{
		std::ifstream ifs( convert_code( path, CP_UTF8, CP_OEMCP ), std::ios::binary );
		if( ifs.fail() ) {
			return false;
		}

		std::istreambuf_iterator< char > first( ifs ), last;
		boost::string_ref const seg( "[Info]\r\nVersion = 3\r\n" );

		return std::search( first, last, seg.begin(), seg.end() ) != last;
	}
Exemplo n.º 12
0
		bool operator()(const boost::string_ref& strRef1, const boost::string_ref& strRef2) const
		{
			auto oneSize = strRef1.size();
			auto twoSize = strRef2.size();

			if (oneSize != twoSize)
			{
				return false;
			}

			return std::memcmp(strRef1.begin(), strRef2.begin(), oneSize) == 0;
		}
Exemplo n.º 13
0
 void
 on_response(int status_,
     boost::string_ref const& reason_,
         int version_, error_code& ec)
 {
     status = status_;
     reason = std::string(
         reason_.data(), reason_.size());
     version = version_;
     got_on_begin = true;
     if(fc_)
         fc_->fail(ec);
 }
Exemplo n.º 14
0
	AttributeSelector::AttributeSelector(SelectorOperator op, boost::string_ref key, boost::string_ref value) :
		m_operator(op),
		m_attributeNameString(key.to_string()),
		m_attributeNameRef(m_attributeNameString),
		m_attributeValueString(value.to_string()),
		m_attributeValueRef(m_attributeValueString)
	{
		if (m_attributeNameRef.size() == 0)
		{
			throw std::runtime_error(u8"In AttributeSelector::AttributeSelector(SelectorOperator, boost::string_ref, const bool) - Supplied attribute identifier has zero length.");
		}

		if (m_attributeValueRef.size() == 0)
		{
			throw std::runtime_error(u8"In AttributeSelector::AttributeSelector(SelectorOperator, boost::string_ref, const bool) - Supplied attribute value has zero length.");
		}

		if (m_operator == SelectorOperator::ValueContainsElementInWhitespaceSeparatedList)
		{
			if (m_attributeNameRef.find_first_of(u8"\t\r\n ") != std::string::npos)
			{
				throw std::runtime_error(u8"In AttributeSelector::AttributeSelector(SelectorOperator, boost::string_ref, const bool) - Constructed ValueContainsElementInWhitespaceSeparatedList attribute selector, but spaces exist in the search value. This is not allowed.");
			}
		}

		#ifndef NDEBUG
			#ifdef GQ_VERBOSE_DEBUG_NFO
				std::cout << "Built AttributeSelector with operator " << static_cast<size_t>(m_operator) << " with key " << m_attributeNameRef << " looking for value " << m_attributeValueRef << std::endl;
			#endif
		#endif

		switch (m_operator)
		{
			case SelectorOperator::ValueEquals:
			case SelectorOperator::ValueContainsElementInWhitespaceSeparatedList:
			{
				AddMatchTrait(m_attributeNameRef, m_attributeValueRef);
			}
			break;

			case SelectorOperator::Exists:
			case SelectorOperator::ValueContains:
			case SelectorOperator::ValueHasPrefix:
			case SelectorOperator::ValueHasSuffix:
			case SelectorOperator::ValueIsHyphenSeparatedListStartingWith:
			{
				AddMatchTrait(m_attributeNameRef, SpecialTraits::GetAnyValue());
			}
			break;
		}
	}
Exemplo n.º 15
0
Protocol CHttpUrl::ParseProtocol(boost::string_ref & str)
{
	const string schemeDelimiter = "://";
	auto schemePos = str.find(schemeDelimiter);
	if (schemePos == boost::string_ref::npos)
	{
		throw CUrlParsingError("Protocol parsing error");
	}
	string protocol = str.substr(0, schemePos).to_string();

	str = str.substr(schemePos + schemeDelimiter.size() , str.size() - 1);

	return ToProtocol(protocol);
}
Exemplo n.º 16
0
 void
 on_request(
     boost::string_ref const& method_,
         boost::string_ref const& path_,
             int version_, error_code& ec)
 {
     method = std::string(
         method_.data(), method_.size());
     path = std::string(
         path_.data(), path_.size());
     version = version_;
     got_on_begin = true;
     if(fc_)
         fc_->fail(ec);
 }
Exemplo n.º 17
0
void url::
rebuild(const boost::string_ref &scheme,
        const boost::optional<boost::string_ref> &host,
        const boost::optional<uint16_t> &port,
        const boost::optional<boost::string_ref> &path,
        const boost::optional<boost::string_ref> &query,
        const boost::optional<boost::string_ref> &fragment,
        const boost::optional<boost::string_ref> &user_info)
{
    std::string str;

    str.append(scheme.data(), scheme.size());
    if (has_authority()) {
        str.append("://");

        if (user_info) {
            str.append(user_info->data(), user_info->size());
            str.append("@");
        }

        str.append(host->data(), host->size());

        if (port) {
            str.append(":");
            str.append(std::to_string(*port));
        }
    }
    else {
        str.append(":");
    }

    if (path) {
        str.append(path->data(), path->size());
    }

    if (query) {
        str.append("?");
        str.append(query->data(), query->size());
    }

    if (fragment) {
        str.append("#");
        str.append(fragment->data(), fragment->size());
    }

    url new_url { std::move(str) };
    swap(new_url);
}
Exemplo n.º 18
0
std::string get_directory_listing( boost::string_ref folder ) {
	namespace fs = boost::filesystem;
	fs::path p { folder.to_string( ) };
	std::ostringstream ss;
	try {
		if( exists( p ) ) {
			if( fs::is_regular_file( p ) ) {
				ss << p << " size is " << fs::file_size( p ) << "\r\n";
			} else if( fs::is_directory( p ) ) {
				ss << p << " is a directory containing:\n";
				std::copy( fs::directory_iterator( p ), fs::directory_iterator( ), std::ostream_iterator<fs::directory_entry>( ss, "\r\n" ) );
			} else {
				ss << p << " exists, but is neither a regular file nor a directory\n";
			}
		} else {
			ss << p << " does not exist\n";
		}
	}

	catch( const fs::filesystem_error& ex ) {
		ss << "ERROR: " << ex.what( ) << '\n';
	}

	return ss.str( );
}
Exemplo n.º 19
0
 id_placeholder::id_placeholder(
         unsigned index,
         boost::string_ref id,
         id_category category,
         id_placeholder const* parent_)
   : index(index),
     unresolved_id(parent_ ?
         parent_->unresolved_id + '.' + detail::to_s(id) :
         detail::to_s(id)),
     id(id.begin(), id.end()),
     parent(parent_),
     category(category),
     num_dots(boost::range::count(id, '.') +
         (parent_ ? parent_->num_dots + 1 : 0))
 {
 }
Exemplo n.º 20
0
 table_features(
       std::uint8_t const table_id
     , boost::string_ref const name
     , std::uint64_t const metadata_match
     , std::uint64_t const metadata_write
     , std::uint32_t const config
     , std::uint32_t const max_entries
     , properties_type properties)
   : table_features_{
         properties.calc_ofp_length(sizeof(ofp_type))
       , table_id
       , { 0, 0, 0, 0, 0 }
       , ""
       , metadata_match
       , metadata_write
       , config
       , max_entries
     }
   , properties_(std::move(properties))
 {
   auto const name_size
     = std::min(name.size(), sizeof(table_features_.name) - 1);
   using boost::adaptors::sliced;
   boost::copy(name | sliced(0, name_size), table_features_.name);
 }
Exemplo n.º 21
0
				base::OptionalError read_file( boost::string_ref path, base::data_t & buffer, bool append_buffer ) {
					std::ifstream in_file( path.to_string( ), std::ifstream::ate | std::ifstream::binary );
					if( !in_file ) {
						auto result = base::create_optional_error( "Could not open file" );
						result->add( "where", "read_file#open" );
						return result;
					}

					auto fsize = in_file.tellg( );
					if( fsize < 0 ) {
						auto result = base::create_optional_error( "Error reading file length" );
						result->add( "where", "read_file#tellg" );
						return result;
					}
					if( !in_file.seekg( 0 ) ) {
						auto result = base::create_optional_error( "Error reseting file position to beginning" );
						result->add( "where", "read_file#seekg" );
						return result;
					}

					size_t first_pos = append_buffer ? buffer.size( ) : 0;
					buffer.resize( first_pos + static_cast<size_t>(fsize) );

					if( !in_file.read( buffer.data( ) + first_pos, fsize ) ) {
						auto result = base::create_optional_error( "Error reading file" );
						result->add( "where", "read_file#read" );
						return result;
					}
					return base::create_optional_error( );
				}
Exemplo n.º 22
0
	inline bool drive_letter_exists(Iterator itr, Iterator end)
	{
		boost::string_ref const str( ":\\" );

		if( std::distance( itr, end ) < static_cast< std::ptrdiff_t >( str.size() + 1 ) ) {
			return false;
		}

		for( int i = 'A'; i <= 'Z'; ++i ) {
			if( *itr == i ) {
				return std::equal( str.begin(), str.end(), itr + 1 );
			}
		}

		return false;
	}
Exemplo n.º 23
0
unsigned short CHttpUrl::ParsePort(boost::string_ref const &url, size_t index)
{
	std::string port;
	if (index == url.size() || (index < url.size() && !isdigit(url[index])))
	{
		throw CUrlParsingError("Unknown port in the url address");
	}
	for (; index != url.size(); ++index)
	{
		if (!isdigit(url[index]))
		{
			break;
		}
		port += url[index];
	}
	return static_cast<unsigned short>(atoi(port.c_str()));
}
Exemplo n.º 24
0
unsigned short CHttpUrl::ParsePort(boost::string_ref & str)
{
	if (str.front() == ':')
	{
		auto portPos = str.find('/');
		string port;
		if (portPos == boost::string_ref::npos)
		{
			port = str.substr(1, str.size()).to_string();
		}
		else
		{
			port = str.substr(1, portPos - 1).to_string();
		}
		str = str.substr(port.size() + 1, str.size());
		bool portOk = !port.empty();
		if (portOk)
		{
			try
			{
				return boost::lexical_cast<unsigned short>(port);
			}
			catch (...)
			{
				portOk = false;
			}
		}
		if (!portOk)
		{
			throw CUrlParsingError("Port parsing error");
		}
	}
	return  0;
}
Exemplo n.º 25
0
bool ssl_options_t::has_strong_verification(boost::string_ref host) const noexcept
{
  // onion and i2p addresses contain information about the server cert
  // which both authenticates and encrypts
  if (host.ends_with(".onion") || host.ends_with(".i2p"))
    return true;
  switch (verification)
  {
    default:
    case ssl_verification_t::none:
    case ssl_verification_t::system_ca:
      return false;
    case ssl_verification_t::user_certificates:
    case ssl_verification_t::user_ca:
      break;
  }
  return true;
}
Exemplo n.º 26
0
void
history::add (const boost::string_ref& text)
{
	this->lines[this->realpos] = text.to_string();
	this->realpos++;
	if (this->realpos == HISTORY_SIZE)
		this->realpos = 0;
	this->pos = this->realpos;
}
Exemplo n.º 27
0
std::string CHttpUrl::ParseDomainName(boost::string_ref const &url, size_t &index)
{
	for (size_t i = 0; i != url.size(); ++i)
	{
		if (url[i] == '/')
		{
			index += i;
			return std::string(url.substr(0, i));
		}
		if (url[i] == ':')
		{
			m_port = ParsePort(url, i + 1);
			return std::string(url.substr(0, i));
		}
	}
	index += url.size();
	return std::string(url);
}
Exemplo n.º 28
0
	explicit glob_matcher(const boost::string_ref pat)
	noexcept : m_pat{pat}
	{
		// If we are in debug mode, ensure that the pattern is valid.
		assert(m_pat.length() > 0);

		#ifndef NDEBUG
		auto i = 0u;

		/*
		** The following sequences are considered to be syntax
		** violations when they occur within glob patterns:
		**
		**   1. Special characters within groups.
		**   2. Empty groups.
		**   3. Any backslash not followed by a special character; this
		**   includes trailing backslashes.
		*/
		do switch (m_pat[i]) {
		default:
		case '*':
		case '?':     ++i;                            continue;
		case '[':     assert(pat[++i] != ']');        goto group_mode;
		// Ensure that the character escaped using a backslash is a
		// special character.
		case '\\':    assert(is_glob(pat[++i])); ++i; continue;
		regular_mode:                                 continue;
		} while (i != pat.length());
		return;
		
		// Check to ensure that the current group is valid.
	group_mode:
		for(;;) switch (m_pat[i]) {
		default:   ++i;                            continue;
		case ']':  ++i;                            goto regular_mode;
		case '\\': assert(is_glob(pat[++i])); ++i; continue;
		case '*':
		case '?':
		case '\0': assert(false && "Invalid group.");
		}

		#endif
	}
Exemplo n.º 29
0
    std::string encode_string(boost::string_ref str)
    {
        std::string result;
        result.reserve(str.size());

        for (boost::string_ref::const_iterator it = str.begin();
            it != str.end(); ++it)
        {
            switch (*it)
            {
                case '<': result += "&lt;";    break;
                case '>': result += "&gt;";    break;
                case '&': result += "&amp;";   break;
                case '"': result += "&quot;";  break;
                default:  result += *it;       break;
            }
        }

        return result;
    }
Exemplo n.º 30
0
std::string
escaped_string(boost::string_ref const& s)
{
    std::string out;
    out.reserve(s.size());
    char const* p = s.data();
    while(p != s.end())
    {
        if(*p == '\r')
            out.append("\\r");
        else if(*p == '\n')
            out.append("\\n");
        else if(*p == '\t')
            out.append("\\t");
        else
            out.append(p, 1);
        ++p;
    }
    return out;
}