// STEP 3: parse the body
  size_t Frame::parse_body(boost::asio::streambuf& _response)
  {
	  std::size_t _content_length = 0, bytecount = 0;
	  string _str;
	//debug_print("Frame parser phase 3");
	// special case: content-length
	if (m_headers.find("content-length") != m_headers.end()) {
		string& val = m_headers["content-length"];
		//debug_print(boost::format("phase 3: body content-length==%1%") % val);
		_content_length = lexical_cast<size_t>(val);
	}
	if (_content_length > 0) {
		bytecount += _content_length;
		// read back the body byte by byte
		const char* rawdata = boost::asio::buffer_cast<const char*>(_response.data());
		for (size_t i = 0; i < _content_length; i++ ) {
			m_body << rawdata[i];
		}
	} else {
		// read all bytes until the first NULL
		mygetline(_response, _str, '\0');
		bytecount += _str.size();
		m_body << _str;
	}
	bytecount += 1; // for the final frame-terminating NULL
	//debug_print(boost::format("phase 3: consumed %1% bytes, BODY(%2% bytes)==%3%") % bytecount % _str.size() % _str);
	_response.consume(bytecount);
	return(bytecount);
  }
Exemple #2
0
static std::string to_string(boost::asio::streambuf& buffer)
{
    boost::asio::streambuf::const_buffers_type bufs = buffer.data();
    std::string data(
        boost::asio::buffers_begin(bufs),
        boost::asio::buffers_begin(bufs) + buffer.size());
    return std::move(data);
}
Exemple #3
0
bool EmptyData::Fill(boost::asio::streambuf& buf)
{
	assert(Size() != UNDEFINED_SIZE);

	uint32_t pos = Pos();
	const uint32_t copyBytes = std::min(buf.size(), Size() - pos);
	buf.consume(copyBytes);
	SetPos(pos + copyBytes);

	return true;
}
Exemple #4
0
		void on_recv_(const boost::system::error_code& error, size_t bytes_transferred)
		{
			if(error && error != boost::asio::error::eof) {
				std::cout << "receive failed: " << error.message() << std::endl;
			} else {
				const char* data = asio::buffer_cast<const char*>(recv_.data());
				std::cout << "response(" << bytes_transferred << "): ";
				std::cout << data << std::endl;
				recv_.consume(recv_.size());
				read_trg_ = true;
			}
		}
  // my own version of getline for an asio streambuf
inline void mygetline (boost::asio::streambuf& sb, string& _str, char delim = '\n') {
	const char* line = boost::asio::buffer_cast<const char*>(sb.data());
	char _c;
	size_t i;
	_str.clear();
	for( i = 0;
		((i < sb.size()) && ((_c = line[i]) != delim));
		i++
	) _str += _c;
	//debug_print( boost::format("mygetline: i=%1%, sb.size()==%2%") % i % sb.size() );
	//hexdump(_str.c_str(), _str.size());
}
Exemple #6
0
    void handle_line(const boost::system::error_code& error, size_t bytes_received) {
        if(!error) {
            boost::asio::streambuf::const_buffers_type bufs = m_buffer.data();
            std::string line(boost::asio::buffers_begin(bufs),
                             boost::asio::buffers_begin(bufs) + bytes_received);

            std::cerr << "Sentence: " << line << std::endl;

            m_buffer.consume(bytes_received);

            read_next();
        } else {
            std::cerr << "Error: " << error << std::endl;
        }
    }
  // construct STOMP frame (command & header) from a streambuf
  // --------------------------------------------------
  Frame::Frame(boost::asio::streambuf& stomp_response, const stomp_server_command_map_t& cmd_map)
  // --------------------------------------------------
  {
		string _str;

		try {
			// STEP 1: find the next STOMP command line in stomp_response.
			// Chomp unknown lines till the buffer is empty, in which case an exception is raised
			//debug_print(boost::format("Frame parser phase 1, stomp_response.size()==%1%") % stomp_response.size());
			//hexdump(boost::asio::buffer_cast<const char*>(stomp_response.data()), stomp_response.size());
			while (stomp_response.size() > 0) {
				mygetline(stomp_response, _str);
				//hexdump(_str.c_str(), _str.length());
				stomp_response.consume(_str.size() + 1); // plus one for the newline
				if (cmd_map.find(_str) != cmd_map.end()) {
					//debug_print(boost::format("phase 1: COMMAND==%1%, sb.size==%2%") % _str % stomp_response.size());
					m_command = _str;
					break;
				}
			}
			// if after all this trouble m_command is not set, and there's no more data in stomp_response
			// (which shouldn't happen since we do async_read_until the double newline), then throw an exception
			if (m_command == "") throw(NoMoreFrames());

			// STEP 2: parse all headers
			//debug_print("Frame parser phase 2");
			vector< string > header_parts;
			while (stomp_response.size() > 0) {
				mygetline(stomp_response, _str);
				stomp_response.consume(_str.size()+1);
				boost::algorithm::split(header_parts, _str, is_any_of(":"));
				if (header_parts.size() > 1) {
					string& key = decode_header_token(header_parts[0]);
					string& val = decode_header_token(header_parts[1]);
					//debug_print(boost::format("phase 2: HEADER[%1%]==%2%") % key % val);
					m_headers[key] = val;
					//
				} else {
					// no valid header line detected, on to the body scanner
					break;
				}
			}
			//
		} catch(NoMoreFrames& e) {
			//debug_print("-- Frame parser ended (no more frames)");
			throw(e);
		}
  };
