#include "IMFMessage.h" #include "IMFHeader.h" #include "IMFMultipart.h" #include "IMFPlainText.h" #include "Log.h" namespace coreutils { IMFMessage::IMFMessage() { body = NULL; } IMFMessage::IMFMessage(PString &in) { parse(in); } bool IMFMessage::parse(PString &in) { Log(LOG_DEBUG_1) << "Parsing-------\n" << in.str(); while (!in.ifNext("\r\n")) { headers.emplace_back(in); } std::string type = getHeader("Content-Type"); std::stringstream length(getHeader("Content-Length")); int len = 0; length >> len; if(len > 0) { PString block = in.readBlock(len); if(type == "multipart/form-data") body = new IMFMultipart(block, getHeaderKeyPairValue("Content-Type", "boundary")); else if(type == "text/plain") body = new IMFPlainText(block); else body = new IMFBody(&block); } 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; } void IMFMessage::setBody(PString *body) { this->body = new IMFBody(body); } }