#include "MultipartFormDecoder.h" #include "lib/logging/logging.h" #include #include namespace bts { namespace http { using namespace std; vector split(const string& contents, const string& deliniator) { vector result; boost::iter_split(result, contents, boost::first_finder(deliniator)); return result; } std::tuple> decode_header(const std::string& header) { auto tokens = split(header, ";"); std::string header_name = *tokens.begin(); map 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 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