Exemple #8
0
//===========================================================================
void CHttpClient::DoReadHeaders (const boost::system::error_code & err) {
    if (err) {
        printf("%s\n", __FUNCTION__);
        cout<<"Error: "<<err.message()<<endl;
        return;
    }

    istream responseStream(&m_response);
    string header;
    while (getline(responseStream, header) && header != "\r")
        cout<<header<<endl;
    cout<<endl;

    if (m_response.size() > 0)
        cout<<&m_response;

    auto handler = boost::bind(
        &CHttpClient::DoReadContent,
        this,
        boost::asio::placeholders::error
    );
    boost::asio::async_read(
        m_socket,
        m_response,
        boost::asio::transfer_at_least(1),
        handler
    );
}
Exemple #9
0
/// @brief Helper function that extracts a string from a streambuf.
std::string make_string(
  boost::asio::streambuf& streambuf,
  std::size_t n)
{
  return std::string(buffers_begin(streambuf.data()),
                     buffers_begin(streambuf.data()) + n);
}
		/// Parse some data. The enum return value is good when a complete request has
		/// been parsed, bad if the data is invalid, indeterminate when more data is
		/// required. The InputIterator return value indicates how much of the input
		/// has been consumed.
		result_type parse(boost::asio::streambuf& buf)
		{
			int c = EOF;
			while ((c = buf.sbumpc()) != EOF)
			{
				result_type result = consume(c);
				if (result == good || result == bad)
				{
					std::string url = urldecode(url_);
					std::string::size_type qmak_pos = url.find("?");
					if (qmak_pos == std::string::npos)
					{
						path_ = url;
					}
					else
					{
						path_ = url.substr(0, qmak_pos);
						std::string quert_str = url.substr(qmak_pos + 1, url.size());
						query_ = query_parser(quert_str);
					}
					return result;
				}
			}
			return indeterminate;
		}
Exemple #11
0
 size_t read_some( AsyncReadStream& s, boost::asio::streambuf& buf )
 {
     char buffer[1024];
     size_t bytes_read = read_some( s, boost::asio::buffer( buffer, sizeof(buffer) ) );
     buf.sputn( buffer, bytes_read );
     return bytes_read;
 }
Exemple #12
0
std::string log_request_helper(const boost::asio::streambuf& buf)
{
    boost::asio::const_buffers_1 b = static_cast<boost::asio::const_buffers_1>(buf.data());
    boost::iterator_range<const char*> ib(buffer_cast<const char*>(b),
            buffer_cast<const char*>(b) + buffer_size(b));
    return string(ib.begin(), ib.end());
}
Exemple #13
0
bool ConstByte::Fill(boost::asio::streambuf& buf)
{
	const char* cp = boost::asio::buffer_cast<const char*>(buf.data());
	if (static_cast<const char>(_expectedValue) != *cp) {
		return false;
	}
	return FixedSizeData<1>::Fill(buf);
}
Exemple #14
0
void MkvTransfer::stream_header(
    StreamInfo const & info,
    boost::asio::streambuf & buf)
{
    //每添加一个流需要添加一个track_entry
    MkvTrackEntry track_entry;
    track_entry.TrackNumber = info.index + 1;
    std::vector<boost::uint8_t> tem(4, (boost::uint8_t)(info.index + 1));
    track_entry.TrackUID = tem;
    track_entry.Language = "eng";
    if (info.type == MEDIA_TYPE_VIDE) {
        track_entry.TrackType = MkvTrackType::VIDEO;
        track_entry.CodecID = "V_MPEG4/ISO/AVC";
        track_entry.CodecPrivate = info.format_data;
        track_entry.Video.PixelWidth = info.video_format.width;
        track_entry.Video.PixelHeight = info.video_format.height;
        track_entry.Video.Size = track_entry.Video.data_size();
    } else if (info.type == MEDIA_TYPE_AUDI) {
        track_entry.TrackType = MkvTrackType::AUDIO;
        track_entry.CodecID = "A_AAC";
        track_entry.CodecPrivate = info.format_data;
        track_entry.Audio.SamplingFrequency =
            (float)info.audio_format.sample_rate;
        track_entry.Audio.Channels =
            info.audio_format.channel_count;
        //track_entry.Audio.BitDepth =
        //    mediainfoex.audio_format.sample_size * 8;
        track_entry.Audio.Size = track_entry.Audio.data_size();
    } else {
        track_entry.TrackType = MkvTrackType::SUBTITLE;
        track_entry.CodecID = "S_TEXT/UTF-8";
    }

    EBML_DataSizeArchive dsa;
    dsa >> track_entry;

    size_t old_size = buf.size();

    util::archive::BigEndianBinaryOArchive<> oa(buf);
    oa << track_entry;

    assert(old_size + track_entry.byte_size() == buf.size());
}
Exemple #15
0
	void run_event_loop_until_frame_received()
	{
		using boost::bind;
		have_frame = false;
		buffer.consume(buffer.size());
		last_error = boost::system::error_code();
		boost::asio::async_read_until(socket,
									  buffer,
									  "END\r\n",
									  bind(&TimedSessionBase::handle_frame_reception,
										   this,
										   boost::asio::placeholders::error,
										   boost::asio::placeholders::bytes_transferred));
		service.reset();
		while (!last_error && !have_frame) {
			service.poll();
			service.reset();
			check_if_timed_out();
		}
	}
