emaildocumententry.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. /*
  2. * This file is part of QtEmailFetcher project: Email parser for C++ Qt.
  3. *
  4. * GPLv3+ (c) acetone, 2023
  5. */
  6. #include "emaildocumententry.h"
  7. #include "emaildocument.h"
  8. #include <QDebug>
  9. enum class ParseState {
  10. contentType,
  11. other
  12. };
  13. EmailDocumentEntry::EmailDocumentEntry(QList<QSharedPointer<EmailDocumentEntry>> *attachments) : m_pAttachments(attachments)
  14. {
  15. }
  16. void EmailDocumentEntry::parse(const QByteArray &data)
  17. {
  18. m_rawData = data;
  19. QString boundary;
  20. QString charset;
  21. m_contentType = parseContentType(data, &m_name, &boundary, &charset);
  22. if (boundary.isEmpty())
  23. {
  24. if (parseTransferEncoding(data) == TransferEncoding::base64)
  25. {
  26. m_content = QByteArray::fromBase64(rawPayload().trimmed()).trimmed();
  27. }
  28. else
  29. {
  30. m_content = rawPayload().trimmed();
  31. }
  32. if (m_contentType.enumerate == EmailDocumentEntry::ContentType::Enum::textOther or
  33. m_contentType.enumerate == EmailDocumentEntry::ContentType::Enum::textPlain)
  34. {
  35. QTextStream stream(m_content);
  36. stream.setCodec(charset.toStdString().c_str());
  37. m_content = stream.readAll().toUtf8();
  38. }
  39. return;
  40. }
  41. if (m_contentType.enumerate == EmailDocumentEntry::ContentType::Enum::multipartRelated or
  42. m_contentType.enumerate == EmailDocumentEntry::ContentType::Enum::multipartMixed or
  43. m_contentType.enumerate == EmailDocumentEntry::ContentType::Enum::multipartAlternative or
  44. m_contentType.enumerate == EmailDocumentEntry::ContentType::Enum::multipartOther)
  45. {
  46. multipart(data);
  47. return;
  48. }
  49. // Other MIME types (non-multipart)
  50. QSharedPointer<EmailDocumentEntry> entry(new EmailDocumentEntry(m_pAttachments));
  51. entry->parse(rawPayload());
  52. if (m_pAttachments != nullptr) m_pAttachments->push_back(entry);
  53. }
  54. QByteArray EmailDocumentEntry::rawPayload() const
  55. {
  56. int pos = m_rawData.indexOf("\n\n");
  57. if (pos < 0)
  58. {
  59. pos = m_rawData.indexOf("\r\n\r\n");
  60. }
  61. if (pos < 0)
  62. {
  63. return QByteArray();
  64. }
  65. return m_rawData.mid(pos).trimmed();
  66. }
  67. QByteArray EmailDocumentEntry::rawHeaders() const
  68. {
  69. int pos = m_rawData.indexOf("\n\n");
  70. if (pos < 0)
  71. {
  72. pos = m_rawData.indexOf("\r\n\r\n");
  73. }
  74. if (pos < 0)
  75. {
  76. return QByteArray();
  77. }
  78. return m_rawData.mid(0, pos).trimmed();
  79. }
  80. void EmailDocumentEntry::multipart(QByteArray section)
  81. {
  82. QString lineDelimiter = primaryLineDelimiter(section);
  83. if (lineDelimiter.isEmpty())
  84. {
  85. qWarning() << __FUNCTION__ << "line delimiter not found";
  86. return;
  87. }
  88. QString boundary;
  89. parseContentType(section, nullptr, &boundary);
  90. if (boundary.isEmpty())
  91. {
  92. qWarning() << __FUNCTION__ << "boundary tag not found" << section.mid(0,100);
  93. return;
  94. }
  95. const QString beginBoundary = "--" + boundary + lineDelimiter;
  96. const QString endBoundary = "--" + boundary + "--";
  97. for (qsizetype beginPos = section.indexOf(beginBoundary.toUtf8());
  98. beginPos > 0;
  99. beginPos = section.indexOf(beginBoundary.toUtf8(), beginPos+1))
  100. {
  101. QByteArray boundaryMarkedPart = section;
  102. boundaryMarkedPart.remove(0, beginPos);
  103. qsizetype endPos = boundaryMarkedPart.indexOf(beginBoundary.toUtf8(), 1);
  104. if (endPos < 0) // last
  105. {
  106. endPos = boundaryMarkedPart.indexOf(endBoundary.toUtf8(), 1);
  107. if (endPos < 0)
  108. {
  109. endPos = boundaryMarkedPart.size()-1;
  110. }
  111. }
  112. boundaryMarkedPart.remove(endPos, boundaryMarkedPart.size()-endPos);
  113. QSharedPointer<EmailDocumentEntry> entry(new EmailDocumentEntry(m_pAttachments));
  114. entry->parse(boundaryMarkedPart.trimmed());
  115. if (m_pAttachments != nullptr) m_pAttachments->push_back(entry);
  116. }
  117. }
  118. EmailDocumentEntry::ContentType EmailDocumentEntry::contentTypeFromString(const QString &string)
  119. {
  120. ContentType result;
  121. if (string.trimmed() == "text/plain") result.enumerate = ContentType::Enum::textPlain;
  122. else if (string.trimmed().startsWith("text/")) result.enumerate = ContentType::Enum::textOther;
  123. else if (string.trimmed() == "image/jpeg") result.enumerate = ContentType::Enum::imageJpeg;
  124. else if (string.trimmed() == "image/png") result.enumerate = ContentType::Enum::imagePng;
  125. else if (string.trimmed().startsWith("image/")) result.enumerate = ContentType::Enum::imageOther;
  126. else if (string.trimmed() == "multipart/mixed") result.enumerate = ContentType::Enum::multipartMixed;
  127. else if (string.trimmed() == "multipart/related") result.enumerate = ContentType::Enum::multipartRelated;
  128. else if (string.trimmed() == "multipart/alternative") result.enumerate = ContentType::Enum::multipartAlternative;
  129. else if (string.trimmed().startsWith("multipart/")) result.enumerate = ContentType::Enum::multipartOther;
  130. else result.enumerate = ContentType::Enum::binary;
  131. result.string = string.trimmed();
  132. return result;
  133. }
  134. EmailDocumentEntry::ContentType EmailDocumentEntry::contentTypeToString(ContentType type)
  135. {
  136. ContentType result;
  137. result.enumerate = type.enumerate;
  138. if (type.enumerate == ContentType::Enum::textPlain) result.string = "text/plain";
  139. else if (type.enumerate == ContentType::Enum::textOther) result.string = "text/";
  140. else if (type.enumerate == ContentType::Enum::imageJpeg) result.string = "image/jpeg";
  141. else if (type.enumerate == ContentType::Enum::imagePng) result.string = "image/png";
  142. else if (type.enumerate == ContentType::Enum::imageOther) result.string = "image/";
  143. else if (type.enumerate == ContentType::Enum::multipartMixed) result.string = "multipart/mixed";
  144. else if (type.enumerate == ContentType::Enum::multipartRelated) result.string = "multipart/related";
  145. else if (type.enumerate == ContentType::Enum::multipartAlternative) result.string = "multipart/alternative";
  146. else if (type.enumerate == ContentType::Enum::multipartOther) result.string = "multipart/";
  147. else result.string = "application/octet-stream" ;
  148. return result;
  149. }
  150. EmailDocumentEntry::ContentType EmailDocumentEntry::parseContentType(const QByteArray &data, QString* name, QString* boundary, QString* charset)
  151. {
  152. ContentType result;
  153. ParseState state = ParseState::other;
  154. QStringList contentTypeRaw;
  155. QTextStream stream(data.trimmed());
  156. QByteArray line = stream.readLine().toUtf8();
  157. QByteArray buffer;
  158. for (; not stream.atEnd(); line = stream.readLine().toUtf8())
  159. {
  160. if (state == ParseState::contentType)
  161. {
  162. if (not line.startsWith('\t') and not line.startsWith(' '))
  163. {
  164. while (buffer.contains(";;")) buffer.replace(";;", ";");
  165. contentTypeRaw = QString(buffer.trimmed()).split(';');
  166. result = contentTypeFromString(contentTypeRaw.first());
  167. QStringListIterator iter(contentTypeRaw);
  168. while (iter.hasNext())
  169. {
  170. auto attr = iter.next();
  171. if (attr.trimmed().startsWith("boundary=") and boundary != nullptr)
  172. {
  173. *boundary = attr.trimmed().remove(0,9).trimmed();
  174. boundary->remove('"');
  175. }
  176. else if (attr.trimmed().startsWith("name=") and name != nullptr)
  177. {
  178. QByteArray decoded = EmailDocument::decodeMimeString(attr.remove(0,5).trimmed());
  179. if (decoded.isEmpty())
  180. {
  181. *name = attr.trimmed();
  182. name->remove('"');
  183. }
  184. else
  185. {
  186. *name = decoded;
  187. }
  188. }
  189. else if (attr.trimmed().startsWith("charset=") and charset != nullptr)
  190. {
  191. *charset = attr.trimmed().remove(0,8).trimmed();
  192. charset->remove('"');
  193. }
  194. }
  195. break;
  196. }
  197. else
  198. {
  199. buffer += ';' + line;
  200. continue;
  201. }
  202. }
  203. if (line.startsWith("Content-Type:"))
  204. {
  205. state = ParseState::contentType;
  206. buffer = line.remove(0,13).trimmed();
  207. }
  208. else if (line.isEmpty())
  209. {
  210. break;
  211. }
  212. }
  213. return result;
  214. }
  215. EmailDocumentEntry::TransferEncoding EmailDocumentEntry::parseTransferEncoding(const QByteArray &data)
  216. {
  217. TransferEncoding result = TransferEncoding::textPlain;
  218. QTextStream stream(data.trimmed());
  219. QString line = stream.readLine();
  220. for (; not stream.atEnd(); line = stream.readLine())
  221. {
  222. if (line.startsWith("Content-Transfer-Encoding:"))
  223. {
  224. if (line.contains("base64", Qt::CaseInsensitive))
  225. {
  226. result = TransferEncoding::base64;
  227. }
  228. }
  229. else if (line.isEmpty())
  230. {
  231. break;
  232. }
  233. }
  234. return result;
  235. }
  236. QString EmailDocumentEntry::primaryLineDelimiter(const QByteArray &data)
  237. {
  238. QString lineDelimiter;
  239. int rnPos = data.indexOf("\r\n");
  240. int nPos = data.indexOf("\n");
  241. if (rnPos < 0 and nPos < 0)
  242. {
  243. qWarning() << __FUNCTION__ << "Invalid input: no line delimiters found";
  244. return QString();
  245. }
  246. else if (rnPos < 0)
  247. {
  248. lineDelimiter = "\n";
  249. }
  250. else if (nPos < 0)
  251. {
  252. lineDelimiter = "\r\n";
  253. }
  254. else
  255. {
  256. lineDelimiter = (rnPos < nPos ? "\r\n" : "\n");
  257. }
  258. return lineDelimiter;
  259. }