12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827 |
- #include <kopano/platform.h>
- #include <exception>
- #include <utility>
- #include "VMIMEToMAPI.h"
- #include <kopano/ECGuid.h>
- #include <kopano/ECLogger.h>
- #include <kopano/memory.hpp>
- #include <algorithm>
- #include <memory>
- #include <string>
- #include <fstream>
- #include <iostream>
- #include <cassert>
- #include <cctype>
- #include <cstdlib>
- #include <cstring>
- #include <kopano/ECDebug.h>
- #include <librosie.h>
- #include <vmime/vmime.hpp>
- #include <vmime/platforms/posix/posixHandler.hpp>
- #include <vmime/contentTypeField.hpp>
- #include <vmime/contentDispositionField.hpp>
- #include <libxml/HTMLparser.h>
- #include <mapi.h>
- #include <mapix.h>
- #include <mapiutil.h>
- #include <kopano/mapiext.h>
- #include <kopano/mapiguidext.h>
- #include <edkmdb.h>
- #include <kopano/EMSAbTag.h>
- #include "tnef.h"
- #include <kopano/codepage.h>
- #include <kopano/Util.h>
- #include <kopano/CommonUtil.h>
- #include <kopano/MAPIErrors.h>
- #include <kopano/namedprops.h>
- #include <kopano/charset/convert.h>
- #include <kopano/stringutil.h>
- #include <kopano/mapi_ptr.h>
- #include "ECMapiUtils.h"
- #include "ECVMIMEUtils.h"
- #include "outputStreamMAPIAdapter.h"
- #include "ICalToMAPI.h"
- #include "config.h"
- using namespace std;
- using namespace KCHL;
- namespace KC {
- static vmime::charset vtm_upgrade_charset(vmime::charset cset, const char *ascii_upgrade = nullptr);
- static const char im_charset_unspec[] = "unspecified";
- static ULONG CreateIntDate(ULONG day, ULONG month, ULONG year)
- {
- return day + month * 32 + year * 32 * 16;
- }
- static ULONG CreateIntTime(ULONG seconds, ULONG minutes, ULONG hours)
- {
- return seconds + minutes * 64 + hours * 64 * 64;
- }
- static ULONG FileTimeToIntDate(const FILETIME &ft)
- {
- struct tm date;
- time_t t;
- FileTimeToUnixTime(ft, &t);
- gmtime_safe(&t, &date);
- return CreateIntDate(date.tm_mday, date.tm_mon+1, date.tm_year+1900);
- }
- static ULONG SecondsToIntTime(ULONG seconds)
- {
- ULONG hours = seconds / (60*60);
- seconds -= hours * 60 * 60;
- ULONG minutes = seconds / 60;
- seconds -= minutes * 60;
- return CreateIntTime(seconds, minutes, hours);
- }
- VMIMEToMAPI::VMIMEToMAPI()
- {
- imopt_default_delivery_options(&m_dopt);
- m_dopt.use_received_date = false;
- m_lpAdrBook = NULL;
- m_lpDefaultDir = NULL;
- m_dopt.html_safety_filter = false;
- }
- VMIMEToMAPI::VMIMEToMAPI(LPADRBOOK lpAdrBook, delivery_options dopt) :
- m_dopt(dopt), m_lpAdrBook(lpAdrBook)
- {
- }
- VMIMEToMAPI::~VMIMEToMAPI()
- {
- if (m_lpDefaultDir)
- m_lpDefaultDir->Release();
- }
- HRESULT VMIMEToMAPI::createIMAPProperties(const std::string &input, std::string *lpEnvelope, std::string *lpBody, std::string *lpBodyStructure)
- {
- auto vmMessage = vmime::make_shared<vmime::message>();
- vmMessage->parse(input);
- if (lpBody || lpBodyStructure)
- messagePartToStructure(input, vmMessage, lpBody, lpBodyStructure);
- if (lpEnvelope)
- *lpEnvelope = createIMAPEnvelope(vmMessage);
- return hrSuccess;
- }
- HRESULT VMIMEToMAPI::convertVMIMEToMAPI(const string &input, IMessage *lpMessage) {
- HRESULT hr = hrSuccess;
-
- ULONG ulAttNr;
- object_ptr<IStream> lpStream;
- ULONG nProps = 0;
- SPropValue attProps[3];
- SPropValue sPropSMIMEClass;
- object_ptr<IMAPITable> lpAttachTable;
- size_t posHeaderEnd;
- bool bUnix = false;
- try {
- if (m_mailState.ulMsgInMsg == 0)
- m_mailState.reset();
-
- posHeaderEnd = input.find("\r\n\r\n");
- if (posHeaderEnd == std::string::npos) {
-
- posHeaderEnd = input.find("\n\n");
- bUnix = true;
- }
- if (posHeaderEnd != std::string::npos) {
- SPropValue sPropHeaders;
- std::string strHeaders = input.substr(0, posHeaderEnd);
-
- if (bUnix)
- StringLFtoCRLF(strHeaders);
- sPropHeaders.ulPropTag = PR_TRANSPORT_MESSAGE_HEADERS_A;
- sPropHeaders.Value.lpszA = (char *) strHeaders.c_str();
- HrSetOneProp(lpMessage, &sPropHeaders);
- }
-
- SPropValue sMessageSize;
- sMessageSize.ulPropTag = PR_MESSAGE_SIZE;
- sMessageSize.Value.ul = input.length();
- lpMessage->SetProps(1, &sMessageSize, nullptr);
-
- auto vmMessage = vmime::make_shared<vmime::message>();
- vmMessage->parse(input);
-
- if (m_dopt.add_imap_data)
- createIMAPBody(input, vmMessage, lpMessage);
- hr = fillMAPIMail(vmMessage, lpMessage);
- if (hr != hrSuccess)
- return hr;
- if (m_mailState.bAttachSignature && !m_dopt.parse_smime_signed) {
- static constexpr const SizedSPropTagArray(2, sptaAttach) =
- {2, {PR_ATTACH_NUM, PR_ATTACHMENT_HIDDEN}};
-
-
-
- hr = lpMessage->GetAttachmentTable(0, &~lpAttachTable);
- if(hr != hrSuccess)
- return hr;
- rowset_ptr lpAttachRows;
- hr = HrQueryAllRows(lpAttachTable, sptaAttach, nullptr, nullptr, -1, &~lpAttachRows);
- if(hr != hrSuccess)
- return hr;
-
- for (unsigned int i = 0; i < lpAttachRows->cRows; ++i) {
- hr = lpMessage->DeleteAttach(lpAttachRows->aRow[i].lpProps[0].Value.ul, 0, NULL, 0);
- if(hr != hrSuccess)
- return hr;
- }
-
-
- auto vmHeader = vmMessage->getHeader();
- object_ptr<IAttach> lpAtt;
- hr = lpMessage->CreateAttach(nullptr, 0, &ulAttNr, &~lpAtt);
- if (hr != hrSuccess)
- return hr;
-
- hr = lpAtt->OpenProperty(PR_ATTACH_DATA_BIN, &IID_IStream, STGM_WRITE | STGM_TRANSACTED,
- MAPI_CREATE | MAPI_MODIFY, &~lpStream);
- if (hr != hrSuccess)
- return hr;
- outputStreamMAPIAdapter os(lpStream);
-
- vmHeader->ContentType()->generate(os);
-
-
- if (posHeaderEnd != string::npos)
- os.write(input.c_str() + posHeaderEnd, input.size() - posHeaderEnd);
- hr = lpStream->Commit(0);
- if (hr != hrSuccess)
- return hr;
- attProps[nProps].ulPropTag = PR_ATTACH_METHOD;
- attProps[nProps++].Value.ul = ATTACH_BY_VALUE;
- attProps[nProps].ulPropTag = PR_ATTACH_MIME_TAG_W;
- attProps[nProps++].Value.lpszW = const_cast<wchar_t *>(L"multipart/signed");
- attProps[nProps].ulPropTag = PR_RENDERING_POSITION;
- attProps[nProps++].Value.ul = -1;
- hr = lpAtt->SetProps(nProps, attProps, NULL);
- if (hr != hrSuccess)
- return hr;
- hr = lpAtt->SaveChanges(0);
- if (hr != hrSuccess)
- return hr;
-
-
- sPropSMIMEClass.ulPropTag = PR_MESSAGE_CLASS_W;
- sPropSMIMEClass.Value.lpszW = const_cast<wchar_t *>(L"IPM.Note.SMIME.MultipartSigned");
- hr = lpMessage->SetProps(1, &sPropSMIMEClass, NULL);
- if (hr != hrSuccess) {
- ec_log_err("Unable to set message class");
- return hr;
- }
- }
- if ((m_mailState.attachLevel == ATTACH_INLINE && m_mailState.bodyLevel == BODY_HTML) || (m_mailState.bAttachSignature && m_mailState.attachLevel <= ATTACH_INLINE)) {
-
- MAPINAMEID sNameID;
- LPMAPINAMEID lpNameID = &sNameID;
- memory_ptr<SPropTagArray> lpPropTag;
- sNameID.lpguid = (GUID*)&PSETID_Common;
- sNameID.ulKind = MNID_ID;
- sNameID.Kind.lID = dispidSmartNoAttach;
- hr = lpMessage->GetIDsFromNames(1, &lpNameID, MAPI_CREATE, &~lpPropTag);
- if (hr != hrSuccess)
- return hrSuccess;
- attProps[0].ulPropTag = CHANGE_PROP_TYPE(lpPropTag->aulPropTag[0], PT_BOOLEAN);
- attProps[0].Value.b = TRUE;
- hr = lpMessage->SetProps(1, attProps, NULL);
- if (hr != hrSuccess)
- return hrSuccess;
- }
- }
- catch (vmime::exception& e) {
- ec_log_err("VMIME exception: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (std::exception& e) {
- ec_log_err("STD exception: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (...) {
- ec_log_err("Unknown generic exception occurred");
- return MAPI_E_CALL_FAILED;
- }
- return hrSuccess;
- }
- HRESULT VMIMEToMAPI::fillMAPIMail(vmime::shared_ptr<vmime::message> vmMessage,
- IMessage *lpMessage)
- {
- HRESULT hr;
- SPropValue sPropDefaults[3];
- sPropDefaults[0].ulPropTag = PR_MESSAGE_CLASS_W;
- sPropDefaults[0].Value.lpszW = const_cast<wchar_t *>(L"IPM.Note");
- sPropDefaults[1].ulPropTag = PR_MESSAGE_FLAGS;
- sPropDefaults[1].Value.ul = (m_dopt.mark_as_read ? MSGFLAG_READ : 0) | MSGFLAG_UNMODIFIED;
-
-
-
-
-
-
-
- sPropDefaults[2].ulPropTag = PR_INTERNET_CPID;
- sPropDefaults[2].Value.ul = 65001;
- hr = lpMessage->SetProps(3, sPropDefaults, NULL);
- if (hr != hrSuccess) {
- ec_log_err("Unable to set default mail properties");
- return hr;
- }
- try {
-
-
- auto vmHeader = vmMessage->getHeader();
- auto vmBody = vmMessage->getBody();
- auto mt = vmime::dynamicCast<vmime::mediaType>(vmHeader->ContentType()->getValue());
-
- hr = handleRecipients(vmHeader, lpMessage);
- if (hr != hrSuccess) {
- ec_log_err("Unable to parse mail recipients");
- return hr;
- }
-
- hr = handleHeaders(vmHeader, lpMessage);
- if (hr != hrSuccess) {
- ec_log_err("Unable to parse mail headers");
- return hr;
- }
- if (vmime::mdn::MDNHelper::isMDN(vmMessage) == true)
- {
- vmime::mdn::receivedMDNInfos receivedMDN = vmime::mdn::MDNHelper::getReceivedMDN(vmMessage);
- auto myBody = vmMessage->getBody();
-
-
-
-
- for (size_t i = 0; i < myBody->getPartCount(); ++i) {
- auto bPart = myBody->getPartAt(i);
- auto ctf = bPart->getHeader()->findField(vmime::fields::CONTENT_TYPE);
- if ((vmime::dynamicCast<vmime::mediaType>(ctf->getValue())->getType() == vmime::mediaTypes::TEXT &&
- vmime::dynamicCast<vmime::mediaType>(ctf->getValue())->getSubType() == vmime::mediaTypes::TEXT_PLAIN) ||
- (vmime::dynamicCast<vmime::mediaType>(ctf->getValue())->getType() == vmime::mediaTypes::MULTIPART &&
- vmime::dynamicCast<vmime::mediaType>(ctf->getValue())->getSubType() == vmime::mediaTypes::MULTIPART_ALTERNATIVE)) {
- hr = dissect_body(bPart->getHeader(), bPart->getBody(), lpMessage);
- if (hr != hrSuccess) {
- ec_log_err("Unable to parse MDN mail body");
- return hr;
- }
-
- break;
- }
- }
- if (receivedMDN.getDisposition().getType() == vmime::dispositionTypes::DELETED)
- {
- sPropDefaults[0].ulPropTag = PR_MESSAGE_CLASS_W;
- sPropDefaults[0].Value.lpszW = const_cast<wchar_t *>(L"REPORT.IPM.Note.IPNNRN");
- } else {
- sPropDefaults[0].ulPropTag = PR_MESSAGE_CLASS_W;
- sPropDefaults[0].Value.lpszW = const_cast<wchar_t *>(L"REPORT.IPM.Note.IPNRN");
- }
- string strId = "<"+receivedMDN.getOriginalMessageId().getId()+">";
- sPropDefaults[1].ulPropTag = 0x1046001E;
- sPropDefaults[1].Value.lpszA = (LPSTR)strId.c_str();
- hr = lpMessage->SetProps(2, sPropDefaults, NULL);
- if (hr != hrSuccess) {
- ec_log_err("Unable to set MDN mail properties");
- return hr;
- }
- } else {
-
- hr = dissect_body(vmHeader, vmBody, lpMessage);
- if (hr != hrSuccess) {
- ec_log_err("Unable to parse mail body");
- return hr;
- }
- }
- }
- catch (vmime::exception& e) {
- ec_log_err("VMIME exception on create message: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (std::exception& e) {
- ec_log_err("STD exception on create message: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (...) {
- ec_log_err("Unknown generic exception occurred on create message");
- return MAPI_E_CALL_FAILED;
- }
- createIMAPEnvelope(vmMessage, lpMessage);
-
- postWriteFixups(lpMessage);
- return hr;
- }
- HRESULT VMIMEToMAPI::handleHeaders(vmime::shared_ptr<vmime::header> vmHeader,
- IMessage *lpMessage)
- {
- HRESULT hr = hrSuccess;
- std::string strInternetMessageId, strInReplyTos, strReferences;
- std::wstring wstrSubject;
- std::wstring wstrReplyTo, wstrReplyToMail;
- std::string strClientTime;
- std::wstring wstrFromName, wstrSenderName;
- std::string strFromEmail, strFromSearchKey;
- std::string strSenderEmail, strSenderSearchKey;
- ULONG cbFromEntryID;
- memory_ptr<ENTRYID> lpFromEntryID, lpSenderEntryID;
- ULONG cbSenderEntryID;
- SPropValue sConTopic;
-
- memory_ptr<FLATENTRY> lpEntry;
- memory_ptr<FLATENTRYLIST> lpEntryList;
- ULONG cb = 0;
- int nProps = 0;
- SPropValue msgProps[22];
-
- ULONG cbEntryID;
- memory_ptr<ENTRYID> lpEntryID;
- memory_ptr<SPropValue> lpRecipProps, lpPropNormalizedSubject;
- ULONG ulRecipProps;
-
- static constexpr const SizedSPropTagArray(7, sptaRecipPropsSentRepr) = {7, {
- PR_SENT_REPRESENTING_ADDRTYPE_W, PR_SENT_REPRESENTING_NAME_W,
- PR_NULL ,
- PR_SENT_REPRESENTING_EMAIL_ADDRESS_W, PR_SENT_REPRESENTING_ENTRYID,
- PR_SENT_REPRESENTING_SEARCH_KEY, PR_NULL
- } };
- static constexpr const SizedSPropTagArray(7, sptaRecipPropsSender) = {7, {
- PR_SENDER_ADDRTYPE_W, PR_SENDER_NAME_W,
- PR_NULL ,
- PR_SENDER_EMAIL_ADDRESS_W, PR_SENDER_ENTRYID,
- PR_SENDER_SEARCH_KEY, PR_NULL
- } };
- try {
-
- if(vmHeader->hasField(vmime::fields::MESSAGE_ID)) {
- strInternetMessageId = vmHeader->MessageId()->getValue()->generate();
- msgProps[nProps].ulPropTag = PR_INTERNET_MESSAGE_ID_A;
- msgProps[nProps++].Value.lpszA = (char*)strInternetMessageId.c_str();
- }
-
- if(vmHeader->hasField(vmime::fields::IN_REPLY_TO)) {
- strInReplyTos = vmHeader->InReplyTo()->getValue()->generate();
- msgProps[nProps].ulPropTag = PR_IN_REPLY_TO_ID_A;
- msgProps[nProps++].Value.lpszA = (char*)strInReplyTos.c_str();
- }
-
- if(vmHeader->hasField(vmime::fields::REFERENCES)) {
- strReferences = vmHeader->References()->getValue()->generate();
- msgProps[nProps].ulPropTag = PR_INTERNET_REFERENCES_A;
- msgProps[nProps++].Value.lpszA = (char*)strReferences.c_str();
- }
-
- if(vmHeader->hasField(vmime::fields::SUBJECT)) {
- wstrSubject = getWideFromVmimeText(*vmime::dynamicCast<vmime::text>(vmHeader->Subject()->getValue()));
- msgProps[nProps].ulPropTag = PR_SUBJECT_W;
- msgProps[nProps++].Value.lpszW = (WCHAR *)wstrSubject.c_str();
- }
-
- if (!vmime::dynamicCast<vmime::mailbox>(vmHeader->ReplyTo()->getValue())->isEmpty()) {
-
- wstrReplyTo = getWideFromVmimeText(vmime::dynamicCast<vmime::mailbox>(vmHeader->ReplyTo()->getValue())->getName());
- wstrReplyToMail = m_converter.convert_to<wstring>(vmime::dynamicCast<vmime::mailbox>(vmHeader->ReplyTo()->getValue())->getEmail().toString());
- if (wstrReplyTo.empty())
- wstrReplyTo = wstrReplyToMail;
- msgProps[nProps].ulPropTag = PR_REPLY_RECIPIENT_NAMES_W;
- msgProps[nProps++].Value.lpszW = (WCHAR *)wstrReplyTo.c_str();
-
- hr = ECCreateOneOff((LPTSTR)wstrReplyTo.c_str(), (LPTSTR)L"SMTP", (LPTSTR)wstrReplyToMail.c_str(), MAPI_UNICODE | MAPI_SEND_NO_RICH_INFO, &cbEntryID, &~lpEntryID);
- if (hr != hrSuccess)
- return hr;
- cb = CbNewFLATENTRY(cbEntryID);
- hr = MAPIAllocateBuffer(cb, &~lpEntry);
- if (hr != hrSuccess)
- return hr;
- memcpy(lpEntry->abEntry, lpEntryID, cbEntryID);
- lpEntry->cb = cbEntryID;
- cb = CbNewFLATENTRYLIST(cb);
- hr = MAPIAllocateBuffer(cb, &~lpEntryList);
- if (hr != hrSuccess)
- return hr;
- lpEntryList->cEntries = 1;
- lpEntryList->cbEntries = CbFLATENTRY(lpEntry);
- memcpy(&lpEntryList->abEntries, lpEntry, CbFLATENTRY(lpEntry));
- msgProps[nProps].ulPropTag = PR_REPLY_RECIPIENT_ENTRIES;
- msgProps[nProps].Value.bin.cb = CbFLATENTRYLIST(lpEntryList);
- msgProps[nProps++].Value.bin.lpb = reinterpret_cast<unsigned char *>(lpEntryList.get());
- }
-
- if(vmHeader->hasField(vmime::fields::DATE)) {
- msgProps[nProps].ulPropTag = PR_CLIENT_SUBMIT_TIME;
- msgProps[nProps++].Value.ft = vmimeDatetimeToFiletime(*vmime::dynamicCast<vmime::datetime>(vmHeader->Date()->getValue()));
-
- vmime::datetime d = *vmime::dynamicCast<vmime::datetime>(vmHeader->Date()->getValue());
- d.setTime(0,0,0,0);
- msgProps[nProps].ulPropTag = PR_EC_CLIENT_SUBMIT_DATE;
- msgProps[nProps++].Value.ft = vmimeDatetimeToFiletime(d);
- }
-
-
- vmime::datetime date = vmime::datetime::now();
- bool found_date = false;
- if (m_dopt.use_received_date || m_mailState.ulMsgInMsg) {
- if (vmHeader->hasField("Received")) {
- auto recv = vmime::dynamicCast<vmime::relay>(vmHeader->findField("Received")->getValue());
- if (recv) {
- date = recv->getDate();
- found_date = true;
- }
- } else if (m_mailState.ulMsgInMsg) {
- date = *vmime::dynamicCast<vmime::datetime>(vmHeader->Date()->getValue());
- found_date = true;
- } else {
- date = vmime::datetime::now();
- }
- }
-
-
-
- if (!m_dopt.parse_smime_signed && (!m_mailState.ulMsgInMsg || found_date)) {
- msgProps[nProps].ulPropTag = PR_MESSAGE_DELIVERY_TIME;
- msgProps[nProps++].Value.ft = vmimeDatetimeToFiletime(date);
-
- date.setTime(0,0,0,0);
- msgProps[nProps].ulPropTag = PR_EC_MESSAGE_DELIVERY_DATE;
- msgProps[nProps++].Value.ft = vmimeDatetimeToFiletime(date);
- }
-
- if(vmHeader->hasField(vmime::fields::FROM)) {
- strFromEmail = vmime::dynamicCast<vmime::mailbox>(vmHeader->From()->getValue())->getEmail().toString();
- if (!vmime::dynamicCast<vmime::mailbox>(vmHeader->From()->getValue())->getName().isEmpty())
- wstrFromName = getWideFromVmimeText(vmime::dynamicCast<vmime::mailbox>(vmHeader->From()->getValue())->getName());
- hr = modifyFromAddressBook(&~lpRecipProps, &ulRecipProps,
- strFromEmail.c_str(), wstrFromName.c_str(),
- MAPI_ORIG, sptaRecipPropsSentRepr);
- if (hr == hrSuccess) {
- hr = lpMessage->SetProps(ulRecipProps, lpRecipProps, NULL);
- if (hr != hrSuccess)
- return hr;
- } else {
- if (wstrFromName.empty())
- wstrFromName = m_converter.convert_to<wstring>(strFromEmail);
- msgProps[nProps].ulPropTag = PR_SENT_REPRESENTING_NAME_W;
- msgProps[nProps++].Value.lpszW = (WCHAR *)wstrFromName.c_str();
- msgProps[nProps].ulPropTag = PR_SENT_REPRESENTING_EMAIL_ADDRESS_A;
- msgProps[nProps++].Value.lpszA = (char*)strFromEmail.c_str();
- strFromSearchKey = strToUpper("SMTP:" + strFromEmail);
- msgProps[nProps].ulPropTag = PR_SENT_REPRESENTING_SEARCH_KEY;
- msgProps[nProps].Value.bin.cb = strFromSearchKey.size()+1;
- msgProps[nProps++].Value.bin.lpb = (BYTE*)strFromSearchKey.c_str();
- msgProps[nProps].ulPropTag = PR_SENT_REPRESENTING_ADDRTYPE_W;
- msgProps[nProps++].Value.lpszW = const_cast<wchar_t *>(L"SMTP");
- hr = ECCreateOneOff((LPTSTR)wstrFromName.c_str(), (LPTSTR)L"SMTP", (LPTSTR)m_converter.convert_to<wstring>(strFromEmail).c_str(),
- MAPI_UNICODE | MAPI_SEND_NO_RICH_INFO, &cbFromEntryID, &~lpFromEntryID);
- if(hr != hrSuccess)
- return hr;
- msgProps[nProps].ulPropTag = PR_SENT_REPRESENTING_ENTRYID;
- msgProps[nProps].Value.bin.cb = cbFromEntryID;
- msgProps[nProps++].Value.bin.lpb = reinterpret_cast<unsigned char *>(lpFromEntryID.get());
-
- }
- }
-
- if (vmHeader->hasField(vmime::fields::SENDER) || vmHeader->hasField(vmime::fields::FROM)) {
-
- strSenderEmail = vmime::dynamicCast<vmime::mailbox>(vmHeader->Sender()->getValue())->getEmail().toString();
- if (vmime::dynamicCast<vmime::mailbox>(vmHeader->Sender()->getValue())->getName().isEmpty() &&
- (strSenderEmail.empty() || strSenderEmail == "@")) {
-
- wstrSenderName = wstrFromName;
- strSenderEmail = strFromEmail;
- } else if (!vmime::dynamicCast<vmime::mailbox>(vmHeader->Sender()->getValue())->getName().isEmpty()) {
- wstrSenderName = getWideFromVmimeText(vmime::dynamicCast<vmime::mailbox>(vmHeader->Sender()->getValue())->getName());
- } else {
- wstrSenderName = m_converter.convert_to<wstring>(strSenderEmail);
- }
- hr = modifyFromAddressBook(&~lpRecipProps, &ulRecipProps,
- strSenderEmail.c_str(), wstrSenderName.c_str(),
- MAPI_ORIG, sptaRecipPropsSender);
- if (hr == hrSuccess) {
- hr = lpMessage->SetProps(ulRecipProps, lpRecipProps, NULL);
- if (hr != hrSuccess)
- return hr;
- } else {
- msgProps[nProps].ulPropTag = PR_SENDER_NAME_W;
- msgProps[nProps++].Value.lpszW = (WCHAR *)wstrSenderName.c_str();
- msgProps[nProps].ulPropTag = PR_SENDER_EMAIL_ADDRESS_A;
- msgProps[nProps++].Value.lpszA = (char*)strSenderEmail.c_str();
- strSenderSearchKey = strToUpper("SMTP:" + strSenderEmail);
- msgProps[nProps].ulPropTag = PR_SENDER_SEARCH_KEY;
- msgProps[nProps].Value.bin.cb = strSenderSearchKey.size()+1;
- msgProps[nProps++].Value.bin.lpb = (BYTE*)strSenderSearchKey.c_str();
- msgProps[nProps].ulPropTag = PR_SENDER_ADDRTYPE_W;
- msgProps[nProps++].Value.lpszW = const_cast<wchar_t *>(L"SMTP");
- hr = ECCreateOneOff((LPTSTR)wstrSenderName.c_str(), (LPTSTR)L"SMTP", (LPTSTR)m_converter.convert_to<wstring>(strSenderEmail).c_str(),
- MAPI_UNICODE | MAPI_SEND_NO_RICH_INFO, &cbSenderEntryID, &~lpSenderEntryID);
- if(hr != hrSuccess)
- return hr;
- msgProps[nProps].ulPropTag = PR_SENDER_ENTRYID;
- msgProps[nProps].Value.bin.cb = cbSenderEntryID;
- msgProps[nProps++].Value.bin.lpb = reinterpret_cast<unsigned char *>(lpSenderEntryID.get());
- }
- }
-
- hr = lpMessage->SetProps(nProps, msgProps, NULL);
- if (hr != hrSuccess)
- return hr;
-
- if (vmHeader->hasField("Thread-Topic"))
- {
- wstring convTT = getWideFromVmimeText(*vmime::dynamicCast<vmime::text>(vmHeader->findField("Thread-Topic")->getValue()));
- sConTopic.ulPropTag = PR_CONVERSATION_TOPIC_W;
- sConTopic.Value.lpszW = (WCHAR *)convTT.c_str();
- hr = lpMessage->SetProps(1, &sConTopic, NULL);
- if (hr != hrSuccess)
- return hr;
- } else if (HrGetOneProp(lpMessage, PR_NORMALIZED_SUBJECT_W, &~lpPropNormalizedSubject) == hrSuccess) {
- sConTopic.ulPropTag = PR_CONVERSATION_TOPIC_W;
- sConTopic.Value.lpszW = lpPropNormalizedSubject->Value.lpszW;
-
- hr = lpMessage->SetProps(1, &sConTopic, NULL);
- if (hr != hrSuccess)
- return hr;
- }
-
- if (vmHeader->hasField("Thread-Index"))
- {
- vmime::string outString;
- SPropValue sThreadIndex;
- string threadIndex = vmHeader->findField("Thread-Index")->getValue()->generate();
- auto enc = vmime::utility::encoder::encoderFactory::getInstance()->create("base64");
- vmime::utility::inputStreamStringAdapter in(threadIndex);
- vmime::utility::outputStreamStringAdapter out(outString);
- enc->decode(in, out);
- sThreadIndex.ulPropTag = PR_CONVERSATION_INDEX;
- sThreadIndex.Value.bin.cb = outString.size();
- sThreadIndex.Value.bin.lpb = (LPBYTE)outString.c_str();
- hr = lpMessage->SetProps(1, &sThreadIndex, NULL);
- if (hr != hrSuccess)
- return hr;
- }
-
- if (vmHeader->hasField("Importance")) {
- SPropValue sPriority[2];
- sPriority[0].ulPropTag = PR_PRIORITY;
- sPriority[1].ulPropTag = PR_IMPORTANCE;
- auto importance = strToLower(vmHeader->findField("Importance")->getValue()->generate());
- if(importance.compare("high") == 0) {
- sPriority[0].Value.ul = PRIO_URGENT;
- sPriority[1].Value.ul = IMPORTANCE_HIGH;
- } else if(importance.compare("low") == 0) {
- sPriority[0].Value.ul = PRIO_NONURGENT;
- sPriority[1].Value.ul = IMPORTANCE_LOW;
- } else {
- sPriority[0].Value.ul = PRIO_NORMAL;
- sPriority[1].Value.ul = IMPORTANCE_NORMAL;
- }
- hr = lpMessage->SetProps(2, sPriority, NULL);
- if (hr != hrSuccess)
- return hr;
- }
-
- if (vmHeader->hasField("X-Priority")) {
- SPropValue sPriority[2];
- sPriority[0].ulPropTag = PR_PRIORITY;
- sPriority[1].ulPropTag = PR_IMPORTANCE;
- string xprio = vmHeader->findField("X-Priority")->getValue()->generate();
- switch (xprio[0]) {
- case '1':
- case '2':
- sPriority[0].Value.ul = PRIO_URGENT;
- sPriority[1].Value.ul = IMPORTANCE_HIGH;
- break;
- case '4':
- case '5':
- sPriority[0].Value.ul = PRIO_NONURGENT;
- sPriority[1].Value.ul = IMPORTANCE_LOW;
- break;
- default:
- case '3':
- sPriority[0].Value.ul = PRIO_NORMAL;
- sPriority[1].Value.ul = IMPORTANCE_NORMAL;
- break;
- };
- hr = lpMessage->SetProps(2, sPriority, NULL);
- if (hr != hrSuccess)
- return hr;
- }
-
- if (vmHeader->hasField("X-Kopano-Vacation")) {
- SPropValue sIcon[1];
- sIcon[0].ulPropTag = PR_ICON_INDEX;
- sIcon[0].Value.l = ICON_MAIL_OOF;
-
- hr = lpMessage->SetProps(1, sIcon, NULL);
- if (hr != hrSuccess)
- return hr;
- }
-
- if (vmHeader->hasField("Sensitivity")) {
- SPropValue sSensitivity[1];
- auto sensitivity = strToLower(vmHeader->findField("Sensitivity")->getValue()->generate());
- sSensitivity[0].ulPropTag = PR_SENSITIVITY;
- if (sensitivity.compare("personal") == 0)
- sSensitivity[0].Value.ul = SENSITIVITY_PERSONAL;
- else if (sensitivity.compare("private") == 0)
- sSensitivity[0].Value.ul = SENSITIVITY_PRIVATE;
- else if (sensitivity.compare("company-confidential") == 0)
- sSensitivity[0].Value.ul = SENSITIVITY_COMPANY_CONFIDENTIAL;
- else
- sSensitivity[0].Value.ul = SENSITIVITY_NONE;
- hr = lpMessage->SetProps(1, sSensitivity, NULL);
- if (hr != hrSuccess)
- return hr;
- }
-
- try {
- if (vmHeader->hasField("Expiry-Time")) {
- SPropValue sExpiryTime;
-
- vmime::datetime expiry(vmHeader->findField("Expiry-Time")->getValue()->generate());
- sExpiryTime.ulPropTag = PR_EXPIRY_TIME;
- sExpiryTime.Value.ft = vmimeDatetimeToFiletime(expiry);
- hr = lpMessage->SetProps(1, &sExpiryTime, NULL);
- if (hr != hrSuccess)
- return hr;
- }
- }
- catch(...) {}
-
-
- if (vmHeader->hasField("Disposition-Notification-To") &&
- !vmime::dynamicCast<vmime::mailboxList>(vmHeader->DispositionNotificationTo()->getValue())->isEmpty())
- {
- auto mbReadReceipt = vmime::dynamicCast<vmime::mailboxList>(vmHeader->DispositionNotificationTo()->getValue())->getMailboxAt(0);
- if (mbReadReceipt && !mbReadReceipt->isEmpty())
- {
- wstring wstrRRName = getWideFromVmimeText(mbReadReceipt->getName());
- wstring wstrRREmail = m_converter.convert_to<wstring>(mbReadReceipt->getEmail().toString());
- if (wstrRRName.empty())
- wstrRRName = wstrRREmail;
-
- hr = ECCreateOneOff((LPTSTR)wstrRRName.c_str(), (LPTSTR)L"SMTP", (LPTSTR)wstrRREmail.c_str(), MAPI_UNICODE | MAPI_SEND_NO_RICH_INFO, &cbEntryID, &~lpEntryID);
- if (hr != hrSuccess)
- return hr;
- SPropValue sRRProps[4];
- sRRProps[0].ulPropTag = PR_READ_RECEIPT_REQUESTED;
- sRRProps[0].Value.b = true;
-
- sRRProps[1].ulPropTag = PR_MESSAGE_FLAGS;
- sRRProps[1].Value.ul = (m_dopt.mark_as_read ? MSGFLAG_READ : 0) | MSGFLAG_UNMODIFIED | MSGFLAG_RN_PENDING | MSGFLAG_NRN_PENDING;
- sRRProps[2].ulPropTag = PR_REPORT_ENTRYID;
- sRRProps[2].Value.bin.cb = cbEntryID;
- sRRProps[2].Value.bin.lpb = reinterpret_cast<unsigned char *>(lpEntryID.get());
- sRRProps[3].ulPropTag = PR_REPORT_NAME_W;
- sRRProps[3].Value.lpszW = (WCHAR *)wstrRREmail.c_str();
- hr = lpMessage->SetProps(4, sRRProps, NULL);
- if (hr != hrSuccess)
- return hr;
- }
- }
- for (const auto &field : vmHeader->getFieldList()) {
- std::string value, name = field->getName();
-
- if (name[0] != 'X')
- continue;
-
- if (name == "X-Priority")
- continue;
- name = strToLower(name);
- memory_ptr<MAPINAMEID> lpNameID;
- memory_ptr<SPropTagArray> lpPropTags;
- if ((hr = MAPIAllocateBuffer(sizeof(MAPINAMEID), &~lpNameID)) != hrSuccess)
- return hr;
- lpNameID->lpguid = (GUID*)&PS_INTERNET_HEADERS;
- lpNameID->ulKind = MNID_STRING;
- int vlen = mbstowcs(NULL, name.c_str(), 0) +1;
- if ((hr = MAPIAllocateMore(vlen*sizeof(WCHAR), lpNameID, (void**)&lpNameID->Kind.lpwstrName)) != hrSuccess)
- return hr;
- mbstowcs(lpNameID->Kind.lpwstrName, name.c_str(), vlen);
- hr = lpMessage->GetIDsFromNames(1, &+lpNameID, MAPI_CREATE, &~lpPropTags);
- if (hr != hrSuccess) {
- hr = hrSuccess;
- continue;
- }
- SPropValue sProp[1];
- value = field->getValue()->generate();
- sProp[0].ulPropTag = PROP_TAG(PT_STRING8, PROP_ID(lpPropTags->aulPropTag[0]));
- sProp[0].Value.lpszA = (char*)value.c_str();
- lpMessage->SetProps(1, sProp, NULL);
-
- }
- }
- catch (vmime::exception& e) {
- ec_log_err("VMIME exception on parsing headers: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (std::exception& e) {
- ec_log_err("STD exception on parsing headers: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (...) {
- ec_log_err("Unknown generic exception occurred on parsing headers");
- return MAPI_E_CALL_FAILED;
- }
- return hr;
- }
- HRESULT VMIMEToMAPI::handleMessageToMeProps(IMessage *lpMessage, LPADRLIST lpRecipients) {
- unsigned int i = 0;
- bool bToMe = false;
- bool bCcMe = false;
- bool bRecipMe = false;
- SPropValue sProps[3];
- if (m_dopt.user_entryid == NULL)
- return hrSuccess;
-
- for (i = 0; i < lpRecipients->cEntries; ++i) {
- auto lpRecipType = PCpropFindProp(lpRecipients->aEntries[i].rgPropVals, lpRecipients->aEntries[i].cValues, PR_RECIPIENT_TYPE);
- auto lpEntryId = PCpropFindProp(lpRecipients->aEntries[i].rgPropVals, lpRecipients->aEntries[i].cValues, PR_ENTRYID);
- if(lpRecipType == NULL)
- continue;
- if(lpEntryId == NULL)
- continue;
-
- if(lpEntryId->Value.bin.cb != m_dopt.user_entryid->cb)
- continue;
- if(memcmp(lpEntryId->Value.bin.lpb, m_dopt.user_entryid->lpb, lpEntryId->Value.bin.cb) != 0)
- continue;
-
- bRecipMe = true;
- if(lpRecipType->Value.ul == MAPI_TO)
- bToMe = true;
- else if(lpRecipType->Value.ul == MAPI_CC)
- bCcMe = true;
- }
-
- sProps[0].ulPropTag = PR_MESSAGE_RECIP_ME;
- sProps[0].Value.b = bRecipMe;
- sProps[1].ulPropTag = PR_MESSAGE_TO_ME;
- sProps[1].Value.b = bToMe;
- sProps[2].ulPropTag = PR_MESSAGE_CC_ME;
- sProps[2].Value.b = bCcMe;
- lpMessage->SetProps(3, sProps, NULL);
- return hrSuccess;
- }
- HRESULT VMIMEToMAPI::handleRecipients(vmime::shared_ptr<vmime::header> vmHeader,
- IMessage *lpMessage)
- {
- HRESULT hr = hrSuccess;
- adrlist_ptr lpRecipients;
- try {
- auto lpVMAListRecip = vmime::dynamicCast<vmime::addressList>(vmHeader->To()->getValue());
- auto lpVMAListCopyRecip = vmime::dynamicCast<vmime::addressList>(vmHeader->Cc()->getValue());
- auto lpVMAListBlCpRecip = vmime::dynamicCast<vmime::addressList>(vmHeader->Bcc()->getValue());
- int iAdresCount = lpVMAListRecip->getAddressCount() + lpVMAListCopyRecip->getAddressCount() + lpVMAListBlCpRecip->getAddressCount();
- if (iAdresCount == 0)
- return hr;
- hr = MAPIAllocateBuffer(CbNewADRLIST(iAdresCount), &~lpRecipients);
- if (hr != hrSuccess)
- return hr;
- lpRecipients->cEntries = 0;
- if (!lpVMAListRecip->isEmpty()) {
- hr = modifyRecipientList(lpRecipients, lpVMAListRecip, MAPI_TO);
- if (hr != hrSuccess)
- return hr;
- }
- if (!lpVMAListCopyRecip->isEmpty()) {
- hr = modifyRecipientList(lpRecipients, lpVMAListCopyRecip, MAPI_CC);
- if (hr != hrSuccess)
- return hr;
- }
- if (!lpVMAListBlCpRecip->isEmpty()) {
- hr = modifyRecipientList(lpRecipients, lpVMAListBlCpRecip, MAPI_BCC);
- if (hr != hrSuccess)
- return hr;
- }
-
-
- hr = handleMessageToMeProps(lpMessage, lpRecipients);
- if (hr != hrSuccess)
- return hr;
-
- hr = lpMessage->ModifyRecipients(MODRECIP_ADD, lpRecipients);
- if (hr != hrSuccess)
- return hr;
- }
- catch (vmime::exception& e) {
- ec_log_err("VMIME exception on recipients: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (std::exception& e) {
- ec_log_err("STD exception on recipients: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (...) {
- ec_log_err("Unknown generic exception occurred on recipients");
- return MAPI_E_CALL_FAILED;
- }
- return hrSuccess;
- }
- HRESULT VMIMEToMAPI::modifyRecipientList(LPADRLIST lpRecipients,
- vmime::shared_ptr<vmime::addressList> vmAddressList, ULONG ulRecipType)
- {
- HRESULT hr = hrSuccess;
- int iAddressCount = vmAddressList->getAddressCount();
- ULONG cbEntryID = 0;
- memory_ptr<ENTRYID> lpEntryID;
- vmime::shared_ptr<vmime::mailbox> mbx;
- vmime::shared_ptr<vmime::mailboxGroup> grp;
- vmime::shared_ptr<vmime::address> vmAddress;
- std::wstring wstrName;
- std::string strEmail, strSearch;
- unsigned int iRecipNum = 0;
-
- static constexpr const SizedSPropTagArray(7, sptaRecipientProps) =
- {7, {PR_ADDRTYPE_W, PR_DISPLAY_NAME_W, PR_DISPLAY_TYPE,
- PR_EMAIL_ADDRESS_W, PR_ENTRYID, PR_SEARCH_KEY,
- PR_SMTP_ADDRESS_W}};
-
- for (int iRecip = 0; iRecip < iAddressCount; ++iRecip) {
-
- try {
- vmime::text vmText;
- mbx = NULL;
- grp = NULL;
- vmAddress = vmAddressList->getAddressAt(iRecip);
-
- if (vmAddress->isGroup()) {
- grp = vmime::dynamicCast<vmime::mailboxGroup>(vmAddress);
- if (!grp)
- continue;
- strEmail.clear();
- vmText = grp->getName();
- if (grp->isEmpty() && vmText == vmime::text("undisclosed-recipients"))
- continue;
- } else {
- mbx = vmime::dynamicCast<vmime::mailbox>(vmAddress);
- if (!mbx)
- continue;
- strEmail = mbx->getEmail().toString();
- vmText = mbx->getName();
- }
- if (!vmText.isEmpty())
- wstrName = getWideFromVmimeText(vmText);
- else
- wstrName.clear();
- }
- catch (vmime::exception& e) {
- ec_log_err("VMIME exception on modify recipient: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (std::exception& e) {
- ec_log_err("STD exception on modify recipient: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (...) {
- ec_log_err("Unknown generic exception occurred on modify recipient");
- return MAPI_E_CALL_FAILED;
- }
- iRecipNum = lpRecipients->cEntries;
-
- strSearch = strEmail;
- if (strSearch.empty())
- strSearch = m_converter.convert_to<std::string>(wstrName);
-
- hr = modifyFromAddressBook(&lpRecipients->aEntries[iRecipNum].rgPropVals,
- &lpRecipients->aEntries[iRecipNum].cValues,
- strSearch.c_str(), NULL, ulRecipType, sptaRecipientProps);
- if (hr != hrSuccess) {
-
- int iNumTags = 8;
-
- iRecipNum = lpRecipients->cEntries;
- if (wstrName.empty())
- wstrName = m_converter.convert_to<wstring>(strEmail);
-
- hr = MAPIAllocateBuffer(sizeof(SPropValue) * iNumTags, (void **)&lpRecipients->aEntries[iRecipNum].rgPropVals);
- if (hr != hrSuccess)
- return hr;
-
- lpRecipients->aEntries[iRecipNum].cValues = iNumTags;
- lpRecipients->aEntries[iRecipNum].ulReserved1 = 0;
-
- lpRecipients->aEntries[iRecipNum].rgPropVals[0].ulPropTag = PR_RECIPIENT_TYPE;
- lpRecipients->aEntries[iRecipNum].rgPropVals[0].Value.l = ulRecipType;
-
- lpRecipients->aEntries[iRecipNum].rgPropVals[1].ulPropTag = PR_DISPLAY_NAME_W;
- hr = MAPIAllocateMore((wstrName.size()+1) * sizeof(WCHAR), lpRecipients->aEntries[iRecipNum].rgPropVals,
- (void **)&lpRecipients->aEntries[iRecipNum].rgPropVals[1].Value.lpszW);
- if (hr != hrSuccess)
- return hr;
- wcscpy(lpRecipients->aEntries[iRecipNum].rgPropVals[1].Value.lpszW, wstrName.c_str());
- lpRecipients->aEntries[iRecipNum].rgPropVals[2].ulPropTag = PR_SMTP_ADDRESS_A;
- hr = MAPIAllocateMore(strEmail.size()+1, lpRecipients->aEntries[iRecipNum].rgPropVals,
- (void **)&lpRecipients->aEntries[iRecipNum].rgPropVals[2].Value.lpszA);
- if (hr != hrSuccess)
- return hr;
- strcpy(lpRecipients->aEntries[iRecipNum].rgPropVals[2].Value.lpszA, strEmail.c_str());
- lpRecipients->aEntries[iRecipNum].rgPropVals[3].ulPropTag = PR_ENTRYID;
- hr = ECCreateOneOff((LPTSTR)wstrName.c_str(), (LPTSTR)L"SMTP", (LPTSTR)m_converter.convert_to<wstring>(strEmail).c_str(),
- MAPI_UNICODE | MAPI_SEND_NO_RICH_INFO, &cbEntryID, &~lpEntryID);
- if (hr != hrSuccess)
- return hr;
-
- hr = MAPIAllocateMore(cbEntryID, lpRecipients->aEntries[iRecipNum].rgPropVals,
- (void **)&lpRecipients->aEntries[iRecipNum].rgPropVals[3].Value.bin.lpb);
- if (hr != hrSuccess)
- return hr;
- lpRecipients->aEntries[iRecipNum].rgPropVals[3].Value.bin.cb = cbEntryID;
- memcpy(lpRecipients->aEntries[iRecipNum].rgPropVals[3].Value.bin.lpb, lpEntryID, cbEntryID);
- lpRecipients->aEntries[iRecipNum].rgPropVals[4].ulPropTag = PR_ADDRTYPE_W;
- lpRecipients->aEntries[iRecipNum].rgPropVals[4].Value.lpszW = const_cast<wchar_t *>(L"SMTP");
- strSearch = strToUpper("SMTP:" + strEmail);
- lpRecipients->aEntries[iRecipNum].rgPropVals[5].ulPropTag = PR_SEARCH_KEY;
- lpRecipients->aEntries[iRecipNum].rgPropVals[5].Value.bin.cb = strSearch.size() + 1;
- hr = MAPIAllocateMore(strSearch.size()+1, lpRecipients->aEntries[iRecipNum].rgPropVals,
- (void **)&lpRecipients->aEntries[iRecipNum].rgPropVals[5].Value.bin.lpb);
- if (hr != hrSuccess)
- return hr;
- memcpy(lpRecipients->aEntries[iRecipNum].rgPropVals[5].Value.bin.lpb, strSearch.c_str(), strSearch.size()+1);
-
- lpRecipients->aEntries[iRecipNum].rgPropVals[6].ulPropTag = PR_EMAIL_ADDRESS_A;
- hr = MAPIAllocateMore(strEmail.size()+1, lpRecipients->aEntries[iRecipNum].rgPropVals,
- (void **)&lpRecipients->aEntries[iRecipNum].rgPropVals[6].Value.lpszA);
- if (hr != hrSuccess)
- return hr;
- strcpy(lpRecipients->aEntries[iRecipNum].rgPropVals[6].Value.lpszA, strEmail.c_str());
-
- lpRecipients->aEntries[iRecipNum].rgPropVals[7].ulPropTag = PR_DISPLAY_TYPE;
- lpRecipients->aEntries[iRecipNum].rgPropVals[7].Value.ul = DT_MAILUSER;
- }
- ++lpRecipients->cEntries;
- }
- return hrSuccess;
- }
- HRESULT VMIMEToMAPI::modifyFromAddressBook(LPSPropValue *lppPropVals,
- ULONG *lpulValues, const char *email, const wchar_t *fullname,
- ULONG ulRecipType, const SPropTagArray *lpPropsList)
- {
- HRESULT hr = hrSuccess;
- memory_ptr<ENTRYID> lpDDEntryID;
- ULONG cbDDEntryID;
- ULONG ulObj = 0;
- adrlist_ptr lpAdrList;
- memory_ptr<FlagList> lpFlagList;
- const SPropValue *lpProp = nullptr;
- SPropValue sRecipProps[9];
- ULONG cValues = 0;
- static constexpr const SizedSPropTagArray(8, sptaAddress) =
- {8, {PR_SMTP_ADDRESS_W, PR_ADDRTYPE_W, PR_EMAIL_ADDRESS_W,
- PR_DISPLAY_TYPE, PR_DISPLAY_NAME_W, PR_ENTRYID, PR_SEARCH_KEY,
- PR_OBJECT_TYPE}};
- if (m_lpAdrBook == nullptr)
- return MAPI_E_NOT_FOUND;
- if ((email == nullptr || *email == '\0') &&
- (fullname == nullptr || *fullname == '\0'))
-
- return MAPI_E_NOT_FOUND;
- if (!m_lpDefaultDir) {
- hr = m_lpAdrBook->GetDefaultDir(&cbDDEntryID, &~lpDDEntryID);
- if (hr != hrSuccess)
- return hr;
- hr = m_lpAdrBook->OpenEntry(cbDDEntryID, lpDDEntryID, NULL, 0, &ulObj, (LPUNKNOWN*)&m_lpDefaultDir);
- if (hr != hrSuccess)
- return hr;
- }
- hr = MAPIAllocateBuffer(CbNewADRLIST(1), &~lpAdrList);
- if (hr != hrSuccess)
- return hr;
- lpAdrList->cEntries = 1;
- lpAdrList->aEntries[0].cValues = 1;
- hr = MAPIAllocateBuffer(sizeof(SPropValue), (void **) &lpAdrList->aEntries[0].rgPropVals);
- if (hr != hrSuccess)
- return hr;
-
- if (!email || *email == '\0') {
- lpAdrList->aEntries[0].rgPropVals[0].ulPropTag = PR_DISPLAY_NAME_W;
- lpAdrList->aEntries[0].rgPropVals[0].Value.lpszW = (WCHAR *)fullname;
- }
- else {
- lpAdrList->aEntries[0].rgPropVals[0].ulPropTag = PR_DISPLAY_NAME_A;
- lpAdrList->aEntries[0].rgPropVals[0].Value.lpszA = (char *)email;
- }
- hr = MAPIAllocateBuffer(CbNewFlagList(1), &~lpFlagList);
- if (hr != hrSuccess)
- return hr;
- lpFlagList->cFlags = 1;
- lpFlagList->ulFlag[0] = MAPI_UNRESOLVED;
- hr = m_lpDefaultDir->ResolveNames(sptaAddress, EMS_AB_ADDRESS_LOOKUP,
- lpAdrList, lpFlagList);
- if (hr != hrSuccess)
- return hr;
- if (lpFlagList->cFlags != 1 || lpFlagList->ulFlag[0] != MAPI_RESOLVED)
- return MAPI_E_NOT_FOUND;
-
-
-
-
- if (PROP_TYPE(lpPropsList->aulPropTag[0]) != PT_NULL) {
- lpProp = PCpropFindProp(lpAdrList->aEntries[0].rgPropVals, lpAdrList->aEntries[0].cValues, PR_ADDRTYPE_W);
- sRecipProps[cValues].ulPropTag = lpPropsList->aulPropTag[0];
- assert(lpProp);
- if (!lpProp) {
- ec_log_warn("Missing PR_ADDRTYPE_W for search entry: email %s, fullname %ls", email ? email : "null", fullname ? fullname : L"null");
- sRecipProps[cValues].Value.lpszW = const_cast<wchar_t *>(L"ZARAFA");
- } else {
- sRecipProps[cValues].Value.lpszW = lpProp->Value.lpszW;
- }
- ++cValues;
- }
- if (PROP_TYPE(lpPropsList->aulPropTag[1]) != PT_NULL) {
- lpProp = PCpropFindProp(lpAdrList->aEntries[0].rgPropVals, lpAdrList->aEntries[0].cValues, PR_DISPLAY_NAME_W);
- sRecipProps[cValues].ulPropTag = lpPropsList->aulPropTag[1];
- if (lpProp)
- sRecipProps[cValues].Value.lpszW = lpProp->Value.lpszW;
- else if (fullname && *fullname != '\0')
- sRecipProps[cValues].Value.lpszW = (WCHAR *)fullname;
- else if (email && *email != '\0')
- sRecipProps[cValues].Value.lpszW = (WCHAR *)email;
- else {
- sRecipProps[cValues].ulPropTag = CHANGE_PROP_TYPE(lpPropsList->aulPropTag[1], PT_ERROR);
- sRecipProps[cValues].Value.err = MAPI_E_NOT_FOUND;
- }
- ++cValues;
- }
- if (PROP_TYPE(lpPropsList->aulPropTag[2]) != PT_NULL) {
- lpProp = PCpropFindProp(lpAdrList->aEntries[0].rgPropVals, lpAdrList->aEntries[0].cValues, PR_DISPLAY_TYPE);
- sRecipProps[cValues].ulPropTag = lpPropsList->aulPropTag[2];
- if (lpProp == nullptr)
- sRecipProps[cValues].Value.ul = DT_MAILUSER;
- else
- sRecipProps[cValues].Value.ul = lpProp->Value.ul;
- ++cValues;
- }
- if (PROP_TYPE(lpPropsList->aulPropTag[3]) != PT_NULL) {
- lpProp = PCpropFindProp(lpAdrList->aEntries[0].rgPropVals, lpAdrList->aEntries[0].cValues, PR_EMAIL_ADDRESS_W);
- sRecipProps[cValues].ulPropTag = lpPropsList->aulPropTag[3];
- assert(lpProp);
- if (!lpProp) {
- sRecipProps[cValues].ulPropTag = CHANGE_PROP_TYPE(lpPropsList->aulPropTag[3], PT_ERROR);
- sRecipProps[cValues].Value.err = MAPI_E_NOT_FOUND;
- } else {
- sRecipProps[cValues].Value.lpszW = lpProp->Value.lpszW;
- }
- ++cValues;
- }
- if (PROP_TYPE(lpPropsList->aulPropTag[4]) != PT_NULL) {
- lpProp = PCpropFindProp(lpAdrList->aEntries[0].rgPropVals, lpAdrList->aEntries[0].cValues, PR_ENTRYID);
- assert(lpProp);
- if (lpProp == nullptr)
-
- return MAPI_E_NOT_FOUND;
- sRecipProps[cValues].ulPropTag = lpPropsList->aulPropTag[4];
- sRecipProps[cValues].Value.bin = lpProp->Value.bin;
- ++cValues;
- }
- if (PROP_TYPE(lpPropsList->aulPropTag[5]) != PT_NULL) {
- lpProp = PCpropFindProp(lpAdrList->aEntries[0].rgPropVals, lpAdrList->aEntries[0].cValues, PR_SEARCH_KEY);
- if (!lpProp) {
- sRecipProps[cValues].ulPropTag = CHANGE_PROP_TYPE(lpPropsList->aulPropTag[5], PT_ERROR);
- sRecipProps[cValues].Value.err = MAPI_E_NOT_FOUND;
- } else {
- sRecipProps[cValues].ulPropTag = lpPropsList->aulPropTag[5];
- sRecipProps[cValues].Value.bin = lpProp->Value.bin;
- }
- ++cValues;
- }
- if (PROP_TYPE(lpPropsList->aulPropTag[6]) != PT_NULL) {
- lpProp = PCpropFindProp(lpAdrList->aEntries[0].rgPropVals, lpAdrList->aEntries[0].cValues, PR_SMTP_ADDRESS_W);
- if (!lpProp) {
- sRecipProps[cValues].ulPropTag = CHANGE_PROP_TYPE(lpPropsList->aulPropTag[6], PT_ERROR);
- sRecipProps[cValues].Value.err = MAPI_E_NOT_FOUND;
- } else {
- sRecipProps[cValues].ulPropTag = lpPropsList->aulPropTag[6];
- sRecipProps[cValues].Value.lpszW = lpProp->Value.lpszW;
- }
- ++cValues;
- }
- lpProp = PCpropFindProp(lpAdrList->aEntries[0].rgPropVals, lpAdrList->aEntries[0].cValues, PR_OBJECT_TYPE);
- assert(lpProp);
- if (lpProp == nullptr)
- sRecipProps[cValues].Value.ul = MAPI_MAILUSER;
- else
- sRecipProps[cValues].Value.ul = lpProp->Value.ul;
- sRecipProps[cValues].ulPropTag = PR_OBJECT_TYPE;
- ++cValues;
- if (ulRecipType != MAPI_ORIG) {
- sRecipProps[cValues].ulPropTag = PR_RECIPIENT_TYPE;
- sRecipProps[cValues].Value.ul = ulRecipType;
- ++cValues;
- }
- hr = Util::HrCopyPropertyArray(sRecipProps, cValues, lppPropVals, &cValues);
- if (hr == hrSuccess && lpulValues)
- *lpulValues = cValues;
- return hr;
- }
- static std::list<unsigned int>
- vtm_order_alternatives(vmime::shared_ptr<vmime::body> vmBody)
- {
- vmime::shared_ptr<vmime::header> vmHeader;
- vmime::shared_ptr<vmime::bodyPart> vmBodyPart;
- vmime::shared_ptr<vmime::mediaType> mt;
- std::list<unsigned int> lBodies, pgtext;
- for (size_t i = 0; i < vmBody->getPartCount(); ++i) {
- vmBodyPart = vmBody->getPartAt(i);
- vmHeader = vmBodyPart->getHeader();
- if (!vmHeader->hasField(vmime::fields::CONTENT_TYPE)) {
-
- lBodies.push_front(i);
- continue;
- }
- mt = vmime::dynamicCast<vmime::mediaType>(vmHeader->ContentType()->getValue());
-
- if (mt->getType() == vmime::mediaTypes::TEXT && mt->getSubType() == vmime::mediaTypes::TEXT_PLAIN)
- lBodies.push_back(i);
- else
- lBodies.push_front(i);
- }
- return lBodies;
- }
- HRESULT VMIMEToMAPI::dissect_multipart(vmime::shared_ptr<vmime::header> vmHeader,
- vmime::shared_ptr<vmime::body> vmBody, IMessage *lpMessage,
- bool bFilterDouble, bool bAppendBody)
- {
- bool bAlternative = false;
- HRESULT hr = hrSuccess;
- if (vmBody->getPartCount() <= 0) {
-
- hr = handleAttachment(vmHeader, vmBody, lpMessage);
- if (hr != hrSuccess)
- ec_log_err("dissect_multipart: Unable to save attachment");
- return hr;
- }
-
- auto mt = vmime::dynamicCast<vmime::mediaType>(vmHeader->ContentType()->getValue());
- if (mt->getSubType() == "appledouble")
- bFilterDouble = true;
- else if (mt->getSubType() == "mixed")
- bAppendBody = true;
- else if (mt->getSubType() == "alternative")
- bAlternative = true;
-
- if (!bAlternative) {
-
- for (size_t i = 0; i < vmBody->getPartCount(); ++i) {
- auto vmBodyPart = vmBody->getPartAt(i);
- hr = dissect_body(vmBodyPart->getHeader(), vmBodyPart->getBody(), lpMessage, bFilterDouble, bAppendBody);
- if (hr != hrSuccess) {
- ec_log_err("dissect_multipart: Unable to parse sub multipart %zu of mail body", i);
- return hr;
- }
- }
- return hrSuccess;
- }
- list<unsigned int> lBodies = vtm_order_alternatives(vmBody);
-
- for (auto body_idx : lBodies) {
- auto vmBodyPart = vmBody->getPartAt(body_idx);
- ec_log_debug("Trying to parse alternative multipart %d of mail body", body_idx);
- hr = dissect_body(vmBodyPart->getHeader(), vmBodyPart->getBody(), lpMessage, bFilterDouble, bAppendBody);
- if (hr == hrSuccess)
- return hrSuccess;
- ec_log_err("Unable to parse alternative multipart %d of mail body, trying other alternatives", body_idx);
- }
-
- if (hr != hrSuccess)
- ec_log_err("Unable to parse all alternative multiparts of mail body");
- return hr;
- }
- void VMIMEToMAPI::dissect_message(vmime::shared_ptr<vmime::body> vmBody,
- IMessage *lpMessage)
- {
-
- ULONG ulAttNr = 0;
- object_ptr<IAttach> pAtt;
- object_ptr<IMessage> lpNewMessage;
- memory_ptr<SPropValue> lpSubject;
- SPropValue sAttachMethod;
- char *lpszBody = NULL, *lpszBodyOrig = NULL;
- sMailState savedState;
- std::string newMessage;
- vmime::utility::outputStreamStringAdapter os(newMessage);
- vmBody->generate(os);
- lpszBodyOrig = lpszBody = (char *)newMessage.c_str();
-
- while (*lpszBody != '\0' && (*lpszBody == '\r' || *lpszBody == '\n'))
- ++lpszBody;
-
- newMessage.erase(0, lpszBody - lpszBodyOrig);
- HRESULT hr = lpMessage->CreateAttach(nullptr, 0, &ulAttNr, &~pAtt);
- if (hr != hrSuccess)
- goto next;
- hr = pAtt->OpenProperty(PR_ATTACH_DATA_OBJ, &IID_IMessage, 0,
- MAPI_CREATE | MAPI_MODIFY, &~lpNewMessage);
- if (hr != hrSuccess)
- goto next;
-
- savedState = m_mailState;
- m_mailState.reset();
- ++m_mailState.ulMsgInMsg;
- hr = convertVMIMEToMAPI(newMessage, lpNewMessage);
-
- m_mailState = savedState;
- if (hr != hrSuccess)
- goto next;
- if (HrGetOneProp(lpNewMessage, PR_SUBJECT_W, &~lpSubject) == hrSuccess) {
-
- lpSubject->ulPropTag = PR_DISPLAY_NAME_W;
- pAtt->SetProps(1, lpSubject, NULL);
- }
- sAttachMethod.ulPropTag = PR_ATTACH_METHOD;
- sAttachMethod.Value.ul = ATTACH_EMBEDDED_MSG;
- pAtt->SetProps(1, &sAttachMethod, NULL);
- lpNewMessage->SaveChanges(0);
- pAtt->SaveChanges(0);
- next:
- ;
- }
- HRESULT VMIMEToMAPI::dissect_ical(vmime::shared_ptr<vmime::header> vmHeader,
- vmime::shared_ptr<vmime::body> vmBody, IMessage *lpMessage,
- bool bIsAttachment)
- {
- HRESULT hr;
-
- string icaldata;
- vmime::utility::outputStreamStringAdapter os(icaldata);
- std::string strCharset;
- MessagePtr ptrNewMessage;
- LPMESSAGE lpIcalMessage = lpMessage;
- AttachPtr ptrAttach;
- ULONG ulAttNr = 0;
- std::unique_ptr<ICalToMapi> lpIcalMapi;
- ICalToMapi *tmpicalmapi;
- SPropValuePtr ptrSubject;
- ULONG ical_mapi_flags = IC2M_NO_RECIPIENTS | IC2M_APPEND_ONLY;
-
- strCharset = vmBody->getCharset().getName();
- if (strCharset == "us-ascii")
-
- strCharset = "utf-8";
- vmBody->getContents()->extract(os);
- if (m_mailState.bodyLevel > BODY_NONE)
-
- bIsAttachment = true;
- if (bIsAttachment) {
-
- SPropValue sAttProps[3];
- hr = lpMessage->CreateAttach(nullptr, 0, &ulAttNr, &~ptrAttach);
- if (hr != hrSuccess) {
- ec_log_err("dissect_ical-1790: Unable to create attachment for ical data: %s (%x)", GetMAPIErrorMessage(hr), hr);
- return hr;
- }
- hr = ptrAttach->OpenProperty(PR_ATTACH_DATA_OBJ, &IID_IMessage, 0, MAPI_CREATE | MAPI_MODIFY, &~ptrNewMessage);
- if (hr != hrSuccess) {
- ec_log_err("dissect_ical-1796: Unable to create message attachment for ical data: %s (%x)", GetMAPIErrorMessage(hr), hr);
- return hr;
- }
- sAttProps[0].ulPropTag = PR_ATTACH_METHOD;
- sAttProps[0].Value.ul = ATTACH_EMBEDDED_MSG;
- sAttProps[1].ulPropTag = PR_ATTACHMENT_HIDDEN;
- sAttProps[1].Value.b = FALSE;
- sAttProps[2].ulPropTag = PR_ATTACH_FLAGS;
- sAttProps[2].Value.ul = 0;
- hr = ptrAttach->SetProps(3, sAttProps, NULL);
- if (hr != hrSuccess) {
- ec_log_err("dissect_ical-1811: Unable to create message attachment for ical data: %s (%x)", GetMAPIErrorMessage(hr), hr);
- return hr;
- }
- lpIcalMessage = ptrNewMessage.get();
- }
- hr = CreateICalToMapi(lpMessage, m_lpAdrBook, true, &tmpicalmapi);
- lpIcalMapi.reset(tmpicalmapi);
- if (hr != hrSuccess) {
- ec_log_err("dissect_ical-1820: Unable to create ical converter: %s (%x)", GetMAPIErrorMessage(hr), hr);
- return hr;
- }
- hr = lpIcalMapi->ParseICal(icaldata, strCharset, "UTC" , NULL, 0);
- if (hr != hrSuccess || lpIcalMapi->GetItemCount() != 1) {
- ec_log_err("dissect_ical-1826: Unable to parse ical information: %s (%x), items: %d, adding as normal attachment",
- GetMAPIErrorMessage(hr), hr, lpIcalMapi->GetItemCount());
- return handleAttachment(vmHeader, vmBody, lpMessage);
- }
- if (lpIcalMessage != lpMessage) {
- hr = lpIcalMapi->GetItem(0, 0, lpIcalMessage);
- if (hr != hrSuccess) {
- ec_log_err("dissect_ical-1833: Error while converting ical to mapi: %s (%x)", GetMAPIErrorMessage(hr), hr);
- return hr;
- }
- }
- if (bIsAttachment)
- ical_mapi_flags |= IC2M_NO_BODY;
-
- hr = lpIcalMapi->GetItem(0, ical_mapi_flags, lpMessage);
- if (hr != hrSuccess) {
- ec_log_err("dissect_ical-1834: Error while converting ical to mapi: %s (%x)", GetMAPIErrorMessage(hr), hr);
- return hr;
- }
-
- if (!bIsAttachment && m_mailState.bodyLevel < BODY_PLAIN &&
- (FPropExists(lpMessage, PR_BODY_A) ||
- FPropExists(lpMessage, PR_BODY_W)))
- m_mailState.bodyLevel = BODY_PLAIN;
- if (!bIsAttachment)
- return hr;
-
- if (HrGetOneProp(ptrNewMessage, PR_SUBJECT_W, &~ptrSubject) == hrSuccess) {
- ptrSubject->ulPropTag = PR_DISPLAY_NAME_W;
- hr = ptrAttach->SetProps(1, ptrSubject, NULL);
- if (hr != hrSuccess)
- return hr;
- }
- hr = ptrNewMessage->SaveChanges(0);
- if (hr != hrSuccess) {
- ec_log_err("dissect_ical-1851: Unable to save ical message: %s (%x)", GetMAPIErrorMessage(hr), hr);
- return hr;
- }
- hr = ptrAttach->SaveChanges(0);
- if (hr != hrSuccess) {
- ec_log_err("dissect_ical-1856: Unable to save ical message attachment: %s (%x)", GetMAPIErrorMessage(hr), hr);
- return hr;
- }
-
- m_mailState.attachLevel = ATTACH_NORMAL;
- return hrSuccess;
- }
- HRESULT VMIMEToMAPI::dissect_body(vmime::shared_ptr<vmime::header> vmHeader,
- vmime::shared_ptr<vmime::body> vmBody, IMessage *lpMessage,
- bool filterDouble, bool appendBody)
- {
- HRESULT hr = hrSuccess;
- object_ptr<IStream> lpStream;
- SPropValue sPropSMIMEClass;
- bool bFilterDouble = filterDouble;
- bool bAppendBody = appendBody;
- bool bIsAttachment = false;
- if (vmHeader->hasField(vmime::fields::MIME_VERSION))
- ++m_mailState.mime_vtag_nest;
- try {
- auto mt = vmime::dynamicCast<vmime::mediaType>(vmHeader->ContentType()->getValue());
- bool force_raw = false;
- try {
- bIsAttachment = vmime::dynamicCast<vmime::contentDisposition>(vmHeader->ContentDisposition()->getValue())->getName() == vmime::contentDispositionTypes::ATTACHMENT;
- } catch (vmime::exception) {
-
-
- }
- try {
- vmBody->getContents()->getEncoding().getEncoder();
- } catch (vmime::exceptions::no_encoder_available &) {
-
- ec_log_debug("Encountered unknown Content-Transfer-Encoding \"%s\".",
- vmBody->getContents()->getEncoding().getName().c_str());
- force_raw = true;
- }
- if (force_raw) {
- hr = handleAttachment(vmHeader, vmBody, lpMessage, true);
- if (hr != hrSuccess)
- goto exit;
- } else if (mt->getType() == "multipart") {
- hr = dissect_multipart(vmHeader, vmBody, lpMessage, bFilterDouble, bAppendBody);
- if (hr != hrSuccess)
- goto exit;
-
- } else if (mt->getType() == vmime::mediaTypes::TEXT &&
- (mt->getSubType() == vmime::mediaTypes::TEXT_PLAIN || mt->getSubType() == vmime::mediaTypes::TEXT_HTML) &&
- !bIsAttachment) {
- if (mt->getSubType() == vmime::mediaTypes::TEXT_HTML || (m_mailState.bodyLevel == BODY_HTML && bAppendBody)) {
-
-
- hr = handleHTMLTextpart(vmHeader, vmBody, lpMessage, bAppendBody);
- if (hr != hrSuccess) {
- ec_log_err("Unable to parse mail HTML text");
- goto exit;
- }
- } else {
- hr = handleTextpart(vmHeader, vmBody, lpMessage, bAppendBody);
- if (hr != hrSuccess)
- goto exit;
- }
-
- } else if (mt->getType() == vmime::mediaTypes::MESSAGE) {
- dissect_message(vmBody, lpMessage);
- } else if(mt->getType() == vmime::mediaTypes::APPLICATION && mt->getSubType() == "ms-tnef") {
- LARGE_INTEGER zero = {{0,0}};
-
- hr = CreateStreamOnHGlobal(nullptr, TRUE, &~lpStream);
- if(hr != hrSuccess)
- goto exit;
-
- outputStreamMAPIAdapter str(lpStream);
- vmBody->getContents()->extract(str);
- hr = lpStream->Seek(zero, STREAM_SEEK_SET, NULL);
- if(hr != hrSuccess)
- goto exit;
-
- ECTNEF tnef(TNEF_DECODE, lpMessage, lpStream);
- hr = tnef.ExtractProps(TNEF_PROP_EXCLUDE, NULL);
- if (hr == hrSuccess) {
- hr = tnef.Finish();
- if (hr != hrSuccess)
- ec_log_warn("TNEF attachment saving failed: 0x%08X", hr);
- } else {
- ec_log_warn("TNEF attachment parsing failed: 0x%08X", hr);
- }
- hr = hrSuccess;
- } else if (mt->getType() == vmime::mediaTypes::TEXT && mt->getSubType() == "calendar") {
- hr = dissect_ical(vmHeader, vmBody, lpMessage, bIsAttachment);
- if (hr != hrSuccess)
- goto exit;
- } else if (filterDouble && mt->getType() == vmime::mediaTypes::APPLICATION && mt->getSubType() == "applefile") {
- } else if (filterDouble && mt->getType() == vmime::mediaTypes::APPLICATION && mt->getSubType() == "mac-binhex40") {
-
-
-
- } else if (mt->getType() == vmime::mediaTypes::APPLICATION && (mt->getSubType() == "pkcs7-signature" || mt->getSubType() == "x-pkcs7-signature")) {
-
-
- m_mailState.bAttachSignature = true;
- } else if (mt->getType() == vmime::mediaTypes::APPLICATION && (mt->getSubType() == "pkcs7-mime" || mt->getSubType() == "x-pkcs7-mime")) {
-
- hr = handleAttachment(vmHeader, vmBody, lpMessage, false);
- if (hr == MAPI_E_NOT_FOUND) {
-
- hr = hrSuccess;
- goto exit;
- }
- if (hr != hrSuccess)
- goto exit;
-
- sPropSMIMEClass.ulPropTag = PR_MESSAGE_CLASS_W;
- sPropSMIMEClass.Value.lpszW = const_cast<wchar_t *>(L"IPM.Note.SMIME");
- hr = lpMessage->SetProps(1, &sPropSMIMEClass, NULL);
- if (hr != hrSuccess) {
- ec_log_err("Unable to set message class");
- goto exit;
- }
- } else if (mt->getType() == vmime::mediaTypes::APPLICATION && mt->getSubType() == vmime::mediaTypes::APPLICATION_OCTET_STREAM) {
- if (vmime::dynamicCast<vmime::contentDispositionField>(vmHeader->ContentDisposition())->hasParameter("filename") ||
- vmime::dynamicCast<vmime::contentTypeField>(vmHeader->ContentType())->hasParameter("name")) {
-
- hr = handleAttachment(vmHeader, vmBody, lpMessage);
- if (hr != hrSuccess)
- goto exit;
- } else {
-
- hr = handleTextpart(vmHeader, vmBody, lpMessage, false);
- if (hr != hrSuccess)
- goto exit;
- }
- } else {
-
- hr = handleAttachment(vmHeader, vmBody, lpMessage);
- if (hr != hrSuccess)
- goto exit;
- }
- }
- catch (vmime::exception& e) {
- ec_log_err("VMIME exception on parsing body: %s", e.what());
- hr = MAPI_E_CALL_FAILED;
- goto exit;
- }
- catch (std::exception& e) {
- ec_log_err("STD exception on parsing body: %s", e.what());
- hr = MAPI_E_CALL_FAILED;
- goto exit;
- }
- catch (...) {
- ec_log_err("Unknown generic exception occurred on parsing body");
- hr = MAPI_E_CALL_FAILED;
- goto exit;
- }
- exit:
- if (vmHeader->hasField(vmime::fields::MIME_VERSION))
- --m_mailState.mime_vtag_nest;
- return hr;
- }
- std::string
- VMIMEToMAPI::content_transfer_decode(vmime::shared_ptr<vmime::body> im_body) const
- {
-
- std::string data;
- vmime::utility::outputStreamStringAdapter str_adap(data);
- auto im_cont = im_body->getContents();
- try {
- im_cont->extract(str_adap);
- } catch (vmime::exceptions::no_encoder_available &e) {
- ec_log_warn("VMIME could not process the Content-Transfer-Encoding \"%s\" (%s). Reading part raw.",
- im_cont->getEncoding().generate().c_str(), e.what());
- im_cont->extractRaw(str_adap);
- }
- return data;
- }
- vmime::charset
- VMIMEToMAPI::get_mime_encoding(vmime::shared_ptr<vmime::header> im_header,
- vmime::shared_ptr<vmime::body> im_body) const
- {
- auto ctf = vmime::dynamicCast<vmime::contentTypeField>(im_header->ContentType());
- if (ctf != NULL && ctf->hasParameter("charset"))
- return im_body->getCharset();
- return vmime::charset(im_charset_unspec);
- }
- int VMIMEToMAPI::renovate_encoding(std::string &data,
- const std::vector<std::string> &cs)
- {
-
- for (size_t i = 0; i < cs.size(); ++i) {
- const char *name = cs[i].c_str();
- try {
- data = m_converter.convert_to<std::string>(
- (cs[i] + "//NOIGNORE").c_str(),
- data, rawsize(data), name);
- ec_log_debug("renovate_encoding: reading data using charset \"%s\" succeeded.", name);
- return i;
- } catch (illegal_sequence_exception &ce) {
-
- unsigned int lvl = EC_LOGLEVEL_DEBUG;
- if (i == 0)
- lvl = EC_LOGLEVEL_WARNING;
- ec_log(lvl, "renovate_encoding: reading data using charset \"%s\" produced partial results: %s",
- name, ce.what());
- } catch (unknown_charset_exception &) {
- ec_log_warn("renovate_encoding: unknown charset \"%s\", skipping", name);
- }
- }
-
- for (size_t i = 0; i < cs.size(); ++i) {
- const char *name = cs[i].c_str();
- try {
- data = m_converter.convert_to<std::string>(
- (cs[i] + "//IGNORE").c_str(), data, rawsize(data), name);
- } catch (unknown_charset_exception &) {
- continue;
- }
- ec_log_debug("renovate_encoding: forced interpretation as charset \"%s\".", name);
- return i;
- }
- return -1;
- }
- HRESULT VMIMEToMAPI::handleTextpart(vmime::shared_ptr<vmime::header> vmHeader,
- vmime::shared_ptr<vmime::body> vmBody, IMessage* lpMessage, bool bAppendBody)
- {
- HRESULT hr = S_OK;
- object_ptr<IStream> lpStream;
- bool append = m_mailState.bodyLevel < BODY_PLAIN ||
- (m_mailState.bodyLevel == BODY_PLAIN && bAppendBody);
- if (!append) {
-
- hr = handleAttachment(vmHeader, vmBody, lpMessage);
- if (hr != hrSuccess) {
- ec_log_err("Unable to parse attached text mail");
- return hr;
- }
- return hrSuccess;
- }
-
- try {
- SPropValue sCodepage;
-
- vmime::charset mime_charset =
- get_mime_encoding(vmHeader, vmBody);
- if (mime_charset == im_charset_unspec) {
- if (m_mailState.mime_vtag_nest == 0) {
-
- ec_log_debug("No charset (case #1). Defaulting to \"%s\".", m_dopt.ascii_upgrade);
- mime_charset = m_dopt.ascii_upgrade;
- } else {
-
- ec_log_debug("No charset (case #2). Defaulting to \"us-ascii\".");
- mime_charset = vmime::charsets::US_ASCII;
- }
- }
- mime_charset = vtm_upgrade_charset(mime_charset, m_dopt.ascii_upgrade);
- if (!ValidateCharset(mime_charset.getName().c_str())) {
-
- ec_log_debug("Unknown Content-Type charset \"%s\". Storing as attachment instead.", mime_charset.getName().c_str());
- return handleAttachment(vmHeader, vmBody, lpMessage, true);
- }
-
- std::string strBuffOut = content_transfer_decode(vmBody);
- std::wstring strUnicodeText = m_converter.convert_to<std::wstring>(CHARSET_WCHAR "//IGNORE", strBuffOut, rawsize(strBuffOut), mime_charset.getName().c_str());
- strUnicodeText.erase(std::remove(strUnicodeText.begin(), strUnicodeText.end(), L'\0'), strUnicodeText.end());
- if (HrGetCPByCharset(mime_charset.getName().c_str(), &sCodepage.Value.ul) != hrSuccess)
-
- sCodepage.Value.ul = 65001;
- sCodepage.ulPropTag = PR_INTERNET_CPID;
- HrSetOneProp(lpMessage, &sCodepage);
-
- ULONG ulFlags = MAPI_MODIFY;
- if (m_mailState.bodyLevel < BODY_PLAIN || !bAppendBody)
- ulFlags |= MAPI_CREATE;
- hr = lpMessage->OpenProperty(PR_BODY_W, &IID_IStream, STGM_TRANSACTED, ulFlags, &~lpStream);
- if (hr != hrSuccess)
- return hr;
- if (bAppendBody) {
- static const LARGE_INTEGER liZero = {{0, 0}};
- hr = lpStream->Seek(liZero, SEEK_END, NULL);
- if (hr != hrSuccess)
- return hr;
- }
- hr = lpStream->Write(strUnicodeText.c_str(), strUnicodeText.length() * sizeof(wstring::value_type), NULL);
- if (hr != hrSuccess)
- return hr;
-
- hr = lpStream->Commit(0);
- if (hr != hrSuccess)
- return hr;
- }
- catch (vmime::exception &e) {
- ec_log_err("VMIME exception on text body: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (std::exception &e) {
- ec_log_err("STD exception on text body: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (...) {
- ec_log_err("Unknown generic exception occurred on text body");
- return MAPI_E_CALL_FAILED;
- }
- m_mailState.bodyLevel = BODY_PLAIN;
- return hrSuccess;
- }
- bool VMIMEToMAPI::filter_html(IMessage *msg, IStream *stream, ULONG flags,
- const std::string &html)
- {
- #ifdef HAVE_TIDY_H
- std::string clean_html;
- std::vector<std::string> error;
- HRESULT ret;
- bool clean_ok = rosie_clean_html(html, &clean_html, &error);
- for (size_t i = 0; i < error.size(); ++i)
- ec_log_debug("HTML clean: %s", error[i].c_str());
- if (!clean_ok)
- return false;
- ret = msg->OpenProperty(PR_EC_BODY_FILTERED, &IID_IStream,
- STGM_TRANSACTED, flags, reinterpret_cast<LPUNKNOWN *>(&stream));
- if (ret != hrSuccess) {
- ec_log_warn("OpenProperty(PR_EC_BODY_FILTERED) failed: %s (%x)",
- GetMAPIErrorDescription(ret).c_str(), ret);
- return false;
- }
- ULONG written = 0;
- ret = stream->Write(clean_html.c_str(), clean_html.length(), &written);
- if (ret != hrSuccess) {
-
- ec_log_warn("Write(PR_EC_BODY_FILTERED) failed: %s (%x)",
- GetMAPIErrorDescription(ret).c_str(), ret);
- return false;
- }
- ret = stream->Commit(0);
- if (ret != hrSuccess) {
- ec_log_warn("Commit(PR_EC_BODY_FILTERED) failed: %s (%x)",
- GetMAPIErrorDescription(ret).c_str(), ret);
- return false;
- }
- #endif
- return true;
- }
- HRESULT VMIMEToMAPI::handleHTMLTextpart(vmime::shared_ptr<vmime::header> vmHeader,
- vmime::shared_ptr<vmime::body> vmBody, IMessage *lpMessage, bool bAppendBody)
- {
- HRESULT hr = hrSuccess;
- object_ptr<IStream> lpHTMLStream;
- ULONG cbWritten = 0;
- std::string strHTML;
- const char *lpszCharset = NULL;
- SPropValue sCodepage;
- LONG ulFlags;
- bool new_text = m_mailState.bodyLevel < BODY_HTML ||
- (m_mailState.bodyLevel == BODY_HTML && bAppendBody);
- if (!new_text) {
-
- hr = handleAttachment(vmHeader, vmBody, lpMessage);
- if (hr != hrSuccess) {
- ec_log_err("Unable to parse attached text mail");
- return hr;
- }
- return hrSuccess;
- }
-
- try {
-
- strHTML = content_transfer_decode(vmBody);
- vmime::charset mime_charset =
- get_mime_encoding(vmHeader, vmBody);
-
- vmime::charset html_charset(im_charset_unspec);
- int html_analyze = getCharsetFromHTML(strHTML, &html_charset);
- if (html_analyze > 0 && html_charset != mime_charset &&
- mime_charset != im_charset_unspec)
-
- ec_log_debug("MIME headers declare charset \"%s\", while HTML meta tag declares \"%s\".",
- mime_charset.getName().c_str(),
- html_charset.getName().c_str());
- if (mime_charset == im_charset_unspec &&
- html_charset == im_charset_unspec) {
- if (m_mailState.mime_vtag_nest > 0) {
- ec_log_debug("No charset (case #3), defaulting to \"us-ascii\".");
- mime_charset = html_charset = vmime::charsets::US_ASCII;
- } else if (html_analyze < 0) {
-
- ec_log_debug("No charset (case #4), defaulting to \"%s\".", m_dopt.ascii_upgrade);
- mime_charset = html_charset = m_dopt.ascii_upgrade;
- } else {
-
- ec_log_debug("No charset (case #6), defaulting to \"us-ascii\".");
- mime_charset = html_charset = vmime::charsets::US_ASCII;
- }
- } else if (mime_charset == im_charset_unspec) {
-
- ec_log_debug("Charset is \"%s\" (case #7).", html_charset.getName().c_str());
- mime_charset = html_charset;
- } else if (html_charset == im_charset_unspec) {
-
- ec_log_debug("Charset is \"%s\" (case #8).", mime_charset.getName().c_str());
- html_charset = mime_charset;
- }
- mime_charset = vtm_upgrade_charset(mime_charset, m_dopt.ascii_upgrade);
- html_charset = vtm_upgrade_charset(html_charset, m_dopt.ascii_upgrade);
-
- std::vector<std::string> cs_cand;
- cs_cand.push_back(mime_charset.getName());
- if (!m_dopt.charset_strict_rfc) {
- if (mime_charset != html_charset)
- cs_cand.push_back(html_charset.getName());
- cs_cand.push_back(vmime::charsets::US_ASCII);
- }
- int cs_best = renovate_encoding(strHTML, cs_cand);
- if (cs_best < 0) {
- ec_log_err("HTML part not readable in any charset. Storing as attachment instead.");
- return handleAttachment(vmHeader, vmBody, lpMessage, true);
- }
-
-
- if (HrGetCPByCharset(cs_cand[cs_best].c_str(), &sCodepage.Value.ul) != hrSuccess) {
-
- sCodepage.Value.ul = 65001;
- strHTML = m_converter.convert_to<std::string>("UTF-8", strHTML, rawsize(strHTML), cs_cand[cs_best].c_str());
- ec_log_info("No Win32 CPID for \"%s\" - upgrading text/html MIME body to UTF-8", cs_cand[cs_best].c_str());
- }
- if (bAppendBody && m_mailState.bodyLevel == BODY_HTML && m_mailState.ulLastCP && sCodepage.Value.ul != m_mailState.ulLastCP) {
-
-
- if(m_mailState.ulLastCP != 65001) {
- hr = HrGetCharsetByCP(m_mailState.ulLastCP, &lpszCharset);
- if (hr != hrSuccess) {
- assert(false);
- return hr;
- }
-
- std::string strCurrentHTML;
- hr = Util::ReadProperty(lpMessage, PR_HTML, strCurrentHTML);
- if (hr != hrSuccess)
- return hr;
- strCurrentHTML = m_converter.convert_to<std::string>("UTF-8", strCurrentHTML, rawsize(strCurrentHTML), lpszCharset);
- hr = Util::WriteProperty(lpMessage, PR_HTML, strCurrentHTML);
- if (hr != hrSuccess)
- return hr;
- }
- if (sCodepage.Value.ul != 65001)
-
- strHTML = m_converter.convert_to<std::string>("UTF-8", strHTML, rawsize(strHTML), mime_charset.getName().c_str());
-
- sCodepage.Value.ul = 65001;
- mime_charset = "utf-8";
- }
- m_mailState.ulLastCP = sCodepage.Value.ul;
- sCodepage.ulPropTag = PR_INTERNET_CPID;
- HrSetOneProp(lpMessage, &sCodepage);
-
- if (vmime::dynamicCast<vmime::mediaType>(vmHeader->ContentType()->getValue())->getSubType() ==
- vmime::mediaTypes::TEXT_PLAIN) {
-
- std::wstring strwBody = m_converter.convert_to<std::wstring>(CHARSET_WCHAR "//IGNORE", strHTML, rawsize(strHTML), mime_charset.getName().c_str());
- strHTML = "<pre>";
- hr = Util::HrTextToHtml(strwBody.c_str(), strHTML, sCodepage.Value.ul);
- if (hr != hrSuccess)
- return hr;
- strHTML += "</pre>";
- }
- }
- catch (vmime::exception &e) {
- ec_log_err("VMIME exception on html body: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (std::exception &e) {
- ec_log_err("STD exception on html body: %s", e.what());
- return MAPI_E_CALL_FAILED;
- }
- catch (...) {
- ec_log_err("Unknown generic exception occurred on html body");
- return MAPI_E_CALL_FAILED;
- }
-
- ulFlags = MAPI_MODIFY;
- if (m_mailState.bodyLevel == BODY_NONE || (m_mailState.bodyLevel < BODY_HTML && !bAppendBody))
- ulFlags |= MAPI_CREATE;
- hr = lpMessage->OpenProperty(PR_HTML, &IID_IStream, STGM_TRANSACTED, ulFlags, &~lpHTMLStream);
- if (hr != hrSuccess) {
- ec_log_err("OpenProperty PR_HTML failed: %s", GetMAPIErrorMessage(hr));
- return hr;
- }
- if (bAppendBody) {
- static const LARGE_INTEGER liZero = {{0, 0}};
- hr = lpHTMLStream->Seek(liZero, SEEK_END, NULL);
- if (hr != hrSuccess)
- return hr;
- }
- hr = lpHTMLStream->Write(strHTML.c_str(), strHTML.length(), &cbWritten);
- if (hr != hrSuccess)
- return hr;
- hr = lpHTMLStream->Commit(0);
- if (hr != hrSuccess)
- return hr;
- m_mailState.bodyLevel = BODY_HTML;
- if (bAppendBody)
- m_mailState.strHTMLBody.append(strHTML);
- else
- swap(strHTML, m_mailState.strHTMLBody);
- if (m_dopt.html_safety_filter)
- filter_html(lpMessage, lpHTMLStream, ulFlags, strHTML);
- return hrSuccess;
- }
- HRESULT VMIMEToMAPI::handleAttachment(vmime::shared_ptr<vmime::header> vmHeader,
- vmime::shared_ptr<vmime::body> vmBody, IMessage *lpMessage, bool bAllowEmpty)
- {
- HRESULT hr = hrSuccess;
- object_ptr<IStream> lpStream;
- object_ptr<IAttach> lpAtt;
- ULONG ulAttNr = 0;
- std::string strId, strMimeType, strLocation, strTmp;
- std::wstring strLongFilename;
- int nProps = 0;
- SPropValue attProps[12];
- vmime::shared_ptr<vmime::contentDispositionField> cdf;
- vmime::shared_ptr<vmime::contentDisposition> cdv;
- vmime::shared_ptr<vmime::contentTypeField> ctf;
- vmime::shared_ptr<vmime::mediaType> mt;
- memset(attProps, 0, sizeof(attProps));
-
- hr = lpMessage->CreateAttach(nullptr, 0, &ulAttNr, &~lpAtt);
- if (hr != hrSuccess)
- goto exit;
-
- hr = lpAtt->OpenProperty(PR_ATTACH_DATA_BIN, &IID_IStream, STGM_WRITE|STGM_TRANSACTED,
- MAPI_CREATE | MAPI_MODIFY, &~lpStream);
- if (hr != hrSuccess)
- goto exit;
- try {
-
- outputStreamMAPIAdapter osMAPI(lpStream);
- cdf = vmime::dynamicCast<vmime::contentDispositionField>(vmHeader->ContentDisposition());
- cdv = vmime::dynamicCast<vmime::contentDisposition>(cdf->getValue());
- ctf = vmime::dynamicCast<vmime::contentTypeField>(vmHeader->ContentType());
- mt = vmime::dynamicCast<vmime::mediaType>(ctf->getValue());
- try {
- vmBody->getContents()->generate(osMAPI, vmime::encoding(vmime::encodingTypes::BINARY));
- } catch (vmime::exceptions::no_encoder_available &) {
-
- vmBody->getContents()->extractRaw(osMAPI);
- mt->setType(vmime::mediaTypes::APPLICATION);
- mt->setSubType(vmime::mediaTypes::APPLICATION_OCTET_STREAM);
- }
- if (!bAllowEmpty) {
- STATSTG stat;
- hr = lpStream->Stat(&stat, 0);
- if (hr != hrSuccess)
- goto exit;
- if (stat.cbSize.QuadPart == 0) {
- ec_log_err("Empty attachment found when not allowed, dropping empty attachment.");
- hr = MAPI_E_NOT_FOUND;
- goto exit;
- }
- }
- hr = lpStream->Commit(0);
- if (hr != hrSuccess)
- goto exit;
-
-
- lpStream.reset();
-
- attProps[nProps].ulPropTag = PR_ATTACH_METHOD;
- attProps[nProps++].Value.ul = ATTACH_BY_VALUE;
-
- strId = vmime::dynamicCast<vmime::messageId>(vmHeader->ContentId()->getValue())->getId();
- if (!strId.empty()) {
-
-
- attProps[nProps].ulPropTag = PR_ATTACH_CONTENT_ID_A;
- attProps[nProps++].Value.lpszA = (char*)strId.c_str();
- }
- try {
- strLocation = vmime::dynamicCast<vmime::text>(vmHeader->ContentLocation()->getValue())->getConvertedText(MAPI_CHARSET);
- }
- catch (vmime::exceptions::charset_conv_error) { }
- if (!strLocation.empty()) {
- attProps[nProps].ulPropTag = PR_ATTACH_CONTENT_LOCATION_A;
- attProps[nProps++].Value.lpszA = (char*)strLocation.c_str();
- }
-
-
- if (cdv->getName() == vmime::contentDispositionTypes::INLINE &&
- (mt->getType() == vmime::mediaTypes::IMAGE || mt->getType() == vmime::mediaTypes::TEXT) &&
- (!strId.empty() || !strLocation.empty()) &&
- m_mailState.bodyLevel == BODY_HTML &&
- ((!strId.empty() && strcasestr(m_mailState.strHTMLBody.c_str(), string("cid:"+strId).c_str())) ||
- (!strLocation.empty() && strcasestr(m_mailState.strHTMLBody.c_str(), strLocation.c_str())) ))
- {
- attProps[nProps].ulPropTag = PR_ATTACHMENT_HIDDEN;
- attProps[nProps++].Value.b = TRUE;
- attProps[nProps].ulPropTag = PR_ATTACH_FLAGS;
- attProps[nProps++].Value.ul = 4;
- attProps[nProps].ulPropTag = PR_ATTACHMENT_FLAGS;
- attProps[nProps++].Value.ul = 8;
- if (m_mailState.attachLevel < ATTACH_NORMAL)
- m_mailState.attachLevel = ATTACH_INLINE;
- } else {
- attProps[nProps].ulPropTag = PR_ATTACHMENT_HIDDEN;
- attProps[nProps++].Value.b = FALSE;
- attProps[nProps].ulPropTag = PR_ATTACH_FLAGS;
- attProps[nProps++].Value.ul = 0;
- m_mailState.attachLevel = ATTACH_NORMAL;
- }
-
- if (cdf->hasParameter("filename"))
- strLongFilename = getWideFromVmimeText(vmime::text(cdf->getFilename()));
- else if (ctf->hasParameter("name"))
- strLongFilename = getWideFromVmimeText(vmime::text(ctf->getParameter("name")->getValue()));
- else if (mt->getType() == vmime::mediaTypes::TEXT && mt->getSubType() == "calendar")
-
- strLongFilename = L"calendar.ics";
- else
-
- strLongFilename = L"inline.txt";
- attProps[nProps].ulPropTag = PR_ATTACH_LONG_FILENAME_W;
- attProps[nProps++].Value.lpszW = (WCHAR*)strLongFilename.c_str();
-
-
-
- attProps[nProps].ulPropTag = PR_RENDERING_POSITION;
- attProps[nProps++].Value.ul = 0;
- try {
- if (!mt->getType().empty() &&
- !mt->getSubType().empty()) {
- strMimeType = mt->getType() + "/" + mt->getSubType();
-
- while (strMimeType[0] == '\r' || strMimeType[0] == '\n' || strMimeType[0] == '\t' || strMimeType[0] == ' ')
- strMimeType.erase(0, 1);
- attProps[nProps].ulPropTag = PR_ATTACH_MIME_TAG_A;
- attProps[nProps++].Value.lpszA = (char*)strMimeType.c_str();
- }
- }
- catch (vmime::exceptions::no_such_field) {
- }
- hr = lpAtt->SetProps(nProps, attProps, NULL);
- if (hr != hrSuccess)
- goto exit;
- }
- catch (vmime::exception& e) {
- ec_log_err("VMIME exception on attachment: %s", e.what());
- hr = MAPI_E_CALL_FAILED;
- goto exit;
- }
- catch (std::exception& e) {
- ec_log_err("STD exception on attachment: %s", e.what());
- hr = MAPI_E_CALL_FAILED;
- goto exit;
- }
- catch (...) {
- ec_log_err("Unknown generic exception occurred on attachment");
- hr = MAPI_E_CALL_FAILED;
- goto exit;
- }
- hr = lpAtt->SaveChanges(0);
- if (hr != hrSuccess)
- goto exit;
- exit:
- if (hr != hrSuccess)
- ec_log_err("Unable to create attachment");
- return hr;
- }
- static const struct {
- const char *original;
- const char *update;
- } vtm_cs_upgrade_list[] = {
- {"cp-850", "cp850"},
- {"gb2312", "gb18030"},
- {"x-gbk", "gb18030"},
- {"ks_c_5601-1987", "cp949"},
- {"iso-8859-8-i", "iso-8859-8"},
- {"win-1252", "windows-1252"},
-
- {"unicode", "utf-8"},
- };
- static vmime::charset vtm_upgrade_charset(vmime::charset cset, const char *upg)
- {
- if (upg != nullptr && cset == vmime::charsets::US_ASCII &&
- cset != upg) {
-
- ec_log_debug("Admin forced charset upgrade \"%s\" -> \"%s\".",
- cset.getName().c_str(), upg);
- cset = upg;
- }
- for (size_t i = 0; i < ARRAY_SIZE(vtm_cs_upgrade_list); ++i)
- if (strcasecmp(vtm_cs_upgrade_list[i].original, cset.getName().c_str()) == 0)
- return vtm_cs_upgrade_list[i].update;
- return cset;
- }
- static htmlNodePtr find_node(htmlNodePtr lpNode, const char *name)
- {
- htmlNodePtr node = NULL;
- for (node = lpNode; node; node = node->next) {
- if (node->type != XML_ELEMENT_NODE)
- continue;
- htmlNodePtr child = NULL;
- if (xmlStrcasecmp(node->name, reinterpret_cast<const xmlChar *>(name)) == 0)
- break;
- child = find_node(node->children, name);
- if (child)
- return child;
- }
- return node;
- }
- void ignoreError(void *ctx, const char *msg, ...)
- {
- }
- static std::string fix_content_type_charset(const char *in)
- {
- const char *cset = im_charset_unspec, *cset_end = im_charset_unspec;
- while (!isspace(*in) && *in != '\0')
- ++in;
- while (*in != '\0') {
- while (isspace(*in))
- ++in;
- if (*in == ';') {
- ++in;
- while (isspace(*in))
- ++in;
- }
- if (strncasecmp(in, "charset=", 8) == 0) {
- in += 8;
- cset = in;
- while (!isspace(*in) && *in != ';' && *in != '\0')
- ++in;
- cset_end = in;
- continue;
-
- }
- while (!isspace(*in) && *in != ';' && *in != '\0')
- ++in;
- }
- return std::string(cset, cset_end - cset);
- }
- int VMIMEToMAPI::getCharsetFromHTML(const string &strHTML, vmime::charset *htmlCharset)
- {
- int ret = 0;
- htmlDocPtr lpDoc = NULL;
- htmlNodePtr root = NULL, lpNode = NULL;
- xmlChar *lpValue = NULL;
- std::string charset;
-
- xmlSetGenericErrorFunc(NULL, ignoreError);
-
- lpDoc = htmlReadMemory(strHTML.c_str(), strHTML.length(), "", NULL, HTML_PARSE_RECOVER | HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR);
- if (!lpDoc) {
- ec_log_warn("Unable to parse HTML document");
- ret = -1;
- goto exit;
- }
-
- root = xmlDocGetRootElement(lpDoc);
- if (root == NULL) {
- ec_log_warn("Unable to parse HTML document");
- ret = -1;
- goto exit;
- }
- lpNode = find_node(root, "head");
- if (!lpNode) {
- ec_log_debug("HTML document contains no HEAD tag");
- goto exit;
- }
- for (lpNode = lpNode->children; lpNode != NULL; lpNode = lpNode->next) {
- if (lpNode->type != XML_ELEMENT_NODE)
- continue;
- if (xmlStrcasecmp(lpNode->name,
- reinterpret_cast<const xmlChar *>("meta")) != 0)
- continue;
-
- lpValue = xmlGetProp(lpNode, (const xmlChar*)"http-equiv");
- if (lpValue && xmlStrcasecmp(lpValue, (const xmlChar*)"Content-Type") == 0) {
- xmlFree(lpValue);
- lpValue = xmlGetProp(lpNode, (const xmlChar*)"content");
- if (lpValue) {
- ec_log_debug("HTML4 meta tag found: charset=\"%s\"", lpValue);
- charset = fix_content_type_charset(reinterpret_cast<const char *>(lpValue));
- }
- break;
- }
- if (lpValue)
- xmlFree(lpValue);
- lpValue = NULL;
-
- lpValue = xmlGetProp(lpNode, (const xmlChar*)"charset");
- if (lpValue) {
- ec_log_debug("HTML5 meta tag found: charset=\"%s\"", lpValue);
- charset = reinterpret_cast<char *>(lpValue);
- break;
- }
- }
- if (!lpValue) {
- ec_log_debug("HTML body does not contain meta charset information");
- goto exit;
- }
- *htmlCharset = charset.size() != 0 ? vtm_upgrade_charset(charset) :
- vmime::charsets::US_ASCII;
- ec_log_debug("HTML charset adjusted to \"%s\"", htmlCharset->getName().c_str());
- ret = 1;
- exit:
- if (lpValue)
- xmlFree(lpValue);
- if (lpDoc)
- xmlFreeDoc(lpDoc);
- return ret;
- }
- std::wstring VMIMEToMAPI::getWideFromVmimeText(const vmime::text &vmText)
- {
- std::string myword;
- std::wstring ret;
- const auto &words = vmText.getWordList();
- for (auto i = words.cbegin(); i != words.cend(); ++i) {
-
- vmime::charset wordCharset = vtm_upgrade_charset((*i)->getCharset());
-
- if (!ValidateCharset(wordCharset.getName().c_str()))
- wordCharset = m_dopt.ascii_upgrade;
-
- myword = (*i)->getBuffer();
- for (auto j = i + 1; j != words.cend() && (*j)->getCharset() == wordCharset; ++j, ++i)
- myword += (*j)->getBuffer();
- std::string tmp = vmime::word(myword, wordCharset).getConvertedText(CHARSET_WCHAR);
- ret.append(reinterpret_cast<const wchar_t *>(tmp.c_str()), tmp.size() / sizeof(wchar_t));
- }
- return ret;
- }
- HRESULT VMIMEToMAPI::postWriteFixups(IMessage *lpMessage)
- {
- HRESULT hr = hrSuccess;
- memory_ptr<SPropValue> lpMessageClass, lpProps, lpRecProps;
- ULONG cValues = 0;
- ULONG cRecProps = 0;
- ULONG cbConversationIndex = 0;
- memory_ptr<unsigned char> lpConversationIndex;
- PROPMAP_START(21)
- PROPMAP_NAMED_ID(RECURRENCESTATE, PT_BINARY, PSETID_Appointment, dispidRecurrenceState)
- PROPMAP_NAMED_ID(RESPONSESTATUS, PT_LONG, PSETID_Appointment, dispidResponseStatus)
- PROPMAP_NAMED_ID(RECURRING, PT_BOOLEAN, PSETID_Appointment, dispidRecurring)
- PROPMAP_NAMED_ID(ATTENDEECRITICALCHANGE, PT_SYSTIME, PSETID_Meeting, dispidAttendeeCriticalChange)
- PROPMAP_NAMED_ID(OWNERCRITICALCHANGE, PT_SYSTIME, PSETID_Meeting, dispidOwnerCriticalChange)
- PROPMAP_NAMED_ID(MEETING_RECURRING, PT_BOOLEAN, PSETID_Meeting, dispidIsRecurring)
- PROPMAP_NAMED_ID(MEETING_STARTRECDATE, PT_LONG, PSETID_Meeting, dispidStartRecurrenceDate)
- PROPMAP_NAMED_ID(MEETING_STARTRECTIME, PT_LONG, PSETID_Meeting, dispidStartRecurrenceTime)
- PROPMAP_NAMED_ID(MEETING_ENDRECDATE, PT_LONG, PSETID_Meeting, dispidEndRecurrenceDate)
- PROPMAP_NAMED_ID(MEETING_ENDRECTIME, PT_LONG, PSETID_Meeting, dispidEndRecurrenceTime)
- PROPMAP_NAMED_ID(MEETING_DAYINTERVAL, PT_I2, PSETID_Meeting, dispidDayInterval)
- PROPMAP_NAMED_ID(MEETING_WEEKINTERVAL, PT_I2, PSETID_Meeting, dispidWeekInterval)
- PROPMAP_NAMED_ID(MEETING_MONTHINTERVAL, PT_I2, PSETID_Meeting, dispidMonthInterval)
- PROPMAP_NAMED_ID(MEETING_YEARINTERVAL, PT_I2, PSETID_Meeting, dispidYearInterval)
- PROPMAP_NAMED_ID(MEETING_DOWMASK, PT_LONG, PSETID_Meeting, dispidDayOfWeekMask)
- PROPMAP_NAMED_ID(MEETING_DOMMASK, PT_LONG, PSETID_Meeting, dispidDayOfMonthMask)
- PROPMAP_NAMED_ID(MEETING_MOYMASK, PT_LONG, PSETID_Meeting, dispidMonthOfYearMask)
- PROPMAP_NAMED_ID(MEETING_RECURRENCETYPE, PT_I2, PSETID_Meeting, dispidOldRecurrenceType)
- PROPMAP_NAMED_ID(MEETING_DOWSTART, PT_I2, PSETID_Meeting, dispidDayOfWeekStart)
- PROPMAP_NAMED_ID(CLIPSTART, PT_SYSTIME, PSETID_Appointment, dispidClipStart)
- PROPMAP_NAMED_ID(CLIPEND, PT_SYSTIME, PSETID_Appointment, dispidClipEnd)
- PROPMAP_INIT(lpMessage)
- hr = HrGetOneProp(lpMessage, PR_MESSAGE_CLASS_A, &~lpMessageClass);
- if (hr != hrSuccess)
- goto exitpm;
- if (strncasecmp(lpMessageClass->Value.lpszA, "IPM.Schedule.Meeting.", strlen( "IPM.Schedule.Meeting." )) == 0)
- {
-
- SizedSPropTagArray(6, sptaMeetingReqProps) = {6, {PROP_RESPONSESTATUS, PROP_RECURRING, PROP_ATTENDEECRITICALCHANGE, PROP_OWNERCRITICALCHANGE, PR_OWNER_APPT_ID, PR_CONVERSATION_INDEX }};
- hr = lpMessage->GetProps(sptaMeetingReqProps, 0, &cValues, &~lpProps);
- if(FAILED(hr))
- goto exitpm;
-
- if(hr != hrSuccess) {
- hr = hrSuccess;
- if(lpProps[0].ulPropTag != PROP_RESPONSESTATUS) {
- lpProps[0].ulPropTag = PROP_RESPONSESTATUS;
- lpProps[0].Value.ul = 0;
- }
- if(lpProps[1].ulPropTag != PROP_RECURRING) {
- lpProps[1].ulPropTag = PROP_RECURRING;
- lpProps[1].Value.b = false;
- }
- if(lpProps[2].ulPropTag != PROP_ATTENDEECRITICALCHANGE) {
- lpProps[2].ulPropTag = PROP_ATTENDEECRITICALCHANGE;
- UnixTimeToFileTime(time(NULL), &lpProps[2].Value.ft);
- }
- if(lpProps[3].ulPropTag != PROP_OWNERCRITICALCHANGE) {
- lpProps[3].ulPropTag = PROP_OWNERCRITICALCHANGE;
- UnixTimeToFileTime(time(NULL), &lpProps[3].Value.ft);
- }
- if(lpProps[4].ulPropTag != PR_OWNER_APPT_ID) {
- lpProps[4].ulPropTag = PR_OWNER_APPT_ID;
- lpProps[4].Value.ul = -1;
- }
- if(lpProps[5].ulPropTag != PR_CONVERSATION_INDEX) {
- lpProps[5].ulPropTag = PR_CONVERSATION_INDEX;
- hr = ScCreateConversationIndex(0, NULL, &cbConversationIndex, &~lpConversationIndex);
- if(hr != hrSuccess)
- goto exitpm;
- lpProps[5].Value.bin.cb = cbConversationIndex;
- lpProps[5].Value.bin.lpb = lpConversationIndex;
- }
- hr = lpMessage->SetProps(6, lpProps, NULL);
- if(hr != hrSuccess)
- goto exitpm;
- }
-
-
-
- if(lpProps[1].Value.b)
- {
-
-
-
- SPropValue sMeetingProps[14];
- SizedSPropTagArray (3, sptaRecProps) = { 3, { PROP_RECURRENCESTATE, PROP_CLIPSTART, PROP_CLIPEND } };
- RecurrenceState rec;
-
- hr = lpMessage->GetProps(sptaRecProps, 0, &cRecProps, &~lpRecProps);
- if(hr != hrSuccess)
- goto exitpm;
-
- hr = rec.ParseBlob(reinterpret_cast<const char *>(lpRecProps[0].Value.bin.lpb),
- static_cast<unsigned int>(lpRecProps[0].Value.bin.cb), 0);
- if(FAILED(hr))
- goto exitpm;
-
-
- hr = hrSuccess;
-
- sMeetingProps[0].ulPropTag = PROP_MEETING_STARTRECDATE;
- sMeetingProps[0].Value.ul = FileTimeToIntDate(lpRecProps[1].Value.ft);
-
- sMeetingProps[1].ulPropTag = PROP_MEETING_STARTRECTIME;
- sMeetingProps[1].Value.ul = SecondsToIntTime(rec.ulStartTimeOffset * 60);
- if(rec.ulEndType != ET_NEVER) {
- sMeetingProps[2].ulPropTag = PROP_MEETING_ENDRECDATE;
- sMeetingProps[2].Value.ul = FileTimeToIntDate(lpRecProps[2].Value.ft);
- } else {
- sMeetingProps[2].ulPropTag = PR_NULL;
- }
-
- sMeetingProps[3].ulPropTag = PROP_MEETING_ENDRECTIME;
- sMeetingProps[3].Value.ul = SecondsToIntTime(rec.ulEndTimeOffset * 60);
-
- sMeetingProps[4].ulPropTag = PROP_MEETING_DAYINTERVAL;
- sMeetingProps[4].Value.i = 0;
- sMeetingProps[5].ulPropTag = PROP_MEETING_WEEKINTERVAL;
- sMeetingProps[5].Value.i = 0;
- sMeetingProps[6].ulPropTag = PROP_MEETING_MONTHINTERVAL;
- sMeetingProps[6].Value.i = 0;
- sMeetingProps[7].ulPropTag = PROP_MEETING_YEARINTERVAL;
- sMeetingProps[7].Value.i = 0;
-
- sMeetingProps[8].ulPropTag = PROP_MEETING_DOWMASK;
- sMeetingProps[8].Value.ul = 0 ;
- sMeetingProps[9].ulPropTag = PROP_MEETING_DOMMASK;
- sMeetingProps[9].Value.ul = 0;
-
- sMeetingProps[10].ulPropTag = PROP_MEETING_MOYMASK;
- sMeetingProps[10].Value.ul = 0;
-
- sMeetingProps[11].ulPropTag = PROP_MEETING_RECURRENCETYPE;
- sMeetingProps[11].Value.ul = 0;
-
- sMeetingProps[12].ulPropTag = PROP_MEETING_DOWSTART;
- sMeetingProps[12].Value.i = rec.ulFirstDOW;
-
- sMeetingProps[13].ulPropTag = PROP_MEETING_RECURRING;
- sMeetingProps[13].Value.b = true;
-
- switch(rec.ulRecurFrequency) {
- case RF_DAILY:
- if (rec.ulPatternType == PT_DAY) {
-
- sMeetingProps[4].Value.i = rec.ulPeriod / 1440;
- sMeetingProps[11].Value.i = 64;
- } else {
-
- sMeetingProps[5].Value.i = 1;
- sMeetingProps[8].Value.ul = 62;
- sMeetingProps[11].Value.i = 48;
- }
- break;
- case RF_WEEKLY:
- sMeetingProps[5].Value.i = rec.ulPeriod;
- sMeetingProps[8].Value.ul = rec.ulWeekDays;
- sMeetingProps[11].Value.i = 48;
- break;
- case RF_MONTHLY:
- sMeetingProps[6].Value.i = rec.ulPeriod;
- if (rec.ulPatternType == PT_MONTH_NTH) {
- sMeetingProps[5].Value.ul = rec.ulWeekNumber;
- sMeetingProps[8].Value.ul = rec.ulWeekDays;
- sMeetingProps[11].Value.i = 56;
- } else {
- sMeetingProps[9].Value.ul = 1 << (rec.ulDayOfMonth - 1);
- sMeetingProps[11].Value.i = 12;
- }
- break;
- case RF_YEARLY:
- sMeetingProps[6].Value.i = rec.ulPeriod;
- sMeetingProps[7].Value.i = rec.ulPeriod / 12;
-
- sMeetingProps[10].Value.ul = 1 << ((rec.ulFirstDateTime/(24*60*29)) % 12);
- if (rec.ulPatternType == PT_MONTH_NTH) {
- sMeetingProps[5].Value.ul = rec.ulWeekNumber;
- sMeetingProps[8].Value.ul = rec.ulWeekDays;
- sMeetingProps[11].Value.i = 51;
- } else {
- sMeetingProps[9].Value.ul = 1 << (rec.ulDayOfMonth - 1);
- sMeetingProps[11].Value.i = 7;
- }
- break;
- default:
- break;
- }
-
- hr = lpMessage->SetProps(14, sMeetingProps, NULL);
- if(hr != hrSuccess)
- goto exitpm;
- }
- }
- exitpm:
- return hr;
- }
- static std::string StringEscape(const char *input, const char *tokens,
- const char escape)
- {
- std::string strEscaped;
- int i = 0;
- int t;
- while (true) {
- if (input[i] == 0)
- break;
- for (t = 0; tokens[t] != 0; ++t)
- if (input[i] == tokens[t])
- strEscaped += escape;
- strEscaped += input[i];
- ++i;
- }
- return strEscaped;
- }
- std::string VMIMEToMAPI::mailboxToEnvelope(vmime::shared_ptr<vmime::mailbox> mbox)
- {
- vector<string> lMBox;
- string buffer;
- string::size_type pos;
- vmime::utility::outputStreamStringAdapter os(buffer);
- if (!mbox || mbox->isEmpty())
- throw vmime::exceptions::no_such_field();
-
-
- mbox->getName().generate(os);
-
- buffer = StringEscape(buffer.c_str(), "\"", '\\');
- lMBox.push_back(buffer.empty() ? "NIL" : "\"" + buffer + "\"");
- lMBox.push_back("NIL");
- buffer = "\"" + mbox->getEmail().toString() + "\"";
- pos = buffer.find("@");
- if (pos != string::npos)
- buffer.replace(pos, 1, "\" \"");
- lMBox.push_back(std::move(buffer));
- if (pos == string::npos)
- lMBox.push_back("NIL");
- return "(" + kc_join(lMBox, " ") + ")";
- }
- std::string VMIMEToMAPI::addressListToEnvelope(vmime::shared_ptr<vmime::addressList> aList)
- {
- list<string> lAddr;
- string buffer;
- int aCount = 0;
- if (!aList)
- throw vmime::exceptions::no_such_field();
- aCount = aList->getAddressCount();
- if (aCount == 0)
- throw vmime::exceptions::no_such_field();
-
- for (int i = 0; i < aCount; ++i) {
- try {
- buffer += mailboxToEnvelope(vmime::dynamicCast<vmime::mailbox>(aList->getAddressAt(i)));
- lAddr.push_back(buffer);
- } catch (vmime::exception &e) {
- }
- }
- if (lAddr.empty())
- return string("NIL");
- return "(" + buffer + ")";
- }
- HRESULT VMIMEToMAPI::createIMAPEnvelope(vmime::shared_ptr<vmime::message> vmMessage,
- IMessage *lpMessage)
- {
- HRESULT hr = hrSuccess;
- std::string buffer;
- SPropValue sEnvelope;
- PROPMAP_START(1)
- PROPMAP_NAMED_ID(ENVELOPE, PT_STRING8, PS_EC_IMAP, dispidIMAPEnvelope);
- PROPMAP_INIT(lpMessage);
- buffer = createIMAPEnvelope(vmMessage);
- sEnvelope.ulPropTag = PROP_ENVELOPE;
- sEnvelope.Value.lpszA = (char*)buffer.c_str();
- hr = lpMessage->SetProps(1, &sEnvelope, NULL);
- exitpm:
- return hr;
- }
- std::string VMIMEToMAPI::createIMAPEnvelope(vmime::shared_ptr<vmime::message> vmMessage)
- {
- vector<string> lItems;
- auto vmHeader = vmMessage->getHeader();
- std::string buffer;
- vmime::utility::outputStreamStringAdapter os(buffer);
-
- try {
- vmime::shared_ptr<vmime::datetime> date;
- try {
- date = vmime::dynamicCast<vmime::datetime>(vmHeader->Date()->getValue());
- } catch (vmime::exception &e) {
-
- date = vmime::make_shared<vmime::datetime>(vmime::datetime::now());
- }
- date->generate(os);
- lItems.push_back("\"" + buffer + "\"");
- } catch (vmime::exception &e) {
-
- lItems.push_back("NIL");
- }
- buffer.clear();
-
- try {
- vmHeader->Subject()->getValue()->generate(os);
-
- buffer = StringEscape(buffer.c_str(), "\"", '\\');
- lItems.push_back(buffer.empty() ? "NIL" : "\"" + buffer + "\"");
- } catch (vmime::exception &e) {
- lItems.push_back("NIL");
- }
- buffer.clear();
-
- try {
- buffer = mailboxToEnvelope(vmime::dynamicCast<vmime::mailbox>(vmHeader->From()->getValue()));
- lItems.push_back("(" + buffer + ")");
- } catch (vmime::exception &e) {
-
- lItems.push_back("NIL");
- }
- buffer.clear();
-
- try {
- buffer = mailboxToEnvelope(vmime::dynamicCast<vmime::mailbox>(vmHeader->Sender()->getValue()));
- lItems.push_back("(" + buffer + ")");
- } catch (vmime::exception &e) {
- lItems.push_back(lItems.back());
- }
- buffer.clear();
-
- try {
- buffer = mailboxToEnvelope(vmime::dynamicCast<vmime::mailbox>(vmHeader->ReplyTo()->getValue()));
- lItems.push_back("(" + buffer + ")");
- } catch (vmime::exception &e) {
- lItems.push_back(lItems.back());
- }
- buffer.clear();
-
- try {
- buffer = addressListToEnvelope(vmime::dynamicCast<vmime::addressList>(vmHeader->To()->getValue()));
- lItems.push_back(buffer);
- } catch (vmime::exception &e) {
- lItems.push_back("NIL");
- }
- buffer.clear();
-
- try {
- auto aList = vmime::dynamicCast<vmime::addressList>(vmHeader->Cc()->getValue());
- int aCount = aList->getAddressCount();
- for (int i = 0; i < aCount; ++i)
- buffer += mailboxToEnvelope(vmime::dynamicCast<vmime::mailbox>(aList->getAddressAt(i)));
- lItems.push_back(buffer.empty() ? "NIL" : "(" + buffer + ")");
- } catch (vmime::exception &e) {
- lItems.push_back("NIL");
- }
- buffer.clear();
-
- try {
- auto aList = vmime::dynamicCast<vmime::addressList>(vmHeader->Bcc()->getValue());
- int aCount = aList->getAddressCount();
- for (int i = 0; i < aCount; ++i)
- buffer += mailboxToEnvelope(vmime::dynamicCast<vmime::mailbox>(aList->getAddressAt(i)));
- lItems.push_back(buffer.empty() ? "NIL" : "(" + buffer + ")");
- } catch (vmime::exception &e) {
- lItems.push_back("NIL");
- }
- buffer.clear();
-
- try {
- vmHeader->InReplyTo()->getValue()->generate(os);
- lItems.push_back(buffer.empty() ? "NIL" : "\"" + buffer + "\"");
- } catch (vmime::exception &e) {
- lItems.push_back("NIL");
- }
- buffer.clear();
-
- try {
- vmHeader->MessageId()->getValue()->generate(os);
- if (buffer.compare("<>") == 0)
- buffer.clear();
- lItems.push_back(buffer.empty() ? "NIL" : "\"" + buffer + "\"");
- } catch (vmime::exception &e) {
- lItems.push_back("NIL");
- }
- return kc_join(lItems, " ");
- }
- HRESULT VMIMEToMAPI::createIMAPBody(const string &input,
- vmime::shared_ptr<vmime::message> vmMessage, IMessage *lpMessage)
- {
- SPropValue sProps[4];
- string strBody;
- string strBodyStructure;
- messagePartToStructure(input, vmMessage, &strBody, &strBodyStructure);
- sProps[0].ulPropTag = PR_EC_IMAP_EMAIL_SIZE;
- sProps[0].Value.ul = input.length();
- sProps[1].ulPropTag = PR_EC_IMAP_EMAIL;
- sProps[1].Value.bin.lpb = (BYTE*)input.c_str();
- sProps[1].Value.bin.cb = input.length();
- sProps[2].ulPropTag = PR_EC_IMAP_BODY;
- sProps[2].Value.lpszA = (char*)strBody.c_str();
- sProps[3].ulPropTag = PR_EC_IMAP_BODYSTRUCTURE;
- sProps[3].Value.lpszA = (char*)strBodyStructure.c_str();
- return lpMessage->SetProps(4, sProps, NULL);
- }
- HRESULT VMIMEToMAPI::messagePartToStructure(const string &input,
- vmime::shared_ptr<vmime::bodyPart> vmBodyPart, std::string *lpSimple,
- std::string *lpExtended)
- {
- HRESULT hr = hrSuccess;
- list<string> lBody;
- list<string> lBodyStructure;
- auto vmHeaderPart = vmBodyPart->getHeader();
- try {
- vmime::shared_ptr<vmime::contentTypeField> ctf;
- if (vmHeaderPart->hasField(vmime::fields::CONTENT_TYPE))
-
- ctf = vmime::dynamicCast<vmime::contentTypeField>(vmHeaderPart->ContentType());
- else
-
- ctf = vmime::dynamicCast<vmime::contentTypeField>(vmime::headerFieldFactory::getInstance()->create("Content-Type", ""));
- auto mt = vmime::dynamicCast<vmime::mediaType>(ctf->getValue());
- if (mt->getType() == vmime::mediaTypes::MULTIPART) {
-
-
- if (vmBodyPart->getBody()->getPartCount() == 0)
- return hr;
-
- string strBody;
- string strBodyStructure;
- for (size_t i = 0; i < vmBodyPart->getBody()->getPartCount(); ++i) {
- messagePartToStructure(input, vmBodyPart->getBody()->getPartAt(i), &strBody, &strBodyStructure);
- lBody.push_back(std::move(strBody));
- lBodyStructure.push_back(std::move(strBodyStructure));
- strBody.clear();
- strBodyStructure.clear();
- }
-
- strBody = kc_join(lBody, "");
- strBodyStructure = kc_join(lBodyStructure, "");
- lBody.clear();
- lBody.push_back(std::move(strBody));
- lBodyStructure.clear();
- lBodyStructure.push_back(std::move(strBodyStructure));
-
-
-
-
- lBody.push_back("\"" + mt->getSubType() + "\"");
- lBodyStructure.push_back("\"" + mt->getSubType() + "\"");
- lBodyStructure.push_back(parameterizedFieldToStructure(ctf));
- lBodyStructure.push_back(getStructureExtendedFields(vmHeaderPart));
- if (lpSimple)
- *lpSimple = "(" + kc_join(lBody, " ") + ")";
- if (lpExtended)
- *lpExtended = "(" + kc_join(lBodyStructure, " ") + ")";
- } else {
-
- bodyPartToStructure(input, vmBodyPart, lpSimple, lpExtended);
- }
- }
- catch (vmime::exception &e) {
- ec_log_warn("Unable to create optimized bodystructure: %s", e.what());
- }
-
- return hr;
- }
- HRESULT VMIMEToMAPI::bodyPartToStructure(const string &input,
- vmime::shared_ptr<vmime::bodyPart> vmBodyPart, std::string *lpSimple,
- std::string *lpExtended)
- {
- string strPart;
- list<string> lBody;
- list<string> lBodyStructure;
- string buffer;
- vmime::utility::outputStreamStringAdapter os(buffer);
- vmime::shared_ptr<vmime::contentTypeField> ctf;
- vmime::shared_ptr<vmime::mediaType> mt;
- auto vmHeaderPart = vmBodyPart->getHeader();
- if (!vmHeaderPart->hasField(vmime::fields::CONTENT_TYPE)) {
-
- lBody.push_back("NIL");
- lBodyStructure.push_back("NIL");
- goto nil;
- }
- ctf = vmime::dynamicCast<vmime::contentTypeField>(vmHeaderPart->findField(vmime::fields::CONTENT_TYPE));
- mt = vmime::dynamicCast<vmime::mediaType>(ctf->getValue());
- lBody.push_back("\"" + mt->getType() + "\"");
- lBody.push_back("\"" + mt->getSubType() + "\"");
-
- lBody.push_back(parameterizedFieldToStructure(ctf));
- if (vmHeaderPart->hasField(vmime::fields::CONTENT_ID)) {
- buffer = vmime::dynamicCast<vmime::messageId>(vmHeaderPart->findField(vmime::fields::CONTENT_ID)->getValue())->getId();
- lBody.push_back(buffer.empty() ? "NIL" : "\"<" + buffer + ">\"");
- } else {
- lBody.push_back("NIL");
- }
- if (vmHeaderPart->hasField(vmime::fields::CONTENT_DESCRIPTION)) {
- buffer.clear();
- vmHeaderPart->findField(vmime::fields::CONTENT_DESCRIPTION)->getValue()->generate(os);
- lBody.push_back(buffer.empty() ? "NIL" : "\"" + buffer + "\"");
- } else {
- lBody.push_back("NIL");
- }
- if (vmHeaderPart->hasField(vmime::fields::CONTENT_TRANSFER_ENCODING)) {
- buffer.clear();
- vmHeaderPart->findField(vmime::fields::CONTENT_TRANSFER_ENCODING)->getValue()->generate(os);
- lBody.push_back(buffer.empty() ? "NIL" : "\"" + buffer + "\"");
- } else {
- lBody.push_back("NIL");
- }
- if (mt->getType() == vmime::mediaTypes::TEXT) {
-
- buffer = stringify(vmBodyPart->getBody()->getParsedLength());
- lBody.push_back(buffer);
-
- buffer = stringify(countBodyLines(input, vmBodyPart->getBody()->getParsedOffset(), vmBodyPart->getBody()->getParsedLength()));
- lBody.push_back(buffer);
- } else {
-
- buffer = stringify(vmBodyPart->getBody()->getParsedLength());
- lBody.push_back(buffer);
- }
-
- lBodyStructure = lBody;
- if (mt->getType() == vmime::mediaTypes::MESSAGE && mt->getSubType() == vmime::mediaTypes::MESSAGE_RFC822) {
- string strSubSingle;
- string strSubExtended;
- auto subMessage = vmime::make_shared<vmime::message>();
-
-
-
-
-
-
- vmBodyPart->getBody()->getContents()->extractRaw(os);
- subMessage->parse(buffer);
- lBody.push_back("("+createIMAPEnvelope(subMessage)+")");
- lBodyStructure.push_back("("+createIMAPEnvelope(subMessage)+")");
-
- messagePartToStructure(buffer, subMessage, &strSubSingle, &strSubExtended);
- lBody.push_back(std::move(strSubSingle));
- lBodyStructure.push_back(std::move(strSubExtended));
-
- lBody.push_back(stringify(countBodyLines(buffer, 0, buffer.length())));
- }
- nil:
- if (lpSimple)
- *lpSimple = "(" + kc_join(lBody, " ") + ")";
-
- lBodyStructure.push_back("NIL");
- lBodyStructure.push_back(getStructureExtendedFields(vmHeaderPart));
- if (lpExtended)
- *lpExtended = "(" + kc_join(lBodyStructure, " ") + ")";
- return hrSuccess;
- }
- std::string VMIMEToMAPI::getStructureExtendedFields(vmime::shared_ptr<vmime::header> vmHeaderPart)
- {
- list<string> lItems;
- string buffer;
- vmime::utility::outputStreamStringAdapter os(buffer);
-
- if (vmHeaderPart->hasField(vmime::fields::CONTENT_DISPOSITION)) {
-
- auto cdf = vmime::dynamicCast<vmime::contentDispositionField>(vmHeaderPart->findField(vmime::fields::CONTENT_DISPOSITION));
- auto cd = vmime::dynamicCast<vmime::contentDisposition>(cdf->getValue());
- lItems.push_back("(\"" + cd->getName() + "\" " + parameterizedFieldToStructure(cdf) + ")");
- } else {
- lItems.push_back("NIL");
- }
-
- lItems.push_back("NIL");
-
- try {
- buffer.clear();
- vmHeaderPart->ContentLocation()->getValue()->generate(os);
- lItems.push_back(buffer.empty() ? "NIL" : "\"" + buffer + "\"");
- }
- catch (vmime::exception &e) {
- lItems.push_back("NIL");
- }
- return kc_join(lItems, " ");
- }
- std::string VMIMEToMAPI::parameterizedFieldToStructure(vmime::shared_ptr<vmime::parameterizedHeaderField> vmParamField)
- {
- list<string> lParams;
- string buffer;
- vmime::utility::outputStreamStringAdapter os(buffer);
- try {
- for (const auto ¶m : vmParamField->getParameterList()) {
- lParams.push_back("\"" + param->getName() + "\"");
- param->getValue().generate(os);
- lParams.push_back("\"" + buffer + "\"");
- buffer.clear();
- }
- }
- catch (vmime::exception &e) {
- return "NIL";
- }
- if (lParams.empty())
- return "NIL";
- return "(" + kc_join(lParams, " ") + ")";
- }
- std::string::size_type VMIMEToMAPI::countBodyLines(const std::string &input, std::string::size_type start, std::string::size_type length)
- {
- string::size_type lines = 0;
- string::size_type pos = start;
- while (true) {
- pos = input.find_first_of('\n', pos);
- if (pos == string::npos || pos > start+length)
- break;
- ++pos;
- ++lines;
- }
- return lines;
- }
- void imopt_default_delivery_options(delivery_options *dopt) {
- dopt->use_received_date = true;
- dopt->mark_as_read = false;
- dopt->add_imap_data = false;
- dopt->charset_strict_rfc = true;
- dopt->user_entryid = NULL;
- dopt->parse_smime_signed = false;
- dopt->ascii_upgrade = nullptr;
- dopt->html_safety_filter = false;
- }
- void imopt_default_sending_options(sending_options *sopt) {
- sopt->alternate_boundary = NULL;
- sopt->no_recipients_workaround = false;
- sopt->msg_in_msg = false;
- sopt->headers_only = false;
- sopt->add_received_date = false;
- sopt->use_tnef = 0;
- sopt->force_utf8 = false;
- sopt->charset_upgrade = const_cast<char *>("windows-1252");
- sopt->allow_send_to_everyone = true;
- sopt->enable_dsn = true;
- sopt->always_expand_distr_list = false;
- sopt->ignore_missing_attachments = false;
- }
- }
|