#include "IMFMessage.h" #include "IMFHeader.h" #include "IMFMultipart.h" #include "IMFPlainText.h" #include "Log.h" namespace coreutils { IMFMessage::IMFMessage() { body = NULL; first = true; } IMFMessage::IMFMessage(PString &in) : IMFMessage() { parse(in); } bool IMFMessage::parse(PString &in) { coreutils::Log(coreutils::LOG_DEBUG_4) << "parse [" << in.str() << "]"; if(first) { if(in.str().find(" ") != std::string::npos) { parse(in); first = false; return true; } } if(in.str() != "") { headers.emplace_back(in); return true; } coreutils::Log(coreutils::LOG_DEBUG_2) << "End of header with Content Type = " << getHeader("Content-Type") << " for " << getHeader("Content-Length") << " bytes."; std::string type = getHeader("Content-Type"); if(type.size() == 0) type = "text/plain"; if(type == "multipart/form-data") body = new IMFMultipart(in, getHeaderKeyPairValue("Content-Type", "boundary")); else if(type == "text/plain") body = new IMFPlainText(in); else body = new IMFBody(); return false; } void IMFMessage::output(std::stringstream &out) { for(IMFHeader header: headers) { out << header.getKey() << ": " << header.getValue() << "\r\n"; } out << "\r\n"; } void IMFMessage::addHeader(std::string key, std::string value) { headers.emplace_back(key, value); } std::string IMFMessage::getHeader(std::string key, bool valueOnly) { for(IMFHeader header: headers) { if(header.getKey() == key) { std::string value = header.getValue(); if(valueOnly) { std::vector split = PString(value).split(";"); value = split[0].str(); } return value; } } return std::string(""); } std::string IMFMessage::getHeaderKeyPairValue(std::string headerKey, std::string key) { std::string value; coreutils::PString psource(getHeader(headerKey, false)); std::vector sourcep = psource.split(";"); for(PString work: sourcep) { work.skipWhitespace(); std::string token = work.getTokenExclude("="); if(work.ifNext("=")) { if(token == key) { if(work.ifNext("\"")) { value = work.getTokenExclude("\""); return value; } else { value = work.str(); return value; } } else continue; } else if (work.ifNext(";") || work.ifNext(" ")) { if(token == key) return std::string("true"); else continue; } } return std::string("false"); } IMFBody * IMFMessage::getBody() { return body; } }