void StreamDemuxer::Push(boost::asio::streambuf& stream)
{
	while (stream.size()) {
		if (_packet->Fill(stream)) {
			if (_packet->IsFull()) {
				_downStream->Push(_packet);
				_packet = std::make_shared<LiveViewPacket>();
			}
		}
	}
}
Exemple #17
0
void Dump(boost::asio::streambuf& buf)
{
	std::ofstream ofs("out.dat", std::ios::binary | std::ios::trunc);
	if (!ofs) {
		cout << "dump failed" << endl;
		return;
	}

	cout << "content size:" << buf.size() << endl;
	ofs << &buf;
}
Exemple #18
0
void webqq::async_fetch_cface_std_saver( boost::system::error_code ec, boost::asio::streambuf& buf, std::string cface, boost::filesystem::path parent_path)
{
	if (!fs::exists(parent_path)){
		fs::create_directories(parent_path);
	}

	if (!ec || ec == boost::asio::error::eof){
		std::string imgfilename = (parent_path / cface).string();
		std::ofstream cfaceimg(imgfilename.c_str(), std::ofstream::binary|std::ofstream::out);
		cfaceimg.write(boost::asio::buffer_cast<const char*>(buf.data()), boost::asio::buffer_size(buf.data()));
	}
}
	void operator()( boost::system::error_code ec, boost::asio::streambuf & buf, std::string cface )
	{
 		using namespace boost::asio::detail;

		if( !ec || ec == boost::asio::error::eof )
		{
			std::ofstream cfaceimg( ( std::string( "images/" ) + cface ).c_str(), std::ofstream::openmode(std::ofstream::binary | std::ofstream::out) );
			cfaceimg.write( boost::asio::buffer_cast<const char*>( buf.data() ), boost::asio::buffer_size( buf.data() ) );
			ec = boost::system::error_code();
		}

		io_service.post( bind_handler( handler, ec));
	}
int proto_get_one_package(tcp::socket *socket, boost::asio::streambuf &buff,
                          boost::uint8_t *packet_no)
{
  unsigned long packet_length;
  if (proto_read_package_header(socket, buff, &packet_length, packet_no))
    return 0;
  std::streamsize inbuffer= buff.in_avail();
  if (inbuffer < 0)
    inbuffer= 0;
  if (packet_length > inbuffer)
    boost::asio::read(*socket, buff,
                      boost::asio::transfer_at_least(packet_length-inbuffer));

  return packet_length;
}
Exemple #21
0
boost::optional<rc_result> parse_rc_response(const boost::asio::streambuf& buf)
{
    typedef boost::asio::streambuf::const_buffers_type const_buffers_type;
    typedef boost::asio::buffers_iterator<const_buffers_type> iterator;
    const_buffers_type buffers = buf.data();
    iterator begin = iterator::begin(buffers);
    iterator end = iterator::end(buffers);

    // Look for the start of the body of the response
    boost::iterator_range<const char*> delim = boost::as_literal("\r\n\r\n");
    std::pair<iterator, bool> result = boost::asio::detail::partial_search(
        begin, end, delim.begin(), delim.end());
    if (result.first != end && result.second)
    {
        iterator start = result.first + delim.size();

        // Skip a line
        delim = boost::as_literal("\r\n");
        result = boost::asio::detail::partial_search(start, end,
                delim.begin(), delim.end());
        if (result.first != end && result.second)
        {
            // todo: we can optimise parsing here
            std::string d;
            start = result.first + delim.size();
            std::copy(start, end, std::back_inserter(d));

            rc_result res;
            try
            {
                std::istringstream iss(d);
                iss >> res.ok;
                iss >> res.sum1;
                iss >> res.sum2;
                iss >> res.sum3;
                iss >> res.sum4;
            }
            catch (...)
            {
                return boost::optional<rc_result>();
            }

            return boost::optional<rc_result>(res);
        }
 size_t size() {
     return streambuf.size();
 }
Exemple #23
0
/// @brief Convert a streambuf to a string.
std::string make_string(boost::asio::streambuf& streambuf)
{
  return std::string(buffers_begin(streambuf.data()),
                     buffers_end(streambuf.data()));
}