SP-150 Decode http multipart form data in WebServer.cpp
This commit is contained in:
1 parent
637d7384b1
commit
38964f4d10
4 files changed
+140
-34
No files matched your search
@@ -1,5 +1,71 @@
|
||||
#include "MultipartFormDecoder.h"
|
||||
#include "lib/logging/logging.h"
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include <boost/algorithm/string/iter_find.hpp>
|
||||
|
||||
namespace bts {
|
||||
namespace http {
|
||||
|
||||
using namespace std;
|
||||
|
||||
vector<string> split(const string& contents, const string& deliniator) {
|
||||
vector<string> result;
|
||||
boost::iter_split(result, contents, boost::first_finder(deliniator));
|
||||
return result;
|
||||
}
|
||||
|
||||
std::tuple<std::string, std::map<std::string,std::string>> decode_header(const std::string& header) {
|
||||
auto tokens = split(header, ";");
|
||||
std::string header_name = *tokens.begin();
|
||||
map<string,string> props;
|
||||
for (const auto& token : tokens) {
|
||||
auto equals = token.find('=');
|
||||
if (equals != std::string::npos) {
|
||||
auto key = token.substr(1,equals-1);
|
||||
auto value = token.substr(equals+1);
|
||||
boost::algorithm::trim_if(value,
|
||||
[](char c) { return c == ' ' || c == '"' || c == '\r' || c == '\n'; });
|
||||
props[key] = value;
|
||||
}
|
||||
}
|
||||
return { header_name, props };
|
||||
}
|
||||
|
||||
std::optional<MultiPartFormData> decode_form_data(const string content_type, const string& body) {
|
||||
auto [_,props] = decode_header(content_type);
|
||||
(void)_;
|
||||
auto boundary = props["boundary"];
|
||||
if (boundary.empty()) {
|
||||
LOG(Http,Warn,"Failed to decode boundary in content type '{}'", content_type);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
MultiPartFormData result;
|
||||
auto parts = split(body, "--" + boundary);
|
||||
for (const auto& part : parts) {
|
||||
auto end_headers = part.find("\r\n\r\n");
|
||||
if (end_headers == std::string::npos) continue;
|
||||
if (part == "--\r\n") continue;
|
||||
auto headers = split(part.substr(0,end_headers), "\r\n");
|
||||
|
||||
FormPart form;
|
||||
form.content_type = part.substr(end_headers+2);
|
||||
for (const auto& header : headers) {
|
||||
const char* content_type = "Content-Type: ";
|
||||
if (boost::starts_with(header, content_type)) {
|
||||
form.content_type = header.substr(sizeof(content_type));
|
||||
}
|
||||
else {
|
||||
auto [_, props] = decode_header(header); (void)_;
|
||||
if (!props["filename"].empty()) {
|
||||
form.filename = props["filename"];
|
||||
}
|
||||
}
|
||||
}
|
||||
result.parts.push_back(form);
|
||||
}
|
||||
|
||||
return {result};
|
||||
}
|
||||
|
||||
}} //namespace
|
||||
Reference in new issue
Block a user