imapsync 339 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488
  1. #!/usr/bin/perl
  2. # $Id: imapsync,v 1.727 2016/08/19 10:30:36 gilles Exp gilles $
  3. # structure
  4. # pod documentation
  5. # pragmas
  6. # main program
  7. # global variables initialisation
  8. # get_options( ) ;
  9. # default values
  10. # folder loop
  11. # subroutines
  12. # sub usage {
  13. # IMAPClient 3.xx ads
  14. # pod documentation
  15. =pod
  16. =head1 NAME
  17. imapsync - Email IMAP tool for syncing, copying and migrating email mailboxes.
  18. The imapsync command synchronises mailboxes between two imap servers.
  19. More than 69 different IMAP server softwares supported with success,
  20. few failures.
  21. $Revision: 1.727 $
  22. =head1 SYNOPSIS
  23. To synchronize the source imap account
  24. "test1" on server "test1.lamiral.info" with password "secret1"
  25. to the destination imap account
  26. "test2" on server "test2.lamiral.info" with password "secret2"
  27. do:
  28. imapsync \
  29. --host1 test1.lamiral.info --user1 test1 --password1 secret1 \
  30. --host2 test2.lamiral.info --user2 test2 --password2 secret2
  31. =head1 REQUIRED ARGUMENTS
  32. The required argmuments are the six values, three on each sides,
  33. needed to login into the IMAP servers,
  34. a host, a username, and a password, two times.
  35. =head1 INSTALL
  36. Imapsync works under any Unix with perl.
  37. Imapsync works under Windows (2000, XP, Vista, Seven)
  38. as a standalone binary software called imapsync.exe
  39. Imapsync works under OS X as a standalone binary
  40. software called imapsync_bin_Darwin.
  41. Purchase latest imapsync at
  42. http://imapsync.lamiral.info/
  43. You'll receive a link to a compressed tarball called imapsync-x.xx.tgz
  44. where x.xx is the version number. Untar the tarball where
  45. you want (on Unix):
  46. tar xzvf imapsync-x.xx.tgz
  47. Go into the directory imapsync-x.xx and read the INSTALL file.
  48. As mentioned at http://imapsync.lamiral.info/#install
  49. the INSTALL file can also be found at
  50. http://imapsync.lamiral.info/INSTALL
  51. It is now split in several files for each system
  52. http://imapsync.lamiral.info/INSTALL.d/
  53. =head1 CONFIGURATION
  54. There is no specific configuration file for imapsync,
  55. everything is specified by the command line parameteres
  56. and the default behavior.
  57. =head1 USAGE
  58. To get a description of each option just run imapsync
  59. with no argument, like this:
  60. imapsync
  61. This description of options is also available at
  62. http://imapsync.lamiral.info/OPTIONS and is
  63. reproduced here:
  64. usage: ./imapsync [options]
  65. Several options are mandatory.
  66. str means string
  67. int means integer
  68. reg means regular expression
  69. cmd means command
  70. --dry : Makes imapsync doing nothing, just print what would
  71. be done without --dry.
  72. --host1 str : Source or "from" imap server. Mandatory.
  73. --port1 int : Port to connect on host1. Default is 143, 993 if --ssl1
  74. --user1 str : User to login on host1. Mandatory.
  75. --showpasswords : Shows passwords on output instead of "MASKED".
  76. Useful to restart a complete run by just reading the log.
  77. --password1 str : Password for the user1.
  78. --host2 str : "destination" imap server. Mandatory.
  79. --port2 int : Port to connect on host2. Default is 143, 993 if --ssl2
  80. --user2 str : User to login on host2. Mandatory.
  81. --password2 str : Password for the user2.
  82. --passfile1 str : Password file for the user1. It must contain the
  83. password on the first line. This option avoids to show
  84. the password on the command line like --password1 does.
  85. --passfile2 str : Password file for the user2. Contains the password.
  86. --ssl1 : Use a SSL connection on host1.
  87. --ssl2 : Use a SSL connection on host2.
  88. --tls1 : Use a TLS connection on host1.
  89. --tls2 : Use a TLS connection on host2.
  90. --debugssl int : SSL debug mode from 0 to 4.
  91. --sslargs1 str : Pass any ssl parameter for host1 ssl or tls connection. Example:
  92. --sslargs1 SSL_verify_mode=1 --sslargs1 SSL_version=SSLv3
  93. See all possibilities in the new() method of IO::Socket::SSL
  94. http://search.cpan.org/perldoc?IO::Socket::SSL#Description_Of_Methods
  95. --sslargs2 str : Pass any ssl parameter for host2 ssl or tls connection.
  96. See --sslargs1
  97. --timeout1 int : Connection timeout in seconds for host1.
  98. Default is 120 and 0 means no timeout at all.
  99. --timeout2 int : Connection timeout in seconds for host2.
  100. Default is 120 and 0 means no timeout at all.
  101. --authmech1 str : Auth mechanism to use with host1:
  102. PLAIN, LOGIN, CRAM-MD5 etc. Use UPPERCASE.
  103. --authmech2 str : Auth mechanism to use with host2. See --authmech1
  104. --authuser1 str : User to auth with on host1 (admin user).
  105. Avoid using --authmech1 SOMETHING with --authuser1.
  106. --authuser2 str : User to auth with on host2 (admin user).
  107. --proxyauth1 : Use proxyauth on host1. Requires --authuser1.
  108. Required by Sun/iPlanet/Netscape IMAP servers to
  109. be able to use an administrative user.
  110. --proxyauth2 : Use proxyauth on host2. Requires --authuser2.
  111. --authmd51 : Use MD5 authentification for host1.
  112. --authmd52 : Use MD5 authentification for host2.
  113. --domain1 str : Domain on host1 (NTLM authentication).
  114. --domain2 str : Domain on host2 (NTLM authentication).
  115. --folder str : Sync this folder.
  116. --folder str : and this one, etc.
  117. --folderrec str : Sync this folder recursively.
  118. --folderrec str : and this one, etc.
  119. --folderfirst str : Sync this folder first. --folderfirst "Work"
  120. --folderfirst str : then this one, etc.
  121. --folderlast str : Sync this folder last. --folderlast "[Gmail]/All Mail"
  122. --folderlast str : then this one, etc.
  123. --nomixfolders : Do not merge folders when host1 is case sensitive
  124. while host2 is not (like Exchange). Only the first
  125. similar folder is synced (ex: Sent SENT sent -> Sent).
  126. --skipemptyfolders : Empty host1 folders are not created on host2.
  127. --f1f2 str1=str2 : Force folder str1 to be synced to str2.
  128. --include reg : Sync folders matching this regular expression
  129. --include reg : or this one, etc.
  130. in case both --include --exclude options are
  131. use, include is done before.
  132. --exclude reg : Skips folders matching this regular expression
  133. Several folders to avoid:
  134. --exclude 'fold1|fold2|f3' skips fold1, fold2 and f3.
  135. --exclude reg : or this one, etc.
  136. --subfolder2 str : Move whole host1 folders hierarchy under this
  137. host2 folder str .
  138. It does it by adding two --regextrans2 options before
  139. all others. Add --debug to see what's really going on.
  140. --regextrans2 reg : Apply the whole regex to each destination folders.
  141. --regextrans2 reg : and this one. etc.
  142. When you play with the --regextrans2 option, first
  143. add also the safe options --dry --justfolders
  144. Then, when happy, remove --dry, remove --justfolders.
  145. Have in mind that --regextrans2 is applied after prefix
  146. and separator inversion.
  147. --tmpdir str : Where to store temporary files and subdirectories.
  148. Will be created if it doesn't exist.
  149. Default is system specific, Unix is /tmp but
  150. it's often small and deleted at reboot.
  151. --tmpdir /var/tmp should be better.
  152. --pidfile str : The file where imapsync pid is written.
  153. --pidfilelocking : Abort if pidfile already exists. Usefull to avoid
  154. concurrent transfers on the same mailbox.
  155. --nolog : Turn off logging on file
  156. --logfile str : Change the default log filename (can be dirname/filename).
  157. --logdir str : Change the default log directory. Default is LOG_imapsync
  158. --prefix1 str : Remove prefix to all destination folders
  159. (usually INBOX. or INBOX/ or an empty string "")
  160. you have to use --prefix1 if host1 imap server
  161. does not have NAMESPACE capability, so imapsync
  162. suggests to use it. All other cases are bad.
  163. --prefix2 str : Add prefix to all host2 folders. See --prefix1
  164. --sep1 str : Host1 separator in case NAMESPACE is not supported.
  165. --sep2 str : Host2 separator in case NAMESPACE is not supported.
  166. --skipmess reg : Skips messages maching the regex.
  167. Example: 'm/[\x80-ff]/' # to avoid 8bits messages.
  168. --skipmess is applied before --regexmess
  169. --skipmess reg : or this one, etc.
  170. --pipemess cmd : Apply this cmd command to each message content
  171. before the copy.
  172. --pipemess cmd : and this one, etc.
  173. --disarmreadreceipts : Disarms read receipts (host2 Exchange issue)
  174. --regexmess reg : Apply the whole regex to each message before transfer.
  175. Example: 's/\000/ /g' # to replace null by space.
  176. --regexmess reg : and this one, etc.
  177. --regexflag reg : Apply the whole regex to each flags list.
  178. Example: 's/"Junk"//g' # to remove "Junk" flag.
  179. --regexflag reg : and this one, etc.
  180. --delete : Deletes messages on host1 server after a successful
  181. transfer. Option --delete has the following behavior:
  182. it marks messages as deleted with the IMAP flag
  183. \Deleted, then messages are really deleted with an
  184. EXPUNGE IMAP command.
  185. --delete2 : Delete messages in host2 that are not in
  186. host1 server. Useful for backup or pre-sync.
  187. --delete2duplicates : Delete messages in host2 that are duplicates.
  188. Works only without --useuid since duplicates are
  189. detected with an header part of each message.
  190. --delete2folders : Delete folders in host2 that are not in host1 server.
  191. For safety, first try it like this (it is safe):
  192. --delete2folders --dry --justfolders --nofoldersizes
  193. --delete2foldersonly reg : Deleted only folders matching regex.
  194. Example: --delete2foldersonly "/^Junk$|^INBOX.Junk$/"
  195. --delete2foldersbutnot reg : Do not delete folders matching regex.
  196. Example: --delete2foldersbutnot "/Tasks$|Contacts$|Foo$/"
  197. --noexpunge : Do not expunge messages on host1.
  198. Expunge really deletes messages marked deleted.
  199. Expunge is made at the beginning, on host1 only.
  200. Newly transferred messages are also expunged if
  201. option --delete is given.
  202. No expunge is done on host2 account (unless --expunge2)
  203. --expunge1 : Expunge messages on host1 after messages transfer.
  204. --expunge2 : Expunge messages on host2 after messages transfer.
  205. --uidexpunge2 : uidexpunge messages on the host2 account
  206. that are not on the host1 account, requires --delete2
  207. --nomixfolders : Avoid merging folders that are considered different on
  208. host1 but the same on destination host2 because of
  209. case sensitivities and insensitivities.
  210. --syncinternaldates : Sets the internal dates on host2 same as host1.
  211. Turned on by default. Internal date is the date
  212. a message arrived on a host (mtime).
  213. --idatefromheader : Sets the internal dates on host2 same as the
  214. "Date:" headers.
  215. --maxsize int : Skip messages larger (or equal) than int bytes
  216. --minsize int : Skip messages smaller (or equal) than int bytes
  217. --maxage int : Skip messages older than int days.
  218. final stats (skipped) don't count older messages
  219. see also --minage
  220. --minage int : Skip messages newer than int days.
  221. final stats (skipped) don't count newer messages
  222. You can do (+ are the messages selected):
  223. past|----maxage+++++++++++++++>now
  224. past|+++++++++++++++minage---->now
  225. past|----maxage+++++minage---->now (intersection)
  226. past|++++minage-----maxage++++>now (union)
  227. --search str : Selects only messages returned by this IMAP SEARCH
  228. command. Applied on both sides.
  229. --search1 str : Same as --search for selecting host1 messages only.
  230. --search2 str : Same as --search for selecting host2 messages only.
  231. --search CRIT equals --search1 CRIT --search2 CRIT
  232. --exitwhenover int : Stop syncing when total bytes transferred reached.
  233. Gmail per day allows
  234. 2500000000 = 2.5 GB downloaded from Gmail as host2
  235. 500000000 = 500 MB uploaded to Gmail as host1.
  236. --maxlinelength int : skip messages with a line length longer than int bytes.
  237. RFC 2822 says it must be no more than 1000 bytes.
  238. --useheader str : Use this header to compare messages on both sides.
  239. Ex: Message-ID or Subject or Date.
  240. --useheader str and this one, etc.
  241. --subscribed : Transfers subscribed folders.
  242. --subscribe : Subscribe to the folders transferred on the
  243. host2 that are subscribed on host1. On by default.
  244. --subscribeall : Subscribe to the folders transferred on the
  245. host2 even if they are not subscribed on host1.
  246. --nofoldersizes : Do not calculate the size of each folder in bytes
  247. and message counts. Default is to calculate them.
  248. --nofoldersizesatend: Do not calculate the size of each folder in bytes
  249. and message counts at the end. Default is on.
  250. --justfoldersizes : Exit after having printed the folder sizes.
  251. --syncacls : Synchronises acls (Access Control Lists).
  252. --nosyncacls : Does not synchronize acls. This is the default.
  253. Acls in IMAP are not standardized, be careful.
  254. --usecache : Use cache to speedup.
  255. --nousecache : Do not use cache. Caveat: --useuid --nousecache creates
  256. duplicates on multiple runs.
  257. --useuid : Use uid instead of header as a criterium to recognize
  258. messages. Option --usecache is then implied unless
  259. --nousecache is used.
  260. --debug : Debug mode.
  261. --debugfolders : Debug mode for the folders part only.
  262. --debugcontent : Debug content of the messages transfered. Huge ouput.
  263. --debugflags : Debug mode for flags.
  264. --debugimap1 : IMAP debug mode for host1. Very verbose.
  265. --debugimap2 : IMAP debug mode for host2. Very verbose.
  266. --debugimap : IMAP debug mode for host1 and host2.
  267. --debugmemory : Debug mode showing memory consumption after each copy.
  268. --errorsmax int : Exit when int number of errors is reached. Default is 50.
  269. --tests : Run local non-regression tests. Exit code 0 means all ok.
  270. --testslive : Run a live test with test1.lamiral.info imap server.
  271. Useful to check the basics. Needs internet connexion.
  272. --version : Print only software version.
  273. --noreleasecheck : Do not check for new imapsync release (a http request).
  274. --releasecheck : Check for new imapsync release (a http request).
  275. --noid : Do not send/receive ID command to imap servers.
  276. --justconnect : Just connect to both servers and print useful
  277. information. Need only --host1 and --host2 options.
  278. --justlogin : Just login to both host1 and host2 with users
  279. credentials, then exit.
  280. --justfolders : Do only things about folders (ignore messages).
  281. --help : print this help.
  282. Example:
  283. To synchronize the source imap account
  284. "test1" on server "test1.lamiral.info" with password "secret1"
  285. to the destination imap account
  286. "test2" on server "test2.lamiral.info" with password "secret2"
  287. do:
  288. imapsync \
  289. --host1 test1.lamiral.info --user1 test1 --password1 secret1 \
  290. --host2 test2.lamiral.info --user2 test2 --password2 secret2
  291. =cut
  292. # comment
  293. =pod
  294. =head1 DESCRIPTION
  295. Imapsync command is a tool allowing incremental and
  296. recursive imap transfers from one mailbox to another.
  297. By default all folders are transferred, recursively, all
  298. possible flags (\Seen \Answered \Flagged etc.) are synced too.
  299. We sometimes need to transfer mailboxes from one imap server to
  300. another. This is called migration.
  301. Imapsync reduces the amount
  302. of data transferred by not transferring a given message
  303. if it resides already on both sides. Same specific headers
  304. and the transfer is done only once; taken into account are by default
  305. Message-Id and Received header lines.
  306. All flags are
  307. preserved, unread will stay unread, read will stay read,
  308. deleted will stay deleted. You can stop the transfer at any
  309. time and restart it later, imapsync works well with bad
  310. connections and interruptions.
  311. You can decide to delete the messages from the source mailbox
  312. after a successful transfer, it can be a good feature when migrating
  313. live mailboxes since messages will be only on one side.
  314. In that case, use the --delete option. Option --delete implies
  315. also option --expunge so all messages marked deleted on host1
  316. will be really deleted.
  317. (you can use --noexpunge to avoid this but I don't see any
  318. good real world scenario for the combination --delete --noexpunge).
  319. A different scenario is synchronizing a mailbox B from another mailbox A
  320. in case you just want to keep a "live" copy of A in B.
  321. In that case --delete2 has to be used, it deletes messages in host2
  322. folder B that are not in host1 folder A. If you also need to destroy
  323. host2 folders that are not in host1 then use --delete2folders (see also
  324. --delete2foldersonly and --delete2foldersbutnot).
  325. Imapsync is not adequate for maintaining two active imap accounts
  326. in synchronization when the user plays independently on both sides.
  327. Use offlineimap (written by John Goerzen) or mbsync (written by
  328. Michael R. Elkins) for 2 ways synchronizations.
  329. =head1 OPTIONS
  330. To get a description of each option just invoke:
  331. imapsync
  332. or read the previous section named USAGE,
  333. or read http://imapsync.lamiral.info/OPTIONS
  334. =head1 HISTORY
  335. I wrote imapsync because an enterprise (basystemes) paid me to install
  336. a new imap server without losing huge old mailboxes located on a far
  337. away remote imap server accessible by a low bandwidth link. The tool
  338. imapcp (written in python) could not help me because I had to verify
  339. every mailbox was well transferred and delete it after a good
  340. transfer. imapsync started its life as a copy_folder.pl patch.
  341. The tool copy_folder.pl comes from the Mail-IMAPClient-2.1.3 perl
  342. module tarball source (in the examples/ directory of the tarball).
  343. =head1 EXAMPLE
  344. While working on imapsync parameters please run imapsync in
  345. dry mode (no modification induced) with the --dry
  346. option. Nothing bad can be done this way.
  347. To synchronize the imap account "buddy" (with password "secret1")
  348. on host "imap.src.fr" to the imap account "max" (with password "secret2")
  349. on host "imap.dest.fr":
  350. imapsync --host1 imap.src.fr --user1 buddy --password1 secret1 \
  351. --host2 imap.dest.fr --user2 max --password2 secret2
  352. Then you will have max's mailbox updated from buddy's
  353. mailbox.
  354. =head1 SECURITY
  355. You can use --passfile1 instead of --password1 to give the
  356. password since it is safer. With --password1 option any user
  357. on your host can see the password by using the 'ps auxwwww'
  358. command. Using a variable (like $PASSWORD1) is also
  359. dangerous because of the 'ps auxwwwwe' command. So, saving
  360. the password in a well protected file (600 or rw-------) is
  361. the best solution.
  362. imasync is not totally protected against sniffers on the
  363. network since passwords may be transferred in plain text
  364. if CRAM-MD5 is not supported by your imap servers. Use
  365. --ssl1 (or --tls1) and --ssl2 (or --tls2) to enable
  366. encryption on host1 and host2.
  367. You may authenticate as one user (typically an admin user),
  368. but be authorized as someone else, which means you don't
  369. need to know every user's personal password. Specify
  370. --authuser1 "adminuser" to enable this on host1. In this
  371. case, --authmech1 PLAIN will be used by default since it
  372. is the only way to go for now. So don't use --authmech1 SOMETHING
  373. with --authuser1 "adminuser", it will not work.
  374. Same behavior with the --authuser2 option.
  375. Authenticate with an admin account must be supported by your
  376. imap server to work with imapsync.
  377. When working on Sun/iPlanet/Netscape IMAP servers you must use
  378. --proxyauth1 to enable administrative user to masquerade as another user.
  379. Can also be used on destination server with --proxyauth2
  380. You can authenticate with OAUTH when transfering from Google Apps.
  381. The consumer key will be the domain part of the --user, and the
  382. --password will be used as the consumer secret. It does not work
  383. with Google Apps free edition.
  384. =head1 EXIT STATUS
  385. imapsync will exit with a 0 status (return code) if everything went good.
  386. Otherwise, it exits with a non-zero status.
  387. So if you have an unreliable internet connection, you can use this loop
  388. in a Bourne shell:
  389. while ! imapsync ...; do
  390. echo imapsync not complete
  391. done
  392. =head1 LICENSE AND COPYRIGHT
  393. imapsync is free, open, public but not always gratis software
  394. cover by the NOLIMIT Public License.
  395. See the LICENSE file included in the distribution or just read this
  396. simple sentence as it is the licence text:
  397. "No limit to do anything with this work and this license."
  398. In case it is not long enough I repeat:
  399. "No limit to do anything with this work and this license."
  400. =head1 MAILING-LIST
  401. The public mailing-list may be the best way to get free support.
  402. To write on the mailing-list, the address is:
  403. <imapsync@linux-france.org>
  404. To subscribe, send any message (even empty) to:
  405. <imapsync-subscribe@listes.linux-france.org>
  406. then just reply to the confirmation message.
  407. To unsubscribe, send a message to:
  408. <imapsync-unsubscribe@listes.linux-france.org>
  409. To contact the person in charge for the list:
  410. <imapsync-request@listes.linux-france.org>
  411. The list archives are available at:
  412. http://www.linux-france.org/prj/imapsync_list/
  413. So consider that the list is public, anyone
  414. can see your post. Use a pseudonym or do not
  415. post to this list if you want to stay private.
  416. Thank you for your participation.
  417. =head1 AUTHOR
  418. Gilles LAMIRAL <gilles.lamiral@laposte.net>
  419. Feedback good or bad is very often welcome.
  420. Gilles LAMIRAL earns his living by writing, installing,
  421. configuring and teaching free, open and often gratis
  422. softwares. It used to be "always gratis" but now it is
  423. "often" because imapsync is sold by its author, a good
  424. way to stay maintening and supporting free open public
  425. softwares (see the license) over decades.
  426. =head1 BUGS AND LIMITATIONS
  427. Help me to help you: follow the following guidelines.
  428. Report any bugs or feature requests to the public mailing-list
  429. or to the author.
  430. Before reporting bugs, read the FAQs, the README and the
  431. TODO files. http://imapsync.lamiral.info/
  432. Upgrade to last imapsync release, maybe the bug
  433. is already fixed.
  434. Upgrade to last Mail-IMAPClient Perl module.
  435. http://search.cpan.org/dist/Mail-IMAPClient/
  436. maybe the bug is already fixed there.
  437. Make a good title with word "imapsync" in it (my spam filters won't filter it),
  438. Try to write an email title with more words than just "imapsync" or "problem",
  439. a good title is made of keywords summary, but not too long (one visible line).
  440. Help us to help you: in your report, please include:
  441. - imapsync version.
  442. - output near the first failures, a few lines before is good to get the context
  443. of the issue. First failures messages are often more significant than
  444. the last ones.
  445. - if the issue is always related to the same messages, include the output
  446. with --debug --debugimap, near the failure point. For example,
  447. Isolate a buggy message or two in a folder 'BUG' and use
  448. imapsync ... --folder 'BUG' --debug --debugimap
  449. - imap server softwares on both sides and their version number.
  450. - imapsync with all the options you use, the full command line
  451. you use (except the passwords of course).
  452. - IMAPClient.pm version.
  453. - the run context. Do you run imapsync.exe, a unix binary
  454. or the perl script imapsync.
  455. - operating system running imapsync.
  456. - virtual software context (vmware, xen etc.)
  457. - operating systems on both sides and the third side in case
  458. you run imapsync on a foreign host from the both.
  459. Most of those values can be found as a copy/paste at the begining of the output,
  460. so a carbon copy of the output is a very easy and very good debug report for me.
  461. One time in your life, read the paper
  462. "How To Ask Questions The Smart Way"
  463. http://www.catb.org/~esr/faqs/smart-questions.html
  464. and then forget it.
  465. =head1 IMAP SERVERS
  466. See http://imapsync.lamiral.info/S/imapservers.shtml
  467. =head1 HUGE MIGRATION
  468. Pay special attention to options
  469. --subscribed
  470. --subscribe
  471. --delete
  472. --delete2
  473. --delete2folders
  474. --maxage
  475. --minage
  476. --maxsize
  477. --useuid
  478. --usecache
  479. If you have many mailboxes to migrate think about a little
  480. shell program. Write a file called file.txt (for example)
  481. containing users and passwords.
  482. The separator used in this example is ';'
  483. The file.txt file contains:
  484. user001_1;password001_1;user001_2;password001_2
  485. user002_1;password002_1;user002_2;password002_2
  486. user003_1;password003_1;user003_2;password003_2
  487. user004_1;password004_1;user004_2;password004_2
  488. user005_1;password005_1;user005_2;password005_2
  489. ...
  490. On Unix the shell program can be:
  491. { while IFS=';' read u1 p1 u2 p2; do
  492. imapsync --host1 imap.side1.org --user1 "$u1" --password1 "$p1" \
  493. --host2 imap.side2.org --user2 "$u2" --password2 "$p2" ...
  494. done ; } < file.txt
  495. On Windows the batch program can be:
  496. FOR /F "tokens=1,2,3,4 delims=; eol=#" %%G IN (file.txt) DO imapsync ^
  497. --host1 imap.side1.org --user1 %%G --password1 %%H ^
  498. --host2 imap.side2.org --user2 %%I --password2 %%J ...
  499. The ... have to be replaced by nothing or any imapsync option.
  500. Welcome in shell programming !
  501. You will find already written scripts at
  502. http://imapsync.lamiral.info/examples/
  503. =head1 HACKING
  504. Feel free to hack imapsync as the NOLIMIT license permits it.
  505. =head1 LINKS
  506. Entries for imapsync:
  507. https://web.archive.org/web/20070202005121/http://www.imap.org/products/showall.php
  508. =head1 SIMILAR SOFTWARES
  509. imap_tools : http://www.athensfbc.com/imap_tools
  510. offlineimap : https://github.com/nicolas33/offlineimap
  511. mbsync : http://isync.sourceforge.net/
  512. mailsync : http://mailsync.sourceforge.net/
  513. mailutil : http://www.washington.edu/imap/
  514. part of the UW IMAP tookit.
  515. imaprepl : http://www.bl0rg.net/software/
  516. http://freecode.com/projects/imap-repl/
  517. imapcopy : http://home.arcor.de/armin.diehl/imapcopy/imapcopy.html
  518. migrationtool : http://sourceforge.net/projects/migrationtool/
  519. imapmigrate : http://sourceforge.net/projects/cyrus-utils/
  520. wonko_imapsync: http://wonko.com/article/554
  521. see also file W/tools/wonko_ruby_imapsync
  522. exchange-away : http://exchange-away.sourceforge.net/
  523. pop2imap : http://www.linux-france.org/prj/pop2imap/
  524. Feedback (good or bad) will often be welcome.
  525. $Id: imapsync,v 1.727 2016/08/19 10:30:36 gilles Exp gilles $
  526. =cut
  527. # pragmas
  528. use strict ;
  529. use warnings ;
  530. ++$| ;
  531. use Carp ;
  532. use Data::Dumper ;
  533. use Digest::HMAC_SHA1 qw( hmac_sha1 ) ;
  534. use Digest::MD5 qw( md5 md5_hex md5_base64 ) ;
  535. use English qw( -no_match_vars ) ;
  536. use Errno qw(EAGAIN EPIPE ECONNRESET) ;
  537. use Fcntl ;
  538. use File::Basename ;
  539. use File::Copy::Recursive ;
  540. use File::Glob qw( :glob ) ;
  541. use File::Path qw( mkpath rmtree ) ;
  542. use File::Spec ;
  543. use File::stat ;
  544. #use Imapsync::Getopt::Long ;
  545. use IO::File ;
  546. use IO::Socket qw(:crlf SOL_SOCKET SO_KEEPALIVE) ;
  547. #use IO::Socket::SSL ;
  548. use IO::Tee ;
  549. use IPC::Open3 'open3' ;
  550. use Mail::IMAPClient 3.30 ;
  551. use MIME::Base64 ;
  552. use POSIX qw(uname SIGALRM) ;
  553. use Term::ReadKey ;
  554. use Test::More ;
  555. use Time::HiRes qw( time sleep ) ;
  556. use Time::Local ;
  557. use Unicode::String ;
  558. use Cwd ;
  559. use Readonly ;
  560. # constants
  561. # Let us do like sysexits.h
  562. # /usr/include/sysexits.h
  563. Readonly my $EX_OK => 0 ; #/* successful termination */
  564. Readonly my $EX_USAGE => 64 ; #/* command line usage error */
  565. #Readonly my $EX_DATAERR => 65 ; #/* data format error */
  566. #Readonly my $EX_NOINPUT => 66 ; #/* cannot open input */
  567. #Readonly my $EX_NOUSER => 67 ; #/* addressee unknown */
  568. #Readonly my $EX_NOHOST => 68 ; #/* host name unknown */
  569. #Readonly my $EX_UNAVAILABLE => 69 ; #/* service unavailable */
  570. Readonly my $EX_SOFTWARE => 70 ; #/* internal software error */
  571. #Readonly my $EX_OSERR => 71 ; #/* system error (e.g., can't fork) */
  572. #Readonly my $EX_OSFILE => 72 ; #/* critical OS file missing */
  573. #Readonly my $EX_CANTCREAT => 73 ; #/* can't create (user) output file */
  574. #Readonly my $EX_IOERR => 74 ; #/* input/output error */
  575. #Readonly my $EX_TEMPFAIL => 75 ; #/* temp failure; user is invited to retry */
  576. #Readonly my $EX_PROTOCOL => 76 ; #/* remote error in protocol */
  577. #Readonly my $EX_NOPERM => 77 ; #/* permission denied */
  578. #Readonly my $EX_CONFIG => 78 ; #/* configuration error */
  579. # Mine
  580. Readonly my $EXIT_BY_SIGNAL => 6 ;
  581. Readonly my $EXIT_PID_FILE_ALREADY_EXIST => 8 ;
  582. Readonly my $EXIT_WITH_ERRORS => 111 ;
  583. Readonly my $EXIT_WITH_ERRORS_MAX => 112 ;
  584. Readonly my $EXIT_UNKNOWN => 126 ;
  585. Readonly my $ERRORS_MAX => 50 ; # exit after 50 errors.
  586. Readonly my $INTERVAL_TO_EXIT => 2 ; # interval max to exit instead of reconnect
  587. Readonly my $SPLIT => 100 ; # By default, 100 at a time, not more.
  588. Readonly my $SPLIT_FACTOR => 10 ; # init_imap() calls Maxcommandlength( $SPLIT_FACTOR * $split )
  589. # which means default Maxcommandlength is 10*100 = 1000 characters ;
  590. Readonly my $IMAP_PORT => 143 ; # Well know port for IMAP
  591. Readonly my $IMAP_SSL_PORT => 993 ; # Well know port for IMAP over SSL
  592. Readonly my $LAST => -1 ;
  593. Readonly my $MINUS_ONE => -1 ;
  594. Readonly my $RELEASE_NUMBER_EXAMPLE_1 => '1.351' ;
  595. Readonly my $RELEASE_NUMBER_EXAMPLE_2 => 42.4242 ;
  596. Readonly my $DEFAULT_TIMEOUT => 120 ;
  597. Readonly my $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND => 3 ;
  598. Readonly my $DEFAULT_UIDNEXT => 999999 ;
  599. Readonly my $DEFAULT_BUFFER_SIZE => 4096 ;
  600. Readonly my $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12 => 3600 ;
  601. Readonly my $PERMISSION_FILTER => 7777 ;
  602. Readonly my $KIBI => 1024 ;
  603. Readonly my $NUMBER_10 => 10 ;
  604. Readonly my $NUMBER_42 => 42 ;
  605. Readonly my $NUMBER_100 => 100 ;
  606. Readonly my $NUMBER_200 => 200 ;
  607. Readonly my $NUMBER_300 => 300 ;
  608. Readonly my $NUMBER_20_000 => 20_000 ;
  609. Readonly my $QUOTA_PERCENT_LIMIT => 90 ;
  610. Readonly my $NUMBER_104857600 => 104857600 ;
  611. Readonly my $SIZE_MAX_STR => 64 ;
  612. Readonly my $NB_SECONDS_IN_A_DAY => 86400 ;
  613. Readonly my $STD_CHAR_PER_LINE => 80 ;
  614. Readonly my $TRUE => 1 ;
  615. Readonly my $FALSE => 0 ;
  616. Readonly my $LAST_RESSORT_SEPARATOR => q{/} ;
  617. # global variables
  618. my(
  619. $sync,
  620. $rcs,
  621. $debug, $debugimap, $debugimap1, $debugimap2, $debugcontent, $debugflags,
  622. $debuglist, $debugdev, $debugmaxlinelength, @debugbasket, $debugcgi,
  623. $host1, $host2, $port1, $port2,
  624. $user1, $user2, $domain1, $domain2,
  625. $password1, $password2, $passfile1, $passfile2,
  626. @folder, @include, @exclude, @folderrec,
  627. @folderfirst, @folderlast,
  628. $prefix1, $prefix2,
  629. $subfolder2,
  630. @regextrans2, @regexmess, @regexflag, @skipmess, @pipemess, $pipemesscheck,
  631. $flagscase, $filterflags, $syncflagsaftercopy,
  632. $sep1, $sep2,
  633. $syncinternaldates,
  634. $idatefromheader,
  635. $syncacls,
  636. $fastio1, $fastio2,
  637. $maxsize, $minsize, $maxage, $minage,
  638. $exitwhenover,
  639. $search, $search1, $search2,
  640. $skipheader, @useheader,
  641. $skipsize, $allowsizemismatch, $foldersizes, $foldersizesatend, $buffersize,
  642. $delete, $delete2, $delete2duplicates,
  643. $expunge, $expunge1, $expunge2, $uidexpunge2, $dry,
  644. $justfoldersizes,
  645. $authmd5, $authmd51, $authmd52,
  646. $subscribed, $subscribe, $subscribeall,
  647. $version, $help,
  648. $justconnect, $justfolders, $justbanner,
  649. $fast,
  650. $total_bytes_transferred,
  651. $total_bytes_skipped,
  652. $total_bytes_error,
  653. $nb_msg_transferred,
  654. $nb_msg_skipped,
  655. $nb_msg_skipped_dry_mode,
  656. $h1_nb_msg_duplicate,
  657. $h2_nb_msg_duplicate,
  658. $h1_nb_msg_noheader,
  659. $h2_nb_msg_noheader,
  660. $h1_total_bytes_duplicate,
  661. $h2_total_bytes_duplicate,
  662. $h1_nb_msg_deleted,
  663. $h2_nb_msg_deleted,
  664. $h1_bytes_processed,
  665. $h1_nb_msg_processed,
  666. $h1_nb_msg_start, $h1_bytes_start,
  667. $h2_nb_msg_start, $h2_bytes_start,
  668. $h1_nb_msg_end, $h1_bytes_end,
  669. $h2_nb_msg_end, $h2_bytes_end,
  670. $timeout,
  671. $timestart_int, $timeend,
  672. $timebefore,
  673. $ssl1, $ssl2,
  674. $ssl1_ssl_version, $ssl2_ssl_version,
  675. $tls1, $tls2,
  676. $uid1, $uid2,
  677. $authuser1, $authuser2,
  678. $proxyauth1, $proxyauth2,
  679. $authmech1, $authmech2,
  680. $split1, $split2,
  681. $reconnectretry1, $reconnectretry2,
  682. $tests, $test_builder, $testsdebug, $testslive,
  683. $justlogin,
  684. $tmpdir,
  685. $releasecheck,
  686. $max_msg_size_in_bytes,
  687. $modulesversion,
  688. $delete2folders, $delete2foldersonly, $delete2foldersbutnot,
  689. $usecache, $debugcache, $cacheaftercopy,
  690. $wholeheaderifneeded, %h1_msgs_copy_by_uid, $useuid, $h2_uidguess,
  691. $addheader,
  692. %h1, %h2,
  693. $checkselectable, $checkmessageexists,
  694. $expungeaftereach,
  695. $abletosearch,
  696. $showpasswords,
  697. $fixslash2,
  698. $messageidnodomain,
  699. $fixInboxINBOX,
  700. $maxlinelength, $maxlinelengthcmd,
  701. $minmaxlinelength,
  702. $uidnext_default,
  703. $fixcolonbug,
  704. $create_folder_old,
  705. $maxmessagespersecond,
  706. $maxbytespersecond,
  707. $skipcrossduplicates, $debugcrossduplicates,
  708. $disarmreadreceipts,
  709. $mixfolders, $skipemptyfolders,
  710. $fetch_hash_set,
  711. );
  712. # main program
  713. # global variables initialisation
  714. $rcs = q{$Id: imapsync,v 1.727 2016/08/19 10:30:36 gilles Exp gilles $} ;
  715. $total_bytes_transferred = 0;
  716. $total_bytes_skipped = 0;
  717. $total_bytes_error = 0;
  718. $nb_msg_transferred = 0;
  719. $nb_msg_skipped = $nb_msg_skipped_dry_mode = 0;
  720. $h1_nb_msg_deleted = $h2_nb_msg_deleted = 0;
  721. $h1_nb_msg_duplicate = $h2_nb_msg_duplicate = 0;
  722. $h1_nb_msg_noheader = $h2_nb_msg_noheader = 0;
  723. $h1_total_bytes_duplicate = $h2_total_bytes_duplicate = 0;
  724. $h1_nb_msg_start = $h1_bytes_start = 0 ;
  725. $h2_nb_msg_start = $h2_bytes_start = 0 ;
  726. $h1_nb_msg_processed = $h1_bytes_processed = 0 ;
  727. #$h1_nb_msg_end = $h1_bytes_end = 0 ;
  728. #$h2_nb_msg_end = $h2_bytes_end = 0 ;
  729. $sync->{nb_errors} = 0;
  730. $max_msg_size_in_bytes = 0;
  731. my %month_abrev = (
  732. Jan => '00',
  733. Feb => '01',
  734. Mar => '02',
  735. Apr => '03',
  736. May => '04',
  737. Jun => '05',
  738. Jul => '06',
  739. Aug => '07',
  740. Sep => '08',
  741. Oct => '09',
  742. Nov => '10',
  743. Dec => '11',
  744. );
  745. # @ARGV will be eat by get_options()
  746. my @argv_copy = @ARGV;
  747. my $cgi_dir = '/var/tmp/imapsync_cgi' ;
  748. # Under CGI environment
  749. if ( $ENV{SERVER_SOFTWARE} ) {
  750. myprint( "\n" ) ;
  751. myprint( "<pre>\n" ) ;
  752. -d $cgi_dir or mkpath $cgi_dir or die "Can not create $cgi_dir: $!\n" ;
  753. chdir $cgi_dir or die "Can not cd to $cgi_dir: $!\n" ;
  754. }
  755. get_options( ) ;
  756. unsetunsafe( ) if ( $ENV{SERVER_SOFTWARE} ) ;
  757. # Under CGI environment
  758. if ( $ENV{SERVER_SOFTWARE} ) {
  759. myprint( 'Current directory is ' . getcwd( ) . "\n" ) ;
  760. myprint( 'Real user id is ' . getpwuid_any_os( $REAL_USER_ID ) . " (uid $REAL_USER_ID)\n" ) ;
  761. myprint( 'Effective user id is ' . getpwuid_any_os( $EFFECTIVE_USER_ID ). " (euid $EFFECTIVE_USER_ID)\n" ) ;
  762. }
  763. local $SIG{ INT } = sub {
  764. my $signame = shift ;
  765. catch_reconnect( $sync, $signame ) ;
  766. } ;
  767. local $SIG{ QUIT } = local $SIG{ TERM } = sub {
  768. my $signame = shift ;
  769. catch_exit( $sync, $signame ) ;
  770. } ;
  771. $sync->{timestart} = $BASETIME ; # Never too let reading books and perlvar
  772. $sync->{log} = defined $sync->{log} ? $sync->{log} : 1 ;
  773. $sync->{errorsdump} = defined $sync->{errorsdump} ? $sync->{errorsdump} : 1 ;
  774. $sync->{errorsmax} = defined $sync->{errorsmax} ? $sync->{errorsmax} : $ERRORS_MAX ;
  775. $sync->{user2} = $user2 ;
  776. if ( $sync->{log} ) {
  777. setlogfile( $sync ) ;
  778. teelaunch( $sync ) ;
  779. }
  780. $timestart_int = int( $sync->{timestart} ) ;
  781. $timebefore = $sync->{timestart} ;
  782. my $timestart_str = localtime( $sync->{timestart} ) ;
  783. myprint( "Transfer started at $timestart_str\n" ) ;
  784. myprint( "PID is $PROCESS_ID\n" ) ;
  785. myprint( "Log file is $sync->{logfile} ( to change it, use --logfile path ; or use --nolog to turn off logging )\n" ) if ( $sync->{log} ) ;
  786. $modulesversion = defined $modulesversion ? $modulesversion : 1 ;
  787. # If you want releasecheck not to be done by default (like the github maintainer),
  788. # then uncomment the first "$releasecheck =" line, the line ending with "0 ;".
  789. # The second line (ending with "1 ;") can stay active or be commented,
  790. # the result will be the same: no releasecheck by default.
  791. $releasecheck = defined $releasecheck ? $releasecheck : 0 ;
  792. #$releasecheck = defined $releasecheck ? $releasecheck : 1 ;
  793. my $warn_release = ( $releasecheck ) ? check_last_release( ) : q{} ;
  794. # default values
  795. $sync->{pidfile} = defined $sync->{pidfile} ? $sync->{pidfile} : $tmpdir . '/imapsync.pid' ;
  796. $sync->{pidfilelocking} = defined $sync->{pidfilelocking} ? $sync->{pidfilelocking} : 0 ;
  797. $wholeheaderifneeded = defined $wholeheaderifneeded ? $wholeheaderifneeded : 1;
  798. # turn on RFC standard flags correction like \SEEN -> \Seen
  799. $flagscase = defined $flagscase ? $flagscase : 1 ;
  800. # Use PERMANENTFLAGS if available
  801. $filterflags = defined $filterflags ? $filterflags : 1 ;
  802. # sync flags just after an APPEND, some servers ignore the flags given in the APPEND
  803. # like MailEnable IMAP server.
  804. # Off by default since it takes time.
  805. $syncflagsaftercopy = defined $syncflagsaftercopy ? $syncflagsaftercopy : 0 ;
  806. # Activate --usecache if --useuid is set and no --nousecache
  807. $usecache = 1 if ( $useuid and ( ! defined $usecache ) ) ;
  808. $cacheaftercopy = 1 if ( $usecache and ( ! defined $cacheaftercopy ) ) ;
  809. $checkselectable = defined $checkselectable ? $checkselectable : 1 ;
  810. $checkmessageexists = defined $checkmessageexists ? $checkmessageexists : 0 ;
  811. $expungeaftereach = defined $expungeaftereach ? $expungeaftereach : 1 ;
  812. $abletosearch = defined $abletosearch ? $abletosearch : 1 ;
  813. $checkmessageexists = 0 if ( not $abletosearch ) ;
  814. $showpasswords = defined $showpasswords ? $showpasswords : 0 ;
  815. $fixslash2 = defined $fixslash2 ? $fixslash2 : 1 ;
  816. $fixInboxINBOX = defined $fixInboxINBOX ? $fixInboxINBOX : 1 ;
  817. $create_folder_old = defined $create_folder_old ? $create_folder_old : 0 ;
  818. $mixfolders = defined $mixfolders ? $mixfolders : 1 ;
  819. $sync->{automap} = defined $sync->{automap} ? $sync->{automap} : 0 ;
  820. $delete2duplicates = 1 if ( $delete2 and ( ! defined $delete2duplicates ) ) ;
  821. $maxmessagespersecond = defined $maxmessagespersecond ? $maxmessagespersecond : 0 ;
  822. $maxbytespersecond = defined $maxbytespersecond ? $maxbytespersecond : 0 ;
  823. myprint( banner_imapsync( @argv_copy ) ) ;
  824. myprint( "Temp directory is $tmpdir ( to change it use --tmpdir dirpath )\n") ;
  825. is_valid_directory( $tmpdir ) || croak "Error creating tmpdir $tmpdir : $!" ;
  826. if ( $sync->{pidfile} ) {
  827. write_pidfile( $sync->{pidfile}, $sync->{pidfilelocking} ) ;
  828. }
  829. $fixcolonbug = defined $fixcolonbug ? $fixcolonbug : 1 ;
  830. if ( $usecache and $fixcolonbug ) { tmpdir_fix_colon_bug( ) } ;
  831. $modulesversion and myprint( "Modules version list:\n", modulesversion(), "( use --no-modulesversion to turn off printing this Perl modules list )\n" ) ;
  832. my $DEFAULT_SSL_VERIFY ;
  833. my %SSL_VERIFY_STR ;
  834. if ( $ssl1 or $ssl2 or $tls1 or $tls2) {
  835. Readonly $DEFAULT_SSL_VERIFY => IO::Socket::SSL::SSL_VERIFY_NONE( ) ;
  836. Readonly %SSL_VERIFY_STR => (
  837. IO::Socket::SSL::SSL_VERIFY_NONE( ) => 'SSL_VERIFY_NONE' ,
  838. IO::Socket::SSL::SSL_VERIFY_PEER( ) => 'SSL_VERIFY_PEER' ,
  839. ) ;
  840. $IO::Socket::SSL::DEBUG = $sync->{debugssl} || 1 ;
  841. myprint( "SSL debug mode level is --debugssl $IO::Socket::SSL::DEBUG (can be set from 0 meaning no debug to 4 meaning max debug)\n" ) ;
  842. }
  843. if ( $ssl1 ) {
  844. myprint( 'Host1: SSL default mode is like --sslargs1 SSL_verify_mode=' . $DEFAULT_SSL_VERIFY . " meaning $SSL_VERIFY_STR{$DEFAULT_SSL_VERIFY} on host1 (do not check the certificate server)\n" ) ;
  845. myprint( 'Host1: Use --sslargs1 SSL_verify_mode=' . IO::Socket::SSL::SSL_VERIFY_PEER( ) . " for $SSL_VERIFY_STR{IO::Socket::SSL::SSL_VERIFY_PEER( )} on host1\n" ) ;
  846. }
  847. if ( $ssl2 ) {
  848. myprint( 'Host2: SSL default mode is like --sslargs2 SSL_verify_mode=' . $DEFAULT_SSL_VERIFY . " meaning $SSL_VERIFY_STR{$DEFAULT_SSL_VERIFY} on host2 (do not check the certificate server)\n" ) ;
  849. myprint( 'Host2: Use --sslargs2 SSL_verify_mode=' . IO::Socket::SSL::SSL_VERIFY_PEER( ) . " for $SSL_VERIFY_STR{IO::Socket::SSL::SSL_VERIFY_PEER( )} on host2\n" ) ;
  850. }
  851. check_lib_version( ) or
  852. croak "imapsync needs perl lib Mail::IMAPClient release 3.30 or superior.\n";
  853. exit_clean( $sync, $EX_OK ) if ( $justbanner ) ;
  854. $split1 ||= $SPLIT ;
  855. $split2 ||= $SPLIT ;
  856. $host1 || missing_option( '--host1' ) ;
  857. $port1 ||= ( $ssl1 ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  858. $host2 || missing_option( '--host2' ) ;
  859. $port2 ||= ( $ssl2 ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  860. $debugimap1 = $debugimap2 = 1 if ( $debugimap ) ;
  861. $debug = 1 if ( $debugimap1 or $debugimap2 ) ;
  862. # By default, don't take size to compare
  863. $skipsize = (defined $skipsize) ? $skipsize : 1;
  864. $uid1 = defined $uid1 ? $uid1 : 1;
  865. $uid2 = defined $uid2 ? $uid2 : 1;
  866. $subscribe = defined $subscribe ? $subscribe : 1;
  867. # Allow size mismatch by default
  868. $allowsizemismatch = defined $allowsizemismatch ? $allowsizemismatch : 1;
  869. $delete2folders = 1
  870. if ( defined $delete2foldersbutnot or defined $delete2foldersonly ) ;
  871. if ( $justconnect ) {
  872. justconnect( ) ;
  873. exit_clean( $sync, $EX_OK ) ;
  874. }
  875. $user1 || missing_option( '--user1' ) ;
  876. $user2 || missing_option( '--user2' ) ;
  877. $syncinternaldates = defined $syncinternaldates ? $syncinternaldates : 1;
  878. # Turn on expunge if there is not explicit option --noexpunge and option
  879. # --delete is given.
  880. # Done because --delete --noexpunge is very dangerous on the second run:
  881. # the Deleted flag is then synced to all previously transfered messages.
  882. # So --delete implies --expunge is a better usability default behaviour.
  883. if ( $delete ) {
  884. if ( ! defined $expunge ) {
  885. myprint( "Info: turning on --expunge1 because --delete --noexpunge1 is very dangerous on the second run.\n" ) ;
  886. $expunge = 1 ;
  887. }
  888. myprint( "Info: if expunging after each message slows down too much the sync then use --noexpungeaftereach to speed up\n" ) ;
  889. }
  890. if ( $uidexpunge2 and not Mail::IMAPClient->can( 'uidexpunge' ) ) {
  891. myprint( "Failure: uidexpunge not supported (IMAPClient release < 3.17), use --expunge2 instead\n" ) ;
  892. exit_clean( $sync, $EX_SOFTWARE ) ;
  893. }
  894. if ( ( $delete2 or $delete2duplicates ) and not defined $uidexpunge2 ) {
  895. if ( Mail::IMAPClient->can( 'uidexpunge' ) ) {
  896. myprint( "Info: will act as --uidexpunge2\n" ) ;
  897. $uidexpunge2 = 1 ;
  898. }elsif ( not defined $expunge2 ) {
  899. myprint( "Info: will act as --expunge2 (no uidexpunge support)\n" ) ;
  900. $expunge2 = 1 ;
  901. }
  902. }
  903. if ( $delete and $delete2 ) {
  904. myprint( "Warning: using --delete and --delete2 together is almost always a bad idea, exiting imapsync\n" ) ;
  905. exit_clean( $sync, $EX_USAGE ) ;
  906. }
  907. if ( $idatefromheader ) {
  908. myprint( 'Turned ON idatefromheader, ',
  909. "will set the internal dates on host2 from the 'Date:' header line.\n" ) ;
  910. $syncinternaldates = 0 ;
  911. }
  912. if ( $syncinternaldates ) {
  913. myprint( 'Info: turned ON syncinternaldates, ',
  914. "will set the internal dates (arrival dates) on host2 same as host1.\n" ) ;
  915. }else{
  916. myprint( "Info: turned OFF syncinternaldates\n" ) ;
  917. }
  918. if ( defined $authmd5 and $authmd5 ) {
  919. $authmd51 = 1 ;
  920. $authmd52 = 1 ;
  921. }
  922. if ( defined $authmd51 and $authmd51 ) {
  923. $authmech1 ||= 'CRAM-MD5';
  924. }
  925. else{
  926. $authmech1 ||= $authuser1 ? 'PLAIN' : 'LOGIN';
  927. }
  928. if ( defined $authmd52 and $authmd52 ) {
  929. $authmech2 ||= 'CRAM-MD5';
  930. }
  931. else{
  932. $authmech2 ||= $authuser2 ? 'PLAIN' : 'LOGIN';
  933. }
  934. $authmech1 = uc $authmech1;
  935. $authmech2 = uc $authmech2;
  936. if (defined $proxyauth1 && !$authuser1) {
  937. missing_option( 'With --proxyauth1, --authuser1' ) ;
  938. }
  939. if (defined $proxyauth2 && !$authuser2) {
  940. missing_option( 'With --proxyauth2, --authuser2' ) ;
  941. }
  942. $authuser1 ||= $user1;
  943. $authuser2 ||= $user2;
  944. myprint( "Host1: will try to use $authmech1 authentication on host1\n") ;
  945. myprint( "Host2: will try to use $authmech2 authentication on host2\n") ;
  946. $timeout = defined $timeout ? $timeout : $DEFAULT_TIMEOUT ;
  947. $sync->{h1}->{timeout} = defined $sync->{h1}->{timeout} ? $sync->{h1}->{timeout} : $timeout ;
  948. myprint( "Host1: imap connexion timeout is $sync->{h1}->{timeout} seconds\n") ;
  949. $sync->{h2}->{timeout} = defined $sync->{h2}->{timeout} ? $sync->{h2}->{timeout} : $timeout ;
  950. myprint( "Host2: imap connexion timeout is $sync->{h2}->{timeout} seconds\n" ) ;
  951. $syncacls = defined $syncacls ? $syncacls : 0 ;
  952. # No folders sizes if --justfolders, unless really wanted.
  953. if ( $justfolders and not defined $foldersizes ) { $foldersizes = 0 ; }
  954. $foldersizes = ( defined $foldersizes ) ? $foldersizes : 1 ;
  955. $foldersizesatend = ( defined $foldersizesatend ) ? $foldersizesatend : $foldersizes ;
  956. $fastio1 = defined $fastio1 ? $fastio1 : 0 ;
  957. $fastio2 = defined $fastio2 ? $fastio2 : 0 ;
  958. $reconnectretry1 = defined $reconnectretry1 ? $reconnectretry1 : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  959. $reconnectretry2 = defined $reconnectretry2 ? $reconnectretry2 : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  960. # Since select_msgs() returns no messages when uidnext does not return something
  961. # then $uidnext_default is never used. So I have to remove it.
  962. $uidnext_default = $DEFAULT_UIDNEXT ;
  963. @useheader = qw( Message-Id Received ) unless ( @useheader ) ;
  964. my %useheader ;
  965. # Make a hash %useheader of each --useheader 'key' in uppercase
  966. for ( @useheader ) { $useheader{ uc $_ } = undef } ;
  967. #myprint( Data::Dumper->Dump( [ \%useheader ] ) ) ;
  968. #exit ;
  969. myprint( "Host1: IMAP server [$host1] port [$port1] user [$user1]\n" ) ;
  970. myprint( "Host2: IMAP server [$host2] port [$port2] user [$user2]\n" ) ;
  971. $password1 || $passfile1 || 'PREAUTH' eq $authmech1 || 'EXTERNAL' eq $authmech1 || do {
  972. myprint( << 'FIN_PASSFILE' ) ;
  973. If you are afraid of giving password on the command line arguments, you can put the
  974. password of user1 in a file named file1 and use "--passfile1 file1" instead of typing it.
  975. Then give this file restrictive permissions with the command "chmod 600 file1".
  976. FIN_PASSFILE
  977. $password1 = ask_for_password( $authuser1 || $user1, $host1 ) ;
  978. } ;
  979. $password1 = ( defined $passfile1 ) ? firstline ( $passfile1 ) : $password1 ;
  980. $password2 || $passfile2 || 'PREAUTH' eq $authmech2 || 'EXTERNAL' eq $authmech2 || do {
  981. myprint( << 'FIN_PASSFILE' ) ;
  982. If you are afraid of giving password on the command line arguments, you can put the
  983. password of user2 in a file named file2 and use "--passfile2 file2" instead of typing it.
  984. Then give this file restrictive permissions with the command "chmod 600 file2".
  985. FIN_PASSFILE
  986. $password2 = ask_for_password( $authuser2 || $user2, $host2 ) ;
  987. } ;
  988. $password2 = ( defined $passfile2 ) ? firstline ( $passfile2 ) : $password2 ;
  989. # need clean up => write methods dry() and dry_message()
  990. $sync->{dry} = $dry ;
  991. my $dry_message = q{} ;
  992. if( $sync->{dry} ) {
  993. $dry_message = "\t(not really since --dry mode)" ;
  994. }
  995. $sync->{dry_message} = $dry_message ;
  996. $search1 ||= $search if ( $search ) ;
  997. $search2 ||= $search if ( $search ) ;
  998. if ( $disarmreadreceipts ) {
  999. push @regexmess, q{s{\A((?:[^\n]+\r\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims} ;
  1000. }
  1001. $pipemesscheck = ( defined $pipemesscheck ) ? $pipemesscheck : 1 ;
  1002. if ( @pipemess and $pipemesscheck ) {
  1003. myprint( 'Checking each --pipemess command, '
  1004. . join( q{, }, @pipemess )
  1005. . ", with an space string. ( Can avoid this check with --nopipemesscheck )\n" ) ;
  1006. my $string = pipemess( q{ }, @pipemess ) ;
  1007. # string undef means something was bad.
  1008. if ( not ( defined $string ) ) {
  1009. die_clean( "Error: one of --pipemess command is bad, check it\n" ) ;
  1010. }
  1011. myprint( "Ok with each --pipemess @pipemess\n" ) ;
  1012. }
  1013. if ( $maxlinelengthcmd ) {
  1014. myprint( "Checking --maxlinelengthcmd command, $maxlinelengthcmd, with an space string.\n" ) ;
  1015. my $string = pipemess( q{ }, $maxlinelengthcmd ) ;
  1016. # string undef means something was bad.
  1017. if ( not ( defined $string ) ) {
  1018. die_clean( "Error: --maxlinelengthcmd command is bad, check it\n" ) ;
  1019. }
  1020. myprint( "Ok with --maxlinelengthcmd $maxlinelengthcmd\n" ) ;
  1021. }
  1022. if ( @regexmess ) {
  1023. my $string = regexmess( q{ } ) ;
  1024. myprint( "Checking each --regexmess command with an space string.\n" ) ;
  1025. # string undef means one of the eval regex was bad.
  1026. if ( not ( defined $string ) ) {
  1027. die_clean( 'Error: one of --regexmess option is bad, check it' ) ;
  1028. }
  1029. myprint( "Ok with each --regexmess\n" ) ;
  1030. }
  1031. if ( @skipmess ) {
  1032. myprint( "Checking each --skipmess command with an space string.\n" ) ;
  1033. my $match = skipmess( q{ } ) ;
  1034. # match undef means one of the eval regex was bad.
  1035. if ( not ( defined $match ) ) {
  1036. die_clean( 'Error: one of --skipmess option is bad, check it' ) ;
  1037. }
  1038. myprint( "Ok with each --skipmess\n" ) ;
  1039. }
  1040. if ( @regexflag ) {
  1041. myprint( "Checking each --regexflag command with an space string.\n" ) ;
  1042. my $string = flags_regex( q{ } ) ;
  1043. # string undef means one of the eval regex was bad.
  1044. if ( not ( defined $string ) ) {
  1045. die_clean( 'Error: one of --regexflag option is bad, check it' ) ;
  1046. }
  1047. myprint( "Ok with each --regexflag\n" ) ;
  1048. }
  1049. $sync->{imap1} = my $imap1 = login_imap($host1, $port1, $user1, $domain1, $password1,
  1050. $debugimap1, $sync->{h1}->{timeout}, $fastio1, $ssl1, $tls1,
  1051. $authmech1, $authuser1, $reconnectretry1,
  1052. $proxyauth1, $uid1, $split1, 'Host1', $sync->{h1} ) ;
  1053. $sync->{imap2} = my $imap2 = login_imap($host2, $port2, $user2, $domain2, $password2,
  1054. $debugimap2, $sync->{h2}->{timeout}, $fastio2, $ssl2, $tls2,
  1055. $authmech2, $authuser2, $reconnectretry2,
  1056. $proxyauth2, $uid2, $split2, 'Host2', $sync->{h2} ) ;
  1057. $debug and myprint( 'Host1 Buffer I/O: ', $imap1->Buffer(), "\n" ) ;
  1058. $debug and myprint( 'Host2 Buffer I/O: ', $imap2->Buffer(), "\n" ) ;
  1059. die_clean( 'Not authenticated on host1' ) unless $imap1->IsAuthenticated( ) ;
  1060. myprint( "Host1: state Authenticated\n" ) ;
  1061. die_clean( 'Not authenticated on host2' ) unless $imap2->IsAuthenticated( ) ;
  1062. myprint( "Host2: state Authenticated\n" ) ;
  1063. myprint( 'Host1 capability: ', join(q{ }, @{ $imap1->capability_update() || [] }), "\n" ) ;
  1064. myprint( 'Host2 capability: ', join(q{ }, @{ $imap2->capability_update() || [] }), "\n" ) ;
  1065. imap_id_stuff( $sync ) ;
  1066. #quota( $imap1, 'host1' ) ; # quota on host1 is useless and pollute host2 output.
  1067. quota( $imap2, 'host2', $sync ) ;
  1068. if ( $justlogin ) {
  1069. $imap1->logout( ) ;
  1070. $imap2->logout( ) ;
  1071. exit_clean( $sync, $EX_OK ) ;
  1072. }
  1073. #
  1074. # Folder stuff
  1075. #
  1076. my (
  1077. @h1_folders_all , %h1_folders_all , @h1_folders_wanted , %requested_folder ,
  1078. %h1_subscribed_folder , %h2_subscribed_folder ,
  1079. @h2_folders_all , %h2_folders_all , %h2_folders_all_UPPER ,
  1080. @h2_folders_from_1_wanted , %h2_folders_from_1_wanted ,
  1081. %h2_folders_from_1_several ,
  1082. %h2_folders_from_1_all ,
  1083. ) ;
  1084. my $h1_folders_wanted_nb = 0 ;
  1085. my $h1_folders_wanted_ct = 0 ; # counter of folders done.
  1086. # All folders on host1 and host2
  1087. @h1_folders_all = sort $imap1->folders( ) ;
  1088. @h2_folders_all = sort $imap2->folders( ) ;
  1089. myprint( 'Host1: found ', scalar @h1_folders_all , " folders.\n" ) ;
  1090. myprint( 'Host2: found ', scalar @h2_folders_all , " folders.\n" ) ;
  1091. for ( @h1_folders_all ) { $h1_folders_all{ $_ } = 1 } ;
  1092. for ( @h2_folders_all ) {
  1093. $h2_folders_all{ $_ } = 1 ;
  1094. $h2_folders_all_UPPER{ uc $_ } = 1 ;
  1095. } ;
  1096. $sync->{h1_folders_all} = \%h1_folders_all ;
  1097. $sync->{h2_folders_all} = \%h2_folders_all ;
  1098. $sync->{h2_folders_all_UPPER} = \%h2_folders_all_UPPER ;
  1099. # Make a hash of subscribed folders in both servers.
  1100. for ( $imap1->subscribed( ) ) { $h1_subscribed_folder{ $_ } = 1 } ;
  1101. for ( $imap2->subscribed( ) ) { $h2_subscribed_folder{ $_ } = 1 } ;
  1102. if ( defined $subfolder2 ) {
  1103. unshift @regextrans2,
  1104. q's,^${h2_prefix}(.*),${h2_prefix}${subfolder2}${h2_sep}$1,',
  1105. q's,^INBOX$,${h2_prefix}${subfolder2}${h2_sep}INBOX,' ;
  1106. }
  1107. if ( $fixInboxINBOX and ( my $reg = fix_Inbox_INBOX_mapping( \%h1_folders_all, \%h2_folders_all ) ) ) {
  1108. push @regextrans2, $reg ;
  1109. }
  1110. if (scalar @folder or $subscribed or scalar @folderrec) {
  1111. # folders given by option --folder
  1112. if (scalar @folder) {
  1113. add_to_requested_folders(@folder);
  1114. }
  1115. # option --subscribed
  1116. if ( $subscribed ) {
  1117. add_to_requested_folders( keys %h1_subscribed_folder ) ;
  1118. }
  1119. # option --folderrec
  1120. if (scalar @folderrec) {
  1121. foreach my $folderrec (@folderrec) {
  1122. add_to_requested_folders($imap1->folders($folderrec));
  1123. }
  1124. }
  1125. }
  1126. else {
  1127. # no include, no folder/subscribed/folderrec options => all folders
  1128. if (not scalar @include) {
  1129. myprint( "Including all folders found by default. Use --subscribed or --folder or --folderrec or --include to select specific folders. Use --exclude to unselect specific folders.\n" ) ;
  1130. add_to_requested_folders(@h1_folders_all);
  1131. }
  1132. }
  1133. # consider (optional) includes and excludes
  1134. if ( scalar @include ) {
  1135. foreach my $include ( @include ) {
  1136. my @included_folders = grep { /$include/ } @h1_folders_all ;
  1137. add_to_requested_folders( @included_folders ) ;
  1138. myprint( "Including folders matching pattern $include\n" . jux_utf8_list( @included_folders ) . "\n" ) ;
  1139. }
  1140. }
  1141. if ( scalar @exclude ) {
  1142. foreach my $exclude ( @exclude ) {
  1143. my @requested_folder = sort keys %requested_folder ;
  1144. my @excluded_folders = grep { /$exclude/ } @requested_folder ;
  1145. remove_from_requested_folders( @excluded_folders ) ;
  1146. myprint( "Excluding folders matching pattern $exclude\n" . jux_utf8_list( @excluded_folders ) . "\n" ) ;
  1147. }
  1148. }
  1149. # sort before is not very powerful
  1150. # it adds --folderfirst and --folderlast even if they don't exist on host1
  1151. @h1_folders_wanted = sort_requested_folders( ) ;
  1152. # Remove no selectable folders
  1153. my @h1_folders_wanted_exist ;
  1154. myprint( "Host1: checking all wanted folders exist.\n" ) ;
  1155. foreach my $folder ( @h1_folders_wanted ) {
  1156. ( $debug or $sync->{debugfolders} ) and myprint( "Checking $folder exists on host1\n" ) ;
  1157. if ( ! exists $h1_folders_all{ $folder } ) {
  1158. myprint( "Host1: warning! ignoring folder $folder because it is not in host1 whole folders list.\n" ) ;
  1159. next ;
  1160. }else{
  1161. push @h1_folders_wanted_exist, $folder ;
  1162. }
  1163. }
  1164. @h1_folders_wanted = @h1_folders_wanted_exist ;
  1165. $checkselectable and do {
  1166. my @h1_folders_wanted_selectable ;
  1167. myprint( "Host1: checking all wanted folders are selectable. Use --nocheckselectable to avoid this check.\n" ) ;
  1168. foreach my $folder ( @h1_folders_wanted ) {
  1169. ( $debug or $sync->{debugfolders} ) and myprint( "Checking $folder is selectable on host1\n" ) ;
  1170. if ( ! $imap1->selectable( $folder ) ) {
  1171. myprint( "Host1: warning! ignoring folder $folder because it is not selectable\n" ) ;
  1172. }else{
  1173. push @h1_folders_wanted_selectable, $folder ;
  1174. }
  1175. }
  1176. @h1_folders_wanted = @h1_folders_wanted_selectable ;
  1177. ( $debug or $sync->{debugfolders} ) and myprint( 'Host1: checking folders took ', timenext( ), " s\n" ) ;
  1178. } ;
  1179. $sync->{h1_folders_wanted} = \@h1_folders_wanted ;
  1180. my( $h1_sep, $h2_sep ) ;
  1181. # what are the private folders separators for each server ?
  1182. ( $debug or $sync->{debugfolders} ) and myprint( "Getting separators\n" ) ;
  1183. $h1_sep = get_separator( $imap1, $sep1, '--sep1', 'Host1', \@h1_folders_all ) ;
  1184. $h2_sep = get_separator( $imap2, $sep2, '--sep2', 'Host2', \@h2_folders_all ) ;
  1185. my( $h1_prefix, $h2_prefix ) ;
  1186. $sync->{ h1_prefix } = $h1_prefix = get_prefix( $imap1, $prefix1, '--prefix1', 'Host1', \@h1_folders_all ) ;
  1187. $sync->{ h2_prefix } = $h2_prefix = get_prefix( $imap2, $prefix2, '--prefix2', 'Host2', \@h2_folders_all ) ;
  1188. myprint( "Host1 separator and prefix: [$h1_sep][$h1_prefix]\n" ) ;
  1189. myprint( "Host2 separator and prefix: [$h2_sep][$h2_prefix]\n" ) ;
  1190. automap( $sync ) ;
  1191. foreach my $h1_fold ( @h1_folders_wanted ) {
  1192. my $h2_fold ;
  1193. $h2_fold = imap2_folder_name( $h1_fold ) ;
  1194. $h2_folders_from_1_wanted{ $h2_fold }++ ;
  1195. if ( 1 < $h2_folders_from_1_wanted{ $h2_fold } ) {
  1196. $h2_folders_from_1_several{ $h2_fold }++ ;
  1197. }
  1198. }
  1199. @h2_folders_from_1_wanted = sort keys %h2_folders_from_1_wanted;
  1200. foreach my $h1_fold ( @h1_folders_all ) {
  1201. my $h2_fold ;
  1202. $h2_fold = imap2_folder_name( $h1_fold ) ;
  1203. $h2_folders_from_1_all{ $h2_fold }++ ;
  1204. }
  1205. myprint( << 'END_LISTING' ) ;
  1206. ++++ Listing folders
  1207. All foldernames are presented between brackets like [X] where X is the foldername.
  1208. When a foldername contains non-ASCII characters it is presented in the form
  1209. [X] = [Y] where
  1210. X is the imap foldername you have to use in command line options and
  1211. Y is the uft8 output just printed for convenience, to recognize it.
  1212. END_LISTING
  1213. print
  1214. "Host1 folders list:\n",
  1215. jux_utf8_list( @h1_folders_all ),
  1216. "\n",
  1217. "Host2 folders list:\n",
  1218. jux_utf8_list( @h2_folders_all ),
  1219. "\n" ;
  1220. print
  1221. 'Host1 subscribed folders list: ',
  1222. jux_utf8_list( sort keys %h1_subscribed_folder ), "\n"
  1223. if ( $subscribed ) ;
  1224. my @h2_folders_not_in_1;
  1225. @h2_folders_not_in_1 = list_folders_in_2_not_in_1( ) ;
  1226. if ( @h2_folders_not_in_1 ) {
  1227. myprint( "Folders in host2 not in host1:\n",
  1228. jux_utf8_list( @h2_folders_not_in_1 ), "\n" ) ;
  1229. }
  1230. if ( defined $sync->{f1f2auto} ) {
  1231. myprint( "Folders mapping from --automap feature (use --f1f2 to override any mapping):\n" ) ;
  1232. foreach my $h1_fold ( keys %{$sync->{f1f2auto}} ) {
  1233. my $h2_fold = $sync->{f1f2auto}{$h1_fold} ;
  1234. myprintf( "%-40s -> %-40s\n",
  1235. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1236. }
  1237. myprint( "\n" ) ;
  1238. }
  1239. if ( defined $sync->{f1f2} ) {
  1240. myprint( "Folders mapping from --f1f2 options, it overrides --automap:\n" ) ;
  1241. foreach my $h1_fold ( keys %{$sync->{f1f2}} ) {
  1242. my $h2_fold = $sync->{f1f2}{$h1_fold} ;
  1243. my $warn = q{} ;
  1244. if ( not exists $h1_folders_all{ $h1_fold } ) {
  1245. $warn = "BUT $h1_fold does NOT exist on host1!" ;
  1246. }
  1247. myprintf( "%-40s -> %-40s %s\n",
  1248. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ), $warn ) ;
  1249. }
  1250. myprint( "\n" ) ;
  1251. }
  1252. exit_clean( $sync, $EX_OK ) if ( $sync->{justfolderlists} ) ;
  1253. exit_clean( $sync, $EX_OK ) if ( $sync->{justautomap} ) ;
  1254. debugsleep( $sync ) ;
  1255. if ( $foldersizes ) {
  1256. foldersizes_on_h1h2( ) ;
  1257. }
  1258. exit_clean( $sync, $EX_OK ) if ( $justfoldersizes ) ;
  1259. $sync->{stats} = 1 ;
  1260. if ( $sync->{'delete1emptyfolders'} ) {
  1261. delete1emptyfolders( $sync ) ;
  1262. }
  1263. delete_folders_in_2_not_in_1( ) if $delete2folders ;
  1264. # folder loop
  1265. $h1_folders_wanted_nb = scalar @h1_folders_wanted ;
  1266. myprint( "++++ Looping on each one of $h1_folders_wanted_nb folders to sync\n" ) ;
  1267. my $begin_transfer_time = time ;
  1268. my %uid_candidate_for_deletion ;
  1269. my %uid_candidate_no_deletion ;
  1270. my %h2_folders_of_md5 = ( ) ;
  1271. FOLDER: foreach my $h1_fold ( @h1_folders_wanted ) {
  1272. last FOLDER if $imap1->IsUnconnected( ) ;
  1273. last FOLDER if $imap2->IsUnconnected( ) ;
  1274. my $h2_fold = imap2_folder_name( $h1_fold ) ;
  1275. $h1_folders_wanted_ct++ ;
  1276. myprintf( "Folder %7s %-35s -> %-35s\n", "$h1_folders_wanted_ct/$h1_folders_wanted_nb",
  1277. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1278. if ( $sync->{debugmemory} ) {
  1279. myprintf("FL: Memory consumption: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI) ;
  1280. }
  1281. # host1 can not be fetched read only, select is needed because of expunge.
  1282. select_folder( $imap1, $h1_fold, 'Host1' ) or next FOLDER ;
  1283. debugsleep( $sync ) ;
  1284. my $h1_fold_nb_messages = count_from_select( $imap1->History ) ;
  1285. myprint( "Host1 folder [$h1_fold] has $h1_fold_nb_messages messages in total (mentioned by SELECT)\n" ) ;
  1286. if ( $skipemptyfolders and 0 == $h1_fold_nb_messages ) {
  1287. myprint( "Skipping empty host1 folder [$h1_fold]\n" ) ;
  1288. next FOLDER ;
  1289. }
  1290. if ( ! exists $h2_folders_all{ $h2_fold } ) {
  1291. create_folder( $imap2, $h2_fold, $h1_fold ) or next FOLDER ;
  1292. }
  1293. acls_sync( $h1_fold, $h2_fold ) ;
  1294. # Sometimes the folder on host2 is listed (it exists) but is
  1295. # not selectable but becomes selectable by a create (Gmail)
  1296. select_folder( $imap2, $h2_fold, 'Host2' )
  1297. or ( create_folder( $imap2, $h2_fold, $h1_fold )
  1298. and select_folder( $imap2, $h2_fold, 'Host2' ) )
  1299. or next FOLDER ;
  1300. my @select_results = $imap2->Results( ) ;
  1301. my $h2_fold_nb_messages = count_from_select( @select_results ) ;
  1302. myprint( "Host2 folder [$h2_fold] has $h2_fold_nb_messages messages in total (mentioned by SELECT)\n" ) ;
  1303. my $permanentflags2 = permanentflags( @select_results ) ;
  1304. ( $debug or $debugflags ) and myprint( "Host2 folder [$h2_fold] permanentflags: $permanentflags2\n" ) ;
  1305. if ( $expunge or $expunge1 ){
  1306. myprint( "Host1: Expunging $h1_fold $dry_message\n" ) ;
  1307. unless( $dry ) { $imap1->expunge( ) } ;
  1308. }
  1309. if ( ( ( $subscribe and exists $h1_subscribed_folder{ $h1_fold } ) or $subscribeall )
  1310. and not exists $h2_subscribed_folder{ $h2_fold } ) {
  1311. myprint( "Host2: Subscribing to folder $h2_fold\n" ) ;
  1312. unless( $dry ) { $imap2->subscribe( $h2_fold ) } ;
  1313. }
  1314. next FOLDER if ( $justfolders ) ;
  1315. last FOLDER if $imap1->IsUnconnected( ) ;
  1316. last FOLDER if $imap2->IsUnconnected( ) ;
  1317. my $h1_msgs_all_hash_ref = { } ;
  1318. my @h1_msgs = select_msgs( $imap1, $h1_msgs_all_hash_ref, $search1, $h1_fold );
  1319. last FOLDER if $imap1->IsUnconnected( ) ;
  1320. my $h1_msgs_nb = scalar @h1_msgs ;
  1321. $h1{ $h1_fold }{ 'messages_nb' } = $h1_msgs_nb ;
  1322. myprint( "Host1 folder [$h1_fold] considering $h1_msgs_nb messages\n" ) ;
  1323. ( $debug or $debuglist ) and myprint( "Host1 folder [$h1_fold] considering $h1_msgs_nb messages, LIST gives: @h1_msgs\n" ) ;
  1324. $debug and myprint( "Host1 selecting messages of folder [$h1_fold] took ", timenext(), " s\n" ) ;
  1325. my $h2_msgs_all_hash_ref = { } ;
  1326. my @h2_msgs = select_msgs( $imap2, $h2_msgs_all_hash_ref, $search2, $h2_fold ) ;
  1327. last FOLDER if $imap2->IsUnconnected( ) ;
  1328. my $h2_msgs_nb = scalar @h2_msgs ;
  1329. $h2{ $h2_fold }{ 'messages_nb' } = $h2_msgs_nb ;
  1330. myprint( "Host2 folder [$h2_fold] considering $h2_msgs_nb messages\n" ) ;
  1331. ( $debug or $debuglist ) and myprint( "Host2 folder [$h2_fold] considering $h2_msgs_nb messages, LIST gives: @h2_msgs\n" ) ;
  1332. $debug and myprint( "Host2 selecting messages of folder [$h2_fold] took ", timenext(), " s\n" ) ;
  1333. my $cache_base = "$tmpdir/imapsync_cache/" ;
  1334. my $cache_dir = cache_folder( $cache_base, "$host1/$user1/$host2/$user2", $h1_fold, $h2_fold ) ;
  1335. my ( $cache_1_2_ref, $cache_2_1_ref ) = ( {}, {} ) ;
  1336. my $h1_uidvalidity = $imap1->uidvalidity( ) || q{} ;
  1337. my $h2_uidvalidity = $imap2->uidvalidity( ) || q{} ;
  1338. last FOLDER if $imap1->IsUnconnected( ) ;
  1339. last FOLDER if $imap2->IsUnconnected( ) ;
  1340. if ( $usecache ) {
  1341. myprint( "cache directory: $cache_dir\n" ) ;
  1342. mkpath( "$cache_dir" ) ;
  1343. ( $cache_1_2_ref, $cache_2_1_ref )
  1344. = get_cache( $cache_dir, \@h1_msgs, \@h2_msgs, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  1345. myprint( 'CACHE h1 h2: ', scalar keys %{ $cache_1_2_ref } , " files\n" ) ;
  1346. $debug and myprint( '[',
  1347. map ( { "$_->$cache_1_2_ref->{$_} " } keys %{ $cache_1_2_ref } ), " ]\n" ) ;
  1348. }
  1349. my %h1_hash = () ;
  1350. my %h2_hash = () ;
  1351. my ( %h1_msgs, %h2_msgs ) ;
  1352. @h1_msgs{ @h1_msgs } = ();
  1353. @h2_msgs{ @h2_msgs } = ();
  1354. my @h1_msgs_in_cache = sort { $a <=> $b } keys %{ $cache_1_2_ref } ;
  1355. my @h2_msgs_in_cache = keys %{ $cache_2_1_ref } ;
  1356. my ( %h1_msgs_not_in_cache, %h2_msgs_not_in_cache ) ;
  1357. %h1_msgs_not_in_cache = %h1_msgs ;
  1358. %h2_msgs_not_in_cache = %h2_msgs ;
  1359. delete @h1_msgs_not_in_cache{ @h1_msgs_in_cache } ;
  1360. delete @h2_msgs_not_in_cache{ @h2_msgs_in_cache } ;
  1361. my @h1_msgs_not_in_cache = keys %h1_msgs_not_in_cache ;
  1362. #myprint( "h1_msgs_not_in_cache: [@h1_msgs_not_in_cache]\n" ) ;
  1363. my @h2_msgs_not_in_cache = keys %h2_msgs_not_in_cache ;
  1364. my @h2_msgs_delete2_not_in_cache = () ;
  1365. %h1_msgs_copy_by_uid = ( ) ;
  1366. if ( $useuid ) {
  1367. # use uid so we have to avoid getting header
  1368. @h1_msgs_copy_by_uid{ @h1_msgs_not_in_cache } = ( ) ;
  1369. @h2_msgs_delete2_not_in_cache = @h2_msgs_not_in_cache if $usecache ;
  1370. @h1_msgs_not_in_cache = ( ) ;
  1371. @h2_msgs_not_in_cache = ( ) ;
  1372. #myprint( "delete2: @h2_msgs_delete2_not_in_cache\n" ) ;
  1373. }
  1374. $debug and myprint( "Host1 parsing headers of folder [$h1_fold]\n" ) ;
  1375. my ($h1_heads_ref, $h1_fir_ref) = ({}, {});
  1376. $h1_heads_ref = $imap1->parse_headers([@h1_msgs_not_in_cache], @useheader) if (@h1_msgs_not_in_cache);
  1377. $debug and myprint( "Host1 parsing headers of folder [$h1_fold] took ", timenext(), " s\n" ) ;
  1378. @{ $h1_fir_ref }{@h1_msgs} = ( undef ) ;
  1379. $debug and myprint( "Host1 getting flags idate and sizes of folder [$h1_fold]\n" ) ;
  1380. if ( $abletosearch ) {
  1381. $h1_fir_ref = $imap1->fetch_hash( \@h1_msgs, 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE', $h1_fir_ref )
  1382. if ( @h1_msgs ) ;
  1383. }else{
  1384. my $uidnext = $imap1->uidnext( $h1_fold ) || $uidnext_default ;
  1385. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  1386. $h1_fir_ref = $imap1->fetch_hash( $fetch_hash_uids, 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE', $h1_fir_ref )
  1387. if ( @h1_msgs ) ;
  1388. }
  1389. $debug and myprint( "Host1 getting flags idate and sizes of folder [$h1_fold] took ", timenext(), " s\n" ) ;
  1390. unless ($h1_fir_ref) {
  1391. my $error = join( q{}, "Host1 folder $h1_fold: Could not fetch_hash ",
  1392. scalar @h1_msgs, ' msgs: ', $imap1->LastError || q{}, "\n" ) ;
  1393. errors_incr( $sync, $error ) ;
  1394. next FOLDER ;
  1395. }
  1396. my @h1_msgs_duplicate;
  1397. foreach my $m (@h1_msgs_not_in_cache) {
  1398. my $rc = parse_header_msg($imap1, $m, $h1_heads_ref, $h1_fir_ref, 'Host1', \%h1_hash);
  1399. if (! defined $rc) {
  1400. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1401. myprint( "Host1 $h1_fold/$m size $h1_size ignored (no wanted headers so we ignore this message. To solve this: use --addheader)\n" ) ;
  1402. $total_bytes_skipped += $h1_size;
  1403. $nb_msg_skipped += 1;
  1404. $h1_nb_msg_noheader +=1;
  1405. $h1_nb_msg_processed +=1 ;
  1406. } elsif(0 == $rc) {
  1407. # duplicate
  1408. push @h1_msgs_duplicate, $m;
  1409. # duplicate, same id same size?
  1410. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1411. $nb_msg_skipped += 1;
  1412. $h1_total_bytes_duplicate += $h1_size;
  1413. $h1_nb_msg_duplicate += 1;
  1414. $h1_nb_msg_processed +=1 ;
  1415. }
  1416. }
  1417. my $h1_msgs_duplicate_nb = scalar @h1_msgs_duplicate ;
  1418. $h1{ $h1_fold }{ 'duplicates_nb' } = $h1_msgs_duplicate_nb ;
  1419. $debug and myprint( "Host1 selected: $h1_msgs_nb duplicates: $h1_msgs_duplicate_nb\n" ) ;
  1420. $debug and myprint( 'Host1 whole time parsing headers took ', timenext(), " s\n" ) ;
  1421. $debug and myprint( "Host2 parsing headers of folder [$h2_fold]\n" ) ;
  1422. my ($h2_heads_ref, $h2_fir_ref) = ( {}, {} );
  1423. $h2_heads_ref = $imap2->parse_headers([@h2_msgs_not_in_cache], @useheader) if (@h2_msgs_not_in_cache);
  1424. $debug and myprint( "Host2 parsing headers of folder [$h2_fold] took ", timenext(), " s\n" ) ;
  1425. $debug and myprint( "Host2 getting flags idate and sizes of folder [$h2_fold]\n" ) ;
  1426. @{ $h2_fir_ref }{@h2_msgs} = ( ); # fetch_hash can select by uid with last arg as ref
  1427. if ( $abletosearch ) {
  1428. $h2_fir_ref = $imap2->fetch_hash( \@h2_msgs, 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE', $h2_fir_ref)
  1429. if (@h2_msgs) ;
  1430. }else{
  1431. my $uidnext = $imap2->uidnext( $h2_fold ) || $uidnext_default ;
  1432. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  1433. $h2_fir_ref = $imap2->fetch_hash( $fetch_hash_uids, 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE', $h2_fir_ref )
  1434. if ( @h2_msgs ) ;
  1435. }
  1436. $debug and myprint( "Host2 getting flags idate and sizes of folder [$h2_fold] took ", timenext(), " s\n" ) ;
  1437. my @h2_msgs_duplicate;
  1438. foreach my $m (@h2_msgs_not_in_cache) {
  1439. my $rc = parse_header_msg($imap2, $m, $h2_heads_ref, $h2_fir_ref, 'Host2', \%h2_hash) ;
  1440. my $h2_size = $h2_fir_ref->{$m}->{'RFC822.SIZE'} || 0 ;
  1441. if (! defined $rc ) {
  1442. myprint( "Host2 $h2_fold/$m size $h2_size ignored (no wanted headers so we ignore this message)\n" ) ;
  1443. $h2_nb_msg_noheader += 1 ;
  1444. } elsif( 0 == $rc ) {
  1445. # duplicate
  1446. $h2_nb_msg_duplicate += 1 ;
  1447. $h2_total_bytes_duplicate += $h2_size ;
  1448. push @h2_msgs_duplicate, $m ;
  1449. }
  1450. }
  1451. # %h2_folders_of_md5
  1452. foreach my $md5 ( keys %h2_hash ) {
  1453. $h2_folders_of_md5{ $md5 }->{ $h2_fold } ++ ;
  1454. }
  1455. my $h2_msgs_duplicate_nb = scalar @h2_msgs_duplicate ;
  1456. $h2{ $h2_fold }{ 'duplicates_nb' } = $h2_msgs_duplicate_nb ;
  1457. myprint( "Host2 folder $h2_fold selected: $h2_msgs_nb messages, duplicates: $h2_msgs_duplicate_nb\n" )
  1458. if ( $debug or $delete2duplicates or $h2_msgs_duplicate_nb ) ;
  1459. $debug and myprint( 'Host2 whole time parsing headers took ', timenext( ), " s\n" ) ;
  1460. $debug and myprint( "++++ Verifying [$h1_fold] -> [$h2_fold]\n" ) ;
  1461. # messages in host1 that are not in host2
  1462. my @h1_hash_keys_sorted_by_uid
  1463. = sort {$h1_hash{$a}{'m'} <=> $h1_hash{$b}{'m'}} keys %h1_hash;
  1464. #myprint( map { $h1_hash{$_}{'m'} . q{ }} @h1_hash_keys_sorted_by_uid ) ;
  1465. my @h2_hash_keys_sorted_by_uid
  1466. = sort {$h2_hash{$a}{'m'} <=> $h2_hash{$b}{'m'}} keys %h2_hash;
  1467. if( $delete2duplicates and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  1468. my @h2_expunge ;
  1469. foreach my $h2_msg ( @h2_msgs_duplicate ) {
  1470. myprint( "msg $h2_fold/$h2_msg marked \\Deleted [duplicate] on host2 $dry_message\n" ) ;
  1471. push @h2_expunge, $h2_msg if $uidexpunge2 ;
  1472. unless ( $dry ) {
  1473. $imap2->delete_message( $h2_msg ) ;
  1474. $h2_nb_msg_deleted += 1 ;
  1475. }
  1476. }
  1477. my $cnt = scalar @h2_expunge ;
  1478. if( @h2_expunge and not $expunge2 ) {
  1479. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $dry_message\n" ) ;
  1480. $imap2->uidexpunge( \@h2_expunge ) if ! $dry ;
  1481. }
  1482. if ( $expunge2 ){
  1483. myprint( "Host2: Expunging folder $h2_fold $dry_message\n" ) ;
  1484. $imap2->expunge( ) if ! $dry ;
  1485. }
  1486. }
  1487. if( $delete2 and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  1488. # No host1 folders f1a f1b ... going all to same f2 (via --regextrans2)
  1489. my @h2_expunge;
  1490. foreach my $m_id (@h2_hash_keys_sorted_by_uid) {
  1491. #myprint( "$m_id " ) ;
  1492. unless (exists $h1_hash{$m_id}) {
  1493. my $h2_msg = $h2_hash{$m_id}{'m'};
  1494. my $h2_flags = $h2_hash{$m_id}{'F'} || q{};
  1495. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0;
  1496. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted on host2 [$m_id] $dry_message\n" )
  1497. if ! $isdel;
  1498. push @h2_expunge, $h2_msg if $uidexpunge2;
  1499. unless ($dry or $isdel) {
  1500. $imap2->delete_message($h2_msg);
  1501. $h2_nb_msg_deleted += 1;
  1502. }
  1503. }
  1504. }
  1505. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  1506. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted [not in cache] on host2 $dry_message\n" ) ;
  1507. push @h2_expunge, $h2_msg if $uidexpunge2;
  1508. unless ($dry) {
  1509. $imap2->delete_message($h2_msg);
  1510. $h2_nb_msg_deleted += 1;
  1511. }
  1512. }
  1513. my $cnt = scalar @h2_expunge ;
  1514. if( @h2_expunge and not $expunge2 ) {
  1515. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $dry_message\n" ) ;
  1516. $imap2->uidexpunge( \@h2_expunge ) if ! $dry ;
  1517. }
  1518. if ( $expunge2 ) {
  1519. myprint( "Host2: Expunging folder $h2_fold $dry_message\n" ) ;
  1520. $imap2->expunge( ) if ! $dry ;
  1521. }
  1522. }
  1523. if( $delete2 and exists $h2_folders_from_1_several{ $h2_fold } ) {
  1524. myprint( "Host2 folder $h2_fold $h2_folders_from_1_several{ $h2_fold } folders left to sync there\n" ) ;
  1525. my @h2_expunge;
  1526. foreach my $m_id ( @h2_hash_keys_sorted_by_uid ) {
  1527. my $h2_msg = $h2_hash{ $m_id }{ 'm' } ;
  1528. unless ( exists $h1_hash{ $m_id } ) {
  1529. my $h2_flags = $h2_hash{ $m_id }{ 'F' } || q{} ;
  1530. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0 ;
  1531. unless ( $isdel ) {
  1532. $debug and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [$m_id]\n" ) ;
  1533. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  1534. }
  1535. }else{
  1536. $debug and myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [$m_id]\n" ) ;
  1537. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1538. }
  1539. }
  1540. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  1541. myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [not in cache]\n" ) ;
  1542. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  1543. }
  1544. foreach my $h2_msg ( @h2_msgs_in_cache ) {
  1545. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [in cache]\n" ) ;
  1546. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1547. }
  1548. if ( 0 == $h2_folders_from_1_several{ $h2_fold } ) {
  1549. # last host1 folder going to $h2_fold
  1550. myprint( "Last host1 folder going to $h2_fold\n" ) ;
  1551. foreach my $h2_msg ( keys %{ $uid_candidate_for_deletion{ $h2_fold } } ) {
  1552. $debug and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion\n" ) ;
  1553. if ( exists $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg } ) {
  1554. $debug and myprint( "Host2: msg $h2_fold/$h2_msg canceled deletion\n" ) ;
  1555. }else{
  1556. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted $dry_message\n" ) ;
  1557. push @h2_expunge, $h2_msg if $uidexpunge2 ;
  1558. unless ( $dry ) {
  1559. $imap2->delete_message( $h2_msg ) ;
  1560. $h2_nb_msg_deleted += 1 ;
  1561. }
  1562. }
  1563. }
  1564. }
  1565. my $cnt = scalar @h2_expunge ;
  1566. if( @h2_expunge and not $expunge2 ) {
  1567. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $dry_message\n" ) ;
  1568. $imap2->uidexpunge( \@h2_expunge ) if ! $dry ;
  1569. }
  1570. if ( $expunge2 ) {
  1571. myprint( "Host2: Expunging host2 folder $h2_fold $dry_message\n" ) ;
  1572. $imap2->expunge( ) if ! $dry ;
  1573. }
  1574. $h2_folders_from_1_several{ $h2_fold }-- ;
  1575. }
  1576. my $h2_uidnext = $imap2->uidnext( $h2_fold ) ;
  1577. $debug and myprint( "Host2 uidnext: $h2_uidnext\n" ) ;
  1578. $h2_uidguess = $h2_uidnext ;
  1579. MESS: foreach my $m_id (@h1_hash_keys_sorted_by_uid) {
  1580. last FOLDER if $imap1->IsUnconnected( ) ;
  1581. last FOLDER if $imap2->IsUnconnected( ) ;
  1582. #myprint( "h1_nb_msg_processed: $h1_nb_msg_processed\n" ) ;
  1583. my $h1_size = $h1_hash{$m_id}{'s'};
  1584. my $h1_msg = $h1_hash{$m_id}{'m'};
  1585. my $h1_idate = $h1_hash{$m_id}{'D'};
  1586. if ( ( not exists $h2_hash{ $m_id } )
  1587. and ( not ( exists $h2_folders_of_md5{ $m_id } )
  1588. or not $skipcrossduplicates ) ) {
  1589. # copy
  1590. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  1591. $h2_folders_of_md5{ $m_id }->{ $h2_fold } ++ ;
  1592. if( $delete2 and ( exists $h2_folders_from_1_several{ $h2_fold } ) and $h2_msg ) {
  1593. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  1594. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1595. }
  1596. last FOLDER if total_bytes_max_reached( ) ;
  1597. next MESS;
  1598. }
  1599. else{
  1600. # already on host2
  1601. if ( exists $h2_hash{ $m_id } ) {
  1602. my $h2_msg = $h2_hash{$m_id}{'m'} ;
  1603. $debug and myprint( "Host1 found msg $h1_fold/$h1_msg equals Host2 $h2_fold/$h2_msg\n" ) ;
  1604. if ( $usecache ) {
  1605. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$h2_msg\n" ) ;
  1606. touch( "$cache_dir/${h1_msg}_$h2_msg" )
  1607. or croak( "Couldn't touch $cache_dir/${h1_msg}_$h2_msg" ) ;
  1608. }
  1609. }elsif( exists $h2_folders_of_md5{ $m_id } ) {
  1610. my @folders_dup = keys %{ $h2_folders_of_md5{ $m_id } } ;
  1611. ( $debug or $debugcrossduplicates ) and myprint( "Host1 found msg $h1_fold/$h1_msg is also in Host2 folders @folders_dup\n" ) ;
  1612. }
  1613. $total_bytes_skipped += $h1_size ;
  1614. $nb_msg_skipped += 1 ;
  1615. $h1_nb_msg_processed +=1 ;
  1616. }
  1617. if ( exists $h2_hash{ $m_id } ) {
  1618. #$debug and myprint( "MESSAGE $m_id\n" ) ;
  1619. my $h2_msg = $h2_hash{$m_id}{'m'};
  1620. sync_flags_fir( $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  1621. # Good
  1622. my $h2_size = $h2_hash{$m_id}{'s'};
  1623. $debug and myprint(
  1624. "Host1 size msg $h1_fold/$h1_msg = $h1_size <> $h2_size = Host2 $h2_fold/$h2_msg\n" ) ;
  1625. }
  1626. last FOLDER if $imap2->IsUnconnected( ) ;
  1627. if ( $delete ) {
  1628. delete_message_on_host1( $h1_msg, $h1_fold ) ;
  1629. }
  1630. }
  1631. # END MESS: loop
  1632. last FOLDER if $imap1->IsUnconnected( ) ;
  1633. last FOLDER if $imap2->IsUnconnected( ) ;
  1634. MESS_IN_CACHE: foreach my $h1_msg ( @h1_msgs_in_cache ) {
  1635. my $h2_msg = $cache_1_2_ref->{ $h1_msg } ;
  1636. $debugcache and myprint( "cache messages update flags $h1_msg->$h2_msg\n" ) ;
  1637. sync_flags_fir( $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  1638. my $h1_size = $h1_fir_ref->{ $h1_msg }->{ 'RFC822.SIZE' } || 0 ;
  1639. $total_bytes_skipped += $h1_size;
  1640. $nb_msg_skipped += 1;
  1641. $h1_nb_msg_processed +=1 ;
  1642. last FOLDER if $imap2->IsUnconnected( ) ;
  1643. }
  1644. #myprint( "Messages by uid: ", map { "$_ " } keys %h1_msgs_copy_by_uid, "\n" ) ;
  1645. MESS_BY_UID: foreach my $h1_msg ( sort { $a <=> $b } keys %h1_msgs_copy_by_uid ) {
  1646. #
  1647. $debug and myprint( "Copy by uid $h1_fold/$h1_msg\n" ) ;
  1648. last FOLDER if $imap1->IsUnconnected( ) ;
  1649. last FOLDER if $imap2->IsUnconnected( ) ;
  1650. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  1651. if( $delete2 and exists $h2_folders_from_1_several{ $h2_fold } and $h2_msg ) {
  1652. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  1653. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1654. }
  1655. last FOLDER if total_bytes_max_reached( ) ;
  1656. }
  1657. if ( $expunge or $expunge1 ){
  1658. myprint( "Host1: Expunging folder $h1_fold $dry_message\n" ) ;
  1659. unless( $dry ) { $imap1->expunge( ) } ;
  1660. }
  1661. if ( $expunge2 ){
  1662. myprint( "Host2: Expunging folder $h2_fold $dry_message\n" ) ;
  1663. unless( $dry ) { $imap2->expunge( ) } ;
  1664. }
  1665. $debug and myprint( 'Time: ', timenext( ), " s\n" ) ;
  1666. }
  1667. sub total_bytes_max_reached {
  1668. return( 0 ) if not $exitwhenover ;
  1669. if ( $total_bytes_transferred >= $exitwhenover ) {
  1670. myprint( "Maximum bytes transferred reached, $total_bytes_transferred >= $exitwhenover, ending sync\n" ) ;
  1671. return( 1 ) ;
  1672. }
  1673. }
  1674. myprint( "++++ End looping on each folder\n" ) ;
  1675. ( $debug or $sync->{debugfolders} ) and myprint( 'Time: ', timenext( ), " s\n" ) ;
  1676. if ( $foldersizesatend ) {
  1677. myprint( << 'END_SIZE' ) ;
  1678. Folders sizes after the synchronization.
  1679. You can remove this foldersizes listing by using "--nofoldersizesatend"
  1680. END_SIZE
  1681. foldersizesatend( ) ;
  1682. }
  1683. $imap1->logout( ) unless lost_connection( $imap1, "for host1 [$host1]" ) ;
  1684. $imap2->logout( ) unless lost_connection( $imap2, "for host2 [$host2]" ) ;
  1685. stats( $sync ) ;
  1686. myprint( errorsdump( $sync->{nb_errors}, errors_log( $sync ) ) ) if ( $sync->{errorsdump} ) ;
  1687. tests_live_result( $sync->{nb_errors} ) if ( $testslive ) ;
  1688. exit_clean( $sync, $EXIT_WITH_ERRORS ) if ( $sync->{nb_errors} ) ;
  1689. exit_clean( $sync, $EX_OK ) ;
  1690. # END of main program
  1691. # subroutines
  1692. sub myprint { return print @ARG ; }
  1693. sub myprintf { return printf @ARG ; }
  1694. sub mysprintf {
  1695. my( $format, @list ) = @ARG ;
  1696. return sprintf $format, @list ;
  1697. }
  1698. sub unsetunsafe {
  1699. # Remove all content in unsafe evalued options
  1700. @regextrans2 = ( ) ;
  1701. @regexflag = ( ) ;
  1702. @regexmess = ( ) ;
  1703. @skipmess = ( ) ;
  1704. @pipemess = ( ) ;
  1705. $delete2foldersonly = undef ;
  1706. $delete2foldersbutnot = undef ;
  1707. return ;
  1708. }
  1709. sub debugsleep {
  1710. my $mysync = shift ;
  1711. if ( defined $mysync->{debugsleep} ) {
  1712. myprint( "Info: sleeping $mysync->{debugsleep}s\n" ) ;
  1713. sleep $mysync->{debugsleep} ;
  1714. }
  1715. return ;
  1716. }
  1717. sub foldersizes_on_h1h2 {
  1718. myprint( << 'END_SIZE' ) ;
  1719. Folders sizes before the synchronization.
  1720. You can remove foldersizes listings by using "--nofoldersizes" and "--nofoldersizesatend"
  1721. but then you will also loose the ETA (Estimation Time of Arrival) given after each message copy.
  1722. END_SIZE
  1723. ( $h1_nb_msg_start, $h1_bytes_start ) = foldersizes( 'Host1', $imap1, $search1, @h1_folders_wanted ) ;
  1724. ( $h2_nb_msg_start, $h2_bytes_start ) = foldersizes( 'Host2', $imap2, $search2, @h2_folders_from_1_wanted ) ;
  1725. if ( not all_defined( $h1_nb_msg_start, $h1_bytes_start, $h2_nb_msg_start, $h2_bytes_start ) ) {
  1726. my $error = "Failure getting foldersizes, ETA and final diff will not be displayed\n" ;
  1727. errors_incr( $sync, $error ) ;
  1728. $foldersizes = 0 ;
  1729. $foldersizesatend = 0 ;
  1730. return ;
  1731. }
  1732. my $h2_bytes_limit = $sync->{host2}->{quota_limit_bytes} || 0 ;
  1733. if ( $h2_bytes_limit and ( $h2_bytes_limit < $h1_bytes_start ) ) {
  1734. my $quota_percent = mysprintf( '%.0f', $h1_bytes_start/$h2_bytes_limit ) ;
  1735. my $error = "Host2: Quota limit will be exceeded! Over $quota_percent % ( $h1_bytes_start bytes / $h2_bytes_limit bytes )\n" ;
  1736. errors_incr( $sync, $error ) ;
  1737. }
  1738. return ;
  1739. }
  1740. sub all_defined {
  1741. if ( not @ARG ) {
  1742. return 0 ;
  1743. }
  1744. foreach my $elem ( @ARG ) {
  1745. if ( not defined $elem ) {
  1746. return 0 ;
  1747. }
  1748. }
  1749. return 1 ;
  1750. }
  1751. sub tests_all_defined {
  1752. is( 0, all_defined( ), 'all_defined: no param => 0' ) ;
  1753. is( 0, all_defined( () ), 'all_defined: void list => 0' ) ;
  1754. is( 0, all_defined( undef ), 'all_defined: undef => 0' ) ;
  1755. is( 0, all_defined( undef, undef ), 'all_defined: undef => 0' ) ;
  1756. is( 0, all_defined( 1, undef ), 'all_defined: 1 undef => 0' ) ;
  1757. is( 0, all_defined( undef, 1 ), 'all_defined: undef 1 => 0' ) ;
  1758. is( 1, all_defined( 1, 1 ), 'all_defined: 1 1 => 1' ) ;
  1759. is( 1, all_defined( (1, 1) ), 'all_defined: (1 1) => 1' ) ;
  1760. return ;
  1761. }
  1762. sub imap_id_stuff {
  1763. my $sync = shift ;
  1764. if ( not $sync->{id} ) { return ; } ;
  1765. $sync->{h1_imap_id} = imap_id( $sync->{imap1}, 'Host1' ) ;
  1766. #myprint( 'Host1: ' . $sync->{h1_imap_id} ) ;
  1767. $sync->{h2_imap_id} = imap_id( $sync->{imap2}, 'Host2' ) ;
  1768. #myprint( 'Host2: ' . $sync->{h2_imap_id} ) ;
  1769. return ;
  1770. }
  1771. sub imap_id {
  1772. my ( $imap, $Side ) = @_ ;
  1773. $Side ||= q{} ;
  1774. my $imap_id_response = q{} ;
  1775. if ( not $imap->has_capability( 'ID' ) ) {
  1776. $imap_id_response = 'No ID capability' ;
  1777. myprint( "$Side: No ID capability\n" ) ;
  1778. }else{
  1779. my $id_inp = imapsync_id( { side => lc $Side } ) ;
  1780. myprint( "\n$Side: found ID capability. Sending/receiving ID, presented in raw IMAP for now.\n"
  1781. . "In order to avoid sending/receiving ID, use option --noid\n" ) ;
  1782. my $debug_before = $imap->Debug( ) ;
  1783. $imap->Debug( 1 ) ;
  1784. my $id_out = $imap->tag_and_run( 'ID ' . $id_inp ) ;
  1785. #my $id_out = $imap->tag_and_run( 'ID NIL' ) ;
  1786. myprint( "\n" ) ;
  1787. $imap->Debug( $debug_before ) ;
  1788. #$imap_id_response = Data::Dumper->Dump( [ $id_out ], [ 'IMAP_ID' ] ) ;
  1789. }
  1790. return( $imap_id_response ) ;
  1791. }
  1792. sub imapsync_id {
  1793. my $overhashref = shift ;
  1794. # See http://tools.ietf.org/html/rfc2971.html
  1795. my $imapsync_id = { } ;
  1796. my $imapsync_id_lamiral = {
  1797. name => 'imapsync',
  1798. version => imapsync_version( ),
  1799. os => $OSNAME,
  1800. vendor => 'Gilles LAMIRAL',
  1801. 'support-url' => 'http://imapsync.lamiral.info/',
  1802. # Example of date-time: 19-Sep-2015 08:56:07
  1803. date => date_from_rcs( q{$Date: 2016/08/19 10:30:36 $ } ),
  1804. } ;
  1805. my $imapsync_id_github = {
  1806. name => 'imapsync',
  1807. version => imapsync_version( ),
  1808. os => $OSNAME,
  1809. vendor => 'github',
  1810. 'support-url' => 'https://github.com/imapsync/imapsync',
  1811. date => date_from_rcs( q{$Date: 2016/08/19 10:30:36 $ } ),
  1812. } ;
  1813. $imapsync_id = $imapsync_id_lamiral ;
  1814. #$imapsync_id = $imapsync_id_github ;
  1815. my %mix = ( %{ $imapsync_id }, %{ $overhashref } ) ;
  1816. my $imapsync_id_str = format_for_imap_arg( \%mix ) ;
  1817. #myprint( "$imapsync_id_str\n" ) ;
  1818. return( $imapsync_id_str ) ;
  1819. }
  1820. sub tests_imapsync_id {
  1821. ok( '("name" "imapsync" "version" "111" "os" "beurk" "vendor" "Gilles LAMIRAL" "support-url" "http://imapsync.lamiral.info/" "date" "22-12-1968" "side" "host1")'
  1822. eq imapsync_id( {
  1823. version => 111,
  1824. os => 'beurk',
  1825. date => '22-12-1968',
  1826. side => 'host1' } ),
  1827. 'tests_imapsync_id override' ) ;
  1828. return ;
  1829. }
  1830. sub format_for_imap_arg {
  1831. my $ref = shift ;
  1832. my $string = q{} ;
  1833. my %terms = %{ $ref } ;
  1834. my @terms = ( ) ;
  1835. if ( not ( %terms ) ) { return( 'NIL' ) } ;
  1836. # sort like in RFC then add extra key/values
  1837. foreach my $key ( qw( name version os os-version vendor support-url address date command arguments environment) ) {
  1838. if ( $terms{ $key } ) {
  1839. push @terms, $key, $terms{ $key } ;
  1840. delete $terms{ $key } ;
  1841. }
  1842. }
  1843. push @terms, %terms ;
  1844. $string = '(' . ( join q{ }, map { '"' . $_ . '"' } @terms ) . ')' ;
  1845. return( $string ) ;
  1846. }
  1847. sub tests_format_for_imap_arg {
  1848. ok( 'NIL' eq format_for_imap_arg( { } ), 'format_for_imap_arg empty hash ref' ) ;
  1849. ok( '("name" "toto")' eq format_for_imap_arg( { name => 'toto' } ), 'format_for_imap_arg { name => toto }' ) ;
  1850. ok( '("name" "toto" "key" "val")' eq format_for_imap_arg( { name => 'toto', key => 'val' } ), 'format_for_imap_arg 2 x key val' ) ;
  1851. return ;
  1852. }
  1853. sub quota {
  1854. my ( $imap, $side, $sync ) = @_ ;
  1855. my $Side = ucfirst $side ;
  1856. my $debug_before = $imap->Debug( ) ;
  1857. $imap->Debug( 1 ) ;
  1858. if ( not $imap->has_capability( 'QUOTA' ) ) {
  1859. $imap->Debug( $debug_before ) ;
  1860. return ;
  1861. } ;
  1862. myprint( "\n$Side: found quota, presented in raw IMAP\n" ) ;
  1863. my $getquotaroot = $imap->getquotaroot( 'INBOX' ) ;
  1864. # Gmail INBOX quotaroot is "" but with it Mail::IMAPClient does a literal GETQUOTA {2} \n ""
  1865. #$imap->quota( 'ROOT' ) ;
  1866. #$imap->quota( '""' ) ;
  1867. myprint( "\n" ) ;
  1868. $imap->Debug( $debug_before ) ;
  1869. my $quota_limit_bytes = quota_extract_storage_limit_in_bytes( $getquotaroot ) ;
  1870. my $quota_current_bytes = quota_extract_storage_current_in_bytes( $getquotaroot ) ;
  1871. $sync->{$side}->{quota_limit_bytes} = $quota_limit_bytes ;
  1872. $sync->{$side}->{quota_current_bytes} = $quota_current_bytes ;
  1873. my $quota_percent ;
  1874. if ( $quota_limit_bytes > 0 ) {
  1875. $quota_percent = mysprintf( '%.2f', $NUMBER_100 * $quota_current_bytes / $quota_limit_bytes ) ;
  1876. }else{
  1877. $quota_percent = 0 ;
  1878. }
  1879. myprint( "$Side: Quota current storage is $quota_current_bytes bytes. Limit is $quota_limit_bytes bytes. So $quota_percent % full\n" ) ;
  1880. if ( $QUOTA_PERCENT_LIMIT < $quota_percent ) {
  1881. my $error = "$Side: $quota_percent % full: it is time to find a bigger place! ( $quota_current_bytes bytes / $quota_limit_bytes bytes )\n" ;
  1882. errors_incr( $sync, $error ) ;
  1883. }
  1884. return ;
  1885. }
  1886. sub tests_quota_extract_storage_limit_in_bytes {
  1887. my $imap_output = [
  1888. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  1889. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  1890. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  1891. '5 OK Getquotaroot completed.'
  1892. ] ;
  1893. ok( $NUMBER_104857600 * $KIBI == quota_extract_storage_limit_in_bytes( $imap_output ), 'quota_extract_storage_limit_in_bytes ') ;
  1894. return ;
  1895. }
  1896. sub quota_extract_storage_limit_in_bytes {
  1897. my $imap_output = shift ;
  1898. my $limit_kb ;
  1899. $limit_kb = ( map { /.*\(\s*STORAGE\s+\d+\s+(\d+)\s*\)/ ? $1 : () } @{ $imap_output } )[0] ;
  1900. $limit_kb ||= 0 ;
  1901. $debug and myprint( "storage_limit_kb = $limit_kb\n" ) ;
  1902. return( $KIBI * $limit_kb ) ;
  1903. }
  1904. sub tests_quota_extract_storage_current_in_bytes {
  1905. my $imap_output = [
  1906. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  1907. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  1908. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  1909. '5 OK Getquotaroot completed.'
  1910. ] ;
  1911. ok( 1*$KIBI == quota_extract_storage_current_in_bytes( $imap_output ), 'quota_extract_storage_current_in_bytes: 1 => 1024 ') ;
  1912. return ;
  1913. }
  1914. sub quota_extract_storage_current_in_bytes {
  1915. my $imap_output = shift ;
  1916. my $current_kb ;
  1917. $current_kb = ( map { /.*\(\s*STORAGE\s+(\d+)\s+\d+\s*\)/ ? $1 : () } @{ $imap_output } )[0] ;
  1918. $current_kb ||= 0 ;
  1919. $debug and myprint( "storage_current_kb = $current_kb\n" ) ;
  1920. return( $KIBI * $current_kb ) ;
  1921. }
  1922. sub automap {
  1923. my ( $sync ) = @_ ;
  1924. if ( $sync->{automap} ) {
  1925. myprint( "Turned on automapping folders ( use --noautomap to turn off automapping )\n" ) ;
  1926. }else{
  1927. myprint( "Turned off automapping folders ( use --automap to turn on automapping )\n" ) ;
  1928. return ;
  1929. }
  1930. $sync->{h1_special} = special_from_folders_hash( $sync->{imap1}, 'Host1' ) ;
  1931. $sync->{h2_special} = special_from_folders_hash( $sync->{imap2}, 'Host2' ) ;
  1932. build_possible_special( $sync ) ;
  1933. build_guess_special( $sync ) ;
  1934. build_automap( $sync ) ;
  1935. return ;
  1936. }
  1937. sub build_guess_special {
  1938. my ( $sync ) = shift ;
  1939. foreach my $h1_fold ( sort keys %{ $sync->{h1_folders_all} } ) {
  1940. my $special = guess_special( $h1_fold, $sync->{possible_special}, $sync->{h1_prefix} ) ;
  1941. if ( $special ) {
  1942. $sync->{h1_special_guessed}{$h1_fold} = $special ;
  1943. my $already_guessed = $sync->{h1_special_guessed}{$special} ;
  1944. if ( $already_guessed ) {
  1945. myprint( "Host1: $h1_fold not $special because set to $already_guessed\n" ) ;
  1946. }else{
  1947. $sync->{h1_special_guessed}{$special} = $h1_fold ;
  1948. }
  1949. }
  1950. }
  1951. foreach my $h2_fold ( sort keys %{ $sync->{h2_folders_all} } ) {
  1952. my $special = guess_special( $h2_fold, $sync->{possible_special}, $sync->{h2_prefix} ) ;
  1953. if ( $special ) {
  1954. $sync->{h2_special_guessed}{$h2_fold} = $special ;
  1955. my $already_guessed = $sync->{h2_special_guessed}{$special} ;
  1956. if ( $already_guessed ) {
  1957. myprint( "Host2: $h2_fold not $special because set to $already_guessed\n" ) ;
  1958. }else{
  1959. $sync->{h2_special_guessed}{$special} = $h2_fold ;
  1960. }
  1961. }
  1962. }
  1963. return ;
  1964. }
  1965. sub guess_special {
  1966. my( $folder, $possible_special_ref, $prefix ) = @_ ;
  1967. my $folder_no_prefix = $folder ;
  1968. $folder_no_prefix =~ s/${prefix}// ;
  1969. #$debug and myprint( "folder_no_prefix: $folder_no_prefix\n" ) ;
  1970. my $guess_special = $possible_special_ref->{ $folder }
  1971. || $possible_special_ref->{ $folder_no_prefix }
  1972. || q{} ;
  1973. return( $guess_special ) ;
  1974. }
  1975. sub tests_guess_special {
  1976. my $possible_special_ref = build_possible_special( my $sync ) ;
  1977. ok( '\Sent' eq guess_special( 'Sent', $possible_special_ref, q{} ) ,'guess_special: Sent => \Sent' ) ;
  1978. ok( q{} eq guess_special( 'Blabla', $possible_special_ref, q{} ) ,'guess_special: Blabla => q{}' ) ;
  1979. ok( '\Sent' eq guess_special( 'INBOX.Sent', $possible_special_ref, 'INBOX.' ) ,'guess_special: INBOX.Sent => \Sent' ) ;
  1980. return ;
  1981. }
  1982. sub build_automap {
  1983. my ( $sync ) = @_ ;
  1984. foreach my $h1_fold ( @{ $sync->{h1_folders_wanted} } ) {
  1985. my $h2_fold ;
  1986. my $h1_special = $sync->{h1_special}{$h1_fold} ;
  1987. my $h1_special_guessed = $sync->{h1_special_guessed}{$h1_fold} ;
  1988. # Case 1: special on both sides.
  1989. if ( $h1_special
  1990. and exists $sync->{h2_special}{$h1_special} ) {
  1991. $h2_fold = $sync->{h2_special}{$h1_special} ;
  1992. $sync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  1993. next ;
  1994. }
  1995. # Case 2: special on host1, not on host2
  1996. if ( $h1_special
  1997. and ( not exists $sync->{h2_special}{$h1_special} )
  1998. and ( exists $sync->{h2_special_guessed}{$h1_special} )
  1999. ) {
  2000. # special_guessed on host2
  2001. $h2_fold = $sync->{h2_special_guessed}{$h1_special} ;
  2002. $sync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  2003. next ;
  2004. }
  2005. # Case 3: no special on host1, special on host2
  2006. if ( ( not $h1_special )
  2007. and ( $h1_special_guessed )
  2008. and ( exists $sync->{h2_special}{$h1_special_guessed} )
  2009. ) {
  2010. $h2_fold = $sync->{h2_special}{$h1_special_guessed} ;
  2011. $sync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  2012. next ;
  2013. }
  2014. # Case 4: no special on both sides.
  2015. if ( ( not $h1_special )
  2016. and ( $h1_special_guessed )
  2017. and ( not exists $sync->{h2_special}{$h1_special_guessed} )
  2018. and ( exists $sync->{h2_special_guessed}{$h1_special_guessed} )
  2019. ) {
  2020. $h2_fold = $sync->{h2_special_guessed}{$h1_special_guessed} ;
  2021. $sync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  2022. next ;
  2023. }
  2024. }
  2025. return( $sync->{f1f2auto} ) ;
  2026. }
  2027. # I willll probably add what there is at:
  2028. # http://stackoverflow.com/questions/2185391/localized-gmail-imap-folders/2185548#2185548
  2029. sub build_possible_special {
  2030. my $sync = shift ;
  2031. my $possible_special = { } ;
  2032. # All|Archive|Drafts|Flagged|Junk|Sent|Trash
  2033. $possible_special->{'\All'} = [ 'All', 'All Messages', '&BBIEQQQ1-' ] ;
  2034. $possible_special->{'\Archive'} = [ 'Archive', 'Archives', '&BBAEQARFBDgEMg-' ] ;
  2035. $possible_special->{'\Drafts'} = [ 'Drafts', '&BCcENQRABD0EPgQyBDgEOgQ4-' ] ;
  2036. $possible_special->{'\Flagged'} = [ 'Flagged', 'Starred', '&BB8EPgQ8BDUERwQ1BD0EPQRLBDU-' ] ;
  2037. $possible_special->{'\Junk'} = [ 'Junk', 'Spam', '&BCEEPwQwBDw-' ] ;
  2038. $possible_special->{'\Sent'} = [ 'Sent', 'Sent Messages', 'Sent Items',
  2039. 'Gesendete Elemente', 'Gesendete Objekte',
  2040. '&AMk-l&AOk-ments envoy&AOk-s', 'Envoy&AOk-',
  2041. 'Elementos enviados',
  2042. '&kAFP4W4IMH8wojCkMMYw4A-',
  2043. '&BB4EQgQ,BEAEMAQyBDsENQQ9BD0ESwQ1-'] ;
  2044. $possible_special->{'\Trash'} = [ 'Trash', '&BCMENAQwBDsENQQ9BD0ESwQ1-', '&BBoEPgRABDcEOAQ9BDA-' ] ;
  2045. foreach my $special ( qw( \All \Archive \Drafts \Flagged \Junk \Sent \Trash ) ){
  2046. foreach my $possible_folder ( @{ $possible_special->{$special} } ) {
  2047. $possible_special->{ $possible_folder } = $special ;
  2048. } ;
  2049. }
  2050. $sync->{possible_special} = $possible_special ;
  2051. $debug and myprint( Data::Dumper->Dump( [ $possible_special ], [ 'possible_special' ] ) ) ;
  2052. return( $possible_special ) ;
  2053. }
  2054. sub special_from_folders_hash {
  2055. my ( $imap, $side ) = @_ ;
  2056. my %special = ( ) ;
  2057. if ( not( Mail::IMAPClient->can( 'folders_hash' ) ) ) {
  2058. my $error = "$side: To have automagic rfc6154 folder mapping, upgrade Mail::IMAPClient >= 3.34\n" ;
  2059. errors_incr( $sync, $error ) ;
  2060. return( \%special ) ; # empty hash ref
  2061. }
  2062. my $folders_hash = $imap->folders_hash( ) ;
  2063. foreach my $fhash (@{ $folders_hash } ) {
  2064. my @special = grep { /\\(?:All|Archive|Drafts|Flagged|Junk|Sent|Trash)/ } @{ $fhash->{attrs} } ;
  2065. if ( @special ) {
  2066. my $special = $special[0] ; # keep first one. Could be not very good.
  2067. if ( exists $special{ $special } ) {
  2068. myprintf( "%s: special %-20s = %s already asigned to %s\n",
  2069. $side, $fhash->{name}, join( q{ }, @special ), $special{ $special } ) ;
  2070. }else{
  2071. myprintf( "%s: special %-20s = %s\n",
  2072. $side, $fhash->{name}, join( q{ }, @special ) ) ;
  2073. $special{ $special } = $fhash->{name} ;
  2074. $special{ $fhash->{name} } = $special ; # double entry value => key
  2075. }
  2076. }
  2077. }
  2078. myprint( "\n" ) if ( %special ) ;
  2079. return( \%special ) ;
  2080. }
  2081. sub errors_incr {
  2082. my ( $mysync, @error ) = @ARG ;
  2083. $sync->{nb_errors}++ ;
  2084. if ( @error ) {
  2085. errors_log( $mysync, @error ) ;
  2086. myprint( @error ) ;
  2087. }
  2088. $mysync->{errorsmax} ||= $ERRORS_MAX ;
  2089. if ( $sync->{nb_errors} >= $mysync->{errorsmax} ) {
  2090. myprint( "Maximum number of errors $mysync->{errorsmax} reached ( you can change $mysync->{errorsmax} to 100 with --errorsmax 100 ). Exiting.\n" ) ;
  2091. if ( $mysync->{errorsdump} ) {
  2092. myprint( errorsdump( $sync->{nb_errors}, errors_log( $mysync ) ) ) ;
  2093. # again since errorsdump( ) can be very verbose and masq previous warning
  2094. myprint( "Maximum number of errors $mysync->{errorsmax} reached ( you can change $mysync->{errorsmax} to 100 with --errorsmax 100 ). Exiting.\n" ) ;
  2095. }
  2096. exit_clean( $mysync, $EXIT_WITH_ERRORS_MAX ) ;
  2097. }
  2098. return ;
  2099. }
  2100. sub errors_log {
  2101. my ( $mysync, @error ) = @ARG ;
  2102. if ( ! $mysync->{errors_log} ) {
  2103. $mysync->{errors_log} = [] ;
  2104. }
  2105. if ( @error ) {
  2106. push @{ $mysync->{errors_log} }, join( q{}, @error ) ;
  2107. }
  2108. if ( @{ $mysync->{errors_log} } ) {
  2109. return @{ $mysync->{errors_log} } ;
  2110. }
  2111. else {
  2112. return ;
  2113. }
  2114. }
  2115. sub tests_errors_log {
  2116. }
  2117. sub errorsdump {
  2118. my( $nb_errors, @errors_log ) = @ARG ;
  2119. my $error_num = 0 ;
  2120. my $errors_list = q{} ;
  2121. if ( @errors_log ) {
  2122. $errors_list = "++++ Listing $nb_errors errors encountered during the sync ( avoid this listing with --noerrorsdump ).\n" ;
  2123. foreach my $error ( @errors_log ) {
  2124. $error_num++ ;
  2125. $errors_list .= "Err $error_num/$nb_errors: $error" ;
  2126. }
  2127. }
  2128. return( $errors_list ) ;
  2129. }
  2130. sub tests_live_result {
  2131. my $nb_errors = shift ;
  2132. if ( $nb_errors ) {
  2133. myprint( "Live tests failed with $nb_errors errors\n" ) ;
  2134. } else {
  2135. myprint( "Live tests ended successfully\n" ) ;
  2136. }
  2137. return ;
  2138. }
  2139. sub foldersizesatend {
  2140. timenext( ) ;
  2141. return if ( $imap1->IsUnconnected( ) ) ;
  2142. return if ( $imap2->IsUnconnected( ) ) ;
  2143. # Get all folders on host2 again since new were created
  2144. @h2_folders_all = sort $imap2->folders();
  2145. for ( @h2_folders_all ) {
  2146. $h2_folders_all{ $_ } = 1 ;
  2147. $h2_folders_all_UPPER{ uc $_ } = 1 ;
  2148. } ;
  2149. ( $h1_nb_msg_end, $h1_bytes_end ) = foldersizes( 'Host1', $imap1, $search1, @h1_folders_wanted ) ;
  2150. ( $h2_nb_msg_end, $h2_bytes_end ) = foldersizes( 'Host2', $imap2, $search2, @h2_folders_from_1_wanted ) ;
  2151. if ( not all_defined( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end ) ) {
  2152. my $error = "Failure getting foldersizes, final differences will not be calculated\n" ;
  2153. errors_incr( $sync, $error ) ;
  2154. }
  2155. return ;
  2156. }
  2157. sub size_filtered_flag {
  2158. my $h1_size = shift ;
  2159. if (defined $maxsize and $h1_size >= $maxsize) {
  2160. return( 1 ) ;
  2161. }
  2162. if (defined $minsize and $h1_size <= $minsize) {
  2163. return( 1 ) ;
  2164. }
  2165. return( 0 ) ;
  2166. }
  2167. sub sync_flags_fir {
  2168. my ( $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) = @_ ;
  2169. if ( not defined $h1_msg ) { return } ;
  2170. if ( not defined $h2_msg ) { return } ;
  2171. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} ;
  2172. return if size_filtered_flag( $h1_size ) ;
  2173. # used cached flag values for efficiency
  2174. my $h1_flags = $h1_fir_ref->{ $h1_msg }->{ 'FLAGS' } || q{} ;
  2175. my $h2_flags = $h2_fir_ref->{ $h2_msg }->{ 'FLAGS' } || q{} ;
  2176. sync_flags( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  2177. return ;
  2178. }
  2179. sub sync_flags_after_copy {
  2180. my( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $permanentflags2 ) = @_ ;
  2181. my @h2_flags = $imap2->flags( $h2_msg ) ;
  2182. my $h2_flags = "@h2_flags" ;
  2183. ( $debug or $debugflags ) and myprint( "Host2 flags before resync by STORE on msg $h2_msg: $h2_flags\n" ) ;
  2184. sync_flags( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  2185. return ;
  2186. }
  2187. sub sync_flags {
  2188. my( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) = @_ ;
  2189. ( $debug or $debugflags ) and
  2190. myprint( "Host1: flags init msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  2191. $h1_flags = flags_for_host2( $h1_flags, $permanentflags2 ) ;
  2192. $h2_flags = flagscase( $h2_flags ) ;
  2193. ( $debug or $debugflags ) and
  2194. myprint( "Host1 flags filt msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  2195. # compare flags - set flags if there a difference
  2196. my @h1_flags = sort split(q{ }, $h1_flags );
  2197. my @h2_flags = sort split(q{ }, $h2_flags );
  2198. my $diff = compare_lists( \@h1_flags, \@h2_flags );
  2199. $diff and ( $debug or $debugflags )
  2200. and myprint( "Host2 flags msg $h2_fold/$h2_msg replacing h2 flags( $h2_flags ) with h1 flags( $h1_flags )\n" ) ;
  2201. # This sets flags so flags can be removed with this
  2202. # When you remove a \Seen flag on host1 you want to it
  2203. # to be removed on host2. Just add flags is not what
  2204. # we need most of the time.
  2205. if ( not $dry and $diff and not $imap2->store( $h2_msg, "FLAGS.SILENT (@h1_flags)" ) ) {
  2206. my $error_msg = join q{}, "Host2 flags msg $h2_fold/$h2_msg could not add flags [@h1_flags]: ",
  2207. $imap2->LastError || q{}, "\n" ;
  2208. errors_incr( $sync, $error_msg ) ;
  2209. }
  2210. return ;
  2211. }
  2212. sub _filter {
  2213. my $str = shift or return q{} ;
  2214. my $sz = $SIZE_MAX_STR ;
  2215. my $len = length $str ;
  2216. if ( not $debug and $len > $sz*2 ) {
  2217. my $beg = substr $str, 0, $sz ;
  2218. my $end = substr $str, -$sz, $sz ;
  2219. $str = $beg . '...' . $end ;
  2220. }
  2221. $str =~ s/\012?\015$//x ;
  2222. return "(len=$len) " . $str ;
  2223. }
  2224. sub lost_connection {
  2225. my( $imap, $error_message ) = @_;
  2226. if ( $imap->IsUnconnected( ) ) {
  2227. $sync->{nb_errors}++ ;
  2228. my $lcomm = $imap->LastIMAPCommand || q{} ;
  2229. my $einfo = $imap->LastError || @{$imap->History}[$LAST] || q{} ;
  2230. # if string is long try reduce to a more reasonable size
  2231. $lcomm = _filter( $lcomm ) ;
  2232. $einfo = _filter( $einfo ) ;
  2233. myprint( "Failure: last command: $lcomm\n") if ($debug && $lcomm) ;
  2234. myprint( "Failure: lost connection $error_message: ", $einfo, "\n") ;
  2235. return( 1 ) ;
  2236. }
  2237. else{
  2238. return( 0 ) ;
  2239. }
  2240. }
  2241. sub max {
  2242. my @list = @_ ;
  2243. return( undef ) if ( 0 == scalar @list ) ;
  2244. my @sorted = sort { $a <=> $b } @list ;
  2245. return( pop @sorted ) ;
  2246. }
  2247. sub tests_max {
  2248. ok( 0 == max( 0 ), 'max 0' ) ;
  2249. ok( 1 == max( 1 ), 'max 1' ) ;
  2250. ok( $MINUS_ONE == max( $MINUS_ONE ), 'max -1') ;
  2251. ok( not ( defined max( ) ), 'max no arg' ) ;
  2252. ok( $NUMBER_100 == max( 1, $NUMBER_100 ), 'max 1 100' ) ;
  2253. ok( $NUMBER_100 == max( $NUMBER_100, 1 ), 'max 100 1' ) ;
  2254. ok( $NUMBER_100 == max( $NUMBER_100, $NUMBER_42, 1 ), 'max 100 42 1' ) ;
  2255. ok( $NUMBER_100 == max( $NUMBER_100, '42', 1 ), 'max 100 42 1' ) ;
  2256. ok( $NUMBER_100 == max( '100', '42', 1 ), 'max 100 42 1' ) ;
  2257. #ok( 100 == max( 100, 'haha', 1 ), 'max 100 42 1') ;
  2258. return ;
  2259. }
  2260. sub check_lib_version {
  2261. $debug and myprint( "IMAPClient $Mail::IMAPClient::VERSION\n" ) ;
  2262. if ( '2.2.9' eq $Mail::IMAPClient::VERSION ) {
  2263. myprint( "imapsync no longer supports Mail::IMAPClient 2.2.9, upgrade it\n" ) ;
  2264. return 0 ;
  2265. }
  2266. else{
  2267. # 3.x.x is no longer buggy with imapsync.
  2268. # 3.30 or currently superior is imposed in the Perl "use Mail::IMAPClient line".
  2269. return 1 ;
  2270. }
  2271. return ;
  2272. }
  2273. sub module_version_str {
  2274. my( $module_name, $module_version ) = @_ ;
  2275. my $str = mysprintf( "%-20s %s\n", $module_name, $module_version ) ;
  2276. return( $str ) ;
  2277. }
  2278. sub modulesversion {
  2279. my @list_version;
  2280. my $v ;
  2281. eval { require Mail::IMAPClient; $v = $Mail::IMAPClient::VERSION } or $v = q{?} ;
  2282. push @list_version, module_version_str( 'Mail::IMAPClient', $v ) ;
  2283. eval { require IO::Socket; $v = $IO::Socket::VERSION } or $v = q{?} ;
  2284. push @list_version, module_version_str( 'IO::Socket', $v ) ;
  2285. eval { require IO::Socket::INET; $v = $IO::Socket::INET::VERSION } or $v = q{?} ;
  2286. push @list_version, module_version_str( 'IO::Socket::INET', $v ) ;
  2287. eval { require IO::Socket::INET6; $v = $IO::Socket::INET6::VERSION } or $v = q{?} ;
  2288. push @list_version, module_version_str( 'IO::Socket::INET6', $v ) ;
  2289. eval { require IO::Socket::SSL ; $v = $IO::Socket::SSL::VERSION } or $v = q{?} ;
  2290. push @list_version, module_version_str( 'IO::Socket::SSL ', $v ) ;
  2291. eval { require Net::SSLeay ; $v = $Net::SSLeay::VERSION } or $v = q{?} ;
  2292. push @list_version, module_version_str( 'Net::SSLeay ', $v ) ;
  2293. eval { require Compress::Zlib; $v = $Compress::Zlib::VERSION } or $v = q{?} ;
  2294. push @list_version, module_version_str( 'Compress::Zlib', $v ) ;
  2295. eval { require Digest::MD5; $v = $Digest::MD5::VERSION } or $v = q{?} ;
  2296. push @list_version, module_version_str( 'Digest::MD5', $v ) ;
  2297. eval { require Digest::HMAC_MD5; $v = $Digest::HMAC_MD5::VERSION } or $v = q{?} ;
  2298. push @list_version, module_version_str( 'Digest::HMAC_MD5', $v ) ;
  2299. eval { require Digest::HMAC_SHA1; $v = $Digest::HMAC_SHA1::VERSION } or $v = q{?} ;
  2300. push @list_version, module_version_str( 'Digest::HMAC_SHA1', $v ) ;
  2301. eval { require Term::ReadKey; $v = $Term::ReadKey::VERSION } or $v = q{?} ;
  2302. push @list_version, module_version_str( 'Term::ReadKey', $v ) ;
  2303. eval { require File::Spec; $v = $File::Spec::VERSION } or $v = q{?} ;
  2304. push @list_version, module_version_str( 'File::Spec', $v ) ;
  2305. eval { require Time::HiRes; $v = $Time::HiRes::VERSION } or $v = q{?} ;
  2306. push @list_version, module_version_str( 'Time::HiRes', $v ) ;
  2307. eval { require Unicode::String; $v = $Unicode::String::VERSION } or $v = q{?} ;
  2308. push @list_version, module_version_str( 'Unicode::String', $v ) ;
  2309. eval { require IO::Tee; $v = $IO::Tee::VERSION } or $v = q{?} ;
  2310. push @list_version, module_version_str( 'IO::Tee', $v ) ;
  2311. eval { require File::Copy::Recursive; $v = $File::Copy::Recursive::VERSION } or $v = q{?} ;
  2312. push @list_version, module_version_str( 'File::Copy::Recursive', $v ) ;
  2313. eval { require Authen::NTLM; $v = $Authen::NTLM::VERSION } or $v = q{?} ;
  2314. push @list_version, module_version_str( 'Authen::NTLM', $v ) ;
  2315. eval { require URI::Escape; $v = $URI::Escape::VERSION } or $v = q{?} ;
  2316. push @list_version, module_version_str( 'URI::Escape', $v ) ;
  2317. eval { require Data::Uniqid; $v = $Data::Uniqid::VERSION } or $v = q{?} ;
  2318. push @list_version, module_version_str( 'Data::Uniqid', $v ) ;
  2319. eval { require JSON; $v = $JSON::VERSION } or $v = q{?} ;
  2320. push @list_version, module_version_str( 'JSON', $v ) ;
  2321. eval { require JSON::WebToken; $v = $JSON::WebToken::VERSION } or $v = q{?} ;
  2322. push @list_version, module_version_str( 'JSON::WebToken', $v ) ;
  2323. eval { require Crypt::OpenSSL::RSA; $v = $Crypt::OpenSSL::RSA::VERSION } or $v = q{?} ;
  2324. push @list_version, module_version_str( 'Crypt::OpenSSL::RSA', $v ) ;
  2325. eval { require LWP; $v = $LWP::VERSION } or $v = q{?} ;
  2326. push @list_version, module_version_str( 'LWP', $v ) ;
  2327. eval { require HTML::Entities; $v = $HTML::Entities::VERSION } or $v = q{?} ;
  2328. push @list_version, module_version_str( 'HTML::Entities', $v ) ;
  2329. #eval { require Filesys::DfPortable; $v = $Filesys::DfPortable::VERSION } or $v = q{?} ;
  2330. #push @list_version, module_version_str( 'Filesys::DfPortable', $v ) ;
  2331. eval { require Getopt::Long; $v = $Getopt::Long::VERSION } or $v = q{?} ;
  2332. push @list_version, module_version_str( 'Getopt::Long', $v ) ;
  2333. eval { require Test::MockObject; $v = $Test::MockObject::VERSION } or $v = q{?} ;
  2334. push @list_version, module_version_str( 'Test::MockObject', $v ) ;
  2335. return( @list_version ) ;
  2336. }
  2337. # Construct a command line copy with passwords replaced by MASKED.
  2338. sub command_line_nopassword {
  2339. my @argv = @_ ;
  2340. my @argv_nopassword ;
  2341. return( "@argv" ) if $showpasswords ;
  2342. while ( @argv ) {
  2343. my $arg = shift @argv ; # option name or value
  2344. if ( $arg =~ m/-password[12]/x ) {
  2345. shift @argv ; # password value
  2346. push @argv_nopassword, $arg, 'MASKED' ; # option name and fake value
  2347. }else{
  2348. push @argv_nopassword, $arg ; # same option or value
  2349. }
  2350. }
  2351. return("@argv_nopassword") ;
  2352. }
  2353. sub tests_command_line_nopassword {
  2354. ok(q{} eq command_line_nopassword(), 'command_line_nopassword void');
  2355. ok('--blabla' eq command_line_nopassword('--blabla'), 'command_line_nopassword --blabla');
  2356. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  2357. ok('--password1 MASKED' eq command_line_nopassword(qw{ --password1 secret1}), 'command_line_nopassword --password1');
  2358. ok('--blabla --password1 MASKED --blibli'
  2359. eq command_line_nopassword(qw{ --blabla --password1 secret1 --blibli }), 'command_line_nopassword --password1 --blibli');
  2360. $showpasswords = 1 ;
  2361. ok(q{} eq command_line_nopassword(), 'command_line_nopassword void');
  2362. ok('--blabla' eq command_line_nopassword('--blabla'), 'command_line_nopassword --blabla');
  2363. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  2364. ok('--password1 secret1' eq command_line_nopassword(qw{ --password1 secret1}), 'command_line_nopassword --password1');
  2365. ok('--blabla --password1 secret1 --blibli'
  2366. eq command_line_nopassword(qw{ --blabla --password1 secret1 --blibli }), 'command_line_nopassword --password1 --blibli');
  2367. return ;
  2368. }
  2369. sub ask_for_password {
  2370. my ( $user, $host ) = @_ ;
  2371. myprint( "What's the password for $user" . '@' . "$host? (not visible while you type, then enter RETURN) " ) ;
  2372. Term::ReadKey::ReadMode( 2 ) ;
  2373. my $password = <> ;
  2374. chomp $password ;
  2375. myprint( "\nGot it\n" ) ;
  2376. Term::ReadKey::ReadMode( 0 ) ;
  2377. return $password ;
  2378. }
  2379. sub catch_exit {
  2380. my $mysync = shift ;
  2381. my $signame = shift ;
  2382. if ( $signame ) {
  2383. myprint( "\nGot a signal $signame\n" ) ;
  2384. }
  2385. stats( $mysync ) ;
  2386. myprint( "Ended by a signal\n" ) ;
  2387. exit_clean( $mysync, $EXIT_BY_SIGNAL ) ;
  2388. return ;
  2389. }
  2390. sub catch_reconnect {
  2391. my $mysync = shift ;
  2392. my $signame = shift ;
  2393. myprint( "\nGot a signal $signame\n",
  2394. "Hit 2 ctr-c within 2 seconds to exit the program\n",
  2395. "Hit only 1 ctr-c to reconnect to both imap servers\n",
  2396. ) ;
  2397. if ( here_twice( $mysync ) ) {
  2398. myprint( "Got two signals $signame within $INTERVAL_TO_EXIT seconds. Exiting...\n" ) ;
  2399. catch_exit( $mysync ) ;
  2400. }
  2401. else{
  2402. myprint( "For now only one signal $signame within $INTERVAL_TO_EXIT seconds.\n" ) ;
  2403. }
  2404. if ( ! defined $mysync->{imap1} ) { return ; }
  2405. if ( ! defined $mysync->{imap2} ) { return ; }
  2406. myprint( "Info: reconnecting to host1 imap server\n" ) ;
  2407. $mysync->{imap1}->State( Mail::IMAPClient::Unconnected ) ;
  2408. $mysync->{imap1}->reconnect( ) ;
  2409. myprint( "Info: reconnecting to host2 imap server\n" ) ;
  2410. $mysync->{imap2}->State( Mail::IMAPClient::Unconnected ) ;
  2411. $mysync->{imap2}->reconnect( ) ;
  2412. myprint( "Info: reconnected to both imap servers\n" ) ;
  2413. return ;
  2414. }
  2415. sub here_twice {
  2416. my $mysync = shift ;
  2417. my $now = time ;
  2418. my $previous = $mysync->{lastcatch} || 0 ;
  2419. $mysync->{lastcatch} = $now ;
  2420. if ( $INTERVAL_TO_EXIT >= $now - $previous ) {
  2421. return $TRUE ;
  2422. }else{
  2423. return $FALSE ;
  2424. }
  2425. }
  2426. sub justconnect {
  2427. $imap1 = connect_imap( $host1, $port1, $debugimap1, $ssl1, $tls1, 'Host1', $sync->{h1}->{timeout}, $sync->{h1} ) ;
  2428. myprint( 'Host1 banner: ', $imap1->Banner( ) ) ;
  2429. myprint( 'Host1 capability: ', join(q{ }, $imap1->capability( ) ), "\n" ) ;
  2430. $imap2 = connect_imap( $host2, $port2, $debugimap2, $ssl2, $tls2, 'Host2', $sync->{h2}->{timeout}, $sync->{h2} ) ;
  2431. myprint( 'Host2 banner: ', $imap2->Banner( ) ) ;
  2432. myprint( 'Host2 capability: ', join(q{ }, $imap2->capability( ) ), "\n" ) ;
  2433. $imap1->logout( ) ;
  2434. $imap2->logout( ) ;
  2435. return ;
  2436. }
  2437. sub connect_imap {
  2438. my( $host, $port, $mydebugimap, $ssl, $tls, $Side, $mytimeout, $h ) = @_ ;
  2439. my $imap = Mail::IMAPClient->new() ;
  2440. if ( $ssl ) { set_ssl( $imap, $h ) }
  2441. if ( $tls ) { $imap->Tls( 1 ) }
  2442. $imap->Server( $host ) ;
  2443. $imap->Port( $port ) ;
  2444. $imap->Debug( $mydebugimap ) ;
  2445. $imap->Timeout( $mytimeout ) ;
  2446. $imap->connect( )
  2447. or die_clean( "$Side: Can not open imap connection on [$host]: $@\n" ) ;
  2448. my $banner = $imap->Results()->[0] ;
  2449. $imap->Banner( $banner ) ;
  2450. if ( $imap->Tls( ) ) {
  2451. set_tls( $imap, $h ) ;
  2452. $imap->starttls( )
  2453. or die_clean("$Side: Can not go to tls encryption on [$host]:", $imap->LastError, "\n" ) ;
  2454. myprint( "$Side: Socket successfuly converted to SSL\n" ) ;
  2455. }
  2456. return( $imap ) ;
  2457. }
  2458. sub login_imap {
  2459. my @allargs = @_ ;
  2460. my(
  2461. $host, $port, $user, $domain, $password,
  2462. $mydebugimap, $mytimeout, $fastio,
  2463. $ssl, $tls, $authmech, $authuser, $reconnectretry,
  2464. $proxyauth, $uid, $split, $Side, $h ) = @allargs ;
  2465. my $side = lc $Side ;
  2466. myprint( "$Side: connecting and login on $side [$host] port [$port] with user [$user]\n" ) ;
  2467. my $imap = init_imap( @allargs ) ;
  2468. $imap->connect()
  2469. or die_clean("$Side failure: can not open imap connection on $side [$host] with user [$user]: $@\n") ;
  2470. my $banner = $imap->Results()->[0] ;
  2471. $imap->Banner( $banner ) ;
  2472. myprint( "$Side banner: $banner" ) ;
  2473. if ( $authmech eq 'PREAUTH' ) {
  2474. if ( $imap->IsAuthenticated( ) ) {
  2475. $imap->Socket ;
  2476. myprintf("%s: Assuming PREAUTH for %s\n", $Side, $imap->Server ) ;
  2477. }else{
  2478. die_clean( "$Side failure: error login on $side [$host] with user [$user] auth [PREAUTH]" ) ;
  2479. }
  2480. }
  2481. if ( $imap->Tls( ) ) {
  2482. set_tls( $imap, $h ) ;
  2483. $imap->starttls( )
  2484. or die_clean("$Side failure: Can not go to tls encryption on $side [$host]:", $imap->LastError, "\n" ) ;
  2485. myprint( "$Side: Socket successfuly converted to SSL\n" ) ;
  2486. }
  2487. authenticate_imap( $imap, @allargs ) ;
  2488. myprint( "$Side: success login on [$host] with user [$user] auth [$authmech]\n" ) ;
  2489. return( $imap ) ;
  2490. }
  2491. sub authenticate_imap {
  2492. my($imap,
  2493. $host, $port, $user, $domain, $password,
  2494. $mydebugimap, $mytimeout, $fastio,
  2495. $ssl, $tls, $authmech, $authuser, $reconnectretry,
  2496. $proxyauth, $uid, $split, $Side, $h ) = @_ ;
  2497. check_capability( $imap, $authmech, $Side ) ;
  2498. if ( $proxyauth ) {
  2499. $imap->Authmechanism(q{}) ;
  2500. $imap->User($authuser) ;
  2501. } else {
  2502. $imap->Authmechanism( $authmech ) unless ( $authmech eq 'LOGIN' or $authmech eq 'PREAUTH' ) ;
  2503. $imap->User($user) ;
  2504. }
  2505. $imap->Authcallback(\&xoauth) if ( 'XOAUTH' eq $authmech ) ;
  2506. $imap->Authcallback(\&xoauth2) if ( 'XOAUTH2' eq $authmech ) ;
  2507. $imap->Authcallback(\&plainauth) if ( ( 'PLAIN' eq $authmech ) or ( 'EXTERNAL' eq $authmech ) ) ;
  2508. $imap->Domain($domain) if (defined $domain) ;
  2509. $imap->Authuser($authuser) ;
  2510. $imap->Password($password) ;
  2511. unless ( $authmech eq 'PREAUTH' or $imap->login( ) ) {
  2512. my $info = "$Side failure: Error login on [$host] with user [$user] auth" ;
  2513. my $einfo = $imap->LastError || @{$imap->History}[$LAST] ;
  2514. chomp $einfo ;
  2515. my $error = "$info [$authmech]: $einfo\n" ;
  2516. if ( $authmech eq 'LOGIN' or $imap->IsUnconnected( ) or $authuser ) {
  2517. die_clean( $error ) ;
  2518. }else{
  2519. myprint( $error ) ;
  2520. }
  2521. myprint( "$Side info: trying LOGIN Auth mechanism on [$host] with user [$user]\n" ) ;
  2522. $imap->Authmechanism(q{}) ;
  2523. $imap->login() or
  2524. die_clean("$info [LOGIN]: ", $imap->LastError, "\n") ;
  2525. }
  2526. if ( $proxyauth ) {
  2527. if ( ! $imap->proxyauth( $user ) ) {
  2528. my $info = "$Side failure: Error doing proxyauth as user [$user] on [$host] using proxy-login as [$authuser]" ;
  2529. my $einfo = $imap->LastError || @{$imap->History}[$LAST] ;
  2530. chomp $einfo ;
  2531. die_clean( "$info: $einfo\n" ) ;
  2532. }
  2533. }
  2534. return ;
  2535. }
  2536. sub check_capability {
  2537. my( $imap, $authmech, $Side ) = @_ ;
  2538. if ($imap->has_capability("AUTH=$authmech")
  2539. or $imap->has_capability($authmech)
  2540. ) {
  2541. myprintf("%s: %s says it has CAPABILITY for AUTHENTICATE %s\n",
  2542. $Side, $imap->Server, $authmech);
  2543. }
  2544. else {
  2545. myprintf("%s: %s says it has NO CAPABILITY for AUTHENTICATE %s\n",
  2546. $Side, $imap->Server, $authmech);
  2547. if ($authmech eq 'PLAIN') {
  2548. myprint( "$Side: frequently PLAIN is only supported with SSL, ",
  2549. "try --ssl or --tls options\n" ) ;
  2550. }
  2551. }
  2552. return ;
  2553. }
  2554. sub set_ssl {
  2555. my ( $imap, $h ) = @_ ;
  2556. # SSL_version can be
  2557. # SSLv3 SSLv2 SSLv23 SSLv23:!SSLv2 (last one is the default in IO-Socket-SSL-1.953)
  2558. #
  2559. my $sslargs_hash = $h->{sslargs} ;
  2560. my $sslargs_default = {
  2561. SSL_verify_mode => $DEFAULT_SSL_VERIFY,
  2562. SSL_verifycn_scheme => 'imap',
  2563. } ;
  2564. # initiate with default values
  2565. my %sslargs_mix = %{ $sslargs_default } ;
  2566. # now override with passed values
  2567. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  2568. # remove keys with undef values
  2569. foreach my $key ( keys %sslargs_mix ) {
  2570. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  2571. }
  2572. # back to an ARRAY
  2573. my @sslargs_mix = %sslargs_mix ;
  2574. #myprint( Data::Dumper->Dump( [ $sslargs_hash, $sslargs_default, \%sslargs_mix, \@sslargs_mix ] ) ) ;
  2575. $imap->Ssl( \@sslargs_mix ) ;
  2576. return ;
  2577. }
  2578. sub set_tls {
  2579. my ( $imap, $h ) = @_ ;
  2580. my $sslargs_hash = $h->{sslargs} ;
  2581. my $sslargs_default = {
  2582. SSL_verify_mode => $DEFAULT_SSL_VERIFY,
  2583. } ;
  2584. # initiate with default values
  2585. my %sslargs_mix = %{ $sslargs_default } ;
  2586. # now override with passed values
  2587. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  2588. # remove keys with undef values
  2589. foreach my $key ( keys %sslargs_mix ) {
  2590. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  2591. }
  2592. # back to an ARRAY
  2593. my @sslargs_mix = %sslargs_mix ;
  2594. $imap->Starttls( \@sslargs_mix ) ;
  2595. return ;
  2596. }
  2597. sub init_imap {
  2598. my(
  2599. $host, $port, $user, $domain, $password,
  2600. $mydebugimap, $mytimeout, $fastio,
  2601. $ssl, $tls, $authmech, $authuser, $reconnectretry,
  2602. $proxyauth, $uid, $split, $Side, $h ) = @_ ;
  2603. my ( $imap ) ;
  2604. $imap = Mail::IMAPClient->new() ;
  2605. if ( $ssl ) { set_ssl( $imap, $h ) }
  2606. if ( $tls ) { $imap->Tls( 1 ) } # can not do set_tls() here because connect() will directly do a STARTTLS
  2607. $imap->Clear(1);
  2608. $imap->Server($host);
  2609. $imap->Port($port);
  2610. $imap->Fast_io($fastio);
  2611. $imap->Buffer($buffersize || $DEFAULT_BUFFER_SIZE);
  2612. $imap->Uid($uid);
  2613. $imap->Peek(1);
  2614. $imap->Debug($mydebugimap);
  2615. defined $mytimeout and $imap->Timeout( $mytimeout ) ;
  2616. $imap->Reconnectretry( $reconnectretry ) if ( $reconnectretry ) ;
  2617. $imap->Ignoresizeerrors( $allowsizemismatch ) ;
  2618. $split and $imap->Maxcommandlength( $SPLIT_FACTOR * $split ) ;
  2619. return( $imap ) ;
  2620. }
  2621. sub plainauth {
  2622. my $code = shift;
  2623. my $imap = shift;
  2624. my $string = mysprintf("%s\x00%s\x00%s", $imap->User,
  2625. $imap->Authuser, $imap->Password);
  2626. return encode_base64("$string", q{});
  2627. }
  2628. # Copy from https://github.com/imapsync/imapsync/pull/25/files
  2629. # Changes "use" pragmas to "require".
  2630. # The openssl system call shall be replaced by pure Perl and
  2631. # https://metacpan.org/pod/Crypt::OpenSSL::PKCS12
  2632. # Now the Joaquin Lopez code:
  2633. #
  2634. # Used this as an example: https://gist.github.com/gsainio/6322375
  2635. #
  2636. # And this as a reference: https://developers.google.com/accounts/docs/OAuth2ServiceAccount
  2637. # (note there is an http/rest tab, where the real info is hidden away... went on a witch hunt
  2638. # until I noticed that...)
  2639. #
  2640. # This is targeted at gmail to maintain compatibility after google's oauth1 service is deactivated
  2641. # on May 5th, 2015: https://developers.google.com/gmail/oauth_protocol
  2642. # If there are other oauth2 implementations out there, this would need to be modified to be
  2643. # compatible
  2644. #
  2645. # This is a good guide on setting up the google api/apps side of the equation:
  2646. # http://www.limilabs.com/blog/oauth2-gmail-imap-service-account
  2647. #
  2648. # 2016/05/27: Updated to support oauth/key data in the .json files Google now defaults to
  2649. # when creating gmail service accounts. They're easier to work with since they neither
  2650. # requiring decrypting nor specifying the oauth2 client id separately.
  2651. #
  2652. # If the password arg ends in .json, it will assume this new json method, otherwise it
  2653. # will fallback to the "oauth client id;.p12" format it was previously using.
  2654. sub xoauth2 {
  2655. require JSON::WebToken ;
  2656. require LWP::UserAgent ;
  2657. require HTML::Entities ;
  2658. require JSON ;
  2659. require JSON::WebToken::Crypt::RSA ;
  2660. require Crypt::OpenSSL::RSA ;
  2661. require Encode::Byte ;
  2662. require IO::Socket::SSL ;
  2663. my $code = shift;
  2664. my $imap = shift;
  2665. my ($iss,$key);
  2666. if( $imap->Password =~ /^(.*\.json)$/ ) {
  2667. my $json = JSON->new( ) ;
  2668. my $filename = $1;
  2669. $debug and myprint( "XOAUTH2 json file: $filename\n" ) ;
  2670. open( my $FILE, '<', $filename ) or die_clean( "error [$filename]: $! " ) ;
  2671. my $jsonfile = $json->decode( join q{}, <$FILE> ) ;
  2672. close $FILE ;
  2673. $iss = $jsonfile->{client_id};
  2674. $key = $jsonfile->{private_key};
  2675. $debug and myprint( "Service account: $iss\n");
  2676. $debug and myprint( "Private key:\n$key\n");
  2677. }
  2678. else {
  2679. # Get iss (service account address), keyfile name, and keypassword if necessary
  2680. ( $iss, my $keyfile, my $keypass ) = $imap->Password =~ /([\-\d\w\@\.]+);([a-zA-Z0-9 \_\-\.\/]+);?(.*)?/ ;
  2681. # Assume key password is google default if not provided
  2682. $keypass = 'notasecret' if not $keypass;
  2683. $debug and myprint( "Service account: $iss\nKey file: $keyfile\nKey password: $keypass\n");
  2684. # Get private key from p12 file (would be better in perl...)
  2685. $key = `openssl pkcs12 -in "$keyfile" -nodes -nocerts -passin pass:$keypass -nomacver`;
  2686. $debug and myprint( "Private key:\n$key\n");
  2687. }
  2688. # Create jwt of oauth2 request
  2689. my $time = time ;
  2690. my $jwt = JSON::WebToken->encode( {
  2691. 'iss' => $iss, # service account
  2692. 'scope' => 'https://mail.google.com/',
  2693. 'aud' => 'https://www.googleapis.com/oauth2/v3/token',
  2694. 'exp' => $time + $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12,
  2695. 'iat' => $time,
  2696. 'prn' => $imap->User # user to auth as
  2697. },
  2698. $key, 'RS256', {'typ' => 'JWT'} ); # Crypt::OpenSSL::RSA needed here.
  2699. # Post oauth2 request
  2700. my $ua = LWP::UserAgent->new( ) ;
  2701. $ua->env_proxy( ) ;
  2702. my $response = $ua->post('https://www.googleapis.com/oauth2/v3/token',
  2703. { grant_type => HTML::Entities::encode_entities('urn:ietf:params:oauth:grant-type:jwt-bearer'),
  2704. assertion => $jwt } ) ;
  2705. unless( $response->is_success( ) ) {
  2706. die_clean( $response->code, "\n", $response->content, "\n" ) ;
  2707. }else{
  2708. $debug and myprint( $response->content ) ;
  2709. }
  2710. # access_token in response is what we need
  2711. my $data = JSON::decode_json( $response->content ) ;
  2712. # format as oauth2 auth data
  2713. my $xoauth2_string = encode_base64( 'user=' . $imap->User . "\1auth=Bearer " . $data->{access_token} . "\1\1", q{} ) ;
  2714. $debug and myprint( "XOAUTH2 String: $xoauth2_string\n");
  2715. return($xoauth2_string);
  2716. }
  2717. # xoauth() thanks to Eduardo Bortoluzzi Junior
  2718. sub xoauth {
  2719. require URI::Escape ;
  2720. require Data::Uniqid ;
  2721. my $code = shift;
  2722. my $imap = shift;
  2723. # The base information needed to construct the OAUTH authentication
  2724. my $method = 'GET' ;
  2725. my $url = mysprintf( 'https://mail.google.com/mail/b/%s/imap/', $imap->User ) ;
  2726. my $urlparm = mysprintf( 'xoauth_requestor_id=%s', URI::Escape::uri_escape( $imap->User ) ) ;
  2727. # For Google Apps, the consumer key is the primary domain
  2728. # TODO: create a command line argument to define the consumer key
  2729. my @user_parts = split /@/x, $imap->User ;
  2730. $debug and myprint( "XOAUTH: consumer key: $user_parts[1]\n" ) ;
  2731. # All the parameters needed to be signed on the XOAUTH
  2732. my %hash = ();
  2733. $hash { 'xoauth_requestor_id' } = URI::Escape::uri_escape($imap->User);
  2734. $hash { 'oauth_consumer_key' } = $user_parts[1];
  2735. $hash { 'oauth_nonce' } = md5_hex(Data::Uniqid::uniqid(rand(), 1==1));
  2736. $hash { 'oauth_signature_method' } = 'HMAC-SHA1';
  2737. $hash { 'oauth_timestamp' } = time ;
  2738. $hash { 'oauth_version' } = '1.0';
  2739. # Base will hold the string to be signed
  2740. my $base = "$method&" . URI::Escape::uri_escape( $url ) . q{&} ;
  2741. # The parameters must be in dictionary order before signing
  2742. my $baseparms = q{} ;
  2743. foreach my $key ( sort keys %hash ) {
  2744. if ( length( $baseparms ) > 0 ) {
  2745. $baseparms .= q{&} ;
  2746. }
  2747. $baseparms .= "$key=$hash{$key}" ;
  2748. }
  2749. $base .= URI::Escape::uri_escape($baseparms);
  2750. $debug and myprint( "XOAUTH: base request to sign: $base\n" ) ;
  2751. # Sign it with the consumer secret, informed on the command line (password)
  2752. my $digest = hmac_sha1( $base, URI::Escape::uri_escape( $imap->Password ) . q{&} ) ;
  2753. # The parameters signed become a parameter and...
  2754. $hash { 'oauth_signature' } = URI::Escape::uri_escape( substr encode_base64( $digest ), 0, $MINUS_ONE ) ;
  2755. # ... we don't need the requestor_id anymore.
  2756. delete $hash{'xoauth_requestor_id'} ;
  2757. # Create the final authentication string
  2758. my $string = $method . q{ } . $url . q{?} . $urlparm .q{ } ;
  2759. # All the parameters must be sorted
  2760. $baseparms = q{};
  2761. foreach my $key (sort keys %hash) {
  2762. if(length($baseparms)>0) {
  2763. $baseparms .= q{,} ;
  2764. }
  2765. $baseparms .= "$key=\"$hash{$key}\"";
  2766. }
  2767. $string .= $baseparms;
  2768. $debug and myprint( "XOAUTH: authentication string: $string\n" ) ;
  2769. # It must be base64 encoded
  2770. return encode_base64("$string", q{});
  2771. }
  2772. sub server_banner {
  2773. my $imap = shift;
  2774. my $banner = $imap->Banner() || "No banner\n";
  2775. return $banner;
  2776. }
  2777. sub banner_imapsync {
  2778. my @argv = @_ ;
  2779. my $banner_imapsync = join q{},
  2780. q{$RCSfile: imapsync,v $ },
  2781. q{$Revision: 1.727 $ },
  2782. q{$Date: 2016/08/19 10:30:36 $ },
  2783. "\n", localhost_info(), "\n",
  2784. "Command line used:\n",
  2785. "$0 ", command_line_nopassword( @argv ), "\n" ;
  2786. return( $banner_imapsync ) ;
  2787. }
  2788. sub is_valid_directory {
  2789. my $dir = shift;
  2790. # all good => return ok.
  2791. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  2792. # exist but bad
  2793. if ( -e $dir and not -d _ ) {
  2794. myprint( "Error: $dir exists but is not a directory\n" ) ;
  2795. return( 0 ) ;
  2796. }
  2797. if ( -e $dir and not -w _ ) {
  2798. my $sb = stat $dir ;
  2799. myprintf( "Error: directory %s is not writable for user %s, permissions are %04o and owner is %s ( uid %s )\n",
  2800. $dir, getpwuid_any_os( $EFFECTIVE_USER_ID ), ($sb->mode & oct($PERMISSION_FILTER) ), getpwuid_any_os( $sb->uid ), $sb->uid( ) ) ;
  2801. return( 0 ) ;
  2802. }
  2803. # Trying to create it
  2804. myprint( "Creating directory $dir\n" ) ;
  2805. eval { mkpath( $dir ) } ;
  2806. myprint( "$@" ) if ( $@ ) ;
  2807. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  2808. return( 0 ) ;
  2809. }
  2810. sub tests_is_valid_directory {
  2811. Readonly my $NB_UNIX_tests_is_valid_directory => 4 ;
  2812. SKIP: {
  2813. skip( 'Tests only for Unix', $NB_UNIX_tests_is_valid_directory ) if ( 'MSWin32' eq $OSNAME ) ;
  2814. ok( 1 == is_valid_directory( '.'), 'is_valid_directory: . good' ) ;
  2815. ok( 1 == is_valid_directory( './tmp/tests/valid/sub'), 'is_valid_directory: ./tmp/tests/valid/sub good' ) ;
  2816. diag( 'Error / not writable is on purpose' ) ;
  2817. ok( 0 == is_valid_directory( '/'), 'is_valid_directory: / bad' ) ;
  2818. diag( 'Error permission denied on /noway is on purpose' ) ;
  2819. ok( 0 == is_valid_directory( '/noway'), 'is_valid_directory: /noway bad' ) ;
  2820. }
  2821. return ;
  2822. }
  2823. sub write_pidfile {
  2824. my $pid_filename = shift ;
  2825. my $lock = shift ;
  2826. myprint( "PID file is $pid_filename ( to change it use --pidfile filepath ; to avoid it use --pidfile \"\" )\n" ) ;
  2827. if ( -e $pid_filename and $lock ) {
  2828. myprint( "$pid_filename already exists, another imapsync may be curently running. Aborting imapsync.\n" ) ;
  2829. exit $EXIT_PID_FILE_ALREADY_EXIST ;
  2830. }
  2831. if ( -e $pid_filename ) {
  2832. myprint( "$pid_filename already exists, overwriting it ( use --pidfilelocking to avoid concurrent runs )\n" ) ;
  2833. }
  2834. open my $FILE_HANDLE, '>', $pid_filename
  2835. or do {
  2836. myprint( "Could not open $pid_filename for writing. Check permissions or disk space." ) ;
  2837. return ;
  2838. } ;
  2839. myprint( "Wrinting my PID $PROCESS_ID in $pid_filename\n" ) ;
  2840. print $FILE_HANDLE $PROCESS_ID ;
  2841. close $FILE_HANDLE ;
  2842. return( $PROCESS_ID ) ;
  2843. }
  2844. sub remove_tmp_files {
  2845. my $mysync = shift ;
  2846. unlink $mysync->{pidfile} ;
  2847. return ;
  2848. }
  2849. sub exit_clean {
  2850. my $mysync = shift ;
  2851. my $status = shift ;
  2852. $status = defined $status ? $status : $EXIT_UNKNOWN ;
  2853. remove_tmp_files( $mysync ) ;
  2854. myprint( "Exiting with return value $status\n" ) ;
  2855. if ( $mysync->{log} ) {
  2856. myprint( "Log file is $mysync->{logfile} ( to change it, use --logfile filepath ; or use --nolog to turn off logging )\n" ) ;
  2857. close $mysync->{logfile_handle} ;
  2858. }
  2859. exit $status ;
  2860. }
  2861. sub die_clean {
  2862. my @messages = @_ ;
  2863. remove_tmp_files( $sync ) ;
  2864. die @messages ;
  2865. }
  2866. sub missing_option {
  2867. my ( $option ) = @_ ;
  2868. die_clean( "$option option is mandatory, for help run $0 --help\n" ) ;
  2869. return ;
  2870. }
  2871. sub fix_Inbox_INBOX_mapping {
  2872. my( $h1_all, $h2_all ) = @_ ;
  2873. my $regex = q{} ;
  2874. SWITCH: {
  2875. if ( exists $h1_all->{INBOX} and exists $h2_all->{INBOX} ) { $regex = q{} ; last SWITCH ; } ;
  2876. if ( exists $h1_all->{Inbox} and exists $h2_all->{Inbox} ) { $regex = q{} ; last SWITCH ; } ;
  2877. if ( exists $h1_all->{INBOX} and exists $h2_all->{Inbox} ) { $regex = q{s/^INBOX$/Inbox/x} ; last SWITCH ; } ;
  2878. if ( exists $h1_all->{Inbox} and exists $h2_all->{INBOX} ) { $regex = q{s/^Inbox$/INBOX/x} ; last SWITCH ; } ;
  2879. } ;
  2880. return( $regex ) ;
  2881. }
  2882. sub tests_fix_Inbox_INBOX_mapping {
  2883. my( $h1_all, $h2_all ) ;
  2884. $h1_all = { 'INBOX' => q{} } ;
  2885. $h2_all = { 'INBOX' => q{} } ;
  2886. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX INBOX' ) ;
  2887. $h1_all = { 'Inbox' => q{} } ;
  2888. $h2_all = { 'Inbox' => q{} } ;
  2889. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox Inbox' ) ;
  2890. $h1_all = { 'INBOX' => q{} } ;
  2891. $h2_all = { 'Inbox' => q{} } ;
  2892. ok( q{s/^INBOX$/Inbox/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX Inbox' ) ;
  2893. $h1_all = { 'Inbox' => q{} } ;
  2894. $h2_all = { 'INBOX' => q{} } ;
  2895. ok( q{s/^Inbox$/INBOX/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox INBOX' ) ;
  2896. $h1_all = { 'INBOX' => q{} } ;
  2897. $h2_all = { 'rrrrr' => q{} } ;
  2898. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX rrrrrr' ) ;
  2899. $h1_all = { 'rrrrr' => q{} } ;
  2900. $h2_all = { 'Inbox' => q{} } ;
  2901. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: rrrrr Inbox' ) ;
  2902. return ;
  2903. }
  2904. sub jux_utf8_list {
  2905. my @s_inp = @_ ;
  2906. my $s_out = q{} ;
  2907. foreach my $s ( @s_inp ) {
  2908. $s_out .= jux_utf8( $s ) . "\n" ;
  2909. }
  2910. return( $s_out ) ;
  2911. }
  2912. sub tests_jux_utf8_list {
  2913. ok( q{} eq jux_utf8_list( ), 'jux_utf8_list: void' ) ;
  2914. ok( "[]\n" eq jux_utf8_list( q{} ), 'jux_utf8_list: empty string' ) ;
  2915. ok( "[INBOX]\n" eq jux_utf8_list( 'INBOX' ), 'jux_utf8_list: INBOX' ) ;
  2916. ok( "[&ANY-] = [Ö]\n" eq jux_utf8_list( '&ANY-' ), 'jux_utf8_list: &ANY-' ) ;
  2917. return( 0 ) ;
  2918. }
  2919. sub jux_utf8 {
  2920. # juxtapose utf8 at the right if different
  2921. my ( $s_utf7 ) = shift ;
  2922. my ( $s_utf8 ) = imap_utf7_decode( $s_utf7 ) ;
  2923. if ( $s_utf7 eq $s_utf8 ) {
  2924. #myprint( "[$s_utf7]\n" ) ;
  2925. return( "[$s_utf7]" ) ;
  2926. }else{
  2927. #myprint( "[$s_utf7] = [$s_utf8]\n" ) ;
  2928. return( "[$s_utf7] = [$s_utf8]" ) ;
  2929. }
  2930. }
  2931. # editing utf8 can be tricky without an utf8 editor
  2932. sub tests_jux_utf8 {
  2933. ok( '[INBOX]' eq jux_utf8( 'INBOX'), 'jux_utf8: INBOX => [INBOX]' ) ;
  2934. ok( '[&ZTZO9nux-] = [收件箱]' eq jux_utf8( '&ZTZO9nux-'), 'jux_utf8: => [&ZTZO9nux-] = [收件箱]' ) ;
  2935. ok( '[&ANY-] = [Ö]' eq jux_utf8( '&ANY-'), 'jux_utf8: &ANY- => [&ANY-] = [Ö]' ) ;
  2936. ok( '[]' eq jux_utf8( q{} ), 'jux_utf8: void => []' ) ;
  2937. ok( '[+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]' eq jux_utf8( '+BD8EQAQ1BDQEOwQ+BDM-' ), 'jux_utf8: => [+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]' ) ;
  2938. ok( '[&BB8EQAQ+BDUEOgRC-] = [Проект]' eq jux_utf8( '&BB8EQAQ+BDUEOgRC-' ), 'jux_utf8: => [&BB8EQAQ+BDUEOgRC-] = [Проект]' ) ;
  2939. return( 0 ) ;
  2940. }
  2941. # Copied from http://cpansearch.perl.org/src/FABPOT/Unicode-IMAPUtf7-2.01/lib/Unicode/IMAPUtf7.pm
  2942. # and then fixed with
  2943. # https://rt.cpan.org/Public/Bug/Display.html?id=11172
  2944. sub imap_utf7_decode {
  2945. my ( $s ) = shift ;
  2946. # Algorithm
  2947. # On remplace , par / dans les BASE 64 (, entre & et -)
  2948. # On remplace les &, non suivi d'un - par +
  2949. # On remplace les &- par &
  2950. $s =~ s/&([^,&\-]*),([^,\-&]*)\-/&$1\/$2\-/g ;
  2951. $s =~ s/&(?!\-)/\+/g ;
  2952. $s =~ s/&\-/&/g ;
  2953. return( Unicode::String::utf7( $s )->utf8 ) ;
  2954. }
  2955. sub imap_utf7_encode {
  2956. my ( $s ) = @_ ;
  2957. $s = Unicode::String::utf8( $s )->utf7 ;
  2958. $s =~ s/\+([^\/&\-]*)\/([^\/\-&]*)\-/\+$1,$2\-/g ;
  2959. $s =~ s/&/&\-/g ;
  2960. $s =~ s/\+([^+\-]+)?\-/&$1\-/g ;
  2961. return( $s ) ;
  2962. }
  2963. sub select_folder {
  2964. my ( $imap, $folder, $hostside ) = @_ ;
  2965. if ( ! $imap->select( $folder ) ) {
  2966. my $error = join q{},
  2967. "$hostside folder $folder: Could not select: ",
  2968. $imap->LastError, "\n" ;
  2969. errors_incr( $sync, $error ) ;
  2970. return( 0 ) ;
  2971. }else{
  2972. # ok select succeeded
  2973. return( 1 ) ;
  2974. }
  2975. }
  2976. sub examine_folder {
  2977. my ( $imap, $folder, $hostside ) = @_ ;
  2978. if ( ! $imap->examine( $folder ) ) {
  2979. my $error = join q{},
  2980. "$hostside folder $folder: Could not examine: ",
  2981. $imap->LastError, "\n" ;
  2982. errors_incr( $sync, $error ) ;
  2983. return( 0 ) ;
  2984. }else{
  2985. # ok select succeeded
  2986. return( 1 ) ;
  2987. }
  2988. }
  2989. sub count_from_select {
  2990. my @lines = @_ ;
  2991. my $count ;
  2992. foreach my $line ( @lines ) {
  2993. #myprint( "line = [$line]\n" ) ;
  2994. if ( $line =~ m/^\*\s+(\d+)\s+EXISTS/ ) {
  2995. $count = $1 ;
  2996. return( $count ) ;
  2997. }
  2998. }
  2999. return( undef ) ;
  3000. }
  3001. sub create_folder_old {
  3002. my( $imap, $h2_fold, $h1_fold ) = @_ ;
  3003. myprint( "Creating (old way) folder [$h2_fold] on host2\n" ) ;
  3004. if ( ( 'INBOX' eq uc $h2_fold )
  3005. and ( $imap->exists( $h2_fold ) ) ) {
  3006. myprint( "Folder [$h2_fold] already exists\n" ) ;
  3007. return( 1 ) ;
  3008. }
  3009. if ( ! $dry ){
  3010. if ( ! $imap->create( $h2_fold ) ) {
  3011. my $error = join q{},
  3012. "Could not create folder [$h2_fold] from [$h1_fold]: ",
  3013. $imap->LastError( ), "\n" ;
  3014. errors_incr( $sync, $error ) ;
  3015. # success if folder exists ("already exists" error)
  3016. return( 1 ) if $imap->exists( $h2_fold ) ;
  3017. # failure since create failed
  3018. return( 0 ) ;
  3019. }else{
  3020. #create succeeded
  3021. myprint( "Created ( the old way ) folder [$h2_fold] on host2\n" ) ;
  3022. return( 1 ) ;
  3023. }
  3024. }else{
  3025. # dry mode, no folder so many imap will fail, assuming failure
  3026. myprint( "Created ( the old way ) folder [$h2_fold] on host2 $dry_message\n" ) ;
  3027. return( 0 ) ;
  3028. }
  3029. }
  3030. sub create_folder {
  3031. my( $imap2 , $h2_fold , $h1_fold ) = @_ ;
  3032. my( @parts , $parent ) ;
  3033. if ( $imap2->IsUnconnected( ) ) {
  3034. myprint( "Host2: Unconnected state\n" ) ;
  3035. return( 0 ) ;
  3036. }
  3037. if ( $create_folder_old ) {
  3038. return( create_folder_old( $imap2 , $h2_fold , $h1_fold ) ) ;
  3039. }
  3040. myprint( "Creating folder [$h2_fold] on host2\n" ) ;
  3041. if ( ( 'INBOX' eq uc $h2_fold )
  3042. and ( $imap2->exists( $h2_fold ) ) ) {
  3043. myprint( "Folder [$h2_fold] already exists\n" ) ;
  3044. return( 1 ) ;
  3045. }
  3046. if ( $mixfolders and $imap2->exists( $h2_fold ) ) {
  3047. myprint( "Folder [$h2_fold] already exists (--nomixfolders is not set)\n" ) ;
  3048. return( 1 ) ;
  3049. }
  3050. if ( ( not $mixfolders ) and ( $imap2->exists( $h2_fold ) ) ) {
  3051. myprint( "Folder [$h2_fold] already exists and --nomixfolders is set\n" ) ;
  3052. return( 0 ) ;
  3053. }
  3054. @parts = split /\Q$h2_sep\E/, $h2_fold ;
  3055. pop @parts ;
  3056. $parent = join $h2_sep, @parts ;
  3057. $parent =~ s/^\s+|\s+$//g ;
  3058. if ( ( $parent ne q{} ) and ( ! $imap2->exists( $parent ) ) ) {
  3059. create_folder( $imap2 , $parent , $h1_fold ) ;
  3060. }
  3061. if ( ! $dry ) {
  3062. if ( ! $imap2->create( $h2_fold ) ) {
  3063. my $error = join q{},
  3064. "Could not create folder [$h2_fold] from [$h1_fold]: " ,
  3065. $imap2->LastError( ), "\n" ;
  3066. errors_incr( $sync, $error ) ;
  3067. # success if folder exists ("already exists" error)
  3068. return( 1 ) if $imap2->exists( $h2_fold ) ;
  3069. # failure since create failed
  3070. return( 0 ) ;
  3071. }else{
  3072. #create succeeded
  3073. myprint( "Created folder [$h2_fold] on host2\n" ) ;
  3074. return( 1 ) ;
  3075. }
  3076. }else{
  3077. # dry mode, no folder so many imap will fail, assuming failure
  3078. myprint( "Created folder [$h2_fold] on host2 $dry_message\n" ) ;
  3079. if ( ! $justfolders ) {
  3080. myprint( "Since --dry mode is on and folder [$h2_fold] on host2 does not exist yet, syncing messages will not be simulated.\n"
  3081. . "To simulate message syncing, use --justfolders without --dry to first create the missing folders then rerun the --dry sync.\n" ) ;
  3082. }
  3083. return( 0 ) ;
  3084. }
  3085. }
  3086. sub tests_folder_routines {
  3087. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 1' );
  3088. ok( add_to_requested_folders('folder_foo'), 'add_to_requested_folders folder_foo' );
  3089. ok( is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 2' );
  3090. ok( !is_requested_folder('folder_NO_EXIST'), 'is_requested_folder folder_NO_EXIST' );
  3091. ok( !remove_from_requested_folders('folder_foo'), 'removed folder_foo' );
  3092. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 3' );
  3093. my @f ;
  3094. ok( @f = add_to_requested_folders('folder_bar', 'folder_toto'), "add result: @f" );
  3095. ok( is_requested_folder('folder_bar'), 'is_requested_folder 4' );
  3096. ok( is_requested_folder('folder_toto'), 'is_requested_folder 5' );
  3097. ok( remove_from_requested_folders('folder_toto'), 'remove_from_requested_folders: ' );
  3098. ok( !is_requested_folder('folder_toto'), 'is_requested_folder 6' );
  3099. ok( !remove_from_requested_folders('folder_bar'), 'remove_from_requested_folders: empty' ) ;
  3100. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [] ), 'sort_requested_folders: all empty' ) ;
  3101. ok( add_to_requested_folders('M_55'), 'add_to_requested_folders M_55' );
  3102. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'M_55' ] ), 'sort_requested_folders: middle' ) ;
  3103. @folderfirst = ( 'Z_11' ) ;
  3104. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_55' ] ), 'sort_requested_folders: first+middle' ) ;
  3105. @folderlast = ( 'A_99' ) ;
  3106. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_55', 'A_99' ] ), 'sort_requested_folders: first+middle+last 1' ) ;
  3107. ok( add_to_requested_folders('M_55', 'M_44',), 'add_to_requested_folders M_55 M_44' );
  3108. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_44', 'M_55', 'A_99' ] ), 'sort_requested_folders: first+middle+last 2' ) ;
  3109. @folderfirst = qw( Z_22 Z_11 ) ;
  3110. @folderlast = qw( A_99 A_88 ) ;
  3111. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_22', 'Z_11', 'M_44', 'M_55', 'A_99', 'A_88' ] ), 'sort_requested_folders: first+middle+last 3' ) ;
  3112. return ;
  3113. }
  3114. sub sort_requested_folders {
  3115. my @requested_folders_sorted = () ;
  3116. foreach my $folder ( @folderfirst ) {
  3117. remove_from_requested_folders( $folder ) ;
  3118. }
  3119. foreach my $folder ( @folderlast ) {
  3120. remove_from_requested_folders( $folder ) ;
  3121. }
  3122. my @middle = sort keys %requested_folder ;
  3123. @requested_folders_sorted = ( @folderfirst, @middle, @folderlast ) ;
  3124. return( @requested_folders_sorted ) ;
  3125. }
  3126. sub is_requested_folder {
  3127. my ( $folder ) = @_;
  3128. return( defined $requested_folder{ $folder } ) ;
  3129. }
  3130. sub add_to_requested_folders {
  3131. my @wanted_folders = @_ ;
  3132. foreach my $folder ( @wanted_folders ) {
  3133. ++$requested_folder{ $folder } ;
  3134. }
  3135. return( keys %requested_folder ) ;
  3136. }
  3137. sub remove_from_requested_folders {
  3138. my @wanted_folders = @_ ;
  3139. foreach my $folder ( @wanted_folders ) {
  3140. delete $requested_folder{ $folder } ;
  3141. }
  3142. return( keys %requested_folder ) ;
  3143. }
  3144. sub compare_lists {
  3145. my ($list_1_ref, $list_2_ref) = @_;
  3146. return($MINUS_ONE) if ((not defined $list_1_ref) and defined $list_2_ref);
  3147. return(0) if ((not defined $list_1_ref) and not defined $list_2_ref); # end if no list
  3148. return(1) if (not defined $list_2_ref); # end if only one list
  3149. if (not ref $list_1_ref ) {$list_1_ref = [$list_1_ref]};
  3150. if (not ref $list_2_ref ) {$list_2_ref = [$list_2_ref]};
  3151. my $last_used_indice = $MINUS_ONE;
  3152. ELEMENT:
  3153. foreach my $indice ( 0 .. $#{ $list_1_ref } ) {
  3154. $last_used_indice = $indice ;
  3155. # End of list_2
  3156. return 1 if ($indice > $#{ $list_2_ref } ) ;
  3157. my $element_list_1 = $list_1_ref->[$indice] ;
  3158. my $element_list_2 = $list_2_ref->[$indice] ;
  3159. my $balance = $element_list_1 cmp $element_list_2 ;
  3160. next ELEMENT if ($balance == 0) ;
  3161. return $balance ;
  3162. }
  3163. # each element equal until last indice of list_1
  3164. return $MINUS_ONE if ($last_used_indice < $#{ $list_2_ref } ) ;
  3165. # same size, each element equal
  3166. return 0 ;
  3167. }
  3168. sub tests_compare_lists {
  3169. my $empty_list_ref = [];
  3170. ok( 0 == compare_lists() , 'compare_lists, no args');
  3171. ok( 0 == compare_lists(undef) , 'compare_lists, undef = nothing');
  3172. ok( 0 == compare_lists(undef, undef) , 'compare_lists, undef = undef');
  3173. ok($MINUS_ONE == compare_lists(undef , []) , 'compare_lists, undef < []');
  3174. ok($MINUS_ONE == compare_lists(undef , [1]) , 'compare_lists, undef < [1]');
  3175. ok($MINUS_ONE == compare_lists(undef , [0]) , 'compare_lists, undef < [0]');
  3176. ok(+1 == compare_lists([]) , 'compare_lists, [] > nothing');
  3177. ok(+1 == compare_lists([], undef) , 'compare_lists, [] > undef');
  3178. ok( 0 == compare_lists([] , []) , 'compare_lists, [] = []');
  3179. ok($MINUS_ONE == compare_lists([] , [1]) , 'compare_lists, [] < [1]');
  3180. ok(+1 == compare_lists([1] , []) , 'compare_lists, [1] > []');
  3181. ok( 0 == compare_lists([1], 1 ) , 'compare_lists, [1] = 1 ') ;
  3182. ok( 0 == compare_lists( 1 , [1]) , 'compare_lists, 1 = [1]') ;
  3183. ok( 0 == compare_lists( 1 , 1 ) , 'compare_lists, 1 = 1 ') ;
  3184. ok($MINUS_ONE == compare_lists( 0 , 1 ) , 'compare_lists, 0 < 1 ') ;
  3185. ok($MINUS_ONE == compare_lists($MINUS_ONE , 0 ) , 'compare_lists, -1 < 0 ') ;
  3186. ok($MINUS_ONE == compare_lists( 1 , 2 ) , 'compare_lists, 1 < 2 ') ;
  3187. ok(+1 == compare_lists( 2 , 1 ) , 'compare_lists, 2 > 1 ') ;
  3188. ok( 0 == compare_lists([1,2], [1,2]) , 'compare_lists, [1,2] = [1,2]' ) ;
  3189. ok($MINUS_ONE == compare_lists([1], [1,2]) , 'compare_lists, [1] < [1,2]' ) ;
  3190. ok(+1 == compare_lists([2], [1,2]) , 'compare_lists, [2] > [1,2]' ) ;
  3191. ok($MINUS_ONE == compare_lists([1], [1,1]) , 'compare_lists, [1] < [1,1]' ) ;
  3192. ok(+1 == compare_lists([1, 1], [1]) , 'compare_lists, [1, 1] > [1]' ) ;
  3193. ok( 0 == compare_lists([1 .. $NUMBER_20_000] , [1 .. $NUMBER_20_000])
  3194. , 'compare_lists, [1..20_000] = [1..20_000]' ) ;
  3195. ok($MINUS_ONE == compare_lists([1], [2]) , 'compare_lists, [1] < [2]') ;
  3196. ok( 0 == compare_lists([2], [2]) , 'compare_lists, [0] = [2]') ;
  3197. ok(+1 == compare_lists([2], [1]) , 'compare_lists, [2] > [1]') ;
  3198. ok($MINUS_ONE == compare_lists(['a'], ['b']) , 'compare_lists, ["a"] < ["b"]') ;
  3199. ok( 0 == compare_lists(['a'], ['a']) , 'compare_lists, ["a"] = ["a"]') ;
  3200. ok( 0 == compare_lists(['ab'], ['ab']) , 'compare_lists, ["ab"] = ["ab"]') ;
  3201. ok(+1 == compare_lists(['b'], ['a']) , 'compare_lists, ["b"] > ["a"]') ;
  3202. ok($MINUS_ONE == compare_lists(['a'], ['aa']) , 'compare_lists, ["a"] < ["aa"]') ;
  3203. ok($MINUS_ONE == compare_lists(['a'], ['a', 'a']), 'compare_lists, ["a"] < ["a", "a"]') ;
  3204. ok( 0 == compare_lists([split q{ }, 'a b' ], ['a', 'b']), 'compare_lists, split') ;
  3205. ok( 0 == compare_lists([sort split q{ }, 'b a' ], ['a', 'b']), 'compare_lists, sort split') ;
  3206. return ;
  3207. }
  3208. sub guess_prefix {
  3209. my @foldernames = @_ ;
  3210. return( undef ) unless ( @foldernames ) ;
  3211. my $prefix_guessed = q{} ;
  3212. foreach my $folder ( @foldernames ) {
  3213. next if ( $folder =~ m{^INBOX$}i ) ; # no guessing from INBOX
  3214. if ( $folder !~ m{^INBOX}i ) {
  3215. $prefix_guessed = q{} ; # prefix empty guessed
  3216. last ;
  3217. }
  3218. if ( $folder =~ m{^(INBOX(?:\.|\/))}i ) {
  3219. $prefix_guessed = $1 ; # prefix Inbox/ or INBOX. guessed
  3220. }
  3221. }
  3222. return( $prefix_guessed ) ;
  3223. }
  3224. sub tests_guess_prefix {
  3225. ok( not( defined guess_prefix( ) ), 'guess_prefix: no args' ) ;
  3226. ok( q{} eq guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  3227. ok( q{} eq guess_prefix( 'Inbox' ), 'guess_prefix: Inbox alone' ) ;
  3228. ok( q{} eq guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  3229. ok( 'INBOX/' eq guess_prefix( 'INBOX', 'INBOX/Junk' ), 'guess_prefix: INBOX INBOX/Junk' ) ;
  3230. ok( 'INBOX.' eq guess_prefix( 'INBOX', 'INBOX.Junk' ), 'guess_prefix: INBOX INBOX.Junk' ) ;
  3231. ok( 'Inbox/' eq guess_prefix( 'Inbox', 'Inbox/Junk' ), 'guess_prefix: Inbox Inbox/Junk' ) ;
  3232. ok( 'Inbox.' eq guess_prefix( 'Inbox', 'Inbox.Junk' ), 'guess_prefix: Inbox Inbox.Junk' ) ;
  3233. ok( 'INBOX/' eq guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr' ) ;
  3234. ok( q{} eq guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr', 'zzz' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr zzz' ) ;
  3235. ok( q{} eq guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  3236. ok( q{} eq guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  3237. return ;
  3238. }
  3239. sub get_prefix {
  3240. my( $imap, $prefix_in, $prefix_opt, $Side, $folders_ref ) = @_ ;
  3241. my( $prefix_out, $prefix_guessed ) ;
  3242. ( $debug or $sync->{debugfolders} ) and myprint( "$Side: Getting prefix\n" ) ;
  3243. $prefix_guessed = guess_prefix( @{ $folders_ref } ) ;
  3244. myprint( "$Side: guessing prefix from folder listing: [$prefix_guessed]\n" ) ;
  3245. ( $debug or $sync->{debugfolders} ) and myprint( "$Side: Calling namespace capability\n" ) ;
  3246. if ( $imap->has_capability( 'namespace' ) ) {
  3247. my $r_namespace = $imap->namespace( ) ;
  3248. $prefix_out = $r_namespace->[0][0][0] ;
  3249. myprint( "$Side: prefix given by NAMESPACE: [$prefix_out]\n" ) ;
  3250. if ( defined $prefix_in ) {
  3251. myprint( "$Side: but using [$prefix_in] given by $prefix_opt\n" ) ;
  3252. $prefix_out = $prefix_in ;
  3253. return( $prefix_out ) ;
  3254. }else{
  3255. # all good
  3256. return( $prefix_out ) ;
  3257. }
  3258. }
  3259. else{
  3260. if ( defined $prefix_in ) {
  3261. myprint( "$Side: using [$prefix_in] given by $prefix_opt\n" ) ;
  3262. $prefix_out = $prefix_in ;
  3263. return( $prefix_out ) ;
  3264. }else{
  3265. myprint(
  3266. "$Side: No NAMESPACE capability so using guessed prefix [$prefix_guessed]\n",
  3267. help_to_guess_prefix( $imap, $prefix_opt ) ) ;
  3268. return( $prefix_guessed ) ;
  3269. }
  3270. }
  3271. return ;
  3272. }
  3273. sub guess_separator {
  3274. my @foldernames = @_ ;
  3275. #return( undef ) unless ( @foldernames ) ;
  3276. my $sep_guessed ;
  3277. my %counter ;
  3278. foreach my $folder ( @foldernames ) {
  3279. $counter{'/'}++ while ( $folder =~ m{/}g ) ; # count /
  3280. $counter{'.'}++ while ( $folder =~ m{\.}g ) ; # count .
  3281. $counter{'\\\\'}++ while ( $folder =~ m{(\\){2}}g ) ; # count \\
  3282. }
  3283. my @race_sorted = sort { $counter{ $b } <=> $counter{ $a } } keys %counter ;
  3284. #myprint( "@race_sorted\n" ) ;
  3285. $sep_guessed = shift @race_sorted || $LAST_RESSORT_SEPARATOR ; # / when nothing found.
  3286. return( $sep_guessed ) ;
  3287. }
  3288. sub tests_guess_separator {
  3289. ok( '/' eq guess_separator( ), 'guess_separator: no args' ) ;
  3290. ok( '/' eq guess_separator( 'abcd' ), 'guess_separator: abcd' ) ;
  3291. ok( '/' eq guess_separator( 'a/b/c.d' ), 'guess_separator: a/b/c.d' ) ;
  3292. ok( '.' eq guess_separator( 'a.b/c.d' ), 'guess_separator: a.b/c.d' ) ;
  3293. ok( '\\\\' eq guess_separator( 'a\\\\b\\\\c.c\\\\d/e/f' ), 'guess_separator: a\\\\b\\\\c.c\\\\d/e/f' ) ;
  3294. return ;
  3295. }
  3296. sub get_separator {
  3297. my( $imap, $sep_in, $sep_opt, $Side, $folders_ref ) = @_ ;
  3298. my( $sep_out, $sep_guessed ) ;
  3299. ( $debug or $sync->{debugfolders} ) and myprint( "$Side: Getting separator\n" ) ;
  3300. $sep_guessed = guess_separator( @{ $folders_ref } ) ;
  3301. myprint( "$Side: guessing separator from folder listing: [$sep_guessed]\n" ) ;
  3302. ( $debug or $sync->{debugfolders} ) and myprint( "$Side: calling namespace capability\n" ) ;
  3303. if ( $imap->has_capability( 'namespace' ) ) {
  3304. $sep_out = $imap->separator( ) ;
  3305. if ( defined $sep_out ) {
  3306. myprint( "$Side: separator given by NAMESPACE: [$sep_out]\n" ) ;
  3307. if ( defined $sep_in ) {
  3308. myprint( "$Side: but using [$sep_in] given by $sep_opt\n" ) ;
  3309. $sep_out = $sep_in ;
  3310. return( $sep_out ) ;
  3311. }else{
  3312. return( $sep_out ) ;
  3313. }
  3314. }else{
  3315. if ( defined $sep_in ) {
  3316. myprint( "$Side: NAMESPACE request failed but using [$sep_in] given by $sep_opt\n" ) ;
  3317. $sep_out = $sep_in ;
  3318. return( $sep_out ) ;
  3319. }else{
  3320. myprint(
  3321. "$Side: NAMESPACE request failed so using guessed separator [$sep_guessed]\n",
  3322. help_to_guess_sep( $imap, $sep_opt ) ) ;
  3323. return( $sep_guessed ) ;
  3324. }
  3325. }
  3326. }
  3327. else{
  3328. if ( defined $sep_in ) {
  3329. myprint( "$Side: No NAMESPACE capability but using [$sep_in] given by $sep_opt\n" ) ;
  3330. $sep_out = $sep_in ;
  3331. return( $sep_out ) ;
  3332. }else{
  3333. myprint(
  3334. "$Side: No NAMESPACE capability, so using guessed separator [$sep_guessed]\n",
  3335. help_to_guess_sep( $imap, $sep_opt ) ) ;
  3336. return( $sep_guessed ) ;
  3337. }
  3338. }
  3339. return ;
  3340. }
  3341. sub help_to_guess_sep {
  3342. my( $imap, $sep_opt ) = @_ ;
  3343. my $help_to_guess_sep = "You can set the separator character with the $sep_opt option,\n"
  3344. . "the complete listing of folders may help you to find it\n"
  3345. . folders_list_to_help( $imap ) ;
  3346. return( $help_to_guess_sep ) ;
  3347. }
  3348. sub help_to_guess_prefix {
  3349. my( $imap, $prefix_opt ) = @_ ;
  3350. my $help_to_guess_prefix = "You can set the prefix namespace with the $prefix_opt option,\n"
  3351. . "the folowing listing of folders may help you to find it:\n"
  3352. . folders_list_to_help( $imap ) ;
  3353. return( $help_to_guess_prefix ) ;
  3354. }
  3355. sub folders_list_to_help {
  3356. my($imap) = @_ ;
  3357. my @folders = $imap->folders ;
  3358. my $listing = join q{}, map { "[$_]\n" } @folders ;
  3359. return( $listing ) ;
  3360. }
  3361. sub tests_separator_invert {
  3362. $fixslash2 = 0 ;
  3363. ok( not( defined separator_invert( ) ), 'separator_invert: no args' ) ;
  3364. ok( not( defined separator_invert( q{} ) ), 'separator_invert: not enough args' ) ;
  3365. ok( not( defined separator_invert( q{}, q{} ) ), 'separator_invert: not enough args' ) ;
  3366. ok( q{} eq separator_invert( q{}, q{}, q{} ), 'separator_invert: 3 empty strings' ) ;
  3367. ok( 'lalala' eq separator_invert( 'lalala', q{}, q{} ), 'separator_invert: empty separator' ) ;
  3368. ok( 'lalala' eq separator_invert( 'lalala', '/', '/' ), 'separator_invert: same separator /' ) ;
  3369. ok( 'lal/ala' eq separator_invert( 'lal/ala', '/', '/' ), 'separator_invert: same separator / 2' ) ;
  3370. ok( 'lal.ala' eq separator_invert( 'lal/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  3371. ok( 'lal/ala' eq separator_invert( 'lal.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  3372. ok( 'la.l/ala' eq separator_invert( 'la/l.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  3373. ok( 'l/al.ala' eq separator_invert( 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  3374. $fixslash2 = 1 ;
  3375. ok( 'l_al.ala' eq separator_invert( 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  3376. return ;
  3377. }
  3378. sub separator_invert {
  3379. my( $h1_fold, $h1_separator, $h2_separator ) = @_ ;
  3380. return( undef ) if ( not defined $h1_fold or not defined $h1_separator or not defined $h2_separator ) ;
  3381. # The separator we hope we'll never encounter: 00000000 == 0x00
  3382. my $o_sep = "\000" ;
  3383. my $h2_fold = $h1_fold ;
  3384. $h2_fold =~ s,\Q$h2_separator,$o_sep,xg ;
  3385. $h2_fold =~ s,\Q$h1_separator,$h2_separator,xg ;
  3386. $h2_fold =~ s,\Q$o_sep,$h1_separator,xg ;
  3387. $h2_fold =~ s,/,_,xg if( $fixslash2 and '/' ne $h2_separator and '/' eq $h1_separator ) ;
  3388. return( $h2_fold ) ;
  3389. }
  3390. sub tests_imap2_folder_name {
  3391. $h1_prefix = $h2_prefix = q{};
  3392. $h1_sep = '/';
  3393. $h2_sep = '.';
  3394. $debug and myprint( <<"EOS"
  3395. prefix1: [$h1_prefix]
  3396. prefix2: [$h2_prefix]
  3397. sep1:[$h1_sep]
  3398. sep2:[$h2_sep]
  3399. EOS
  3400. ) ;
  3401. $fixslash2 = 0 ;
  3402. ok(q{} eq imap2_folder_name(q{}), 'imap2_folder_name: empty string');
  3403. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla');
  3404. ok('spam.spam' eq imap2_folder_name('spam/spam'), 'imap2_folder_name: spam/spam');
  3405. ok('spam/spam' eq imap2_folder_name('spam.spam'), 'imap2_folder_name: spam.spam');
  3406. ok('spam.spam/spam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam');
  3407. ok('s pam.spam/sp am' eq imap2_folder_name('s pam/spam.sp am'), 'imap2_folder_name: s pam/spam.sp am');
  3408. $sync->{f1f2}{ 'auto' } = 'moto' ;
  3409. ok( 'moto' eq imap2_folder_name( 'auto' ), 'imap2_folder_name: auto' ) ;
  3410. $sync->{f1f2}{ 'auto/auto' } = 'moto x 2' ;
  3411. ok( 'moto x 2' eq imap2_folder_name( 'auto/auto' ), 'imap2_folder_name: auto/auto' ) ;
  3412. @regextrans2 = ('s,/,X,g');
  3413. ok(q{} eq imap2_folder_name(q{}), 'imap2_folder_name: empty string [s,/,X,g]');
  3414. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla [s,/,X,g]');
  3415. ok('spam.spam' eq imap2_folder_name('spam/spam'), 'imap2_folder_name: spam/spam [s,/,X,g]');
  3416. ok('spamXspam' eq imap2_folder_name('spam.spam'), 'imap2_folder_name: spam.spam [s,/,X,g]');
  3417. ok('spam.spamXspam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam [s,/,X,g]');
  3418. @regextrans2 = ( 's, ,_,g' ) ;
  3419. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla [s, ,_,g]');
  3420. ok('bla_bla' eq imap2_folder_name('bla bla'), 'imap2_folder_name: blabla [s, ,_,g]');
  3421. @regextrans2 = ( q{s,(.*),\U$1,} ) ;
  3422. ok( 'BLABLA' eq imap2_folder_name( 'blabla' ), q{imap2_folder_name: blabla [s,\U(.*)\E,$1,]} ) ;
  3423. $fixslash2 = 1 ;
  3424. @regextrans2 = ( ) ;
  3425. ok(q{} eq imap2_folder_name(q{}), 'imap2_folder_name: empty string');
  3426. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla');
  3427. ok('spam.spam' eq imap2_folder_name('spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  3428. ok('spam_spam' eq imap2_folder_name('spam.spam'), 'imap2_folder_name: spam.spam -> spam_spam');
  3429. ok('spam.spam_spam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam_spam');
  3430. ok('s pam.spam_spa m' eq imap2_folder_name('s pam/spam.spa m'), 'imap2_folder_name: s pam/spam.spa m -> s pam.spam_spa m');
  3431. $h1_sep = '.';
  3432. $h2_sep = '/';
  3433. ok(q{} eq imap2_folder_name(q{}), 'imap2_folder_name: empty string');
  3434. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla');
  3435. ok('spam.spam' eq imap2_folder_name('spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  3436. ok('spam/spam' eq imap2_folder_name('spam.spam'), 'imap2_folder_name: spam.spam -> spam/spam');
  3437. ok('spam.spam/spam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam');
  3438. $fixslash2 = 0 ;
  3439. $h1_prefix = q{ };
  3440. ok('spam.spam/spam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam');
  3441. ok('spam.spam/spam' eq imap2_folder_name(' spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam');
  3442. $h1_sep = '.' ;
  3443. $h2_sep = '/' ;
  3444. $h1_prefix = 'INBOX.' ;
  3445. $h2_prefix = q{} ;
  3446. @regextrans2 = ( q{s,(.*),\U$1,} ) ;
  3447. ok( 'BLABLA' eq imap2_folder_name( 'blabla' ), 'imap2_folder_name: blabla' ) ;
  3448. ok( 'TEST/TEST/TEST/TEST' eq imap2_folder_name( 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  3449. @regextrans2 = ( q{s,(.*),\L$1,} ) ;
  3450. ok( 'test/test/test/test' eq imap2_folder_name( 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  3451. return ;
  3452. }
  3453. sub imap2_folder_name {
  3454. my ( $h1_fold ) = @_ ;
  3455. my ( $h2_fold ) ;
  3456. if ( $sync->{f1f2}{ $h1_fold } ) {
  3457. $h2_fold = $sync->{f1f2}{ $h1_fold } ;
  3458. ( $debug or $sync->{debugfolders} ) and myprint( "f1f2 [$h1_fold] -> [$h2_fold]\n" ) ;
  3459. return( $h2_fold ) ;
  3460. }
  3461. if ( $sync->{f1f2auto}{ $h1_fold } ) {
  3462. $h2_fold = $sync->{f1f2auto}{ $h1_fold } ;
  3463. ( $debug or $sync->{debugfolders} ) and myprint( "automap [$h1_fold] -> [$h2_fold]\n" ) ;
  3464. return( $h2_fold ) ;
  3465. }
  3466. $h2_fold = prefix_seperator_invertion( $h1_fold ) ;
  3467. $h2_fold = regextrans2( $h2_fold ) ;
  3468. return( $h2_fold ) ;
  3469. }
  3470. sub prefix_seperator_invertion {
  3471. my ( $h1_fold ) = @_ ;
  3472. my ( $h2_fold ) ;
  3473. # first we remove the prefix
  3474. $h1_fold =~ s/^\Q$h1_prefix\E//x ;
  3475. ( $debug or $sync->{debugfolders} ) and myprint( "removed host1 prefix: [$h1_fold]\n" ) ;
  3476. $h2_fold = separator_invert( $h1_fold, $h1_sep, $h2_sep ) ;
  3477. ( $debug or $sync->{debugfolders} ) and myprint( "inverted separators: [$h2_fold]\n" ) ;
  3478. # Adding the prefix supplied by namespace or the --prefix2 option
  3479. $h2_fold = $h2_prefix . $h2_fold
  3480. unless( ( $h2_prefix eq 'INBOX' . $h2_sep ) and ( $h2_fold =~ m/^INBOX$/xi ) ) ;
  3481. ( $debug or $sync->{debugfolders} ) and myprint( "added host2 prefix: [$h2_fold]\n" ) ;
  3482. return( $h2_fold ) ;
  3483. }
  3484. sub regextrans2 {
  3485. my( $h2_fold ) = @_ ;
  3486. # Transforming the folder name by the --regextrans2 option(s)
  3487. foreach my $regextrans2 ( @regextrans2 ) {
  3488. my $h2_fold_before = $h2_fold ;
  3489. my $ret = eval "\$h2_fold =~ $regextrans2 ; 1 " ;
  3490. ( $debug or $sync->{debugfolders} ) and myprint( "[$h2_fold_before] -> [$h2_fold] using regextrans2 [$regextrans2]\n" ) ;
  3491. if ( not ( defined $ret ) or $@ ) {
  3492. die_clean( "error: eval regextrans2 '$regextrans2': $@\n" ) ;
  3493. }
  3494. }
  3495. return( $h2_fold ) ;
  3496. }
  3497. sub tests_decompose_regex {
  3498. ok( 1, 'decompose_regex 1' ) ;
  3499. ok( 0 == compare_lists( [ q{}, q{} ], [ decompose_regex( q{} ) ] ), 'decompose_regex empty string' ) ;
  3500. ok( 0 == compare_lists( [ '.*', 'lala' ], [ decompose_regex( 's/.*/lala/' ) ] ), 'decompose_regex s/.*/lala/' ) ;
  3501. return ;
  3502. }
  3503. sub decompose_regex {
  3504. my $regex = shift ;
  3505. my( $left_part, $right_part ) ;
  3506. ( $left_part, $right_part ) = $regex =~ m{^s/((?:[^/]|\\/)+)/((?:[^/]|\\/)+)/}x;
  3507. return( q{}, q{} ) if not $left_part ;
  3508. return( $left_part, $right_part ) ;
  3509. }
  3510. sub foldersizes {
  3511. my ( $side, $imap, $search_cmd, @folders ) = @_ ;
  3512. my $total_size = 0 ;
  3513. my $total_nb = 0 ;
  3514. my $biggest_in_all = 0 ;
  3515. my $nb_folders = scalar @folders ;
  3516. my $ct_folders = 0 ; # folder counter.
  3517. myprint( "++++ Calculating sizes of $nb_folders folders on $side\n" ) ;
  3518. foreach my $folder ( @folders ) {
  3519. my $stot = 0 ;
  3520. my $nb_msgs = 0 ;
  3521. $ct_folders++ ;
  3522. myprintf( "$side folder %7s %-35s", "$ct_folders/$nb_folders", jux_utf8( $folder ) ) ;
  3523. if ( 'Host2' eq $side and not exists $h2_folders_all_UPPER{ uc $folder } ) {
  3524. myprint( " does not exist yet\n") ;
  3525. next ;
  3526. }
  3527. if ( 'Host1' eq $side and not exists $h1_folders_all{ $folder } ) {
  3528. myprint( " does not exist\n" ) ;
  3529. next ;
  3530. }
  3531. last if $imap->IsUnconnected( ) ;
  3532. # FTGate is RFC buggy with EXAMINE it does not act as SELECT
  3533. #unless ( $imap->examine( $folder ) ) {
  3534. unless ( $imap->select( $folder ) ) {
  3535. my $error = join q{},
  3536. "$side Folder $folder: Could not select: ",
  3537. $imap->LastError, "\n" ;
  3538. errors_incr( $sync, $error ) ;
  3539. next ;
  3540. }
  3541. last if $imap->IsUnconnected( ) ;
  3542. my $hash_ref = { } ;
  3543. my @msgs = select_msgs( $imap, undef, $search_cmd, $folder ) ;
  3544. $nb_msgs = scalar @msgs ;
  3545. my $biggest_in_folder = 0 ;
  3546. @{ $hash_ref }{ @msgs } = ( undef ) if @msgs ;
  3547. last if $imap->IsUnconnected( ) ;
  3548. if ( $nb_msgs > 0 and @msgs ) {
  3549. if ( $abletosearch ) {
  3550. if ( ! $imap->fetch_hash( \@msgs, 'RFC822.SIZE', $hash_ref) ) {
  3551. my $error = "$side failure with fetch_hash: $@" ;
  3552. errors_incr( $sync, $error ) ;
  3553. return ;
  3554. }
  3555. }else{
  3556. my $uidnext = $imap->uidnext( $folder ) || $uidnext_default ;
  3557. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  3558. if ( ! $imap->fetch_hash( $fetch_hash_uids, 'RFC822.SIZE', $hash_ref ) ) {
  3559. my $error = "$side failure with fetch_hash: $@" ;
  3560. errors_incr( $sync, $error ) ;
  3561. return ;
  3562. }
  3563. }
  3564. for ( keys %{ $hash_ref } ) {
  3565. my $size = $hash_ref->{ $_ }->{ 'RFC822.SIZE' } ;
  3566. $stot += $size ;
  3567. $biggest_in_folder = max( $biggest_in_folder, $size ) ;
  3568. }
  3569. }
  3570. myprintf( ' Size: %9s', $stot ) ;
  3571. myprintf( ' Messages: %5s', $nb_msgs ) ;
  3572. myprintf( " Biggest: %9s\n", $biggest_in_folder ) ;
  3573. $total_size += $stot ;
  3574. $total_nb += $nb_msgs ;
  3575. $biggest_in_all = max( $biggest_in_all, $biggest_in_folder ) ;
  3576. }
  3577. myprintf( "%s Nb folders: %11s folders\n", $side, $nb_folders ) ;
  3578. myprintf( "%s Nb messages: %11s messages\n", $side, $total_nb ) ;
  3579. myprintf( "%s Total size: %11s bytes (%s)\n", $side, $total_size, bytes_display_string( $total_size ) ) ;
  3580. myprintf( "%s Biggest message: %11s bytes (%s)\n", $side, $biggest_in_all, bytes_display_string( $biggest_in_all ) ) ;
  3581. myprintf( "%s Time spent: %11.1f seconds\n", $side, timenext( ) ) ;
  3582. return( $total_nb, $total_size ) ;
  3583. }
  3584. sub timenext {
  3585. my ( $timenow, $timediff ) ;
  3586. # $timebefore is global, beurk !
  3587. $timenow = time ;
  3588. $timediff = $timenow - $timebefore ;
  3589. $timebefore = $timenow ;
  3590. return( $timediff ) ;
  3591. }
  3592. sub timesince {
  3593. my $timeinit = shift ;
  3594. my ( $timenow, $timediff ) ;
  3595. $timenow = time ;
  3596. $timediff = $timenow - $timeinit ;
  3597. return( $timediff ) ;
  3598. }
  3599. sub tests_flags_regex {
  3600. ok( q{} eq flags_regex(q{} ), 'flags_regex, null string q{}' ) ;
  3601. ok( q'\Seen NonJunk $Spam' eq flags_regex( q'\Seen NonJunk $Spam' ), 'flags_regex, nothing to do');
  3602. @regexflag = ('I am BAD' ) ;
  3603. ok( not ( defined flags_regex( q{} ) ), 'flags_regex, bad regex' ) ;
  3604. @regexflag = ( 's/NonJunk//g' ) ;
  3605. ok( q'\Seen $Spam' eq flags_regex( q'\Seen NonJunk $Spam' ), q{flags_regex, remove NonJunk: 's/NonJunk//g'} ) ;
  3606. @regexflag = ( q's/\$Spam//g' ) ;
  3607. ok( '\Seen NonJunk ' eq flags_regex( q'\Seen NonJunk $Spam' ), q{flags_regex, remove $Spam: 's/\$Spam//g'} ) ;
  3608. @regexflag = ( 's/\\\\Seen//g' ) ;
  3609. ok( q' NonJunk $Spam' eq flags_regex( q'\Seen NonJunk $Spam' ), q{flags_regex, remove \Seen: 's/\\\\\\\\Seen//g'} ) ;
  3610. @regexflag = ( 's/(\s|^)[^\\\\]\w+//g' ) ;
  3611. ok( '\Seen \Middle \End' eq flags_regex( q'\Seen NonJunk \Middle $Spam \End' ), q{flags_regex: only \word among \Seen NonJunk \Middle $Spam \End} ) ;
  3612. ok( ' \Seen \Middle \End1' eq flags_regex( q'Begin \Seen NonJunk \Middle $Spam \End1 End' ),
  3613. q'flags_regex: only \word among Begin \Seen NonJunk \Middle $Spam \End1 End' ) ;
  3614. @regexflag = ( q's/.*?(Keep1|Keep2|Keep3)/$1 /g' ) ;
  3615. ok('Keep1 Keep2 ReB' eq flags_regex('ReA Keep1 REM Keep2 ReB'), 'Keep only regex' ) ;
  3616. ok('Keep1 Keep2 ' eq flags_regex( 'REM REM Keep1 Keep2'), 'Keep only regex' ) ;
  3617. ok('Keep1 Keep2 ' eq flags_regex( 'Keep1 REM REM Keep2'), 'Keep only regex' ) ;
  3618. ok('Keep1 Keep2 ' eq flags_regex( 'REM Keep1 REM REM Keep2'), 'Keep only regex' ) ;
  3619. ok('Keep1 Keep2 ' eq flags_regex( 'Keep1 Keep2'), 'Keep only regex' ) ;
  3620. ok('Keep1 ' eq flags_regex( 'REM Keep1'), 'Keep only regex' ) ;
  3621. @regexflag = ( q's/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g' ) ;
  3622. ok('Keep1 Keep2 ' eq flags_regex( 'Keep1 Keep2 ReB'), 'Keep only regex' ) ;
  3623. ok('Keep1 Keep2 ' eq flags_regex( 'Keep1 Keep2 REM REM REM'), 'Keep only regex' ) ;
  3624. ok('Keep2 ' eq flags_regex('Keep2 REM REM REM'), 'Keep only regex' ) ;
  3625. @regexflag = ( q's/.*?(Keep1|Keep2|Keep3)/$1 /g',
  3626. 's/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g');
  3627. ok('Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2 REM'), 'Keep only regex');
  3628. ok('Keep1 Keep2 ' eq flags_regex('Keep1 REM Keep2 REM'), 'Keep only regex');
  3629. ok('Keep1 Keep2 ' eq flags_regex('REM Keep1 Keep2 REM'), 'Keep only regex');
  3630. ok('Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2'), 'Keep only regex');
  3631. ok('Keep1 Keep2 Keep3 ' eq flags_regex('REM Keep1 REM Keep2 REM REM Keep3 REM'), 'Keep only regex');
  3632. ok('Keep1 ' eq flags_regex('REM REM Keep1 REM REM REM '), 'Keep only regex');
  3633. ok('Keep1 Keep3 ' eq flags_regex('RE1 Keep1 RE2 Keep3 RE3 RE4 RE5 '), 'Keep only regex');
  3634. @regexflag = ('s/(.*)/$1 jrdH8u/');
  3635. ok('REM REM REM REM REM jrdH8u' eq flags_regex('REM REM REM REM REM'), q{Keep only regex 's/(.*)/\$1 jrdH8u/'} ) ;
  3636. @regexflag = ('s/jrdH8u *//');
  3637. ok('REM REM REM REM REM ' eq flags_regex('REM REM REM REM REM jrdH8u'), q{Keep only regex s/jrdH8u *//} ) ;
  3638. @regexflag = (
  3639. 's/(.*)/$1 jrdH8u/',
  3640. 's/.*?(Keep1|Keep2|Keep3|jrdH8u)/$1 /g',
  3641. 's/(Keep1|Keep2|Keep3|jrdH8u) (?!(Keep1|Keep2|Keep3|jrdH8u)).*/$1 /g',
  3642. 's/jrdH8u *//'
  3643. );
  3644. ok('Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2 REM'), q{Keep only regex 'REM Keep1 REM Keep2 REM'} ) ;
  3645. ok('Keep1 Keep2 ' eq flags_regex('Keep1 REM Keep2 REM'), 'Keep only regex');
  3646. ok('Keep1 Keep2 ' eq flags_regex('REM Keep1 Keep2 REM'), 'Keep only regex');
  3647. ok('Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2'), 'Keep only regex');
  3648. ok('Keep1 Keep2 Keep3 ' eq flags_regex('REM Keep1 REM Keep2 REM REM Keep3 REM'), 'Keep only regex');
  3649. ok('Keep1 ' eq flags_regex('REM REM Keep1 REM REM REM '), 'Keep only regex');
  3650. ok('Keep1 Keep3 ' eq flags_regex('RE1 Keep1 RE2 Keep3 RE3 RE4 RE5 '), 'Keep only regex');
  3651. ok(q{} eq flags_regex('REM REM REM REM REM'), 'Keep only regex');
  3652. @regexflag = (
  3653. 's/(.*)/$1 jrdH8u/',
  3654. 's/.*?(\\\\Seen|\\\\Answered|\\\\Flagged|\\\\Deleted|\\\\Draft|jrdH8u)/$1 /g',
  3655. 's/(\\\\Seen|\\\\Answered|\\\\Flagged|\\\\Deleted|\\\\Draft|jrdH8u) (?!(\\\\Seen|\\\\Answered|\\\\Flagged|\\\\Deleted|\\\\Draft|jrdH8u)).*/$1 /g',
  3656. 's/jrdH8u *//'
  3657. );
  3658. ok('\\Deleted \\Answered '
  3659. eq flags_regex('Blabla $Junk \\Deleted machin \\Answered truc'), 'Keep only regex: Exchange case' ) ;
  3660. ok( q{} eq flags_regex( q{} ), 'Keep only regex: Exchange case, null string' ) ;
  3661. ok( q{}
  3662. eq flags_regex('Blabla $Junk machin truc'), 'Keep only regex: Exchange case, no accepted flags' ) ;
  3663. ok( '\\Deleted \\Answered \\Draft \\Flagged '
  3664. eq flags_regex('\\Deleted \\Answered \\Draft \\Flagged '), 'Keep only regex: Exchange case' ) ;
  3665. @regexflag = (
  3666. 's/.*?(?:(\\\\(?:Answered|Flagged|Deleted|Seen|Draft)\s?)|$)/defined($1)?$1:q()/eg'
  3667. );
  3668. ok( '\\Deleted \\Answered '
  3669. eq flags_regex('Blabla \$Junk \\Deleted machin \\Answered truc'),
  3670. 'Keep only regex: Exchange case (Phil)' ) ;
  3671. ok( q{} eq flags_regex( q{} ), 'Keep only regex: Exchange case, null string (Phil)' ) ;
  3672. ok( q{}
  3673. eq flags_regex('Blabla $Junk machin truc'),
  3674. 'Keep only regex: Exchange case, no accepted flags (Phil)' ) ;
  3675. ok('\\Deleted \\Answered \\Draft \\Flagged '
  3676. eq flags_regex('\\Deleted \\Answered \\Draft \\Flagged '),
  3677. 'Keep only regex: Exchange case (Phil)' ) ;
  3678. return ;
  3679. }
  3680. sub flags_regex {
  3681. my ( $h1_flags ) = @_ ;
  3682. foreach my $regexflag ( @regexflag ) {
  3683. my $h1_flags_orig = $h1_flags ;
  3684. $debugflags and myprint( "eval \$h1_flags =~ $regexflag\n" ) ;
  3685. my $ret = eval "\$h1_flags =~ $regexflag ; 1 " ;
  3686. $debugflags and myprint( "regexflag $regexflag [$h1_flags_orig] -> [$h1_flags]\n" ) ;
  3687. if( not ( defined $ret ) or $@ ) {
  3688. myprint( "Error: eval regexflag '$regexflag': $@\n" ) ;
  3689. return( undef ) ;
  3690. }
  3691. }
  3692. return( $h1_flags ) ;
  3693. }
  3694. sub acls_sync {
  3695. my($h1_fold, $h2_fold) = @_ ;
  3696. if ( $syncacls ) {
  3697. my $h1_hash = $imap1->getacl($h1_fold)
  3698. or myprint( "Could not getacl for $h1_fold: $@\n" ) ;
  3699. my $h2_hash = $imap2->getacl($h2_fold)
  3700. or myprint( "Could not getacl for $h2_fold: $@\n" ) ;
  3701. my %users = map { ($_, 1) } ( keys %{ $h1_hash} , keys %{ $h2_hash } ) ;
  3702. foreach my $user (sort keys %users ) {
  3703. my $acl = $h1_hash->{$user} || 'none' ;
  3704. myprint( "acl $user: [$acl]\n" ) ;
  3705. next if ($h1_hash->{$user} && $h2_hash->{$user} &&
  3706. $h1_hash->{$user} eq $h2_hash->{$user});
  3707. unless ($dry) {
  3708. myprint( "setting acl $h2_fold $user $acl\n" ) ;
  3709. $imap2->setacl($h2_fold, $user, $acl)
  3710. or myprint( "Could not set acl: $@\n" ) ;
  3711. }
  3712. }
  3713. }
  3714. return ;
  3715. }
  3716. sub tests_permanentflags {
  3717. my $string;
  3718. ok(q{} eq permanentflags(' * OK [PERMANENTFLAGS (\* \Draft \Answered)] Limited'),
  3719. 'permanentflags \*');
  3720. ok('\Draft \Answered' eq permanentflags(' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited'),
  3721. 'permanentflags \Draft \Answered');
  3722. ok('\Draft \Answered'
  3723. eq permanentflags('Blabla',
  3724. ' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited',
  3725. 'Blabla'),
  3726. 'permanentflags \Draft \Answered'
  3727. );
  3728. ok(q{} eq permanentflags('Blabla'), 'permanentflags nothing');
  3729. return ;
  3730. }
  3731. sub permanentflags {
  3732. my @lines = @_ ;
  3733. foreach my $line (@lines) {
  3734. if ( $line =~ m{\[PERMANENTFLAGS\s\(([^)]+?)\)\]}x ) {
  3735. ( $debugflags or $debug ) and myprint( "permanentflags: $line" ) ;
  3736. my $permanentflags = $1 ;
  3737. if ( $permanentflags =~ m{\\\*}x ) {
  3738. $permanentflags = q{} ;
  3739. }
  3740. return($permanentflags) ;
  3741. } ;
  3742. }
  3743. return( q{} ) ;
  3744. }
  3745. sub tests_flags_filter {
  3746. ok( '\Seen' eq flags_filter('\Seen', '\Draft \Seen \Answered'), 'flags_filter ' );
  3747. ok( q{} eq flags_filter('\Seen', '\Draft \Answered'), 'flags_filter ' );
  3748. ok( '\Seen' eq flags_filter('\Seen', '\Seen'), 'flags_filter ' );
  3749. ok( '\Seen' eq flags_filter('\Seen', ' \Seen '), 'flags_filter ' );
  3750. ok( '\Seen \Draft'
  3751. eq flags_filter('\Seen \Draft', '\Draft \Seen \Answered'), 'flags_filter ' );
  3752. ok( '\Seen \Draft'
  3753. eq flags_filter('\Seen \Draft', ' \Draft \Seen \Answered '), 'flags_filter ' );
  3754. return ;
  3755. }
  3756. sub flags_filter {
  3757. my( $flags, $allowed_flags ) = @_ ;
  3758. my @flags = split /\s+/x, $flags ;
  3759. my %allowed_flags = map { $_ => 1 } split q{ }, $allowed_flags ;
  3760. my @flags_out = map { exists $allowed_flags{$_} ? $_ : () } @flags ;
  3761. my $flags_out = join q{ }, @flags_out ;
  3762. return( $flags_out ) ;
  3763. }
  3764. sub flagscase {
  3765. my $flags = shift ;
  3766. my @flags = split /\s+/x, $flags ;
  3767. my %rfc_flags = map { $_ => 1 } split q{ }, '\Answered \Flagged \Deleted \Seen \Draft' ;
  3768. my @flags_out = map { exists $rfc_flags{ ucsecond( lc $_ ) } ? ucsecond( lc $_ ) : $_ } @flags ;
  3769. my $flags_out = join q{ }, @flags_out ;
  3770. return( $flags_out ) ;
  3771. }
  3772. sub tests_flagscase {
  3773. ok( '\Seen' eq flagscase( '\Seen' ), 'flagscase: \Seen -> \Seen' ) ;
  3774. ok( '\Seen' eq flagscase( '\SEEN' ), 'flagscase: \SEEN -> \Seen' ) ;
  3775. ok( '\Seen \Draft' eq flagscase( '\SEEN \DRAFT' ), 'flagscase: \SEEN \DRAFT -> \Seen \Draft' ) ;
  3776. ok( '\Draft \Seen' eq flagscase( '\DRAFT \SEEN' ), 'flagscase: \DRAFT \SEEN -> \Draft \Seen' ) ;
  3777. ok( '\Draft LALA \Seen' eq flagscase( '\DRAFT LALA \SEEN' ), 'flagscase: \DRAFT LALA \SEEN -> \Draft LALA \Seen' ) ;
  3778. ok( '\Draft lala \Seen' eq flagscase( '\DRAFT lala \SEEN' ), 'flagscase: \DRAFT lala \SEEN -> \Draft lala \Seen' ) ;
  3779. return ;
  3780. }
  3781. sub ucsecond {
  3782. my $string = shift ;
  3783. my $output ;
  3784. return( $string ) if ( 1 >= length $string ) ;
  3785. $output = ( substr( $string, 0, 1) ) . ( uc substr $string, 1, 1 ) . ( substr $string, 2 ) ;
  3786. #myprint( "UUU $string -> $output\n" ) ;
  3787. return( $output ) ;
  3788. }
  3789. sub tests_ucsecond {
  3790. ok( 'aBcde' eq ucsecond( 'abcde' ), 'ucsecond: abcde -> aBcde' ) ;
  3791. ok( 'ABCDE' eq ucsecond( 'ABCDE' ), 'ucsecond: ABCDE -> ABCDE' ) ;
  3792. ok( 'ABCDE' eq ucsecond( 'AbCDE' ), 'ucsecond: AbCDE -> ABCDE' ) ;
  3793. ok( 'ABCde' eq ucsecond( 'AbCde' ), 'ucsecond: AbCde -> ABCde' ) ;
  3794. ok( 'A' eq ucsecond( 'A' ), 'ucsecond: A -> A' ) ;
  3795. ok( 'AB' eq ucsecond( 'Ab' ), 'ucsecond: Ab -> AB' ) ;
  3796. ok( '\B' eq ucsecond( '\b' ), 'ucsecond: \b -> \B' ) ;
  3797. ok( '\Bcde' eq ucsecond( '\bcde' ), 'ucsecond: \bcde -> \Bcde' ) ;
  3798. return ;
  3799. }
  3800. sub select_msgs {
  3801. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  3802. my ( @msgs ) ;
  3803. if ( $abletosearch ) {
  3804. @msgs = select_msgs_by_search( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  3805. }else{
  3806. @msgs = select_msgs_by_fetch( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  3807. }
  3808. return( @msgs ) ;
  3809. }
  3810. sub select_msgs_by_search {
  3811. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  3812. my ( @msgs, @msgs_all ) ;
  3813. # Need to have the whole list in msgs_all_hash_ref
  3814. # without calling messages() several times.
  3815. # Need all messages list to avoid deleting useful cache part
  3816. # in case of --search or --minage or --maxage
  3817. if ( ( defined $msgs_all_hash_ref and $usecache )
  3818. or ( not defined $maxage and not defined $minage and not defined $search_cmd )
  3819. ) {
  3820. $debugdev and myprint( "Calling messages()\n" ) ;
  3821. @msgs_all = $imap->messages( ) ;
  3822. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  3823. if ( defined $msgs_all_hash_ref ) {
  3824. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  3825. }
  3826. # return all messages
  3827. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  3828. return( @msgs_all ) ;
  3829. }
  3830. }
  3831. if ( defined $search_cmd ) {
  3832. @msgs = $imap->search( $search_cmd ) ;
  3833. return( @msgs ) ;
  3834. }
  3835. # we are here only if $maxage or $minage is defined
  3836. @msgs = select_msgs_by_age( $imap ) ;
  3837. return( @msgs );
  3838. }
  3839. sub select_msgs_by_fetch {
  3840. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  3841. my ( @msgs, @msgs_all, %fetch ) ;
  3842. # Need to have the whole list in msgs_all_hash_ref
  3843. # without calling messages() several times.
  3844. # Need all messages list to avoid deleting useful cache part
  3845. # in case of --search or --minage or --maxage
  3846. $debugdev and myprint( "Calling fetch_hash()\n" ) ;
  3847. my $uidnext = $imap->uidnext( $folder ) || $uidnext_default ;
  3848. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  3849. %fetch = %{$imap->fetch_hash( $fetch_hash_uids, 'INTERNALDATE' ) } ;
  3850. @msgs_all = sort { $a <=> $b } keys %fetch ;
  3851. $debugdev and myprint( "Done fetch_hash()\n" ) ;
  3852. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  3853. if ( defined $msgs_all_hash_ref ) {
  3854. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  3855. }
  3856. # return all messages
  3857. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  3858. return( @msgs_all ) ;
  3859. }
  3860. if ( defined $search_cmd ) {
  3861. myprint( "Warning: strange to see --search with --noabletosearch, an error can happen\n" ) ;
  3862. @msgs = $imap->search( $search_cmd ) ;
  3863. return( @msgs ) ;
  3864. }
  3865. # we are here only if $maxage or $minage is defined
  3866. my( @max, @min, $maxage_epoch, $minage_epoch ) ;
  3867. if ( defined $maxage ) { $maxage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ; }
  3868. if ( defined $minage ) { $minage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ; }
  3869. foreach my $msg ( @msgs_all ) {
  3870. my $idate = $fetch{ $msg }->{'INTERNALDATE'} ;
  3871. #myprint( "$idate\n" ) ;
  3872. if ( defined $maxage and ( epoch( $idate ) >= $maxage_epoch ) ) {
  3873. push @max, $msg ;
  3874. }
  3875. if ( defined $minage and ( epoch( $idate ) <= $minage_epoch ) ) {
  3876. push @min, $msg ;
  3877. }
  3878. }
  3879. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  3880. return( @msgs ) ;
  3881. }
  3882. sub select_msgs_by_age {
  3883. my( $imap ) = @_ ;
  3884. my( @max, @min, @msgs, @inter, @union ) ;
  3885. if ( defined $maxage ) {
  3886. @max = $imap->sentsince( $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ) ;
  3887. }
  3888. if ( defined $minage ) {
  3889. @min = $imap->sentbefore( $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ) ;
  3890. }
  3891. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  3892. return( @msgs ) ;
  3893. }
  3894. sub msgs_from_maxmin {
  3895. my( $max_ref, $min_ref ) = @_ ;
  3896. my( @max, @min, @msgs, @inter, @union ) ;
  3897. @max = @{ $max_ref } ;
  3898. @min = @{ $min_ref } ;
  3899. SWITCH: {
  3900. unless( defined $minage ) { @msgs = @max ; last SWITCH } ;
  3901. unless( defined $maxage ) { @msgs = @min ; last SWITCH } ;
  3902. my ( %union, %inter ) ;
  3903. foreach my $m ( @min, @max ) { $union{ $m }++ && $inter{ $m }++ }
  3904. @inter = sort { $a <=> $b } keys %inter ;
  3905. @union = sort { $a <=> $b } keys %union ;
  3906. # normal case
  3907. if ( $minage <= $maxage ) { @msgs = @inter ; last SWITCH } ;
  3908. # just exclude messages between
  3909. if ( $minage > $maxage ) { @msgs = @union ; last SWITCH } ;
  3910. }
  3911. return( @msgs ) ;
  3912. }
  3913. sub tests_msgs_from_maxmin {
  3914. my @msgs ;
  3915. $maxage = $NUMBER_200 ;
  3916. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  3917. ok( 0 == compare_lists( [ '1', '2' ], \@msgs ), 'msgs_from_maxmin: maxage++' ) ;
  3918. $minage = $NUMBER_100 ;
  3919. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  3920. ok( 0 == compare_lists( [ '2' ], \@msgs ), 'msgs_from_maxmin: -maxage++minage-' ) ;
  3921. $minage = $NUMBER_300 ;
  3922. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  3923. ok( 0 == compare_lists( [ '1', '2', '3' ], \@msgs ), 'msgs_from_maxmin: ++maxage-minage++' ) ;
  3924. $maxage = undef ;
  3925. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  3926. ok( 0 == compare_lists( [ '2', '3' ], \@msgs ), 'msgs_from_maxmin: ++minage-' ) ;
  3927. return ;
  3928. }
  3929. sub lastuid {
  3930. my $imap = shift ;
  3931. my $folder = shift ;
  3932. my $lastuid_guess = shift ;
  3933. my $lastuid ;
  3934. # rfc3501: The only reliable way to identify recent messages is to
  3935. # look at message flags to see which have the \Recent flag
  3936. # set, or to do a SEARCH RECENT.
  3937. # SEARCH RECENT doesn't work this way on courrier.
  3938. my @recent_messages ;
  3939. # SEARCH RECENT for each transfer can be expensive with a big folder
  3940. # Call commented for now
  3941. #@recent_messages = $imap->recent( ) ;
  3942. #myprint( "Recent: @recent_messages\n" ) ;
  3943. my $max_recent ;
  3944. $max_recent = max( @recent_messages ) ;
  3945. if ( defined $max_recent and ($lastuid_guess <= $max_recent ) ) {
  3946. $lastuid = $max_recent ;
  3947. }else{
  3948. $lastuid = $lastuid_guess
  3949. }
  3950. return( $lastuid ) ;
  3951. }
  3952. sub size_filtered {
  3953. my( $h1_size, $h1_msg, $h1_fold, $h2_fold ) = @_ ;
  3954. $h1_size = 0 if ( ! $h1_size ) ; # null if empty or undef
  3955. if (defined $maxsize and $h1_size > $maxsize) {
  3956. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size exceeds maxsize limit $maxsize bytes)\n" ) ;
  3957. $total_bytes_skipped += $h1_size;
  3958. $nb_msg_skipped += 1;
  3959. return( 1 ) ;
  3960. }
  3961. if (defined $minsize and $h1_size <= $minsize) {
  3962. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size smaller than minsize $minsize bytes)\n" ) ;
  3963. $total_bytes_skipped += $h1_size;
  3964. $nb_msg_skipped += 1;
  3965. return( 1 ) ;
  3966. }
  3967. return( 0 ) ;
  3968. }
  3969. sub message_exists {
  3970. my( $imap, $msg ) = @_ ;
  3971. return( 1 ) if not $imap->Uid( ) ;
  3972. my $search_uid ;
  3973. ( $search_uid ) = $imap->search( "UID $msg" ) ;
  3974. #myprint( "$search ? $msg\n" ) ;
  3975. return( 1 ) if ( $search_uid eq $msg ) ;
  3976. return( 0 ) ;
  3977. }
  3978. sub copy_message {
  3979. # copy
  3980. my ( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) = @_ ;
  3981. ( $debug or $dry) and myprint( "msg $h1_fold/$h1_msg copying to $h2_fold $dry_message\n" ) ;
  3982. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} || 0 ;
  3983. my $h1_flags = $h1_fir_ref->{$h1_msg}->{'FLAGS'} || q{} ;
  3984. my $h1_idate = $h1_fir_ref->{$h1_msg}->{'INTERNALDATE'} || q{} ;
  3985. if ( size_filtered( $h1_size, $h1_msg, $h1_fold, $h2_fold ) ) {
  3986. $h1_nb_msg_processed +=1 ;
  3987. return ;
  3988. }
  3989. debugsleep( $sync ) ;
  3990. myprint( "- msg $h1_fold/$h1_msg S[$h1_size] F[$h1_flags] I[$h1_idate] has RFC822.SIZE null!\n" ) if ( ! $h1_size ) ;
  3991. if ( $checkmessageexists and not message_exists( $imap1, $h1_msg ) ) {
  3992. $total_bytes_skipped += $h1_size;
  3993. $nb_msg_skipped += 1;
  3994. $h1_nb_msg_processed +=1 ;
  3995. return ;
  3996. }
  3997. if ( $sync->{debugmemory} ) {
  3998. myprintf("C1: Memory consumption: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI) ;
  3999. }
  4000. my ( $string, $string_len ) ;
  4001. ( $string_len ) = message_for_host2( $sync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, \$string ) ;
  4002. if ( $sync->{debugmemory} ) {
  4003. myprintf("C2: Memory consumption: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI) ;
  4004. }
  4005. # not defined or empty $string
  4006. if ( ( not $string ) and ( not $string_len ) ) {
  4007. myprint( "- msg $h1_fold/$h1_msg skipped.\n" ) ;
  4008. $total_bytes_skipped += $h1_size;
  4009. $nb_msg_skipped += 1;
  4010. $h1_nb_msg_processed +=1 ;
  4011. return ;
  4012. }
  4013. # Lines too long (or not enough) => do no copy or fix
  4014. if ( ( defined $maxlinelength ) or ( defined $minmaxlinelength ) ) {
  4015. $string = linelengthstuff( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) ;
  4016. if ( not defined $string ) {
  4017. $h1_nb_msg_processed +=1 ;
  4018. $total_bytes_skipped += $h1_size ;
  4019. $nb_msg_skipped += 1 ;
  4020. return ;
  4021. }
  4022. }
  4023. my $h1_date = date_for_host2( $h1_msg, $h1_idate ) ;
  4024. ( $debug or $debugflags ) and
  4025. myprint( "Host1 flags init msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  4026. $h1_flags = flags_for_host2( $h1_flags, $permanentflags2 ) ;
  4027. ( $debug or $debugflags ) and
  4028. myprint( "Host1 flags filt msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  4029. $h1_date = undef if ($h1_date eq q{});
  4030. my $new_id = append_message_on_host2( \$string, $h1_fold, $h1_msg, $string_len, $h2_fold, $h1_size, $h1_flags, $h1_date, $cache_dir ) ;
  4031. if ( $new_id and $syncflagsaftercopy ) {
  4032. sync_flags_after_copy( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $new_id, $permanentflags2 ) ;
  4033. }
  4034. if ( $sync->{debugmemory} ) {
  4035. myprintf("C3: Memory consumption: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI) ;
  4036. }
  4037. return $new_id ;
  4038. }
  4039. sub linelengthstuff {
  4040. my( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) = @_ ;
  4041. my $maxlinelength_string = max_line_length( $string ) ;
  4042. $debugmaxlinelength and myprint( "msg $h1_fold/$h1_msg maxlinelength: $maxlinelength_string\n" ) ;
  4043. if ( ( defined $minmaxlinelength ) and ( $maxlinelength_string <= $minmaxlinelength ) ) {
  4044. my $subject = subject( $string ) ;
  4045. $debugdev and myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  4046. . "(Subject:[$subject]) (max line length under minmaxlinelength $minmaxlinelength bytes)\n" ) ;
  4047. return ;
  4048. }
  4049. if ( ( defined $maxlinelength ) and ( $maxlinelength_string > $maxlinelength ) ) {
  4050. my $subject = subject( $string ) ;
  4051. if ( $maxlinelengthcmd ) {
  4052. $string = pipemess( $string, $maxlinelengthcmd ) ;
  4053. # string undef means something was bad.
  4054. if ( not ( defined $string ) ) {
  4055. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] "
  4056. . "(Subject:[$subject]) could not be successfully transformed by --maxlinelengthcmd option\n" ) ;
  4057. return ;
  4058. }else{
  4059. return $string ;
  4060. }
  4061. }
  4062. myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  4063. . "(Subject:[$subject]) (line length exceeds maxlinelength $maxlinelength bytes)\n" ) ;
  4064. return ;
  4065. }
  4066. return $string ;
  4067. }
  4068. sub message_for_host2 {
  4069. # global variable list:
  4070. # @skipmess
  4071. # @regexmess
  4072. # @pipemess
  4073. # $addheader
  4074. # $debugcontent
  4075. # $debug
  4076. #
  4077. # API current
  4078. #
  4079. # at failure:
  4080. # * return nothing ( will then be undef or () )
  4081. # * $string_ref content is undef or empty
  4082. # at success:
  4083. # * return string length ($string_ref content length)
  4084. # * $string_ref content filled with message
  4085. # API future
  4086. #
  4087. #
  4088. my ( $sync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) = @_ ;
  4089. # abort when missing a parameter
  4090. if ( (!$sync) or (!$h1_msg) or (!$h1_fold) or (!$h1_size) or (!defined $h1_flags) or (!$h1_idate) or (!$h1_fir_ref) or (!$string_ref) ) {
  4091. return ;
  4092. }
  4093. if ( $sync->{debugmemory} ) {
  4094. myprintf("M1: Memory consumption: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI) ;
  4095. }
  4096. my $imap1 = $sync->{imap1} ;
  4097. my $string_ok = $imap1->message_to_file( $string_ref, $h1_msg ) ;
  4098. if ( $sync->{debugmemory} ) {
  4099. myprintf("M2: Memory consumption: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI) ;
  4100. }
  4101. my $string_len = length_ref( $string_ref ) ;
  4102. unless ( defined $string_ok and $string_len ) {
  4103. # undef or 0 length
  4104. my $error = join q{},
  4105. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] could not be fetched: ",
  4106. $imap1->LastError || q{}, "\n" ;
  4107. errors_incr( $sync, $error ) ;
  4108. $total_bytes_error += $h1_size if ( $h1_size ) ;
  4109. $h1_nb_msg_processed +=1 ;
  4110. return ;
  4111. }
  4112. if ( @skipmess ) {
  4113. my $match = skipmess( ${ $string_ref } ) ;
  4114. # string undef means the eval regex was bad.
  4115. if ( not ( defined $match ) ) {
  4116. myprint(
  4117. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  4118. . " could not be skipped by --skipmess option, bad regex\n" ) ;
  4119. return ;
  4120. }
  4121. if ( $match ) {
  4122. my $subject = subject( ${ $string_ref } ) ;
  4123. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  4124. . " (Subject:[$subject]) skipped by --skipmess\n" ) ;
  4125. return ;
  4126. }
  4127. }
  4128. if ( @regexmess ) {
  4129. ${ $string_ref } = regexmess( ${ $string_ref } ) ;
  4130. # string undef means the eval regex was bad.
  4131. if ( not ( defined ${ $string_ref } ) ) {
  4132. myprint(
  4133. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  4134. . " could not be transformed by --regexmess\n" ) ;
  4135. return ;
  4136. }
  4137. }
  4138. if ( @pipemess ) {
  4139. ${ $string_ref } = pipemess( ${ $string_ref }, @pipemess ) ;
  4140. # string undef means something was bad.
  4141. if ( not ( defined ${ $string_ref } ) ) {
  4142. myprint(
  4143. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  4144. . " could not be successfully transformed by --pipemess option\n" ) ;
  4145. return ;
  4146. }
  4147. }
  4148. if ( $addheader and defined $h1_fir_ref->{$h1_msg}->{'NO_HEADER'} ) {
  4149. my $header = add_header( $h1_msg ) ;
  4150. $debug and myprint( "msg $h1_fold/$h1_msg adding custom header [$header]\n" ) ;
  4151. ${ $string_ref } = $header . "\r\n" . ${ $string_ref } ;
  4152. }
  4153. $string_len = length_ref( $string_ref ) ;
  4154. $debugcontent and myprint(
  4155. q{=} x $STD_CHAR_PER_LINE, "\n",
  4156. "F message content begin next line ($string_len characters long)\n",
  4157. ${ $string_ref },
  4158. "F message content ended on previous line\n", q{=} x $STD_CHAR_PER_LINE, "\n" ) ;
  4159. if ( $sync->{debugmemory} ) {
  4160. myprintf("M3: Memory consumption: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI) ;
  4161. }
  4162. return $string_len ;
  4163. }
  4164. sub tests_message_for_host2 {
  4165. my ( $sync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) ;
  4166. is( undef, message_for_host2( ), q{message_for_host2: no args} ) ;
  4167. is( undef, message_for_host2( $sync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ), q{message_for_host2: undef args} ) ;
  4168. require Test::MockObject ;
  4169. my $imapT = Test::MockObject->new( ) ;
  4170. $sync->{imap1} = $imapT ;
  4171. my $string ;
  4172. $h1_msg = 1 ;
  4173. $h1_fold = 'FoldFoo';
  4174. $h1_size = 9 ;
  4175. $h1_flags = '' ;
  4176. $h1_idate = '10-Jul-2015 09:00:00 +0200' ;
  4177. $h1_fir_ref = {} ;
  4178. $string_ref = \$string ;
  4179. $imapT->mock( 'message_to_file',
  4180. sub {
  4181. my ( $imap, $string_ref, $msg ) = @_ ;
  4182. ${$string_ref} = 'blablabla' ;
  4183. return length ${$string_ref} ;
  4184. }
  4185. ) ;
  4186. is( 9, message_for_host2( $sync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  4187. q{message_for_host2: msg 1 == "blablabla", length} ) ;
  4188. is( 'blablabla', $string, q{message_for_host2: msg 1 == "blablabla", value} ) ;
  4189. # so far so good
  4190. # now the --pipemess stuff
  4191. SKIP: {
  4192. Readonly my $NB_WIN_tests_message_for_host2 => 0 ;
  4193. skip( 'Not on MSWin32', $NB_WIN_tests_message_for_host2 ) if ('MSWin32' ne $OSNAME) ;
  4194. # Windows
  4195. # "type" command does not accept redirection of STDIN with <
  4196. # "sort" does
  4197. } ;
  4198. SKIP: {
  4199. Readonly my $NB_UNX_tests_message_for_host2 => 6 ;
  4200. skip( 'Not on Unix', $NB_UNX_tests_message_for_host2 ) if ('MSWin32' eq $OSNAME) ;
  4201. # Unix
  4202. # no change by cat
  4203. @pipemess = ( 'cat' ) ;
  4204. is( 9, message_for_host2( $sync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  4205. q{message_for_host2: --pipemess 'cat', length} ) ;
  4206. is( 'blablabla', $string, q{message_for_host2: --pipemess 'cat', value} ) ;
  4207. # failure by false
  4208. @pipemess = ( 'false' ) ;
  4209. is( undef, message_for_host2( $sync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  4210. q{message_for_host2: --pipemess 'false', length} ) ;
  4211. is( undef, $string, q{message_for_host2: --pipemess 'false', value} ) ;
  4212. # failure by true since no output
  4213. @pipemess = ( 'true' ) ;
  4214. is( undef, message_for_host2( $sync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  4215. q{message_for_host2: --pipemess 'true', length} ) ;
  4216. is( undef, $string, q{message_for_host2: --pipemess 'true', value} ) ;
  4217. }
  4218. return ;
  4219. }
  4220. sub length_ref {
  4221. my $string_ref = shift ;
  4222. my $string_len = defined ${ $string_ref } ? length( ${ $string_ref } ) : q{} ; # length or empty string
  4223. return $string_len ;
  4224. }
  4225. sub tests_length_ref {
  4226. my $notdefined ;
  4227. is( q{}, length_ref( \$notdefined ), q{length_ref: value not defined} ) ;
  4228. my $notref ;
  4229. is( q{}, length_ref( $notref ), q{length_ref: param not a ref} ) ;
  4230. my $lala = 'lala' ;
  4231. is( 4, length_ref( \$lala ), q{length_ref: lala length == 4} ) ;
  4232. is( 4, length_ref( \'lili' ), q{length_ref: lili length == 4} ) ;
  4233. return ;
  4234. }
  4235. sub date_for_host2 {
  4236. my( $h1_msg, $h1_idate ) = @_ ;
  4237. my $h1_date = q{} ;
  4238. if ( $syncinternaldates ) {
  4239. $h1_date = $h1_idate ;
  4240. $debug and myprint( "internal date from host1: [$h1_date]\n" ) ;
  4241. $h1_date = good_date( $h1_date ) ;
  4242. $debug and myprint( "internal date from host1: [$h1_date] (fixed)\n" ) ;
  4243. }
  4244. if ( $idatefromheader ) {
  4245. $h1_date = $imap1->get_header( $h1_msg, 'Date' ) ;
  4246. $debug and myprint( "header date from host1: [$h1_date]\n" ) ;
  4247. $h1_date = good_date( $h1_date ) ;
  4248. $debug and myprint( "header date from host1: [$h1_date] (fixed)\n" ) ;
  4249. }
  4250. return( $h1_date ) ;
  4251. }
  4252. sub flags_for_host2 {
  4253. my( $h1_flags, $permanentflags2 ) = @_ ;
  4254. # RFC 2060: This flag can not be altered by any client
  4255. $h1_flags =~ s@\\Recent\s?@@xgi ;
  4256. my $h1_flags_re ;
  4257. if ( @regexflag and defined( $h1_flags_re = flags_regex( $h1_flags ) ) ) {
  4258. $h1_flags = $h1_flags_re ;
  4259. }
  4260. $h1_flags = flagscase( $h1_flags ) if $flagscase ;
  4261. $h1_flags = flags_filter( $h1_flags, $permanentflags2) if ( $permanentflags2 and $filterflags ) ;
  4262. return( $h1_flags ) ;
  4263. }
  4264. sub subject {
  4265. my $string = shift ;
  4266. my $subject = q{} ;
  4267. my $header = extract_header( $string ) ;
  4268. if( $header =~ m/^Subject:\s*([^\n\r]*)\r?$/msx ) {
  4269. #myprint( "MMM[$1]\n" ) ;
  4270. $subject = $1 ;
  4271. }
  4272. return( $subject ) ;
  4273. }
  4274. sub tests_subject {
  4275. ok( q{} eq subject( q{} ), 'subject: null') ;
  4276. ok( 'toto le hero' eq subject( 'Subject: toto le hero' ), 'subject: toto le hero') ;
  4277. ok( 'toto le hero' eq subject( 'Subject:toto le hero' ), 'subject: toto le hero blank') ;
  4278. ok( 'toto le hero' eq subject( "Subject:toto le hero\r\n" ), 'subject: toto le hero\r\n') ;
  4279. my $MESS ;
  4280. $MESS = <<'EOF';
  4281. From: lalala
  4282. Subject: toto le hero
  4283. Date: zzzzzz
  4284. Boogie boogie
  4285. EOF
  4286. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 2') ;
  4287. $MESS = <<'EOF';
  4288. Subject: toto le hero
  4289. From: lalala
  4290. Date: zzzzzz
  4291. Boogie boogie
  4292. EOF
  4293. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 3') ;
  4294. $MESS = <<'EOF';
  4295. From: lalala
  4296. Subject: cuicui
  4297. Date: zzzzzz
  4298. Subject: toto le hero
  4299. EOF
  4300. ok( 'cuicui' eq subject( $MESS ), 'subject: cuicui') ;
  4301. $MESS = <<'EOF';
  4302. From: lalala
  4303. Date: zzzzzz
  4304. Subject: toto le hero
  4305. EOF
  4306. ok( q{} eq subject( $MESS ), 'subject: null but body could') ;
  4307. return ;
  4308. }
  4309. # GlobVar
  4310. # $dry
  4311. # $max_msg_size_in_bytes
  4312. # $imap2
  4313. # $imap1
  4314. # $total_bytes_error
  4315. # $h1_nb_msg_processed
  4316. # $h2_uidguess
  4317. # $total_bytes_transferred
  4318. # $nb_msg_transferred
  4319. # $begin_transfer_time
  4320. # $time_spent
  4321. # ...
  4322. #
  4323. #
  4324. sub append_message_on_host2 {
  4325. my( $string_ref, $h1_fold, $h1_msg, $string_len, $h2_fold, $h1_size, $h1_flags, $h1_date, $cache_dir ) = @_ ;
  4326. if ( $sync->{debugmemory} ) {
  4327. myprintf("A1: Memory consumption: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI) ;
  4328. }
  4329. my $new_id ;
  4330. if ( ! $dry ) {
  4331. $max_msg_size_in_bytes = max( $h1_size, $max_msg_size_in_bytes ) ;
  4332. $new_id = $imap2->append_string( $h2_fold, ${ $string_ref }, $h1_flags, $h1_date ) ;
  4333. if ( $sync->{debugmemory} ) {
  4334. myprintf("A2: Memory consumption: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI) ;
  4335. }
  4336. if ( ! $new_id){
  4337. my $subject = subject( ${ $string_ref } ) ;
  4338. my $error_imap = $imap2->LastError || q{} ;
  4339. my $error = "- msg $h1_fold/$h1_msg {$string_len} couldn't append (Subject:[$subject]) to folder $h2_fold: $error_imap\n" ;
  4340. errors_incr( $sync, $error ) ;
  4341. $total_bytes_error += $h1_size;
  4342. $h1_nb_msg_processed +=1 ;
  4343. return ;
  4344. }
  4345. else{
  4346. # good
  4347. # $new_id is an id if the IMAP server has the
  4348. # UIDPLUS capability else just a ref
  4349. if ( $new_id !~ m{^\d+$}x ) {
  4350. $new_id = lastuid( $imap2, $h2_fold, $h2_uidguess ) ;
  4351. }
  4352. $h2_uidguess += 1 ;
  4353. $total_bytes_transferred += $h1_size ;
  4354. $nb_msg_transferred += 1 ;
  4355. $h1_nb_msg_processed +=1 ;
  4356. my $time_spent = timesince( $begin_transfer_time ) ;
  4357. my $rate = bytes_display_string( $total_bytes_transferred / $time_spent ) ;
  4358. my $eta = eta( $time_spent,
  4359. $h1_nb_msg_processed, $h1_nb_msg_start, $nb_msg_transferred ) ;
  4360. my $amount_transferred = bytes_display_string( $total_bytes_transferred ) ;
  4361. myprintf( "msg %s/%-19s copied to %s/%-10s %.2f msgs/s %s/s %s copied %s\n",
  4362. $h1_fold, "$h1_msg {$string_len}", $h2_fold, $new_id, $nb_msg_transferred/$time_spent, $rate,
  4363. $amount_transferred,
  4364. $eta );
  4365. sleep_if_needed( $time_spent, $total_bytes_transferred, $nb_msg_transferred ) ;
  4366. if ( $usecache and $cacheaftercopy and $new_id =~ m{^\d+$}x ) {
  4367. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$new_id\n" ) ;
  4368. touch( "$cache_dir/${h1_msg}_$new_id" )
  4369. or croak( "Couldn't touch $cache_dir/${h1_msg}_$new_id" ) ;
  4370. }
  4371. if ( $delete ) {
  4372. delete_message_on_host1( $h1_msg, $h1_fold ) ;
  4373. }
  4374. #myprint( "PRESS ENTER" ) and my $a = <> ;
  4375. return( $new_id ) ;
  4376. }
  4377. }
  4378. else{
  4379. # NOOP to avoid timeout on large folders.
  4380. $imap2->noop( ) ;
  4381. $nb_msg_skipped_dry_mode += 1 ;
  4382. $h1_nb_msg_processed +=1 ;
  4383. }
  4384. return ;
  4385. }
  4386. sub sleep_if_needed {
  4387. my( $time_spent, $total_bytes_transferred, $nb_msg_transferred ) = @_ ;
  4388. my $sleep_max_messages = sleep_max_messages( $nb_msg_transferred, $time_spent, $maxmessagespersecond ) ;
  4389. my $sleep_max_bytes = sleep_max_bytes( $total_bytes_transferred, $time_spent, $maxbytespersecond ) ;
  4390. my $sleep_max = max( $sleep_max_messages, $sleep_max_bytes ) ;
  4391. if ( $sleep_max > 0 ) {
  4392. myprintf( "sleeping %.2f s\n", $sleep_max ) ;
  4393. sleep $sleep_max ;
  4394. }
  4395. return ;
  4396. }
  4397. sub sleep_max_messages {
  4398. # how long we have to sleep to go under max_messages_per_second
  4399. my( $nb_msg_transferred, $time_spent, $maxmessagespersecond ) = @_ ;
  4400. if ( ( not defined $maxmessagespersecond ) or $maxmessagespersecond <= 0 ) { return( 0 ) } ;
  4401. my $sleep = ( $nb_msg_transferred / $maxmessagespersecond ) - $time_spent ;
  4402. # the sleep must be positive
  4403. return( max( 0, $sleep ) ) ;
  4404. }
  4405. sub tests_sleep_max_messages {
  4406. ok( 0 == sleep_max_messages( 4, 2, undef ), 'sleep_max_messages: maxmessagespersecond = undef') ;
  4407. ok( 0 == sleep_max_messages( 4, 2, 0 ), 'sleep_max_messages: maxmessagespersecond = 0') ;
  4408. ok( 0 == sleep_max_messages( 4, 2, $MINUS_ONE ), 'sleep_max_messages: maxmessagespersecond = -1') ;
  4409. ok( 0 == sleep_max_messages( 4, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max reached') ;
  4410. ok( 2 == sleep_max_messages( 8, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max over') ;
  4411. ok( 0 == sleep_max_messages( 2, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max not reached') ;
  4412. return ;
  4413. }
  4414. sub sleep_max_bytes {
  4415. # how long we have to sleep to go under max_bytes_per_second
  4416. my( $total_bytes_transferred, $time_spent, $maxbytespersecond ) = @_ ;
  4417. if ( ( not defined $maxbytespersecond ) or $maxbytespersecond <= 0 ) { return( 0 ) } ;
  4418. my $sleep = ( $total_bytes_transferred / $maxbytespersecond ) - $time_spent ;
  4419. # the sleep must be positive
  4420. return( max( 0, $sleep ) ) ;
  4421. }
  4422. sub tests_sleep_max_bytes {
  4423. ok( 0 == sleep_max_bytes( 4000, 2, undef ), 'sleep_max_bytes: maxbytespersecond = undef') ;
  4424. ok( 0 == sleep_max_bytes( 4000, 2, 0 ), 'sleep_max_bytes: maxbytespersecond = 0') ;
  4425. ok( 0 == sleep_max_bytes( 4000, 2, $MINUS_ONE ), 'sleep_max_bytes: maxbytespersecond = -1') ;
  4426. ok( 0 == sleep_max_bytes( 4000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2 max reached') ;
  4427. ok( 2 == sleep_max_bytes( 8000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2 max over') ;
  4428. ok( 0 == sleep_max_bytes( 2000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2 max not reached') ;
  4429. return ;
  4430. }
  4431. # 6 GlobVar: $dry_message $dry $imap1 $h1_nb_msg_deleted $expunge $expunge1
  4432. sub delete_message_on_host1 {
  4433. my( $h1_msg, $h1_fold ) = @_ ;
  4434. my $expunge_message = q{} ;
  4435. $expunge_message = 'and expunged' if ( $expungeaftereach and ( $expunge or $expunge1 ) ) ;
  4436. myprint( "Host1 msg $h1_fold/$h1_msg marked deleted $expunge_message $dry_message\n" ) ;
  4437. if ( ! $dry ) {
  4438. $imap1->delete_message( $h1_msg ) ;
  4439. $h1_nb_msg_deleted += 1 ;
  4440. $imap1->expunge( ) if ( $expungeaftereach and ( $expunge or $expunge1 ) ) ;
  4441. }
  4442. return ;
  4443. }
  4444. sub eta {
  4445. my( $my_time_spent, $h1_nb_processed, $h1_nb_msg_start, $nb_transferred ) = @_ ;
  4446. return( q{} ) if not $foldersizes ;
  4447. my $time_remaining = time_remaining( $my_time_spent, $h1_nb_processed, $h1_nb_msg_start, $nb_transferred ) ;
  4448. my $nb_msg_remaining = $h1_nb_msg_start - $h1_nb_processed ;
  4449. my $eta_date = localtime( time + $time_remaining ) ;
  4450. return( mysprintf( 'ETA: %s %1.0f s %s/%s msgs left', $eta_date, $time_remaining, $nb_msg_remaining, $h1_nb_msg_start ) ) ;
  4451. }
  4452. sub time_remaining {
  4453. my( $my_time_spent, $h1_nb_processed, $h1_nb_msg_start, $nb_transferred ) = @_ ;
  4454. my $time_remaining = ( $my_time_spent / $nb_transferred ) * ( $h1_nb_msg_start - $h1_nb_processed ) ;
  4455. return( $time_remaining ) ;
  4456. }
  4457. sub tests_time_remaining {
  4458. ok( 1 == time_remaining( 1, 1, 2, 1 ), 'time_remaining: 1, 1, 2, 1 -> 1' ) ;
  4459. ok( 1 == time_remaining( 9, 9, 10, 9 ), 'time_remaining: 9, 9, 10, 9 -> 1' ) ;
  4460. ok( 9 == time_remaining( 1, 1, 10, 1 ), 'time_remaining: 1, 1, 10, 1 -> 1' ) ;
  4461. return ;
  4462. }
  4463. sub cache_map {
  4464. my ( $cache_files_ref, $h1_msgs_ref, $h2_msgs_ref ) = @_;
  4465. my ( %map1_2, %map2_1, %done2 ) ;
  4466. my $h1_msgs_hash_ref = { } ;
  4467. my $h2_msgs_hash_ref = { } ;
  4468. @{ $h1_msgs_hash_ref }{ @{ $h1_msgs_ref } } = ( ) ;
  4469. @{ $h2_msgs_hash_ref }{ @{ $h2_msgs_ref } } = ( ) ;
  4470. foreach my $file ( sort @{ $cache_files_ref } ) {
  4471. $debugcache and myprint( "C12: $file\n" ) ;
  4472. ( $uid1, $uid2 ) = match_a_cache_file( $file ) ;
  4473. if ( exists( $h1_msgs_hash_ref->{ defined $uid1 ? $uid1 : q{} } )
  4474. and exists( $h2_msgs_hash_ref->{ defined $uid2 ? $uid2 : q{} } ) ) {
  4475. # keep only the greatest uid2
  4476. # 130_2301 and
  4477. # 130_231 => keep only 130 -> 2301
  4478. # keep only the greatest uid1
  4479. # 1601_260 and
  4480. # 161_260 => keep only 1601 -> 260
  4481. my $max_uid2 = max( $uid2, $map1_2{ $uid1 } || $MINUS_ONE ) ;
  4482. if ( exists $done2{ $max_uid2 } ) {
  4483. if ( $done2{ $max_uid2 } < $uid1 ) {
  4484. $map1_2{ $uid1 } = $max_uid2 ;
  4485. delete $map1_2{ $done2{ $max_uid2 } } ;
  4486. $done2{ $max_uid2 } = $uid1 ;
  4487. }
  4488. }else{
  4489. $map1_2{ $uid1 } = $max_uid2 ;
  4490. $done2{ $max_uid2 } = $uid1 ;
  4491. }
  4492. };
  4493. }
  4494. %map2_1 = reverse %map1_2 ;
  4495. return( \%map1_2, \%map2_1) ;
  4496. }
  4497. sub tests_cache_map {
  4498. #$debugcache = 1 ;
  4499. my @cache_files = qw (
  4500. 100_200
  4501. 101_201
  4502. 120_220
  4503. 142_242
  4504. 143_243
  4505. 177_277
  4506. 177_278
  4507. 177_279
  4508. 155_255
  4509. 180_280
  4510. 181_280
  4511. 182_280
  4512. 130_231
  4513. 130_2301
  4514. 161_260
  4515. 1601_260
  4516. ) ;
  4517. my $msgs_1 = [120, 142, 143, 144, 161, 1601, 177, 182, 130 ];
  4518. my $msgs_2 = [ 242, 243, 260, 299, 377, 279, 255, 280, 231, 2301 ];
  4519. my( $c12, $c21 ) ;
  4520. ok( ( $c12, $c21 ) = cache_map( \@cache_files, $msgs_1, $msgs_2 ), 'cache_map: 02' );
  4521. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  4522. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  4523. ok( 0 == compare_lists( [ 130, 142, 143, 177, 182, 1601 ], $a1 ), 'cache_map: 03' );
  4524. ok( 0 == compare_lists( [ 242, 243, 260, 279, 280, 2301 ], $a2 ), 'cache_map: 04' );
  4525. ok( ! $c12->{161}, 'cache_map: ! 161 -> 260' );
  4526. ok( 260 == $c12->{1601}, 'cache_map: 1601 -> 260' );
  4527. ok( 2301 == $c12->{130}, 'cache_map: 130 -> 2301' );
  4528. #myprint( $c12->{1601}, "\n" ) ;
  4529. return ;
  4530. }
  4531. sub cache_dir_fix {
  4532. my $cache_dir = shift ;
  4533. $cache_dir =~ s/([;<>\*\|`&\$!#\(\)\[\]\{\}:'"\\])/\\$1/xg ;
  4534. #myprint( "cache_dir_fix: $cache_dir\n" ) ;
  4535. return( $cache_dir ) ;
  4536. }
  4537. sub tests_cache_dir_fix {
  4538. ok( 'lalala' eq cache_dir_fix('lalala'), 'cache_dir_fix: lalala -> lalala' );
  4539. ok( 'ii\\\\ii' eq cache_dir_fix('ii\ii'), 'cache_dir_fix: ii\ii -> ii\\\\ii' );
  4540. ok( 'ii@ii' eq cache_dir_fix('ii@ii'), 'cache_dir_fix: ii@ii -> ii@ii' );
  4541. ok( 'ii@ii\\:ii' eq cache_dir_fix('ii@ii:ii'), 'cache_dir_fix: ii@ii:ii -> ii@ii\\:ii' );
  4542. ok( 'i\\\\i\\\\ii' eq cache_dir_fix('i\i\ii'), 'cache_dir_fix: i\i\ii -> i\\\\i\\\\ii' );
  4543. ok( 'i\\\\ii' eq cache_dir_fix('i\\ii'), 'cache_dir_fix: i\\ii -> i\\\\\\\\ii' );
  4544. ok( '\\\\ ' eq cache_dir_fix('\\ '), 'cache_dir_fix: \\ -> \\\\\ ' );
  4545. ok( '\\\\ ' eq cache_dir_fix('\ '), 'cache_dir_fix: \ -> \\\\\ ' );
  4546. ok( '\[bracket\]' eq cache_dir_fix('[bracket]'), 'cache_dir_fix: [bracket] -> \[bracket\]' );
  4547. return ;
  4548. }
  4549. sub cache_dir_fix_win {
  4550. my $cache_dir = shift ;
  4551. $cache_dir =~ s/(\[|\])/[$1]/xg ;
  4552. #myprint( "cache_dir_fix_win: $cache_dir\n" ) ;
  4553. return( $cache_dir ) ;
  4554. }
  4555. sub tests_cache_dir_fix_win {
  4556. ok( 'lalala' eq cache_dir_fix_win('lalala'), 'cache_dir_fix_win: lalala -> lalala' );
  4557. ok( '[[]bracket[]]' eq cache_dir_fix_win('[bracket]'), 'cache_dir_fix_win: [bracket] -> [[]bracket[]]' );
  4558. return ;
  4559. }
  4560. sub get_cache {
  4561. my ( $cache_dir, $h1_msgs_ref, $h2_msgs_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_;
  4562. $debugcache and myprint( "Entering get_cache\n" ) ;
  4563. -d $cache_dir or return( undef ); # exit if cache directory doesn't exist
  4564. $debugcache and myprint( "cache_dir : $cache_dir\n" ) ;
  4565. if ( 'MSWin32' ne $OSNAME ) {
  4566. $cache_dir = cache_dir_fix( $cache_dir ) ;
  4567. }else{
  4568. $cache_dir = cache_dir_fix_win( $cache_dir ) ;
  4569. }
  4570. $debugcache and myprint( "cache_dir_fix: $cache_dir\n" ) ;
  4571. my @cache_files = bsd_glob( "$cache_dir/*" ) ;
  4572. #$debugcache and myprint( "cache_files: [@cache_files]\n" ) ;
  4573. $debugcache and myprint( 'cache_files: ', scalar @cache_files , " files found\n" ) ;
  4574. my( $cache_1_2_ref, $cache_2_1_ref )
  4575. = cache_map( \@cache_files, $h1_msgs_ref, $h2_msgs_ref ) ;
  4576. clean_cache( \@cache_files, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  4577. $debugcache and myprint( "Exiting get_cache\n" ) ;
  4578. return( $cache_1_2_ref, $cache_2_1_ref ) ;
  4579. }
  4580. sub tests_get_cache {
  4581. ok( not( get_cache('/cache_no_exist') ), 'get_cache: /cache_no_exist' );
  4582. ok( ( not -d 'W/tmp/cache/F1/F2' or rmtree( 'W/tmp/cache/F1/F2' )), 'get_cache: rmtree W/tmp/cache/F1/F2' ) ;
  4583. ok( mkpath( 'W/tmp/cache/F1/F2' ), 'get_cache: mkpath W/tmp/cache/F1/F2' ) ;
  4584. my @test_files_cache = ( qw(
  4585. W/tmp/cache/F1/F2/100_200
  4586. W/tmp/cache/F1/F2/101_201
  4587. W/tmp/cache/F1/F2/120_220
  4588. W/tmp/cache/F1/F2/142_242
  4589. W/tmp/cache/F1/F2/143_243
  4590. W/tmp/cache/F1/F2/177_277
  4591. W/tmp/cache/F1/F2/177_377
  4592. W/tmp/cache/F1/F2/177_777
  4593. W/tmp/cache/F1/F2/155_255
  4594. ) ) ;
  4595. ok( touch( @test_files_cache ), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  4596. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  4597. # on live:
  4598. my $msgs_1 = [120, 142, 143, 144, 177 ];
  4599. my $msgs_2 = [ 242, 243, 299, 377, 777, 255 ];
  4600. my $msgs_all_1 = { 120 => 0, 142 => 0, 143 => 0, 144 => 0, 177 => 0 } ;
  4601. my $msgs_all_2 = { 242 => 0, 243 => 0, 299 => 0, 377 => 0, 777 => 0, 255 => 0 } ;
  4602. my( $c12, $c21 ) ;
  4603. ok( ( $c12, $c21 ) = get_cache( 'W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  4604. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  4605. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  4606. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: 03' );
  4607. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: 04' );
  4608. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  4609. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  4610. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file removed 100_200');
  4611. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file removed 101_201');
  4612. # test clean_cache executed
  4613. $maxage = 2 ;
  4614. ok( touch(@test_files_cache), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  4615. ok( ( $c12, $c21 ) = get_cache('W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  4616. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  4617. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  4618. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file NOT removed 100_200');
  4619. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file NOT removed 101_201');
  4620. # strange files
  4621. #$debugcache = 1 ;
  4622. $maxage = undef ;
  4623. ok( ( not -d 'W/tmp/cache/rr\uee' or rmtree( 'W/tmp/cache/rr\uee' )), 'get_cache: rmtree W/tmp/cache/rr\uee' ) ;
  4624. ok( mkpath( 'W/tmp/cache/rr\uee' ), 'get_cache: mkpath W/tmp/cache/rr\uee' ) ;
  4625. @test_files_cache = ( qw(
  4626. W/tmp/cache/rr\uee/100_200
  4627. W/tmp/cache/rr\uee/101_201
  4628. W/tmp/cache/rr\uee/120_220
  4629. W/tmp/cache/rr\uee/142_242
  4630. W/tmp/cache/rr\uee/143_243
  4631. W/tmp/cache/rr\uee/177_277
  4632. W/tmp/cache/rr\uee/177_377
  4633. W/tmp/cache/rr\uee/177_777
  4634. W/tmp/cache/rr\uee/155_255
  4635. ) ) ;
  4636. ok( touch(@test_files_cache), 'get_cache: touch strange W/tmp/cache/...' ) ;
  4637. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  4638. # on live:
  4639. $msgs_1 = [120, 142, 143, 144, 177 ] ;
  4640. $msgs_2 = [ 242, 243, 299, 377, 777, 255 ] ;
  4641. $msgs_all_1 = { 120 => q{}, 142 => q{}, 143 => q{}, 144 => q{}, 177 => q{} } ;
  4642. $msgs_all_2 = { 242 => q{}, 243 => q{}, 299 => q{}, 377 => q{}, 777 => q{}, 255 => q{} } ;
  4643. ok( ( $c12, $c21 ) = get_cache('W/tmp/cache/rr\uee', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2), 'get_cache: strange path 02' );
  4644. $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  4645. $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  4646. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: strange path 03' );
  4647. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: strange path 04' );
  4648. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 142_242');
  4649. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 143_243');
  4650. ok( ! -f 'W/tmp/cache/rr\uee/100_200', 'get_cache: strange path file removed 100_200');
  4651. ok( ! -f 'W/tmp/cache/rr\uee/101_201', 'get_cache: strange path file removed 101_201');
  4652. return ;
  4653. }
  4654. sub match_a_cache_file {
  4655. my $file = shift ;
  4656. my ( $cache_uid1, $cache_uid2 ) ;
  4657. return( ( undef, undef ) ) if ( ! $file ) ;
  4658. if ( $file =~ m{(?:^|/)(\d+)_(\d+)$}x ) {
  4659. $cache_uid1 = $1 ;
  4660. $cache_uid2 = $2 ;
  4661. }
  4662. return( $cache_uid1, $cache_uid2 ) ;
  4663. }
  4664. sub tests_match_a_cache_file {
  4665. my ( $tuid1, $tuid2 ) ;
  4666. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( ), 'match_a_cache_file: no arg' ) ;
  4667. ok( ! defined $tuid1 , 'match_a_cache_file: no arg 1' ) ;
  4668. ok( ! defined $tuid2 , 'match_a_cache_file: no arg 2' ) ;
  4669. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( q{} ), 'match_a_cache_file: empty arg' ) ;
  4670. ok( ! defined $tuid1 , 'match_a_cache_file: empty arg 1' ) ;
  4671. ok( ! defined $tuid2 , 'match_a_cache_file: empty arg 2' ) ;
  4672. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '000_000' ), 'match_a_cache_file: 000_000' ) ;
  4673. ok( '000' eq $tuid1, 'match_a_cache_file: 000_000 1' ) ;
  4674. ok( '000' eq $tuid2, 'match_a_cache_file: 000_000 2' ) ;
  4675. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '123_456' ), 'match_a_cache_file: 123_456' ) ;
  4676. ok( '123' eq $tuid1, 'match_a_cache_file: 123_456 1' ) ;
  4677. ok( '456' eq $tuid2, 'match_a_cache_file: 123_456 2' ) ;
  4678. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/tmp/truc/123_456' ), 'match_a_cache_file: /tmp/truc/123_456' ) ;
  4679. ok( '123' eq $tuid1, 'match_a_cache_file: /tmp/truc/123_456 1' ) ;
  4680. ok( '456' eq $tuid2, 'match_a_cache_file: /tmp/truc/123_456 2' ) ;
  4681. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/lala123_456' ), 'match_a_cache_file: NO /lala123_456' ) ;
  4682. ok( ! $tuid1, 'match_a_cache_file: /lala123_456 1' ) ;
  4683. ok( ! $tuid2, 'match_a_cache_file: /lala123_456 2' ) ;
  4684. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( 'la123_456' ), 'match_a_cache_file: NO la123_456' ) ;
  4685. ok( ! $tuid1, 'match_a_cache_file: la123_456 1' ) ;
  4686. ok( ! $tuid2, 'match_a_cache_file: la123_456 2' ) ;
  4687. return ;
  4688. }
  4689. sub clean_cache {
  4690. my ( $cache_files_ref, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_ ;
  4691. $debugcache and myprint( "Entering clean_cache\n" ) ;
  4692. $debugcache and myprint( map { "$_ -> " . $cache_1_2_ref->{ $_ } . "\n" } keys %{ $cache_1_2_ref } ) ;
  4693. foreach my $file ( @{ $cache_files_ref } ) {
  4694. $debugcache and myprint( "$file\n" ) ;
  4695. my ( $cache_uid1, $cache_uid2 ) = match_a_cache_file( $file ) ;
  4696. $debugcache and myprint( "u1: $cache_uid1 u2: $cache_uid2 c12: ", $cache_1_2_ref->{ $cache_uid1 } || q{}, "\n") ;
  4697. # or ( ! exists( $cache_1_2_ref->{ $cache_uid1 } ) )
  4698. # or ( ! ( $cache_uid2 == $cache_1_2_ref->{ $cache_uid1 } ) )
  4699. if ( ( not defined $cache_uid1 )
  4700. or ( not defined $cache_uid2 )
  4701. or ( not exists $h1_msgs_all_hash_ref->{ $cache_uid1 } )
  4702. or ( not exists $h2_msgs_all_hash_ref->{ $cache_uid2 } )
  4703. ) {
  4704. $debugcache and myprint( "remove $file\n" ) ;
  4705. unlink $file or myprint( "$!" ) ;
  4706. }
  4707. }
  4708. $debugcache and myprint( "Exiting clean_cache\n" ) ;
  4709. return( 1 ) ;
  4710. }
  4711. sub tests_clean_cache {
  4712. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache: rmtree W/tmp/cache/G1/G2' ) ;
  4713. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache: mkpath W/tmp/cache/G1/G2' ) ;
  4714. my @test_files_cache = ( qw(
  4715. W/tmp/cache/G1/G2/100_200
  4716. W/tmp/cache/G1/G2/101_201
  4717. W/tmp/cache/G1/G2/120_220
  4718. W/tmp/cache/G1/G2/142_242
  4719. W/tmp/cache/G1/G2/143_243
  4720. W/tmp/cache/G1/G2/177_277
  4721. W/tmp/cache/G1/G2/177_377
  4722. W/tmp/cache/G1/G2/177_777
  4723. W/tmp/cache/G1/G2/155_255
  4724. ) ) ;
  4725. ok( touch(@test_files_cache), 'clean_cache: touch W/tmp/cache/G1/G2/...' ) ;
  4726. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 before' );
  4727. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 before' );
  4728. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 before' );
  4729. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 before' );
  4730. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 before' );
  4731. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 before' );
  4732. my $cache = {
  4733. 142 => 242,
  4734. 177 => 777,
  4735. } ;
  4736. my $all_1 = {
  4737. 142 => q{},
  4738. 177 => q{},
  4739. } ;
  4740. my $all_2 = {
  4741. 200 => q{},
  4742. 242 => q{},
  4743. 777 => q{},
  4744. } ;
  4745. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache: ' ) ;
  4746. ok( ! -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 after' );
  4747. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 after' );
  4748. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 after' );
  4749. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 after' );
  4750. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 after' );
  4751. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 after' );
  4752. return ;
  4753. }
  4754. sub tests_clean_cache_2 {
  4755. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache_2: rmtree W/tmp/cache/G1/G2' ) ;
  4756. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache_2: mkpath W/tmp/cache/G1/G2' ) ;
  4757. my @test_files_cache = ( qw(
  4758. W/tmp/cache/G1/G2/100_200
  4759. W/tmp/cache/G1/G2/101_201
  4760. W/tmp/cache/G1/G2/120_220
  4761. W/tmp/cache/G1/G2/142_242
  4762. W/tmp/cache/G1/G2/143_243
  4763. W/tmp/cache/G1/G2/177_277
  4764. W/tmp/cache/G1/G2/177_377
  4765. W/tmp/cache/G1/G2/177_777
  4766. W/tmp/cache/G1/G2/155_255
  4767. ) ) ;
  4768. ok( touch(@test_files_cache), 'clean_cache_2: touch W/tmp/cache/G1/G2/...' ) ;
  4769. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 before' );
  4770. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 before' );
  4771. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 before' );
  4772. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 before' );
  4773. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 before' );
  4774. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 before' );
  4775. my $cache = {
  4776. 142 => 242,
  4777. 177 => 777,
  4778. } ;
  4779. my $all_1 = {
  4780. $NUMBER_100 => q{},
  4781. 142 => q{},
  4782. 177 => q{},
  4783. } ;
  4784. my $all_2 = {
  4785. 200 => q{},
  4786. 242 => q{},
  4787. 777 => q{},
  4788. } ;
  4789. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache_2: ' ) ;
  4790. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 after' );
  4791. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 after' );
  4792. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 after' );
  4793. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 after' );
  4794. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 after' );
  4795. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 after' );
  4796. return ;
  4797. }
  4798. sub tests_mkpath {
  4799. ok( 1 == 1, 'tests_mkpath: 1 == 1' ) ;
  4800. SKIP: {
  4801. skip( 'Tests only for Unix', 2 ) if ( 'MSWin32' eq $OSNAME ) ;
  4802. my $long_path_unix = '123456789/' x 30 ;
  4803. ok( (-d "W/tmp/tests/long/$long_path_unix" or mkpath( "W/tmp/tests/long/$long_path_unix" ) ), 'tests_mkpath: mkpath > 300 char' ) ;
  4804. ok( (-d "W/tmp/tests/long/$long_path_unix" and rmtree( 'W/tmp/tests/long/' ) ), 'tests_mkpath: rmtree > 300 char' ) ;
  4805. } ;
  4806. SKIP: {
  4807. skip( 'Tests only for MSWin32', 6 ) if ( 'MSWin32' ne $OSNAME ) ;
  4808. my $long_path_2_prefix = "$tmpdir\\imapsync_tests" || '\\\?\\E:\\TEMP\\imapsync_tests' ;
  4809. myprint( "long_path_2_prefix: $long_path_2_prefix\n" ) ;
  4810. my $long_path_2 = $long_path_2_prefix . '\\' . '123456789\\' x 10 . 'END' ;
  4811. my $long_path_300 = $long_path_2_prefix . '\\' . '123456789\\' x 30 . 'END' ;
  4812. myprint( "$long_path_2\n" ) ;
  4813. #ok( ( -d $long_path_2_prefix and rmtree( $long_path_2_prefix ) ), 'tests_mkpath: rmtree > 200 char' ) ;
  4814. #ok( ( -d $long_path_2_prefix or mkpath( "\\\\\?\\E:\\\\TEMP\\imapsync_tests" ) ), 'tests_mkpath: -d small path 1' ) ;
  4815. ok( ( -d $long_path_2_prefix or mkpath( $long_path_2_prefix ) ), 'tests_mkpath: -d mkpath small path' ) ;
  4816. ok( ( -d $long_path_2_prefix ), 'tests_mkpath: -d mkpath small path done' ) ;
  4817. ok( ( -d $long_path_2 or mkpath( $long_path_2 ) ), 'tests_mkpath: mkpath > 200 char' ) ;
  4818. ok( ( -d $long_path_2 ), 'tests_mkpath: -d mkpath > 200 char done' ) ;
  4819. ok( ( -d $long_path_2_prefix and rmtree( $long_path_2_prefix ) ), 'tests_mkpath: rmtree > 200 char' ) ;
  4820. ok( (! -d $long_path_2_prefix ), 'tests_mkpath: ! -d rmtree done' ) ;
  4821. myprint( "$long_path_300\n" ) ;
  4822. # This one just kill the whole process without a whisper:
  4823. #ok( ( -d $long_path_300 or mkpath( $long_path_300 ) ), 'tests_mkpath: mkpath fails > 300 char' ) ;
  4824. #ok( ( -d $long_path_300 and rmtree( $long_path_300 ) ), 'tests_mkpath: rmtree \ > 300 char' ) ;
  4825. } ;
  4826. return 1 ;
  4827. }
  4828. sub tests_touch {
  4829. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' )), 'tests_touch: mkpath W/tmp/tests/' ) ;
  4830. ok( 1 == touch( 'W/tmp/tests/lala'), 'tests_touch: W/tmp/tests/lala') ;
  4831. ok( 1 == touch( 'W/tmp/tests/\y'), 'tests_touch: W/tmp/tests/\y') ;
  4832. ok( 0 == touch( '/no/no/no/aaa'), 'tests_touch: not /aaa') ;
  4833. ok( 1 == touch( 'W/tmp/tests/lili', 'W/tmp/tests/lolo'), 'tests_touch: 2 files') ;
  4834. ok( 0 == touch( 'W/tmp/tests/\y', '/no/no/aaa'), 'tests_touch: 2 files, 1 fails' ) ;
  4835. return ;
  4836. }
  4837. sub touch {
  4838. my @files = @_ ;
  4839. my $failures = 0 ;
  4840. foreach my $file ( @files ) {
  4841. my $fh = IO::File->new ;
  4842. if ( $fh->open(">> $file" ) ) {
  4843. $fh->close ;
  4844. }else{
  4845. myprint( "Could not open file $file in write/append mode\n" ) ;
  4846. $failures++ ;
  4847. }
  4848. }
  4849. return( ! $failures );
  4850. }
  4851. sub tests_tmpdir_has_colon_bug {
  4852. ok( 0 == tmpdir_has_colon_bug( q{} ), 'tmpdir_has_colon_bug: ' ) ;
  4853. ok( 0 == tmpdir_has_colon_bug( '/tmp' ), 'tmpdir_has_colon_bug: /tmp' ) ;
  4854. ok( 1 == tmpdir_has_colon_bug( 'C:' ), 'tmpdir_has_colon_bug: C:' ) ;
  4855. ok( 1 == tmpdir_has_colon_bug( 'C:\temp' ), 'tmpdir_has_colon_bug: C:\temp' ) ;
  4856. return( 0 ) ;
  4857. }
  4858. sub tmpdir_has_colon_bug {
  4859. my $path = shift ;
  4860. my $path_filtered = filter_forbidden_characters( $path ) ;
  4861. if ( $path_filtered ne $path ) {
  4862. ( -d $path_filtered ) and myprint( "Path $path was previously mistakely changed to $path_filtered\n" ) ;
  4863. return( 1 ) ;
  4864. }
  4865. return( 0 ) ;
  4866. }
  4867. sub tmpdir_fix_colon_bug {
  4868. my $err = 0 ;
  4869. if ( not (-d $tmpdir and -r _ and -w _) ) {
  4870. myprint( "tmpdir $tmpdir is not valid\n" ) ;
  4871. return( 0 ) ;
  4872. }
  4873. my $cachedir_new = "$tmpdir/imapsync_cache" ;
  4874. if ( not tmpdir_has_colon_bug( $cachedir_new ) ) { return( 0 ) } ;
  4875. # check if old cache directory already exists
  4876. my $cachedir_old = filter_forbidden_characters( $cachedir_new ) ;
  4877. if ( not ( -d $cachedir_old ) ) {
  4878. myprint( "Old cache directory $cachedir_new no exists, nothing to do\n" ) ;
  4879. return( 1 ) ;
  4880. }
  4881. # check if new cache directory already exists
  4882. if ( -d $cachedir_new ) {
  4883. myprint( "New fixed cache directory $cachedir_new already exists, not moving the old one $cachedir_old. Fix this manually.\n" ) ;
  4884. return( 0 ) ;
  4885. }else{
  4886. # move the old one to the new place
  4887. myprint( "Moving $cachedir_old to $cachedir_new Do not interrupt this task.\n" ) ;
  4888. File::Copy::Recursive::rmove( $cachedir_old, $cachedir_new )
  4889. or do {
  4890. myprint( "Could not move $cachedir_old to $cachedir_new\n" ) ;
  4891. $err++ ;
  4892. } ;
  4893. # check it succeeded
  4894. if ( -d $cachedir_new and -r _ and -w _ ) {
  4895. myprint( "New fixed cache directory $cachedir_new ok\n" ) ;
  4896. }else{
  4897. myprint( "New fixed cache directory $cachedir_new does not exist\n" ) ;
  4898. $err++ ;
  4899. }
  4900. if ( -d $cachedir_old ) {
  4901. myprint( "Old cache directory $cachedir_old still exists\n" ) ;
  4902. $err++ ;
  4903. }else{
  4904. myprint( "Old cache directory $cachedir_old successfuly moved\n" ) ;
  4905. }
  4906. }
  4907. return( not $err ) ;
  4908. }
  4909. sub tests_cache_folder {
  4910. ok( '/path/fold1/fold2' eq cache_folder( q{}, '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  4911. ok( '/pa_th/fold1/fold2' eq cache_folder( q{}, '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  4912. ok( '/_p_a__th/fol_d1/fold2' eq cache_folder( q{}, '/>p<a|*th', 'fol*d1', 'fold2'), 'cache_folder: />p<a|*th, fol*d1, fold2 -> /path/fol_d1/fold2' ) ;
  4913. ok( 'D:/path/fold1/fold2' eq cache_folder( 'D:', '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  4914. ok( 'D:/pa_th/fold1/fold2' eq cache_folder( 'D:', '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  4915. ok( 'D:/_p_a__th/fol_d1/fold2' eq cache_folder( 'D:', '/>p<a|*th', 'fol*d1', 'fold2'), 'cache_folder: />p<a|*th, fol*d1, fold2 -> /path/fol_d1/fold2' ) ;
  4916. ok( '//' eq cache_folder( q{}, q{}, q{}, q{}), 'cache_folder: -> //' ) ;
  4917. ok( '//_______' eq cache_folder( q{}, q{}, q{}, '*|?:"<>'), 'cache_folder: *|?:"<> -> //_______' ) ;
  4918. return ;
  4919. }
  4920. sub cache_folder {
  4921. my( $cache_base, $cache_dir, $h1_fold, $h2_fold ) = @_ ;
  4922. my $sep_1 = $h1_sep || '/';
  4923. my $sep_2 = $h2_sep || '/';
  4924. #myprint( "$cache_dir h1_fold $h1_fold sep1 $sep_1 h2_fold $h2_fold sep2 $sep_2\n" ) ;
  4925. $h1_fold = convert_sep_to_slash( $h1_fold, $sep_1 ) ;
  4926. $h2_fold = convert_sep_to_slash( $h2_fold, $sep_2 ) ;
  4927. my $cache_folder = "$cache_base" . filter_forbidden_characters( "$cache_dir/$h1_fold/$h2_fold" ) ;
  4928. #myprint( "cache_folder [$cache_folder]\n" ) ;
  4929. return( $cache_folder ) ;
  4930. }
  4931. sub filter_forbidden_characters {
  4932. my $string = shift ;
  4933. if ( 'MSWin32' eq $OSNAME ) {
  4934. # Move trailing whitespace to _ " a b /c d " -> " a b_/c d_"
  4935. $string =~ s{\ (/|$)}{_$1}xg ;
  4936. }
  4937. $string =~ s{[\Q*|?:"<>\E]}{_}xg ;
  4938. #myprint( "[$string]\n" ) ;
  4939. return( $string ) ;
  4940. }
  4941. sub tests_filter_forbidden_characters {
  4942. ok( 'a_b' eq filter_forbidden_characters( 'a_b' ), 'filter_forbidden_characters: a_b -> a_b' ) ;
  4943. ok( 'a_b' eq filter_forbidden_characters( 'a*b' ), 'filter_forbidden_characters: a*b -> a_b' ) ;
  4944. ok( 'a_b' eq filter_forbidden_characters( 'a|b' ), 'filter_forbidden_characters: a|b -> a_b' ) ;
  4945. ok( 'a_b' eq filter_forbidden_characters( 'a?b' ), 'filter_forbidden_characters: a?b -> a_b' ) ;
  4946. ok( 'a_______b' eq filter_forbidden_characters( 'a*|?:"<>b' ), 'filter_forbidden_characters: a*|?:"<>b -> a_______b' ) ;
  4947. SKIP: {
  4948. skip( 'Not on MSWin32', 1 ) if ( 'MSWin32' eq $OSNAME ) ;
  4949. ok( ( 'a b ' eq filter_forbidden_characters( 'a b ' ) ), 'filter_forbidden_characters: "a b " -> "a b "' ) ;
  4950. } ;
  4951. SKIP: {
  4952. skip( 'Only on MSWin32', 2 ) if ( 'MSWin32' ne $OSNAME ) ;
  4953. ok( ( ' a b_' eq filter_forbidden_characters( ' a b ' ) ), 'filter_forbidden_characters: "a b " -> "a b_"' ) ;
  4954. ok( ( ' a b_/ c d_' eq filter_forbidden_characters( ' a b / c d ' ) ), 'filter_forbidden_characters: " a b / c d " -> "a b_/ c d_"' ) ;
  4955. } ;
  4956. return ;
  4957. }
  4958. sub convert_sep_to_slash {
  4959. my ( $folder, $sep ) = @_ ;
  4960. $folder =~ s{\Q$sep\E}{/}xg ;
  4961. return( $folder ) ;
  4962. }
  4963. sub tests_convert_sep_to_slash {
  4964. ok(q{} eq convert_sep_to_slash(q{}, '/'), 'convert_sep_to_slash: no folder');
  4965. ok('INBOX' eq convert_sep_to_slash('INBOX', '/'), 'convert_sep_to_slash: INBOX');
  4966. ok('INBOX/foo' eq convert_sep_to_slash('INBOX/foo', '/'), 'convert_sep_to_slash: INBOX/foo');
  4967. ok('INBOX/foo' eq convert_sep_to_slash('INBOX_foo', '_'), 'convert_sep_to_slash: INBOX_foo');
  4968. ok('INBOX/foo/zob' eq convert_sep_to_slash('INBOX_foo_zob', '_'), 'convert_sep_to_slash: INBOX_foo_zob');
  4969. ok('INBOX/foo' eq convert_sep_to_slash('INBOX.foo', '.'), 'convert_sep_to_slash: INBOX.foo');
  4970. ok('INBOX/foo/hi' eq convert_sep_to_slash('INBOX.foo.hi', '.'), 'convert_sep_to_slash: INBOX.foo.hi');
  4971. return ;
  4972. }
  4973. sub tests_regexmess {
  4974. ok( 'blabla' eq regexmess( 'blabla' ), 'regexmess, no regexmess, nothing to do' ) ;
  4975. @regexmess = ( 'lalala' ) ;
  4976. ok( not( defined regexmess( 'popopo' ) ), 'regexmess, bad regex lalala' ) ;
  4977. @regexmess = ( 's/p/Z/g' ) ;
  4978. ok( 'ZoZoZo' eq regexmess( 'popopo' ), 'regexmess, s/p/Z/g' ) ;
  4979. @regexmess = ( 's{c}{C}gxms' ) ;
  4980. ok("H1: abC\nH2: Cde\n\nBody abC"
  4981. eq regexmess( "H1: abc\nH2: cde\n\nBody abc"),
  4982. 'regexmess, c->C');
  4983. @regexmess = ( 's{\AFrom\ }{From:}gxms' ) ;
  4984. ok( q{}
  4985. eq regexmess(q{}),
  4986. 'From mbox 1 add colon blank');
  4987. ok( 'From:<tartanpion@machin.truc>'
  4988. eq regexmess('From <tartanpion@machin.truc>'),
  4989. 'From mbox 2 add colo');
  4990. ok( "\n" . 'From <tartanpion@machin.truc>'
  4991. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  4992. 'From mbox 3 add colo') ;
  4993. ok( "From: zzz\n" . 'From <tartanpion@machin.truc>'
  4994. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  4995. 'From mbox 4 add colo') ;
  4996. @regexmess = ( 's{\AFrom\ [^\n]*(\n)?}{}gxms' ) ;
  4997. ok( q{}
  4998. eq regexmess(q{}),
  4999. 'From mbox 1 remove, blank');
  5000. ok( q{}
  5001. eq regexmess('From <tartanpion@machin.truc>'),
  5002. 'From mbox 2 remove');
  5003. ok( "\n" . 'From <tartanpion@machin.truc>'
  5004. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  5005. 'From mbox 3 remove');
  5006. #myprint( "[", regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'), "]" ) ;
  5007. ok( q{} . 'From <tartanpion@machin.truc>'
  5008. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  5009. 'From mbox 4 remove');
  5010. ok(
  5011. <<'EOM'
  5012. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5013. From:<tartanpion@machin.truc>
  5014. Hello,
  5015. Bye.
  5016. EOM
  5017. eq regexmess(
  5018. <<'EOM'
  5019. From zzz
  5020. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5021. From:<tartanpion@machin.truc>
  5022. Hello,
  5023. Bye.
  5024. EOM
  5025. ), 'From mbox 5 remove');
  5026. @regexmess = ( 's{\A((?:[^\n]+\n)+|)^Disposition-Notification-To:[^\n]*\n(\r?\n|.*\n\r?\n)}{$1$2}xms' ) ; # SUPER SUPER BEST!
  5027. ok(
  5028. <<'EOM'
  5029. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5030. From:<tartanpion@machin.truc>
  5031. Hello,
  5032. Bye.
  5033. EOM
  5034. eq regexmess(
  5035. <<'EOM'
  5036. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5037. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5038. From:<tartanpion@machin.truc>
  5039. Hello,
  5040. Bye.
  5041. EOM
  5042. ),
  5043. 'regexmess: 1 Delete header Disposition-Notification-To:');
  5044. ok(
  5045. <<'EOM'
  5046. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5047. From:<tartanpion@machin.truc>
  5048. Hello,
  5049. Bye.
  5050. EOM
  5051. eq regexmess(
  5052. <<'EOM'
  5053. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5054. From:<tartanpion@machin.truc>
  5055. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5056. Hello,
  5057. Bye.
  5058. EOM
  5059. ),
  5060. 'regexmess: 2 Delete header Disposition-Notification-To:');
  5061. ok(
  5062. <<'EOM'
  5063. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5064. From:<tartanpion@machin.truc>
  5065. Hello,
  5066. Bye.
  5067. EOM
  5068. eq regexmess(
  5069. <<'EOM'
  5070. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5071. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5072. From:<tartanpion@machin.truc>
  5073. Hello,
  5074. Bye.
  5075. EOM
  5076. ),
  5077. 'regexmess: 3 Delete header Disposition-Notification-To:');
  5078. ok(
  5079. <<'EOM'
  5080. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5081. From:<tartanpion@machin.truc>
  5082. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5083. Bye.
  5084. EOM
  5085. eq regexmess(
  5086. <<'EOM'
  5087. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5088. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5089. From:<tartanpion@machin.truc>
  5090. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5091. Bye.
  5092. EOM
  5093. ),
  5094. 'regexmess: 4 Delete header Disposition-Notification-To:');
  5095. ok(
  5096. <<'EOM'
  5097. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5098. From:<tartanpion@machin.truc>
  5099. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5100. Bye.
  5101. EOM
  5102. eq regexmess(
  5103. <<'EOM'
  5104. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5105. From:<tartanpion@machin.truc>
  5106. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5107. Bye.
  5108. EOM
  5109. ),
  5110. 'regexmess: 5 Delete header Disposition-Notification-To:');
  5111. ok(
  5112. <<'EOM'
  5113. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5114. From:<tartanpion@machin.truc>
  5115. Hello,
  5116. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5117. Bye.
  5118. EOM
  5119. eq regexmess(
  5120. <<'EOM'
  5121. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5122. From:<tartanpion@machin.truc>
  5123. Hello,
  5124. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5125. Bye.
  5126. EOM
  5127. ),
  5128. 'regexmess: 6 Delete header Disposition-Notification-To:');
  5129. ok(
  5130. <<'EOM'
  5131. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5132. From:<tartanpion@machin.truc>
  5133. Hello,
  5134. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5135. Bye.
  5136. EOM
  5137. eq regexmess(
  5138. <<'EOM'
  5139. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5140. From:<tartanpion@machin.truc>
  5141. Hello,
  5142. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5143. Bye.
  5144. EOM
  5145. ),
  5146. 'regexmess: 7 Delete header Disposition-Notification-To:');
  5147. ok(
  5148. <<'EOM'
  5149. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5150. From:<tartanpion@machin.truc>
  5151. Hello,
  5152. Bye.
  5153. EOM
  5154. eq regexmess(
  5155. <<'EOM'
  5156. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5157. From:<tartanpion@machin.truc>
  5158. Hello,
  5159. Bye.
  5160. EOM
  5161. ),
  5162. 'regexmess: 8 Delete header Disposition-Notification-To:');
  5163. ok(
  5164. <<'EOM'
  5165. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5166. From:<tartanpion@machin.truc>
  5167. Hello,
  5168. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5169. Bye.
  5170. EOM
  5171. eq regexmess(
  5172. <<'EOM'
  5173. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5174. From:<tartanpion@machin.truc>
  5175. Hello,
  5176. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5177. Bye.
  5178. EOM
  5179. ),
  5180. 'regexmess: 9 Delete header Disposition-Notification-To:');
  5181. ok(
  5182. <<'EOM'
  5183. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5184. From:<tartanpion@machin.truc>
  5185. Hello,
  5186. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5187. Bye.
  5188. EOM
  5189. eq regexmess(
  5190. <<'EOM'
  5191. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5192. From:<tartanpion@machin.truc>
  5193. Hello,
  5194. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5195. Bye.
  5196. EOM
  5197. ),
  5198. 'regexmess: 10 Delete header Disposition-Notification-To:');
  5199. ok(
  5200. <<'EOM'
  5201. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5202. From:<tartanpion@machin.truc>
  5203. Hello,
  5204. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5205. Bye.
  5206. EOM
  5207. eq regexmess(
  5208. <<'EOM'
  5209. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5210. From:<tartanpion@machin.truc>
  5211. Hello,
  5212. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5213. Bye.
  5214. EOM
  5215. ),
  5216. 'regexmess: 11 Delete header Disposition-Notification-To:');
  5217. ok(
  5218. <<'EOM'
  5219. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5220. From:<tartanpion@machin.truc>
  5221. Hello,
  5222. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5223. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5224. Bye.
  5225. EOM
  5226. eq regexmess(
  5227. <<'EOM'
  5228. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5229. From:<tartanpion@machin.truc>
  5230. Hello,
  5231. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5232. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5233. Bye.
  5234. EOM
  5235. ),
  5236. 'regexmess: 12 Delete header Disposition-Notification-To:');
  5237. @regexmess = ( 's{\A(.*?(?! ^$))^Disposition-Notification-To:(.*?)$}{$1X-Disposition-Notification-To:$2}igxms' ) ; # BAD!
  5238. @regexmess = ( 's{\A((?:[^\n]+\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims' ) ;
  5239. ok(
  5240. <<'EOM'
  5241. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5242. From:<tartanpion@machin.truc>
  5243. Hello,
  5244. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5245. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5246. Bye.
  5247. EOM
  5248. eq regexmess(
  5249. <<'EOM'
  5250. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5251. From:<tartanpion@machin.truc>
  5252. Hello,
  5253. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5254. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5255. Bye.
  5256. EOM
  5257. ),
  5258. 'regexmess: 13 Delete header Disposition-Notification-To:');
  5259. ok(
  5260. <<'EOM'
  5261. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5262. X-Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5263. From:<tartanpion@machin.truc>
  5264. Hello,
  5265. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5266. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5267. Bye.
  5268. EOM
  5269. eq regexmess(
  5270. <<'EOM'
  5271. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5272. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5273. From:<tartanpion@machin.truc>
  5274. Hello,
  5275. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5276. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5277. Bye.
  5278. EOM
  5279. ),
  5280. 'regexmess: 14 Delete header Disposition-Notification-To:');
  5281. ok(
  5282. <<'EOM'
  5283. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5284. X-Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5285. From:<tartanpion@machin.truc>
  5286. Hello,
  5287. Bye.
  5288. EOM
  5289. eq regexmess(
  5290. <<'EOM'
  5291. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5292. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5293. From:<tartanpion@machin.truc>
  5294. Hello,
  5295. Bye.
  5296. EOM
  5297. ),
  5298. 'regexmess: 15 Delete header Disposition-Notification-To:');
  5299. ok(
  5300. <<'EOM'
  5301. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5302. From:<tartanpion@machin.truc>
  5303. X-Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5304. Hello,
  5305. Bye.
  5306. EOM
  5307. eq regexmess(
  5308. <<'EOM'
  5309. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5310. From:<tartanpion@machin.truc>
  5311. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5312. Hello,
  5313. Bye.
  5314. EOM
  5315. ),
  5316. 'regexmess: 16 Delete header Disposition-Notification-To:');
  5317. ok(
  5318. <<'EOM'
  5319. X-Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5320. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5321. From:<tartanpion@machin.truc>
  5322. Hello,
  5323. Bye.
  5324. EOM
  5325. eq regexmess(
  5326. <<'EOM'
  5327. Disposition-Notification-To: Gilles LAMIRAL <gilles.lamiral@laposte.net>
  5328. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5329. From:<tartanpion@machin.truc>
  5330. Hello,
  5331. Bye.
  5332. EOM
  5333. ),
  5334. 'regexmess: 17 Delete header Disposition-Notification-To:');
  5335. # regex to play with Date: from the FAQ
  5336. #@regexmess = 's{\A(.*?(?! ^$))^Date:(.*?)$}{$1Date:$2\nX-Date:$2}gxms'
  5337. return ;
  5338. }
  5339. sub regexmess {
  5340. my ( $string ) = @_ ;
  5341. foreach my $regexmess ( @regexmess ) {
  5342. $debug and myprint( "eval \$string =~ $regexmess\n" ) ;
  5343. my $ret = eval "\$string =~ $regexmess ; 1" ;
  5344. #myprint( "eval [$ret]\n" ) ;
  5345. if ( ( not $ret ) or $@ ) {
  5346. myprint( "Error: eval regexmess '$regexmess': $@" ) ;
  5347. return( undef ) ;
  5348. }
  5349. }
  5350. $debug and myprint( "$string\n" ) ;
  5351. return( $string ) ;
  5352. }
  5353. sub tests_skipmess {
  5354. ok( not( defined skipmess( 'blabla' ) ), 'skipmess, no skipmess, no skip' ) ;
  5355. @skipmess = ('[') ;
  5356. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex [' ) ;
  5357. @skipmess = ('lalala') ;
  5358. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex lalala' ) ;
  5359. @skipmess = ('/popopo/') ;
  5360. ok( 1 == skipmess( 'popopo' ), 'skipmess, popopo match regex /popopo/' ) ;
  5361. @skipmess = ('/popopo/') ;
  5362. ok( 0 == skipmess( 'rrrrrr' ), 'skipmess, rrrrrr does not match regex /popopo/' ) ;
  5363. @skipmess = ('m{^$}') ;
  5364. ok( 1 == skipmess( q{} ), 'skipmess: empty string yes' ) ;
  5365. ok( 0 == skipmess( 'Hi!' ), 'skipmess: empty string no' ) ;
  5366. @skipmess = ('m{i}') ;
  5367. ok( 1 == skipmess( 'Hi!' ), 'skipmess: i string yes' ) ;
  5368. ok( 0 == skipmess( 'Bye!' ), 'skipmess: i string no' ) ;
  5369. @skipmess = ('m{[\x80-\xff]}') ;
  5370. ok( 0 == skipmess( 'Hi!' ), 'skipmess: i 8bit no' ) ;
  5371. ok( 1 == skipmess( "\xff" ), 'skipmess: \xff 8bit yes' ) ;
  5372. @skipmess = ('m{A}', 'm{B}') ;
  5373. ok( 0 == skipmess( 'Hi!' ), 'skipmess: A or B no' ) ;
  5374. ok( 0 == skipmess( 'lala' ), 'skipmess: A or B no' ) ;
  5375. ok( 0 == skipmess( "\xff" ), 'skipmess: A or B no' ) ;
  5376. ok( 1 == skipmess( 'AB' ), 'skipmess: A or B yes' ) ;
  5377. ok( 1 == skipmess( 'BA' ), 'skipmess: A or B yes' ) ;
  5378. ok( 1 == skipmess( 'AA' ), 'skipmess: A or B yes' ) ;
  5379. ok( 1 == skipmess( 'Ok Bye' ), 'skipmess: A or B yes' ) ;
  5380. @skipmess = ( 'm#\A((?:[^\n]+\n)+|)^Content-Type: Message/Partial;[^\n]*\n(?:\n|.*\n\n)#ism' ) ; # SUPER BEST!
  5381. ok( 1 == skipmess(
  5382. <<'EOM'
  5383. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5384. Content-Type: Message/Partial; blabla
  5385. From:<tartanpion@machin.truc>
  5386. Hello!
  5387. Bye.
  5388. EOM
  5389. ),
  5390. 'skipmess: 1 match Content-Type: Message/Partial' ) ;
  5391. ok( 0 == skipmess(
  5392. <<'EOM'
  5393. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5394. From:<tartanpion@machin.truc>
  5395. Hello!
  5396. Bye.
  5397. EOM
  5398. ),
  5399. 'skipmess: 2 not match Content-Type: Message/Partial' ) ;
  5400. ok( 1 == skipmess(
  5401. <<'EOM'
  5402. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5403. From:<tartanpion@machin.truc>
  5404. Content-Type: Message/Partial; blabla
  5405. Hello!
  5406. Bye.
  5407. EOM
  5408. ),
  5409. 'skipmess: 3 match Content-Type: Message/Partial' ) ;
  5410. ok( 0 == skipmess(
  5411. <<'EOM'
  5412. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5413. From:<tartanpion@machin.truc>
  5414. Hello!
  5415. Content-Type: Message/Partial; blabla
  5416. Bye.
  5417. EOM
  5418. ),
  5419. 'skipmess: 4 not match Content-Type: Message/Partial' ) ;
  5420. ok( 0 == skipmess(
  5421. <<'EOM'
  5422. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5423. From:<tartanpion@machin.truc>
  5424. Hello!
  5425. Content-Type: Message/Partial; blabla
  5426. Bye.
  5427. EOM
  5428. ),
  5429. 'skipmess: 5 not match Content-Type: Message/Partial' ) ;
  5430. ok( 1 == skipmess(
  5431. <<'EOM'
  5432. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5433. Content-Type: Message/Partial; blabla
  5434. From:<tartanpion@machin.truc>
  5435. Hello!
  5436. Content-Type: Message/Partial; blabla
  5437. Bye.
  5438. EOM
  5439. ),
  5440. 'skipmess: 6 match Content-Type: Message/Partial' ) ;
  5441. ok( 1 == skipmess(
  5442. <<'EOM'
  5443. Date: Sat, 10 Jul 2010 05:34:45 -0700
  5444. Content-Type: Message/Partial;
  5445. From:<tartanpion@machin.truc>
  5446. Hello!
  5447. Bye.
  5448. EOM
  5449. ),
  5450. 'skipmess: 7 match Content-Type: Message/Partial' ) ;
  5451. ok( 1 == skipmess(
  5452. <<'EOM'
  5453. Date: Wed, 2 Jul 2014 02:26:40 +0000
  5454. MIME-Version: 1.0
  5455. Content-Type: message/partial;
  5456. id="TAN_U_P<1404267997.00007489ed17>";
  5457. number=3;
  5458. total=3
  5459. 6HQ6Hh3CdXj77qEGixerQ6zHx0OnQ/Cf5On4W0Y6vtU2crABZQtD46Hx1EOh8dDz4+OnTr1G
  5460. Hello!
  5461. Bye.
  5462. EOM
  5463. ),
  5464. 'skipmess: 8 match Content-Type: Message/Partial' ) ;
  5465. ok( 1 == skipmess(
  5466. <<'EOM'
  5467. Return-Path: <gilles@lamiral.info>
  5468. Received: by lamiral.info (Postfix, from userid 1000)
  5469. id 21EB12443BF; Mon, 2 Mar 2015 15:38:35 +0100 (CET)
  5470. Subject: test: aethaecohngiexao
  5471. To: <tata@petite.lamiral.info>
  5472. X-Mailer: mail (GNU Mailutils 2.2)
  5473. Message-Id: <20150302143835.21EB12443BF@lamiral.info>
  5474. Content-Type: message/partial;
  5475. id="TAN_U_P<1404267997.00007489ed17>";
  5476. number=3;
  5477. total=3
  5478. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  5479. From: gilles@lamiral.info (Gilles LAMIRAL)
  5480. test: aethaecohngiexao
  5481. EOM
  5482. ),
  5483. 'skipmess: 9 match Content-Type: Message/Partial' ) ;
  5484. ok( 1 == skipmess(
  5485. <<'EOM'
  5486. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  5487. From: gilles@lamiral.info (Gilles LAMIRAL)
  5488. Content-Type: message/partial;
  5489. id="TAN_U_P<1404267997.00007489ed17>";
  5490. number=3;
  5491. total=3
  5492. test: aethaecohngiexao
  5493. EOM
  5494. . "lalala\n" x 3000000
  5495. ),
  5496. 'skipmess: 10 match Content-Type: Message/Partial' ) ;
  5497. ok( 0 == skipmess(
  5498. <<'EOM'
  5499. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  5500. From: gilles@lamiral.info (Gilles LAMIRAL)
  5501. test: aethaecohngiexao
  5502. EOM
  5503. . "lalala\n" x 3000000
  5504. ),
  5505. 'skipmess: 11 match Content-Type: Message/Partial' ) ;
  5506. ok( 0 == skipmess(
  5507. <<"EOM"
  5508. From: fff\r
  5509. To: fff\r
  5510. Subject: Testing imapsync --skipmess\r
  5511. Date: Mon, 22 Aug 2011 08:40:20 +0800\r
  5512. Mime-Version: 1.0\r
  5513. Content-Type: text/plain; charset=iso-8859-1\r
  5514. Content-Transfer-Encoding: 7bit\r
  5515. \r
  5516. EOM
  5517. . qq{!#"$%&'()*+,-./0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg\r\n } x 32730
  5518. ),
  5519. 'skipmess: 12 not match Content-Type: Message/Partial' ) ;
  5520. # Complex regular subexpression recursion limit (32766) exceeded with more lines
  5521. # exit;
  5522. return ;
  5523. }
  5524. sub skipmess {
  5525. my ( $string ) = @_ ;
  5526. my $match ;
  5527. #myprint( "$string\n" ) ;
  5528. foreach my $skipmess ( @skipmess ) {
  5529. $debug and myprint( "eval \$match = \$string =~ $skipmess\n" ) ;
  5530. my $ret = eval "\$match = \$string =~ $skipmess ; 1" ;
  5531. #myprint( "eval [$ret]\n" ) ;
  5532. $debug and myprint( "match [$match]\n" ) ;
  5533. if ( ( not $ret ) or $@ ) {
  5534. myprint( "Error: eval skipmess '$skipmess': $@" ) ;
  5535. return( undef ) ;
  5536. }
  5537. return( $match ) if ( $match ) ;
  5538. }
  5539. return( $match ) ;
  5540. }
  5541. sub tests_bytes_display_string {
  5542. is( 'NA', bytes_display_string( ), 'bytes_display_string: no args => NA' ) ;
  5543. is( 'NA', bytes_display_string( undef ), 'bytes_display_string: undef => NA' ) ;
  5544. is( 'NA', bytes_display_string( 'blabla' ), 'bytes_display_string: blabla => NA' ) ;
  5545. ok( '0.000 KiB' eq bytes_display_string( 0 ), 'bytes_display_string: 0' ) ;
  5546. ok( '0.001 KiB' eq bytes_display_string( 1 ), 'bytes_display_string: 1' ) ;
  5547. ok( '0.010 KiB' eq bytes_display_string( 10 ), 'bytes_display_string: 10' ) ;
  5548. ok( '1.000 MiB' eq bytes_display_string( 1048575 ), 'bytes_display_string: 1048575' ) ;
  5549. ok( '1.000 MiB' eq bytes_display_string( 1048576 ), 'bytes_display_string: 1048576' ) ;
  5550. ok( '1.000 GiB' eq bytes_display_string( 1073741823 ), 'bytes_display_string: 1073741823 ' ) ;
  5551. ok( '1.000 GiB' eq bytes_display_string( 1073741824 ), 'bytes_display_string: 1073741824 ' ) ;
  5552. ok( '1.000 TiB' eq bytes_display_string( 1099511627775 ), 'bytes_display_string: 1099511627775' ) ;
  5553. ok( '1.000 TiB' eq bytes_display_string( 1099511627776 ), 'bytes_display_string: 1099511627776' ) ;
  5554. ok( '1.000 PiB' eq bytes_display_string( 1125899906842623 ), 'bytes_display_string: 1125899906842623' ) ;
  5555. ok( '1.000 PiB' eq bytes_display_string( 1125899906842624 ), 'bytes_display_string: 1125899906842624' ) ;
  5556. ok( '1024.000 PiB' eq bytes_display_string( 1152921504606846975 ), 'bytes_display_string: 1152921504606846975' ) ;
  5557. ok( '1024.000 PiB' eq bytes_display_string( 1152921504606846976 ), 'bytes_display_string: 1152921504606846976' ) ;
  5558. ok( '1048576.000 PiB' eq bytes_display_string( 1180591620717411303424 ), 'bytes_display_string: 1180591620717411303424' ) ;
  5559. #myprint( bytes_display_string( 1180591620717411303424 ), "\n" ) ;
  5560. return ;
  5561. }
  5562. sub bytes_display_string {
  5563. my ( $bytes ) = @_ ;
  5564. my $readable_value = q{} ;
  5565. if ( ! defined( $bytes ) ) {
  5566. return( 'NA' ) ;
  5567. }
  5568. if ( not match_number( $bytes ) ) {
  5569. return( 'NA' ) ;
  5570. }
  5571. SWITCH: {
  5572. if ( abs( $bytes ) < ( 1000 * $KIBI ) ) {
  5573. $readable_value = mysprintf( '%.3f KiB', $bytes / $KIBI) ;
  5574. last SWITCH ;
  5575. }
  5576. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI ) ) {
  5577. $readable_value = mysprintf( '%.3f MiB', $bytes / ($KIBI * $KIBI) ) ;
  5578. last SWITCH ;
  5579. }
  5580. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI) ) {
  5581. $readable_value = mysprintf( '%.3f GiB', $bytes / ($KIBI * $KIBI * $KIBI) ) ;
  5582. last SWITCH ;
  5583. }
  5584. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI * $KIBI) ) {
  5585. $readable_value = mysprintf( '%.3f TiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI) ) ;
  5586. last SWITCH ;
  5587. } else {
  5588. $readable_value = mysprintf( '%.3f PiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI * $KIBI) ) ;
  5589. }
  5590. # if you have exabytes (EiB) of email to transfer, you have too much email!
  5591. }
  5592. #myprint( "$bytes = $readable_value\n" ) ;
  5593. return( $readable_value ) ;
  5594. }
  5595. sub stats {
  5596. my $sync_loc = shift ;
  5597. if ( ! $sync_loc->{stats} ) {
  5598. return ;
  5599. }
  5600. $timeend = time ;
  5601. my $timediff = $timeend - $sync_loc->{timestart} ;
  5602. my $timeend_str = localtime $timeend ;
  5603. my $memory_consumption = 0 ;
  5604. $memory_consumption = memory_consumption( ) || 0 ;
  5605. my $memory_ratio = ($max_msg_size_in_bytes) ?
  5606. mysprintf('%.1f', $memory_consumption / $max_msg_size_in_bytes) : 'NA' ;
  5607. my $host1_reconnect_count = $imap1->Reconnect_counter() || 0 ;
  5608. my $host2_reconnect_count = $imap2->Reconnect_counter() || 0 ;
  5609. myprint( "++++ Statistics\n" ) ;
  5610. myprint( "Transfer started on : $timestart_str\n" ) ;
  5611. myprint( "Transfer ended on : $timeend_str\n" ) ;
  5612. myprintf( "Transfer time : %.1f sec\n", $timediff ) ;
  5613. myprint( "Folders synced : $h1_folders_wanted_ct/$h1_folders_wanted_nb synced\n" ) ;
  5614. myprint( "Messages transferred : $nb_msg_transferred " ) ;
  5615. myprint( "(could be $nb_msg_skipped_dry_mode without dry mode)" ) if ( $dry ) ;
  5616. myprint( "\n" ) ;
  5617. myprint( "Messages skipped : $nb_msg_skipped\n" ) ;
  5618. myprint( "Messages found duplicate on host1 : $h1_nb_msg_duplicate\n" ) ;
  5619. myprint( "Messages found duplicate on host2 : $h2_nb_msg_duplicate\n" ) ;
  5620. myprint( "Messages void (noheader) on host1 : $h1_nb_msg_noheader\n" ) ;
  5621. myprint( "Messages void (noheader) on host2 : $h2_nb_msg_noheader\n" ) ;
  5622. myprint( "Messages deleted on host1 : $h1_nb_msg_deleted\n" ) ;
  5623. myprint( "Messages deleted on host2 : $h2_nb_msg_deleted\n" ) ;
  5624. myprintf( "Total bytes transferred : %s (%s)\n",
  5625. $total_bytes_transferred,
  5626. bytes_display_string( $total_bytes_transferred ) ) ;
  5627. myprintf( "Total bytes duplicate host1 : %s (%s)\n",
  5628. $h1_total_bytes_duplicate,
  5629. bytes_display_string( $h1_total_bytes_duplicate) ) ;
  5630. myprintf( "Total bytes duplicate host2 : %s (%s)\n",
  5631. $h2_total_bytes_duplicate,
  5632. bytes_display_string( $h2_total_bytes_duplicate) ) ;
  5633. myprintf( "Total bytes skipped : %s (%s)\n",
  5634. $total_bytes_skipped,
  5635. bytes_display_string( $total_bytes_skipped ) ) ;
  5636. myprintf( "Total bytes error : %s (%s)\n",
  5637. $total_bytes_error,
  5638. bytes_display_string( $total_bytes_error ) ) ;
  5639. $timediff ||= 1 ; # No division per 0
  5640. myprintf("Message rate : %.1f messages/s\n", $nb_msg_transferred / $timediff ) ;
  5641. myprintf("Average bandwidth rate : %.1f KiB/s\n", $total_bytes_transferred / $KIBI / $timediff ) ;
  5642. #myprint( "Reconnections to host1 : $host1_reconnect_count\n" ) ;
  5643. #myprint( "Reconnections to host2 : $host2_reconnect_count\n" ) ;
  5644. myprintf("Memory consumption : %.1f MiB\n", $memory_consumption / $KIBI / $KIBI ) ;
  5645. myprintf("Biggest message : %s bytes (%s)\n",
  5646. $max_msg_size_in_bytes,
  5647. bytes_display_string( $max_msg_size_in_bytes) ) ;
  5648. myprint( "Memory/biggest message ratio : $memory_ratio\n" ) ;
  5649. if ( $foldersizesatend and $foldersizes ) {
  5650. my $nb_msg_start_diff = diff_or_NA( $h2_nb_msg_start, $h1_nb_msg_start ) ;
  5651. my $bytes_start_diff = diff_or_NA( $h2_bytes_start, $h1_bytes_start ) ;
  5652. myprintf("Start difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_start_diff,
  5653. $bytes_start_diff,
  5654. bytes_display_string( $bytes_start_diff ) ) ;
  5655. my $nb_msg_end_diff = diff_or_NA( $h2_nb_msg_end, $h1_nb_msg_end ) ;
  5656. my $bytes_end_diff = diff_or_NA( $h2_bytes_end, $h1_bytes_end ) ;
  5657. myprintf("Final difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_end_diff,
  5658. $bytes_end_diff,
  5659. bytes_display_string( $bytes_end_diff ) ) ;
  5660. }
  5661. myprint( "Detected $sync->{nb_errors} errors\n\n" ) ;
  5662. myprint( $warn_release, "\n" ) ;
  5663. myprint( thank_author( ) ) ;
  5664. return ;
  5665. }
  5666. sub diff_or_NA {
  5667. my( $n1, $n2 ) = @ARG ;
  5668. if ( not defined $n1 or not defined $n2 ) {
  5669. return 'NA' ;
  5670. }
  5671. if ( not match_number( $n1 )
  5672. or not match_number( $n2 ) ) {
  5673. return 'NA' ;
  5674. }
  5675. return( $n1 - $n2 ) ;
  5676. }
  5677. sub match_number {
  5678. my $n = shift @ARG ;
  5679. if ( not defined $n ) {
  5680. return 0 ;
  5681. }
  5682. if ( $n =~ /[0-9]+\.?[0-9]?/ ) {
  5683. return 1 ;
  5684. }
  5685. else {
  5686. return 0 ;
  5687. }
  5688. }
  5689. sub tests_match_number {
  5690. is( 0, match_number( ), 'match_number: no parameters => 0' ) ;
  5691. is( 0, match_number( undef ), 'match_number: undef => 0' ) ;
  5692. is( 0, match_number( 'blabla' ), 'match_number: blabla => 0' ) ;
  5693. is( 1, match_number( 0 ), 'match_number: 0 => 1' ) ;
  5694. is( 1, match_number( 1 ), 'match_number: 1 => 1' ) ;
  5695. is( 1, match_number( 1.0 ), 'match_number: 1.0 => 1' ) ;
  5696. is( 1, match_number( 0.0 ), 'match_number: 0.0 => 1' ) ;
  5697. return ;
  5698. }
  5699. sub tests_diff_or_NA {
  5700. is( 'NA', diff_or_NA( ), 'diff_or_NA: no parameters => NA' ) ;
  5701. is( 'NA', diff_or_NA( undef ), 'diff_or_NA: undef => NA' ) ;
  5702. is( 'NA', diff_or_NA( undef, undef ), 'diff_or_NA: undef undef => NA' ) ;
  5703. is( 'NA', diff_or_NA( undef, 1 ), 'diff_or_NA: undef 1 => NA' ) ;
  5704. is( 'NA', diff_or_NA( 1, undef ), 'diff_or_NA: 1 undef => NA' ) ;
  5705. is( 'NA', diff_or_NA( 'blabla', 1 ), 'diff_or_NA: blabla 1 => NA' ) ;
  5706. is( 'NA', diff_or_NA( 1, 'blabla' ), 'diff_or_NA: 1 blabla => NA' ) ;
  5707. is( 0, diff_or_NA( 1, 1 ), 'diff_or_NA: 1 1 => 0' ) ;
  5708. is( 1, diff_or_NA( 1, 0 ), 'diff_or_NA: 1 0 => 1' ) ;
  5709. is( -1, diff_or_NA( 0, 1 ), 'diff_or_NA: 0 1 => -1' ) ;
  5710. is( 0, diff_or_NA( 1.0, 1 ), 'diff_or_NA: 1.0 1 => 0' ) ;
  5711. is( 1, diff_or_NA( 1.0, 0 ), 'diff_or_NA: 1.0 0 => 1' ) ;
  5712. is( -1, diff_or_NA( 0, 1.0 ), 'diff_or_NA: 0 1.0 => -1' ) ;
  5713. return ;
  5714. }
  5715. sub thank_author {
  5716. return( "Homepage: http://imapsync.lamiral.info/\n" ) ;
  5717. }
  5718. sub load_modules {
  5719. if ( $ssl1 or $ssl2 or $tls1 or $tls2) {
  5720. # not yet a "use" statement
  5721. require IO::Socket::SSL ;
  5722. if ( $sync->{inet4} ) {
  5723. IO::Socket::SSL->import( 'inet4' ) ;
  5724. }
  5725. if ( $sync->{inet6} ) {
  5726. IO::Socket::SSL->import( 'inet6' ) ;
  5727. }
  5728. }
  5729. if ( ( ( not( $password1 or $passfile1 ) )
  5730. or (not ( $password2 or $passfile2 ) )
  5731. )
  5732. and ( not $help ) ) {
  5733. # now a "use" statement
  5734. #require Term::ReadKey ;
  5735. }
  5736. return ;
  5737. }
  5738. sub parse_header_msg {
  5739. my ( $imap, $m_uid, $s_heads, $s_fir, $side, $s_hash ) = @_ ;
  5740. my $head = $s_heads->{$m_uid} ;
  5741. my $headnum = scalar keys %{ $head } ;
  5742. $debug and myprint( "$side uid $m_uid head nb pass one: ", $headnum, "\n" ) ;
  5743. if ( ( ! $headnum ) and ( $wholeheaderifneeded ) ){
  5744. myprint( "$side uid $m_uid no header by parse_headers so taking whole header with BODY.PEEK[HEADER]\n" ) ;
  5745. $imap->fetch($m_uid, 'BODY.PEEK[HEADER]' ) ;
  5746. my $whole_header = $imap->_transaction_literals ;
  5747. #myprint( $whole_header ) ;
  5748. $head = decompose_header( $whole_header ) ;
  5749. $headnum = scalar keys %{ $head } ;
  5750. $debug and myprint( "$side uid $m_uid head nb pass two: ", $headnum, "\n" ) ;
  5751. }
  5752. #myprint( Data::Dumper->Dump( [ $head, \%useheader ] ) ) ;
  5753. my $headstr ;
  5754. $headstr = header_construct( $head, $side, $m_uid ) ;
  5755. if ( ( ! $headstr) and ( $addheader ) and ( $side eq 'Host1' ) ) {
  5756. my $header = add_header( $m_uid ) ;
  5757. myprint( "Host1 uid $m_uid no header found so adding our own [$header]\n" ) ;
  5758. $headstr .= uc $header ;
  5759. $s_fir->{$m_uid}->{NO_HEADER} = 1;
  5760. }
  5761. return if ( ! $headstr ) ;
  5762. my $size = $s_fir->{$m_uid}->{'RFC822.SIZE'} ;
  5763. my $flags = $s_fir->{$m_uid}->{'FLAGS'} ;
  5764. my $idate = $s_fir->{$m_uid}->{'INTERNALDATE'} ;
  5765. $size = length $headstr unless ( $size ) ;
  5766. my $m_md5 = md5_base64( $headstr ) ;
  5767. $debug and myprint( "$side uid $m_uid sig $m_md5 size $size idate $idate\n" ) ;
  5768. my $key ;
  5769. if ($skipsize) {
  5770. $key = "$m_md5";
  5771. }
  5772. else {
  5773. $key = "$m_md5:$size";
  5774. }
  5775. # 0 return code is used to identify duplicate message hash
  5776. return 0 if exists $s_hash->{"$key"};
  5777. $s_hash->{"$key"}{'5'} = $m_md5;
  5778. $s_hash->{"$key"}{'s'} = $size;
  5779. $s_hash->{"$key"}{'D'} = $idate;
  5780. $s_hash->{"$key"}{'F'} = $flags;
  5781. $s_hash->{"$key"}{'m'} = $m_uid;
  5782. return( 1 ) ;
  5783. }
  5784. sub header_construct {
  5785. my( $head, $side, $m_uid ) = @_ ;
  5786. my $headstr ;
  5787. foreach my $h ( sort keys %{ $head } ) {
  5788. next if ( not ( exists $useheader{ uc $h } )
  5789. and ( not exists $useheader{ 'ALL' } )
  5790. ) ;
  5791. foreach my $val ( sort @{$head->{$h}} ) {
  5792. my $H = header_line_normalize( $h, $val ) ;
  5793. # show stuff in debug mode
  5794. $debug and myprint( "$side uid $m_uid header [$H]", "\n" ) ;
  5795. if ($skipheader and $H =~ m/$skipheader/xi) {
  5796. $debug and myprint( "$side uid $m_uid skipping header [$H]\n" ) ;
  5797. next ;
  5798. }
  5799. $headstr .= "$H" ;
  5800. }
  5801. }
  5802. return( $headstr ) ;
  5803. }
  5804. sub header_line_normalize {
  5805. my( $header_key, $header_val ) = @_ ;
  5806. # no 8-bit data in headers !
  5807. $header_val =~ s/[\x80-\xff]/X/xog;
  5808. # change tabulations to space (Gmail bug on with "Received:" on multilines)
  5809. $header_val =~ s/\t/\ /xgo ;
  5810. # remove the first blanks ( dbmail bug? )
  5811. $header_val =~ s/^\s*//xo;
  5812. # remove the last blanks ( Gmail bug )
  5813. $header_val =~ s/\s*$//xo;
  5814. # remove successive blanks ( Mailenable does it )
  5815. $header_val =~ s/\s+/ /xgo;
  5816. # remove Message-Id value domain part ( Mailenable changes it )
  5817. if ( ( $messageidnodomain ) and ( 'MESSAGE-ID' eq uc $header_key ) ) { $header_val =~ s/^([^@]+).*$/$1/xo ; }
  5818. # and uppercase header line
  5819. # (dbmail and dovecot)
  5820. my $header_line = uc "$header_key: $header_val" ;
  5821. return( $header_line ) ;
  5822. }
  5823. sub tests_header_line_normalize {
  5824. ok( ': ' eq header_line_normalize( q{}, q{} ), 'header_line_normalize: empty args' ) ;
  5825. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', 'vvv' ), 'header_line_normalize: hhh vvv ' ) ;
  5826. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', ' vvv' ), 'header_line_normalize: remove first blancs' ) ;
  5827. ok( 'HHH: AA BB CCC D' eq header_line_normalize( 'hhh', 'aa bb ccc d' ), 'header_line_normalize: remove succesive blanks' ) ;
  5828. ok( 'HHH: AA BB CCC' eq header_line_normalize( 'hhh', 'aa bb ccc ' ), 'header_line_normalize: remove last blanks' ) ;
  5829. ok( 'HHH: VVV XX YY' eq header_line_normalize( 'hhh', "vvv\t\txx\tyy" ), 'header_line_normalize: tabs' ) ;
  5830. ok( 'HHH: XABX' eq header_line_normalize( 'hhh', "\x80AB\xff" ), 'header_line_normalize: 8bit' ) ;
  5831. return ;
  5832. }
  5833. sub firstline {
  5834. # extract the first line of a file (without \n)
  5835. my( $file ) = @_ ;
  5836. my $line = q{} ;
  5837. my $FILE ;
  5838. open $FILE, '<', $file or do {
  5839. myprint( "Error opening file $file : $!\n" ) ;
  5840. return ;
  5841. } ;
  5842. $line = <$FILE> || q{} ;
  5843. close $FILE ;
  5844. chomp $line ;
  5845. return $line ;
  5846. }
  5847. sub tests_firstline {
  5848. is( 1 , string_to_file( "blabla\n", 'tmp/firstline.txt' ), 'tests_firstline: put blabla in tmp/firstline.txt' ) ;
  5849. is( 'blabla' , firstline( 'tmp/firstline.txt' ), 'tests_firstline: get blabla from tmp/firstline.txt' ) ;
  5850. is( undef , firstline( 'tmp/noexist.txt' ), 'tests_firstline: get blabla from tmp/noexist.txt' ) ;
  5851. is( 1 , string_to_file( q{}, 'tmp/firstline2.txt' ), 'tests_firstline: put empty string in tmp/firstline2.txt' ) ;
  5852. is( q{} , firstline( 'tmp/firstline2.txt' ), 'tests_firstline: get empty string from tmp/firstline2.txt' ) ;
  5853. is( 1 , string_to_file( "\n", 'tmp/firstline3.txt' ), 'tests_firstline: put CR in tmp/firstline3.txt' ) ;
  5854. is( q{} , firstline( 'tmp/firstline3.txt' ), 'tests_firstline: get empty string from tmp/firstline3.txt' ) ;
  5855. return ;
  5856. }
  5857. sub file_to_string {
  5858. my( $file ) = @_ ;
  5859. my @string ;
  5860. open my $FILE, '<', $file or die_clean( "Error with file $file : $! " ) ;
  5861. @string = <$FILE> ;
  5862. close $FILE ;
  5863. return( join q{}, @string ) ;
  5864. }
  5865. sub string_to_file {
  5866. my( $string, $file ) = @_ ;
  5867. sysopen( FILE, $file, O_WRONLY|O_TRUNC|O_CREAT, 0600) or die_clean( "$! $file" ) ;
  5868. print FILE $string ;
  5869. close FILE ;
  5870. return 1 ;
  5871. }
  5872. q^
  5873. This is a multiline comment.
  5874. Based on David Carter discussion, to do:
  5875. * Call parameters stay the same.
  5876. * Now always "return( $string, $error )". Descriptions below.
  5877. OK * Still capture STDOUT via "1> $output_tmpfile" to finish in $string and "return( $string, $error )"
  5878. OK * Now also capture STDERR via "2> $error_tmpfile" to finish in $error and "return( $string, $error )"
  5879. OK * in case of CHILD_ERROR, return( undef, $error )
  5880. and print $error, with folder/UID/maybeSubject context,
  5881. on console and at the end with the final error listing. Count this as a sync error.
  5882. * in case of good command, take final $string as is, unless void. In case $error with value then print it.
  5883. * in case of good command and final $string empty, consider it like CHILD_ERROR =>
  5884. return( undef, $error ) and print $error, with folder/UID/maybeSubject context,
  5885. on console and at the end with the final error listing. Count this as a sync error.
  5886. ^ if 0 ; # End of multiline comment.
  5887. sub pipemess {
  5888. my ( $string, @commands ) = @_ ;
  5889. my $error = q{} ;
  5890. foreach my $command ( @commands ) {
  5891. my $input_tmpfile = "$tmpdir/imapsync_tmp_file.$PROCESS_ID.inp.txt" ;
  5892. my $output_tmpfile = "$tmpdir/imapsync_tmp_file.$PROCESS_ID.out.txt" ;
  5893. my $error_tmpfile = "$tmpdir/imapsync_tmp_file.$PROCESS_ID.err.txt" ;
  5894. string_to_file( $string, $input_tmpfile ) ;
  5895. ` $command < $input_tmpfile 1> $output_tmpfile 2> $error_tmpfile ` ;
  5896. my $is_command_ko = $CHILD_ERROR ;
  5897. my $error_cmd = file_to_string( $error_tmpfile ) ;
  5898. chomp( $error_cmd ) ;
  5899. $string = file_to_string( $output_tmpfile ) ;
  5900. my $string_len = length( $string ) ;
  5901. unlink $input_tmpfile, $output_tmpfile, $error_tmpfile ;
  5902. if ( $is_command_ko or ( ! $string_len ) ) {
  5903. my $cmd_exit_value = $CHILD_ERROR >> 8 ;
  5904. my $cmd_end_signal = $CHILD_ERROR & 127 ;
  5905. my $signal_log = ( $cmd_end_signal ) ? " signal $cmd_end_signal and" : q{} ;
  5906. my $error_log = qq{Failure: --pipemess command "$command" ended with$signal_log "$string_len" characters exit value "$cmd_exit_value" and STDERR "$error_cmd"\n} ;
  5907. myprint( $error_log ) ;
  5908. if ( wantarray ) {
  5909. return @{ [ undef, $error_log ] }
  5910. }else{
  5911. return ;
  5912. }
  5913. }
  5914. if ( $error_cmd ) {
  5915. $error .= qq{STDERR of --pipemess "$command": $error_cmd\n} ;
  5916. myprint( qq{STDERR of --pipemess "$command": $error_cmd\n} ) ;
  5917. }
  5918. }
  5919. #myprint( "[$string]\n" ) ;
  5920. if ( wantarray ) {
  5921. return ( $string, $error ) ;
  5922. }else{
  5923. return $string ;
  5924. }
  5925. }
  5926. sub tests_pipemess {
  5927. SKIP: {
  5928. Readonly my $NB_WIN_tests_pipemess => 3 ;
  5929. skip( 'Not on MSWin32', $NB_WIN_tests_pipemess ) if ('MSWin32' ne $OSNAME) ;
  5930. # Windows
  5931. # "type" command does not accept redirection of STDIN with <
  5932. # "sort" does
  5933. ok( "nochange\n" eq pipemess( 'nochange', 'sort' ), 'pipemess: nearly no change by sort' ) ;
  5934. ok( "nochange2\n" eq pipemess( 'nochange2', qw( sort sort ) ), 'pipemess: nearly no change by sort,sort' ) ;
  5935. # command not found
  5936. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  5937. ok( ! defined( pipemess( q{}, 'cacaprout' ) ), 'pipemess: command not found' ) ;
  5938. } ;
  5939. my ( $stringT, $errorT ) ;
  5940. SKIP: {
  5941. Readonly my $NB_UNX_tests_pipemess => 25 ;
  5942. skip( 'Not on Unix', $NB_UNX_tests_pipemess ) if ('MSWin32' eq $OSNAME) ;
  5943. # Unix
  5944. ok( 'nochange' eq pipemess( 'nochange', 'cat' ), 'pipemess: no change by cat' ) ;
  5945. ok( 'nochange2' eq pipemess( 'nochange2', 'cat', 'cat' ), 'pipemess: no change by cat,cat' ) ;
  5946. ok( " 1\tnumberize\n" eq pipemess( "numberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  5947. ok( " 1\tnumberize\n 2\tnumberize\n" eq pipemess( "numberize\nnumberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  5948. ok( "A\nB\nC\n" eq pipemess( "A\nC\nB\n", 'sort' ), 'pipemess: sort' ) ;
  5949. # command not found
  5950. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  5951. is( undef, pipemess( q{}, 'cacaprout' ), 'pipemess: command not found' ) ;
  5952. # success with true but no output at all
  5953. is( undef, pipemess( q{blabla}, 'true' ), 'pipemess: true but no output' ) ;
  5954. # failure with false and no output at all
  5955. is( undef, pipemess( q{blabla}, 'false' ), 'pipemess: false and no output' ) ;
  5956. # Failure since pipemess is not a real pipe, so first cat wait for standard input
  5957. is( q{blabla}, pipemess( q{blabla}, '( cat|cat ) ' ), 'pipemess: ok by ( cat|cat )' ) ;
  5958. ( $stringT, $errorT ) = pipemess( 'nochange', 'cat' ) ;
  5959. is( $stringT, 'nochange', 'pipemess: list context, no change by cat, string' ) ;
  5960. is( $errorT, q{}, 'pipemess: list context, no change by cat, no error' ) ;
  5961. ( $stringT, $errorT ) = pipemess( 'dontcare', 'true' ) ;
  5962. is( $stringT, undef, 'pipemess: list context, true but no output, string' ) ;
  5963. like( $errorT, qr{Failure: --pipemess command "true" ended with "0" characters exit value "0" and STDERR ""}, 'pipemess: list context, true but no output, error' ) ;
  5964. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false' ) ;
  5965. is( $stringT, undef, 'pipemess: list context, false and no output, string' ) ;
  5966. like( $errorT, qr{Failure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""}, 'pipemess: list context, false and no output, error' ) ;
  5967. ( $stringT, $errorT ) = pipemess( 'dontcare', 'echo -n blablabla' ) ;
  5968. is( $stringT, q{blablabla}, 'pipemess: list context, "echo -n blablabla", string' ) ;
  5969. is( $errorT, q{}, 'pipemess: list context, "echo blablabla", error' ) ;
  5970. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  5971. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla", string' ) ;
  5972. like( $errorT, qr{blablabla"$}, 'pipemess: list context, "no output STDERR blablabla", error' ) ;
  5973. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )', 'false' ) ;
  5974. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla then false", string' ) ;
  5975. like( $errorT, qr{blablabla"$}, 'pipemess: list context, "no output STDERR blablabla then false", error' ) ;
  5976. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  5977. is( $stringT, undef, 'pipemess: list context, "false then STDERR blablabla", string' ) ;
  5978. like( $errorT, qr{Failure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""}, 'pipemess: list context, "false then STDERR blablabla", error' ) ;
  5979. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo rrrrr ; echo -n error_blablabla 3>&1 1>&2 2>&3 )' ) ;
  5980. like( $stringT, qr{rrrrr}, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", string' ) ;
  5981. like( $errorT, qr{STDERR.*error_blablabla}, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", error' ) ;
  5982. }
  5983. ( $stringT, $errorT ) = pipemess( 'dontcare', 'cacaprout' ) ;
  5984. is( $stringT, undef, 'pipemess: list context, cacaprout not found, string' ) ;
  5985. like( $errorT, qr{Failure: --pipemess command "cacaprout" ended with "0" characters exit value.*}, 'pipemess: list context, cacaprout not found, error' ) ;
  5986. return ;
  5987. }
  5988. sub tests_is_a_release_number {
  5989. ok(is_a_release_number($RELEASE_NUMBER_EXAMPLE_1), 'is_a_release_number 1.351') ;
  5990. ok(is_a_release_number($RELEASE_NUMBER_EXAMPLE_2), 'is_a_release_number 42.4242') ;
  5991. ok(is_a_release_number(imapsync_version()), 'is_a_release_number imapsync_version()') ;
  5992. ok(! is_a_release_number('blabla' ), '! is_a_release_number blabla') ;
  5993. return ;
  5994. }
  5995. sub is_a_release_number {
  5996. my $number = shift;
  5997. return( $number =~ m{^\d+\.\d+$}xo ) ;
  5998. }
  5999. sub check_last_release {
  6000. my $public_release = not_long_imapsync_version_public( ) ;
  6001. $debug and myprint( "check_last_release: [$public_release]\n" ) ;
  6002. return('unknown') if ($public_release eq 'unknown') ;
  6003. return('timeout') if ($public_release eq 'timeout') ;
  6004. return('unknown') if (! is_a_release_number( $public_release ) ) ;
  6005. my $imapsync_here = imapsync_version();
  6006. if ($public_release > $imapsync_here) {
  6007. return("New imapsync release $public_release available");
  6008. }else{
  6009. return( 'This imapsync is up to date') ;
  6010. }
  6011. }
  6012. sub imapsync_version {
  6013. my $rcs_imapsync = '$Id: imapsync,v 1.727 2016/08/19 10:30:36 gilles Exp gilles $ ' ;
  6014. my $imapsync_version ;
  6015. if ( $rcs_imapsync =~ m{,v\s+(\d+\.\d+)}xo ) {
  6016. $imapsync_version = $1
  6017. } else {
  6018. $imapsync_version = 'UNKNOWN' ;
  6019. }
  6020. return( $imapsync_version ) ;
  6021. }
  6022. sub tests_imapsync_basename {
  6023. ok( imapsync_basename() =~ m/imapsync/, 'imapsync_basename: match imapsync');
  6024. ok( 'blabla' ne imapsync_basename(), 'imapsync_basename: do not equal blabla');
  6025. return ;
  6026. }
  6027. sub imapsync_basename {
  6028. return basename($0);
  6029. }
  6030. sub imapsync_version_public {
  6031. my $local_version = imapsync_version();
  6032. my $imapsync_basename = imapsync_basename();
  6033. my $agent_info = "$OSNAME system, perl "
  6034. . mysprintf( '%vd', $PERL_VERSION)
  6035. . ", Mail::IMAPClient $Mail::IMAPClient::VERSION"
  6036. . " $imapsync_basename";
  6037. my $sock = IO::Socket::INET->new(
  6038. PeerAddr => 'imapsync.lamiral.info',
  6039. PeerPort => 80,
  6040. Proto => 'tcp',
  6041. ) ;
  6042. return( 'unknown' ) if not $sock ;
  6043. print $sock
  6044. "GET /prj/imapsync/VERSION HTTP/1.0\n",
  6045. "User-Agent: imapsync/$local_version ($agent_info)\n",
  6046. "Host: ks.lamiral.info\n\n";
  6047. my @line = <$sock>;
  6048. close $sock ;
  6049. my $last_release = $line[$LAST];
  6050. chomp $last_release ;
  6051. return($last_release) ;
  6052. }
  6053. sub not_long_imapsync_version_public {
  6054. #myprint( "Entering not_long_imapsync_version_public\n" ) ;
  6055. my $val;
  6056. # Doesn't work with gethostbyname (see perlipc)
  6057. #local $SIG{ALRM} = sub { die "alarm\n" };
  6058. if ('MSWin32' eq $OSNAME) {
  6059. local $SIG{ALRM} = sub { die "alarm\n" };
  6060. }else{
  6061. POSIX::sigaction(SIGALRM,
  6062. POSIX::SigAction->new(sub { croak 'alarm' } ) )
  6063. or myprint( "Error setting SIGALRM handler: $!\n" ) ;
  6064. }
  6065. my $ret = eval {
  6066. alarm 3 ;
  6067. {
  6068. $val = imapsync_version_public( ) ;
  6069. #sleep 4 ;
  6070. #myprint( "End of imapsync_version_public\n" ) ;
  6071. }
  6072. alarm 0 ;
  6073. 1 ;
  6074. } ;
  6075. #myprint( "eval [$ret]\n" ) ;
  6076. if ( ( not $ret ) or $@ ) {
  6077. #myprint( "$@" ) ;
  6078. if ($@ =~ /alarm/) {
  6079. # timed out
  6080. return('timeout');
  6081. }else{
  6082. alarm 0 ;
  6083. return('unknown'); # propagate unexpected errors
  6084. }
  6085. }else {
  6086. # Good!
  6087. return($val);
  6088. }
  6089. }
  6090. sub localhost_info {
  6091. my($infos) = join q{},
  6092. "Here is a [$OSNAME] system (",
  6093. join(q{ },
  6094. uname(),
  6095. ),
  6096. ")\n",
  6097. 'with Perl ',
  6098. mysprintf( '%vd', $PERL_VERSION),
  6099. " Mail::IMAPClient $Mail::IMAPClient::VERSION",
  6100. ;
  6101. return($infos) ;
  6102. }
  6103. sub memory_consumption {
  6104. # memory consumed by imapsync until now in bytes
  6105. return( ( memory_consumption_of_pids( ) )[0] );
  6106. }
  6107. sub tests_memory_consumption {
  6108. like( memory_consumption( ), qr{\d+},'memory_consumption no args') ;
  6109. like( memory_consumption( 1 ), qr{\d+},'memory_consumption 1') ;
  6110. like( memory_consumption( $PROCESS_ID ), qr{\d+},"memory_consumption_of_pids $PROCESS_ID") ;
  6111. like( memory_consumption_ratio(), qr{\d+}, 'memory_consumption_ratio' ) ;
  6112. like( memory_consumption_ratio(1), qr{\d+}, 'memory_consumption_ratio 1' ) ;
  6113. like( memory_consumption_ratio(10), qr{\d+}, 'memory_consumption_ratio 10' ) ;
  6114. like( memory_consumption(), qr{\d+}, "memory_consumption\n" ) ;
  6115. return ;
  6116. }
  6117. sub memory_consumption_of_pids {
  6118. my @pid = @_;
  6119. @pid = (@pid) ? @pid : ($PROCESS_ID) ;
  6120. #myprint( "PIDs: @pid\n" ) ;
  6121. my @val;
  6122. if ('MSWin32' eq $OSNAME) {
  6123. @val = memory_consumption_of_pids_win32(@pid);
  6124. }else{
  6125. # Unix
  6126. my @ps = qx{ ps -o vsz -p @pid } ;
  6127. #myprint( @ps ) ;
  6128. #my @ps = backtick( "ps -o vsz -p @pid" ) ;
  6129. shift @ps; # First line is column name "VSZ"
  6130. chomp @ps;
  6131. # convert to octets
  6132. @val = map { $_ * $KIBI } @ps;
  6133. }
  6134. return( @val ) ;
  6135. }
  6136. sub memory_consumption_of_pids_win32 {
  6137. # Windows
  6138. my @PID = @_;
  6139. my %PID;
  6140. # hash of pids as key values
  6141. map { $PID{$_}++ } @PID;
  6142. # Does not work but should reading the tasklist documentation
  6143. #@ps = qx{ tasklist /FI "PID eq @PID" };
  6144. my @ps = qx{ tasklist /NH /FO CSV } ;
  6145. #my @ps = backtick( 'tasklist /NH /FO CSV' ) ;
  6146. #myprint( "-" x $STD_CHAR_PER_LINE, "\n", @ps, "-" x $STD_CHAR_PER_LINE, "\n" ) ;
  6147. my @val;
  6148. foreach my $line (@ps) {
  6149. my($name, $pid, $mem) = (split ',', $line )[0,1,4];
  6150. next if (! $pid);
  6151. #myprint( "[$name][$pid][$mem]" ) ;
  6152. if ($PID{remove_qq($pid)}) {
  6153. #myprint( "MATCH !\n" ) ;
  6154. chomp $mem ;
  6155. $mem = remove_qq($mem);
  6156. $mem = remove_Ko($mem);
  6157. $mem = remove_not_num($mem);
  6158. #myprint( "[$mem]\n" ) ;
  6159. push @val, $mem * $KIBI;
  6160. }
  6161. }
  6162. return(@val);
  6163. }
  6164. sub backtick {
  6165. my $command = shift ;
  6166. my ( $writer, $reader, $err ) ;
  6167. my @output ;
  6168. open3( $writer, $reader, $err, $command ) ;
  6169. @output = <$reader>; #Output here
  6170. #my @errors = <$err>; #Errors here, instead of the console
  6171. $debugdev and myprint( @output ) ;
  6172. return( @output ) ;
  6173. }
  6174. sub tests_backtick {
  6175. SKIP: {
  6176. skip( 'Tests for MSWin32', 3 ) if ('MSWin32' ne $OSNAME) ;
  6177. my @output ;
  6178. @output = backtick( 'echo Hello World!' ) ;
  6179. # Add \r on Windows.
  6180. ok( "Hello World!\r\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  6181. $debug and myprint( "[@output]" ) ;
  6182. @output = backtick( 'echo Hello & echo World!' ) ;
  6183. ok( "Hello \r\n" eq $output[0], 'backtick: echo Hello & echo World!' ) ;
  6184. ok( "World!\r\n" eq $output[1], 'backtick: echo Hello & echo World!' ) ;
  6185. $debug and myprint( "[@output][$output[0]][$output[1]]" ) ;
  6186. } ;
  6187. SKIP: {
  6188. skip( 'Tests for Unix', 3 ) if ('MSWin32' eq $OSNAME) ;
  6189. my @output ;
  6190. @output = backtick( 'echo Hello World!' ) ;
  6191. ok( "Hello World!\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  6192. $debug and myprint( "[@output]" ) ;
  6193. @output = backtick( "echo Hello\necho World!" ) ;
  6194. ok( "Hello\n" eq $output[0], 'backtick: echo Hello; echo World!' ) ;
  6195. ok( "World!\n" eq $output[1], 'backtick: echo Hello; echo World!' ) ;
  6196. $debug and myprint( "[@output]" ) ;
  6197. }
  6198. return ;
  6199. }
  6200. sub remove_not_num {
  6201. my $string = shift;
  6202. $string =~ tr/0-9//cd;
  6203. #myprint( "tr [$string]\n" ) ;
  6204. return($string);
  6205. }
  6206. sub tests_remove_not_num {
  6207. ok('123' eq remove_not_num(123), 'remove_not_num( 123 )' ) ;
  6208. ok('123' eq remove_not_num('123'), q{remove_not_num( '123' )} ) ;
  6209. ok('123' eq remove_not_num('12 3'), q{remove_not_num( '12 3' )} ) ;
  6210. ok('123' eq remove_not_num('a 12 3 Ko'), q{remove_not_num( 'a 12 3 Ko' )} ) ;
  6211. return ;
  6212. }
  6213. sub remove_Ko {
  6214. my $string = shift;
  6215. if ($string =~ /^(.*)\sKo$/xo) {
  6216. return($1);
  6217. }else{
  6218. return($string);
  6219. }
  6220. }
  6221. sub remove_qq {
  6222. my $string = shift;
  6223. if ($string =~ /^"(.*)"$/xo) {
  6224. return($1);
  6225. }else{
  6226. return($string);
  6227. }
  6228. }
  6229. sub memory_consumption_ratio {
  6230. my ($base) = @_;
  6231. $base ||= 1;
  6232. my $consu = memory_consumption();
  6233. return($consu / $base);
  6234. }
  6235. sub date_from_rcs {
  6236. my $d = shift ;
  6237. my %num2mon = qw( 01 Jan 02 Feb 03 Mar 04 Apr 05 May 06 Jun 07 Jul 08 Aug 09 Sep 10 Oct 11 Nov 12 Dec ) ;
  6238. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  6239. # Handles the following format
  6240. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  6241. #myprint( "$d\n" ) ;
  6242. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  6243. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  6244. $month = $num2mon{$month} ;
  6245. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  6246. #myprint( "$d\n" ) ;
  6247. }
  6248. return( $d ) ;
  6249. }
  6250. sub tests_date_from_rcs {
  6251. ok('19-Sep-2015 16:11:07 +0000'
  6252. eq date_from_rcs('Date: 2015/09/19 16:11:07 '), 'date_from_rcs from RCS date' ) ;
  6253. return ;
  6254. }
  6255. sub good_date {
  6256. # two incoming formats:
  6257. # header Tue, 24 Aug 2010 16:00:00 +0200
  6258. # internal 24-Aug-2010 16:00:00 +0200
  6259. # outgoing format: internal date format
  6260. # 24-Aug-2010 16:00:00 +0200
  6261. my $d = shift ;
  6262. return(q{}) if not defined $d;
  6263. SWITCH: {
  6264. if ( $d =~ m{(\d?)(\d-...-\d{4})(\s\d{2}:\d{2}:\d{2})(\s(?:\+|-)\d{4})?}xo ) {
  6265. #myprint( "internal: [$1][$2][$3][$4]\n" ) ;
  6266. my ($day_1, $date_rest, $hour, $zone) = ($1,$2,$3,$4) ;
  6267. $day_1 = '0' if ($day_1 eq q{}) ;
  6268. $zone = ' +0000' if not defined $zone ;
  6269. $d = $day_1 . $date_rest . $hour . $zone ;
  6270. last SWITCH ;
  6271. }
  6272. if ($d =~ m{(?:\w{3,},\s)?(\d{1,2}),?\s+(\w{3,})\s+(\d{2,4})\s+(\d{1,2})(?::|\.)(\d{1,2})(?:(?::|\.)(\d{1,2}))?\s*((?:\+|-)\d{4})?}xo ) {
  6273. # Handles any combination of following formats
  6274. # Tue, 24 Aug 2010 16:00:00 +0200 -- Standard
  6275. # 24 Aug 2010 16:00:00 +0200 -- Missing Day of Week
  6276. # Tue, 24 Aug 97 16:00:00 +0200 -- Two digit year
  6277. # Tue, 24 Aug 1997 16.00.00 +0200 -- Periods instead of colons
  6278. # Tue, 24 Aug 1997 16:00:00 +0200 -- Extra whitespace between year and hour
  6279. # Tue, 24 Aug 1997 6:5:2 +0200 -- Single digit hour, min, or second
  6280. # Tue, 24, Aug 1997 16:00:00 +0200 -- Extra comma
  6281. #myprint( "header: [$1][$2][$3][$4][$5][$6][$7][$8]\n" ) ;
  6282. my ($day, $month, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7,$8);
  6283. $year = '19' . $year if length($year) == 2 && $year =~ m/^[789]/xo;
  6284. $year = '20' . $year if length($year) == 2;
  6285. $month = substr $month, 0, 3 if length($month) > 4;
  6286. $day = mysprintf( '%02d', $day);
  6287. $hour = mysprintf( '%02d', $hour);
  6288. $min = mysprintf( '%02d', $min);
  6289. $sec = '00' if not defined $sec ;
  6290. $sec = mysprintf( '%02d', $sec ) ;
  6291. $zone = '+0000' if not defined $zone ;
  6292. $d = "$day-$month-$year $hour:$min:$sec $zone" ;
  6293. last SWITCH ;
  6294. }
  6295. if ($d =~ m{(?:.{3})\s(...)\s+(\d{1,2})\s(\d{1,2}):(\d{1,2}):(\d{1,2})\s(?:\w{3})?\s?(\d{4})}xo ) {
  6296. # Handles any combination of following formats
  6297. # Sun Aug 20 11:55:09 2006
  6298. # Wed Jan 24 11:58:38 MST 2007
  6299. # Wed Jan 2 08:40:57 2008
  6300. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  6301. my ($month, $day, $hour, $min, $sec, $year) = ($1,$2,$3,$4,$5,$6);
  6302. $day = mysprintf( '%02d', $day ) ;
  6303. $hour = mysprintf( '%02d', $hour ) ;
  6304. $min = mysprintf( '%02d', $min ) ;
  6305. $sec = mysprintf( '%02d', $sec ) ;
  6306. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  6307. last SWITCH ;
  6308. }
  6309. my %num2mon = qw( 01 Jan 02 Feb 03 Mar 04 Apr 05 May 06 Jun 07 Jul 08 Aug 09 Sep 10 Oct 11 Nov 12 Dec ) ;
  6310. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  6311. # Handles the following format
  6312. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  6313. #myprint( "$d\n" ) ;
  6314. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  6315. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  6316. $month = $num2mon{$month} ;
  6317. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  6318. #myprint( "$d\n" ) ;
  6319. last SWITCH ;
  6320. }
  6321. if ($d =~ m{(\d{2})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  6322. # Handles the following format
  6323. # 02/06/09 22:18:08 -- Generated by AVTECH TemPageR devices
  6324. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  6325. my ($month, $day, $year, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6);
  6326. $year = '20' . $year;
  6327. $month = $num2mon{$month};
  6328. $d = "$day-$month-$year $hour:$min:$sec +0000";
  6329. last SWITCH ;
  6330. }
  6331. if ($d =~ m{\w{6,},\s(\w{3})\w+\s+(\d{1,2}),\s(\d{4})\s(\d{2}):(\d{2})\s(AM|PM)}xo ) {
  6332. # Handles the following format
  6333. # Saturday, December 14, 2002 05:00 PM - KBtoys.com order confirmations
  6334. my ($month, $day, $year, $hour, $min, $apm) = ($1,$2,$3,$4,$5,$6);
  6335. $hour += 12 if $apm eq 'PM' ;
  6336. $day = mysprintf( '%02d', $day ) ;
  6337. $d = "$day-$month-$year $hour:$min:00 +0000" ;
  6338. last SWITCH ;
  6339. }
  6340. if ($d =~ m{(\w{3})\s(\d{1,2})\s(\d{4})\s(\d{2}):(\d{2}):(\d{2})\s((?:\+|-)\d{4})}xo ) {
  6341. # Handles the following format
  6342. # Saturday, December 14, 2002 05:00 PM - jr.com order confirmations
  6343. my ($month, $day, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7);
  6344. $day = mysprintf( '%02d', $day ) ;
  6345. $d = "$day-$month-$year $hour:$min:$sec $zone";
  6346. last SWITCH ;
  6347. }
  6348. if ($d =~ m{(\d{1,2})-(\w{3})-(\d{4})}xo ) {
  6349. # Handles the following format
  6350. # 21-Jun-2001 - register.com domain transfer email circa 2001
  6351. my ($day, $month, $year) = ($1,$2,$3);
  6352. $day = mysprintf( '%02d', $day);
  6353. $d = "$day-$month-$year 11:11:11 +0000";
  6354. last SWITCH ;
  6355. }
  6356. # unknown or unmatch => return same string
  6357. return($d);
  6358. }
  6359. $d = qq("$d") ;
  6360. return( $d ) ;
  6361. }
  6362. sub tests_good_date {
  6363. ok(q{} eq good_date(), 'good_date no arg');
  6364. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('24-Aug-2010 16:00:00 +0200'), 'good_date internal 2digit zone');
  6365. ok('"24-Aug-2010 16:00:00 +0000"' eq good_date('24-Aug-2010 16:00:00'), 'good_date internal 2digit no zone');
  6366. ok('"01-Sep-2010 16:00:00 +0200"' eq good_date( '1-Sep-2010 16:00:00 +0200'), 'good_date internal SP 1digit');
  6367. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('Tue, 24 Aug 2010 16:00:00 +0200'), 'good_date header 2digit zone');
  6368. ok('"01-Sep-2010 16:00:00 +0000"' eq good_date('Wed, 1 Sep 2010 16:00:00'), 'good_date header SP 1digit zone');
  6369. ok('"01-Sep-2010 16:00:00 +0200"' eq good_date('Wed, 1 Sep 2010 16:00:00 +0200'), 'good_date header SP 1digit zone');
  6370. ok('"01-Sep-2010 16:00:00 +0200"' eq good_date('Wed, 1 Sep 2010 16:00:00 +0200 (CEST)'), 'good_date header SP 1digit zone');
  6371. ok('"06-Feb-2009 22:18:08 +0000"' eq good_date('02/06/09 22:18:08'), 'good_date header TemPageR');
  6372. ok('"02-Jan-2008 08:40:57 +0000"' eq good_date('Wed Jan 2 08:40:57 2008'), 'good_date header dice.com support 1digit day');
  6373. ok('"20-Aug-2006 11:55:09 +0000"' eq good_date('Sun Aug 20 11:55:09 2006'), 'good_date header dice.com support 2digit day');
  6374. ok('"24-Jan-2007 11:58:38 +0000"' eq good_date('Wed Jan 24 11:58:38 MST 2007'), 'good_date header status-now.com');
  6375. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('24 Aug 2010 16:00:00 +0200'), 'good_date header missing date of week');
  6376. ok('"24-Aug-2067 16:00:00 +0200"' eq good_date('Tue, 24 Aug 67 16:00:00 +0200'), 'good_date header 2digit year');
  6377. ok('"24-Aug-1977 16:00:00 +0200"' eq good_date('Tue, 24 Aug 77 16:00:00 +0200'), 'good_date header 2digit year');
  6378. ok('"24-Aug-1987 16:00:00 +0200"' eq good_date('Tue, 24 Aug 87 16:00:00 +0200'), 'good_date header 2digit year');
  6379. ok('"24-Aug-1997 16:00:00 +0200"' eq good_date('Tue, 24 Aug 97 16:00:00 +0200'), 'good_date header 2digit year');
  6380. ok('"24-Aug-2004 16:00:00 +0200"' eq good_date('Tue, 24 Aug 04 16:00:00 +0200'), 'good_date header 2digit year');
  6381. ok('"24-Aug-1997 16:00:00 +0200"' eq good_date('Tue, 24 Aug 1997 16.00.00 +0200'), 'good_date header period time sep');
  6382. ok('"24-Aug-1997 16:00:00 +0200"' eq good_date('Tue, 24 Aug 1997 16:00:00 +0200'), 'good_date header extra white space type1');
  6383. ok('"24-Aug-1997 05:06:02 +0200"' eq good_date('Tue, 24 Aug 1997 5:6:2 +0200'), 'good_date header 1digit time vals');
  6384. ok('"24-Aug-1997 05:06:02 +0200"' eq good_date('Tue, 24, Aug 1997 05:06:02 +0200'), 'good_date header extra commas');
  6385. ok('"01-Oct-2003 12:45:24 +0000"' eq good_date('Wednesday, 01 October 2003 12:45:24 CDT'), 'good_date header no abbrev');
  6386. ok('"11-Jan-2005 17:58:27 -0500"' eq good_date('Tue, 11 Jan 2005 17:58:27 -0500'), 'good_date extra white space');
  6387. ok('"18-Dec-2002 15:07:00 +0000"' eq good_date('Wednesday, December 18, 2002 03:07 PM'), 'good_date kbtoys.com orders');
  6388. ok('"16-Dec-2004 02:01:49 -0500"' eq good_date('Dec 16 2004 02:01:49 -0500'), 'good_date jr.com orders');
  6389. ok('"21-Jun-2001 11:11:11 +0000"' eq good_date('21-Jun-2001'), 'good_date register.com domain transfer');
  6390. ok('"18-Nov-2012 18:34:38 +0100"' eq good_date('Sun, 18 Nov 2012 18:34:38 +0100'), 'good_date pop2imap bug (Westeuropäische Normalzeit)');
  6391. ok('"19-Sep-2015 16:11:07 +0000"' eq good_date('Date: 2015/09/19 16:11:07 '), 'good_date from RCS date' ) ;
  6392. return ;
  6393. }
  6394. sub tests_list_keys_in_2_not_in_1 {
  6395. my @list;
  6396. ok( ! list_keys_in_2_not_in_1( {}, {}), 'list_keys_in_2_not_in_1: {} {}');
  6397. ok( 0 == compare_lists( [], [ list_keys_in_2_not_in_1( {}, {} ) ] ), 'list_keys_in_2_not_in_1: {} {}');
  6398. ok( 0 == compare_lists( ['a','b'], [ list_keys_in_2_not_in_1( {}, {'a' => 1, 'b' => 1}) ]), 'list_keys_in_2_not_in_1: {} {a, b}');
  6399. ok( 0 == compare_lists( ['b'], [ list_keys_in_2_not_in_1( {'a' => 1}, {'a' => 1, 'b' => 1}) ]), 'list_keys_in_2_not_in_1: {a} {a, b}');
  6400. ok( 0 == compare_lists( [], [ list_keys_in_2_not_in_1( {'a' => 1, 'b' => 1}, {'a' => 1, 'b' => 1}) ]), 'list_keys_in_2_not_in_1: {a, b} {a, b}');
  6401. ok( 0 == compare_lists( [], [ list_keys_in_2_not_in_1( {'a' => 1, 'b' => 1, 'c' => 1}, {'a' => 1, 'b' => 1}) ]), 'list_keys_in_2_not_in_1: {a, b, c} {a, b}');
  6402. ok( 0 == compare_lists( ['b'], [ list_keys_in_2_not_in_1( {'a' => 1, 'c' => 1}, {'a' => 1, 'b' => 1}) ]), 'list_keys_in_2_not_in_1: {a, b, c} {a, b}');
  6403. return ;
  6404. }
  6405. sub list_keys_in_2_not_in_1 {
  6406. my $folders1_ref = shift;
  6407. my $folders2_ref = shift;
  6408. my @list;
  6409. foreach my $folder ( sort keys %{ $folders2_ref } ) {
  6410. next if exists $folders1_ref->{$folder};
  6411. push @list, $folder;
  6412. }
  6413. return(@list);
  6414. }
  6415. sub list_folders_in_2_not_in_1 {
  6416. my (@h2_folders_not_in_h1, %h2_folders_not_in_h1) ;
  6417. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h1_folders_all, \%h2_folders_all) ;
  6418. map { $h2_folders_not_in_h1{$_} = 1} @h2_folders_not_in_h1 ;
  6419. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h2_folders_from_1_all, \%h2_folders_not_in_h1) ;
  6420. return( reverse @h2_folders_not_in_h1 );
  6421. }
  6422. sub delete_folders_in_2_not_in_1 {
  6423. foreach my $folder (@h2_folders_not_in_1) {
  6424. if ( defined $delete2foldersonly and eval "\$folder !~ $delete2foldersonly" ) {
  6425. myprint( "Not deleting $folder because of --delete2foldersonly $delete2foldersonly\n" ) ;
  6426. next ;
  6427. }
  6428. if ( defined $delete2foldersbutnot and eval "\$folder =~ $delete2foldersbutnot" ) {
  6429. myprint( "Not deleting $folder because of --delete2foldersbutnot $delete2foldersbutnot\n" ) ;
  6430. next ;
  6431. }
  6432. my $res = $dry ; # always success in dry mode!
  6433. $imap2->unsubscribe( $folder ) if ( ! $dry ) ;
  6434. $res = $imap2->delete( $folder ) if ( ! $dry ) ;
  6435. if ( $res ) {
  6436. myprint( "Deleted $folder", "$dry_message", "\n" ) ;
  6437. }else{
  6438. myprint( "Deleting $folder failed", "\n" ) ;
  6439. }
  6440. }
  6441. return ;
  6442. }
  6443. sub delete_folder {
  6444. my ( $sync, $imap, $folder, $Side ) = @_ ;
  6445. if ( ! $sync ) { return ; }
  6446. if ( ! $imap ) { return ; }
  6447. if ( ! $folder ) { return ; }
  6448. $Side ||= 'HostX' ;
  6449. my $res = $sync->{dry} ; # always success in dry mode!
  6450. if ( ! $sync->{dry} ) {
  6451. $imap->unsubscribe( $folder ) ;
  6452. $res = $imap->delete( $folder ) ;
  6453. }
  6454. if ( $res ) {
  6455. myprint( "$Side deleted $folder", $sync->{dry_message}, "\n" ) ;
  6456. return 1 ;
  6457. }else{
  6458. myprint( "$Side deleting $folder failed", "\n" ) ;
  6459. return ;
  6460. }
  6461. }
  6462. sub delete1emptyfolders {
  6463. my $sync = shift ;
  6464. if ( ! $sync ) { return ; } # abort if no parameter
  6465. if ( ! $sync->{delete1emptyfolders} ) { return ; } # abort if --delete1emptyfolders off
  6466. my $imap = $sync->{imap1} ;
  6467. if ( ! $imap ) { return ; } # abort if no imap
  6468. if ( $imap->IsUnconnected( ) ) { return ; } # abort if diesconnected
  6469. my %folders_kept ;
  6470. myprint( qq{Host1 deleting empty folders\n} ) ;
  6471. foreach my $folder ( reverse sort @{ $sync->{h1_folders_wanted} } ) {
  6472. my $parenthood = $imap->is_parent( $folder ) ;
  6473. if ( defined $parenthood and $parenthood ) {
  6474. myprint( "Host1 folder $folder has subfolders\n" ) ;
  6475. $folders_kept{ $folder }++ ;
  6476. next ;
  6477. }
  6478. my $nb_messages_select = examine_folder_and_count( $imap, $folder, 'Host1' ) ;
  6479. if ( ! defined $nb_messages_select ) { next ; } # Select failed => Neither continue nor keep this folder }
  6480. my $nb_messages_search = scalar( @{ $imap->messages( ) } ) ;
  6481. if ( 0 != $nb_messages_select and 0 != $nb_messages_search ) {
  6482. myprint( "Host1 folder $folder has messages: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  6483. $folders_kept{ $folder }++ ;
  6484. next ;
  6485. }
  6486. if ( 0 != $nb_messages_select + $nb_messages_search ) {
  6487. myprint( "Host1 folder $folder odd messages count: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  6488. $folders_kept{ $folder }++ ;
  6489. next ;
  6490. }
  6491. # Here we must have 0 messages by messages() aka "SEARCH ALL" and also "EXAMINE"
  6492. if ( uc $folder eq 'INBOX' ) {
  6493. myprint( "Host1 Not deleting $folder\n" ) ;
  6494. $folders_kept{ $folder }++ ;
  6495. next ;
  6496. }
  6497. myprint( "Host1 deleting empty folder $folder\n" ) ;
  6498. # can not delete a SELECTed or EXAMINEd folder so closing it
  6499. # could changed be SELECT INBOX
  6500. $imap->close( ) ; # close after examine does not expunge; anyway expunging an empty folder...
  6501. if ( delete_folder( $sync, $imap, $folder, 'Host1' ) ) {
  6502. next ; # Deleted, good!
  6503. }else{
  6504. $folders_kept{ $folder }++ ;
  6505. next ; # Not deleted, bad!
  6506. }
  6507. }
  6508. remove_deleted_folders_from_wanted_list( $sync, %folders_kept ) ;
  6509. myprint( qq{Host1 ended deleting empty folders\n} ) ;
  6510. return ;
  6511. }
  6512. sub remove_deleted_folders_from_wanted_list {
  6513. my ( $sync, %folders_kept ) = @ARG ;
  6514. my @h1_folders_wanted_init = @{ $sync->{h1_folders_wanted} } ;
  6515. my @h1_folders_wanted_last ;
  6516. foreach my $folder ( @h1_folders_wanted_init ) {
  6517. if ( $folders_kept{ $folder } ) {
  6518. push @h1_folders_wanted_last, $folder ;
  6519. }
  6520. }
  6521. @{ $sync->{h1_folders_wanted} } = @h1_folders_wanted_last ;
  6522. return ;
  6523. }
  6524. sub examine_folder_and_count {
  6525. my ( $imap, $folder, $Side ) = @_ ;
  6526. $Side ||= 'HostX' ;
  6527. if ( ! examine_folder( $imap, $folder, $Side ) ) {
  6528. return ;
  6529. }
  6530. my $nb_messages_select = count_from_select( $imap->History ) ;
  6531. return $nb_messages_select ;
  6532. }
  6533. sub tests_delete1emptyfolders {
  6534. is( undef, delete1emptyfolders( ), q{delete1emptyfolders: undef} ) ;
  6535. my $syncT ;
  6536. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef 2} ) ;
  6537. my $imapT ;
  6538. $syncT->{imap1} = $imapT ;
  6539. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef imap} ) ;
  6540. require Test::MockObject ;
  6541. $imapT = Test::MockObject->new( ) ;
  6542. $syncT->{imap1} = $imapT ;
  6543. $imapT->set_true( 'IsUnconnected' ) ;
  6544. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: Unconnected imap} ) ;
  6545. # Now connected tests
  6546. $imapT->set_false( 'IsUnconnected' ) ;
  6547. $imapT->mock( 'LastError', sub { q{LastError mocked} } ) ;
  6548. $syncT->{delete1emptyfolders} = 0 ;
  6549. tests_delete1emptyfolders_unit(
  6550. $syncT,
  6551. [ qw{ INBOX DELME1 DELME2 } ],
  6552. [ qw{ INBOX DELME1 DELME2 } ],
  6553. q{tests_delete1emptyfolders: --delete1emptyfolders OFF}
  6554. ) ;
  6555. # All are parents => no deletion at all
  6556. $imapT->set_true( 'is_parent' ) ;
  6557. $syncT->{delete1emptyfolders} = 1 ;
  6558. tests_delete1emptyfolders_unit(
  6559. $syncT,
  6560. [ qw{ INBOX DELME1 DELME2 } ],
  6561. [ qw{ INBOX DELME1 DELME2 } ],
  6562. q{tests_delete1emptyfolders: --delete1emptyfolders ON}
  6563. ) ;
  6564. # No parents but examine false for all => skip all
  6565. $imapT->set_false( 'is_parent', 'examine' ) ;
  6566. tests_delete1emptyfolders_unit(
  6567. $syncT,
  6568. [ qw{ INBOX DELME1 DELME2 } ],
  6569. [ ],
  6570. q{tests_delete1emptyfolders: EXAMINE fails}
  6571. ) ;
  6572. # examine ok for all but History bad => skip all
  6573. $imapT->set_true( 'examine' ) ;
  6574. $imapT->mock( 'History', sub { ( q{History badly mocked} ) } ) ;
  6575. tests_delete1emptyfolders_unit(
  6576. $syncT,
  6577. [ qw{ INBOX DELME1 DELME2 } ],
  6578. [ ],
  6579. q{tests_delete1emptyfolders: examine ok but History badly mocked so count messages fails}
  6580. ) ;
  6581. # History good but some messages EXISTS == messages() => no deletion
  6582. $imapT->mock( 'History', sub { ( q{* 2 EXISTS} ) } ) ;
  6583. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  6584. tests_delete1emptyfolders_unit(
  6585. $syncT,
  6586. [ qw{ INBOX DELME1 DELME2 } ],
  6587. [ qw{ INBOX DELME1 DELME2 } ],
  6588. q{tests_delete1emptyfolders: History EXAMINE ok, several messages}
  6589. ) ;
  6590. # 0 EXISTS but != messages() => no deletion
  6591. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  6592. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  6593. tests_delete1emptyfolders_unit(
  6594. $syncT,
  6595. [ qw{ INBOX DELME1 DELME2 } ],
  6596. [ qw{ INBOX DELME1 DELME2 } ],
  6597. q{tests_delete1emptyfolders: 0 EXISTS but 2 by messages()}
  6598. ) ;
  6599. # 1 EXISTS but != 0 == messages() => no deletion
  6600. $imapT->mock( 'History', sub { ( q{* 1 EXISTS} ) } ) ;
  6601. $imapT->mock( 'messages', sub { [ ] } ) ;
  6602. tests_delete1emptyfolders_unit(
  6603. $syncT,
  6604. [ qw{ INBOX DELME1 DELME2 } ],
  6605. [ qw{ INBOX DELME1 DELME2 } ],
  6606. q{tests_delete1emptyfolders: 1 EXISTS but 0 by messages()}
  6607. ) ;
  6608. # 0 EXISTS and 0 == messages() => deletion except INBOX
  6609. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  6610. $imapT->mock( 'messages', sub { [ ] } ) ;
  6611. $imapT->set_true( qw{ delete close unsubscribe } ) ;
  6612. $syncT->{dry_message} = q{ (not really since in a mocked test)} ;
  6613. tests_delete1emptyfolders_unit(
  6614. $syncT,
  6615. [ qw{ INBOX DELME1 DELME2 } ],
  6616. [ qw{ INBOX } ],
  6617. q{tests_delete1emptyfolders: 0 EXISTS 0 by messages() delete folders, keep INBOX}
  6618. ) ;
  6619. return ;
  6620. }
  6621. sub tests_delete1emptyfolders_unit {
  6622. my $syncT = shift ;
  6623. my $folders1wanted_init_ref = shift ;
  6624. my $folders1wanted_after_ref = shift ;
  6625. my $comment = shift || q{delete1emptyfolders:} ;
  6626. my @folders1wanted_init = @{ $folders1wanted_init_ref } ;
  6627. my @folders1wanted_after = @{ $folders1wanted_after_ref } ;
  6628. @{ $syncT->{h1_folders_wanted} } = @folders1wanted_init ;
  6629. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_init, qq{$comment, init check} ) ;
  6630. delete1emptyfolders( $syncT ) ;
  6631. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_after, qq{$comment, after check} ) ;
  6632. return ;
  6633. }
  6634. sub extract_header {
  6635. my $string = shift ;
  6636. my ( $header ) = split /\n\n/x, $string ;
  6637. if ( ! $header ) { return( q{} ) ; }
  6638. #myprint( "[$header]\n" ) ;
  6639. return( $header ) ;
  6640. }
  6641. sub tests_extract_header {
  6642. my $h = <<'EOM';
  6643. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  6644. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  6645. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  6646. EOM
  6647. chomp $h ;
  6648. ok( $h eq extract_header(
  6649. <<'EOM'
  6650. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  6651. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  6652. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  6653. body
  6654. lalala
  6655. EOM
  6656. ), 'extract_header: 1') ;
  6657. return ;
  6658. }
  6659. sub decompose_header{
  6660. my $string = shift ;
  6661. # a hash, for a keyword header KEY value are list of strings [VAL1, VAL1_other, etc]
  6662. # Think of multiple "Received:" header lines.
  6663. my $header = { } ;
  6664. my ($key, $val ) ;
  6665. my @line = split /\n|\r\n/x, $string ;
  6666. foreach my $line ( @line ) {
  6667. #myprint( "DDD $line\n" ) ;
  6668. # End of header
  6669. last if ( $line =~ m{^$}xo ) ;
  6670. # Key: value
  6671. if ( $line =~ m/(^[^:]+):\s(.*)/xo ) {
  6672. $key = $1 ;
  6673. $val = $2 ;
  6674. $debugdev and myprint( "DDD KV [$key] [$val]\n" ) ;
  6675. push @{ $header->{ $key } }, $val ;
  6676. # blanc and value => value from previous line continues
  6677. }elsif( $line =~ m/^(\s+)(.*)/xo ) {
  6678. $val = $2 ;
  6679. $debugdev and myprint( "DDD V [$val]\n" ) ;
  6680. @{ $header->{ $key } }[ $LAST ] .= " $val" if $key ;
  6681. # dirty line?
  6682. }else{
  6683. next ;
  6684. }
  6685. }
  6686. #myprint( Data::Dumper->Dump( [ $header ] ) ) ;
  6687. return( $header ) ;
  6688. }
  6689. sub tests_decompose_header{
  6690. my $header_dec ;
  6691. $header_dec = decompose_header(
  6692. <<'EOH'
  6693. KEY_1: VAL_1
  6694. KEY_2: VAL_2
  6695. VAL_2_+
  6696. VAL_2_++
  6697. KEY_3: VAL_3
  6698. KEY_1: VAL_1_other
  6699. KEY_4: VAL_4
  6700. VAL_4_+
  6701. KEY_5 BLANC: VAL_5
  6702. KEY_6_BAD_BODY: VAL_6
  6703. EOH
  6704. ) ;
  6705. ok( 'VAL_3'
  6706. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: VAL_3' ) ;
  6707. ok( 'VAL_1'
  6708. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: VAL_1' ) ;
  6709. ok( 'VAL_1_other'
  6710. eq $header_dec->{ 'KEY_1' }[1], 'decompose_header: VAL_1_other' ) ;
  6711. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  6712. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: VAL_2 VAL_2_+ VAL_2_++' ) ;
  6713. ok( 'VAL_4 VAL_4_+'
  6714. eq $header_dec->{ 'KEY_4' }[0], 'decompose_header: VAL_4 VAL_4_+' ) ;
  6715. ok( ' VAL_5'
  6716. eq $header_dec->{ 'KEY_5 BLANC' }[0], 'decompose_header: KEY_5 BLANC' ) ;
  6717. ok( not( defined $header_dec->{ 'KEY_6_BAD_BODY' }[0] ), 'decompose_header: KEY_6_BAD_BODY' ) ;
  6718. $header_dec = decompose_header(
  6719. <<'EOH'
  6720. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  6721. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  6722. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  6723. EOH
  6724. ) ;
  6725. ok( '<20100428101817.A66CB162474E@plume.est.belle>'
  6726. eq $header_dec->{ 'Message-Id' }[0], 'decompose_header: 1' ) ;
  6727. $header_dec = decompose_header(
  6728. <<'EOH'
  6729. Return-Path: <gilles@louloutte.dyndns.org>
  6730. Received: by plume.est.belle (Postfix, from userid 1000)
  6731. id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)
  6732. Subject: test:eekahceishukohpe
  6733. EOH
  6734. ) ;
  6735. ok(
  6736. 'by plume.est.belle (Postfix, from userid 1000) id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)'
  6737. eq $header_dec->{ 'Received' }[0], 'decompose_header: 2' ) ;
  6738. $header_dec = decompose_header(
  6739. <<'EOH'
  6740. Received: from plume (localhost [127.0.0.1])
  6741. by plume.est.belle (Postfix) with ESMTP id C6EB73F6C9
  6742. for <gilles@localhost>; Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  6743. Received: from plume [192.168.68.7]
  6744. by plume with POP3 (fetchmail-6.3.6)
  6745. for <gilles@localhost> (single-drop); Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  6746. EOH
  6747. ) ;
  6748. ok(
  6749. 'from plume (localhost [127.0.0.1]) by plume.est.belle (Postfix) with ESMTP id C6EB73F6C9 for <gilles@localhost>; Mon, 26 Nov 2007 10:39:06 +0100 (CET)'
  6750. eq $header_dec->{ 'Received' }[0], 'decompose_header: 3' ) ;
  6751. ok(
  6752. 'from plume [192.168.68.7] by plume with POP3 (fetchmail-6.3.6) for <gilles@localhost> (single-drop); Mon, 26 Nov 2007 10:39:06 +0100 (CET)'
  6753. eq $header_dec->{ 'Received' }[1], 'decompose_header: 3' ) ;
  6754. # Bad header beginning with a blank character
  6755. $header_dec = decompose_header(
  6756. <<'EOH'
  6757. KEY_1: VAL_1
  6758. KEY_2: VAL_2
  6759. VAL_2_+
  6760. VAL_2_++
  6761. KEY_3: VAL_3
  6762. KEY_1: VAL_1_other
  6763. EOH
  6764. ) ;
  6765. ok( 'VAL_3'
  6766. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: Bad header VAL_3' ) ;
  6767. ok( 'VAL_1_other'
  6768. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: Bad header VAL_1_other' ) ;
  6769. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  6770. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: Bad header VAL_2 VAL_2_+ VAL_2_++' ) ;
  6771. return ;
  6772. }
  6773. sub epoch {
  6774. # incoming format:
  6775. # internal date 24-Aug-2010 16:00:00 +0200
  6776. # outgoing format: epoch
  6777. my $d = shift ;
  6778. return(q{}) if not defined $d;
  6779. my ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m ) ;
  6780. my $time ;
  6781. if ( $d =~ m{(\d{1,2})-([A-Z][a-z]{2})-(\d{4})\s(\d{2}):(\d{2}):(\d{2})\s((?:\+|-))(\d{2})(\d{2})}xo ) {
  6782. #myprint( "internal: [$1][$2][$3][$4][$5][$6][$7][$8][$9]\n" ) ;
  6783. ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )
  6784. = ( $1, $2, $3, $4, $5, $6, $7, $8, $9 ) ;
  6785. #myprint( "( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )\n" ) ;
  6786. $sign = +1 if ( '+' eq $sign ) ;
  6787. $sign = $MINUS_ONE if ( '-' eq $sign ) ;
  6788. $time = timegm( $sec, $min, $hour, $mday, $month_abrev{$month}, $year )
  6789. - $sign * ( 3600 * $zone_h + 60 * $zone_m ) ;
  6790. #myprint( "$time ", scalar localtime($time), "\n");
  6791. }
  6792. return( $time ) ;
  6793. }
  6794. sub tests_epoch {
  6795. ok( '1282658400' eq epoch( '24-Aug-2010 16:00:00 +0200' ), 'epoch 24-Aug-2010 16:00:00 +0200 -> 1282658400' ) ;
  6796. ok( '1282658400' eq epoch( '24-Aug-2010 14:00:00 +0000' ), 'epoch 24-Aug-2010 14:00:00 +0000 -> 1282658400' ) ;
  6797. ok( '1282658400' eq epoch( '24-Aug-2010 12:00:00 -0200' ), 'epoch 24-Aug-2010 12:00:00 -0200 -> 1282658400' ) ;
  6798. ok( '1282658400' eq epoch( '24-Aug-2010 16:01:00 +0201' ), 'epoch 24-Aug-2010 16:01:00 +0201 -> 1282658400' ) ;
  6799. ok( '1282658400' eq epoch( '24-Aug-2010 14:01:00 +0001' ), 'epoch 24-Aug-2010 14:01:00 +0001 -> 1282658400' ) ;
  6800. ok( '1280671200' eq epoch( '1-Aug-2010 16:00:00 +0200' ), 'epoch 1-Aug-2010 16:00:00 +0200 -> 1280671200' ) ;
  6801. ok( '1280671200' eq epoch( '1-Aug-2010 14:00:00 +0000' ), 'epoch 1-Aug-2010 14:00:00 +0000 -> 1280671200' ) ;
  6802. ok( '1280671200' eq epoch( '1-Aug-2010 12:00:00 -0200' ), 'epoch 1-Aug-2010 12:00:00 -0200 -> 1280671200' ) ;
  6803. ok( '1280671200' eq epoch( '1-Aug-2010 16:01:00 +0201' ), 'epoch 1-Aug-2010 16:01:00 +0201 -> 1280671200' ) ;
  6804. ok( '1280671200' eq epoch( '1-Aug-2010 14:01:00 +0001' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  6805. return ;
  6806. }
  6807. sub add_header {
  6808. my $header_uid = shift || 'mistake' ;
  6809. my $header_Message_Id = 'Message-Id: <' . $header_uid . '@imapsync>' ;
  6810. return( $header_Message_Id ) ;
  6811. }
  6812. sub tests_add_header {
  6813. ok( 'Message-Id: <mistake@imapsync>' eq add_header(), 'add_header no arg' ) ;
  6814. ok( 'Message-Id: <123456789@imapsync>' eq add_header(123456789), 'add_header 123456789' ) ;
  6815. return ;
  6816. }
  6817. sub tests_Banner{
  6818. my $imap = Mail::IMAPClient->new( ) ;
  6819. ok( 'lalala' eq $imap->Banner('lalala'), 'Banner set lalala' ) ;
  6820. ok( 'lalala' eq $imap->Banner(), 'Banner returns lalala' ) ;
  6821. return ;
  6822. }
  6823. sub max_line_length {
  6824. my $string = shift ;
  6825. my $max = 0 ;
  6826. while ( $string =~ m/([^\n]*\n?)/msxg ) {
  6827. $max = max( $max, length $1 ) ;
  6828. }
  6829. return( $max ) ;
  6830. }
  6831. sub tests_max_line_length {
  6832. ok( 0 == max_line_length( q{} ), 'max_line_length: 0 == null string' ) ;
  6833. ok( 1 == max_line_length( "\n" ), 'max_line_length: 1 == \n' ) ;
  6834. ok( 1 == max_line_length( "\n\n" ), 'max_line_length: 1 == \n\n' ) ;
  6835. ok( 1 == max_line_length( "\n" x 500 ), 'max_line_length: 1 == 500 \n' ) ;
  6836. ok( 1 == max_line_length( 'a' ), 'max_line_length: 1 == a' ) ;
  6837. ok( 2 == max_line_length( "a\na" ), 'max_line_length: 2 == a\na' ) ;
  6838. ok( 2 == max_line_length( "a\na\n" ), 'max_line_length: 2 == a\na\n' ) ;
  6839. ok( 3 == max_line_length( "a\nab\n" ), 'max_line_length: 3 == a\nab\n' ) ;
  6840. ok( 3 == max_line_length( "a\nab\n" x 10000 ), 'max_line_length: 3 == 10000 a\nab\n' ) ;
  6841. ok( 3 == max_line_length( "a\nab\nabc" ), 'max_line_length: 3 == a\nab\nabc' ) ;
  6842. ok( 4 == max_line_length( "a\nab\nabc\n" ), 'max_line_length: 4 == a\nab\nabc\n' ) ;
  6843. ok( 5 == max_line_length( "a\nabcd\nabc\n" ), 'max_line_length: 5 == a\nabcd\nabc\n' ) ;
  6844. ok( 5 == max_line_length( "a\nabcd\nabc\n\nabcd\nabcd\nabcd\nabcd\nabcd\nabcd\nabcd\nabcd" ), 'max_line_length: 5 == a\nabcd\nabc\n\nabcd\nabcd\nabcd\nabcd\nabcd\nabcd\nabcd\nabcd' ) ;
  6845. return ;
  6846. }
  6847. sub setlogfile {
  6848. my( $mysync ) = shift ;
  6849. $mysync->{logdir} = defined $mysync->{logdir} ? $mysync->{logdir} : 'LOG_imapsync' ;
  6850. $mysync->{logfile} = defined $mysync->{logfile} ? "$mysync->{logdir}/$mysync->{logfile}" :
  6851. logfile( $mysync->{timestart}, $mysync->{user2}, $mysync->{logdir} ) ;
  6852. #myprint( "logdir = $mysync->{logdir}\n" ) ;
  6853. #myprint( "logfile = $mysync->{logfile}\n" ) ;
  6854. return( $mysync->{logfile} ) ;
  6855. }
  6856. sub tests_setlogfile {
  6857. my $mysync = {
  6858. timestart => 2,
  6859. user2 => 'user2',
  6860. } ;
  6861. ok( 'LOG_imapsync/1970_01_01_01_00_02_user2.txt' eq setlogfile( $mysync ),
  6862. 'setlogfile: default is like LOG_imapsync/1970_01_01_01_00_02_user2.txt' ) ;
  6863. $mysync->{logdir} = undef ;
  6864. $mysync->{logfile} = undef ;
  6865. ok( 'LOG_imapsync/1970_01_01_01_00_02_user2.txt' eq setlogfile( $mysync ),
  6866. 'setlogfile: logdir undef, LOG_imapsync/1970_01_01_01_00_02_user2.txt' ) ;
  6867. $mysync->{logdir} = q{} ;
  6868. $mysync->{logfile} = undef ;
  6869. ok( '1970_01_01_01_00_02_user2.txt' eq setlogfile( $mysync ),
  6870. 'setlogfile: logdir empty, 1970_01_01_01_00_02_user2.txt' ) ;
  6871. $mysync->{logdir} = 'vallogdir' ;
  6872. $mysync->{logfile} = undef ;
  6873. ok( 'vallogdir/1970_01_01_01_00_02_user2.txt' eq setlogfile( $mysync ),
  6874. 'setlogfile: logdir vallogdir, vallogdir/1970_01_01_01_00_02_user2.txt' ) ;
  6875. $mysync->{logdir} = 'vallogdir' ;
  6876. $mysync->{logfile} = 'vallogfile.txt' ;
  6877. ok( 'vallogdir/vallogfile.txt' eq setlogfile( $mysync ),
  6878. 'setlogfile: logdir vallogdir, logfile vallogfile.txt, vallogdir/vallogfile.txt' ) ;
  6879. return ;
  6880. }
  6881. sub logfile {
  6882. my ( $time, $suffix, $dir ) = @_ ;
  6883. $time ||= 0 ;
  6884. $suffix ||= q{} ;
  6885. my $sep_suffix = ( $suffix ) ? '_' : q{} ;
  6886. $dir ||= q{} ;
  6887. my $sep_dir = ( $dir ) ? '/' : q{} ;
  6888. my $date_str = POSIX::strftime( '%Y_%m_%d_%H_%M_%S', localtime $time ) ;
  6889. my $logfile = "${dir}${sep_dir}${date_str}${sep_suffix}${suffix}.txt" ;
  6890. $debug and myprint( "date_str: $date_str\n" ) ;
  6891. $debug and myprint( "logfile : $logfile\n" ) ;
  6892. return( $logfile ) ;
  6893. }
  6894. sub tests_logfile {
  6895. SKIP: {
  6896. # Too hard to have a well known timezone on Windows
  6897. skip( 'Too hard to have a well known timezone on Windows', 6 ) if ( 'MSWin32' eq $OSNAME ) ;
  6898. local $ENV{TZ} = 'GMT' ;
  6899. { POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  6900. ok( '1970_01_01_00_00_00.txt' eq logfile( ), 'logfile: no args => 1970_01_01_00_00_00.txt' ) ;
  6901. ok( '1970_01_01_00_00_00.txt' eq logfile( 0 ), 'logfile: 0 => 1970_01_01_00_00_00.txt' ) ;
  6902. ok( '1970_01_01_00_01_01.txt' eq logfile( 61 ), 'logfile: 0 => 1970_01_01_00_01_01.txt' ) ;
  6903. ok( '2010_08_24_14_00_00.txt' eq logfile( 1282658400 ), 'logfile: 1282658400 => 2010_08_24_14_00_00.txt' ) ;
  6904. ok( '2010_08_24_14_01_01.txt' eq logfile( 1282658461 ), 'logfile: 1282658461 => 2010_08_24_14_01_01.txt' ) ;
  6905. ok( '2010_08_24_14_01_01_poupinette.txt' eq logfile( 1282658461, 'poupinette' ), 'logfile: 1282658461 poupinette => 2010_08_24_14_01_01_poupinette.txt' ) ;
  6906. }
  6907. POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  6908. } ;
  6909. return ;
  6910. }
  6911. sub tests_million_folders_baby_2 {
  6912. my %long ;
  6913. @long{ 1 .. 900_000 } = (1) x 900_000 ;
  6914. #myprint( %long, "\n" ) ;
  6915. my $pasglop = 0 ;
  6916. foreach my $elem ( 1 .. 900_000 ) {
  6917. #$debug and myprint( "$elem " ) ;
  6918. if ( not exists $long{ $elem } ) {
  6919. $pasglop++ ;
  6920. }
  6921. }
  6922. ok( 0 == $pasglop, 'tests_million_folders_baby_2: search among 900_000' ) ;
  6923. # myprint( "$pasglop\n" ) ;
  6924. return ;
  6925. }
  6926. sub tests_always_fail {
  6927. ok( 0 == 1, '0 == 1' ) ;
  6928. ok( 1 == 1, '1 == 1' ) ;
  6929. return ;
  6930. }
  6931. sub logfileprepa {
  6932. my $logfile = shift ;
  6933. my $dirname = dirname( $logfile ) ;
  6934. is_valid_directory( $dirname ) || return( 0 ) ;
  6935. return( 1 ) ;
  6936. }
  6937. sub teelaunch {
  6938. my $mysync = shift ;
  6939. my $logfile = $mysync->{logfile} ;
  6940. logfileprepa( $logfile ) || croak "Error no valid directory to write log file $logfile : $!" ;
  6941. my $logfile_handle ;
  6942. open $logfile_handle, '>', $logfile
  6943. or croak( "Can not open $logfile for write: $!" ) ;
  6944. my $tee = IO::Tee->new( $logfile_handle, \*STDOUT ) ;
  6945. *STDERR = *$tee{IO} ;
  6946. select $tee ;
  6947. $tee->autoflush( 1 ) ;
  6948. $mysync->{logfile_handle} = $logfile_handle ;
  6949. $mysync->{tee} = $tee ;
  6950. return $logfile_handle ;
  6951. }
  6952. sub getpwuid_any_os {
  6953. my $uid = shift ;
  6954. return( scalar getlogin ) if ( 'MSWin32' eq $OSNAME ) ; # Windows system
  6955. return( scalar getpwuid $uid ) ; # Unix system
  6956. }
  6957. sub usage {
  6958. my $localhost_info = localhost_info();
  6959. my $thank = thank_author();
  6960. my $imapsync_release = q{};
  6961. $imapsync_release = check_last_release() if (not defined $releasecheck);
  6962. my $escape_char = ( 'MSWin32' eq $OSNAME ) ? '^' : '\\';
  6963. myprint( <<"EOF" ) ;
  6964. usage: $0 [options]
  6965. Several options are mandatory.
  6966. str means string
  6967. int means integer
  6968. reg means regular expression
  6969. cmd means command
  6970. --dry : Makes imapsync doing nothing, just print what would
  6971. be done without --dry.
  6972. --host1 str : Source or "from" imap server. Mandatory.
  6973. --port1 int : Port to connect on host1. Default is 143, 993 if --ssl1
  6974. --user1 str : User to login on host1. Mandatory.
  6975. --showpasswords : Shows passwords on output instead of "MASKED".
  6976. Useful to restart a complete run by just reading the log.
  6977. --password1 str : Password for the user1.
  6978. --host2 str : "destination" imap server. Mandatory.
  6979. --port2 int : Port to connect on host2. Default is 143, 993 if --ssl2
  6980. --user2 str : User to login on host2. Mandatory.
  6981. --password2 str : Password for the user2.
  6982. --passfile1 str : Password file for the user1. It must contain the
  6983. password on the first line. This option avoids to show
  6984. the password on the command line like --password1 does.
  6985. --passfile2 str : Password file for the user2. Contains the password.
  6986. --ssl1 : Use a SSL connection on host1.
  6987. --ssl2 : Use a SSL connection on host2.
  6988. --tls1 : Use a TLS connection on host1.
  6989. --tls2 : Use a TLS connection on host2.
  6990. --debugssl int : SSL debug mode from 0 to 4.
  6991. --sslargs1 str : Pass any ssl parameter for host1 ssl or tls connection. Example:
  6992. --sslargs1 SSL_verify_mode=1 --sslargs1 SSL_version=SSLv3
  6993. See all possibilities in the new() method of IO::Socket::SSL
  6994. http://search.cpan.org/perldoc?IO::Socket::SSL#Description_Of_Methods
  6995. --sslargs2 str : Pass any ssl parameter for host2 ssl or tls connection.
  6996. See --sslargs1
  6997. --timeout1 int : Connection timeout in seconds for host1.
  6998. Default is 120 and 0 means no timeout at all.
  6999. --timeout2 int : Connection timeout in seconds for host2.
  7000. Default is 120 and 0 means no timeout at all.
  7001. --authmech1 str : Auth mechanism to use with host1:
  7002. PLAIN, LOGIN, CRAM-MD5 etc. Use UPPERCASE.
  7003. --authmech2 str : Auth mechanism to use with host2. See --authmech1
  7004. --authuser1 str : User to auth with on host1 (admin user).
  7005. Avoid using --authmech1 SOMETHING with --authuser1.
  7006. --authuser2 str : User to auth with on host2 (admin user).
  7007. --proxyauth1 : Use proxyauth on host1. Requires --authuser1.
  7008. Required by Sun/iPlanet/Netscape IMAP servers to
  7009. be able to use an administrative user.
  7010. --proxyauth2 : Use proxyauth on host2. Requires --authuser2.
  7011. --authmd51 : Use MD5 authentification for host1.
  7012. --authmd52 : Use MD5 authentification for host2.
  7013. --domain1 str : Domain on host1 (NTLM authentication).
  7014. --domain2 str : Domain on host2 (NTLM authentication).
  7015. --folder str : Sync this folder.
  7016. --folder str : and this one, etc.
  7017. --folderrec str : Sync this folder recursively.
  7018. --folderrec str : and this one, etc.
  7019. --folderfirst str : Sync this folder first. --folderfirst "Work"
  7020. --folderfirst str : then this one, etc.
  7021. --folderlast str : Sync this folder last. --folderlast "[Gmail]/All Mail"
  7022. --folderlast str : then this one, etc.
  7023. --nomixfolders : Do not merge folders when host1 is case sensitive
  7024. while host2 is not (like Exchange). Only the first
  7025. similar folder is synced (ex: Sent SENT sent -> Sent).
  7026. --skipemptyfolders : Empty host1 folders are not created on host2.
  7027. --include reg : Sync folders matching this regular expression
  7028. --include reg : or this one, etc.
  7029. in case both --include --exclude options are
  7030. use, include is done before.
  7031. --exclude reg : Skips folders matching this regular expression
  7032. Several folders to avoid:
  7033. --exclude 'fold1|fold2|f3' skips fold1, fold2 and f3.
  7034. --exclude reg : or this one, etc.
  7035. --subfolder2 str : Move whole host1 folders hierarchy under this
  7036. host2 folder str .
  7037. It does it by adding two --regextrans2 options before
  7038. all others. Add --debug to see what's really going on.
  7039. --automap : guesses folders mapping, for folders like
  7040. "Sent", "Junk", "Drafts", "All", "Archive", "Flagged".
  7041. --f1f2 str1=str2 : Force folder str1 to be synced to str2,
  7042. --f1f2 overrides --automap and --regextrans2.
  7043. --regextrans2 reg : Apply the whole regex to each destination folders.
  7044. --regextrans2 reg : and this one. etc.
  7045. When you play with the --regextrans2 option, first
  7046. add also the safe options --dry --justfolders
  7047. Then, when happy, remove --dry, remove --justfolders.
  7048. Have in mind that --regextrans2 is applied after prefix
  7049. and separator inversion. For examples see
  7050. http://imapsync.lamiral.info/FAQ.d/FAQ.Folders_Mapping.txt
  7051. --tmpdir str : Where to store temporary files and subdirectories.
  7052. Will be created if it doesn't exist.
  7053. Default is system specific, Unix is /tmp but
  7054. it's often small and deleted at reboot.
  7055. --tmpdir /var/tmp should be better.
  7056. --pidfile str : The file where imapsync pid is written.
  7057. --pidfilelocking : Abort if pidfile already exists. Usefull to avoid
  7058. concurrent transfers on the same mailbox.
  7059. --nolog : Turn off logging on file
  7060. --logfile str : Change the default log filename (can be dirname/filename).
  7061. --logdir str : Change the default log directory. Default is LOG_imapsync
  7062. --prefix1 str : Remove prefix to all destination folders
  7063. (usually INBOX. or INBOX/ or an empty string "")
  7064. you have to use --prefix1 if host1 imap server
  7065. does not have NAMESPACE capability, so imapsync
  7066. suggests to use it. All other cases are bad.
  7067. --prefix2 str : Add prefix to all host2 folders. See --prefix1
  7068. --sep1 str : Host1 separator in case NAMESPACE is not supported.
  7069. --sep2 str : Host2 separator in case NAMESPACE is not supported.
  7070. --skipmess reg : Skips messages maching the regex.
  7071. Example: 'm/[\\x80-ff]/' # to avoid 8bits messages.
  7072. --skipmess is applied before --regexmess
  7073. --skipmess reg : or this one, etc.
  7074. --pipemess cmd : Apply this cmd command to each message content
  7075. before the copy.
  7076. --pipemess cmd : and this one, etc.
  7077. --disarmreadreceipts : Disarms read receipts (host2 Exchange issue)
  7078. --regexmess reg : Apply the whole regex to each message before transfer.
  7079. Example: 's/\\000/ /g' # to replace null by space.
  7080. --regexmess reg : and this one, etc.
  7081. --regexflag reg : Apply the whole regex to each flags list.
  7082. Example: 's/\"Junk"//g' # to remove "Junk" flag.
  7083. --regexflag reg : and this one, etc.
  7084. --delete : Deletes messages on host1 server after a successful
  7085. transfer. Option --delete has the following behavior:
  7086. it marks messages as deleted with the IMAP flag
  7087. \\Deleted, then messages are really deleted with an
  7088. EXPUNGE IMAP command.
  7089. --delete2 : Delete messages in host2 that are not in
  7090. host1 server. Useful for backup or pre-sync.
  7091. --delete2duplicates : Delete messages in host2 that are duplicates.
  7092. Works only without --useuid since duplicates are
  7093. detected with an header part of each message.
  7094. --delete2folders : Delete folders in host2 that are not in host1 server.
  7095. For safety, first try it like this (it is safe):
  7096. --delete2folders --dry --justfolders --nofoldersizes
  7097. --delete2foldersonly reg : Deleted only folders matching regex.
  7098. Example: --delete2foldersonly "/^Junk\$|^INBOX.Junk\$/"
  7099. --delete2foldersbutnot reg : Do not delete folders matching regex.
  7100. Example: --delete2foldersbutnot "/Tasks\$|Contacts\$|Foo\$/"
  7101. --noexpunge : Do not expunge messages on host1.
  7102. Expunge really deletes messages marked deleted.
  7103. Expunge is made at the beginning, on host1 only.
  7104. Newly transferred messages are also expunged if
  7105. option --delete is given.
  7106. No expunge is done on host2 account (unless --expunge2)
  7107. --expunge1 : Expunge messages on host1 after messages transfer.
  7108. --expunge2 : Expunge messages on host2 after messages transfer.
  7109. --uidexpunge2 : uidexpunge messages on the host2 account
  7110. that are not on the host1 account, requires --delete2
  7111. --nomixfolders : Avoid merging folders that are considered different on
  7112. host1 but the same on destination host2 because of
  7113. case sensitivities and insensitivities.
  7114. --syncinternaldates : Sets the internal dates on host2 same as host1.
  7115. Turned on by default. Internal date is the date
  7116. a message arrived on a host (mtime).
  7117. --idatefromheader : Sets the internal dates on host2 same as the
  7118. "Date:" headers.
  7119. --maxsize int : Skip messages larger (or equal) than int bytes
  7120. --minsize int : Skip messages smaller (or equal) than int bytes
  7121. --maxage int : Skip messages older than int days.
  7122. final stats (skipped) don't count older messages
  7123. see also --minage
  7124. --minage int : Skip messages newer than int days.
  7125. final stats (skipped) don't count newer messages
  7126. You can do (+ are the messages selected):
  7127. past|----maxage+++++++++++++++>now
  7128. past|+++++++++++++++minage---->now
  7129. past|----maxage+++++minage---->now (intersection)
  7130. past|++++minage-----maxage++++>now (union)
  7131. --search str : Selects only messages returned by this IMAP SEARCH
  7132. command. Applied on both sides.
  7133. --search1 str : Same as --search for selecting host1 messages only.
  7134. --search2 str : Same as --search for selecting host2 messages only.
  7135. --search CRIT equals --search1 CRIT --search2 CRIT
  7136. --exitwhenover int : Stop syncing when total bytes transferred reached.
  7137. Gmail per day allows
  7138. 2500000000 = 2.5 GB downloaded from Gmail as host2
  7139. 500000000 = 500 MB uploaded to Gmail as host1.
  7140. --maxlinelength int : skip messages with a line length longer than int bytes.
  7141. RFC 2822 says it must be no more than 1000 bytes.
  7142. --useheader str : Use this header to compare messages on both sides.
  7143. Ex: Message-ID or Subject or Date.
  7144. --useheader str and this one, etc.
  7145. --subscribed : Transfers subscribed folders.
  7146. --subscribe : Subscribe to the folders transferred on the
  7147. host2 that are subscribed on host1. On by default.
  7148. --subscribeall : Subscribe to the folders transferred on the
  7149. host2 even if they are not subscribed on host1.
  7150. --nofoldersizes : Do not calculate the size of each folder in bytes
  7151. and message counts. Default is to calculate them.
  7152. --nofoldersizesatend: Do not calculate the size of each folder in bytes
  7153. and message counts at the end. Default is on.
  7154. --justfoldersizes : Exit after having printed the folder sizes.
  7155. --syncacls : Synchronises acls (Access Control Lists).
  7156. --nosyncacls : Does not synchronize acls. This is the default.
  7157. Acls in IMAP are not standardized, be careful.
  7158. --usecache : Use cache to speedup.
  7159. --nousecache : Do not use cache. Caveat: --useuid --nousecache creates
  7160. duplicates on multiple runs.
  7161. --useuid : Use uid instead of header as a criterium to recognize
  7162. messages. Option --usecache is then implied unless
  7163. --nousecache is used.
  7164. --debug : Debug mode.
  7165. --debugfolders : Debug mode for the folders part only.
  7166. --debugcontent : Debug content of the messages transfered. Huge ouput.
  7167. --debugflags : Debug mode for flags.
  7168. --debugimap1 : IMAP debug mode for host1. Very verbose.
  7169. --debugimap2 : IMAP debug mode for host2. Very verbose.
  7170. --debugimap : IMAP debug mode for host1 and host2.
  7171. --debugmemory : Debug mode showing memory consumption after each copy.
  7172. --errorsmax int : Exit when int number of errors is reached. Default is 50.
  7173. --tests : Run local non-regression tests. Exit code 0 means all ok.
  7174. --testslive : Run a live test with test1.lamiral.info imap server.
  7175. Useful to check the basics. Needs internet connexion.
  7176. --version : Print only software version.
  7177. --noreleasecheck : Do not check for new imapsync release (a http request).
  7178. --releasecheck : Check for new imapsync release (a http request).
  7179. --noid : Do not send/receive ID command to imap servers.
  7180. --justconnect : Just connect to both servers and print useful
  7181. information. Need only --host1 and --host2 options.
  7182. --justlogin : Just login to both host1 and host2 with users
  7183. credentials, then exit.
  7184. --justfolders : Do only things about folders (ignore messages).
  7185. --help : print this help.
  7186. Example: to synchronize imap account "test1" on "test1.lamiral.info"
  7187. to imap account "test2" on "test2.lamiral.info"
  7188. with test1 password "secret1"
  7189. and test2 password "secret2"
  7190. $0 $escape_char
  7191. --host1 test1.lamiral.info --user1 test1 --password1 secret1 $escape_char
  7192. --host2 test2.lamiral.info --user2 test2 --password2 secret2
  7193. $localhost_info
  7194. $rcs
  7195. $imapsync_release
  7196. $thank
  7197. EOF
  7198. return( 1 ) ;
  7199. }
  7200. sub usage_complete {
  7201. myprint( <<'EOF' ) ;
  7202. --skipheader reg : Don't take into account header keyword
  7203. matching reg ex: --skipheader 'X.*'
  7204. --skipsize : Don't take message size into account to compare
  7205. messages on both sides. On by default.
  7206. Use --no-skipsize for using size comparaison.
  7207. --allowsizemismatch : allow RFC822.SIZE != fetched msg size
  7208. consider also --skipsize to avoid duplicate messages
  7209. when running syncs more than one time per mailbox
  7210. --reconnectretry1 int : reconnect to host1 if connection is lost up to
  7211. int times per imap command (default is 3)
  7212. --reconnectretry2 int : same as --reconnectretry1 but for host2
  7213. --split1 int : split the requests in several parts on host1.
  7214. int is the number of messages handled per request.
  7215. default is like --split1 500.
  7216. --split2 int : same thing on host2.
  7217. --nofixInboxINBOX : Don't fix Inbox INBOX mapping.
  7218. EOF
  7219. return ;
  7220. }
  7221. sub get_options {
  7222. # In CGI context arguments are not in @ARGV but in QUERY_STRING variable (with GET).
  7223. my $numopt = scalar @ARGV || length $ENV{'QUERY_STRING'} ;
  7224. my $argv = join "\x00", @ARGV ;
  7225. if ( $argv =~ m/-delete\x002/x ) {
  7226. myprint( "May be you mean --delete2 instead of --delete 2\n" ) ;
  7227. exit 1 ;
  7228. }
  7229. $sync->{f1f2} = {} ;
  7230. my $opt_ret = Imapsync::Getopt::Long::GetOptions(
  7231. 'debug!' => \$debug,
  7232. 'debuglist!' => \$debuglist,
  7233. 'debugcontent!' => \$debugcontent,
  7234. 'debugsleep=f' => \$sync->{debugsleep},
  7235. 'debugflags!' => \$debugflags,
  7236. 'debugimap!' => \$debugimap,
  7237. 'debugimap1!' => \$debugimap1,
  7238. 'debugimap2!' => \$debugimap2,
  7239. 'debugdev!' => \$debugdev,
  7240. 'debugmemory!' => \$sync->{debugmemory},
  7241. 'debugfolders!' => \$sync->{debugfolders},
  7242. 'debugssl=i' => \$sync->{debugssl},
  7243. 'debugbasket=s' => \@debugbasket,
  7244. 'debugcgi!' => \$debugcgi,
  7245. 'host1=s' => \$host1,
  7246. 'host2=s' => \$host2,
  7247. 'port1=i' => \$port1,
  7248. 'port2=i' => \$port2,
  7249. 'inet4' => \$sync->{inet4},
  7250. 'inet6' => \$sync->{inet6},
  7251. 'user1=s' => \$user1,
  7252. 'user2=s' => \$user2,
  7253. 'domain1=s' => \$domain1,
  7254. 'domain2=s' => \$domain2,
  7255. 'password1=s' => \$password1,
  7256. 'password2=s' => \$password2,
  7257. 'passfile1=s' => \$passfile1,
  7258. 'passfile2=s' => \$passfile2,
  7259. 'authmd5!' => \$authmd5,
  7260. 'authmd51!' => \$authmd51,
  7261. 'authmd52!' => \$authmd52,
  7262. 'sep1=s' => \$sep1,
  7263. 'sep2=s' => \$sep2,
  7264. 'folder=s' => \@folder,
  7265. 'folderrec=s' => \@folderrec,
  7266. 'include=s' => \@include,
  7267. 'exclude=s' => \@exclude,
  7268. 'folderfirst=s' => \@folderfirst,
  7269. 'folderlast=s' => \@folderlast,
  7270. 'prefix1=s' => \$prefix1,
  7271. 'prefix2=s' => \$prefix2,
  7272. 'subfolder2=s' => \$subfolder2,
  7273. 'fixslash2!' => \$fixslash2,
  7274. 'fixInboxINBOX!' => \$fixInboxINBOX,
  7275. 'regextrans2=s' => \@regextrans2,
  7276. 'mixfolders!' => \$mixfolders,
  7277. 'skipemptyfolders!' => \$skipemptyfolders,
  7278. 'regexmess=s' => \@regexmess,
  7279. 'skipmess=s' => \@skipmess,
  7280. 'pipemess=s' => \@pipemess,
  7281. 'pipemesscheck!' => \$pipemesscheck,
  7282. 'disarmreadreceipts!' => \$disarmreadreceipts,
  7283. 'regexflag=s' => \@regexflag,
  7284. 'filterflags!' => \$filterflags,
  7285. 'flagscase!' => \$flagscase,
  7286. 'syncflagsaftercopy!' => \$syncflagsaftercopy,
  7287. 'delete|delete1!' => \$delete,
  7288. 'delete2!' => \$delete2,
  7289. 'delete2duplicates!' => \$delete2duplicates,
  7290. 'delete2folders!' => \$delete2folders,
  7291. 'delete2foldersonly=s' => \$delete2foldersonly,
  7292. 'delete2foldersbutnot=s' => \$delete2foldersbutnot,
  7293. 'syncinternaldates!' => \$syncinternaldates,
  7294. 'idatefromheader!' => \$idatefromheader,
  7295. 'syncacls!' => \$syncacls,
  7296. 'maxsize=i' => \$maxsize,
  7297. 'minsize=i' => \$minsize,
  7298. 'maxage=i' => \$maxage,
  7299. 'minage=i' => \$minage,
  7300. 'search=s' => \$search,
  7301. 'search1=s' => \$search1,
  7302. 'search2=s' => \$search2,
  7303. 'foldersizes!' => \$foldersizes,
  7304. 'foldersizesatend!' => \$foldersizesatend,
  7305. 'dry!' => \$dry,
  7306. 'expunge!' => \$expunge,
  7307. 'expunge1!' => \$expunge1,
  7308. 'expunge2!' => \$expunge2,
  7309. 'uidexpunge2!' => \$uidexpunge2,
  7310. 'subscribed!' => \$subscribed,
  7311. 'subscribe!' => \$subscribe,
  7312. 'subscribeall|subscribe_all!' => \$subscribeall,
  7313. 'justbanner!' => \$justbanner,
  7314. 'justconnect!'=> \$justconnect,
  7315. 'justfolders!'=> \$justfolders,
  7316. 'justfoldersizes!' => \$justfoldersizes,
  7317. 'fast!' => \$fast,
  7318. 'version' => \$version,
  7319. 'help' => \$help,
  7320. 'timeout=i' => \$timeout,
  7321. 'timeout1=i' => \$sync->{h1}->{timeout},
  7322. 'timeout2=i' => \$sync->{h2}->{timeout},
  7323. 'skipheader=s' => \$skipheader,
  7324. 'useheader=s' => \@useheader,
  7325. 'wholeheaderifneeded!' => \$wholeheaderifneeded,
  7326. 'messageidnodomain!' => \$messageidnodomain,
  7327. 'skipsize!' => \$skipsize,
  7328. 'allowsizemismatch!' => \$allowsizemismatch,
  7329. 'fastio1!' => \$fastio1,
  7330. 'fastio2!' => \$fastio2,
  7331. 'ssl1!' => \$ssl1,
  7332. 'ssl2!' => \$ssl2,
  7333. 'ssl1_ssl_version=s' => \$sync->{h1}->{sslargs}->{SSL_version},
  7334. 'ssl2_ssl_version=s' => \$sync->{h2}->{sslargs}->{SSL_version},
  7335. 'sslargs1=s%' => \$sync->{h1}->{sslargs},
  7336. 'sslargs2=s%' => \$sync->{h2}->{sslargs},
  7337. 'tls1!' => \$tls1,
  7338. 'tls2!' => \$tls2,
  7339. 'uid1!' => \$uid1,
  7340. 'uid2!' => \$uid2,
  7341. 'authmech1=s' => \$authmech1,
  7342. 'authmech2=s' => \$authmech2,
  7343. 'authuser1=s' => \$authuser1,
  7344. 'authuser2=s' => \$authuser2,
  7345. 'proxyauth1' => \$proxyauth1,
  7346. 'proxyauth2' => \$proxyauth2,
  7347. 'split1=i' => \$split1,
  7348. 'split2=i' => \$split2,
  7349. 'buffersize=i' => \$buffersize,
  7350. 'reconnectretry1=i' => \$reconnectretry1,
  7351. 'reconnectretry2=i' => \$reconnectretry2,
  7352. 'tests!' => \$tests,
  7353. 'testsdebug|tests_debug!' => \$testsdebug,
  7354. 'testslive!' => \$testslive,
  7355. 'justlogin!' => \$justlogin,
  7356. 'tmpdir=s' => \$tmpdir,
  7357. 'pidfile=s' => \$sync->{pidfile},
  7358. 'pidfilelocking!' => \$sync->{pidfilelocking},
  7359. 'releasecheck!' => \$releasecheck,
  7360. 'modulesversion|modules_version!' => \$modulesversion,
  7361. 'usecache!' => \$usecache,
  7362. 'cacheaftercopy!' => \$cacheaftercopy,
  7363. 'debugcache!' => \$debugcache,
  7364. 'useuid!' => \$useuid,
  7365. 'addheader!' => \$addheader,
  7366. 'exitwhenover=i' => \$exitwhenover,
  7367. 'checkselectable!' => \$checkselectable,
  7368. 'checkmessageexists!' => \$checkmessageexists,
  7369. 'expungeaftereach!' => \$expungeaftereach,
  7370. 'abletosearch!' => \$abletosearch,
  7371. 'showpasswords!' => \$showpasswords,
  7372. 'maxlinelength=i' => \$maxlinelength,
  7373. 'maxlinelengthcmd=s' => \$maxlinelengthcmd,
  7374. 'minmaxlinelength=i' => \$minmaxlinelength,
  7375. 'debugmaxlinelength!' => \$debugmaxlinelength,
  7376. 'fixcolonbug!' => \$fixcolonbug,
  7377. 'create_folder_old!' => \$create_folder_old,
  7378. 'maxmessagespersecond=f' => \$maxmessagespersecond,
  7379. 'maxbytespersecond=i' => \$maxbytespersecond,
  7380. 'skipcrossduplicates!' => \$skipcrossduplicates,
  7381. 'debugcrossduplicates!' => \$debugcrossduplicates,
  7382. 'log!' => \$sync->{log},
  7383. 'logfile=s' => \$sync->{logfile},
  7384. 'logdir=s' => \$sync->{logdir},
  7385. 'errorsmax=i' => \$sync->{errorsmax},
  7386. 'errorsdump!' => \$sync->{errorsdump},
  7387. 'fetch_hash_set=s' => \$fetch_hash_set,
  7388. 'automap!' => \$sync->{automap},
  7389. 'justautomap!' => \$sync->{justautomap},
  7390. 'id!' => \$sync->{id},
  7391. 'f1f2=s%' => \$sync->{f1f2},
  7392. 'justfolderlists!' => \$sync->{justfolderlists},
  7393. 'delete1emptyfolders' => \$sync->{delete1emptyfolders},
  7394. ) ;
  7395. $debugcgi and myprint( map { "$_ => $ENV{$_}\n" } sort keys %ENV ) ;
  7396. $debugcgi and myprint( "@debugbasket\n" ) ;
  7397. $debug and myprint( "get options: [$opt_ret]\n" ) ;
  7398. # just the version
  7399. myprint( imapsync_version( ), "\n" ) and exit 0 if ( $version ) ;
  7400. # $tmpdir is used in tests_pipemess()
  7401. $tmpdir ||= File::Spec->tmpdir( ) ;
  7402. if ( $tests or $testsdebug ) {
  7403. $test_builder = Test::More->builder ;
  7404. if ( $tests ) { tests( ) ; }
  7405. if ( $testsdebug ) { testsdebug( ) ; }
  7406. #$test_builder->reset( ) ;
  7407. exit ;
  7408. }
  7409. #$help = 1 if ! $numopt;
  7410. load_modules( );
  7411. # exit with --help option or no option at all
  7412. $debug and myprint( "numopt:$numopt\n" ) ;
  7413. usage( ) and exit if ( $help or not $numopt ) ;
  7414. # don't go on if options are not all known.
  7415. exit $EX_USAGE unless ( $opt_ret ) ;
  7416. # init live varaiables
  7417. testslive( ) if ( $testslive ) ;
  7418. return ;
  7419. }
  7420. sub testslive {
  7421. $host1 = 'test1.lamiral.info' ;
  7422. $user1 = 'test1' ;
  7423. $password1 = 'secret1' ;
  7424. $host2 = 'test2.lamiral.info' ;
  7425. $user2 = 'test2' ;
  7426. $password2 ='secret2' ;
  7427. return ;
  7428. }
  7429. sub testsdebug {
  7430. SKIP: {
  7431. skip 'No test in normal run' if ( not $testsdebug ) ;
  7432. #tests_bytes_display_string( ) ;
  7433. #tests_ucsecond( ) ;
  7434. #tests_mkpath( ) ;
  7435. #eval { tests_mkpath( ) ; } or ok( 0 == 1, 'tests_mkpath fail badly?' ) ;
  7436. #tests_format_for_imap_arg( ) ;
  7437. #tests_is_a_release_number( ) ;
  7438. #tests_delete1emptyfolders( ) ;
  7439. #tests_memory_consumption( ) ;
  7440. #tests_imap2_folder_name() ;
  7441. #tests_length_ref( ) ;
  7442. #tests_is_valid_directory( ) ;
  7443. #tests_firstline( ) ;
  7444. #tests_diff_or_NA( ) ;
  7445. #tests_match_number( ) ;
  7446. #tests_all_defined( ) ;
  7447. #tests_guess_separator( ) ;
  7448. tests_pipemess( ) ;
  7449. #tests_message_for_host2( ) ;
  7450. done_testing( ) ;
  7451. note('End of imapsync --tests_debug') ;
  7452. }
  7453. return ;
  7454. }
  7455. sub tests {
  7456. SKIP: {
  7457. skip 'No test in normal run' if ( not $tests ) ;
  7458. tests_folder_routines( ) ;
  7459. tests_compare_lists( ) ;
  7460. tests_regexmess();
  7461. tests_skipmess( ) ;
  7462. tests_flags_regex();
  7463. tests_ucsecond( ) ;
  7464. tests_permanentflags();
  7465. tests_flags_filter( ) ;
  7466. tests_separator_invert( ) ;
  7467. tests_imap2_folder_name() ;
  7468. tests_command_line_nopassword();
  7469. tests_good_date( ) ;
  7470. tests_max();
  7471. tests_remove_not_num();
  7472. tests_memory_consumption( ) ;
  7473. tests_is_a_release_number();
  7474. tests_imapsync_basename();
  7475. tests_list_keys_in_2_not_in_1();
  7476. tests_convert_sep_to_slash( ) ;
  7477. tests_match_a_cache_file( ) ;
  7478. tests_cache_map( ) ;
  7479. tests_get_cache( ) ;
  7480. tests_clean_cache( ) ;
  7481. tests_clean_cache_2( ) ;
  7482. tests_touch( ) ;
  7483. tests_flagscase( ) ;
  7484. eval { tests_mkpath( ) ; } or ok( 0 == 1, 'tests_mkpath fail badly?' ) ;
  7485. tests_extract_header( ) ;
  7486. tests_decompose_header( ) ;
  7487. tests_epoch( ) ;
  7488. tests_add_header( ) ;
  7489. tests_cache_dir_fix( ) ;
  7490. tests_cache_dir_fix_win( ) ;
  7491. tests_filter_forbidden_characters( ) ;
  7492. tests_cache_folder( ) ;
  7493. tests_time_remaining( ) ;
  7494. tests_decompose_regex( ) ;
  7495. tests_Banner( ) ;
  7496. tests_backtick( ) ;
  7497. tests_bytes_display_string( ) ;
  7498. tests_header_line_normalize( ) ;
  7499. tests_fix_Inbox_INBOX_mapping( ) ;
  7500. tests_max_line_length( ) ;
  7501. tests_subject( ) ;
  7502. tests_msgs_from_maxmin( ) ;
  7503. tests_tmpdir_has_colon_bug( ) ;
  7504. tests_sleep_max_messages( ) ;
  7505. tests_sleep_max_bytes( ) ;
  7506. tests_logfile( ) ;
  7507. tests_setlogfile( ) ;
  7508. tests_jux_utf8( ) ;
  7509. tests_pipemess( ) ;
  7510. tests_jux_utf8_list( ) ;
  7511. tests_guess_prefix( ) ;
  7512. tests_guess_separator( ) ;
  7513. tests_format_for_imap_arg( ) ;
  7514. tests_imapsync_id( ) ;
  7515. tests_date_from_rcs( ) ;
  7516. tests_quota_extract_storage_limit_in_bytes( ) ;
  7517. tests_quota_extract_storage_current_in_bytes( ) ;
  7518. tests_guess_special( ) ;
  7519. tests_is_valid_directory( ) ;
  7520. tests_delete1emptyfolders( ) ;
  7521. tests_message_for_host2( ) ;
  7522. tests_length_ref( ) ;
  7523. tests_firstline( ) ;
  7524. tests_diff_or_NA( ) ;
  7525. #tests_always_fail( ) ;
  7526. tests_match_number( ) ;
  7527. tests_all_defined( ) ;
  7528. done_testing( 693 ) ;
  7529. note('End of imapsync --tests') ;
  7530. }
  7531. return ;
  7532. }
  7533. # IMAPClient 3.xx ads
  7534. package Mail::IMAPClient;
  7535. sub Tls {
  7536. my $self = shift ;
  7537. my $value = shift ;
  7538. if ( defined $value ) { $self->{TLS} = $value }
  7539. return $self->{TLS};
  7540. }
  7541. sub Reconnect_counter {
  7542. my $self = shift ;
  7543. my $value = shift ;
  7544. $self->{Reconnect_counter} = 0 if ( not defined $self->{Reconnect_counter} ) ;
  7545. if ( defined $value ) { $self->{Reconnect_counter} = $value }
  7546. return( $self->{Reconnect_counter} ) ;
  7547. }
  7548. sub Banner {
  7549. my $self = shift ;
  7550. my $value = shift ;
  7551. if ( defined $value ) { $self->{ BANNER } = $value }
  7552. return $self->{ BANNER };
  7553. }
  7554. sub capability_update {
  7555. my $self = shift ;
  7556. delete $self->{CAPABILITY} ;
  7557. return( $self->capability ) ;
  7558. }
  7559. package Imapsync::Getopt::Long ;
  7560. # Started as a copy of Luke Ross Getopt::Long::CGI
  7561. # https://metacpan.org/release/Getopt-Long-CGI
  7562. # So this section is under the same license as Getopt-Long-CGI Luke Ross wants it,
  7563. # which was Perl 5.6 or later licenses at the date of the copy.
  7564. use strict ;
  7565. use warnings ;
  7566. use Getopt::Long( ) ;
  7567. sub GetOptions {
  7568. my %options = @_ ;
  7569. if ( not $ENV{SERVER_SOFTWARE} ) {
  7570. # Not CGI - pass upstream for normal command line handling
  7571. return Getopt::Long::GetOptions( %options ) ;
  7572. }
  7573. my $b_ref = $options{'debugbasket=s'} ;
  7574. require CGI ;
  7575. require CGI::Carp ;
  7576. CGI::Carp->import( 'fatalsToBrowser' ) ;
  7577. my $cgi = CGI->new( ) ;
  7578. $cgi->param( 'debugcgi' ) and myprint( "<h2>Current Values</h2>\n" . $cgi->Dump ) ;
  7579. foreach my $key (sort keys %options) {
  7580. my $val = $options{$key};
  7581. #push( @{$b_ref}, "opt:[$key] val:[$val]" . ( ('SCALAR' eq ref($val) and defined $$val ) ? " [$$val]" : q{} ) . "\n" ) ;
  7582. if ( $key !~ m/^([\w\d\|]+)([=:][isf])?([\+!\@\%])?$/ ) {
  7583. push @{$b_ref}, "Unknown opt: [$key]\n" ;
  7584. next ; # Unknown item
  7585. }
  7586. my $name = [split '|', $1, 1 ]->[0];
  7587. if (($3 || q{}) eq '+') {
  7588. ${ $val } = $cgi->param($name); # "Incremental" integer
  7589. } elsif ($2) {
  7590. my @values = $cgi->param($name);
  7591. my $type = $2;
  7592. if (($3 || q{}) eq '%' or ref($val) eq 'HASH') {
  7593. my %values = map { split /=/, $_, 1 } @values;
  7594. if ($type =~ m/i$/) {
  7595. foreach my $k (keys %values) {
  7596. $values{$k} = int $values{$k} ;
  7597. }
  7598. } elsif ($type =~ m/f$/) {
  7599. foreach my $k (keys %values) {
  7600. $values{$k} = 0 + $values{$k}
  7601. }
  7602. }
  7603. if ( ref($val) eq 'CODE') {
  7604. while(my($k, $v) = each %values) {
  7605. $val->($name, $k, $v);
  7606. }
  7607. } elsif ( 'REF' eq ref $val ) {
  7608. #push( @{$b_ref}, "refref($$val): " . ref($$val) . " %values= ", %values, "\n\n" ) ;
  7609. %{ ${ $val } } = %values;
  7610. } else {
  7611. #push( @{$b_ref}, "ref($val): " . ref($val) . " %values= ", %values, "\n\n" ) ;
  7612. %{ $val } = %values;
  7613. }
  7614. } else {
  7615. if ($type =~ m/i$/) {
  7616. @values = map { int $_ } @values;
  7617. } elsif ($type =~ m/f$/) {
  7618. @values = map { 0 + $_ } @values;
  7619. }
  7620. if (($3 || q{}) eq '@' or ref($val) eq 'ARRAY') {
  7621. if (ref($val) eq 'CODE') {
  7622. $val->($name, \@values)
  7623. } else {
  7624. @{ $val } = @values ;
  7625. }
  7626. } else {
  7627. if (ref($val) eq 'CODE') {
  7628. $val->($name, $values[0]);
  7629. } else {
  7630. ${ $val } = $values[0];
  7631. }
  7632. }
  7633. }
  7634. } else {
  7635. # Checkbox
  7636. ${ $val } = $cgi->param($name) ? 1 : undef ;
  7637. #push( @{$b_ref}, "param($name) ref($val): " . ref($val) . " val=[$$val]\n\n" ) ;
  7638. }
  7639. }
  7640. return( 1 ) ;
  7641. }