5

我正在使用Simple-Web-Server库来创建简单的 Web 服务,以便将XML转换为JSON,反之亦然。反过来,它使用了几个boost库以及boost::coroutine。对于XML<->JSON转换,我使用boost::property_tree库进行中间表示。这是代码:

#include <iostream>
#include <sstream>

#include <server_http.hpp>

#define BOOST_SPIRIT_THREADSAFE
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>

using namespace std;
using namespace boost::property_tree;

using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;

int main()
{
  HttpServer server(8080, 1);

  server.resource["^/json_to_xml$"]["POST"] = [](auto& response, auto request) {
    try
    {
      ptree pt;
      read_json(request->content, pt);
      ostringstream json, xml;
      write_json(json, pt);
      clog << "JSON request content:" << endl << json.str() << endl;
      write_xml(xml, pt, xml_writer_make_settings<ptree::key_type>(' ', 1u));
      clog << "XML response content:" << endl << xml.str() << endl;
      response << "HTTP/1.1 200 OK\r\nContent-Length: " << xml.str().length() << "\r\n\r\n" << xml.str();
    }
    catch(const exception& e)
    {
      cerr << "Error:" << endl << e.what() << endl;
      response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
    }
  };

  server.resource["^/xml_to_json$"]["POST"] = [](auto& response, auto request) {
    try
    {
      ptree pt;
      read_xml(request->content, pt, xml_parser::trim_whitespace | xml_parser::no_comments);
      ostringstream xml, json;
      write_xml(xml, pt, xml_writer_make_settings<ptree::key_type>(' ', 1u));
      clog << "XML request content:" << endl << xml.str() << endl;
      write_json(json, pt);
      clog << "JSON response content: " << endl << json.str() << endl;
      response << "HTTP/1.1 200 OK\r\nContent-Length: " << json.str().length() << "\r\n\r\n" << json.str();
    }
    catch(const exception& e)
    {
      cerr << "Error:" << endl << e.what() << endl;
      response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
    }
  };

  server.start();

  return 0;
}

JSONXML的转换工作正常,但相反会导致程序崩溃。当我不在服务器回调中使用boost::property_treeXML解析器时,程序运行良好。是执行的结果。GDB回溯。最后是Valgrind输出。

使用的boost库版本是1.58.0但在最新版本1.61.0中观察到相同的结果。使用Simple-Web-Server的1.4.2版。

4

1 回答 1

3

read_xml() 可能会溢出协程的堆栈;请参阅此处,了解可追溯到 rapidxml 解析器中的 64K 堆栈变量的类似崩溃。

编辑。总结一下链接...事情的要点是,埋在read_xml中的rapidxml解析器在堆栈上分配了64K,这溢出了Linux上的8K默认协程堆栈。您可以尝试两件事......要么强制堆栈变量更小,例如,

#define BOOST_PROPERTY_TREE_RAPIDXML_STATIC_POOL_SIZE 512
#include <boost/property_tree/xml_parser.hpp>

或者在生成协程时分配更大的堆栈(如果可以通过 Simple-Web-Server 访问它)

于 2017-08-03T02:47:46.103 回答