diff --git a/autotests/messagetest.cpp b/autotests/messagetest.cpp index 0a75613..fea33d2 100644 --- a/autotests/messagetest.cpp +++ b/autotests/messagetest.cpp @@ -1,667 +1,679 @@ /* Copyright (c) 2007 Volker Krause This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messagetest.h" #include #include #include #include using namespace KMime; QTEST_MAIN(MessageTest) void MessageTest::testMainBodyPart() { Message *msg = new Message(); Message *msg2 = new Message(); Content *text = new Content(); text->contentType()->setMimeType("text/plain"); Content *html = new Content(); html->contentType()->setMimeType("text/html"); // empty message QCOMPARE(msg->mainBodyPart(), msg); QCOMPARE(msg->mainBodyPart("text/plain"), (Content *)nullptr); // non-multipart msg->contentType()->setMimeType("text/html"); QCOMPARE(msg->mainBodyPart(), msg); QCOMPARE(msg->mainBodyPart("text/plain"), (Content *)nullptr); QCOMPARE(msg->mainBodyPart("text/html"), msg); // multipart/mixed msg2->contentType()->setMimeType("multipart/mixed"); msg2->addContent(text); msg2->addContent(html); QCOMPARE(msg2->mainBodyPart(), text); QCOMPARE(msg2->mainBodyPart("text/plain"), text); QCOMPARE(msg2->mainBodyPart("text/html"), (Content *)nullptr); // Careful with removing content here. If we remove one of the two contents // (by adding it to another message), the multipart will automatically be // converted to a single-part, deleting the other content! msg2->clearContents(false); // mulitpart/alternative msg->contentType()->setMimeType("multipart/alternative"); msg->addContent(html); msg->addContent(text); QCOMPARE(msg->mainBodyPart(), html); QCOMPARE(msg->mainBodyPart("text/plain"), text); QCOMPARE(msg->mainBodyPart("text/html"), html); // mulitpart/alternative inside multipart/mixed Message *msg3 = new Message(); msg3->contentType()->setMimeType("multipart/mixed"); msg3->addContent(msg); Content *attach = new Content(); attach->contentType()->setMimeType("text/plain"); QCOMPARE(msg3->mainBodyPart(), html); QCOMPARE(msg3->mainBodyPart("text/plain"), text); QCOMPARE(msg3->mainBodyPart("text/html"), html); delete msg2; delete msg3; delete attach; } void MessageTest::testBrunosMultiAssembleBug() { QByteArray data = "From: Sender \n" "Subject: Sample message\n" "To: Receiver \n" "Date: Sat, 04 Aug 2007 12:44:00 +0200\n" "MIME-Version: 1.0\n" "Content-Type: text/plain\n" "X-Foo: bla\n" "X-Bla: foo\n" "\n" "body"; Message *msg = new Message; msg->setContent(data); msg->parse(); msg->assemble(); QCOMPARE(msg->encodedContent(), data); msg->inReplyTo(); msg->assemble(); QCOMPARE(msg->encodedContent(), data); delete msg; } void MessageTest::testWillsAndTillsCrash() { QByteArray deadlyMail = "From: censored@yahoogroups.com\n" "To: censored@yahoogroups.com\n" "Sender: censored@yahoogroups.com\n" "MIME-Version: 1.0\n" "Date: 29 Jan 2006 23:58:21 -0000\n" "Subject: [censored] Birthday Reminder\n" "Reply-To: censored@yahoogroups.com\n" "Content-Type: multipart/alternative;\n boundary=\"YCalReminder=cNM4SNTGA4Cg1MVLaPpqNF1138579098\"\n" "X-Length: 9594\n" "X-UID: 6161\n" "Status: RO\n" "X-Status: OC\n" "X-KMail-EncryptionState:\n" "X-KMail-SignatureState:\n" "X-KMail-MDN-Sent:\n\n"; KMime::Message *msg = new KMime::Message; msg->setContent(deadlyMail); msg->parse(); QVERIFY(!msg->date()->isEmpty()); QCOMPARE(msg->subject()->as7BitString(false), QByteArray("[censored] Birthday Reminder")); QCOMPARE(msg->from()->mailboxes().count(), 1); QCOMPARE(msg->sender()->mailboxes().count(), 1); QCOMPARE(msg->replyTo()->mailboxes().count(), 1); QCOMPARE(msg->to()->mailboxes().count(), 1); QCOMPARE(msg->cc()->mailboxes().count(), 0); QCOMPARE(msg->bcc()->mailboxes().count(), 0); QCOMPARE(msg->inReplyTo()->identifiers().count(), 0); QCOMPARE(msg->messageID()->identifiers().count(), 0); delete msg; } void MessageTest::testDavidsParseCrash() { KMime::Message::Ptr mail = readAndParseMail(QStringLiteral("dfaure-crash.mbox")); QCOMPARE(mail->to()->asUnicodeString().toLatin1().data(), "frank@domain.com"); } void MessageTest::testHeaderFieldWithoutSpace() { // Headers without a space, like the CC header here, are allowed according to // the examples in RFC2822, Appendix A5 QString mail = QStringLiteral("From:\n" "To: heinz@test.de\n" "Cc:moritz@test.de\n" "Subject: Test\n" "X-Mailer:"); KMime::Message msg; msg.setContent(mail.toLatin1()); msg.parse(); QCOMPARE(msg.to()->asUnicodeString(), QLatin1String("heinz@test.de")); QCOMPARE(msg.from()->asUnicodeString(), QString()); QCOMPARE(msg.cc()->asUnicodeString(), QLatin1String("moritz@test.de")); QCOMPARE(msg.subject()->asUnicodeString(), QLatin1String("Test")); QVERIFY(msg.hasHeader("X-Mailer")); QVERIFY(msg.headerByType("X-Mailer")->asUnicodeString().isEmpty()); } void MessageTest::testWronglyFoldedHeaders() { // The first subject line here doesn't contain anything. This is invalid, // however there are some mailers out there that produce those messages. QString mail = QStringLiteral("Subject:\n" " Hello\n" " World\n" "To: \n" " test@test.de\n\n" ""); KMime::Message msg; msg.setContent(mail.toLatin1()); msg.parse(); QCOMPARE(msg.subject()->asUnicodeString(), QLatin1String("Hello World")); QCOMPARE(msg.body().data(), ""); QCOMPARE(msg.to()->asUnicodeString(), QLatin1String("test@test.de")); } void MessageTest::missingHeadersTest() { // Test that the message body is OK even though some headers are missing KMime::Message msg; QString body = QStringLiteral("Hi Donald, look at those nice pictures I found!\n"); QString content = QLatin1String("From: georgebush@whitehouse.org\n" "To: donaldrumsfeld@whitehouse.org\n" "Subject: Cute Kittens\n" "\n") + body; msg.setContent(content.toLatin1()); msg.parse(); msg.assemble(); QCOMPARE(body, QString::fromLatin1(msg.body())); // Now create a new message, based on the content of the first one. // The body of the new message should still be the same. // (there was a bug that caused missing mandatory headers to be // added as a empty newline, which caused parts of the header to // leak into the body) KMime::Message msg2; msg2.setContent(msg.encodedContent()); msg2.parse(); msg2.assemble(); QCOMPARE(body, QString::fromLatin1(msg2.body())); } void MessageTest::testBug219749() { // Test that the message body is OK even though some headers are missing KMime::Message msg; const QString content = QStringLiteral( "Content-Type: MULTIPART/MIXED;\n" " BOUNDARY=\"0-1804289383-1260384639=:52580\"\n" "\n" "--0-1804289383-1260384639=:52580\n" "Content-Type: TEXT/plain; CHARSET=UTF-8\n" "\n" "--0-1804289383-1260384639=:52580\n" "Content-Type: APPLICATION/octet-stream\n" "Content-Transfer-Encoding: BASE64\n" "Content-ID: \n" "Content-Disposition: ATTACHMENT; FILENAME=\"jaselka 1.docx\"\n" "\n" "UEsDBBQABgAIAAAAIQDd/JU3ZgEAACAFAAATAAgCW0NvbnRlbnRfVHlwZXNd\n" "SUwAAAAA\n" "\n" "--0-1804289383-1260384639=:52580--\n"); msg.setContent(content.toLatin1()); msg.parse(); QCOMPARE(msg.contents().size(), 2); KMime::Content *attachment = msg.contents()[1]; QCOMPARE(attachment->contentType(false)->mediaType().data(), "application"); QCOMPARE(attachment->contentType(false)->subType().data(), "octet-stream"); QCOMPARE(attachment->contentID()->identifier().data(), "jaselka1.docx4AECA1F9@9230725.3CDBB752"); QCOMPARE(attachment->contentID()->as7BitString(false).data(), ""); Headers::ContentDisposition *cd = attachment->contentDisposition(false); QVERIFY(cd); QCOMPARE(cd->filename(), QLatin1String("jaselka 1.docx")); } void MessageTest::testBidiSpoofing() { const QString RLO(QChar(0x202E)); //const QString PDF( QChar( 0x202C ) ); const QByteArray senderAndRLO = encodeRFC2047String(QLatin1String("Sender") + RLO + QLatin1String(" "), "utf-8"); // The display name of the "From" has an RLO, make sure the KMime parser balances it QByteArray data = "From: " + senderAndRLO + "\n" "\n" "Body"; KMime::Message msg; msg.setContent(data); msg.parse(); // Test adjusted for taking into account that KMIME now removes bidi control chars // instead of adding PDF chars, because of broken KHTML. //const QString expectedDisplayName = "\"Sender" + RLO + PDF + "\""; const QString expectedDisplayName = QStringLiteral("Sender"); const QString expectedMailbox = expectedDisplayName + QLatin1String(" "); QCOMPARE(msg.from()->addresses().count(), 1); QCOMPARE(msg.from()->asUnicodeString(), expectedMailbox); QCOMPARE(msg.from()->displayNames().first(), expectedDisplayName); QCOMPARE(msg.from()->mailboxes().first().name(), expectedDisplayName); QCOMPARE(msg.from()->mailboxes().first().address().data(), "sender@test.org"); } // Test to see if header fields of mails with an UTF-16 body are properly read // and written. // See also https://issues.kolab.org/issue3707 void MessageTest::testUtf16() { QByteArray data = "From: foo@bar.com\n" "Subject: UTF-16 Test\n" "MIME-Version: 1.0\n" "Content-Type: Text/Plain;\n" " charset=\"utf-16\"\n" "Content-Transfer-Encoding: base64\n" "\n" "//5UAGgAaQBzACAAaQBzACAAVQBUAEYALQAxADYAIABUAGUAeAB0AC4ACgAKAAo"; KMime::Message msg; msg.setContent(data); msg.parse(); QCOMPARE(msg.from()->asUnicodeString(), QLatin1String("foo@bar.com")); QCOMPARE(msg.subject()->asUnicodeString(), QLatin1String("UTF-16 Test")); QCOMPARE(msg.decodedText(false, true), QLatin1String("This is UTF-16 Text.")); // Add a new To header, for testings KMime::Headers::To *to = new KMime::Headers::To; KMime::Types::Mailbox address; address.setAddress("test@test.de"); address.setName(QStringLiteral("Fränz Töster")); to->addAddress(address); to->setRFC2047Charset("ISO-8859-1"); // default changed to UTF-8 in KF5, which is fine, but breaks the test msg.appendHeader(to); msg.assemble(); QByteArray newData = "From: foo@bar.com\n" "Subject: UTF-16 Test\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=\"utf-16\"\n" "Content-Transfer-Encoding: base64\n" "To: =?ISO-8859-1?Q?Fr=E4nz_T=F6ster?= \n" "\n" "//5UAGgAaQBzACAAaQBzACAAVQBUAEYALQAxADYAIABUAGUAeAB0AC4ACgAKAAo=\n" "\n"; QCOMPARE(msg.encodedContent().data(), newData.data()); } void MessageTest::testDecodedText() { QByteArray data = "Subject: Test\n" "\n" "Testing Whitespace \n \n \n\n\n"; KMime::Message msg; msg.setContent(data); msg.parse(); QCOMPARE(msg.decodedText(true, false), QLatin1String("Testing Whitespace")); QCOMPARE(msg.decodedText(true, true), QLatin1String("Testing Whitespace")); QCOMPARE(msg.decodedText(false, true), QLatin1String("Testing Whitespace \n \n ")); QByteArray data2 = "Subject: Test\n" "\n" "Testing Whitespace \n \n \n\n\n "; KMime::Message msg2; msg2.setContent(data2); msg2.parse(); QCOMPARE(msg2.decodedText(true, false), QLatin1String("Testing Whitespace")); QCOMPARE(msg2.decodedText(true, true), QLatin1String("Testing Whitespace")); QCOMPARE(msg2.decodedText(false, true), QLatin1String("Testing Whitespace \n \n \n\n\n ")); } void MessageTest::testInlineImages() { QByteArray data = "From: \n" "To: kde@kde.org\n" "Subject: Inline Image (unsigned)\n" "Date: Wed, 23 Dec 2009 14:00:59 +0100\n" "MIME-Version: 1.0\n" "Content-Type: multipart/related;\n" " boundary=\"Boundary-02=_LShMLJyjC7zqmVP\"\n" "Content-Transfer-Encoding: 7bit\n" "\n" "\n" "--Boundary-02=_LShMLJyjC7zqmVP\n" "Content-Type: multipart/alternative;\n" " boundary=\"Boundary-01=_LShMLzAUPqE38S8\"\n" "Content-Transfer-Encoding: 7bit\n" "Content-Disposition: inline\n" "\n" "--Boundary-01=_LShMLzAUPqE38S8\n" "Content-Type: text/plain;\n" " charset=\"us-ascii\"\n" "Content-Transfer-Encoding: 7bit\n" "\n" "First line\n" "\n" "\n" "Image above\n" "\n" "Last line\n" "\n" "--Boundary-01=_LShMLzAUPqE38S8\n" "Content-Type: text/html;\n" " charset=\"us-ascii\"\n" "Content-Transfer-Encoding: 7bit\n" "\n" "Line 1\n" "--Boundary-01=_LShMLzAUPqE38S8--\n" "\n" "--Boundary-02=_LShMLJyjC7zqmVP\n" "Content-Type: image/png;\n" " name=\"inlineimage.png\"\n" "Content-Transfer-Encoding: base64\n" "Content-Id: <740439759>\n" "\n" "jxrG/ha/VB+rODav6/d5i1US6Za/YEMvtm2SgJC/CXVFiD3UFSH2UFeE2ENdEWIPdUWIPdQVIfZQ\n" "V4TYQ10RYg91RYg91BUh9lBXhNhDXRFiD3VFiD3UFSH2UFeE2ENdEWIPdUWIPdQVIfZQV4TYQ10R\n" "Yg91RYg91BUh9lBX5E+Tz6Vty1HSx+NR++UuCOqKEHv+Ax0Y5U59+AHBAAAAAElFTkSuQmCC\n" "\n" "--Boundary-02=_LShMLJyjC7zqmVP--"; KMime::Message msg; msg.setContent(data); msg.parse(); QCOMPARE(msg.contents().size(), 2); QCOMPARE(msg.contents()[0]->contentType()->isMultipart(), true); QCOMPARE(msg.contents()[0]->contentType()->subType().data(), "alternative"); QCOMPARE(msg.contents()[1]->contentType()->isImage(), true); QCOMPARE(msg.contents()[1]->contentType()->name(), QLatin1String("inlineimage.png")); QCOMPARE(msg.contents()[1]->contentID()->identifier().data(), "740439759"); QCOMPARE(msg.contents()[1]->contentID()->as7BitString(false).data(), "<740439759>"); } void MessageTest::testIssue3908() { KMime::Message::Ptr msg = readAndParseMail(QStringLiteral("issue3908.mbox")); QCOMPARE(msg->contents().size(), 2); KMime::Content *attachment = msg->contents().at(1); QVERIFY(attachment); QVERIFY(attachment->contentDescription(false)); QCOMPARE(attachment->contentDescription()->asUnicodeString(), QString::fromUtf8( "Kontact oder auch KDE-PIM ist der Groupware-Client aus der KDE Software Compilation 4.Eine der Besonderheiten von Kontact " "gegenüber anderen Groupware-Clients ist, dass die Teil-Programme auch weiterhin unabhängig von Kontact gestartet werden " "können. So spielt es zum Beispiel keine Rolle für das Arbeiten mit KMail, ob es mal allein oder mal im Rahmen von Kontact " "gestartet wird: Die Mails und die persönlichen Einstellungen bleiben stets erhalten.Auch sieht Kontact eine modulare " "Anbindung der Programme vor, wodurch sich auch in Zukunft weitere Module entwickeln und anfügen lassen, ohne Kontact " "dafür zu ändern. Dies bietet die Möglichkeit, auch privat entwickelte Module einzubinden und so die Groupware grundlegend " "eigenen Bedürfnissen anzupassen.")); } void MessageTest::testIssue3914() { // This loads a mail which has a content-disposition of which the filename parameter is empty. // Check that the parser doesn't choke on this. KMime::Message::Ptr msg = readAndParseMail(QStringLiteral("broken-content-disposition.mbox")); QCOMPARE(msg->subject()->as7BitString().data(), "Subject: Fwd: test broken mail"); QCOMPARE(msg->contents().size(), 2); KMime::Content *attachedMail = msg->contents().at(1); QCOMPARE(attachedMail->contentType()->mimeType().data(), "message/rfc822"); QVERIFY(attachedMail->contentDisposition(false)); QVERIFY(attachedMail->contentDisposition()->hasParameter(QLatin1String("filename"))); QVERIFY(attachedMail->contentDisposition()->parameter(QLatin1String("filename")).isEmpty()); } void MessageTest::testBug223509() { KMime::Message::Ptr msg = readAndParseMail(QStringLiteral("encoding-crash.mbox")); QCOMPARE(msg->subject()->as7BitString().data(), "Subject: Blub"); QCOMPARE(msg->contents().size(), 0); QCOMPARE(msg->contentTransferEncoding()->encoding(), KMime::Headers::CEbinary); QCOMPARE(msg->decodedText().toLatin1().data(), "Bla Bla Bla"); QCOMPARE(msg->encodedBody().data(), "Bla Bla Bla\n"); // encodedContent() was crashing in this bug because of an invalid assert QVERIFY(!msg->encodedContent().isEmpty()); // Make sure that the encodedContent() is sane, by parsing it again. KMime::Message msg2; msg2.setContent(msg->encodedContent()); msg2.parse(); QCOMPARE(msg2.subject()->as7BitString().data(), "Subject: Blub"); QCOMPARE(msg2.contents().size(), 0); QCOMPARE(msg2.contentTransferEncoding()->encoding(), KMime::Headers::CEbinary); QCOMPARE(msg2.decodedText().toLatin1().data(), "Bla Bla Bla"); QCOMPARE(msg2.decodedText(true, true /* remove newlines at end */).toLatin1().data(), "Bla Bla Bla"); } void MessageTest::testEncapsulatedMessages() { // // First, test some basic properties to check that the parsing was correct // KMime::Message::Ptr msg = readAndParseMail(QStringLiteral("simple-encapsulated.mbox")); QCOMPARE(msg->contentType()->mimeType().data(), "multipart/mixed"); QCOMPARE(msg->contents().size(), 2); QVERIFY(msg->isTopLevel()); KMime::Content *const textContent = msg->contents().at(0); QCOMPARE(textContent->contentType()->mimeType().data(), "text/plain"); QVERIFY(textContent->contents().isEmpty()); QVERIFY(!textContent->bodyIsMessage()); QVERIFY(!textContent->bodyAsMessage()); QVERIFY(!textContent->isTopLevel()); QCOMPARE(textContent->decodedText(true, true), QLatin1String("Hi Hans!\nLook at this interesting mail I forwarded to you!")); QCOMPARE(textContent->index().toString().toLatin1().data(), "1"); KMime::Content *messageContent = msg->contents().at(1); QCOMPARE(messageContent->contentType()->mimeType().data(), "message/rfc822"); QVERIFY(messageContent->body().isEmpty()); QCOMPARE(messageContent->contents().count(), 1); QVERIFY(messageContent->bodyIsMessage()); QVERIFY(messageContent->bodyAsMessage().data()); QVERIFY(!messageContent->isTopLevel()); QCOMPARE(messageContent->index().toString().toLatin1().data(), "2"); KMime::Message::Ptr encapsulated = messageContent->bodyAsMessage(); QCOMPARE(encapsulated->contents().size(), 0); QCOMPARE(encapsulated->contentType()->mimeType().data(), "text/plain"); QVERIFY(!encapsulated->bodyIsMessage()); QVERIFY(!encapsulated->bodyAsMessage()); QCOMPARE(encapsulated->subject()->as7BitString(false).data(), "Foo"); QCOMPARE(encapsulated->decodedText(false, false), QLatin1String("This is the encapsulated message body.")); QCOMPARE(encapsulated.data(), messageContent->bodyAsMessage().data()); QCOMPARE(encapsulated.data(), messageContent->contents().first()); QCOMPARE(encapsulated->parent(), messageContent); QVERIFY(!encapsulated->isTopLevel()); QCOMPARE(encapsulated->topLevel(), msg.data()); QCOMPARE(encapsulated->index().toString().toLatin1().data(), "2.1"); // Now test some misc functions QCOMPARE(msg->storageSize(), msg->head().size() + textContent->storageSize() + messageContent->storageSize()); QCOMPARE(messageContent->storageSize(), messageContent->head().size() + encapsulated->storageSize()); // Now change some properties on the encapsulated message encapsulated->subject()->fromUnicodeString(QStringLiteral("New subject"), "us-ascii"); encapsulated->fromUnicodeString(QStringLiteral("New body string.")); // Since we didn't assemble the encapsulated message yet, it should still have the old headers QVERIFY(encapsulated->encodedContent().contains("Foo")); QVERIFY(!encapsulated->encodedContent().contains("New subject")); // Now assemble the container message msg->assemble(); // Assembling the container message should have assembled the encapsulated message as well. QVERIFY(!encapsulated->encodedContent().contains("Foo")); QVERIFY(encapsulated->encodedContent().contains("New subject")); QCOMPARE(encapsulated->body().data(), "New body string."); QVERIFY(msg->encodedContent().contains(encapsulated->body())); QCOMPARE(msg->contentType()->mimeType().data(), "multipart/mixed"); QCOMPARE(msg->contents().size(), 2); messageContent = msg->contents().at(1); QCOMPARE(messageContent->contentType()->mimeType().data(), "message/rfc822"); QVERIFY(encapsulated.data() == messageContent->bodyAsMessage().data()); // Setting a new body and then parsing it should discard the encapsulated message messageContent->contentType()->setMimeType("text/plain"); messageContent->assemble(); messageContent->setBody("Some new body"); messageContent->parse(); QVERIFY(!messageContent->bodyIsMessage()); QVERIFY(!messageContent->bodyAsMessage()); QCOMPARE(messageContent->contents().size(), 0); } void MessageTest::testOutlookAttachmentNaming() { KMime::setUseOutlookAttachmentEncoding(true); // Try and decode KMime::Message::Ptr msg = readAndParseMail(QStringLiteral("outlook-attachment.mbox")); QVERIFY(msg->attachments().count() == 1); KMime::Content *attachment = msg->contents()[1]; QCOMPARE(attachment->contentType(false)->mediaType().data(), "text"); QCOMPARE(attachment->contentType(false)->subType().data(), "x-patch"); Headers::ContentDisposition *cd = attachment->contentDisposition(false); QVERIFY(cd); QCOMPARE(cd->filename(), QString::fromUtf8("å.diff")); // Try and encode attachment->clear();// = new Content(); attachment->contentDisposition()->setDisposition(Headers::CDattachment); attachment->contentDisposition()->setFilename(QStringLiteral("å.diff")); attachment->contentDisposition()->setRFC2047Charset("ISO-8859-1"); // default changed to UTF-8 in KF5, which is fine, but breaks the test attachment->assemble(); qDebug() << "got:" << attachment->contentDisposition()->as7BitString(false); QCOMPARE(attachment->contentDisposition()->as7BitString(false), QByteArray("attachment; filename=\"=?ISO-8859-1?Q?=E5=2Ediff?=\"")); KMime::setUseOutlookAttachmentEncoding(false); } void MessageTest::testEncryptedMails() { KMime::Message::Ptr msg = readAndParseMail(QStringLiteral("x-pkcs7.mbox")); QVERIFY(msg->contents().size() == 0); QVERIFY(msg->attachments().count() == 0); QVERIFY(KMime::isEncrypted(msg.data()) == true); QVERIFY(KMime::isInvitation(msg.data()) == false); QVERIFY(KMime::isSigned(msg.data()) == false); } void MessageTest::testReturnSameMail() { KMime::Message::Ptr msg = readAndParseMail(QStringLiteral("dontchangemail.mbox")); QFile file(QLatin1String(TEST_DATA_DIR) + QLatin1String("/mails/dontchangemail.mbox")); const bool ok = file.open(QIODevice::ReadOnly); if (!ok) { qWarning() << file.fileName() << "not found"; } Q_ASSERT(ok); QByteArray fileContent = file.readAll(); QCOMPARE(msg->encodedContent(), fileContent); QCOMPARE(msg->decodedText(), QLatin1String("")); KMime::Message msg2; msg2.setContent(msg->encodedContent()); msg2.parse(); QCOMPARE(msg2.encodedContent(), fileContent); } void MessageTest::testEmptySubject() { auto msg = readAndParseMail(QStringLiteral("empty-subject.mbox")); QVERIFY(msg); // was crashing for Andre QVERIFY(msg->hasHeader("Subject")); QVERIFY(msg->subject()->asUnicodeString().isEmpty()); } void MessageTest::testReplyHeader() { auto msg = readAndParseMail(QStringLiteral("reply-header.mbox")); QVERIFY(msg); QVERIFY(!msg->replyTo(false)); QCOMPARE(msg->hasHeader("Reply-To"), false); QCOMPARE(msg->hasHeader("Reply"), true); QVERIFY(msg->headerByType("Reply")); } KMime::Message::Ptr MessageTest::readAndParseMail(const QString &mailFile) const { QFile file(QLatin1String(TEST_DATA_DIR) + QLatin1String("/mails/") + mailFile); const bool ok = file.open(QIODevice::ReadOnly); if (!ok) { qWarning() << file.fileName() << "not found"; } Q_ASSERT(ok); const QByteArray data = KMime::CRLFtoLF(file.readAll()); Q_ASSERT(!data.isEmpty()); KMime::Message::Ptr msg(new KMime::Message); msg->setContent(data); msg->parse(); return msg; } void MessageTest::testBug392239() { auto msg = readAndParseMail(QStringLiteral("bug392239.mbox")); QCOMPARE(msg->subject()->as7BitString().data(), "Subject: "); QCOMPARE(msg->contents().size(), 0); QCOMPARE(msg->contentTransferEncoding()->encoding(), KMime::Headers::CEbase64); QCOMPARE(msg->decodedText().toUtf8().data(), "Following this paragraph there is a double line break which should result in vertical spacing.\r\rPreceding this paragraph there is a double line break which should result in vertical spacing.\r"); + const QByteArray data = KMime::CRtoLF(msg->decodedText().toUtf8()); + QCOMPARE(data, "Following this paragraph there is a double line break which should result in vertical spacing.\n\nPreceding this paragraph there is a double line break which should result in vertical spacing.\n"); +} + +void MessageTest::testCRtoLF() +{ + QByteArray data = "Subject: Test\n"; + QCOMPARE(CRtoLF(data), "Subject: Test\n"); + data = "Subject: Test\r"; + QCOMPARE(CRtoLF(data), "Subject: Test\n"); + data = "Subject: Test\r\n"; + QCOMPARE(CRtoLF(data), "Subject: Test\r\n"); } diff --git a/autotests/messagetest.h b/autotests/messagetest.h index 92f5a06..78cc633 100644 --- a/autotests/messagetest.h +++ b/autotests/messagetest.h @@ -1,57 +1,58 @@ /* Copyright (c) 2007 Volker Krause This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef MESSAGE_TEST_H #define MESSAGE_TEST_H #include "kmime_message.h" #include class MessageTest : public QObject { Q_OBJECT private Q_SLOTS: void testMainBodyPart(); void testBrunosMultiAssembleBug(); void testWillsAndTillsCrash(); void testDavidsParseCrash(); void testHeaderFieldWithoutSpace(); void testWronglyFoldedHeaders(); void missingHeadersTest(); void testBug219749(); void testBidiSpoofing(); void testUtf16(); void testDecodedText(); void testInlineImages(); void testIssue3908(); void testIssue3914(); void testBug223509(); void testEncapsulatedMessages(); void testOutlookAttachmentNaming(); void testEncryptedMails(); void testReturnSameMail(); void testEmptySubject(); void testReplyHeader(); void testBug392239(); + void testCRtoLF(); private: KMime::Message::Ptr readAndParseMail(const QString &mailFile) const; }; #endif diff --git a/src/kmime_util.cpp b/src/kmime_util.cpp index dd95eb1..fbd351a 100644 --- a/src/kmime_util.cpp +++ b/src/kmime_util.cpp @@ -1,703 +1,727 @@ /* kmime_util.cpp KMime, the KDE Internet mail/usenet news message library. Copyright (c) 2001 the KMime authors. See file AUTHORS for details This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kmime_util.h" #include "kmime_util_p.h" #include "kmime_charfreq.h" #include "kmime_debug.h" #include "kmime_header_parsing.h" #include "kmime_message.h" #include "kmime_warning.h" #include // #include // for strcasestr #include #include #include #include #include #include #include #include #include using namespace KMime; namespace KMime { QVector c_harsetCache; bool u_seOutlookEncoding = false; QByteArray cachedCharset(const QByteArray &name) { foreach (const QByteArray &charset, c_harsetCache) { if (qstricmp(name.data(), charset.data()) == 0) { return charset; } } c_harsetCache.append(name.toUpper()); //qCDebug(KMIME_LOG) << "KNMimeBase::cachedCharset() number of cs" << c_harsetCache.count(); return c_harsetCache.last(); } bool isUsAscii(const QString &s) { uint sLength = s.length(); for (uint i = 0; i < sLength; i++) { if (s.at(i).toLatin1() <= 0) { // c==0: non-latin1, c<0: non-us-ascii return false; } } return true; } QString nameForEncoding(Headers::contentEncoding enc) { switch (enc) { case Headers::CE7Bit: return QStringLiteral("7bit"); case Headers::CE8Bit: return QStringLiteral("8bit"); case Headers::CEquPr: return QStringLiteral("quoted-printable"); case Headers::CEbase64: return QStringLiteral("base64"); case Headers::CEuuenc: return QStringLiteral("uuencode"); case Headers::CEbinary: return QStringLiteral("binary"); default: return QStringLiteral("unknown"); } } QVector encodingsForData(const QByteArray &data) { QVector allowed; CharFreq cf(data); switch (cf.type()) { case CharFreq::SevenBitText: allowed << Headers::CE7Bit; Q_FALLTHROUGH(); case CharFreq::EightBitText: allowed << Headers::CE8Bit; Q_FALLTHROUGH(); case CharFreq::SevenBitData: if (cf.printableRatio() > 5.0 / 6.0) { // let n the length of data and p the number of printable chars. // Then base64 \approx 4n/3; qp \approx p + 3(n-p) // => qp < base64 iff p > 5n/6. allowed << Headers::CEquPr; allowed << Headers::CEbase64; } else { allowed << Headers::CEbase64; allowed << Headers::CEquPr; } break; case CharFreq::EightBitData: allowed << Headers::CEbase64; break; case CharFreq::None: default: Q_ASSERT(false); } return allowed; } // all except specials, CTLs, SPACE. const uchar aTextMap[16] = { 0x00, 0x00, 0x00, 0x00, 0x5F, 0x35, 0xFF, 0xC5, 0x7F, 0xFF, 0xFF, 0xE3, 0xFF, 0xFF, 0xFF, 0xFE }; // all except tspecials, CTLs, SPACE. const uchar tTextMap[16] = { 0x00, 0x00, 0x00, 0x00, 0x5F, 0x36, 0xFF, 0xC0, 0x7F, 0xFF, 0xFF, 0xE3, 0xFF, 0xFF, 0xFF, 0xFE }; void setUseOutlookAttachmentEncoding(bool violateStandard) { u_seOutlookEncoding = violateStandard; } bool useOutlookAttachmentEncoding() { return u_seOutlookEncoding; } QByteArray uniqueString() { static const char chars[] = "0123456789abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; time_t now; char p[11]; int ran; unsigned int timeval; p[10] = '\0'; now = time(nullptr); ran = 1 + (int)(1000.0 * rand() / (RAND_MAX + 1.0)); timeval = (now / ran) + QCoreApplication::applicationPid(); for (int i = 0; i < 10; i++) { int pos = (int)(61.0 * rand() / (RAND_MAX + 1.0)); //qCDebug(KMIME_LOG) << pos; p[i] = chars[pos]; } QByteArray ret; ret.setNum(timeval); ret += '.'; ret += p; return ret; } QByteArray multiPartBoundary() { return "nextPart" + uniqueString(); } QByteArray unfoldHeader(const char *header, size_t headerSize) { QByteArray result; if (headerSize == 0) { return result; } // unfolding skips characters so result will be at worst headerSize long result.reserve(headerSize); const char *end = header + headerSize; const char *pos = header, *foldBegin = nullptr, *foldMid = nullptr, *foldEnd = nullptr; while ((foldMid = strchr(pos, '\n')) && foldMid < end) { foldBegin = foldEnd = foldMid; // find the first space before the line-break while (foldBegin) { if (!QChar::isSpace(*(foldBegin - 1))) { break; } --foldBegin; } // find the first non-space after the line-break while (foldEnd <= end - 1) { if (QChar::isSpace(*foldEnd)) { ++foldEnd; } else if (foldEnd && *(foldEnd - 1) == '\n' && *foldEnd == '=' && foldEnd + 2 < (header + headerSize - 1) && ((*(foldEnd + 1) == '0' && *(foldEnd + 2) == '9') || (*(foldEnd + 1) == '2' && *(foldEnd + 2) == '0'))) { // bug #86302: malformed header continuation starting with =09/=20 foldEnd += 3; } else { break; } } result.append(pos, foldBegin - pos); if (foldEnd < end - 1) { result += ' '; } pos = foldEnd; } if (end > pos) { result.append(pos, end - pos); } return result; } QByteArray unfoldHeader(const QByteArray &header) { return unfoldHeader(header.constData(), header.size()); } int findHeaderLineEnd(const QByteArray &src, int &dataBegin, bool *folded) { int end = dataBegin; int len = src.length() - 1; if (folded) { *folded = false; } if (dataBegin < 0) { // Not found return -1; } if (dataBegin > len) { // No data available return len + 1; } // If the first line contains nothing, but the next line starts with a space // or a tab, that means a stupid mail client has made the first header field line // entirely empty, and has folded the rest to the next line(s). if (src.at(end) == '\n' && end + 1 < len && (src[end + 1] == ' ' || src[end + 1] == '\t')) { // Skip \n and first whitespace dataBegin += 2; end += 2; } if (src.at(end) != '\n') { // check if the header is not empty while (true) { end = src.indexOf('\n', end + 1); if (end == -1 || end == len) { // end of string break; } else if (src[end + 1] == ' ' || src[end + 1] == '\t' || (src[end + 1] == '=' && end + 3 <= len && ((src[end + 2] == '0' && src[end + 3] == '9') || (src[end + 2] == '2' && src[end + 3] == '0')))) { // next line is header continuation or starts with =09/=20 (bug #86302) if (folded) { *folded = true; } } else { // end of header (no header continuation) break; } } } if (end < 0) { end = len + 1; //take the rest of the string } return end; } #ifndef HAVE_STRCASESTR #ifdef WIN32 #define strncasecmp _strnicmp #endif static const char *strcasestr(const char *haystack, const char *needle) { /* Copied from libreplace as part of qtwebengine 5.5.1 */ const char *s; size_t nlen = strlen(needle); for (s = haystack; *s; s++) { if (toupper(*needle) == toupper(*s) && strncasecmp(s, needle, nlen) == 0) { return (char *)((uintptr_t)s); } } return NULL; } #endif int indexOfHeader(const QByteArray &src, const QByteArray &name, int &end, int &dataBegin, bool *folded) { QByteArray n = name; n.append(':'); int begin = -1; if (qstrnicmp(n.constData(), src.constData(), n.length()) == 0) { begin = 0; } else { n.prepend('\n'); const char *p = strcasestr(src.constData(), n.constData()); if (!p) { begin = -1; } else { begin = p - src.constData(); ++begin; } } if (begin > -1) { //there is a header with the given name dataBegin = begin + name.length() + 1; //skip the name // skip the usual space after the colon if (dataBegin < src.length() && src.at(dataBegin) == ' ') { ++dataBegin; } end = findHeaderLineEnd(src, dataBegin, folded); return begin; } else { end = -1; dataBegin = -1; return -1; //header not found } } QByteArray extractHeader(const QByteArray &src, const QByteArray &name) { int begin, end; bool folded; QByteArray result; if (src.isEmpty() || indexOfHeader(src, name, end, begin, &folded) < 0) { return result; } if (begin >= 0) { if (!folded) { result = src.mid(begin, end - begin); } else { if (end > begin) { result = unfoldHeader(src.constData() + begin, end - begin); } } } return result; } QByteArray CRLFtoLF(const QByteArray &s) { if (!s.contains("\r\n")) { return s; } QByteArray ret = s; ret.replace("\r\n", "\n"); return ret; } QByteArray CRLFtoLF(const char *s) { QByteArray ret = s; return CRLFtoLF(ret); } QByteArray LFtoCRLF(const QByteArray &s) { const int firstNewline = s.indexOf('\n'); if (firstNewline == -1) { return s; } if (firstNewline > 0 && s.at(firstNewline - 1) == '\r') { // We found \r\n already, don't change anything // This check assumes that input is consistent in terms of newlines, // but so did if (s.contains("\r\n")), too. return s; } QByteArray ret = s; ret.replace('\n', "\r\n"); return ret; } QByteArray LFtoCRLF(const char *s) { QByteArray ret = s; return LFtoCRLF(ret); } +QByteArray CRtoLF(const QByteArray &s) +{ + const int firstNewline = s.indexOf('\r'); + if (firstNewline == -1) { + return s; + } + if (firstNewline > 0 && (s.length() > firstNewline + 1) && s.at(firstNewline + 1) == '\n') { + // We found \r\n already, don't change anything + // This check assumes that input is consistent in terms of newlines, + // but so did if (s.contains("\r\n")), too. + return s; + } + + QByteArray ret = s; + ret.replace('\r', '\n'); + return ret; +} + +QByteArray CRtoLF(const char *s) +{ + const QByteArray ret = s; + return CRtoLF(ret); +} + namespace { template < typename StringType, typename CharType > void removeQuotesGeneric(StringType &str) { bool inQuote = false; for (int i = 0; i < str.length(); ++i) { if (str[i] == CharType('"')) { str.remove(i, 1); i--; inQuote = !inQuote; } else { if (inQuote && (str[i] == CharType('\\'))) { str.remove(i, 1); } } } } } void removeQuotes(QByteArray &str) { removeQuotesGeneric(str); } void removeQuotes(QString &str) { removeQuotesGeneric(str); } template void addQuotes_impl(StringType &str, bool forceQuotes) { bool needsQuotes = false; for (int i = 0; i < str.length(); i++) { const CharType cur = str.at(i); if (QString(ToString(str)).contains(QRegExp(QStringLiteral("\"|\\\\|=|\\]|\\[|:|;|,|\\.|,|@|<|>|\\)|\\(")))) { needsQuotes = true; } if (cur == CharConverterType('\\') || cur == CharConverterType('\"')) { str.insert(i, CharConverterType('\\')); i++; } } if (needsQuotes || forceQuotes) { str.insert(0, CharConverterType('\"')); str.append(StringConverterType("\"")); } } void addQuotes(QByteArray &str, bool forceQuotes) { addQuotes_impl(str, forceQuotes); } void addQuotes(QString &str, bool forceQuotes) { addQuotes_impl(str, forceQuotes); } KMIME_EXPORT QString balanceBidiState(const QString &input) { const int LRO = 0x202D; const int RLO = 0x202E; const int LRE = 0x202A; const int RLE = 0x202B; const int PDF = 0x202C; QString result = input; int openDirChangers = 0; int numPDFsRemoved = 0; for (int i = 0; i < input.length(); i++) { const ushort &code = input.at(i).unicode(); if (code == LRO || code == RLO || code == LRE || code == RLE) { openDirChangers++; } else if (code == PDF) { if (openDirChangers > 0) { openDirChangers--; } else { // One PDF too much, remove it qCWarning(KMIME_LOG) << "Possible Unicode spoofing (unexpected PDF) detected in" << input; result.remove(i - numPDFsRemoved, 1); numPDFsRemoved++; } } } if (openDirChangers > 0) { qCWarning(KMIME_LOG) << "Possible Unicode spoofing detected in" << input; // At PDF chars to the end until the correct state is restored. // As a special exception, when encountering quoted strings, place the PDF before // the last quote. for (int i = openDirChangers; i > 0; i--) { if (result.endsWith(QLatin1Char('"'))) { result.insert(result.length() - 1, QChar(PDF)); } else { result += QChar(PDF); } } } return result; } QString removeBidiControlChars(const QString &input) { const int LRO = 0x202D; const int RLO = 0x202E; const int LRE = 0x202A; const int RLE = 0x202B; QString result = input; result.remove(LRO); result.remove(RLO); result.remove(LRE); result.remove(RLE); return result; } bool isCryptoPart(Content *content) { auto ct = content->contentType(false); if (!ct || !ct->isMediatype("application")) { return false; } const QByteArray lowerSubType = ct->subType().toLower(); if (lowerSubType == "pgp-encrypted" || lowerSubType == "pgp-signature" || lowerSubType == "pkcs7-mime" || lowerSubType == "x-pkcs7-mime" || lowerSubType == "pkcs7-signature" || lowerSubType == "x-pkcs7-signature") { return true; } if (lowerSubType == "octet-stream") { auto cd = content->contentDisposition(false); if (!cd) return false; const auto fileName = cd->filename().toLower(); return fileName == QLatin1String("msg.asc") || fileName == QLatin1String("encrypted.asc"); } return false; } bool isAttachment(Content* content) { if (!content) { return false; } const auto contentType = content->contentType(false); // multipart/* is never an attachment itself, message/rfc822 always is if (contentType) { if (contentType->isMultipart()) return false; if (contentType->isMimeType("message/rfc822")) return true; } // the main body part is not an attachment if (content->parent()) { const auto top = content->topLevel(); if (content == top->textContent()) return false; } // ignore crypto parts if (isCryptoPart(content)) return false; // content type or content disposition having a file name set looks like an attachment const auto contentDisposition = content->contentDisposition(false); if (contentDisposition && !contentDisposition->filename().isEmpty()) { return true; } if (contentType && !contentType->name().isEmpty()) { return true; } // "attachment" content disposition is otherwise a good indicator though if (contentDisposition && contentDisposition->disposition() == Headers::CDattachment) return true; return false; } bool hasAttachment(Content *content) { if (!content) return false; if (isAttachment(content)) return true; // Ok, content itself is not an attachment. now we deal with multiparts auto ct = content->contentType(false); if (ct && ct->isMultipart() && !ct->isSubtype("related")) {// && !ct->isSubtype("alternative")) { Q_FOREACH (Content *child, content->contents()) { if (hasAttachment(child)) { return true; } } } return false; } bool hasInvitation(Content *content) { if (!content) { return false; } if (isInvitation(content)) { return true; } // Ok, content itself is not an invitation. now we deal with multiparts if (content->contentType()->isMultipart()) { Q_FOREACH (Content *child, content->contents()) { if (hasInvitation(child)) { return true; } } } return false; } bool isSigned(Message *message) { if (!message) { return false; } const KMime::Headers::ContentType *const contentType = message->contentType(); if (contentType->isSubtype("signed") || contentType->isSubtype("pgp-signature") || contentType->isSubtype("pkcs7-signature") || contentType->isSubtype("x-pkcs7-signature") || message->mainBodyPart("multipart/signed") || message->mainBodyPart("application/pgp-signature") || message->mainBodyPart("application/pkcs7-signature") || message->mainBodyPart("application/x-pkcs7-signature")) { return true; } return false; } bool isEncrypted(Message *message) { if (!message) { return false; } const KMime::Headers::ContentType *const contentType = message->contentType(); if (contentType->isSubtype("encrypted") || contentType->isSubtype("pgp-encrypted") || contentType->isSubtype("pkcs7-mime") || contentType->isSubtype("x-pkcs7-mime") || message->mainBodyPart("multipart/encrypted") || message->mainBodyPart("application/pgp-encrypted") || message->mainBodyPart("application/pkcs7-mime") || message->mainBodyPart("application/x-pkcs7-mime")) { return true; } return false; } bool isInvitation(Content *content) { if (!content) { return false; } const KMime::Headers::ContentType *const contentType = content->contentType(false); if (contentType && contentType->isMediatype("text") && contentType->isSubtype("calendar")) { return true; } return false; } } // namespace KMime diff --git a/src/kmime_util.h b/src/kmime_util.h index 09744fc..618ac62 100644 --- a/src/kmime_util.h +++ b/src/kmime_util.h @@ -1,295 +1,325 @@ /* -*- c++ -*- kmime_util.h KMime, the KDE Internet mail/usenet news message library. Copyright (c) 2001 the KMime authors. See file AUTHORS for details This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __KMIME_UTIL_H__ #define __KMIME_UTIL_H__ #include "kmime_export.h" #include "kmime_headers.h" #include "kmime_content.h" #include #include namespace KMime { class Message; /** Checks whether @p s contains any non-us-ascii characters. @param s */ KMIME_EXPORT extern bool isUsAscii(const QString &s); /** Returns a user-visible string for a contentEncoding, for example "quoted-printable" for CEquPr. @param enc the contentEncoding to return string for @ since 4.4 TODO should they be i18n'ed? */ KMIME_EXPORT extern QString nameForEncoding(KMime::Headers::contentEncoding enc); /** Returns a list of encodings that can correctly encode the @p data. @param data the data to check encodings for @ since 4.4 */ Q_REQUIRED_RESULT KMIME_EXPORT QVector encodingsForData(const QByteArray &data); /** * Set whether or not to use outlook compatible attachment filename encoding. Outlook * fails to properly adhere to the RFC2322 standard for parametrized header fields, and * instead is only able to read and write attachment filenames encoded in RFC2047-style. * This will create mails that are not standards-compliant! * * @param violateStandard Whether or not to use outlook-compatible attachment * filename encodings. * * @since 4.5 */ KMIME_EXPORT extern void setUseOutlookAttachmentEncoding(bool violateStandard); /** * Retrieve whether or not to use outlook compatible encodings for attachments. */ KMIME_EXPORT extern bool useOutlookAttachmentEncoding(); /** Constructs a random string (sans leading/trailing "--") that can be used as a multipart delimiter (ie. as @p boundary parameter to a multipart/... content-type). @return the randomized string. @see uniqueString */ KMIME_EXPORT extern QByteArray multiPartBoundary(); /** Unfolds the given header if necessary. @param header The header to unfold. */ KMIME_EXPORT extern QByteArray unfoldHeader(const QByteArray &header); KMIME_EXPORT extern QByteArray unfoldHeader(const char *header, size_t headerSize); /** Tries to extract the header with name @p name from the string @p src, unfolding it if necessary. @param src the source string. @param name the name of the header to search for. @return the first instance of the header @p name in @p src or a null QByteArray if no such header was found. */ KMIME_EXPORT extern QByteArray extractHeader(const QByteArray &src, const QByteArray &name); /** Converts all occurrences of "\r\n" (CRLF) in @p s to "\n" (LF). This function is expensive and should be used only if the mail will be stored locally. All decode functions can cope with both line endings. @param s source string containing CRLF's @return the string with CRLF's substitued for LF's @see CRLFtoLF(const char*) LFtoCRLF */ KMIME_EXPORT extern QByteArray CRLFtoLF(const QByteArray &s); /** Converts all occurrences of "\r\n" (CRLF) in @p s to "\n" (LF). This function is expensive and should be used only if the mail will be stored locally. All decode functions can cope with both line endings. @param s source string containing CRLF's @return the string with CRLF's substitued for LF's @see CRLFtoLF(const QByteArray&) LFtoCRLF */ KMIME_EXPORT extern QByteArray CRLFtoLF(const char *s); /** Converts all occurrences of "\n" (LF) in @p s to "\r\n" (CRLF). This function is expensive and should be used only if the mail will be transmitted as an RFC822 message later. All decode functions can cope with and all encode functions can optionally produce both line endings, which is much faster. @param s source string containing CRLF's @return the string with CRLF's substitued for LF's @see CRLFtoLF(const QByteArray&) LFtoCRLF */ KMIME_EXPORT extern QByteArray LFtoCRLF(const QByteArray &s); +/** + Converts all occurrences of "\r" (CR) in @p s to "\n" (LF). + + This function is expensive and should be used only if the mail + will be stored locally. All decode functions can cope with both + line endings. + + @param s source string containing CR's + + @return the string with CR's substitued for LF's + @see CRtoLF(const QByteArray&) CRtoLF +*/ +KMIME_EXPORT extern QByteArray CRtoLF(const char *s); + +/** + Converts all occurrences of "\r" (CR) in @p s to "\n" (LF). + + This function is expensive and should be used only if the mail + will be transmitted as an RFC822 message later. All decode + functions can cope with and all encode functions can optionally + produce both line endings, which is much faster. + + @param s source string containing CR's + + @return the string with CR's substitued for LF's + @see CRtoLF(const QByteArray&) CRtoLF +*/ +KMIME_EXPORT extern QByteArray CRtoLF(const QByteArray &s); + + /** Removes quote (DQUOTE) characters and decodes "quoted-pairs" (ie. backslash-escaped characters) @param str the string to work on. @see addQuotes */ KMIME_EXPORT extern void removeQuotes(QByteArray &str); /** Removes quote (DQUOTE) characters and decodes "quoted-pairs" (ie. backslash-escaped characters) @param str the string to work on. @see addQuotes */ KMIME_EXPORT extern void removeQuotes(QString &str); /** Converts the given string into a quoted-string if the string contains any special characters (ie. one of ()<>@,.;:[]=\"). @param str us-ascii string to work on. @param forceQuotes if @c true, always add quote characters. */ KMIME_EXPORT extern void addQuotes(QByteArray &str, bool forceQuotes); /** * Overloaded method, behaves same as the above. * @param str us-ascii string to work on. * @param forceQuotes if @c true, always add quote characters. * @since 4.5 */ KMIME_EXPORT extern void addQuotes(QString &str, bool forceQuotes); /** * Makes sure that the bidirectional state at the end of the string is the * same as at the beginning of the string. * * This is useful so that Unicode control characters that can change the text * direction can not spill over to following strings. * * As an example, consider a mailbox in the form "display name" . * If the display name here contains unbalanced control characters that change the * text direction, it would also have an effect on the addrspec, which could lead to * spoofing. * * By passing the display name to this function, one can make sure that no change of * the bidi state can spill over to the next strings, in this case the addrspec. * * Example: The string "Hello World" is unbalanced, as it contains a right-to-left * override character, which is never followed by a , the "pop directional * formatting" character. This function adds the missing at the end, and * the output of this function would be "Hello World". * * Example of spoofing: * Consider "Firstname Lastname" . Because of the RLO, * it is displayed as "Firstname Lastname ", which spoofs the * domain name. * By passing "Firstname Lastname" to this function, one can balance the , * leading to "Firstname Lastname", so the whole mailbox is displayed * correctly as "Firstname Lastname" again. * * See https://unicode.org/reports/tr9 for more information on bidi control chars. * * @param input the display name of a mailbox, which is checked for unbalanced Unicode * direction control characters * @return the display name which now contains a balanced state of direction control * characters * * Note that this function does not do any parsing related to mailboxes, it only works * on plain strings. Therefore, passing the complete mailbox will not lead to any results, * only the display name should be passed. * * @since 4.5 */ KMIME_EXPORT QString balanceBidiState(const QString &input); /** * Similar to the above function. Instead of trying to balance the Bidi chars, it outright * removes them from the string. * * @param input the display name of a mailbox, which is checked for unbalanced Unicode * direction control characters * Reason: KHTML seems to ignore the PDF character, so adding them doesn't fix things :( */ KMIME_EXPORT QString removeBidiControlChars(const QString &input); /** * Returns whether or not the given MIME node is an attachment part. * @param content the MIME node to parse * @see hasAttachment() */ KMIME_EXPORT bool isAttachment(Content *content); /** * Returns whether or not the given MIME node contains an attachment part. This function will * recursively parse the MIME tree looking for a suitable attachment and return true if one is found. * @param content the MIME node to parse * @see isAttachment() */ KMIME_EXPORT bool hasAttachment(Content *content); /** * Returns whether or not the given MIME node contains an invitation part. This function will * recursively parse the MIME tree looking for a suitable invitation and return true if one is found. * @param content the MIME node to parse * @since 4.14.6 */ KMIME_EXPORT bool hasInvitation(Content *content); /** * Returns whether or not the given @p message is partly or fully signed. * * @param message the message to check for being signed * @since 4.6 */ KMIME_EXPORT bool isSigned(Message *message); /** * Returns whether or not the given @p message is partly or fully encrypted. * * @param message the message to check for being encrypted * @since 4.6 */ KMIME_EXPORT bool isEncrypted(Message *message); /** * Determines if the MIME part @p content is a crypto part. * This is, is either an encrypted part or a signature part. */ KMIME_EXPORT bool isCryptoPart(Content *content); /** * Returns whether or not the given MIME @p content is an invitation * message of the iTIP protocol. * * @since 4.6 */ KMIME_EXPORT bool isInvitation(Content *content); } // namespace KMime #endif /* __KMIME_UTIL_H__ */