imapsync 482 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808
  1. #!/usr/bin/perl
  2. # $Id: imapsync,v 1.882 2018/05/05 21:10:43 gilles Exp gilles $
  3. # structure
  4. # pod documentation
  5. # use pragmas
  6. # main program
  7. # global variables initialization
  8. # get_options( ) ;
  9. # default values
  10. # folder loop
  11. # subroutines
  12. # sub usage {
  13. # pod documentation
  14. =pod
  15. =head1 NAME
  16. imapsync - Email IMAP tool for syncing, copying and migrating
  17. email mailboxes between two imap servers, one way,
  18. and without duplicates.
  19. =head1 VERSION
  20. This documentation refers to Imapsync $Revision: 1.882 $
  21. =head1 USAGE
  22. To synchronize the source imap account
  23. "test1" on server "test1.lamiral.info" with password "secret1"
  24. to the destination imap account
  25. "test2" on server "test2.lamiral.info" with password "secret2"
  26. do:
  27. imapsync \
  28. --host1 test1.lamiral.info --user1 test1 --password1 secret1 \
  29. --host2 test2.lamiral.info --user2 test2 --password2 secret2
  30. =head1 DESCRIPTION
  31. We sometimes need to transfer mailboxes from one imap server to
  32. one another.
  33. Imapsync command is a tool allowing incremental and
  34. recursive imap transfers from one mailbox to another.
  35. By default all folders are transferred, recursively, meaning
  36. the whole folder hierarchy is taken, all messages in them,
  37. and all messages flags (\Seen \Answered \Flagged etc.)
  38. are synced too.
  39. Imapsync reduces the amount of data transferred by not transferring
  40. a given message if it resides already on both sides.
  41. Same specific headers and the transfer is done only once.
  42. By default, the identification headers are
  43. "Message-Id:" and "Received:" lines
  44. but this choice can be changed with the --useheader option.
  45. All flags are preserved, unread messages will stay unread,
  46. read ones will stay read, deleted will stay deleted.
  47. You can stop the transfer at any time and restart it later,
  48. imapsync works well with bad connections and interruptions,
  49. by design.
  50. You can decide to delete the messages from the source mailbox
  51. after a successful transfer, it can be a good feature when migrating
  52. live mailboxes since messages will be only on one side.
  53. In that case, use the --delete1 option. Option --delete1 implies
  54. also option --expunge1 so all messages marked deleted on host1
  55. will be really deleted.
  56. You can also decide to remove empty folders once all of their
  57. messages have been transferred. Add --delete1emptyfolders to
  58. obtain this behavior.
  59. A different scenario is synchronizing a mailbox B from another mailbox A
  60. in case you just want to keep a "live" copy of A in B.
  61. For this, option --delete2 has to be used, it deletes messages in host2
  62. folder B that are not in host1 folder A. If you also need to destroy
  63. host2 folders that are not in host1 then use --delete2folders. See also
  64. --delete2foldersonly and --delete2foldersbutnot.
  65. Imapsync is not adequate for maintaining two active imap accounts
  66. in synchronization when the user plays independently on both sides.
  67. Use offlineimap (written by John Goerzen) or mbsync (written by
  68. Michael R. Elkins) for a 2 ways synchronization.
  69. =head1 OPTIONS
  70. usage: imapsync [options]
  71. Mandatory options are the six values, three on each sides,
  72. needed to log in into the IMAP servers, ie,
  73. a host, a username, and a password, two times.
  74. Conventions used:
  75. str means string
  76. int means integer
  77. reg means regular expression
  78. cmd means command
  79. --dry : Makes imapsync doing nothing for real, just print what
  80. would be done without --dry.
  81. =head2 OPTIONS/credentials
  82. --host1 str : Source or "from" imap server. Mandatory.
  83. --port1 int : Port to connect on host1.
  84. Optional since default port is 143 or 993 if --ssl1
  85. --user1 str : User to login on host1. Mandatory.
  86. --password1 str : Password for the user1.
  87. --host2 str : "destination" imap server. Mandatory.
  88. --port2 int : Port to connect on host2.
  89. Optional since default port is 143 or 993 if --ssl2
  90. --user2 str : User to login on host2. Mandatory.
  91. --password2 str : Password for the user2.
  92. --showpasswords : Shows passwords on output instead of "MASKED".
  93. Useful to restart a complete run by just reading the log,
  94. or to debug passwords. It's not a secure practice.
  95. --passfile1 str : Password file for the user1. It must contain the
  96. password on the first line. This option avoids to show
  97. the password on the command line like --password1 does.
  98. --passfile2 str : Password file for the user2. Contains the password.
  99. =head2 OPTIONS/encryption
  100. --nossl1 : Do not use a SSL connection on host1.
  101. --ssl1 : Use a SSL connection on host1. On by default if possible.
  102. --nossl2 : Do not use a SSL connection on host2.
  103. --ssl2 : Use a SSL connection on host2. On by default if possible.
  104. --notls1 : Do not use a TLS connection on host1.
  105. --tls1 : Use a TLS connection on host1. On by default if possible.
  106. --notls2 : Do not use a TLS connection on host2.
  107. --tls2 : Use a TLS connection on host2. On by default if possible.
  108. --debugssl int : SSL debug mode from 0 to 4.
  109. --sslargs1 str : Pass any ssl parameter for host1 ssl or tls connection. Example:
  110. --sslargs1 SSL_verify_mode=1 --sslargs1 SSL_version=SSLv3
  111. See all possibilities in the new() method of IO::Socket::SSL
  112. http://search.cpan.org/perldoc?IO::Socket::SSL#Description_Of_Methods
  113. --sslargs2 str : Pass any ssl parameter for host2 ssl or tls connection.
  114. See --sslargs1
  115. --timeout1 int : Connection timeout in seconds for host1.
  116. Default is 120 and 0 means no timeout at all.
  117. --timeout2 int : Connection timeout in seconds for host2.
  118. Default is 120 and 0 means no timeout at all.
  119. =head2 OPTIONS/authentication
  120. --authmech1 str : Auth mechanism to use with host1:
  121. PLAIN, LOGIN, CRAM-MD5 etc. Use UPPERCASE.
  122. --authmech2 str : Auth mechanism to use with host2. See --authmech1
  123. --authuser1 str : User to auth with on host1 (admin user).
  124. Avoid using --authmech1 SOMETHING with --authuser1.
  125. --authuser2 str : User to auth with on host2 (admin user).
  126. --proxyauth1 : Use proxyauth on host1. Requires --authuser1.
  127. Required by Sun/iPlanet/Netscape IMAP servers to
  128. be able to use an administrative user.
  129. --proxyauth2 : Use proxyauth on host2. Requires --authuser2.
  130. --authmd51 : Use MD5 authentication for host1.
  131. --authmd52 : Use MD5 authentication for host2.
  132. --domain1 str : Domain on host1 (NTLM authentication).
  133. --domain2 str : Domain on host2 (NTLM authentication).
  134. =head2 OPTIONS/folders
  135. --folder str : Sync this folder.
  136. --folder str : and this one, etc.
  137. --folderrec str : Sync this folder recursively.
  138. --folderrec str : and this one, etc.
  139. --folderfirst str : Sync this folder first. --folderfirst "Work"
  140. --folderfirst str : then this one, etc.
  141. --folderlast str : Sync this folder last. --folderlast "[Gmail]/All Mail"
  142. --folderlast str : then this one, etc.
  143. --nomixfolders : Do not merge folders when host1 is case-sensitive
  144. while host2 is not (like Exchange). Only the first
  145. similar folder is synced (ex: with Sent SENT sent
  146. on host1 only Sent will be synced to host2).
  147. --skipemptyfolders : Empty host1 folders are not created on host2.
  148. --include reg : Sync folders matching this regular expression
  149. --include reg : or this one, etc.
  150. If both --include --exclude options are used, then
  151. include is done before.
  152. --exclude reg : Skips folders matching this regular expression
  153. Several folders to avoid:
  154. --exclude 'fold1|fold2|f3' skips fold1, fold2 and f3.
  155. --exclude reg : or this one, etc.
  156. --automap : guesses folders mapping, for folders well known as
  157. "Sent", "Junk", "Drafts", "All", "Archive", "Flagged".
  158. --f1f2 str1=str2 : Force folder str1 to be synced to str2,
  159. --f1f2 overrides --automap and --regextrans2.
  160. --subfolder2 str : Move whole host1 folders hierarchy under this
  161. host2 folder str .
  162. It does it by adding two --regextrans2 options before
  163. all others. Add --debug to see what's really going on.
  164. --subscribed : Transfers subscribed folders.
  165. --subscribe : Subscribe to the folders transferred on the
  166. host2 that are subscribed on host1. On by default.
  167. --subscribeall : Subscribe to the folders transferred on the
  168. host2 even if they are not subscribed on host1.
  169. --prefix1 str : Remove prefix str to all destination folders,
  170. usually INBOX. or INBOX/ or an empty string "".
  171. imapsync guesses the prefix if host1 imap server
  172. does not have NAMESPACE capability. This option
  173. should not be used, most of the time.
  174. --prefix2 str : Add prefix to all host2 folders. See --prefix1
  175. --sep1 str : Host1 separator in case NAMESPACE is not supported.
  176. --sep2 str : Host2 separator in case NAMESPACE is not supported.
  177. --regextrans2 reg : Apply the whole regex to each destination folders.
  178. --regextrans2 reg : and this one. etc.
  179. When you play with the --regextrans2 option, first
  180. add also the safe options --dry --justfolders
  181. Then, when happy, remove --dry, remove --justfolders.
  182. Have in mind that --regextrans2 is applied after prefix
  183. and separator inversion. For examples see
  184. https://imapsync.lamiral.info/FAQ.d/FAQ.Folders_Mapping.txt
  185. =head2 OPTIONS/folders sizes
  186. --nofoldersizes : Do not calculate the size of each folder at the
  187. beginning of the sync. Default is to calculate them.
  188. --nofoldersizesatend: Do not calculate the size of each folder at the
  189. end of the sync. Default is to calculate them.
  190. --justfoldersizes : Exit after having printed the initial folder sizes.
  191. =head2 OPTIONS/tmp
  192. --tmpdir str : Where to store temporary files and subdirectories.
  193. Will be created if it doesn't exist.
  194. Default is system specific, Unix is /tmp but
  195. /tmp is often too small and deleted at reboot.
  196. --tmpdir /var/tmp should be better.
  197. --pidfile str : The file where imapsync pid is written,
  198. it can be dirname/filename.
  199. Default name is imapsync.pid in tmpdir.
  200. --pidfilelocking : Abort if pidfile already exists. Useful to avoid
  201. concurrent transfers on the same mailbox.
  202. =head2 OPTIONS/log
  203. --nolog : Turn off logging on file
  204. --logfile str : Change the default log filename (can be dirname/filename).
  205. --logdir str : Change the default log directory. Default is LOG_imapsync/
  206. =head2 OPTIONS/messages
  207. --skipmess reg : Skips messages matching the regex.
  208. Example: 'm/[\x80-ff]/' # to avoid 8bits messages.
  209. --skipmess is applied before --regexmess
  210. --skipmess reg : or this one, etc.
  211. --pipemess cmd : Apply this cmd command to each message content
  212. before the copy.
  213. --pipemess cmd : and this one, etc.
  214. --disarmreadreceipts : Disarms read receipts (host2 Exchange issue)
  215. --regexmess reg : Apply the whole regex to each message before transfer.
  216. Example: 's/\000/ /g' # to replace null by space.
  217. --regexmess reg : and this one, etc.
  218. =head2 OPTIONS/flags
  219. --regexflag reg : Apply the whole regex to each flags list.
  220. Example: 's/"Junk"//g' # to remove "Junk" flag.
  221. --regexflag reg : then this one, etc.
  222. --resyncflags : Resync flags for already transferred messages.
  223. On by default.
  224. --noresyncflags : Do not resync flags for already transferred messages.
  225. May be useful when a user has already started to play
  226. with its host2 account.
  227. =head2 OPTIONS/deletions
  228. --delete1 : Deletes messages on host1 server after a successful
  229. transfer. Option --delete1 has the following behavior:
  230. it marks messages as deleted with the IMAP flag
  231. \Deleted, then messages are really deleted with an
  232. EXPUNGE IMAP command. If expunging after each message
  233. slows down too much the sync then use
  234. --noexpungeaftereach to speed up.
  235. --expunge1 : Expunge messages on host1 just before syncing a folder.
  236. Expunge is done per folder.
  237. Expunge aims is to really delete messages marked deleted.
  238. An expunge is also done after each message copied
  239. if option --delete1 is set.
  240. --noexpunge1 : Do not expunge messages on host1.
  241. --delete1emptyfolders : Deletes empty folders on host1, INBOX excepted.
  242. Useful with --delete1 since what remains on host1
  243. is only what failed to be synced.
  244. --delete2 : Delete messages in host2 that are not in
  245. host1 server. Useful for backup or pre-sync.
  246. --delete2duplicates : Delete messages in host2 that are duplicates.
  247. Works only without --useuid since duplicates are
  248. detected with an header part of each message.
  249. --delete2folders : Delete folders in host2 that are not in host1 server.
  250. For safety, first try it like this (it is safe):
  251. --delete2folders --dry --justfolders --nofoldersizes
  252. --delete2foldersonly reg : Deleted only folders matching regex.
  253. Example: --delete2foldersonly "/^Junk$|^INBOX.Junk$/"
  254. --delete2foldersbutnot reg : Do not delete folders matching regex.
  255. Example: --delete2foldersbutnot "/Tasks$|Contacts$|Foo$/"
  256. --expunge2 : Expunge messages on host2 after messages transfer.
  257. --uidexpunge2 : uidexpunge messages on the host2 account
  258. that are not on the host1 account, requires --delete2
  259. =head2 OPTIONS/dates
  260. --syncinternaldates : Sets the internal dates on host2 same as host1.
  261. Turned on by default. Internal date is the date
  262. a message arrived on a host (mtime).
  263. --idatefromheader : Sets the internal dates on host2 same as the
  264. "Date:" headers.
  265. If you encounter problems with dates see also
  266. https://imapsync.lamiral.info/FAQ.d/FAQ.Dates.txt
  267. =head2 OPTIONS/message selection
  268. --maxsize int : Skip messages larger (or equal) than int bytes
  269. --minsize int : Skip messages smaller (or equal) than int bytes
  270. --maxage int : Skip messages older than int days.
  271. final stats (skipped) don't count older messages
  272. see also --minage
  273. --minage int : Skip messages newer than int days.
  274. final stats (skipped) don't count newer messages
  275. You can do (+ are the messages selected):
  276. past|----maxage+++++++++++++++>now
  277. past|+++++++++++++++minage---->now
  278. past|----maxage+++++minage---->now (intersection)
  279. past|++++minage-----maxage++++>now (union)
  280. --search str : Selects only messages returned by this IMAP SEARCH
  281. command. Applied on both sides.
  282. For a complete of what can be search see
  283. https://imapsync.lamiral.info/FAQ.d/FAQ.Messages_Selection.txt
  284. --search1 str : Same as --search but for selecting host1 messages only.
  285. --search2 str : Same as --search but for selecting host2 messages only.
  286. --search CRIT equals --search1 CRIT --search2 CRIT
  287. --maxlinelength int : skip messages with a line length longer than int bytes.
  288. RFC 2822 says it must be no more than 1000 bytes.
  289. --useheader str : Use this header to compare messages on both sides.
  290. Ex: Message-ID or Subject or Date.
  291. --useheader str and this one, etc.
  292. --usecache : Use cache to speed up the sync.
  293. --nousecache : Do not use cache. Caveat: --useuid --nousecache creates
  294. duplicates on multiple runs.
  295. --useuid : Use UIDs instead of headers as a criterium to recognize
  296. messages. Option --usecache is then implied unless
  297. --nousecache is used.
  298. =head2 OPTIONS/miscellaneous
  299. --syncacls : Synchronizes acls (Access Control Lists).
  300. --nosyncacls : Does not synchronize acls. This is the default.
  301. Acls in IMAP are not standardized, be careful.
  302. =head2 OPTIONS/debugging
  303. --debug : Debug mode.
  304. --debugfolders : Debug mode for the folders part only.
  305. --debugcontent : Debug content of the messages transferred. Huge output.
  306. --debugflags : Debug mode for flags.
  307. --debugimap1 : IMAP debug mode for host1. Very verbose.
  308. --debugimap2 : IMAP debug mode for host2. Very verbose.
  309. --debugimap : IMAP debug mode for host1 and host2. Twice very verbose.
  310. --debugmemory : Debug mode showing memory consumption after each copy.
  311. --errorsmax int : Exit when int number of errors is reached. Default is 50.
  312. --tests : Run local non-regression tests. Exit code 0 means all ok.
  313. --testslive : Run a live test with test1.lamiral.info imap server.
  314. Useful to check the basics. Needs internet connection.
  315. --testslive6 : Run a live test with ks2ipv6.lamiral.info imap server.
  316. Useful to check the ipv6 connectivity. Needs internet.
  317. =head2 OPTIONS/specific
  318. --gmail1 : sets --host1 to Gmail and options from FAQ.Gmail.txt
  319. --gmail2 : sets --host2 to Gmail and options from FAQ.Gmail.txt
  320. --office1 : sets --host1 to Office365 options from FAQ.Exchange.txt
  321. --office2 : sets --host2 to Office365 options from FAQ.Exchange.txt
  322. --exchange1 : sets options from FAQ.Exchange.txt, account1 part
  323. --exchange2 : sets options from FAQ.Exchange.txt, account2 part
  324. --domino1 : sets options from FAQ.Domino.txt, account1 part
  325. --domino2 : sets options from FAQ.Domino.txt, account2 part
  326. =head2 OPTIONS/behavior
  327. --maxmessagespersecond int : limits the number of messages transferred per second.
  328. --maxbytespersecond int : limits the average transfer rate per second.
  329. --maxbytesafter int : starts --maxbytespersecond limitation only after
  330. --maxbytesafter amount of data transferred.
  331. --maxsleep int : do not sleep more than int seconds.
  332. On by default, 2 seconds max, like --maxsleep 2
  333. --abort : terminates a previous call still running.
  334. It uses the pidfile to know what process to abort.
  335. --exitwhenover int : Stop syncing when total bytes transferred reached.
  336. --version : Print only software version.
  337. --noreleasecheck : Do not check for new imapsync release (a http request).
  338. --releasecheck : Check for new imapsync release (a http request).
  339. --noid : Do not send/receive ID command to imap servers.
  340. --justconnect : Just connect to both servers and print useful
  341. information. Need only --host1 and --host2 options.
  342. --justlogin : Just login to both host1 and host2 with users
  343. credentials, then exit.
  344. --justfolders : Do only things about folders (ignore messages).
  345. --help : print this help.
  346. Example: to synchronize imap account "test1" on "test1.lamiral.info"
  347. to imap account "test2" on "test2.lamiral.info"
  348. with test1 password "secret1"
  349. and test2 password "secret2"
  350. imapsync \
  351. --host1 test1.lamiral.info --user1 test1 --password1 secret1 \
  352. --host2 test2.lamiral.info --user2 test2 --password2 secret2
  353. =cut
  354. # comment
  355. =pod
  356. =head1 SECURITY
  357. You can use --passfile1 instead of --password1 to give the
  358. password since it is safer. With --password1 option, any user
  359. on your host can see the password by using the 'ps auxwwww'
  360. command. Using a variable (like $PASSWORD1) is also
  361. dangerous because of the 'ps auxwwwwe' command. So, saving
  362. the password in a well protected file (600 or rw-------) is
  363. the best solution.
  364. Imapsync activates ssl or tls encryption by default, if possible.
  365. What detailed behavior is under this "if possible"?
  366. Imapsync activates ssl if the well known port imaps port (993) is open
  367. on the imap servers. If the imaps port is closed then it open a
  368. normal (clear) connection on port 143 but it looks for TLS support
  369. in the CAPABILITY list of the servers. If TLS is supported
  370. then imapsync goes to encryption.
  371. If the automatic ssl/tls detection fails then imapsync will
  372. not protect against sniffing activities on the
  373. network, especially for passwords.
  374. If you want to force ssl or tls just use --ssl1 --ssl2 or --tls1 --tls2
  375. See also the document FAQ.Security.txt in the FAQ.d/ directory
  376. or at https://imapsync.lamiral.info/FAQ.d/FAQ.Security.txt
  377. =head1 EXIT STATUS
  378. Imapsync will exit with a 0 status (return code) if everything went good.
  379. Otherwise, it exits with a non-zero status.
  380. =head1 LICENSE AND COPYRIGHT
  381. Imapsync is free, open, public but not always gratis software
  382. cover by the NOLIMIT Public License.
  383. See the LICENSE file included in the distribution or just read this
  384. simple sentence as it IS the licence text:
  385. "No limits to do anything with this work and this license."
  386. In case it is not long enough, I repeat:
  387. "No limits to do anything with this work and this license."
  388. https://imapsync.lamiral.info/LICENSE
  389. =head1 AUTHOR
  390. Gilles LAMIRAL <gilles@lamiral.info>
  391. Feedback good or bad is very often welcome.
  392. Gilles LAMIRAL earns his living by writing, installing,
  393. configuring and teaching free, open and often gratis
  394. software. Imapsync used to be "always gratis" but now it is
  395. only "often gratis" because imapsync is sold by its author,
  396. a good way to maintain and support free open public
  397. software over decades.
  398. =head1 BUGS AND LIMITATIONS
  399. See https://imapsync.lamiral.info/FAQ.d/FAQ.Reporting_Bugs.txt
  400. =head1 IMAP SERVERS supported
  401. See https://imapsync.lamiral.info/S/imapservers.shtml
  402. =head1 HUGE MIGRATION
  403. Pay special attention to options
  404. --subscribed
  405. --subscribe
  406. --delete1
  407. --delete1emptyfolders
  408. --delete2
  409. --delete2folders
  410. --maxage
  411. --minage
  412. --maxsize
  413. --useuid
  414. --usecache
  415. If you have many mailboxes to migrate think about a little
  416. shell program. Write a file called file.txt (for example)
  417. containing users and passwords.
  418. The separator used in this example is ';'
  419. The file.txt file contains:
  420. user001_1;password001_1;user001_2;password001_2
  421. user002_1;password002_1;user002_2;password002_2
  422. user003_1;password003_1;user003_2;password003_2
  423. user004_1;password004_1;user004_2;password004_2
  424. user005_1;password005_1;user005_2;password005_2
  425. ...
  426. On Unix the shell program can be:
  427. { while IFS=';' read u1 p1 u2 p2; do
  428. imapsync --host1 imap.side1.org --user1 "$u1" --password1 "$p1" \
  429. --host2 imap.side2.org --user2 "$u2" --password2 "$p2" ...
  430. done ; } < file.txt
  431. On Windows the batch program can be:
  432. FOR /F "tokens=1,2,3,4 delims=; eol=#" %%G IN (file.txt) DO imapsync ^
  433. --host1 imap.side1.org --user1 %%G --password1 %%H ^
  434. --host2 imap.side2.org --user2 %%I --password2 %%J ...
  435. The ... have to be replaced by nothing or any imapsync option.
  436. Welcome in shell or batch programming !
  437. You will find already written scripts at
  438. https://imapsync.lamiral.info/examples/
  439. =head1 INSTALL
  440. Imapsync works under any Unix with perl.
  441. Imapsync works under most Windows (2000, XP, Vista, Seven, Eight, Ten
  442. and all Server releases 2000, 2003, 2008 and R2, 2012 and R2)
  443. as a standalone binary software called imapsync.exe,
  444. usually launched from a batch file in order to avoid always typing
  445. the options.
  446. Imapsync works under OS X as a standalone binary
  447. software called imapsync_bin_Darwin
  448. Purchase latest imapsync at
  449. https://imapsync.lamiral.info/
  450. You'll receive a link to a compressed tarball called imapsync-x.xx.tgz
  451. where x.xx is the version number. Untar the tarball where
  452. you want (on Unix):
  453. tar xzvf imapsync-x.xx.tgz
  454. Go into the directory imapsync-x.xx and read the INSTALL file.
  455. As mentioned at https://imapsync.lamiral.info/#install
  456. the INSTALL file can also be found at
  457. https://imapsync.lamiral.info/INSTALL.d/INSTALL.ANY.txt
  458. It is now split in several files for each system
  459. https://imapsync.lamiral.info/INSTALL.d/
  460. =head1 CONFIGURATION
  461. There is no specific configuration file for imapsync,
  462. everything is specified by the command line parameters
  463. and the default behavior.
  464. =head1 HACKING
  465. Feel free to hack imapsync as the NOLIMIT license permits it.
  466. =head1 SIMILAR SOFTWARE
  467. See also https://imapsync.lamiral.info/S/external.shtml
  468. for a better up to date list.
  469. imap_tools : https://github.com/andrewnimmo/rick-sanders-imap-tools
  470. offlineimap : https://github.com/nicolas33/offlineimap
  471. Doveadm-Sync : http://wiki2.dovecot.org/Tools/Doveadm/Sync
  472. ( Dovecot sync tool )
  473. mbsync : http://isync.sourceforge.net/
  474. mailsync : http://mailsync.sourceforge.net/
  475. mailutil : http://www.washington.edu/imap/
  476. part of the UW IMAP tookit.
  477. imaprepl : http://www.bl0rg.net/software/
  478. http://freecode.com/projects/imap-repl/
  479. imapcopy : http://www.ardiehl.de/imapcopy/
  480. migrationtool : http://sourceforge.net/projects/migrationtool/
  481. imapmigrate : http://sourceforge.net/projects/cyrus-utils/
  482. wonko_imapsync: http://wonko.com/article/554
  483. see also file W/tools/wonko_ruby_imapsync
  484. exchange-away : http://exchange-away.sourceforge.net/
  485. pop2imap : http://www.linux-france.org/prj/pop2imap/
  486. Feedback (good or bad) will often be welcome.
  487. =head1 HISTORY
  488. I wrote imapsync because an enterprise (basystemes) paid me to install
  489. a new imap server without losing huge old mailboxes located in a far
  490. away remote imap server, accessible by a low-bandwidth often broken link.
  491. The tool imapcp (written in python) could not help me because I had to verify
  492. every mailbox was well transferred, and then delete it after a good
  493. transfer. Imapsync started its life as a patch of the copy_folder.pl
  494. script. The script copy_folder.pl comes from the Mail-IMAPClient-2.1.3 perl
  495. module tarball source (more precisely in the examples/ directory of the
  496. Mail-IMAPClient tarball). So many happened since then that I wonder
  497. if it remains any lines of the original copy_folder.pl in imapsync source code.
  498. =cut
  499. # use pragmas
  500. use strict ;
  501. use warnings ;
  502. use Carp ;
  503. use Data::Dumper ;
  504. use Digest::HMAC_SHA1 qw( hmac_sha1 hmac_sha1_hex ) ;
  505. use Digest::MD5 qw( md5 md5_hex md5_base64 ) ;
  506. use English qw( -no_match_vars ) ;
  507. use Errno qw(EAGAIN EPIPE ECONNRESET) ;
  508. use Fcntl ;
  509. use File::Basename ;
  510. use File::Copy::Recursive ;
  511. use File::Glob qw( :glob ) ;
  512. use File::Path qw( mkpath rmtree ) ;
  513. use File::Spec ;
  514. use File::stat ;
  515. use Getopt::Long ( ) ;
  516. use IO::File ;
  517. use IO::Socket qw( :crlf SOL_SOCKET SO_KEEPALIVE ) ;
  518. use IO::Socket::INET6 ;
  519. use IO::Socket::SSL ;
  520. use IO::Tee ;
  521. use IPC::Open3 'open3' ;
  522. use Mail::IMAPClient 3.30 ;
  523. use MIME::Base64 ;
  524. use Pod::Usage qw(pod2usage) ;
  525. use POSIX qw(uname SIGALRM) ;
  526. use Sys::Hostname ;
  527. use Term::ReadKey ;
  528. use Test::More ;
  529. use Time::HiRes qw( time sleep ) ;
  530. use Time::Local ;
  531. use Unicode::String ;
  532. use Cwd ;
  533. use Readonly ;
  534. use Sys::MemInfo ;
  535. use Regexp::Common ;
  536. local $OUTPUT_AUTOFLUSH = 1 ;
  537. # constants
  538. # Let us do like sysexits.h
  539. # /usr/include/sysexits.h
  540. Readonly my $EX_OK => 0 ; #/* successful termination */
  541. Readonly my $EX_USAGE => 64 ; #/* command line usage error */
  542. #Readonly my $EX_DATAERR => 65 ; #/* data format error */
  543. Readonly my $EX_NOINPUT => 66 ; #/* cannot open input */
  544. #Readonly my $EX_NOUSER => 67 ; #/* addressee unknown */
  545. #Readonly my $EX_NOHOST => 68 ; #/* host name unknown */
  546. Readonly my $EX_UNAVAILABLE => 69 ; #/* service unavailable */
  547. Readonly my $EX_SOFTWARE => 70 ; #/* internal software error */
  548. #Readonly my $EX_OSERR => 71 ; #/* system error (e.g., can't fork) */
  549. #Readonly my $EX_OSFILE => 72 ; #/* critical OS file missing */
  550. #Readonly my $EX_CANTCREAT => 73 ; #/* can't create (user) output file */
  551. #Readonly my $EX_IOERR => 74 ; #/* input/output error */
  552. #Readonly my $EX_TEMPFAIL => 75 ; #/* temp failure; user is invited to retry */
  553. #Readonly my $EX_PROTOCOL => 76 ; #/* remote error in protocol */
  554. #Readonly my $EX_NOPERM => 77 ; #/* permission denied */
  555. #Readonly my $EX_CONFIG => 78 ; #/* configuration error */
  556. # Mine
  557. Readonly my $EXIT_BY_SIGNAL => 6 ;
  558. Readonly my $EXIT_PID_FILE_ERROR => 8 ;
  559. Readonly my $EXIT_WITH_ERRORS => 111 ;
  560. Readonly my $EXIT_WITH_ERRORS_MAX => 112 ;
  561. Readonly my $EXIT_UNKNOWN => 126 ;
  562. Readonly my $EXIT_TESTS_FAILED => 254 ; # Like Test::More API
  563. Readonly my $DEFAULT_LOGDIR => 'LOG_imapsync' ;
  564. Readonly my $ERRORS_MAX => 50 ; # exit after 50 errors.
  565. Readonly my $ERRORS_MAX_CGI => 20 ; # exit after 20 errors in CGI context.
  566. Readonly my $INTERVAL_TO_EXIT => 2 ; # interval max to exit instead of reconnect
  567. Readonly my $SPLIT => 100 ; # By default, 100 at a time, not more.
  568. Readonly my $SPLIT_FACTOR => 10 ; # init_imap() calls Maxcommandlength( $SPLIT_FACTOR * $split )
  569. # which means default Maxcommandlength is 10*100 = 1000 characters ;
  570. Readonly my $IMAP_PORT => 143 ; # Well know port for IMAP
  571. Readonly my $IMAP_SSL_PORT => 993 ; # Well know port for IMAP over SSL
  572. Readonly my $LAST => -1 ;
  573. Readonly my $MINUS_ONE => -1 ;
  574. Readonly my $MINUS_TWO => -2 ;
  575. Readonly my $RELEASE_NUMBER_EXAMPLE_1 => '1.351' ;
  576. Readonly my $RELEASE_NUMBER_EXAMPLE_2 => 42.4242 ;
  577. Readonly my $TCP_PING_TIMEOUT => 5 ;
  578. Readonly my $DEFAULT_TIMEOUT => 120 ;
  579. Readonly my $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND => 3 ;
  580. Readonly my $DEFAULT_UIDNEXT => 999_999 ;
  581. Readonly my $DEFAULT_BUFFER_SIZE => 4096 ;
  582. Readonly my $MAX_SLEEP => 2 ; # 2 seconds max for limiting too long sleeps from --maxbytespersecond and --maxmessagespersecond
  583. Readonly my $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12 => 3600 ;
  584. Readonly my $PERMISSION_FILTER => 7777 ;
  585. Readonly my $KIBI => 1024 ;
  586. Readonly my $NUMBER_10 => 10 ;
  587. Readonly my $NUMBER_42 => 42 ;
  588. Readonly my $NUMBER_100 => 100 ;
  589. Readonly my $NUMBER_200 => 200 ;
  590. Readonly my $NUMBER_300 => 300 ;
  591. Readonly my $NUMBER_20_000 => 20_000 ;
  592. Readonly my $QUOTA_PERCENT_LIMIT => 90 ;
  593. Readonly my $NUMBER_104_857_600 => 104_857_600 ;
  594. Readonly my $SIZE_MAX_STR => 64 ;
  595. Readonly my $NB_SECONDS_IN_A_DAY => 86_400 ;
  596. Readonly my $STD_CHAR_PER_LINE => 80 ;
  597. Readonly my $TRUE => 1 ;
  598. Readonly my $FALSE => 0 ;
  599. Readonly my $LAST_RESSORT_SEPARATOR => q{/} ;
  600. Readonly my $CGI_TMPDIR_TOP => '/var/tmp/imapsync_cgi' ;
  601. Readonly my $CGI_HASHFILE => '/var/tmp/imapsync_hash' ;
  602. Readonly my $UMASK_PARANO => '0077' ;
  603. Readonly my $STR_use_releasecheck => q{Check if a new imapsync release is available by adding --releasecheck} ;
  604. # global variables
  605. # Currently working to finish with only $sync
  606. # Not finished yet...
  607. my(
  608. $sync,
  609. $debug, $debugimap, $debugimap1, $debugimap2, $debugcontent, $debugflags,
  610. $debuglist, $debugdev, $debugmaxlinelength, $debugcgi,
  611. $domain1, $domain2,
  612. $passfile1, $passfile2,
  613. @include, @exclude, @folderrec,
  614. @folderfirst, @folderlast,
  615. $prefix1, $prefix2,
  616. $subfolder2,
  617. @regextrans2, @regexmess, @regexflag, @skipmess, @pipemess, $pipemesscheck,
  618. $flagscase, $filterflags, $syncflagsaftercopy,
  619. $sep1, $sep2,
  620. $syncinternaldates,
  621. $idatefromheader,
  622. $syncacls,
  623. $fastio1, $fastio2,
  624. $maxsize, $minsize, $maxage, $minage,
  625. $exitwhenover,
  626. $search, $search1, $search2,
  627. $skipheader, @useheader,
  628. $skipsize, $allowsizemismatch, $foldersizes, $foldersizesatend, $buffersize,
  629. $delete1, $delete2, $delete2duplicates,
  630. $expunge1, $expunge2, $uidexpunge2,
  631. $justfoldersizes,
  632. $authmd5, $authmd51, $authmd52,
  633. $subscribed, $subscribe, $subscribeall,
  634. $help,
  635. $justfolders, $justbanner,
  636. $fast,
  637. $total_bytes_skipped,
  638. $total_bytes_error,
  639. $nb_msg_skipped,
  640. $nb_msg_skipped_dry_mode,
  641. $h1_nb_msg_duplicate,
  642. $h2_nb_msg_duplicate,
  643. $h1_nb_msg_noheader,
  644. $h2_nb_msg_noheader,
  645. $h1_total_bytes_duplicate,
  646. $h2_total_bytes_duplicate,
  647. $h1_nb_msg_deleted,
  648. $h2_nb_msg_deleted,
  649. $h1_bytes_processed,
  650. $h1_nb_msg_processed,
  651. $h1_nb_msg_start, $h1_bytes_start,
  652. $h2_nb_msg_start, $h2_bytes_start,
  653. $h1_nb_msg_end, $h1_bytes_end,
  654. $h2_nb_msg_end, $h2_bytes_end,
  655. $timeout,
  656. $timestart_int,
  657. $timebefore,
  658. $uid1, $uid2,
  659. $authuser1, $authuser2,
  660. $proxyauth1, $proxyauth2,
  661. $authmech1, $authmech2,
  662. $split1, $split2,
  663. $reconnectretry1, $reconnectretry2,
  664. $max_msg_size_in_bytes,
  665. $modulesversion,
  666. $delete2folders, $delete2foldersonly, $delete2foldersbutnot,
  667. $usecache, $debugcache, $cacheaftercopy,
  668. $wholeheaderifneeded, %h1_msgs_copy_by_uid, $useuid, $h2_uidguess,
  669. %h1, %h2,
  670. $checkmessageexists,
  671. $expungeaftereach,
  672. $fixslash2,
  673. $messageidnodomain,
  674. $fixInboxINBOX,
  675. $maxlinelength, $maxlinelengthcmd,
  676. $minmaxlinelength,
  677. $uidnext_default,
  678. $fixcolonbug,
  679. $create_folder_old,
  680. $skipcrossduplicates, $debugcrossduplicates,
  681. $disarmreadreceipts,
  682. $mixfolders, $skipemptyfolders,
  683. $fetch_hash_set,
  684. );
  685. # main program
  686. # global variables initialization
  687. # Currently removing all global variables except $sync
  688. # passing each of them under $sync->{variable_name}
  689. $sync->{timestart} = time ; # Is a float because of use Time::HiRres
  690. $sync->{rcs} = q{$Id: imapsync,v 1.882 2018/05/05 21:10:43 gilles Exp gilles $} ;
  691. $sync->{ memory_consumption_at_start } = memory_consumption( ) || 0 ;
  692. my @loadavg = loadavg( ) ;
  693. $sync->{cpu_number} = cpu_number( ) ;
  694. $sync->{loaddelay} = load_and_delay( $sync->{cpu_number}, @loadavg ) ;
  695. $sync->{loadavg} = join( q{ }, $loadavg[ 0 ] )
  696. . " on $sync->{cpu_number} cores and "
  697. . ram_memory_info( ) ;
  698. $sync->{total_bytes_transferred} = 0 ;
  699. $total_bytes_skipped = 0;
  700. $total_bytes_error = 0;
  701. $sync->{nb_msg_transferred} = 0;
  702. $nb_msg_skipped = $nb_msg_skipped_dry_mode = 0;
  703. $h1_nb_msg_deleted = $h2_nb_msg_deleted = 0;
  704. $h1_nb_msg_duplicate = $h2_nb_msg_duplicate = 0;
  705. $h1_nb_msg_noheader = $h2_nb_msg_noheader = 0;
  706. $h1_total_bytes_duplicate = $h2_total_bytes_duplicate = 0;
  707. $h1_nb_msg_start = $h1_bytes_start = 0 ;
  708. $h2_nb_msg_start = $h2_bytes_start = 0 ;
  709. $h1_nb_msg_processed = $h1_bytes_processed = 0 ;
  710. #$h1_nb_msg_end = $h1_bytes_end = 0 ;
  711. #$h2_nb_msg_end = $h2_bytes_end = 0 ;
  712. $sync->{nb_errors} = 0;
  713. $max_msg_size_in_bytes = 0;
  714. my %month_abrev = (
  715. Jan => '00',
  716. Feb => '01',
  717. Mar => '02',
  718. Apr => '03',
  719. May => '04',
  720. Jun => '05',
  721. Jul => '06',
  722. Aug => '07',
  723. Sep => '08',
  724. Oct => '09',
  725. Nov => '10',
  726. Dec => '11',
  727. );
  728. my $cgidir ;
  729. # Just create a CGI object if under cgi context only.
  730. # Needed for the get_options() call
  731. cgibegin( $sync ) ;
  732. # In cgi context, printing must start by the header so we delay other prints by using output() storage
  733. my $options_good = get_options( $sync, @ARGV ) ;
  734. # Is it The first myprint?
  735. docker_context( $sync ) ;
  736. cgibuildheader( $sync ) ;
  737. myprint( output( $sync ) ) ;
  738. output_reset_with( $sync ) ;
  739. # Can break here if load is too heavy
  740. cgiload( $sync ) ;
  741. # don't go on if options are not all known.
  742. if ( ! defined $options_good ) { exit $EX_USAGE ; }
  743. # If you want releasecheck not to be done by default (like the github maintainer),
  744. # then just uncomment the first "$sync->{releasecheck} =" line, the line ending with "0 ;",
  745. # the second line (ending with "1 ;") can then stay active or be commented,
  746. # the result will be the same: no releasecheck by default (because 0 is then the defined value).
  747. $sync->{releasecheck} = defined $sync->{releasecheck} ? $sync->{releasecheck} : 0 ;
  748. #$sync->{releasecheck} = defined $sync->{releasecheck} ? $sync->{releasecheck} : 1 ;
  749. # just the version
  750. if ( $sync->{ version } ) {
  751. myprint( imapsync_version( $sync ), "\n" ) ;
  752. exit 0 ;
  753. }
  754. $sync->{debugenv} and printenv( $sync ) ; # if option --debugenv
  755. load_modules( ) ;
  756. # after_get_options call usage and exit if --help or options were not well got
  757. after_get_options( $sync, $options_good ) ;
  758. # Under CGI environment, fix caveat emptor potential issues
  759. cgisetcontext( $sync ) ;
  760. easyany( $sync ) ;
  761. $sync->{ tmpdir } ||= File::Spec->tmpdir( ) ;
  762. # Unit tests
  763. testsexit( $sync ) ;
  764. # init live varaiables
  765. testslive( $sync ) if ( $sync->{testslive} ) ;
  766. testslive6( $sync ) if ( $sync->{testslive6} ) ;
  767. #
  768. $sync->{pidfile} = defined $sync->{pidfile} ? $sync->{pidfile} : $sync->{ tmpdir } . '/imapsync.pid' ;
  769. $sync->{pidfilelocking} = defined $sync->{pidfilelocking} ? $sync->{pidfilelocking} : 0 ;
  770. # old abort place
  771. @{ $sync->{ sigexit } } = ( defined( $sync->{ sigexit } ) ) ? @{ $sync->{ sigexit } } : ( 'QUIT', 'TERM' ) ;
  772. @{ $sync->{ sigreconnect } } = ( defined( $sync->{ sigreconnect } ) ) ? @{ $sync->{ sigreconnect } } : ( 'INT' ) ;
  773. sig_install( $sync, \&catch_exit, @{ $sync->{ sigexit } } ) ;
  774. sig_install( $sync, \&catch_reconnect, @{ $sync->{ sigreconnect } } ) ;
  775. # --sigignore can override sigexit and sigreconnect (for the same signals only)
  776. sig_install( $sync, \&catch_ignore, @{ $sync->{ sigignore } } ) ;
  777. sig_install( $sync, \&toggle_sleep, 'USR1' ) ;
  778. $sync->{log} = defined $sync->{log} ? $sync->{log} : 1 ;
  779. $sync->{errorsdump} = defined $sync->{errorsdump} ? $sync->{errorsdump} : 1 ;
  780. $sync->{errorsmax} = defined $sync->{errorsmax} ? $sync->{errorsmax} : $ERRORS_MAX ;
  781. if ( $sync->{log} ) {
  782. setlogfile( $sync ) ;
  783. teelaunch( $sync ) ;
  784. # now $sync->{tee} is a filehandle to STDOUT and the logfile
  785. }
  786. # STDERR goes to the same place: LOG and STDOUT (if logging is on)
  787. $sync->{tee} and local *STDERR = *${$sync->{tee}}{IO} ;
  788. $timestart_int = int( $sync->{timestart} ) ;
  789. $timebefore = $sync->{timestart} ;
  790. my $timestart_str = localtime( $sync->{timestart} ) ;
  791. myprint( localhost_info( $sync ), "\n" ) ;
  792. myprint( "Transfer started at $timestart_str\n" ) ;
  793. myprint( "PID is $PROCESS_ID\n" ) ;
  794. myprint( "Log file is $sync->{logfile} ( to change it, use --logfile path ; or use --nolog to turn off logging )\n" ) if ( $sync->{log} ) ;
  795. myprint( "Load is " . ( join( q{ }, loadavg( ) ) || 'unknown' ), " on $sync->{cpu_number} cores\n" ) ;
  796. #myprintf( "Memory consumption so far: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  797. myprint( 'Current directory is ' . getcwd( ) . "\n" ) ;
  798. myprint( 'Real user id is ' . getpwuid_any_os( $REAL_USER_ID ) . " (uid $REAL_USER_ID)\n" ) ;
  799. myprint( 'Effective user id is ' . getpwuid_any_os( $EFFECTIVE_USER_ID ). " (euid $EFFECTIVE_USER_ID)\n" ) ;
  800. $modulesversion = defined $modulesversion ? $modulesversion : 1 ;
  801. my $warn_release = ( $sync->{releasecheck} ) ? check_last_release( ) : $STR_use_releasecheck ;
  802. $wholeheaderifneeded = defined $wholeheaderifneeded ? $wholeheaderifneeded : 1;
  803. # Activate --usecache if --useuid is set and no --nousecache
  804. $usecache = 1 if ( $useuid and ( ! defined $usecache ) ) ;
  805. $cacheaftercopy = 1 if ( $usecache and ( ! defined $cacheaftercopy ) ) ;
  806. $sync->{ checkselectable } = defined $sync->{ checkselectable } ? $sync->{ checkselectable } : 1 ;
  807. $sync->{ checkfoldersexist } = defined $sync->{ checkfoldersexist } ? $sync->{ checkfoldersexist } : 1 ;
  808. $checkmessageexists = defined $checkmessageexists ? $checkmessageexists : 0 ;
  809. $expungeaftereach = defined $expungeaftereach ? $expungeaftereach : 1 ;
  810. # abletosearch is on by default
  811. $sync->{abletosearch} = defined $sync->{abletosearch} ? $sync->{abletosearch} : 1 ;
  812. $sync->{abletosearch1} = defined $sync->{abletosearch1} ? $sync->{abletosearch1} : $sync->{abletosearch} ;
  813. $sync->{abletosearch2} = defined $sync->{abletosearch2} ? $sync->{abletosearch2} : $sync->{abletosearch} ;
  814. $checkmessageexists = 0 if ( not $sync->{abletosearch1} ) ;
  815. $sync->{showpasswords} = defined $sync->{showpasswords} ? $sync->{showpasswords} : 0 ;
  816. $fixslash2 = defined $fixslash2 ? $fixslash2 : 1 ;
  817. $fixInboxINBOX = defined $fixInboxINBOX ? $fixInboxINBOX : 1 ;
  818. $create_folder_old = defined $create_folder_old ? $create_folder_old : 0 ;
  819. $mixfolders = defined $mixfolders ? $mixfolders : 1 ;
  820. $sync->{automap} = defined $sync->{automap} ? $sync->{automap} : 0 ;
  821. $delete2duplicates = 1 if ( $delete2 and ( ! defined $delete2duplicates ) ) ;
  822. $sync->{maxmessagespersecond} = defined $sync->{maxmessagespersecond} ? $sync->{maxmessagespersecond} : 0 ;
  823. $sync->{maxbytespersecond} = defined $sync->{maxbytespersecond} ? $sync->{maxbytespersecond} : 0 ;
  824. $sync->{sslcheck} = defined $sync->{sslcheck} ? $sync->{sslcheck} : 1 ;
  825. myprint( banner_imapsync( @ARGV ) ) ;
  826. myprint( "Temp directory is $sync->{ tmpdir } ( to change it use --tmpdir dirpath )\n" ) ;
  827. myprint( output( $sync ) ) ;
  828. do_valid_directory( $sync->{ tmpdir } ) || croak "Error creating tmpdir $sync->{ tmpdir } : $OS_ERROR" ;
  829. remove_pidfile_not_running( $sync->{pidfile} ) ;
  830. if ( ! write_pidfile( $sync ) ) {
  831. exit $EXIT_PID_FILE_ERROR ;
  832. }
  833. # simulong is just a loop printing some lines for xx seconds with option "--simulong xx".
  834. if ( $sync->{simulong} ) { simulong( $sync->{simulong} ) ; }
  835. # New place to abort
  836. if ( $sync->{abort} ) {
  837. abort( $sync ) ;
  838. }
  839. $fixcolonbug = defined $fixcolonbug ? $fixcolonbug : 1 ;
  840. if ( $usecache and $fixcolonbug ) { tmpdir_fix_colon_bug( $sync ) } ;
  841. $modulesversion and myprint( "Modules version list:\n", modulesversion(), "( use --no-modulesversion to turn off printing this Perl modules list )\n" ) ;
  842. check_lib_version( ) or
  843. croak "imapsync needs perl lib Mail::IMAPClient release 3.30 or superior.\n";
  844. exit_clean( $sync, $EX_OK ) if ( $justbanner ) ;
  845. # turn on RFC standard flags correction like \SEEN -> \Seen
  846. $flagscase = defined $flagscase ? $flagscase : 1 ;
  847. # Use PERMANENTFLAGS if available
  848. $filterflags = defined $filterflags ? $filterflags : 1 ;
  849. # sync flags just after an APPEND, some servers ignore the flags given in the APPEND
  850. # like MailEnable IMAP server.
  851. # Off by default since it takes time.
  852. $syncflagsaftercopy = defined $syncflagsaftercopy ? $syncflagsaftercopy : 0 ;
  853. # update flags on host2 for already transferred messages
  854. $sync->{resyncflags} = defined $sync->{resyncflags} ? $sync->{resyncflags} : 1 ;
  855. if ( $sync->{resyncflags} ) {
  856. myprint( "Info: will resync flags for already transferred messages. Use --noresyncflags to not resync flags.\n" ) ;
  857. }else{
  858. myprint( "Info: will not resync flags for already transferred messages. Use --resyncflags to resync flags.\n" ) ;
  859. }
  860. sslcheck( $sync ) ;
  861. $split1 ||= $SPLIT ;
  862. $split2 ||= $SPLIT ;
  863. $sync->{host1} || missing_option( '--host1' ) ;
  864. $sync->{port1} ||= ( $sync->{ssl1} ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  865. $sync->{host2} || missing_option( '--host2' ) ;
  866. $sync->{port2} ||= ( $sync->{ssl2} ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  867. $debugimap1 = $debugimap2 = 1 if ( $debugimap ) ;
  868. $debug = 1 if ( $debugimap1 or $debugimap2 ) ;
  869. # By default, don't take size to compare
  870. $skipsize = (defined $skipsize) ? $skipsize : 1;
  871. $uid1 = defined $uid1 ? $uid1 : 1;
  872. $uid2 = defined $uid2 ? $uid2 : 1;
  873. $subscribe = defined $subscribe ? $subscribe : 1;
  874. # Allow size mismatch by default
  875. $allowsizemismatch = defined $allowsizemismatch ? $allowsizemismatch : 1;
  876. if ( defined $delete2foldersbutnot or defined $delete2foldersonly ) {
  877. $delete2folders = 1 ;
  878. }
  879. my $SSL_VERIFY_POLICY ;
  880. my %SSL_VERIFY_STR ;
  881. Readonly $SSL_VERIFY_POLICY => IO::Socket::SSL::SSL_VERIFY_NONE( ) ;
  882. Readonly %SSL_VERIFY_STR => (
  883. IO::Socket::SSL::SSL_VERIFY_NONE( ) => 'SSL_VERIFY_NONE, ie, do not check the certificate server.' ,
  884. IO::Socket::SSL::SSL_VERIFY_PEER( ) => 'SSL_VERIFY_PEER, ie, check the certificate server' ,
  885. ) ;
  886. $IO::Socket::SSL::DEBUG = $sync->{debugssl} || 1 ;
  887. if ( $sync->{ssl1} or $sync->{ssl2} or $sync->{tls1} or $sync->{tls2}) {
  888. 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" ) ;
  889. }
  890. if ( $sync->{ssl1} ) {
  891. myprint( qq{Host1: SSL default mode is like --sslargs1 "SSL_verify_mode=$SSL_VERIFY_POLICY", meaning for host1 $SSL_VERIFY_STR{$SSL_VERIFY_POLICY}\n} ) ;
  892. myprint( 'Host1: Use --sslargs1 SSL_verify_mode=' . IO::Socket::SSL::SSL_VERIFY_PEER( ) . " to have $SSL_VERIFY_STR{IO::Socket::SSL::SSL_VERIFY_PEER( )} of host1\n" ) ;
  893. }
  894. if ( $sync->{ssl2} ) {
  895. myprint( qq{Host2: SSL default mode is like --sslargs2 "SSL_verify_mode=$SSL_VERIFY_POLICY", meaning for host2 $SSL_VERIFY_STR{$SSL_VERIFY_POLICY}\n} ) ;
  896. myprint( 'Host2: Use --sslargs2 SSL_verify_mode=' . IO::Socket::SSL::SSL_VERIFY_PEER( ) . " to have $SSL_VERIFY_STR{IO::Socket::SSL::SSL_VERIFY_PEER( )} of host2\n" ) ;
  897. }
  898. if ( $sync->{justconnect} ) {
  899. justconnect( ) ;
  900. myprint( debugmemory( $sync, " after justconnect() call" ) ) ;
  901. exit_clean( $sync, $EX_OK ) ;
  902. }
  903. $sync->{user1} || missing_option( '--user1' ) ;
  904. $sync->{user2} || missing_option( '--user2' ) ;
  905. $syncinternaldates = defined $syncinternaldates ? $syncinternaldates : 1;
  906. # Turn on expunge if there is not explicit option --noexpunge1 and option
  907. # --delete1 is given.
  908. # Done because --delete1 --noexpunge1 is very dangerous on the second run:
  909. # the Deleted flag is then synced to all previously transferred messages.
  910. # So --delete1 implies --expunge1 is a better usability default behavior.
  911. if ( $delete1 ) {
  912. if ( ! defined $expunge1 ) {
  913. myprint( "Info: turning on --expunge1 because --delete1 --noexpunge1 is very dangerous on the second run.\n" ) ;
  914. $expunge1 = 1 ;
  915. }
  916. myprint( "Info: if expunging after each message slows down too much the sync then use --noexpungeaftereach to speed up\n" ) ;
  917. }
  918. if ( $uidexpunge2 and not Mail::IMAPClient->can( 'uidexpunge' ) ) {
  919. myprint( "Failure: uidexpunge not supported (IMAPClient release < 3.17), use --expunge2 instead\n" ) ;
  920. exit_clean( $sync, $EX_SOFTWARE ) ;
  921. }
  922. if ( ( $delete2 or $delete2duplicates ) and not defined $uidexpunge2 ) {
  923. if ( Mail::IMAPClient->can( 'uidexpunge' ) ) {
  924. myprint( "Info: will act as --uidexpunge2\n" ) ;
  925. $uidexpunge2 = 1 ;
  926. }elsif ( not defined $expunge2 ) {
  927. myprint( "Info: will act as --expunge2 (no uidexpunge support)\n" ) ;
  928. $expunge2 = 1 ;
  929. }
  930. }
  931. if ( $delete1 and $delete2 ) {
  932. myprint( "Warning: using --delete1 and --delete2 together is almost always a bad idea, exiting imapsync\n" ) ;
  933. exit_clean( $sync, $EX_USAGE ) ;
  934. }
  935. if ( $idatefromheader ) {
  936. myprint( 'Turned ON idatefromheader, ',
  937. "will set the internal dates on host2 from the 'Date:' header line.\n" ) ;
  938. $syncinternaldates = 0 ;
  939. }
  940. if ( $syncinternaldates ) {
  941. myprint( 'Info: turned ON syncinternaldates, ',
  942. "will set the internal dates (arrival dates) on host2 same as host1.\n" ) ;
  943. }else{
  944. myprint( "Info: turned OFF syncinternaldates\n" ) ;
  945. }
  946. if ( defined $authmd5 and $authmd5 ) {
  947. $authmd51 = 1 ;
  948. $authmd52 = 1 ;
  949. }
  950. if ( defined $authmd51 and $authmd51 ) {
  951. $authmech1 ||= 'CRAM-MD5';
  952. }
  953. else{
  954. $authmech1 ||= $authuser1 ? 'PLAIN' : 'LOGIN';
  955. }
  956. if ( defined $authmd52 and $authmd52 ) {
  957. $authmech2 ||= 'CRAM-MD5';
  958. }
  959. else{
  960. $authmech2 ||= $authuser2 ? 'PLAIN' : 'LOGIN';
  961. }
  962. $authmech1 = uc $authmech1;
  963. $authmech2 = uc $authmech2;
  964. if (defined $proxyauth1 && !$authuser1) {
  965. missing_option( 'With --proxyauth1, --authuser1' ) ;
  966. }
  967. if (defined $proxyauth2 && !$authuser2) {
  968. missing_option( 'With --proxyauth2, --authuser2' ) ;
  969. }
  970. $authuser1 ||= $sync->{user1};
  971. $authuser2 ||= $sync->{user2};
  972. myprint( "Host1: will try to use $authmech1 authentication on host1\n") ;
  973. myprint( "Host2: will try to use $authmech2 authentication on host2\n") ;
  974. $timeout = defined $timeout ? $timeout : $DEFAULT_TIMEOUT ;
  975. $sync->{h1}->{timeout} = defined $sync->{h1}->{timeout} ? $sync->{h1}->{timeout} : $timeout ;
  976. myprint( "Host1: imap connection timeout is $sync->{h1}->{timeout} seconds\n") ;
  977. $sync->{h2}->{timeout} = defined $sync->{h2}->{timeout} ? $sync->{h2}->{timeout} : $timeout ;
  978. myprint( "Host2: imap connection timeout is $sync->{h2}->{timeout} seconds\n" ) ;
  979. $syncacls = defined $syncacls ? $syncacls : 0 ;
  980. # No folders sizes if --justfolders, unless really wanted.
  981. if ( $justfolders and not defined $foldersizes ) { $foldersizes = 0 ; }
  982. $foldersizes = ( defined $foldersizes ) ? $foldersizes : 1 ;
  983. $foldersizesatend = ( defined $foldersizesatend ) ? $foldersizesatend : $foldersizes ;
  984. $fastio1 = defined $fastio1 ? $fastio1 : 0 ;
  985. $fastio2 = defined $fastio2 ? $fastio2 : 0 ;
  986. $reconnectretry1 = defined $reconnectretry1 ? $reconnectretry1 : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  987. $reconnectretry2 = defined $reconnectretry2 ? $reconnectretry2 : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  988. # Since select_msgs() returns no messages when uidnext does not return something
  989. # then $uidnext_default is never used. So I have to remove it.
  990. $uidnext_default = $DEFAULT_UIDNEXT ;
  991. if ( ! @useheader ) { @useheader = qw( Message-Id Received ) ; }
  992. my %useheader ;
  993. # Make a hash %useheader of each --useheader 'key' in uppercase
  994. for ( @useheader ) { $useheader{ uc $_ } = undef } ;
  995. #myprint( Data::Dumper->Dump( [ \%useheader ] ) ) ;
  996. #exit ;
  997. myprint( "Host1: IMAP server [$sync->{host1}] port [$sync->{port1}] user [$sync->{user1}]\n" ) ;
  998. myprint( "Host2: IMAP server [$sync->{host2}] port [$sync->{port2}] user [$sync->{user2}]\n" ) ;
  999. get_password1( $sync ) ;
  1000. get_password2( $sync ) ;
  1001. $sync->{dry_message} = q{} ;
  1002. if( $sync->{dry} ) {
  1003. $sync->{dry_message} = "\t(not really since --dry mode)" ;
  1004. }
  1005. $search1 ||= $search if ( $search ) ;
  1006. $search2 ||= $search if ( $search ) ;
  1007. if ( $disarmreadreceipts ) {
  1008. push @regexmess, q{s{\A((?:[^\n]+\r\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims} ;
  1009. }
  1010. $pipemesscheck = ( defined $pipemesscheck ) ? $pipemesscheck : 1 ;
  1011. if ( @pipemess and $pipemesscheck ) {
  1012. myprint( 'Checking each --pipemess command, '
  1013. . join( q{, }, @pipemess )
  1014. . ", with an space string. ( Can avoid this check with --nopipemesscheck )\n" ) ;
  1015. my $string = pipemess( q{ }, @pipemess ) ;
  1016. # string undef means something was bad.
  1017. if ( not ( defined $string ) ) {
  1018. die_clean( "Error: one of --pipemess command is bad, check it\n" ) ;
  1019. }
  1020. myprint( "Ok with each --pipemess @pipemess\n" ) ;
  1021. }
  1022. if ( $maxlinelengthcmd ) {
  1023. myprint( "Checking --maxlinelengthcmd command, $maxlinelengthcmd, with an space string.\n" ) ;
  1024. my $string = pipemess( q{ }, $maxlinelengthcmd ) ;
  1025. # string undef means something was bad.
  1026. if ( not ( defined $string ) ) {
  1027. die_clean( "Error: --maxlinelengthcmd command is bad, check it\n" ) ;
  1028. }
  1029. myprint( "Ok with --maxlinelengthcmd $maxlinelengthcmd\n" ) ;
  1030. }
  1031. if ( @regexmess ) {
  1032. my $string = regexmess( q{ } ) ;
  1033. myprint( "Checking each --regexmess command with an space string.\n" ) ;
  1034. # string undef means one of the eval regex was bad.
  1035. if ( not ( defined $string ) ) {
  1036. die_clean( 'Error: one of --regexmess option is bad, check it' ) ;
  1037. }
  1038. myprint( "Ok with each --regexmess\n" ) ;
  1039. }
  1040. if ( @skipmess ) {
  1041. myprint( "Checking each --skipmess command with an space string.\n" ) ;
  1042. my $match = skipmess( q{ } ) ;
  1043. # match undef means one of the eval regex was bad.
  1044. if ( not ( defined $match ) ) {
  1045. die_clean( 'Error: one of --skipmess option is bad, check it' ) ;
  1046. }
  1047. myprint( "Ok with each --skipmess\n" ) ;
  1048. }
  1049. if ( @regexflag ) {
  1050. myprint( "Checking each --regexflag command with an space string.\n" ) ;
  1051. my $string = flags_regex( q{ } ) ;
  1052. # string undef means one of the eval regex was bad.
  1053. if ( not ( defined $string ) ) {
  1054. die_clean( 'Error: one of --regexflag option is bad, check it' ) ;
  1055. }
  1056. myprint( "Ok with each --regexflag\n" ) ;
  1057. }
  1058. $sync->{imap1} = my $imap1 = login_imap( $sync->{host1}, $sync->{port1}, $sync->{user1}, $domain1, $sync->{password1},
  1059. $debugimap1, $sync->{h1}->{timeout}, $fastio1, $sync->{ssl1}, $sync->{tls1},
  1060. $authmech1, $authuser1, $reconnectretry1,
  1061. $proxyauth1, $uid1, $split1, 'Host1', $sync->{h1}, $sync ) ;
  1062. $sync->{imap2} = my $imap2 = login_imap( $sync->{host2}, $sync->{port2}, $sync->{user2}, $domain2, $sync->{password2},
  1063. $debugimap2, $sync->{h2}->{timeout}, $fastio2, $sync->{ssl2}, $sync->{tls2},
  1064. $authmech2, $authuser2, $reconnectretry2,
  1065. $proxyauth2, $uid2, $split2, 'Host2', $sync->{h2}, $sync ) ;
  1066. $debug and myprint( 'Host1 Buffer I/O: ', $imap1->Buffer(), "\n" ) ;
  1067. $debug and myprint( 'Host2 Buffer I/O: ', $imap2->Buffer(), "\n" ) ;
  1068. if ( ! $imap1->IsAuthenticated( ) ) { die_clean( 'Not authenticated on host1' ) ; }
  1069. myprint( "Host1: state Authenticated\n" ) ;
  1070. if ( ! $imap2->IsAuthenticated( ) ) { die_clean( 'Not authenticated on host2' ) ; }
  1071. myprint( "Host2: state Authenticated\n" ) ;
  1072. myprint( 'Host1 capability once authenticated: ', join(q{ }, @{ $imap1->capability() || [] }), "\n" ) ;
  1073. myprint( 'Host2 capability once authenticated: ', join(q{ }, @{ $imap2->capability() || [] }), "\n" ) ;
  1074. # ID on by default since 1.832
  1075. $sync->{id} = defined $sync->{id} ? $sync->{id} : 1 ;
  1076. imap_id_stuff( $sync ) ;
  1077. #quota( $imap1, 'h1', $sync ) ; # quota on host1 is useless and pollute host2 output.
  1078. quota( $imap2, 'h2', $sync ) ;
  1079. if ( $sync->{justlogin} ) {
  1080. $imap1->logout( ) ;
  1081. $imap2->logout( ) ;
  1082. exit_clean( $sync, $EX_OK ) ;
  1083. }
  1084. #
  1085. # Folder stuff
  1086. #
  1087. my (
  1088. @h1_folders_all , %h1_folders_all , @h1_folders_wanted , %requested_folder ,
  1089. %h1_subscribed_folder , %h2_subscribed_folder ,
  1090. @h2_folders_all , %h2_folders_all , %h2_folders_all_UPPER ,
  1091. @h2_folders_from_1_wanted , %h2_folders_from_1_wanted ,
  1092. %h2_folders_from_1_several ,
  1093. %h2_folders_from_1_all ,
  1094. ) ;
  1095. my $h1_folders_wanted_nb = 0 ;
  1096. my $h1_folders_wanted_ct = 0 ; # counter of folders done.
  1097. # All folders on host1 and host2
  1098. @h1_folders_all = sort $imap1->folders( ) ;
  1099. @h2_folders_all = sort $imap2->folders( ) ;
  1100. myprint( 'Host1: found ', scalar @h1_folders_all , " folders.\n" ) ;
  1101. myprint( 'Host2: found ', scalar @h2_folders_all , " folders.\n" ) ;
  1102. foreach my $f ( @h1_folders_all ) {
  1103. $h1_folders_all{ $f } = 1
  1104. }
  1105. foreach my $f ( @h2_folders_all ) {
  1106. $h2_folders_all{ $f } = 1 ;
  1107. $h2_folders_all_UPPER{ uc $f } = 1 ;
  1108. }
  1109. $sync->{h1_folders_all} = \%h1_folders_all ;
  1110. $sync->{h2_folders_all} = \%h2_folders_all ;
  1111. $sync->{h2_folders_all_UPPER} = \%h2_folders_all_UPPER ;
  1112. # Make a hash of subscribed folders in both servers.
  1113. for ( $imap1->subscribed( ) ) { $h1_subscribed_folder{ $_ } = 1 } ;
  1114. for ( $imap2->subscribed( ) ) { $h2_subscribed_folder{ $_ } = 1 } ;
  1115. if ( defined $subfolder2 ) {
  1116. unshift @regextrans2,
  1117. q(s,^$sync->{h2_prefix}(.*),$sync->{h2_prefix}${subfolder2}${h2_sep}$1,),
  1118. q(s,^INBOX$,$sync->{h2_prefix}${subfolder2}${h2_sep}INBOX,) ;
  1119. }
  1120. if ( $fixInboxINBOX and ( my $reg = fix_Inbox_INBOX_mapping( \%h1_folders_all, \%h2_folders_all ) ) ) {
  1121. push @regextrans2, $reg ;
  1122. }
  1123. if ( ( $sync->{folder} and scalar @{ $sync->{folder} } )
  1124. or $subscribed
  1125. or scalar @folderrec ) {
  1126. # folders given by option --folder
  1127. if ( $sync->{folder} and scalar @{ $sync->{folder} } ) {
  1128. add_to_requested_folders( @{ $sync->{folder} } );
  1129. }
  1130. # option --subscribed
  1131. if ( $subscribed ) {
  1132. add_to_requested_folders( keys %h1_subscribed_folder ) ;
  1133. }
  1134. # option --folderrec
  1135. if (scalar @folderrec) {
  1136. foreach my $folderrec (@folderrec) {
  1137. add_to_requested_folders($imap1->folders($folderrec));
  1138. }
  1139. }
  1140. } else {
  1141. # no include, no folder/subscribed/folderrec options => all folders
  1142. if ( not scalar @include ) {
  1143. 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" ) ;
  1144. add_to_requested_folders(@h1_folders_all);
  1145. }
  1146. }
  1147. # consider (optional) includes and excludes
  1148. if ( scalar @include ) {
  1149. foreach my $include ( @include ) {
  1150. my @included_folders = grep { /$include/ } @h1_folders_all ;
  1151. add_to_requested_folders( @included_folders ) ;
  1152. myprint( "Including folders matching pattern $include\n" . jux_utf8_list( @included_folders ) . "\n" ) ;
  1153. }
  1154. }
  1155. if ( scalar @exclude ) {
  1156. foreach my $exclude ( @exclude ) {
  1157. my @requested_folder = sort keys %requested_folder ;
  1158. my @excluded_folders = grep { /$exclude/ } @requested_folder ;
  1159. remove_from_requested_folders( @excluded_folders ) ;
  1160. myprint( "Excluding folders matching pattern $exclude\n" . jux_utf8_list( @excluded_folders ) . "\n" ) ;
  1161. }
  1162. }
  1163. # sort before is not very powerful
  1164. # it adds --folderfirst and --folderlast even if they don't exist on host1
  1165. @h1_folders_wanted = sort_requested_folders( ) ;
  1166. # Remove no selectable folders
  1167. if ( $sync->{ checkfoldersexist } ) {
  1168. my @h1_folders_wanted_exist ;
  1169. myprint( "Host1: Checking wanted folders exist. Use --nocheckfoldersexist to avoid this check (shared of public namespace targeted).\n" ) ;
  1170. foreach my $folder ( @h1_folders_wanted ) {
  1171. ( $debug or $sync->{debugfolders} ) and myprint( "Checking $folder exists on host1\n" ) ;
  1172. if ( ! exists $h1_folders_all{ $folder } ) {
  1173. myprint( "Host1: warning! ignoring folder $folder because it is not in host1 whole folders list.\n" ) ;
  1174. next ;
  1175. }else{
  1176. push @h1_folders_wanted_exist, $folder ;
  1177. }
  1178. }
  1179. @h1_folders_wanted = @h1_folders_wanted_exist ;
  1180. }else{
  1181. myprint( "Host1: Not checking that wanted folders exist. Remove --nocheckfoldersexist to get this check.\n" ) ;
  1182. }
  1183. if ( $sync->{ checkselectable } ) {
  1184. my @h1_folders_wanted_selectable ;
  1185. myprint( "Host1: Checking wanted folders are selectable. Use --nocheckselectable to avoid this check.\n" ) ;
  1186. foreach my $folder ( @h1_folders_wanted ) {
  1187. ( $debug or $sync->{debugfolders} ) and myprint( "Checking $folder is selectable on host1\n" ) ;
  1188. # It does an imap command LIST "" $folder and then search for no \Noselect
  1189. if ( ! $imap1->selectable( $folder ) ) {
  1190. myprint( "Host1: warning! ignoring folder $folder because it is not selectable\n" ) ;
  1191. }else{
  1192. push @h1_folders_wanted_selectable, $folder ;
  1193. }
  1194. }
  1195. @h1_folders_wanted = @h1_folders_wanted_selectable ;
  1196. ( $debug or $sync->{debugfolders} ) and myprint( 'Host1: checking folders took ', timenext( ), " s\n" ) ;
  1197. }else{
  1198. myprint( "Host1: Not checking that wanted folders are selectable. Remove --nocheckselectable to get this check.\n" ) ;
  1199. }
  1200. $sync->{h1_folders_wanted} = \@h1_folders_wanted ;
  1201. my( $h1_sep, $h2_sep ) ;
  1202. # what are the private folders separators for each server ?
  1203. ( $debug or $sync->{debugfolders} ) and myprint( "Getting separators\n" ) ;
  1204. $h1_sep = get_separator( $imap1, $sep1, '--sep1', 'Host1', \@h1_folders_all ) ;
  1205. $h2_sep = get_separator( $imap2, $sep2, '--sep2', 'Host2', \@h2_folders_all ) ;
  1206. $sync->{ h1_prefix } = get_prefix( $imap1, $prefix1, '--prefix1', 'Host1', \@h1_folders_all ) ;
  1207. $sync->{ h2_prefix } = get_prefix( $imap2, $prefix2, '--prefix2', 'Host2', \@h2_folders_all ) ;
  1208. myprint( "Host1 separator and prefix: [$h1_sep][$sync->{ h1_prefix }]\n" ) ;
  1209. myprint( "Host2 separator and prefix: [$h2_sep][$sync->{ h2_prefix }]\n" ) ;
  1210. # this hack is because LWP post does not pass well a hash in the $form parameter
  1211. # but it does pass well an array
  1212. %{ $sync->{f1f2h} } = split_around_equal( @{ $sync->{f1f2} } ) ;
  1213. automap( $sync ) ;
  1214. foreach my $h1_fold ( @h1_folders_wanted ) {
  1215. my $h2_fold ;
  1216. $h2_fold = imap2_folder_name( $h1_fold ) ;
  1217. $h2_folders_from_1_wanted{ $h2_fold }++ ;
  1218. if ( 1 < $h2_folders_from_1_wanted{ $h2_fold } ) {
  1219. $h2_folders_from_1_several{ $h2_fold }++ ;
  1220. }
  1221. }
  1222. @h2_folders_from_1_wanted = sort keys %h2_folders_from_1_wanted;
  1223. foreach my $h1_fold ( @h1_folders_all ) {
  1224. my $h2_fold ;
  1225. $h2_fold = imap2_folder_name( $h1_fold ) ;
  1226. $h2_folders_from_1_all{ $h2_fold }++ ;
  1227. }
  1228. myprint( << 'END_LISTING' ) ;
  1229. ++++ Listing folders
  1230. All foldernames are presented between brackets like [X] where X is the foldername.
  1231. When a foldername contains non-ASCII characters it is presented in the form
  1232. [X] = [Y] where
  1233. X is the imap foldername you have to use in command line options and
  1234. Y is the uft8 output just printed for convenience, to recognize it.
  1235. END_LISTING
  1236. myprint(
  1237. "Host1 folders list (first the raw imap format then the [X] = [Y]):\n",
  1238. $imap1->list( ),
  1239. "\n",
  1240. jux_utf8_list( @h1_folders_all ),
  1241. "\n",
  1242. "Host2 folders list (first the raw imap format then the [X] = [Y]):\n",
  1243. $imap2->list( ),
  1244. "\n",
  1245. jux_utf8_list( @h2_folders_all ),
  1246. "\n",
  1247. q{}
  1248. ) ;
  1249. if ( $subscribed ) {
  1250. myprint(
  1251. 'Host1 subscribed folders list: ',
  1252. jux_utf8_list( sort keys %h1_subscribed_folder ), "\n",
  1253. ) ;
  1254. }
  1255. my @h2_folders_not_in_1;
  1256. @h2_folders_not_in_1 = list_folders_in_2_not_in_1( ) ;
  1257. if ( @h2_folders_not_in_1 ) {
  1258. myprint( "Folders in host2 not in host1:\n",
  1259. jux_utf8_list( @h2_folders_not_in_1 ), "\n" ) ;
  1260. }
  1261. if ( keys %{ $sync->{f1f2auto} } ) {
  1262. myprint( "Folders mapping from --automap feature (use --f1f2 to override any mapping):\n" ) ;
  1263. foreach my $h1_fold ( keys %{ $sync->{f1f2auto} } ) {
  1264. my $h2_fold = $sync->{f1f2auto}{$h1_fold} ;
  1265. myprintf( "%-40s -> %-40s\n",
  1266. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1267. }
  1268. myprint( "\n" ) ;
  1269. }
  1270. if ( keys %{ $sync->{f1f2h} } ) {
  1271. myprint( "Folders mapping from --f1f2 options, it overrides --automap:\n" ) ;
  1272. foreach my $h1_fold ( keys %{ $sync->{f1f2h} } ) {
  1273. my $h2_fold = $sync->{f1f2h}{$h1_fold} ;
  1274. my $warn = q{} ;
  1275. if ( not exists $h1_folders_all{ $h1_fold } ) {
  1276. $warn = "BUT $h1_fold does NOT exist on host1!" ;
  1277. }
  1278. myprintf( "%-40s -> %-40s %s\n",
  1279. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ), $warn ) ;
  1280. }
  1281. myprint( "\n" ) ;
  1282. }
  1283. exit_clean( $sync, $EX_OK ) if ( $sync->{justfolderlists} ) ;
  1284. exit_clean( $sync, $EX_OK ) if ( $sync->{justautomap} ) ;
  1285. debugsleep( $sync ) ;
  1286. if ( $foldersizes ) {
  1287. foldersizes_on_h1h2( ) ;
  1288. }
  1289. exit_clean( $sync, $EX_OK ) if ( $justfoldersizes ) ;
  1290. $sync->{stats} = 1 ;
  1291. if ( $sync->{'delete1emptyfolders'} ) {
  1292. delete1emptyfolders( $sync ) ;
  1293. }
  1294. delete_folders_in_2_not_in_1( ) if $delete2folders ;
  1295. # folder loop
  1296. $h1_folders_wanted_nb = scalar @h1_folders_wanted ;
  1297. myprint( "++++ Looping on each one of $h1_folders_wanted_nb folders to sync\n" ) ;
  1298. $sync->{begin_transfer_time} = time ;
  1299. my %uid_candidate_for_deletion ;
  1300. my %uid_candidate_no_deletion ;
  1301. my %h2_folders_of_md5 = ( ) ;
  1302. FOLDER: foreach my $h1_fold ( @h1_folders_wanted ) {
  1303. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1304. my $h2_fold = imap2_folder_name( $h1_fold ) ;
  1305. $h1_folders_wanted_ct++ ;
  1306. myprintf( "Folder %7s %-35s -> %-35s\n", "$h1_folders_wanted_ct/$h1_folders_wanted_nb",
  1307. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1308. myprint( debugmemory( $sync, " at folder loop" ) ) ;
  1309. # host1 can not be fetched read only, select is needed because of expunge.
  1310. select_folder( $imap1, $h1_fold, 'Host1' ) or next FOLDER ;
  1311. debugsleep( $sync ) ;
  1312. my $h1_fold_nb_messages = count_from_select( $imap1->History ) ;
  1313. myprint( "Host1 folder [$h1_fold] has $h1_fold_nb_messages messages in total (mentioned by SELECT)\n" ) ;
  1314. if ( $skipemptyfolders and 0 == $h1_fold_nb_messages ) {
  1315. myprint( "Skipping empty host1 folder [$h1_fold]\n" ) ;
  1316. next FOLDER ;
  1317. }
  1318. if ( ! exists $h2_folders_all{ $h2_fold } ) {
  1319. create_folder( $imap2, $h2_fold, $h1_fold ) or next FOLDER ;
  1320. }
  1321. acls_sync( $h1_fold, $h2_fold ) ;
  1322. # Sometimes the folder on host2 is listed (it exists) but is
  1323. # not selectable but becomes selectable by a create (Gmail)
  1324. select_folder( $imap2, $h2_fold, 'Host2' )
  1325. or ( create_folder( $imap2, $h2_fold, $h1_fold )
  1326. and select_folder( $imap2, $h2_fold, 'Host2' ) )
  1327. or next FOLDER ;
  1328. my @select_results = $imap2->Results( ) ;
  1329. my $h2_fold_nb_messages = count_from_select( @select_results ) ;
  1330. myprint( "Host2 folder [$h2_fold] has $h2_fold_nb_messages messages in total (mentioned by SELECT)\n" ) ;
  1331. my $permanentflags2 = permanentflags( @select_results ) ;
  1332. myprint( "Host2 folder [$h2_fold] permanentflags: $permanentflags2\n" ) ;
  1333. if ( $expunge1 ){
  1334. myprint( "Host1: Expunging $h1_fold $sync->{dry_message}\n" ) ;
  1335. if ( ! $sync->{dry} ) { $imap1->expunge( ) } ;
  1336. }
  1337. if ( ( ( $subscribe and exists $h1_subscribed_folder{ $h1_fold } ) or $subscribeall )
  1338. and not exists $h2_subscribed_folder{ $h2_fold } ) {
  1339. myprint( "Host2: Subscribing to folder $h2_fold\n" ) ;
  1340. if ( ! $sync->{dry} ) { $imap2->subscribe( $h2_fold ) } ;
  1341. }
  1342. next FOLDER if ( $justfolders ) ;
  1343. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1344. my $h1_msgs_all_hash_ref = { } ;
  1345. my @h1_msgs = select_msgs( $imap1, $h1_msgs_all_hash_ref, $search1, $sync->{abletosearch1}, $h1_fold );
  1346. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1347. my $h1_msgs_nb = scalar @h1_msgs ;
  1348. $h1{ $h1_fold }{ 'messages_nb' } = $h1_msgs_nb ;
  1349. myprint( "Host1 folder [$h1_fold] considering $h1_msgs_nb messages\n" ) ;
  1350. ( $debug or $debuglist ) and myprint( "Host1 folder [$h1_fold] considering $h1_msgs_nb messages, LIST gives: @h1_msgs\n" ) ;
  1351. $debug and myprint( "Host1 selecting messages of folder [$h1_fold] took ", timenext(), " s\n" ) ;
  1352. my $h2_msgs_all_hash_ref = { } ;
  1353. my @h2_msgs = select_msgs( $imap2, $h2_msgs_all_hash_ref, $search2, $sync->{abletosearch2}, $h2_fold ) ;
  1354. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1355. my $h2_msgs_nb = scalar @h2_msgs ;
  1356. $h2{ $h2_fold }{ 'messages_nb' } = $h2_msgs_nb ;
  1357. myprint( "Host2 folder [$h2_fold] considering $h2_msgs_nb messages\n" ) ;
  1358. ( $debug or $debuglist ) and myprint( "Host2 folder [$h2_fold] considering $h2_msgs_nb messages, LIST gives: @h2_msgs\n" ) ;
  1359. $debug and myprint( "Host2 selecting messages of folder [$h2_fold] took ", timenext(), " s\n" ) ;
  1360. my $cache_base = "$sync->{ tmpdir }/imapsync_cache/" ;
  1361. my $cache_dir = cache_folder( $cache_base, "$sync->{host1}/$sync->{user1}/$sync->{host2}/$sync->{user2}", $h1_fold, $h2_fold ) ;
  1362. my ( $cache_1_2_ref, $cache_2_1_ref ) = ( {}, {} ) ;
  1363. my $h1_uidvalidity = $imap1->uidvalidity( ) || q{} ;
  1364. my $h2_uidvalidity = $imap2->uidvalidity( ) || q{} ;
  1365. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1366. if ( $usecache ) {
  1367. myprint( "cache directory: $cache_dir\n" ) ;
  1368. mkpath( "$cache_dir" ) ;
  1369. ( $cache_1_2_ref, $cache_2_1_ref )
  1370. = get_cache( $cache_dir, \@h1_msgs, \@h2_msgs, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  1371. myprint( 'CACHE h1 h2: ', scalar keys %{ $cache_1_2_ref } , " files\n" ) ;
  1372. $debug and myprint( '[',
  1373. map ( { "$_->$cache_1_2_ref->{$_} " } keys %{ $cache_1_2_ref } ), " ]\n" ) ;
  1374. }
  1375. my %h1_hash = () ;
  1376. my %h2_hash = () ;
  1377. my ( %h1_msgs, %h2_msgs ) ;
  1378. @h1_msgs{ @h1_msgs } = ();
  1379. @h2_msgs{ @h2_msgs } = ();
  1380. my @h1_msgs_in_cache = sort { $a <=> $b } keys %{ $cache_1_2_ref } ;
  1381. my @h2_msgs_in_cache = keys %{ $cache_2_1_ref } ;
  1382. my ( %h1_msgs_not_in_cache, %h2_msgs_not_in_cache ) ;
  1383. %h1_msgs_not_in_cache = %h1_msgs ;
  1384. %h2_msgs_not_in_cache = %h2_msgs ;
  1385. delete @h1_msgs_not_in_cache{ @h1_msgs_in_cache } ;
  1386. delete @h2_msgs_not_in_cache{ @h2_msgs_in_cache } ;
  1387. my @h1_msgs_not_in_cache = keys %h1_msgs_not_in_cache ;
  1388. #myprint( "h1_msgs_not_in_cache: [@h1_msgs_not_in_cache]\n" ) ;
  1389. my @h2_msgs_not_in_cache = keys %h2_msgs_not_in_cache ;
  1390. my @h2_msgs_delete2_not_in_cache = () ;
  1391. %h1_msgs_copy_by_uid = ( ) ;
  1392. if ( $useuid ) {
  1393. # use uid so we have to avoid getting header
  1394. @h1_msgs_copy_by_uid{ @h1_msgs_not_in_cache } = ( ) ;
  1395. @h2_msgs_delete2_not_in_cache = @h2_msgs_not_in_cache if $usecache ;
  1396. @h1_msgs_not_in_cache = ( ) ;
  1397. @h2_msgs_not_in_cache = ( ) ;
  1398. #myprint( "delete2: @h2_msgs_delete2_not_in_cache\n" ) ;
  1399. }
  1400. $debug and myprint( "Host1 parsing headers of folder [$h1_fold]\n" ) ;
  1401. my ($h1_heads_ref, $h1_fir_ref) = ({}, {});
  1402. $h1_heads_ref = $imap1->parse_headers([@h1_msgs_not_in_cache], @useheader) if (@h1_msgs_not_in_cache);
  1403. $debug and myprint( "Host1 parsing headers of folder [$h1_fold] took ", timenext(), " s\n" ) ;
  1404. @{ $h1_fir_ref }{@h1_msgs} = ( undef ) ;
  1405. $debug and myprint( "Host1 getting flags idate and sizes of folder [$h1_fold]\n" ) ;
  1406. if ( $sync->{abletosearch1} ) {
  1407. $h1_fir_ref = $imap1->fetch_hash( \@h1_msgs, 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE', $h1_fir_ref )
  1408. if ( @h1_msgs ) ;
  1409. }else{
  1410. my $uidnext = $imap1->uidnext( $h1_fold ) || $uidnext_default ;
  1411. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  1412. $h1_fir_ref = $imap1->fetch_hash( $fetch_hash_uids, 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE', $h1_fir_ref )
  1413. if ( @h1_msgs ) ;
  1414. }
  1415. $debug and myprint( "Host1 getting flags idate and sizes of folder [$h1_fold] took ", timenext(), " s\n" ) ;
  1416. if ( ! $h1_fir_ref ) {
  1417. my $error = join( q{}, "Host1 folder $h1_fold: Could not fetch_hash ",
  1418. scalar @h1_msgs, ' msgs: ', $imap1->LastError || q{}, "\n" ) ;
  1419. errors_incr( $sync, $error ) ;
  1420. next FOLDER ;
  1421. }
  1422. my @h1_msgs_duplicate;
  1423. foreach my $m (@h1_msgs_not_in_cache) {
  1424. my $rc = parse_header_msg( $sync, $imap1, $m, $h1_heads_ref, $h1_fir_ref, 'Host1', \%h1_hash ) ;
  1425. if ( ! defined $rc ) {
  1426. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1427. myprint( "Host1 $h1_fold/$m size $h1_size ignored (no wanted headers so we ignore this message. To solve this: use --addheader)\n" ) ;
  1428. $total_bytes_skipped += $h1_size;
  1429. $nb_msg_skipped += 1;
  1430. $h1_nb_msg_noheader +=1;
  1431. $h1_nb_msg_processed +=1 ;
  1432. } elsif(0 == $rc) {
  1433. # duplicate
  1434. push @h1_msgs_duplicate, $m;
  1435. # duplicate, same id same size?
  1436. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1437. $nb_msg_skipped += 1;
  1438. $h1_total_bytes_duplicate += $h1_size;
  1439. $h1_nb_msg_duplicate += 1;
  1440. $h1_nb_msg_processed +=1 ;
  1441. }
  1442. }
  1443. my $h1_msgs_duplicate_nb = scalar @h1_msgs_duplicate ;
  1444. $h1{ $h1_fold }{ 'duplicates_nb' } = $h1_msgs_duplicate_nb ;
  1445. $debug and myprint( "Host1 selected: $h1_msgs_nb duplicates: $h1_msgs_duplicate_nb\n" ) ;
  1446. $debug and myprint( 'Host1 whole time parsing headers took ', timenext(), " s\n" ) ;
  1447. # Getting headers and metada can be so long that host2 might be disconnected here
  1448. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1449. $debug and myprint( "Host2 parsing headers of folder [$h2_fold]\n" ) ;
  1450. my ($h2_heads_ref, $h2_fir_ref) = ( {}, {} );
  1451. $h2_heads_ref = $imap2->parse_headers([@h2_msgs_not_in_cache], @useheader) if (@h2_msgs_not_in_cache);
  1452. $debug and myprint( "Host2 parsing headers of folder [$h2_fold] took ", timenext(), " s\n" ) ;
  1453. $debug and myprint( "Host2 getting flags idate and sizes of folder [$h2_fold]\n" ) ;
  1454. @{ $h2_fir_ref }{@h2_msgs} = ( ); # fetch_hash can select by uid with last arg as ref
  1455. if ( $sync->{abletosearch2} and scalar( @h2_msgs ) ) {
  1456. $h2_fir_ref = $imap2->fetch_hash( \@h2_msgs, 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE', $h2_fir_ref) ;
  1457. }else{
  1458. my $uidnext = $imap2->uidnext( $h2_fold ) || $uidnext_default ;
  1459. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  1460. $h2_fir_ref = $imap2->fetch_hash( $fetch_hash_uids, 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE', $h2_fir_ref )
  1461. if ( @h2_msgs ) ;
  1462. }
  1463. $debug and myprint( "Host2 getting flags idate and sizes of folder [$h2_fold] took ", timenext(), " s\n" ) ;
  1464. my @h2_msgs_duplicate;
  1465. foreach my $m (@h2_msgs_not_in_cache) {
  1466. my $rc = parse_header_msg( $sync, $imap2, $m, $h2_heads_ref, $h2_fir_ref, 'Host2', \%h2_hash ) ;
  1467. my $h2_size = $h2_fir_ref->{$m}->{'RFC822.SIZE'} || 0 ;
  1468. if (! defined $rc ) {
  1469. myprint( "Host2 $h2_fold/$m size $h2_size ignored (no wanted headers so we ignore this message)\n" ) ;
  1470. $h2_nb_msg_noheader += 1 ;
  1471. } elsif( 0 == $rc ) {
  1472. # duplicate
  1473. $h2_nb_msg_duplicate += 1 ;
  1474. $h2_total_bytes_duplicate += $h2_size ;
  1475. push @h2_msgs_duplicate, $m ;
  1476. }
  1477. }
  1478. # %h2_folders_of_md5
  1479. foreach my $md5 ( keys %h2_hash ) {
  1480. $h2_folders_of_md5{ $md5 }->{ $h2_fold } ++ ;
  1481. }
  1482. my $h2_msgs_duplicate_nb = scalar @h2_msgs_duplicate ;
  1483. $h2{ $h2_fold }{ 'duplicates_nb' } = $h2_msgs_duplicate_nb ;
  1484. myprint( "Host2 folder $h2_fold selected: $h2_msgs_nb messages, duplicates: $h2_msgs_duplicate_nb\n" )
  1485. if ( $debug or $delete2duplicates or $h2_msgs_duplicate_nb ) ;
  1486. $debug and myprint( 'Host2 whole time parsing headers took ', timenext( ), " s\n" ) ;
  1487. $debug and myprint( "++++ Verifying [$h1_fold] -> [$h2_fold]\n" ) ;
  1488. # messages in host1 that are not in host2
  1489. my @h1_hash_keys_sorted_by_uid
  1490. = sort {$h1_hash{$a}{'m'} <=> $h1_hash{$b}{'m'}} keys %h1_hash;
  1491. #myprint( map { $h1_hash{$_}{'m'} . q{ }} @h1_hash_keys_sorted_by_uid ) ;
  1492. my @h2_hash_keys_sorted_by_uid
  1493. = sort {$h2_hash{$a}{'m'} <=> $h2_hash{$b}{'m'}} keys %h2_hash;
  1494. if( $delete2duplicates and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  1495. my @h2_expunge ;
  1496. foreach my $h2_msg ( @h2_msgs_duplicate ) {
  1497. myprint( "msg $h2_fold/$h2_msg marked \\Deleted [duplicate] on host2 $sync->{dry_message}\n" ) ;
  1498. push @h2_expunge, $h2_msg if $uidexpunge2 ;
  1499. if ( ! $sync->{dry} ) {
  1500. $imap2->delete_message( $h2_msg ) ;
  1501. $h2_nb_msg_deleted += 1 ;
  1502. }
  1503. }
  1504. my $cnt = scalar @h2_expunge ;
  1505. if( @h2_expunge and not $expunge2 ) {
  1506. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  1507. $imap2->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  1508. }
  1509. if ( $expunge2 ){
  1510. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  1511. $imap2->expunge( ) if ! $sync->{dry} ;
  1512. }
  1513. }
  1514. if( $delete2 and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  1515. # No host1 folders f1a f1b ... going all to same f2 (via --regextrans2)
  1516. my @h2_expunge;
  1517. foreach my $m_id (@h2_hash_keys_sorted_by_uid) {
  1518. #myprint( "$m_id " ) ;
  1519. if ( ! exists $h1_hash{$m_id} ) {
  1520. my $h2_msg = $h2_hash{$m_id}{'m'};
  1521. my $h2_flags = $h2_hash{$m_id}{'F'} || q{};
  1522. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0;
  1523. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted on host2 [$m_id] $sync->{dry_message}\n" )
  1524. if ! $isdel;
  1525. push @h2_expunge, $h2_msg if $uidexpunge2;
  1526. if ( ! ( $sync->{dry} or $isdel ) ) {
  1527. $imap2->delete_message($h2_msg);
  1528. $h2_nb_msg_deleted += 1;
  1529. }
  1530. }
  1531. }
  1532. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  1533. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted [not in cache] on host2 $sync->{dry_message}\n" ) ;
  1534. push @h2_expunge, $h2_msg if $uidexpunge2;
  1535. if ( ! $sync->{dry} ) {
  1536. $imap2->delete_message($h2_msg);
  1537. $h2_nb_msg_deleted += 1;
  1538. }
  1539. }
  1540. my $cnt = scalar @h2_expunge ;
  1541. if( @h2_expunge and not $expunge2 ) {
  1542. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  1543. $imap2->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  1544. }
  1545. if ( $expunge2 ) {
  1546. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  1547. $imap2->expunge( ) if ! $sync->{dry} ;
  1548. }
  1549. }
  1550. if( $delete2 and exists $h2_folders_from_1_several{ $h2_fold } ) {
  1551. myprint( "Host2 folder $h2_fold $h2_folders_from_1_several{ $h2_fold } folders left to sync there\n" ) ;
  1552. my @h2_expunge;
  1553. foreach my $m_id ( @h2_hash_keys_sorted_by_uid ) {
  1554. my $h2_msg = $h2_hash{ $m_id }{ 'm' } ;
  1555. if ( ! exists $h1_hash{ $m_id } ) {
  1556. my $h2_flags = $h2_hash{ $m_id }{ 'F' } || q{} ;
  1557. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0 ;
  1558. if ( ! $isdel ) {
  1559. $debug and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [$m_id]\n" ) ;
  1560. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  1561. }
  1562. }else{
  1563. $debug and myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [$m_id]\n" ) ;
  1564. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1565. }
  1566. }
  1567. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  1568. myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [not in cache]\n" ) ;
  1569. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  1570. }
  1571. foreach my $h2_msg ( @h2_msgs_in_cache ) {
  1572. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [in cache]\n" ) ;
  1573. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1574. }
  1575. if ( 0 == $h2_folders_from_1_several{ $h2_fold } ) {
  1576. # last host1 folder going to $h2_fold
  1577. myprint( "Last host1 folder going to $h2_fold\n" ) ;
  1578. foreach my $h2_msg ( keys %{ $uid_candidate_for_deletion{ $h2_fold } } ) {
  1579. $debug and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion\n" ) ;
  1580. if ( exists $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg } ) {
  1581. $debug and myprint( "Host2: msg $h2_fold/$h2_msg canceled deletion\n" ) ;
  1582. }else{
  1583. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted $sync->{dry_message}\n" ) ;
  1584. push @h2_expunge, $h2_msg if $uidexpunge2 ;
  1585. if ( ! $sync->{dry} ) {
  1586. $imap2->delete_message( $h2_msg ) ;
  1587. $h2_nb_msg_deleted += 1 ;
  1588. }
  1589. }
  1590. }
  1591. }
  1592. my $cnt = scalar @h2_expunge ;
  1593. if( @h2_expunge and not $expunge2 ) {
  1594. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  1595. $imap2->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  1596. }
  1597. if ( $expunge2 ) {
  1598. myprint( "Host2: Expunging host2 folder $h2_fold $sync->{dry_message}\n" ) ;
  1599. $imap2->expunge( ) if ! $sync->{dry} ;
  1600. }
  1601. $h2_folders_from_1_several{ $h2_fold }-- ;
  1602. }
  1603. my $h2_uidnext = $imap2->uidnext( $h2_fold ) ;
  1604. $debug and myprint( "Host2 uidnext: $h2_uidnext\n" ) ;
  1605. $h2_uidguess = $h2_uidnext ;
  1606. # Getting host2 headers, metada and delete2 stuff can be so long that host1 might be disconnected here
  1607. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1608. MESS: foreach my $m_id (@h1_hash_keys_sorted_by_uid) {
  1609. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1610. #myprint( "h1_nb_msg_processed: $h1_nb_msg_processed\n" ) ;
  1611. my $h1_size = $h1_hash{$m_id}{'s'};
  1612. my $h1_msg = $h1_hash{$m_id}{'m'};
  1613. my $h1_idate = $h1_hash{$m_id}{'D'};
  1614. if ( ( not exists $h2_hash{ $m_id } )
  1615. and ( not ( exists $h2_folders_of_md5{ $m_id } )
  1616. or not $skipcrossduplicates ) ) {
  1617. # copy
  1618. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  1619. $h2_folders_of_md5{ $m_id }->{ $h2_fold } ++ ;
  1620. if( $delete2 and ( exists $h2_folders_from_1_several{ $h2_fold } ) and $h2_msg ) {
  1621. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  1622. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1623. }
  1624. last FOLDER if total_bytes_max_reached( ) ;
  1625. next MESS;
  1626. }
  1627. else{
  1628. # already on host2
  1629. if ( exists $h2_hash{ $m_id } ) {
  1630. my $h2_msg = $h2_hash{$m_id}{'m'} ;
  1631. $debug and myprint( "Host1 found msg $h1_fold/$h1_msg equals Host2 $h2_fold/$h2_msg\n" ) ;
  1632. if ( $usecache ) {
  1633. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$h2_msg\n" ) ;
  1634. touch( "$cache_dir/${h1_msg}_$h2_msg" )
  1635. or croak( "Couldn't touch $cache_dir/${h1_msg}_$h2_msg" ) ;
  1636. }
  1637. }elsif( exists $h2_folders_of_md5{ $m_id } ) {
  1638. my @folders_dup = keys %{ $h2_folders_of_md5{ $m_id } } ;
  1639. ( $debug or $debugcrossduplicates ) and myprint( "Host1 found msg $h1_fold/$h1_msg is also in Host2 folders @folders_dup\n" ) ;
  1640. }
  1641. $total_bytes_skipped += $h1_size ;
  1642. $nb_msg_skipped += 1 ;
  1643. $h1_nb_msg_processed +=1 ;
  1644. }
  1645. if ( exists $h2_hash{ $m_id } ) {
  1646. #$debug and myprint( "MESSAGE $m_id\n" ) ;
  1647. my $h2_msg = $h2_hash{$m_id}{'m'};
  1648. if ( $sync->{resyncflags} ) {
  1649. sync_flags_fir( $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  1650. }
  1651. # Good
  1652. my $h2_size = $h2_hash{$m_id}{'s'};
  1653. $debug and myprint(
  1654. "Host1 size msg $h1_fold/$h1_msg = $h1_size <> $h2_size = Host2 $h2_fold/$h2_msg\n" ) ;
  1655. }
  1656. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1657. if ( $delete1 ) {
  1658. delete_message_on_host1( $h1_msg, $h1_fold ) ;
  1659. }
  1660. }
  1661. # END MESS: loop
  1662. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1663. MESS_IN_CACHE: foreach my $h1_msg ( @h1_msgs_in_cache ) {
  1664. my $h2_msg = $cache_1_2_ref->{ $h1_msg } ;
  1665. $debugcache and myprint( "cache messages update flags $h1_msg->$h2_msg\n" ) ;
  1666. if ( $sync->{resyncflags} ) {
  1667. sync_flags_fir( $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  1668. }
  1669. my $h1_size = $h1_fir_ref->{ $h1_msg }->{ 'RFC822.SIZE' } || 0 ;
  1670. $total_bytes_skipped += $h1_size;
  1671. $nb_msg_skipped += 1;
  1672. $h1_nb_msg_processed +=1 ;
  1673. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1674. }
  1675. #myprint( "Messages by uid: ", map { "$_ " } keys %h1_msgs_copy_by_uid, "\n" ) ;
  1676. MESS_BY_UID: foreach my $h1_msg ( sort { $a <=> $b } keys %h1_msgs_copy_by_uid ) {
  1677. #
  1678. $debug and myprint( "Copy by uid $h1_fold/$h1_msg\n" ) ;
  1679. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1680. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  1681. if( $delete2 and exists $h2_folders_from_1_several{ $h2_fold } and $h2_msg ) {
  1682. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  1683. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1684. }
  1685. last FOLDER if total_bytes_max_reached( ) ;
  1686. }
  1687. if ( $expunge1 ){
  1688. myprint( "Host1: Expunging folder $h1_fold $sync->{dry_message}\n" ) ;
  1689. if ( ! $sync->{dry} ) { $imap1->expunge( ) } ;
  1690. }
  1691. if ( $expunge2 ){
  1692. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  1693. if ( ! $sync->{dry} ) { $imap2->expunge( ) } ;
  1694. }
  1695. $debug and myprint( 'Time: ', timenext( ), " s\n" ) ;
  1696. }
  1697. myprint( "++++ End looping on each folder\n" ) ;
  1698. if ( $delete1 and $sync->{'delete1emptyfolders'} ) {
  1699. delete1emptyfolders( $sync ) ;
  1700. }
  1701. ( $debug or $sync->{debugfolders} ) and myprint( 'Time: ', timenext( ), " s\n" ) ;
  1702. if ( $foldersizesatend ) {
  1703. myprint( << 'END_SIZE' ) ;
  1704. Folders sizes after the synchronization.
  1705. You can remove this foldersizes listing by using "--nofoldersizesatend"
  1706. END_SIZE
  1707. foldersizesatend( ) ;
  1708. }
  1709. if ( ! lost_connection( $imap1, "for host1 [$sync->{host1}]" ) ) { $imap1->logout( ) ; }
  1710. if ( ! lost_connection( $imap2, "for host2 [$sync->{host2}]" ) ) { $imap2->logout( ) ; }
  1711. stats( $sync ) ;
  1712. myprint( errorsdump( $sync->{nb_errors}, errors_log( $sync ) ) ) if ( $sync->{errorsdump} ) ;
  1713. tests_live_result( $sync->{nb_errors} ) if ( $sync->{testslive} or $sync->{testslive6} ) ;
  1714. exit_clean( $sync, $EXIT_WITH_ERRORS ) if ( $sync->{nb_errors} ) ;
  1715. exit_clean( $sync, $EX_OK ) ;
  1716. # END of main program
  1717. # subroutines
  1718. sub myprint {
  1719. #print @ARG ;
  1720. print { $sync->{ tee } || \*STDOUT } @ARG ;
  1721. return ;
  1722. }
  1723. sub myprintf {
  1724. printf { $sync->{ tee } || \*STDOUT } @ARG ;
  1725. return ;
  1726. }
  1727. sub mysprintf {
  1728. my( $format, @list ) = @ARG ;
  1729. return sprintf $format, @list ;
  1730. }
  1731. sub output_start {
  1732. my $mysync = shift @ARG ;
  1733. if ( not $mysync ) { return ; }
  1734. my @output = @ARG ;
  1735. $mysync->{ output } = join( q{}, @output ) . ( $mysync->{ output } || q{} ) ;
  1736. return $mysync->{ output } ;
  1737. }
  1738. sub tests_output_start {
  1739. note( 'Entering tests_output_start()' ) ;
  1740. my $mysync = { } ;
  1741. is( undef, output_start( ), 'output_start: no args => undef' ) ;
  1742. is( q{}, output_start( $mysync ), 'output_start: one arg => ""' ) ;
  1743. is( 'rrrr', output_start( $mysync, 'rrrr' ), 'output_start: rrrr => rrrr' ) ;
  1744. is( 'aaaarrrr', output_start( $mysync, 'aaaa' ), 'output_start: aaaa => aaaarrrr' ) ;
  1745. is( "\naaaarrrr", output_start( $mysync, "\n" ), 'output_start: \n => \naaaarrrr' ) ;
  1746. is( "ABC\naaaarrrr", output_start( $mysync, 'A', 'B', 'C' ), 'output_start: A B C => ABC\naaaarrrr' ) ;
  1747. note( 'Leaving tests_output_start()' ) ;
  1748. return ;
  1749. }
  1750. sub tests_output {
  1751. note( 'Entering tests_output()' ) ;
  1752. my $mysync = { } ;
  1753. is( undef, output( ), 'output: no args => undef' ) ;
  1754. is( q{}, output( $mysync ), 'output: one arg => ""' ) ;
  1755. is( 'rrrr', output( $mysync, 'rrrr' ), 'output: rrrr => rrrr' ) ;
  1756. is( 'rrrraaaa', output( $mysync, 'aaaa' ), 'output: aaaa => rrrraaaa' ) ;
  1757. is( "rrrraaaa\n", output( $mysync, "\n" ), 'output: \n => rrrraaaa\n' ) ;
  1758. is( "rrrraaaa\nABC", output( $mysync, 'A', 'B', 'C' ), 'output: A B C => rrrraaaaABC\n' ) ;
  1759. note( 'Leaving tests_output()' ) ;
  1760. return ;
  1761. }
  1762. sub output {
  1763. my $mysync = shift @ARG ;
  1764. if ( not $mysync ) { return ; }
  1765. my @output = @ARG ;
  1766. $mysync->{ output } .= join( q{}, @output ) ;
  1767. return $mysync->{ output } ;
  1768. }
  1769. sub tests_output_reset_with {
  1770. note( 'Entering tests_output_reset_with()' ) ;
  1771. my $mysync = { } ;
  1772. is( undef, output_reset_with( ), 'output_reset_with: no args => undef' ) ;
  1773. is( q{}, output_reset_with( $mysync ), 'output_reset_with: one arg => ""' ) ;
  1774. is( 'rrrr', output_reset_with( $mysync, 'rrrr' ), 'output_reset_with: rrrr => rrrr' ) ;
  1775. is( 'aaaa', output_reset_with( $mysync, 'aaaa' ), 'output_reset_with: aaaa => aaaa' ) ;
  1776. is( "\n", output_reset_with( $mysync, "\n" ), 'output_reset_with: \n => \n' ) ;
  1777. note( 'Leaving tests_output_reset_with()' ) ;
  1778. return ;
  1779. }
  1780. sub output_reset_with {
  1781. my $mysync = shift @ARG ;
  1782. if ( not $mysync ) { return ; }
  1783. my @output = @ARG ;
  1784. $mysync->{ output } = join( q{}, @output ) ;
  1785. return $mysync->{ output } ;
  1786. }
  1787. sub abort {
  1788. my $mysync = shift @ARG ;
  1789. if ( ! -r $sync->{pidfile} ) {
  1790. myprint( "Can not read pidfile $sync->{pidfile}. Exiting.\n" ) ;
  1791. exit $EX_OK ;
  1792. }
  1793. my $pidtokill = firstline( $sync->{pidfile} ) ;
  1794. if ( ! $pidtokill ) {
  1795. myprint( "No process to abort. Exiting.\n" ) ;
  1796. exit $EX_OK ;
  1797. }
  1798. # First ask for suicide
  1799. if ( kill 'ZERO', $pidtokill ) {
  1800. myprint( "Sending signal QUIT to PID $pidtokill \n" ) ;
  1801. kill 'QUIT', $pidtokill ;
  1802. sleep 1 ;
  1803. }else{
  1804. myprint( "Can not send signal to PID $pidtokill. Exiting.\n" ) ;
  1805. exit $EX_OK ;
  1806. }
  1807. # Then murder
  1808. if ( kill 'ZERO', $pidtokill ) {
  1809. myprint( "Sending signal KILL to PID $pidtokill \n" ) ;
  1810. kill 'KILL', $pidtokill ;
  1811. sleep 1 ;
  1812. }else{
  1813. myprint( "Process PID $pidtokill ended. Exiting.\n" ) ;
  1814. exit $EX_OK ;
  1815. }
  1816. # Well ...
  1817. if ( kill 'ZERO', $pidtokill ) {
  1818. myprint( "Process PID $pidtokill still there. Can not do much. Exiting.\n" ) ;
  1819. exit $EX_OK ;
  1820. }
  1821. return ;
  1822. }
  1823. sub docker_context {
  1824. my $mysync = shift ;
  1825. -e '/.dockerenv' || return ;
  1826. myprint( "Docker context detected with /.dockerenv\n" ) ;
  1827. # No pidfile
  1828. $mysync->{pidfile} = q{} ;
  1829. # No log
  1830. $mysync->{log} = 0 ;
  1831. # In case
  1832. myprint( "Changing current directory to /var/tmp/\n" ) ;
  1833. chdir '/var/tmp/' ;
  1834. return ;
  1835. }
  1836. sub cgibegin {
  1837. my $mysync = shift ;
  1838. if ( ! under_cgi_context( $mysync ) ) { return ; }
  1839. require CGI ;
  1840. CGI->import( qw( -no_debug ) ) ;
  1841. require CGI::Carp ;
  1842. CGI::Carp->import( qw( fatalsToBrowser ) ) ;
  1843. $mysync->{cgi} = CGI->new( ) ;
  1844. return ;
  1845. }
  1846. sub tests_under_cgi_context {
  1847. note( 'Entering tests_under_cgi_context()' ) ;
  1848. # $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  1849. do {
  1850. # Not in cgi context
  1851. delete local $ENV{SERVER_SOFTWARE} ;
  1852. is( undef, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE unset => not in cgi context' ) ;
  1853. } ;
  1854. do {
  1855. # In cgi context
  1856. local $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  1857. is( 1, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE set => in cgi context' ) ;
  1858. } ;
  1859. do {
  1860. # Not in cgi context
  1861. delete local $ENV{SERVER_SOFTWARE} ;
  1862. is( undef, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE unset => not in cgi context' ) ;
  1863. } ;
  1864. do {
  1865. # In cgi context
  1866. local $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  1867. is( 1, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE set => in cgi context' ) ;
  1868. } ;
  1869. note( 'Leaving tests_under_cgi_context()' ) ;
  1870. return ;
  1871. }
  1872. sub under_cgi_context {
  1873. my $mysync = shift ;
  1874. # Under cgi context
  1875. if ( $ENV{SERVER_SOFTWARE} ) {
  1876. return 1 ;
  1877. }
  1878. # Not in cgi context
  1879. return ;
  1880. }
  1881. sub cgibuildheader {
  1882. my $mysync = shift ;
  1883. if ( ! under_cgi_context( $mysync ) ) { return ; }
  1884. my $imapsync_runs = $mysync->{cgi}->cookie( 'imapsync_runs' ) || 0 ;
  1885. my $cookie = $mysync->{cgi}->cookie(
  1886. -name => 'imapsync_runs',
  1887. -value => 1 + $imapsync_runs,
  1888. -expires => '+20y',
  1889. -path => '/cgi-bin/imapsync',
  1890. ) ;
  1891. my $httpheader ;
  1892. if ( $mysync->{ abort } ) {
  1893. $httpheader = $mysync->{cgi}->header(
  1894. -type => 'text/plain',
  1895. -status => '200 OK to abort syncing IMAP boxes' . ". Here is " . hostname(),
  1896. ) ;
  1897. }elsif( $mysync->{ loaddelay } ) {
  1898. # https://tools.ietf.org/html/rfc2616#section-10.5.4
  1899. # 503 Service Unavailable
  1900. # The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
  1901. $httpheader = $mysync->{cgi}->header(
  1902. -type => 'text/plain',
  1903. -status => '503 Service Unavailable' . ". Be back in $mysync->{ loaddelay } min. Load on " . hostname() . " is $mysync->{ loadavg }",
  1904. ) ;
  1905. }else{
  1906. $httpheader = $mysync->{cgi}->header(
  1907. -type => 'text/plain',
  1908. -status => '200 OK to sync IMAP boxes' . ". Load on " . hostname() . " is $mysync->{ loadavg }",
  1909. -cookie => $cookie,
  1910. ) ;
  1911. }
  1912. output_start( $mysync, $httpheader ) ;
  1913. return ;
  1914. }
  1915. sub cgiload {
  1916. my $mysync = shift ;
  1917. if ( ! under_cgi_context( $mysync ) ) { return ; }
  1918. if ( $mysync->{ abort } ) { return ; } # keep going to abort
  1919. if ( $mysync->{ loaddelay } ) {
  1920. myprint( "Server is on heavy load. Be back in $mysync->{ loaddelay } min. Load is $mysync->{ loadavg }\n") ;
  1921. exit_clean( $mysync, $EX_UNAVAILABLE ) ;
  1922. }
  1923. return ;
  1924. }
  1925. sub tests_set_umask {
  1926. note( 'Entering tests_set_umask()' ) ;
  1927. my $save_umask = umask ;
  1928. my $mysync = {} ;
  1929. if ( 'MSWin32' eq $OSNAME ) {
  1930. is( undef, set_umask( $mysync ), "set_umask: set failure to $UMASK_PARANO on MSWin32" ) ;
  1931. }else{
  1932. is( 1, set_umask( $mysync ), "set_umask: set to $UMASK_PARANO" ) ;
  1933. }
  1934. umask $save_umask ;
  1935. note( 'Leaving tests_set_umask()' ) ;
  1936. return ;
  1937. }
  1938. sub set_umask {
  1939. my $mysync = shift ;
  1940. my $previous_umask = umask_str( ) ;
  1941. my $new_umask = umask_str( $UMASK_PARANO ) ;
  1942. output( $mysync, "Umask set with $new_umask (was $previous_umask)\n" ) ;
  1943. if ( $new_umask eq $UMASK_PARANO ) {
  1944. return 1 ;
  1945. }
  1946. return ;
  1947. }
  1948. sub tests_umask_str {
  1949. note( 'Entering tests_umask_str()' ) ;
  1950. my $save_umask = umask ;
  1951. is( umask_str( ), umask_str( ), 'umask_str: no parameters => idopotent' ) ;
  1952. is( my $save_umask_str = umask_str( ), umask_str( ), 'umask_str: no parameters => idopotent + save' ) ;
  1953. is( '0000', umask_str( q{ } ), 'umask_str: q{ } => 0000' ) ;
  1954. is( '0000', umask_str( q{} ), 'umask_str: q{} => 0000' ) ;
  1955. is( '0000', umask_str( '0000' ), 'umask_str: 0000 => 0000' ) ;
  1956. is( '0000', umask_str( '0' ), 'umask_str: 0 => 0000' ) ;
  1957. is( '0200', umask_str( '0200' ), 'umask_str: 0200 => 0200' ) ;
  1958. is( '0400', umask_str( '0400' ), 'umask_str: 0400 => 0400' ) ;
  1959. is( '0600', umask_str( '0600' ), 'umask_str: 0600 => 0600' ) ;
  1960. SKIP: {
  1961. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests success only for Unix', 6 ) ; }
  1962. is( '0100', umask_str( '0100' ), 'umask_str: 0100 => 0100' ) ;
  1963. is( '0001', umask_str( '0001' ), 'umask_str: 0001 => 0001' ) ;
  1964. is( '0777', umask_str( '0777' ), 'umask_str: 0777 => 0777' ) ;
  1965. is( '0777', umask_str( '00777' ), 'umask_str: 00777 => 0777' ) ;
  1966. is( '0777', umask_str( ' 777 ' ), 'umask_str: 777 => 0777' ) ;
  1967. is( "$UMASK_PARANO", umask_str( $UMASK_PARANO ), "umask_str: UMASK_PARANO $UMASK_PARANO => $UMASK_PARANO" ) ;
  1968. }
  1969. is( $save_umask_str, umask_str( $save_umask_str ), 'umask_str: restore with str' ) ;
  1970. is( $save_umask, umask, 'umask_str: umask is restored, controlled by direct umask' ) ;
  1971. is( $save_umask, umask $save_umask, 'umask_str: umask is restored by direct umask' ) ;
  1972. is( $save_umask, umask, 'umask_str: umask initial controlled by direct umask' ) ;
  1973. note( 'Leaving tests_umask_str()' ) ;
  1974. return ;
  1975. }
  1976. sub umask_str {
  1977. my $value = shift ;
  1978. if ( defined $value ) {
  1979. umask oct( $value ) ;
  1980. }
  1981. my $current = umask ;
  1982. return( sprintf( '%#04o', $current ) ) ;
  1983. }
  1984. sub tests_umask {
  1985. note( 'Entering tests_umask()' ) ;
  1986. my $save_umask ;
  1987. is( umask, umask, 'umask: umask is umask' ) ;
  1988. is( $save_umask = umask, umask, "umask: umask is umask again + save it: $save_umask" ) ;
  1989. is( $save_umask, umask oct(0000), 'umask: umask 0000' ) ;
  1990. is( oct(0000), umask, 'umask: umask is now 0000' ) ;
  1991. is( oct(0000), umask oct(777), 'umask: umask 0777 call, previous 0000' ) ;
  1992. SKIP: {
  1993. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests success only for Unix', 2 ) ; }
  1994. is( oct(777), umask, 'umask: umask is now 0777' ) ;
  1995. is( oct(777), umask $save_umask, "umask: umask $save_umask restore inital value, previous 0777" ) ;
  1996. }
  1997. ok( defined umask $save_umask, "umask: umask $save_umask restore inital value, previous defined" ) ;
  1998. is( $save_umask, umask, 'umask: umask is umask restored' ) ;
  1999. note( 'Leaving tests_umask()' ) ;
  2000. return ;
  2001. }
  2002. sub cgisetcontext {
  2003. my $mysync = shift ;
  2004. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2005. output( $mysync, "Under cgi context\n" ) ;
  2006. set_umask( $mysync ) ;
  2007. # Remove all content in unsafe evaled options
  2008. @regextrans2 = ( ) ;
  2009. @regexflag = ( ) ;
  2010. @regexmess = ( ) ;
  2011. @skipmess = ( ) ;
  2012. @pipemess = ( ) ;
  2013. $delete2foldersonly = undef ;
  2014. $delete2foldersbutnot = undef ;
  2015. $maxlinelengthcmd = undef ;
  2016. # Set safe default values (I hope...)
  2017. $mysync->{pidfile} = 'imapsync.pid' ;
  2018. $mysync->{pidfilelocking} = 1 ;
  2019. $mysync->{errorsmax} = $ERRORS_MAX_CGI ;
  2020. $modulesversion = 0 ;
  2021. $mysync->{releasecheck} = defined $mysync->{releasecheck} ? $mysync->{releasecheck} : 1 ;
  2022. $usecache = 0 ;
  2023. $mysync->{showpasswords} = 0 ;
  2024. $debugimap1 = $debugimap2 = $debugimap = 0 ;
  2025. $reconnectretry1 = $reconnectretry2 = $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  2026. $pipemesscheck = 0 ;
  2027. $mysync->{hashfile} = $CGI_HASHFILE ;
  2028. my $hashsynclocal = hashsynclocal( $mysync ) || die "Can not get hashsynclocal. Exiting\n" ;
  2029. $cgidir = $CGI_TMPDIR_TOP . '/' . $hashsynclocal ;
  2030. -d $cgidir or mkpath $cgidir or die "Can not create $cgidir: $OS_ERROR\n" ;
  2031. chdir $cgidir or die "Can not cd to $cgidir: $OS_ERROR\n" ;
  2032. $mysync->{ tmpdir } = $cgidir ;
  2033. cgioutputenvcontext( $mysync ) ;
  2034. $debug and output( $mysync, 'Current directory is ' . getcwd( ) . "\n" ) ;
  2035. $debug and output( $mysync, 'Real user id is ' . getpwuid_any_os( $REAL_USER_ID ) . " (uid $REAL_USER_ID)\n" ) ;
  2036. $debug and output( $mysync, 'Effective user id is ' . getpwuid_any_os( $EFFECTIVE_USER_ID ). " (euid $EFFECTIVE_USER_ID)\n" ) ;
  2037. # @{ $mysync->{ sigexit } } = ( 'QUIT' ) ;
  2038. # output( $mysync, "Setting the QUIT signal to exit properly\n" ) ;
  2039. return ;
  2040. }
  2041. sub cgioutputenvcontext {
  2042. my $mysync = shift @ARG ;
  2043. for my $envvar ( qw( REMOTE_ADDR REMOTE_HOST HTTP_REFERER HTTP_USER_AGENT SERVER_SOFTWARE SERVER_PORT HTTP_COOKIE ) ) {
  2044. my $envval = $ENV{ $envvar } || q{} ;
  2045. if ( $envval ) { output( $mysync, "$envvar is $envval\n" ) } ;
  2046. }
  2047. return ;
  2048. }
  2049. sub debugsleep {
  2050. my $mysync = shift @ARG ;
  2051. if ( defined $mysync->{debugsleep} ) {
  2052. myprint( "Info: sleeping $mysync->{debugsleep}s\n" ) ;
  2053. sleep $mysync->{debugsleep} ;
  2054. }
  2055. return ;
  2056. }
  2057. sub foldersizes_on_h1h2 {
  2058. myprint( << 'END_SIZE' ) ;
  2059. Folders sizes before the synchronization.
  2060. You can remove foldersizes listings by using "--nofoldersizes" and "--nofoldersizesatend"
  2061. but then you will also loose the ETA (Estimation Time of Arrival) given after each message copy.
  2062. END_SIZE
  2063. ( $h1_nb_msg_start, $h1_bytes_start ) = foldersizes( 'Host1', $imap1, $search1, $sync->{abletosearch1}, @h1_folders_wanted ) ;
  2064. ( $h2_nb_msg_start, $h2_bytes_start ) = foldersizes( 'Host2', $imap2, $search2, $sync->{abletosearch2}, @h2_folders_from_1_wanted ) ;
  2065. if ( not all_defined( $h1_nb_msg_start, $h1_bytes_start, $h2_nb_msg_start, $h2_bytes_start ) ) {
  2066. my $error = "Failure getting foldersizes, ETA and final diff will not be displayed\n" ;
  2067. errors_incr( $sync, $error ) ;
  2068. $foldersizes = 0 ;
  2069. $foldersizesatend = 0 ;
  2070. return ;
  2071. }
  2072. my $h2_bytes_limit = $sync->{h2}->{quota_limit_bytes} || 0 ;
  2073. if ( $h2_bytes_limit and ( $h2_bytes_limit < $h1_bytes_start ) ) {
  2074. my $quota_percent = mysprintf( '%.0f', $NUMBER_100 * $h1_bytes_start / $h2_bytes_limit ) ;
  2075. my $error = "Host2: Quota limit will be exceeded! Over $quota_percent % ( $h1_bytes_start bytes / $h2_bytes_limit bytes )\n" ;
  2076. errors_incr( $sync, $error ) ;
  2077. }
  2078. return ;
  2079. }
  2080. sub total_bytes_max_reached {
  2081. return( 0 ) if not $exitwhenover ;
  2082. if ( $sync->{total_bytes_transferred} >= $exitwhenover ) {
  2083. myprint( "Maximum bytes transferred reached, $sync->{total_bytes_transferred} >= $exitwhenover, ending sync\n" ) ;
  2084. return( 1 ) ;
  2085. }
  2086. }
  2087. sub all_defined {
  2088. if ( not @ARG ) {
  2089. return 0 ;
  2090. }
  2091. foreach my $elem ( @ARG ) {
  2092. if ( not defined $elem ) {
  2093. return 0 ;
  2094. }
  2095. }
  2096. return 1 ;
  2097. }
  2098. sub tests_all_defined {
  2099. note( 'Entering tests_all_defined()' ) ;
  2100. is( 0, all_defined( ), 'all_defined: no param => 0' ) ;
  2101. is( 0, all_defined( () ), 'all_defined: void list => 0' ) ;
  2102. is( 0, all_defined( undef ), 'all_defined: undef => 0' ) ;
  2103. is( 0, all_defined( undef, undef ), 'all_defined: undef => 0' ) ;
  2104. is( 0, all_defined( 1, undef ), 'all_defined: 1 undef => 0' ) ;
  2105. is( 0, all_defined( undef, 1 ), 'all_defined: undef 1 => 0' ) ;
  2106. is( 1, all_defined( 1, 1 ), 'all_defined: 1 1 => 1' ) ;
  2107. is( 1, all_defined( (1, 1) ), 'all_defined: (1 1) => 1' ) ;
  2108. note( 'Leaving tests_all_defined()' ) ;
  2109. return ;
  2110. }
  2111. sub tests_hashsynclocal {
  2112. note( 'Entering tests_hashsynclocal()' ) ;
  2113. my $mysync = {
  2114. host1 => '',
  2115. user1 => '',
  2116. password1 => '',
  2117. host2 => '',
  2118. user2 => '',
  2119. password2 => '',
  2120. } ;
  2121. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: no hashfile name' ) ;
  2122. $mysync->{ hashfile } = '' ;
  2123. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: empty hashfile name' ) ;
  2124. $mysync->{ hashfile } = './noexist/rrr' ;
  2125. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: no exists hashfile dir' ) ;
  2126. SKIP: {
  2127. if ( 'MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) { skip( 'Tests only for non-root Unix', 1 ) ; }
  2128. $mysync->{ hashfile } = '/rrr' ;
  2129. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: permission denied' ) ;
  2130. }
  2131. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'hashsynclocal: mkpath W/tmp/tests/' ) ;
  2132. $mysync->{ hashfile } = 'W/tmp/tests/imapsync_hash' ;
  2133. ok( ! -e 'W/tmp/tests/imapsync_hash' || unlink 'W/tmp/tests/imapsync_hash', 'hashsynclocal: unlink W/tmp/tests/imapsync_hash' ) ;
  2134. ok( ! -e 'W/tmp/tests/imapsync_hash', 'hashsynclocal: verify there is no W/tmp/tests/imapsync_hash' ) ;
  2135. is( 'ecdeb4ede672794d173da4e08c52b8ee19b7d252', hashsynclocal( $mysync, 'mukksyhpmbixkxkpjlqivmlqsulpictj' ), 'hashsynclocal: creating/reading W/tmp/tests/imapsync_hash' ) ;
  2136. # A second time now
  2137. is( 'ecdeb4ede672794d173da4e08c52b8ee19b7d252', hashsynclocal( $mysync ), 'hashsynclocal: reading W/tmp/tests/imapsync_hash second time => same' ) ;
  2138. note( 'Leaving tests_hashsynclocal()' ) ;
  2139. return ;
  2140. }
  2141. sub hashsynclocal {
  2142. my $mysync = shift ;
  2143. my $hashkey = shift ; # Optional, only there for tests
  2144. my $hashfile = $mysync->{ hashfile } ;
  2145. $hashfile = createhashfileifneeded( $hashfile, $hashkey ) ;
  2146. if ( ! $hashfile ) {
  2147. return ;
  2148. }
  2149. $hashkey = firstline( $hashfile ) ;
  2150. if ( ! $hashkey ) {
  2151. myprint( "No hashkey!\n" ) ;
  2152. return ;
  2153. }
  2154. my $hashsynclocal = hashsync( $mysync, $hashkey ) ;
  2155. return( $hashsynclocal ) ;
  2156. }
  2157. sub tests_hashsync {
  2158. note( 'Entering tests_hashsync()' ) ;
  2159. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hashsync( {}, q{} ), 'hashsync: empty args' ) ;
  2160. my $mysync ;
  2161. $mysync->{ host1 } = 'zzz' ;
  2162. is( 'e86a28a3611c1e7bbaf8057cd00ae122781a11fe', hashsync( $mysync, q{} ), 'hashsync: host1 zzz => ' ) ;
  2163. is( 'e86a28a3611c1e7bbaf8057cd00ae122781a11fe', hashsync( $mysync, q{} ), 'hashsync: host1 zzz => ' ) ;
  2164. $mysync->{ host2 } = 'zzz' ;
  2165. is( '15959573e4a86763253a7aedb1a2b0c60d133dc2', hashsync( $mysync, q{} ), 'hashsync: + host2 zzz => ' ) ;
  2166. is( 'b8d4ab541b209c75928528020ca28ee43488bd8f', hashsync( $mysync, 'A' ), 'hashsync: + hashkey A => ' ) ;
  2167. note( 'Leaving tests_hashsync()' ) ;
  2168. return ;
  2169. }
  2170. sub hashsync {
  2171. my $mysync = shift ;
  2172. my $hashkey = shift ;
  2173. my $mystring = join( q{},
  2174. $mysync->{ host1 } || q{},
  2175. $mysync->{ user1 } || q{},
  2176. $mysync->{ password1 } || q{},
  2177. $mysync->{ host2 } || q{},
  2178. $mysync->{ user2 } || q{},
  2179. $mysync->{ password2 } || q{},
  2180. ) ;
  2181. my $hashsync = hmac_sha1_hex( $mystring, $hashkey ) ;
  2182. #myprint( "$hashsync\n" ) ;
  2183. return( $hashsync ) ;
  2184. }
  2185. sub tests_createhashfileifneeded {
  2186. note( 'Entering tests_createhashfileifneeded()' ) ;
  2187. is( undef, createhashfileifneeded( ), 'createhashfileifneeded: no parameters => undef' ) ;
  2188. note( 'Leaving tests_createhashfileifneeded()' ) ;
  2189. return ;
  2190. }
  2191. sub createhashfileifneeded {
  2192. my $hashfile = shift ;
  2193. my $hashkey = shift || rand32( ) ;
  2194. # no name
  2195. if ( ! $hashfile ) {
  2196. return ;
  2197. }
  2198. # already there
  2199. if ( -e -r $hashfile ) {
  2200. return $hashfile ;
  2201. }
  2202. # not creatable
  2203. if ( ! -w dirname( $hashfile ) ) {
  2204. return ;
  2205. }
  2206. # creatable
  2207. open my $FILE_HANDLE, '>', $hashfile
  2208. or do {
  2209. myprint( "Could not open $hashfile for writing. Check permissions or disk space." ) ;
  2210. return ;
  2211. } ;
  2212. myprint( "Writing random hashkey in $hashfile, once for all times\n" ) ;
  2213. print $FILE_HANDLE $hashkey ;
  2214. close $FILE_HANDLE ;
  2215. # Should be there now
  2216. if ( -e -r $hashfile ) {
  2217. return $hashfile ;
  2218. }
  2219. # unknown failure
  2220. return ;
  2221. }
  2222. sub tests_rand32 {
  2223. note( 'Entering tests_rand32()' ) ;
  2224. my $string = rand32( ) ;
  2225. myprint( "$string\n" ) ;
  2226. is( 32, length( $string ), 'rand32: 32 characters long' ) ;
  2227. is( 32, length( rand32( ) ), 'rand32: 32 characters long, another one' ) ;
  2228. note( 'Leaving tests_rand32()' ) ;
  2229. return ;
  2230. }
  2231. sub rand32 {
  2232. my @chars = ( "a".."z" ) ;
  2233. my $string;
  2234. $string .= $chars[rand @chars] for 1..32 ;
  2235. return $string ;
  2236. }
  2237. sub imap_id_stuff {
  2238. my $mysync = shift ;
  2239. if ( not $mysync->{id} ) { return ; } ;
  2240. $mysync->{h1_imap_id} = imap_id( $mysync, $mysync->{imap1}, 'Host1' ) ;
  2241. #myprint( 'Host1: ' . $mysync->{h1_imap_id} ) ;
  2242. $mysync->{h2_imap_id} = imap_id( $mysync, $mysync->{imap2}, 'Host2' ) ;
  2243. #myprint( 'Host2: ' . $mysync->{h2_imap_id} ) ;
  2244. return ;
  2245. }
  2246. sub imap_id {
  2247. my ( $mysync, $imap, $Side ) = @_ ;
  2248. $Side ||= q{} ;
  2249. my $imap_id_response = q{} ;
  2250. if ( not $imap->has_capability( 'ID' ) ) {
  2251. $imap_id_response = 'No ID capability' ;
  2252. myprint( "$Side: No ID capability\n" ) ;
  2253. }else{
  2254. my $id_inp = imapsync_id( $mysync, { side => lc $Side } ) ;
  2255. myprint( "\n$Side: found ID capability. Sending/receiving ID, presented in raw IMAP for now.\n"
  2256. . "In order to avoid sending/receiving ID, use option --noid\n" ) ;
  2257. my $debug_before = $imap->Debug( ) ;
  2258. $imap->Debug( 1 ) ;
  2259. my $id_out = $imap->tag_and_run( 'ID ' . $id_inp ) ;
  2260. #my $id_out = $imap->tag_and_run( 'ID NIL' ) ;
  2261. myprint( "\n" ) ;
  2262. $imap->Debug( $debug_before ) ;
  2263. #$imap_id_response = Data::Dumper->Dump( [ $id_out ], [ 'IMAP_ID' ] ) ;
  2264. }
  2265. return( $imap_id_response ) ;
  2266. }
  2267. sub imapsync_id {
  2268. my $mysync = shift ;
  2269. my $overhashref = shift ;
  2270. # See http://tools.ietf.org/html/rfc2971.html
  2271. my $imapsync_id = { } ;
  2272. my $imapsync_id_lamiral = {
  2273. name => 'imapsync',
  2274. version => imapsync_version( $mysync ),
  2275. os => $OSNAME,
  2276. vendor => 'Gilles LAMIRAL',
  2277. 'support-url' => 'https://imapsync.lamiral.info/',
  2278. # Example of date-time: 19-Sep-2015 08:56:07
  2279. date => date_from_rcs( q{$Date: 2018/05/05 21:10:43 $ } ),
  2280. } ;
  2281. my $imapsync_id_github = {
  2282. name => 'imapsync',
  2283. version => imapsync_version( $mysync ),
  2284. os => $OSNAME,
  2285. vendor => 'github',
  2286. 'support-url' => 'https://github.com/imapsync/imapsync',
  2287. date => date_from_rcs( q{$Date: 2018/05/05 21:10:43 $ } ),
  2288. } ;
  2289. $imapsync_id = $imapsync_id_lamiral ;
  2290. #$imapsync_id = $imapsync_id_github ;
  2291. my %mix = ( %{ $imapsync_id }, %{ $overhashref } ) ;
  2292. my $imapsync_id_str = format_for_imap_arg( \%mix ) ;
  2293. #myprint( "$imapsync_id_str\n" ) ;
  2294. return( $imapsync_id_str ) ;
  2295. }
  2296. sub tests_imapsync_id {
  2297. note( 'Entering tests_imapsync_id()' ) ;
  2298. my $mysync ;
  2299. ok( '("name" "imapsync" "version" "111" "os" "beurk" "vendor" "Gilles LAMIRAL" "support-url" "https://imapsync.lamiral.info/" "date" "22-12-1968" "side" "host1")'
  2300. eq imapsync_id( $mysync,
  2301. {
  2302. version => 111,
  2303. os => 'beurk',
  2304. date => '22-12-1968',
  2305. side => 'host1'
  2306. }
  2307. ),
  2308. 'tests_imapsync_id override'
  2309. ) ;
  2310. note( 'Leaving tests_imapsync_id()' ) ;
  2311. return ;
  2312. }
  2313. sub format_for_imap_arg {
  2314. my $ref = shift ;
  2315. my $string = q{} ;
  2316. my %terms = %{ $ref } ;
  2317. my @terms = ( ) ;
  2318. if ( not ( %terms ) ) { return( 'NIL' ) } ;
  2319. # sort like in RFC then add extra key/values
  2320. foreach my $key ( qw( name version os os-version vendor support-url address date command arguments environment) ) {
  2321. if ( $terms{ $key } ) {
  2322. push @terms, $key, $terms{ $key } ;
  2323. delete $terms{ $key } ;
  2324. }
  2325. }
  2326. push @terms, %terms ;
  2327. $string = '(' . ( join q{ }, map { '"' . $_ . '"' } @terms ) . ')' ;
  2328. return( $string ) ;
  2329. }
  2330. sub tests_format_for_imap_arg {
  2331. note( 'Entering tests_format_for_imap_arg()' ) ;
  2332. ok( 'NIL' eq format_for_imap_arg( { } ), 'format_for_imap_arg empty hash ref' ) ;
  2333. ok( '("name" "toto")' eq format_for_imap_arg( { name => 'toto' } ), 'format_for_imap_arg { name => toto }' ) ;
  2334. ok( '("name" "toto" "key" "val")' eq format_for_imap_arg( { name => 'toto', key => 'val' } ), 'format_for_imap_arg 2 x key val' ) ;
  2335. note( 'Leaving tests_format_for_imap_arg()' ) ;
  2336. return ;
  2337. }
  2338. sub quota {
  2339. my ( $imap, $side, $mysync ) = @_ ;
  2340. my %side = (
  2341. h1 => 'Host1',
  2342. h2 => 'Host2',
  2343. ) ;
  2344. my $Side = $side{ $side } ;
  2345. my $debug_before = $imap->Debug( ) ;
  2346. $imap->Debug( 1 ) ;
  2347. if ( not $imap->has_capability( 'QUOTA' ) ) {
  2348. $imap->Debug( $debug_before ) ;
  2349. return ;
  2350. } ;
  2351. myprint( "\n$Side: found quota, presented in raw IMAP\n" ) ;
  2352. my $getquotaroot = $imap->getquotaroot( 'INBOX' ) ;
  2353. # Gmail INBOX quotaroot is "" but with it Mail::IMAPClient does a literal GETQUOTA {2} \n ""
  2354. #$imap->quota( 'ROOT' ) ;
  2355. #$imap->quota( '""' ) ;
  2356. myprint( "\n" ) ;
  2357. $imap->Debug( $debug_before ) ;
  2358. my $quota_limit_bytes = quota_extract_storage_limit_in_bytes( $getquotaroot ) ;
  2359. my $quota_current_bytes = quota_extract_storage_current_in_bytes( $getquotaroot ) ;
  2360. $mysync->{$side}->{quota_limit_bytes} = $quota_limit_bytes ;
  2361. $mysync->{$side}->{quota_current_bytes} = $quota_current_bytes ;
  2362. my $quota_percent ;
  2363. if ( $quota_limit_bytes > 0 ) {
  2364. $quota_percent = mysprintf( '%.2f', $NUMBER_100 * $quota_current_bytes / $quota_limit_bytes ) ;
  2365. }else{
  2366. $quota_percent = 0 ;
  2367. }
  2368. myprint( "$Side: Quota current storage is $quota_current_bytes bytes. Limit is $quota_limit_bytes bytes. So $quota_percent % full\n" ) ;
  2369. if ( $QUOTA_PERCENT_LIMIT < $quota_percent ) {
  2370. my $error = "$Side: $quota_percent % full: it is time to find a bigger place! ( $quota_current_bytes bytes / $quota_limit_bytes bytes )\n" ;
  2371. errors_incr( $mysync, $error ) ;
  2372. }
  2373. return ;
  2374. }
  2375. sub tests_quota_extract_storage_limit_in_bytes {
  2376. note( 'Entering tests_quota_extract_storage_limit_in_bytes()' ) ;
  2377. my $imap_output = [
  2378. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  2379. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  2380. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  2381. '5 OK Getquotaroot completed.'
  2382. ] ;
  2383. ok( $NUMBER_104_857_600 * $KIBI == quota_extract_storage_limit_in_bytes( $imap_output ), 'quota_extract_storage_limit_in_bytes ') ;
  2384. note( 'Leaving tests_quota_extract_storage_limit_in_bytes()' ) ;
  2385. return ;
  2386. }
  2387. sub quota_extract_storage_limit_in_bytes {
  2388. my $imap_output = shift ;
  2389. my $limit_kb ;
  2390. $limit_kb = ( map { /.*\(\s*STORAGE\s+\d+\s+(\d+)\s*\)/x ? $1 : () } @{ $imap_output } )[0] ;
  2391. $limit_kb ||= 0 ;
  2392. $debug and myprint( "storage_limit_kb = $limit_kb\n" ) ;
  2393. return( $KIBI * $limit_kb ) ;
  2394. }
  2395. sub tests_quota_extract_storage_current_in_bytes {
  2396. note( 'Entering tests_quota_extract_storage_current_in_bytes()' ) ;
  2397. my $imap_output = [
  2398. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  2399. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  2400. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  2401. '5 OK Getquotaroot completed.'
  2402. ] ;
  2403. ok( 1*$KIBI == quota_extract_storage_current_in_bytes( $imap_output ), 'quota_extract_storage_current_in_bytes: 1 => 1024 ') ;
  2404. note( 'Leaving tests_quota_extract_storage_current_in_bytes()' ) ;
  2405. return ;
  2406. }
  2407. sub quota_extract_storage_current_in_bytes {
  2408. my $imap_output = shift ;
  2409. my $current_kb ;
  2410. $current_kb = ( map { /.*\(\s*STORAGE\s+(\d+)\s+\d+\s*\)/x ? $1 : () } @{ $imap_output } )[0] ;
  2411. $current_kb ||= 0 ;
  2412. $debug and myprint( "storage_current_kb = $current_kb\n" ) ;
  2413. return( $KIBI * $current_kb ) ;
  2414. }
  2415. sub automap {
  2416. my ( $mysync ) = @_ ;
  2417. if ( $mysync->{automap} ) {
  2418. myprint( "Turned on automapping folders ( use --noautomap to turn off automapping )\n" ) ;
  2419. }else{
  2420. myprint( "Turned off automapping folders ( use --automap to turn on automapping )\n" ) ;
  2421. return ;
  2422. }
  2423. $mysync->{h1_special} = special_from_folders_hash( $mysync->{imap1}, 'Host1' ) ;
  2424. $mysync->{h2_special} = special_from_folders_hash( $mysync->{imap2}, 'Host2' ) ;
  2425. build_possible_special( $mysync ) ;
  2426. build_guess_special( $mysync ) ;
  2427. build_automap( $mysync ) ;
  2428. return ;
  2429. }
  2430. sub build_guess_special {
  2431. my ( $mysync ) = shift ;
  2432. foreach my $h1_fold ( sort keys %{ $mysync->{h1_folders_all} } ) {
  2433. my $special = guess_special( $h1_fold, $mysync->{possible_special}, $mysync->{h1_prefix} ) ;
  2434. if ( $special ) {
  2435. $mysync->{h1_special_guessed}{$h1_fold} = $special ;
  2436. my $already_guessed = $mysync->{h1_special_guessed}{$special} ;
  2437. if ( $already_guessed ) {
  2438. myprint( "Host1: $h1_fold not $special because set to $already_guessed\n" ) ;
  2439. }else{
  2440. $mysync->{h1_special_guessed}{$special} = $h1_fold ;
  2441. }
  2442. }
  2443. }
  2444. foreach my $h2_fold ( sort keys %{ $mysync->{h2_folders_all} } ) {
  2445. my $special = guess_special( $h2_fold, $mysync->{possible_special}, $mysync->{h2_prefix} ) ;
  2446. if ( $special ) {
  2447. $mysync->{h2_special_guessed}{$h2_fold} = $special ;
  2448. my $already_guessed = $mysync->{h2_special_guessed}{$special} ;
  2449. if ( $already_guessed ) {
  2450. myprint( "Host2: $h2_fold not $special because set to $already_guessed\n" ) ;
  2451. }else{
  2452. $mysync->{h2_special_guessed}{$special} = $h2_fold ;
  2453. }
  2454. }
  2455. }
  2456. return ;
  2457. }
  2458. sub guess_special {
  2459. my( $folder, $possible_special_ref, $prefix ) = @_ ;
  2460. my $folder_no_prefix = $folder ;
  2461. $folder_no_prefix =~ s/\Q${prefix}\E//xms ;
  2462. #$debug and myprint( "folder_no_prefix: $folder_no_prefix\n" ) ;
  2463. my $guess_special = $possible_special_ref->{ $folder }
  2464. || $possible_special_ref->{ $folder_no_prefix }
  2465. || q{} ;
  2466. return( $guess_special ) ;
  2467. }
  2468. sub tests_guess_special {
  2469. note( 'Entering tests_guess_special()' ) ;
  2470. my $possible_special_ref = build_possible_special( my $mysync ) ;
  2471. ok( '\Sent' eq guess_special( 'Sent', $possible_special_ref, q{} ) ,'guess_special: Sent => \Sent' ) ;
  2472. ok( q{} eq guess_special( 'Blabla', $possible_special_ref, q{} ) ,'guess_special: Blabla => q{}' ) ;
  2473. ok( '\Sent' eq guess_special( 'INBOX.Sent', $possible_special_ref, 'INBOX.' ) ,'guess_special: INBOX.Sent => \Sent' ) ;
  2474. ok( '\Sent' eq guess_special( 'IN BOX.Sent', $possible_special_ref, 'IN BOX.' ) ,'guess_special: IN BOX.Sent => \Sent' ) ;
  2475. note( 'Leaving tests_guess_special()' ) ;
  2476. return ;
  2477. }
  2478. sub build_automap {
  2479. my $mysync = shift ;
  2480. $debug and myprint( "Entering build_automap\n" ) ;
  2481. foreach my $h1_fold ( @{ $mysync->{h1_folders_wanted} } ) {
  2482. my $h2_fold ;
  2483. my $h1_special = $mysync->{h1_special}{$h1_fold} ;
  2484. my $h1_special_guessed = $mysync->{h1_special_guessed}{$h1_fold} ;
  2485. # Case 1: special on both sides.
  2486. if ( $h1_special
  2487. and exists $mysync->{h2_special}{$h1_special} ) {
  2488. $h2_fold = $mysync->{h2_special}{$h1_special} ;
  2489. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  2490. next ;
  2491. }
  2492. # Case 2: special on host1, not on host2
  2493. if ( $h1_special
  2494. and ( not exists $mysync->{h2_special}{$h1_special} )
  2495. and ( exists $mysync->{h2_special_guessed}{$h1_special} )
  2496. ) {
  2497. # special_guessed on host2
  2498. $h2_fold = $mysync->{h2_special_guessed}{$h1_special} ;
  2499. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  2500. next ;
  2501. }
  2502. # Case 3: no special on host1, special on host2
  2503. if ( ( not $h1_special )
  2504. and ( $h1_special_guessed )
  2505. and ( exists $mysync->{h2_special}{$h1_special_guessed} )
  2506. ) {
  2507. $h2_fold = $mysync->{h2_special}{$h1_special_guessed} ;
  2508. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  2509. next ;
  2510. }
  2511. # Case 4: no special on both sides.
  2512. if ( ( not $h1_special )
  2513. and ( $h1_special_guessed )
  2514. and ( not exists $mysync->{h2_special}{$h1_special_guessed} )
  2515. and ( exists $mysync->{h2_special_guessed}{$h1_special_guessed} )
  2516. ) {
  2517. $h2_fold = $mysync->{h2_special_guessed}{$h1_special_guessed} ;
  2518. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  2519. next ;
  2520. }
  2521. }
  2522. return( $mysync->{f1f2auto} ) ;
  2523. }
  2524. # I will not add what there is at:
  2525. # http://stackoverflow.com/questions/2185391/localized-gmail-imap-folders/2185548#2185548
  2526. # because it works well without
  2527. sub build_possible_special {
  2528. my $mysync = shift ;
  2529. my $possible_special = { } ;
  2530. # All|Archive|Drafts|Flagged|Junk|Sent|Trash
  2531. $possible_special->{'\All'} = [ 'All', 'All Messages', '&BBIEQQQ1-' ] ;
  2532. $possible_special->{'\Archive'} = [ 'Archive', 'Archives', '&BBAEQARFBDgEMg-' ] ;
  2533. $possible_special->{'\Drafts'} = [ 'Drafts', 'DRAFTS', '&BCcENQRABD0EPgQyBDgEOgQ4-', 'Szkice', 'Wersje robocze' ] ;
  2534. $possible_special->{'\Flagged'} = [ 'Flagged', 'Starred', '&BB8EPgQ8BDUERwQ1BD0EPQRLBDU-' ] ;
  2535. $possible_special->{'\Junk'} = [ 'Junk', 'Spam', 'SPAM', '&BCEEPwQwBDw-', 'Potwierdzony spam', 'Wiadomo&AVs-ci-&AVs-mieci' ] ;
  2536. $possible_special->{'\Sent'} = [ 'Sent', 'Sent Messages', 'Sent Items',
  2537. 'Gesendete Elemente', 'Gesendete Objekte',
  2538. '&AMk-l&AOk-ments envoy&AOk-s', 'Envoy&AOk-', 'Objets envoy&AOk-s',
  2539. 'Elementos enviados',
  2540. '&kAFP4W4IMH8wojCkMMYw4A-',
  2541. '&BB4EQgQ,BEAEMAQyBDsENQQ9BD0ESwQ1-',
  2542. 'Elementy wys&AUI-ane'] ;
  2543. $possible_special->{'\Trash'} = [ 'Trash', 'TRASH', '&BCMENAQwBDsENQQ9BD0ESwQ1-', '&BBoEPgRABDcEOAQ9BDA-', 'Kosz', 'Deleted Items' ] ;
  2544. foreach my $special ( qw( \All \Archive \Drafts \Flagged \Junk \Sent \Trash ) ){
  2545. foreach my $possible_folder ( @{ $possible_special->{$special} } ) {
  2546. $possible_special->{ $possible_folder } = $special ;
  2547. } ;
  2548. }
  2549. $mysync->{possible_special} = $possible_special ;
  2550. $debug and myprint( Data::Dumper->Dump( [ $possible_special ], [ 'possible_special' ] ) ) ;
  2551. return( $possible_special ) ;
  2552. }
  2553. sub special_from_folders_hash {
  2554. my ( $imap, $side ) = @_ ;
  2555. my %special = ( ) ;
  2556. if ( ! defined $imap ) { return ; }
  2557. $side = defined $side ? $side : 'Host?' ;
  2558. if ( ! $imap->can( 'folders_hash' ) ) {
  2559. my $error = "$side: To have automagic rfc6154 folder mapping, upgrade Mail::IMAPClient >= 3.34\n" ;
  2560. errors_incr( $sync, $error ) ;
  2561. return( \%special ) ; # empty hash ref
  2562. }
  2563. my $folders_hash = $imap->folders_hash( ) ;
  2564. foreach my $fhash (@{ $folders_hash } ) {
  2565. my @special = grep { /\\(?:All|Archive|Drafts|Flagged|Junk|Sent|Trash)/x } @{ $fhash->{attrs} } ;
  2566. if ( @special ) {
  2567. my $special = $special[0] ; # keep first one. Could be not very good.
  2568. if ( exists $special{ $special } ) {
  2569. myprintf( "%s: special %-20s = %s already assigned to %s\n",
  2570. $side, $fhash->{name}, join( q{ }, @special ), $special{ $special } ) ;
  2571. }else{
  2572. myprintf( "%s: special %-20s = %s\n",
  2573. $side, $fhash->{name}, join( q{ }, @special ) ) ;
  2574. $special{ $special } = $fhash->{name} ;
  2575. $special{ $fhash->{name} } = $special ; # double entry value => key
  2576. }
  2577. }
  2578. }
  2579. myprint( "\n" ) if ( %special ) ;
  2580. return( \%special ) ;
  2581. }
  2582. sub tests_special_from_folders_hash {
  2583. note( 'Entering tests_special_from_folders_hash()' ) ;
  2584. require Test::MockObject ;
  2585. my $imapT = Test::MockObject->new( ) ;
  2586. is( undef, special_from_folders_hash( ), 'special_from_folders_hash: no args' ) ;
  2587. is_deeply( {}, special_from_folders_hash( $imapT ), 'special_from_folders_hash: $imap void' ) ;
  2588. $imapT->mock( 'folders_hash', sub { return( [ { name => 'Sent', attrs => [ '\Sent' ] } ] ) } ) ;
  2589. is_deeply( { Sent => '\Sent', '\Sent' => 'Sent' }, special_from_folders_hash( $imapT ), 'special_from_folders_hash: $imap \Sent' ) ;
  2590. note( 'Leaving tests_special_from_folders_hash()' ) ;
  2591. return( ) ;
  2592. }
  2593. sub errors_incr {
  2594. my ( $mysync, @error ) = @ARG ;
  2595. $sync->{nb_errors}++ ;
  2596. if ( @error ) {
  2597. errors_log( $mysync, @error ) ;
  2598. myprint( @error ) ;
  2599. }
  2600. $mysync->{errorsmax} ||= $ERRORS_MAX ;
  2601. if ( $sync->{nb_errors} >= $mysync->{errorsmax} ) {
  2602. myprint( "Maximum number of errors $mysync->{errorsmax} reached ( you can change $mysync->{errorsmax} to any value, for example 100 with --errorsmax 100 ). Exiting.\n" ) ;
  2603. if ( $mysync->{errorsdump} ) {
  2604. myprint( errorsdump( $sync->{nb_errors}, errors_log( $mysync ) ) ) ;
  2605. # again since errorsdump( ) can be very verbose and masquerade previous warning
  2606. myprint( "Maximum number of errors $mysync->{errorsmax} reached ( you can change $mysync->{errorsmax} to any value, for example 100 with --errorsmax 100 ). Exiting.\n" ) ;
  2607. }
  2608. exit_clean( $mysync, $EXIT_WITH_ERRORS_MAX ) ;
  2609. }
  2610. return ;
  2611. }
  2612. sub errors_log {
  2613. my ( $mysync, @error ) = @ARG ;
  2614. if ( ! $mysync->{errors_log} ) {
  2615. $mysync->{errors_log} = [] ;
  2616. }
  2617. if ( @error ) {
  2618. push @{ $mysync->{errors_log} }, join( q{}, @error ) ;
  2619. }
  2620. if ( @{ $mysync->{errors_log} } ) {
  2621. return @{ $mysync->{errors_log} } ;
  2622. }
  2623. else {
  2624. return ;
  2625. }
  2626. }
  2627. sub tests_errors_log {
  2628. note( 'Entering tests_errors_log()' ) ;
  2629. note( 'Leaving tests_errors_log()' ) ;
  2630. return ;
  2631. }
  2632. sub errorsdump {
  2633. my( $nb_errors, @errors_log ) = @ARG ;
  2634. my $error_num = 0 ;
  2635. my $errors_list = q{} ;
  2636. if ( @errors_log ) {
  2637. $errors_list = "++++ Listing $nb_errors errors encountered during the sync ( avoid this listing with --noerrorsdump ).\n" ;
  2638. foreach my $error ( @errors_log ) {
  2639. $error_num++ ;
  2640. $errors_list .= "Err $error_num/$nb_errors: $error" ;
  2641. }
  2642. }
  2643. return( $errors_list ) ;
  2644. }
  2645. sub tests_live_result {
  2646. note( 'Entering tests_live_result()' ) ;
  2647. my $nb_errors = shift ;
  2648. if ( $nb_errors ) {
  2649. myprint( "Live tests failed with $nb_errors errors\n" ) ;
  2650. } else {
  2651. myprint( "Live tests ended successfully\n" ) ;
  2652. }
  2653. note( 'Leaving tests_live_result()' ) ;
  2654. return ;
  2655. }
  2656. sub foldersizesatend {
  2657. timenext( ) ;
  2658. return if ( $imap1->IsUnconnected( ) ) ;
  2659. return if ( $imap2->IsUnconnected( ) ) ;
  2660. # Get all folders on host2 again since new were created
  2661. @h2_folders_all = sort $imap2->folders();
  2662. for ( @h2_folders_all ) {
  2663. $h2_folders_all{ $_ } = 1 ;
  2664. $h2_folders_all_UPPER{ uc $_ } = 1 ;
  2665. } ;
  2666. ( $h1_nb_msg_end, $h1_bytes_end ) = foldersizes( 'Host1', $imap1, $search1, $sync->{abletosearch1}, @h1_folders_wanted ) ;
  2667. ( $h2_nb_msg_end, $h2_bytes_end ) = foldersizes( 'Host2', $imap2, $search2, $sync->{abletosearch2}, @h2_folders_from_1_wanted ) ;
  2668. if ( not all_defined( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end ) ) {
  2669. my $error = "Failure getting foldersizes, final differences will not be calculated\n" ;
  2670. errors_incr( $sync, $error ) ;
  2671. }
  2672. return ;
  2673. }
  2674. sub size_filtered_flag {
  2675. my $h1_size = shift ;
  2676. if (defined $maxsize and $h1_size >= $maxsize) {
  2677. return( 1 ) ;
  2678. }
  2679. if (defined $minsize and $h1_size <= $minsize) {
  2680. return( 1 ) ;
  2681. }
  2682. return( 0 ) ;
  2683. }
  2684. sub sync_flags_fir {
  2685. my ( $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) = @_ ;
  2686. if ( not defined $h1_msg ) { return } ;
  2687. if ( not defined $h2_msg ) { return } ;
  2688. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} ;
  2689. return if size_filtered_flag( $h1_size ) ;
  2690. # used cached flag values for efficiency
  2691. my $h1_flags = $h1_fir_ref->{ $h1_msg }->{ 'FLAGS' } || q{} ;
  2692. my $h2_flags = $h2_fir_ref->{ $h2_msg }->{ 'FLAGS' } || q{} ;
  2693. sync_flags( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  2694. return ;
  2695. }
  2696. sub sync_flags_after_copy {
  2697. my( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $permanentflags2 ) = @_ ;
  2698. my @h2_flags = $imap2->flags( $h2_msg ) ;
  2699. my $h2_flags = "@h2_flags" ;
  2700. ( $debug or $debugflags ) and myprint( "Host2 flags before resync by STORE on msg $h2_msg: $h2_flags\n" ) ;
  2701. sync_flags( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  2702. return ;
  2703. }
  2704. sub sync_flags {
  2705. my( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) = @_ ;
  2706. ( $debug or $debugflags ) and
  2707. myprint( "Host1: flags init msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  2708. $h1_flags = flags_for_host2( $h1_flags, $permanentflags2 ) ;
  2709. $h2_flags = flagscase( $h2_flags ) ;
  2710. ( $debug or $debugflags ) and
  2711. myprint( "Host1 flags filt msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  2712. # compare flags - set flags if there a difference
  2713. my @h1_flags = sort split(q{ }, $h1_flags );
  2714. my @h2_flags = sort split(q{ }, $h2_flags );
  2715. my $diff = compare_lists( \@h1_flags, \@h2_flags );
  2716. $diff and ( $debug or $debugflags )
  2717. and myprint( "Host2 flags msg $h2_fold/$h2_msg replacing h2 flags( $h2_flags ) with h1 flags( $h1_flags )\n" ) ;
  2718. # This sets flags so flags can be removed with this
  2719. # When you remove a \Seen flag on host1 you want to it
  2720. # to be removed on host2. Just add flags is not what
  2721. # we need most of the time.
  2722. if ( not $sync->{dry} and $diff and not $imap2->store( $h2_msg, "FLAGS.SILENT (@h1_flags)" ) ) {
  2723. my $error_msg = join q{}, "Host2 flags msg $h2_fold/$h2_msg could not add flags [@h1_flags]: ",
  2724. $imap2->LastError || q{}, "\n" ;
  2725. errors_incr( $sync, $error_msg ) ;
  2726. }
  2727. return ;
  2728. }
  2729. sub _filter {
  2730. my $str = shift or return q{} ;
  2731. my $sz = $SIZE_MAX_STR ;
  2732. my $len = length $str ;
  2733. if ( not $debug and $len > $sz*2 ) {
  2734. my $beg = substr $str, 0, $sz ;
  2735. my $end = substr $str, -$sz, $sz ;
  2736. $str = $beg . '...' . $end ;
  2737. }
  2738. $str =~ s/\012?\015$//x ;
  2739. return "(len=$len) " . $str ;
  2740. }
  2741. sub lost_connection {
  2742. my( $imap, $error_message ) = @_;
  2743. if ( $imap->IsUnconnected( ) ) {
  2744. $sync->{nb_errors}++ ;
  2745. my $lcomm = $imap->LastIMAPCommand || q{} ;
  2746. my $einfo = $imap->LastError || @{$imap->History}[$LAST] || q{} ;
  2747. # if string is long try reduce to a more reasonable size
  2748. $lcomm = _filter( $lcomm ) ;
  2749. $einfo = _filter( $einfo ) ;
  2750. myprint( "Failure: last command: $lcomm\n") if ($debug && $lcomm) ;
  2751. myprint( "Failure: lost connection $error_message: ", $einfo, "\n") ;
  2752. return( 1 ) ;
  2753. }
  2754. else{
  2755. return( 0 ) ;
  2756. }
  2757. }
  2758. sub tests_max {
  2759. note( 'Entering tests_max()' ) ;
  2760. is( 0, max( 0 ), 'max 0 => 0' ) ;
  2761. is( 1, max( 1 ), 'max 1 => 1' ) ;
  2762. is( $MINUS_ONE, max( $MINUS_ONE ), 'max -1 => -1') ;
  2763. is( undef, max( ), 'max no arg => undef' ) ;
  2764. is( $NUMBER_100, max( 1, $NUMBER_100 ), 'max 1 100 => 100' ) ;
  2765. is( $NUMBER_100, max( $NUMBER_100, 1 ), 'max 100 1 => 100' ) ;
  2766. is( $NUMBER_100, max( $NUMBER_100, $NUMBER_42, 1 ), 'max 100 42 1 => 100' ) ;
  2767. is( $NUMBER_100, max( $NUMBER_100, '42', 1 ), 'max 100 42 1 => 100' ) ;
  2768. is( $NUMBER_100, max( '100', '42', 1 ), 'max 100 42 1 => 100' ) ;
  2769. is( $NUMBER_100, max( $NUMBER_100, 'haha', 1 ), 'max 100 haha 1 => 100') ;
  2770. is( $NUMBER_100, max( 'bb', $NUMBER_100, 'haha' ), 'max bb 100 haha => 100') ;
  2771. is( $MINUS_ONE, max( q{}, $MINUS_ONE, 'haha' ), 'max "" -1 haha => -1') ;
  2772. is( $MINUS_ONE, max( q{}, $MINUS_ONE, $MINUS_TWO ), 'max "" -1 -2 => -1') ;
  2773. is( $MINUS_ONE, max( 'haha', $MINUS_ONE, $MINUS_TWO ), 'max haha -1 -2 => -1') ;
  2774. is( 1, max( $MINUS_ONE, 1 ), 'max -1 1 => 1') ;
  2775. is( 1, max( undef, 1 ), 'max undef 1 => 1' ) ;
  2776. is( 0, max( undef, 0 ), 'max undef 0 => 0' ) ;
  2777. is( 'haha', max( 'haha' ), 'max haha => haha') ;
  2778. is( 'bb', max( 'aa', 'bb' ), 'max aa bb => bb') ;
  2779. is( 'bb', max( 'bb', 'aa' ), 'max bb aa => bb') ;
  2780. is( 'bb', max( 'bb', 'aa', 'bb' ), 'max bb aa bb => bb') ;
  2781. note( 'Leaving tests_max()' ) ;
  2782. return ;
  2783. }
  2784. sub max {
  2785. my @list = @_ ;
  2786. return( undef ) if ( 0 == scalar @list ) ;
  2787. my( @numbers, @notnumbers ) ;
  2788. foreach my $item ( @list ) {
  2789. if ( is_number( $item ) ) {
  2790. push @numbers, $item ;
  2791. }else{
  2792. push @notnumbers, $item ;
  2793. }
  2794. }
  2795. my @sorted ;
  2796. if ( @numbers ) {
  2797. @sorted = sort { $a <=> $b } @numbers ;
  2798. }elsif( @notnumbers ) {
  2799. @sorted = sort { $a cmp $b } @notnumbers ;
  2800. }else{
  2801. return ;
  2802. }
  2803. return( pop @sorted ) ;
  2804. }
  2805. sub tests_is_number {
  2806. ok( ! is_number( ), 'is_number: no args => undef ' ) ;
  2807. ok( is_number( 1 ), 'is_number: 1 => 1' ) ;
  2808. ok( is_number( 1.1 ), 'is_number: 1.1 => 1' ) ;
  2809. ok( is_number( 0 ), 'is_number: 0 => 1' ) ;
  2810. ok( is_number( -1 ), 'is_number: -1 => 1' ) ;
  2811. ok( ! is_number( 1.1.1 ), 'is_number: 1.1.1 => no' ) ;
  2812. ok( ! is_number( q{} ), 'is_number: q{} => no' ) ;
  2813. ok( ! is_number( 'haha' ), 'is_number: haha => no' ) ;
  2814. ok( ! is_number( '0haha' ), 'is_number: 0haha => no' ) ;
  2815. ok( ! is_number( '2haha' ), 'is_number: 2haha => no' ) ;
  2816. ok( ! is_number( 'haha2' ), 'is_number: haha2 => no' ) ;
  2817. return ;
  2818. }
  2819. sub is_number {
  2820. my $item = shift ;
  2821. if ( ! defined $item ) { return ; }
  2822. if ( $item =~ /\A$RE{num}{real}\Z/ ) {
  2823. return 1 ;
  2824. }
  2825. return ;
  2826. }
  2827. sub tests_min {
  2828. note( 'Entering tests_min()' ) ;
  2829. is( 0, min( 0 ), 'min 0 => 0' ) ;
  2830. is( 1, min( 1 ), 'min 1 => 1' ) ;
  2831. is( $MINUS_ONE, min( $MINUS_ONE ), 'min -1 => -1' ) ;
  2832. is( undef, min( ), 'min no arg => undef' ) ;
  2833. is( 1, min( 1, $NUMBER_100 ), 'min 1 100 => 1' ) ;
  2834. is( 1, min( $NUMBER_100, 1 ), 'min 100 1 => 1' ) ;
  2835. is( 1, min( $NUMBER_100, $NUMBER_42, 1 ), 'min 100 42 1 => 1' ) ;
  2836. is( 1, min( $NUMBER_100, '42', 1 ), 'min 100 42 1 => 1' ) ;
  2837. is( 1, min( '100', '42', 1 ), 'min 100 42 1 => 1' ) ;
  2838. is( 1, min( $NUMBER_100, 'haha', 1 ), 'min 100 haha 1 => 1') ;
  2839. is( $MINUS_ONE, min( $MINUS_ONE, 1 ), 'min -1 1 => -1') ;
  2840. is( 1, min( undef, 1 ), 'min undef 1 => 1' ) ;
  2841. is( 0, min( undef, 0 ), 'min undef 0 => 0' ) ;
  2842. is( 1, min( undef, 1 ), 'min undef 1 => 1' ) ;
  2843. is( 0, min( undef, 2, 0, 1 ), 'min undef, 2, 0, 1 => 0' ) ;
  2844. is( 'haha', min( 'haha' ), 'min haha => haha') ;
  2845. is( 'aa', min( 'aa', 'bb' ), 'min aa bb => aa') ;
  2846. is( 'aa', min( 'bb', 'aa' ), 'min bb aa bb => aa') ;
  2847. is( 'aa', min( 'bb', 'aa', 'bb' ), 'min bb aa bb => aa') ;
  2848. note( 'Leaving tests_min()' ) ;
  2849. return ;
  2850. }
  2851. sub min {
  2852. my @list = @_ ;
  2853. return( undef ) if ( 0 == scalar @list ) ;
  2854. my( @numbers, @notnumbers ) ;
  2855. foreach my $item ( @list ) {
  2856. if ( is_number( $item ) ) {
  2857. push @numbers, $item ;
  2858. }else{
  2859. push @notnumbers, $item ;
  2860. }
  2861. }
  2862. my @sorted ;
  2863. if ( @numbers ) {
  2864. @sorted = sort { $a <=> $b } @numbers ;
  2865. }elsif( @notnumbers ) {
  2866. @sorted = sort { $a cmp $b } @notnumbers ;
  2867. }else{
  2868. return ;
  2869. }
  2870. return( shift @sorted ) ;
  2871. }
  2872. sub check_lib_version {
  2873. $debug and myprint( "IMAPClient $Mail::IMAPClient::VERSION\n" ) ;
  2874. if ( '2.2.9' eq $Mail::IMAPClient::VERSION ) {
  2875. myprint( "imapsync no longer supports Mail::IMAPClient 2.2.9, upgrade it\n" ) ;
  2876. return 0 ;
  2877. }
  2878. else{
  2879. # 3.x.x is no longer buggy with imapsync.
  2880. # 3.30 or currently superior is imposed in the Perl "use Mail::IMAPClient line".
  2881. return 1 ;
  2882. }
  2883. return ;
  2884. }
  2885. sub module_version_str {
  2886. my( $module_name, $module_version ) = @_ ;
  2887. my $str = mysprintf( "%-20s %s\n", $module_name, $module_version ) ;
  2888. return( $str ) ;
  2889. }
  2890. sub modulesversion {
  2891. my @list_version;
  2892. my %modulesversion = (
  2893. 'Authen::NTLM' => sub { $Authen::NTLM::VERSION },
  2894. 'Compress::Zlib' => sub { $Compress::Zlib::VERSION },
  2895. 'Crypt::OpenSSL::RSA' => sub { $Crypt::OpenSSL::RSA::VERSION },
  2896. 'Data::Uniqid' => sub { $Data::Uniqid::VERSION },
  2897. 'Digest::HMAC_MD5' => sub { $Digest::HMAC_MD5::VERSION },
  2898. 'Digest::HMAC_SHA1' => sub { $Digest::HMAC_SHA1::VERSION },
  2899. 'Digest::MD5' => sub { $Digest::MD5::VERSION },
  2900. 'File::Copy::Recursive' => sub { $File::Copy::Recursive::VERSION },
  2901. 'File::Spec' => sub { $File::Spec::VERSION },
  2902. 'Getopt::Long' => sub { $Getopt::Long::VERSION },
  2903. 'HTML::Entities' => sub { $HTML::Entities::VERSION },
  2904. 'IO::Socket::INET6' => sub { $IO::Socket::INET6::VERSION },
  2905. 'IO::Socket::INET' => sub { $IO::Socket::INET::VERSION },
  2906. 'IO::Socket::SSL' => sub { $IO::Socket::SSL::VERSION },
  2907. 'IO::Socket' => sub { $IO::Socket::VERSION },
  2908. 'IO::Tee' => sub { $IO::Tee::VERSION },
  2909. 'JSON' => sub { $JSON::VERSION },
  2910. 'JSON::WebToken' => sub { $JSON::WebToken::VERSION },
  2911. 'LWP' => sub { $LWP::VERSION },
  2912. 'Mail::IMAPClient' => sub { $Mail::IMAPClient::VERSION },
  2913. 'Net::Ping' => sub { $Net::Ping::VERSION },
  2914. 'Net::SSLeay' => sub { $Net::SSLeay::VERSION },
  2915. 'Term::ReadKey' => sub { $Term::ReadKey::VERSION },
  2916. 'Test::MockObject' => sub { $Test::MockObject::VERSION },
  2917. 'Time::HiRes' => sub { $Time::HiRes::VERSION },
  2918. 'Unicode::String' => sub { $Unicode::String::VERSION },
  2919. 'URI::Escape' => sub { $URI::Escape::VERSION },
  2920. #'Lalala' => sub { $Lalala::VERSION },
  2921. ) ;
  2922. foreach my $module_name ( sort keys %modulesversion ) {
  2923. # trick from http://www.perlmonks.org/?node_id=152122
  2924. my $file_name = $module_name . '.pm' ;
  2925. $file_name =~s,::,/,xmgs; # Foo::Bar::Baz => Foo/Bar/Baz.pm
  2926. my $v ;
  2927. eval {
  2928. require $file_name ;
  2929. $v = defined $modulesversion{ $module_name } ? $modulesversion{ $module_name }->() : q{?} ;
  2930. } or $v = q{Not installed} ;
  2931. push @list_version, module_version_str( $module_name, $v ) ;
  2932. }
  2933. return( @list_version ) ;
  2934. }
  2935. # Construct a command line copy with passwords replaced by MASKED.
  2936. sub command_line_nopassword {
  2937. my @argv = @_ ;
  2938. my @argv_nopassword ;
  2939. return( "@argv" ) if $sync->{showpasswords} ;
  2940. while ( @argv ) {
  2941. my $arg = shift @argv ; # option name or value
  2942. if ( $arg =~ m/-password[12]/x ) {
  2943. shift @argv ; # password value
  2944. push @argv_nopassword, $arg, 'MASKED' ; # option name and fake value
  2945. }else{
  2946. push @argv_nopassword, $arg ; # same option or value
  2947. }
  2948. }
  2949. return("@argv_nopassword") ;
  2950. }
  2951. sub tests_command_line_nopassword {
  2952. note( 'Entering tests_command_line_nopassword()' ) ;
  2953. ok(q{} eq command_line_nopassword(), 'command_line_nopassword void');
  2954. ok('--blabla' eq command_line_nopassword('--blabla'), 'command_line_nopassword --blabla');
  2955. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  2956. ok('--password1 MASKED' eq command_line_nopassword(qw{ --password1 secret1}), 'command_line_nopassword --password1');
  2957. ok('--blabla --password1 MASKED --blibli'
  2958. eq command_line_nopassword(qw{ --blabla --password1 secret1 --blibli }), 'command_line_nopassword --password1 --blibli');
  2959. $sync->{showpasswords} = 1 ;
  2960. ok(q{} eq command_line_nopassword(), 'command_line_nopassword void');
  2961. ok('--blabla' eq command_line_nopassword('--blabla'), 'command_line_nopassword --blabla');
  2962. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  2963. ok('--password1 secret1' eq command_line_nopassword(qw{ --password1 secret1}), 'command_line_nopassword --password1');
  2964. ok('--blabla --password1 secret1 --blibli'
  2965. eq command_line_nopassword(qw{ --blabla --password1 secret1 --blibli }), 'command_line_nopassword --password1 --blibli');
  2966. note( 'Leaving tests_command_line_nopassword()' ) ;
  2967. return ;
  2968. }
  2969. sub ask_for_password {
  2970. my ( $user, $host ) = @ARG ;
  2971. myprint( "What's the password for $user" . '@' . "$host? (not visible while you type, then enter RETURN) " ) ;
  2972. Term::ReadKey::ReadMode( 2 ) ;
  2973. my $password = <STDIN> ;
  2974. chomp $password ;
  2975. myprint( "\nGot it\n" ) ;
  2976. Term::ReadKey::ReadMode( 0 ) ;
  2977. return $password ;
  2978. }
  2979. # Have to refactor get_password1() get_password2()
  2980. # to have only get_password() and two calls
  2981. sub get_password1 {
  2982. my $mysync = shift ;
  2983. $mysync->{password1}
  2984. || $passfile1
  2985. || 'PREAUTH' eq $authmech1
  2986. || 'EXTERNAL' eq $authmech1
  2987. || $ENV{IMAPSYNC_PASSWORD1}
  2988. || do {
  2989. myprint( << 'FIN_PASSFILE' ) ;
  2990. If you are afraid of giving password on the command line arguments, you can put the
  2991. password of user1 in a file named file1 and use "--passfile1 file1" instead of typing it.
  2992. Then give this file restrictive permissions with the command "chmod 600 file1".
  2993. An other solution is to set the environment variable IMAPSYNC_PASSWORD1
  2994. FIN_PASSFILE
  2995. $mysync->{password1} = ask_for_password( $authuser1 || $mysync->{user1}, $mysync->{host1} ) ;
  2996. } ;
  2997. if ( defined $passfile1 ) {
  2998. if ( ! -e -r $passfile1 ) {
  2999. myprint( "Failure: file from parameter --passfile1 $passfile1 does not exist or is not readable\n" ) ;
  3000. exit_clean( $mysync, $EX_NOINPUT ) ;
  3001. }
  3002. # passfile1 readable
  3003. $mysync->{password1} = firstline ( $passfile1 ) ;
  3004. return ;
  3005. }
  3006. if ( $ENV{IMAPSYNC_PASSWORD1} ) {
  3007. $mysync->{password1} = $ENV{IMAPSYNC_PASSWORD1} ;
  3008. return ;
  3009. }
  3010. return ;
  3011. }
  3012. sub get_password2 {
  3013. my $mysync = shift ;
  3014. $mysync->{password2}
  3015. || $passfile2
  3016. || 'PREAUTH' eq $authmech2
  3017. || 'EXTERNAL' eq $authmech2
  3018. || $ENV{IMAPSYNC_PASSWORD2}
  3019. || do {
  3020. myprint( << 'FIN_PASSFILE' ) ;
  3021. If you are afraid of giving password on the command line arguments, you can put the
  3022. password of user2 in a file named file2 and use "--passfile2 file2" instead of typing it.
  3023. Then give this file restrictive permissions with the command "chmod 600 file2".
  3024. An other solution is to set the environment variable IMAPSYNC_PASSWORD2
  3025. FIN_PASSFILE
  3026. $mysync->{password2} = ask_for_password( $authuser2 || $mysync->{user2}, $mysync->{host2} ) ;
  3027. } ;
  3028. if ( defined $passfile2 ) {
  3029. if ( ! -e -r $passfile2 ) {
  3030. myprint( "Failure: file from parameter --passfile2 $passfile2 does not exist or is not readable\n" ) ;
  3031. exit_clean( $mysync, $EX_NOINPUT ) ;
  3032. }
  3033. # passfile2 readable
  3034. $mysync->{password2} = firstline ( $passfile2 ) ;
  3035. return ;
  3036. }
  3037. if ( $ENV{IMAPSYNC_PASSWORD2} ) {
  3038. $mysync->{password2} = $ENV{IMAPSYNC_PASSWORD2} ;
  3039. return ;
  3040. }
  3041. return ;
  3042. }
  3043. sub catch_ignore {
  3044. my $mysync = shift ;
  3045. my $signame = shift ;
  3046. my $sigcounter = ++$mysync->{ sigcounter }{ $signame } ;
  3047. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID). Received $sigcounter $signame signals so far. Thanks!\n" ) ;
  3048. stats( $mysync ) ;
  3049. return ;
  3050. }
  3051. sub catch_exit {
  3052. my $mysync = shift ;
  3053. my $signame = shift || q{} ;
  3054. if ( $signame ) {
  3055. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID). Asked to terminate\n" ) ;
  3056. }
  3057. myprint( "Here are the final stats of this sync not completely finished so far\n" ) ;
  3058. stats( $mysync ) ;
  3059. myprint( "Ended by a signal $signame (my PID is $PROCESS_ID). I am asked to terminate immediately.\n" ) ;
  3060. myprint( "You should resynchronize those accounts by running a sync again,\n",
  3061. "since some messages and entire folders might still be missing on host2.\n" ) ;
  3062. exit_clean( $mysync, $EXIT_BY_SIGNAL ) ;
  3063. return ;
  3064. }
  3065. sub catch_reconnect {
  3066. my $mysync = shift ;
  3067. my $signame = shift ;
  3068. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID)\n",
  3069. "Hit 2 ctr-c within 2 seconds to exit the program\n",
  3070. "Hit only 1 ctr-c to reconnect to both imap servers\n",
  3071. ) ;
  3072. if ( here_twice( $mysync ) ) {
  3073. myprint( "Got two signals $signame within $INTERVAL_TO_EXIT seconds. Exiting...\n" ) ;
  3074. catch_exit( $mysync ) ;
  3075. }else{
  3076. myprint( "For now only one signal $signame within $INTERVAL_TO_EXIT seconds.\n" ) ;
  3077. }
  3078. if ( ! defined $mysync->{imap1} ) { return ; }
  3079. if ( ! defined $mysync->{imap2} ) { return ; }
  3080. myprint( "Info: reconnecting to host1 imap server\n" ) ;
  3081. $mysync->{imap1}->State( Mail::IMAPClient::Unconnected ) ;
  3082. $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  3083. $mysync->{imap1}->reconnect( ) ;
  3084. myprint( "Info: reconnecting to host2 imap server\n" ) ;
  3085. $mysync->{imap2}->State( Mail::IMAPClient::Unconnected ) ;
  3086. $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  3087. $mysync->{imap2}->reconnect( ) ;
  3088. myprint( "Info: reconnected to both imap servers\n" ) ;
  3089. return ;
  3090. }
  3091. sub tests_reconnect_12_if_needed {
  3092. note( 'Entering tests_reconnect_12_if_needed()' ) ;
  3093. my $mysync ;
  3094. $mysync->{imap1} = Mail::IMAPClient->new( ) ;
  3095. $mysync->{imap2} = Mail::IMAPClient->new( ) ;
  3096. $mysync->{imap1}->Server( 'test1.lamiral.info' ) ;
  3097. $mysync->{imap2}->Server( 'test2.lamiral.info' ) ;
  3098. is( 2, reconnect_12_if_needed( $mysync ), 'reconnect_12_if_needed: test1&test2 .lamiral.info => 1' ) ;
  3099. is( 1, $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_12_if_needed: test1.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  3100. is( 1, $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_12_if_needed: test2.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  3101. note( 'Leaving tests_reconnect_12_if_needed()' ) ;
  3102. return ;
  3103. }
  3104. sub reconnect_12_if_needed {
  3105. my $mysync = shift ;
  3106. #return 2 ;
  3107. if ( ! reconnect_if_needed( $mysync->{imap1} ) ) {
  3108. return ;
  3109. }
  3110. if ( ! reconnect_if_needed( $mysync->{imap2} ) ) {
  3111. return ;
  3112. }
  3113. # both were good
  3114. return 2 ;
  3115. }
  3116. sub tests_reconnect_if_needed {
  3117. note( 'Entering tests_reconnect_if_needed()' ) ;
  3118. my $myimap ;
  3119. is( undef, reconnect_if_needed( ), 'reconnect_if_needed: no args => undef' ) ;
  3120. is( undef, reconnect_if_needed( $myimap ), 'reconnect_if_needed: undef arg => undef' ) ;
  3121. $myimap = Mail::IMAPClient->new( ) ;
  3122. $myimap->Debug( 1 ) ;
  3123. is( undef, reconnect_if_needed( $myimap ), 'reconnect_if_needed: empty new Mail::IMAPClient => undef' ) ;
  3124. $myimap->Server( 'test.lamiral.info' ) ;
  3125. is( 1, reconnect_if_needed( $myimap ), 'reconnect_if_needed: test.lamiral.info => 1' ) ;
  3126. is( 1, $myimap->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_if_needed: test.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  3127. note( 'Leaving tests_reconnect_if_needed()' ) ;
  3128. return ;
  3129. }
  3130. sub reconnect_if_needed {
  3131. # return undef upon failure.
  3132. # return 1 upon connection success, with or without reconnection.
  3133. my $imap = shift ;
  3134. if ( ! defined $imap ) { return ; }
  3135. if ( ! $imap->Server( ) ) { return ; }
  3136. if ( $imap->IsUnconnected( ) ) {
  3137. $imap->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  3138. if ( $imap->reconnect( ) ) {
  3139. return 1 ;
  3140. }
  3141. }else{
  3142. return 1 ;
  3143. }
  3144. # A last forced one
  3145. $imap->State( Mail::IMAPClient::Unconnected ) ;
  3146. $imap->reconnect( ) ;
  3147. $imap->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  3148. if ( $imap->noop ) {
  3149. # NOOP is ok
  3150. return 1 ;
  3151. }
  3152. return ;
  3153. }
  3154. sub here_twice {
  3155. my $mysync = shift ;
  3156. my $now = time ;
  3157. my $previous = $mysync->{lastcatch} || 0 ;
  3158. $mysync->{lastcatch} = $now ;
  3159. if ( $INTERVAL_TO_EXIT >= $now - $previous ) {
  3160. return $TRUE ;
  3161. }else{
  3162. return $FALSE ;
  3163. }
  3164. }
  3165. sub justconnect {
  3166. $imap1 = connect_imap( $sync->{host1}, $sync->{port1}, $debugimap1, $sync->{ssl1}, $sync->{tls1}, 'Host1', $sync->{h1}->{timeout}, $sync->{h1} ) ;
  3167. $imap2 = connect_imap( $sync->{host2}, $sync->{port2}, $debugimap2, $sync->{ssl2}, $sync->{tls2}, 'Host2', $sync->{h2}->{timeout}, $sync->{h2} ) ;
  3168. $imap1->logout( ) ;
  3169. $imap2->logout( ) ;
  3170. return ;
  3171. }
  3172. sub tests_mailimapclient_connect {
  3173. note( 'Entering tests_mailimapclient_connect()' ) ;
  3174. my $imap ;
  3175. # ipv4
  3176. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv4: new' ) ;
  3177. is( 'Mail::IMAPClient', ref( $imap ), 'mailimapclient_connect ipv4: ref is Mail::IMAPClient' ) ;
  3178. SKIP: {
  3179. if ( 'macosx' eq hostname()
  3180. or 'macosx.polarhome.com' eq hostname()
  3181. ) { skip( 'Tests avoided on macosx get stuck', 1 ) ; }
  3182. is( undef, $imap->connect( ), 'mailimapclient_connect ipv4: connect with no server => failure' ) ;
  3183. }
  3184. is( 'test.lamiral.info', $imap->Server( 'test.lamiral.info' ), 'mailimapclient_connect ipv4: setting Server(test.lamiral.info)' ) ;
  3185. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4: setting Debug( 1 )' ) ;
  3186. is( 143, $imap->Port( 143 ), 'mailimapclient_connect ipv4: setting Port( 143 )' ) ;
  3187. is( 3, $imap->Timeout( 3 ), 'mailimapclient_connect ipv4: setting Timout( 30 )' ) ;
  3188. like( ref( $imap->connect( ) ), qr/IO::Socket::INET/, 'mailimapclient_connect ipv4: connect to test.lamiral.info' ) ;
  3189. like( $imap->logout( ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv4: logout' ) ;
  3190. is( undef, undef $imap, 'mailimapclient_connect ipv4: free variable' ) ;
  3191. # ipv4 + ssl
  3192. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv4 + ssl: new' ) ;
  3193. is( 'test.lamiral.info', $imap->Server( 'test.lamiral.info' ), 'mailimapclient_connect ipv4 + ssl: setting Server(test.lamiral.info)' ) ;
  3194. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4 + ssl: setting Debug( 1 )' ) ;
  3195. ok( $imap->Ssl( [ SSL_verify_mode => SSL_VERIFY_NONE ] ), 'mailimapclient_connect ipv4 + ssl: setting Ssl( SSL_VERIFY_NONE )' ) ;
  3196. is( 993, $imap->Port( 993 ), 'mailimapclient_connect ipv4 + ssl: setting Port( 993 )' ) ;
  3197. like( ref( $imap->connect( ) ), qr/IO::Socket::SSL/, 'mailimapclient_connect ipv4 + ssl: connect to test.lamiral.info' ) ;
  3198. is( $imap->logout( ), undef, 'mailimapclient_connect ipv4 + ssl: logout in ssl causes failure' ) ;
  3199. is( undef, undef $imap, 'mailimapclient_connect ipv4 + ssl: free variable' ) ;
  3200. # ipv6 + ssl
  3201. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv6 + ssl: new' ) ;
  3202. is( 'ks2ipv6.lamiral.info', $imap->Server( 'ks2ipv6.lamiral.info' ), 'mailimapclient_connect ipv6 + ssl: setting Server(ks2ipv6.lamiral.info)' ) ;
  3203. ok( $imap->Ssl( [ SSL_verify_mode => SSL_VERIFY_NONE ] ), 'mailimapclient_connect ipv6 + ssl: setting Ssl( SSL_VERIFY_NONE )' ) ;
  3204. is( 993, $imap->Port( 993 ), 'mailimapclient_connect ipv6 + ssl: setting Port( 993 )' ) ;
  3205. SKIP: {
  3206. if ( 'CUILLERE' eq hostname() ) { skip( 'Tests avoided on CUILLERE can not do ipv6', 2 ) ; }
  3207. like( ref( $imap->connect( ) ), qr/IO::Socket::SSL/, 'mailimapclient_connect ipv6 + ssl: connect to ks2ipv6.lamiral.info' ) ;
  3208. is( $imap->logout( ), undef, 'mailimapclient_connect ipv6 + ssl: logout in ssl causes failure' ) ;
  3209. }
  3210. is( undef, undef $imap, 'mailimapclient_connect ipv6 + ssl: free variable' ) ;
  3211. note( 'Leaving tests_mailimapclient_connect()' ) ;
  3212. return ;
  3213. }
  3214. sub tests_mailimapclient_connect_bug {
  3215. note( 'Entering tests_mailimapclient_connect_bug()' ) ;
  3216. my $imap ;
  3217. # ipv6
  3218. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv6: new' ) ;
  3219. is( 'ks2ipv6.lamiral.info', $imap->Server( 'ks2ipv6.lamiral.info' ), 'mailimapclient_connect ipv6: setting Server(ks2ipv6.lamiral.info)' ) ;
  3220. is( 143, $imap->Port( 143 ), 'mailimapclient_connect ipv6: setting Port( 993 )' ) ;
  3221. SKIP: {
  3222. if ( 'CUILLERE' eq hostname() ) { skip( 'Tests avoided on CUILLERE can not do ipv6', 1 ) ; }
  3223. like( ref( $imap->connect( ) ), qr/IO::Socket::INET/, 'mailimapclient_connect ipv6: connect to ks2ipv6.lamiral.info' )
  3224. or diag( 'mailimapclient_connect ipv6: ', $imap->LastError( ), $!, ) ;
  3225. }
  3226. #is( $imap->logout( ), undef, 'mailimapclient_connect ipv6: logout in ssl causes failure' ) ;
  3227. is( undef, undef $imap, 'mailimapclient_connect ipv6: free variable' ) ;
  3228. note( 'Leaving tests_mailimapclient_connect_bug()' ) ;
  3229. return ;
  3230. }
  3231. sub mailimapclient_connect {
  3232. return ;
  3233. }
  3234. sub tests_connect_socket {
  3235. note( 'Entering tests_connect_socket()' ) ;
  3236. is( undef, connect_socket( ), 'connect_socket: no args' ) ;
  3237. my $socket ;
  3238. my $imap ;
  3239. SKIP: {
  3240. if ( 'CUILLERE' eq hostname() ) { skip( 'Tests avoided on CUILLERE cannot do ipv6', 2 ) ; }
  3241. $socket = IO::Socket::INET6->new(
  3242. PeerAddr => 'ks2ipv6.lamiral.info',
  3243. PeerPort => 143,
  3244. ) ;
  3245. ok( $imap = connect_socket( $socket ), 'connect_socket: ks2ipv6.lamiral.info port 143 IO::Socket::INET6' ) ;
  3246. #$imap->Debug( 1 ) ;
  3247. # myprint( $imap->capability( ) ) ;
  3248. if ( $imap ) {
  3249. $imap->logout( ) ;
  3250. }
  3251. #$IO::Socket::SSL::DEBUG = 4 ;
  3252. $socket = IO::Socket::SSL->new(
  3253. PeerHost => 'ks2ipv6.lamiral.info',
  3254. PeerPort => 993,
  3255. SSL_verify_mode => SSL_VERIFY_NONE,
  3256. ) ;
  3257. # myprint $socket ;
  3258. ok( $imap = connect_socket( $socket ), 'connect_socket: ks2ipv6.lamiral.info port 993 IO::Socket::SSL' ) ;
  3259. #$imap->Debug( 1 ) ;
  3260. # myprint $imap->capability( ) ;
  3261. $socket->close( ) ;
  3262. if ( $imap ) {
  3263. $socket->close( ) ;
  3264. }
  3265. #$socket->close(SSL_no_shutdown => 1) ;
  3266. #$imap->logout( ) ;
  3267. #myprint "\n" ;
  3268. #$imap->logout( ) ;
  3269. }
  3270. note( 'Leaving tests_connect_socket()' ) ;
  3271. return ;
  3272. }
  3273. sub connect_socket {
  3274. my( $socket ) = @ARG ;
  3275. if ( ! defined $socket ) { return ; }
  3276. my $host = $socket->peerhost( ) ;
  3277. my $port = $socket->peerport( ) ;
  3278. #print "socket->peerhost: ", $socket->peerhost( ), "\n" ;
  3279. #print "socket->peerport: ", $socket->peerport( ), "\n" ;
  3280. my $imap = Mail::IMAPClient->new( ) ;
  3281. $imap->Socket( $socket ) ;
  3282. my $banner = $imap->Results()->[0] ;
  3283. #myprint( "banner: $banner" ) ;
  3284. return $imap ;
  3285. }
  3286. sub tests_probe_imapssl {
  3287. note( 'Entering tests_probe_imapssl()' ) ;
  3288. is( undef, probe_imapssl( ), 'probe_imapssl: no args => undef' ) ;
  3289. is( undef, probe_imapssl( 'unknown' ), 'probe_imapssl: unknown => undef' ) ;
  3290. SKIP: {
  3291. if ( 'CUILLERE' eq hostname() ) { skip( 'Tests avoided on CUILLERE cannot do ipv6', 1 ) ; }
  3292. like( probe_imapssl( 'ks2ipv6.lamiral.info' ), qr/^\* OK/, 'probe_imapssl: ks2ipv6.lamiral.info matches "* OK"' ) ;
  3293. } ;
  3294. like( probe_imapssl( 'test1.lamiral.info' ), qr/^\* OK/, 'probe_imapssl: test1.lamiral.info matches "* OK"' ) ;
  3295. like( probe_imapssl( 'imap.gmail.com' ), qr/^\* OK/, 'probe_imapssl: imap.gmail.com matches "* OK"' ) ;
  3296. note( 'Leaving tests_probe_imapssl()' ) ;
  3297. return ;
  3298. }
  3299. sub probe_imapssl {
  3300. my $host = shift ;
  3301. if ( ! $host ) { return ; }
  3302. my $socket = IO::Socket::SSL->new(
  3303. PeerHost => $host,
  3304. PeerPort => $IMAP_SSL_PORT,
  3305. SSL_verify_mode => SSL_VERIFY_NONE,
  3306. ) ;
  3307. #print "$socket\n" ;
  3308. if ( ! $socket ) { return ; }
  3309. my $banner ;
  3310. $socket->sysread( $banner, 65_536 ) ;
  3311. #print "$banner" ;
  3312. $socket->close( ) ;
  3313. return $banner ;
  3314. }
  3315. sub connect_imap {
  3316. my( $host, $port, $mydebugimap, $ssl, $tls, $Side, $mytimeout, $h ) = @_ ;
  3317. my $imap = Mail::IMAPClient->new( ) ;
  3318. if ( $ssl ) { set_ssl( $imap, $h ) }
  3319. $imap->Server( $host ) ;
  3320. $imap->Port( $port ) ;
  3321. $imap->Debug( $mydebugimap ) ;
  3322. $imap->Timeout( $mytimeout ) ;
  3323. my $side = lc $Side ;
  3324. myprint( "$Side: connecting on $side [$host] port [$port]\n" ) ;
  3325. $imap->connect( )
  3326. or die_clean( "$Side: Can not open imap connection on [$host]: " . $imap->LastError . " $OS_ERROR\n" ) ;
  3327. myprint( "$Side IP address: ", $imap->Socket->peerhost(), "\n" ) ;
  3328. my $banner = $imap->Results()->[0] ;
  3329. myprint( "$Side banner: $banner" ) ;
  3330. myprint( "$Side capability: ", join(q{ }, @{ $imap->capability() || [] }), "\n" ) ;
  3331. if ( $tls ) {
  3332. set_tls( $imap, $h ) ;
  3333. $imap->starttls( )
  3334. or die_clean("$Side: Can not go to tls encryption on $side [$host]:", $imap->LastError, "\n" ) ;
  3335. myprint( "$Side: Socket successfuly converted to SSL\n" ) ;
  3336. }
  3337. return( $imap ) ;
  3338. }
  3339. sub login_imap {
  3340. my @allargs = @_ ;
  3341. my(
  3342. $host, $port, $user, $domain, $password,
  3343. $mydebugimap, $mytimeout, $fastio,
  3344. $ssl, $tls, $authmech, $authuser, $reconnectretry,
  3345. $proxyauth, $uid, $split, $Side, $h, $mysync ) = @allargs ;
  3346. my $side = lc $Side ;
  3347. myprint( "$Side: connecting and login on $side [$host] port [$port] with user [$user]\n" ) ;
  3348. my $imap = init_imap( @allargs ) ;
  3349. $imap->connect()
  3350. or die_clean("$Side failure: can not open imap connection on $side [$host] with user [$user]: " . $imap->LastError . " $OS_ERROR\n" ) ;
  3351. myprint( "$Side IP address: ", $imap->Socket->peerhost(), "\n" ) ;
  3352. my $banner = $imap->Results()->[0] ;
  3353. myprint( "$Side banner: $banner" ) ;
  3354. myprint( "$Side capability before authentication: ", join(q{ }, @{ $imap->capability() || [] }), "\n" ) ;
  3355. if ( (! $ssl) and (! defined $tls ) and $imap->has_capability( 'STARTTLS' ) ) {
  3356. myprint( "$Side: going to ssl because STARTTLS is in CAPABILITY. Use --notls1 or --notls2 to avoid that behavior\n" ) ;
  3357. $tls = 1 ;
  3358. }
  3359. if ( $authmech eq 'PREAUTH' ) {
  3360. if ( $imap->IsAuthenticated( ) ) {
  3361. $imap->Socket ;
  3362. myprintf("%s: Assuming PREAUTH for %s\n", $Side, $imap->Server ) ;
  3363. }else{
  3364. die_clean( "$Side failure: error login on $side [$host] with user [$user] auth [PREAUTH]" ) ;
  3365. }
  3366. }
  3367. if ( $tls ) {
  3368. set_tls( $imap, $h ) ;
  3369. $imap->starttls( )
  3370. or die_clean("$Side failure: Can not go to tls encryption on $side [$host]:", $imap->LastError, "\n" ) ;
  3371. myprint( "$Side: Socket successfuly converted to SSL\n" ) ;
  3372. }
  3373. authenticate_imap( $imap, @allargs ) ;
  3374. myprint( "$Side: success login on [$host] with user [$user] auth [$authmech]\n" ) ;
  3375. return( $imap ) ;
  3376. }
  3377. sub authenticate_imap {
  3378. my($imap,
  3379. $host, $port, $user, $domain, $password,
  3380. $mydebugimap, $mytimeout, $fastio,
  3381. $ssl, $tls, $authmech, $authuser, $reconnectretry,
  3382. $proxyauth, $uid, $split, $Side, $h, $mysync ) = @_ ;
  3383. check_capability( $imap, $authmech, $Side ) ;
  3384. if ( $proxyauth ) {
  3385. $imap->Authmechanism(q{}) ;
  3386. $imap->User($authuser) ;
  3387. } else {
  3388. $imap->Authmechanism( $authmech ) unless ( $authmech eq 'LOGIN' or $authmech eq 'PREAUTH' ) ;
  3389. $imap->User($user) ;
  3390. }
  3391. $imap->Authcallback(\&xoauth) if ( 'XOAUTH' eq $authmech ) ;
  3392. $imap->Authcallback(\&xoauth2) if ( 'XOAUTH2' eq $authmech ) ;
  3393. $imap->Authcallback(\&plainauth) if ( ( 'PLAIN' eq $authmech ) or ( 'EXTERNAL' eq $authmech ) ) ;
  3394. $imap->Domain($domain) if (defined $domain) ;
  3395. $imap->Authuser($authuser) ;
  3396. $imap->Password($password) ;
  3397. unless ( $authmech eq 'PREAUTH' or $imap->login( ) ) {
  3398. my $info = "$Side failure: Error login on [$host] with user [$user] auth" ;
  3399. my $einfo = $imap->LastError || @{$imap->History}[$LAST] ;
  3400. chomp $einfo ;
  3401. my $error = "$info [$authmech]: $einfo\n" ;
  3402. if ( $authmech eq 'LOGIN' or $imap->IsUnconnected( ) or $authuser ) {
  3403. die_clean( $error ) ;
  3404. }else{
  3405. myprint( $error ) ;
  3406. }
  3407. myprint( "$Side info: trying LOGIN Auth mechanism on [$host] with user [$user]\n" ) ;
  3408. $imap->Authmechanism(q{}) ;
  3409. $imap->login() or
  3410. die_clean("$info [LOGIN]: ", $imap->LastError, "\n") ;
  3411. }
  3412. if ( $proxyauth ) {
  3413. if ( ! $imap->proxyauth( $user ) ) {
  3414. my $info = "$Side failure: Error doing proxyauth as user [$user] on [$host] using proxy-login as [$authuser]" ;
  3415. my $einfo = $imap->LastError || @{$imap->History}[$LAST] ;
  3416. chomp $einfo ;
  3417. die_clean( "$info: $einfo\n" ) ;
  3418. }
  3419. }
  3420. return ;
  3421. }
  3422. sub check_capability {
  3423. my( $imap, $authmech, $Side ) = @_ ;
  3424. if ($imap->has_capability( "AUTH=$authmech" )
  3425. or $imap->has_capability( $authmech ) ) {
  3426. myprintf("%s: %s says it has CAPABILITY for AUTHENTICATE %s\n",
  3427. $Side, $imap->Server, $authmech) ;
  3428. return ;
  3429. }
  3430. if ( $authmech eq 'LOGIN' ) {
  3431. # Well, the warning is so common and useless that I prefer to remove it
  3432. # No more "... says it has NO CAPABILITY for AUTHENTICATE LOGIN"
  3433. return ;
  3434. }
  3435. myprintf( "%s: %s says it has NO CAPABILITY for AUTHENTICATE %s\n",
  3436. $Side, $imap->Server, $authmech ) ;
  3437. if ($authmech eq 'PLAIN') {
  3438. myprint( "$Side: frequently PLAIN is only supported with SSL, try --ssl or --tls options\n" ) ;
  3439. }
  3440. return ;
  3441. }
  3442. sub set_ssl {
  3443. my ( $imap, $h ) = @_ ;
  3444. # SSL_version can be
  3445. # SSLv3 SSLv2 SSLv23 SSLv23:!SSLv2 (last one is the default in IO-Socket-SSL-1.953)
  3446. #
  3447. my $sslargs_hash = $h->{sslargs} ;
  3448. my $sslargs_default = {
  3449. SSL_verify_mode => $SSL_VERIFY_POLICY,
  3450. SSL_verifycn_scheme => 'imap',
  3451. SSL_cipher_list => 'DEFAULT:!DH',
  3452. } ;
  3453. # initiate with default values
  3454. my %sslargs_mix = %{ $sslargs_default } ;
  3455. # now override with passed values
  3456. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  3457. # remove keys with undef values
  3458. foreach my $key ( keys %sslargs_mix ) {
  3459. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  3460. }
  3461. # back to an ARRAY
  3462. my @sslargs_mix = %sslargs_mix ;
  3463. #myprint( Data::Dumper->Dump( [ $sslargs_hash, $sslargs_default, \%sslargs_mix, \@sslargs_mix ] ) ) ;
  3464. $imap->Ssl( \@sslargs_mix ) ;
  3465. return ;
  3466. }
  3467. sub set_tls {
  3468. my ( $imap, $h ) = @_ ;
  3469. my $sslargs_hash = $h->{sslargs} ;
  3470. my $sslargs_default = {
  3471. SSL_verify_mode => $SSL_VERIFY_POLICY,
  3472. SSL_cipher_list => 'DEFAULT:!DH',
  3473. } ;
  3474. # initiate with default values
  3475. my %sslargs_mix = %{ $sslargs_default } ;
  3476. # now override with passed values
  3477. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  3478. # remove keys with undef values
  3479. foreach my $key ( keys %sslargs_mix ) {
  3480. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  3481. }
  3482. # back to an ARRAY
  3483. my @sslargs_mix = %sslargs_mix ;
  3484. $imap->Starttls( \@sslargs_mix ) ;
  3485. return ;
  3486. }
  3487. sub init_imap {
  3488. my(
  3489. $host, $port, $user, $domain, $password,
  3490. $mydebugimap, $mytimeout, $fastio,
  3491. $ssl, $tls, $authmech, $authuser, $reconnectretry,
  3492. $proxyauth, $uid, $split, $Side, $h, $mysync ) = @_ ;
  3493. my ( $imap ) ;
  3494. $imap = Mail::IMAPClient->new() ;
  3495. if ( $ssl ) { set_ssl( $imap, $h ) }
  3496. if ( $tls ) { } # can not do set_tls() here because connect() will directly do a STARTTLS
  3497. $imap->Clear(1);
  3498. $imap->Server($host);
  3499. $imap->Port($port);
  3500. $imap->Fast_io($fastio);
  3501. $imap->Buffer($buffersize || $DEFAULT_BUFFER_SIZE);
  3502. $imap->Uid($uid);
  3503. $imap->Peek(1);
  3504. $imap->Debug($mydebugimap);
  3505. if ( $mysync->{ showpasswords } ) {
  3506. $imap->Showcredentials( 1 ) ;
  3507. }
  3508. defined $mytimeout and $imap->Timeout( $mytimeout ) ;
  3509. $imap->Reconnectretry( $reconnectretry ) if ( $reconnectretry ) ;
  3510. $imap->{IMAPSYNC_RECONNECT_COUNT} = 0 ;
  3511. $imap->Ignoresizeerrors( $allowsizemismatch ) ;
  3512. $split and $imap->Maxcommandlength( $SPLIT_FACTOR * $split ) ;
  3513. return( $imap ) ;
  3514. }
  3515. sub plainauth {
  3516. my $code = shift;
  3517. my $imap = shift;
  3518. my $string = mysprintf("%s\x00%s\x00%s", $imap->User,
  3519. $imap->Authuser, $imap->Password);
  3520. return encode_base64("$string", q{});
  3521. }
  3522. # Copy from https://github.com/imapsync/imapsync/pull/25/files
  3523. # Changes "use" pragmas to "require".
  3524. # The openssl system call shall be replaced by pure Perl and
  3525. # https://metacpan.org/pod/Crypt::OpenSSL::PKCS12
  3526. # Now the Joaquin Lopez code:
  3527. #
  3528. # Used this as an example: https://gist.github.com/gsainio/6322375
  3529. #
  3530. # And this as a reference: https://developers.google.com/accounts/docs/OAuth2ServiceAccount
  3531. # (note there is an http/rest tab, where the real info is hidden away... went on a witch hunt
  3532. # until I noticed that...)
  3533. #
  3534. # This is targeted at gmail to maintain compatibility after google's oauth1 service is deactivated
  3535. # on May 5th, 2015: https://developers.google.com/gmail/oauth_protocol
  3536. # If there are other oauth2 implementations out there, this would need to be modified to be
  3537. # compatible
  3538. #
  3539. # This is a good guide on setting up the google api/apps side of the equation:
  3540. # http://www.limilabs.com/blog/oauth2-gmail-imap-service-account
  3541. #
  3542. # 2016/05/27: Updated to support oauth/key data in the .json files Google now defaults to
  3543. # when creating gmail service accounts. They're easier to work with since they neither
  3544. # requiring decrypting nor specifying the oauth2 client id separately.
  3545. #
  3546. # If the password arg ends in .json, it will assume this new json method, otherwise it
  3547. # will fallback to the "oauth client id;.p12" format it was previously using.
  3548. sub xoauth2 {
  3549. require JSON::WebToken ;
  3550. require LWP::UserAgent ;
  3551. require HTML::Entities ;
  3552. require JSON ;
  3553. require JSON::WebToken::Crypt::RSA ;
  3554. require Crypt::OpenSSL::RSA ;
  3555. require Encode::Byte ;
  3556. require IO::Socket::SSL ;
  3557. my $code = shift;
  3558. my $imap = shift;
  3559. my ($iss,$key);
  3560. if( $imap->Password =~ /^(.*\.json)$/x ) {
  3561. my $json = JSON->new( ) ;
  3562. my $filename = $1;
  3563. $debug and myprint( "XOAUTH2 json file: $filename\n" ) ;
  3564. open( my $FILE, '<', $filename ) or die_clean( "error [$filename]: $OS_ERROR " ) ;
  3565. my $jsonfile = $json->decode( join q{}, <$FILE> ) ;
  3566. close $FILE ;
  3567. $iss = $jsonfile->{client_id};
  3568. $key = $jsonfile->{private_key};
  3569. $debug and myprint( "Service account: $iss\n");
  3570. $debug and myprint( "Private key:\n$key\n");
  3571. }
  3572. else {
  3573. # Get iss (service account address), keyfile name, and keypassword if necessary
  3574. ( $iss, my $keyfile, my $keypass ) = $imap->Password =~ /([\-\d\w\@\.]+);([a-zA-Z0-9 \_\-\.\/]+);?(.*)?/x ;
  3575. # Assume key password is google default if not provided
  3576. $keypass = 'notasecret' if not $keypass;
  3577. $debug and myprint( "Service account: $iss\nKey file: $keyfile\nKey password: $keypass\n");
  3578. # Get private key from p12 file (would be better in perl...)
  3579. $key = `openssl pkcs12 -in "$keyfile" -nodes -nocerts -passin pass:$keypass -nomacver`;
  3580. $debug and myprint( "Private key:\n$key\n");
  3581. }
  3582. # Create jwt of oauth2 request
  3583. my $time = time ;
  3584. my $jwt = JSON::WebToken->encode( {
  3585. 'iss' => $iss, # service account
  3586. 'scope' => 'https://mail.google.com/',
  3587. 'aud' => 'https://www.googleapis.com/oauth2/v3/token',
  3588. 'exp' => $time + $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12,
  3589. 'iat' => $time,
  3590. 'prn' => $imap->User # user to auth as
  3591. },
  3592. $key, 'RS256', {'typ' => 'JWT'} ); # Crypt::OpenSSL::RSA needed here.
  3593. # Post oauth2 request
  3594. my $ua = LWP::UserAgent->new( ) ;
  3595. $ua->env_proxy( ) ;
  3596. my $response = $ua->post('https://www.googleapis.com/oauth2/v3/token',
  3597. { grant_type => HTML::Entities::encode_entities('urn:ietf:params:oauth:grant-type:jwt-bearer'),
  3598. assertion => $jwt } ) ;
  3599. unless( $response->is_success( ) ) {
  3600. die_clean( $response->code, "\n", $response->content, "\n" ) ;
  3601. }else{
  3602. $debug and myprint( $response->content ) ;
  3603. }
  3604. # access_token in response is what we need
  3605. my $data = JSON::decode_json( $response->content ) ;
  3606. # format as oauth2 auth data
  3607. my $xoauth2_string = encode_base64( 'user=' . $imap->User . "\1auth=Bearer " . $data->{access_token} . "\1\1", q{} ) ;
  3608. $debug and myprint( "XOAUTH2 String: $xoauth2_string\n");
  3609. return($xoauth2_string);
  3610. }
  3611. # xoauth() thanks to Eduardo Bortoluzzi Junior
  3612. sub xoauth {
  3613. require URI::Escape ;
  3614. require Data::Uniqid ;
  3615. my $code = shift;
  3616. my $imap = shift;
  3617. # The base information needed to construct the OAUTH authentication
  3618. my $method = 'GET' ;
  3619. my $url = mysprintf( 'https://mail.google.com/mail/b/%s/imap/', $imap->User ) ;
  3620. my $urlparm = mysprintf( 'xoauth_requestor_id=%s', URI::Escape::uri_escape( $imap->User ) ) ;
  3621. # For Google Apps, the consumer key is the primary domain
  3622. # TODO: create a command line argument to define the consumer key
  3623. my @user_parts = split /@/x, $imap->User ;
  3624. $debug and myprint( "XOAUTH: consumer key: $user_parts[1]\n" ) ;
  3625. # All the parameters needed to be signed on the XOAUTH
  3626. my %hash = ();
  3627. $hash { 'xoauth_requestor_id' } = URI::Escape::uri_escape($imap->User);
  3628. $hash { 'oauth_consumer_key' } = $user_parts[1];
  3629. $hash { 'oauth_nonce' } = md5_hex(Data::Uniqid::uniqid(rand(), 1==1));
  3630. $hash { 'oauth_signature_method' } = 'HMAC-SHA1';
  3631. $hash { 'oauth_timestamp' } = time ;
  3632. $hash { 'oauth_version' } = '1.0';
  3633. # Base will hold the string to be signed
  3634. my $base = "$method&" . URI::Escape::uri_escape( $url ) . q{&} ;
  3635. # The parameters must be in dictionary order before signing
  3636. my $baseparms = q{} ;
  3637. foreach my $key ( sort keys %hash ) {
  3638. if ( length( $baseparms ) > 0 ) {
  3639. $baseparms .= q{&} ;
  3640. }
  3641. $baseparms .= "$key=$hash{$key}" ;
  3642. }
  3643. $base .= URI::Escape::uri_escape($baseparms);
  3644. $debug and myprint( "XOAUTH: base request to sign: $base\n" ) ;
  3645. # Sign it with the consumer secret, informed on the command line (password)
  3646. my $digest = hmac_sha1( $base, URI::Escape::uri_escape( $imap->Password ) . q{&} ) ;
  3647. # The parameters signed become a parameter and...
  3648. $hash { 'oauth_signature' } = URI::Escape::uri_escape( substr encode_base64( $digest ), 0, $MINUS_ONE ) ;
  3649. # ... we don't need the requestor_id anymore.
  3650. delete $hash{'xoauth_requestor_id'} ;
  3651. # Create the final authentication string
  3652. my $string = $method . q{ } . $url . q{?} . $urlparm .q{ } ;
  3653. # All the parameters must be sorted
  3654. $baseparms = q{};
  3655. foreach my $key (sort keys %hash) {
  3656. if(length($baseparms)>0) {
  3657. $baseparms .= q{,} ;
  3658. }
  3659. $baseparms .= "$key=\"$hash{$key}\"";
  3660. }
  3661. $string .= $baseparms;
  3662. $debug and myprint( "XOAUTH: authentication string: $string\n" ) ;
  3663. # It must be base64 encoded
  3664. return encode_base64("$string", q{});
  3665. }
  3666. sub banner_imapsync {
  3667. my @argv = @_ ;
  3668. my $banner_imapsync = join q{},
  3669. q{$RCSfile: imapsync,v $ },
  3670. q{$Revision: 1.882 $ },
  3671. q{$Date: 2018/05/05 21:10:43 $ },
  3672. "\n",
  3673. "Command line used:\n",
  3674. "$PROGRAM_NAME ", command_line_nopassword( @argv ), "\n" ;
  3675. return( $banner_imapsync ) ;
  3676. }
  3677. sub do_valid_directory {
  3678. my $dir = shift;
  3679. # all good => return ok.
  3680. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  3681. # exist but bad
  3682. if ( -e $dir and not -d _ ) {
  3683. myprint( "Error: $dir exists but is not a directory\n" ) ;
  3684. return( 0 ) ;
  3685. }
  3686. if ( -e $dir and not -w _ ) {
  3687. my $sb = stat $dir ;
  3688. myprintf( "Error: directory %s is not writable for user %s, permissions are %04o and owner is %s ( uid %s )\n",
  3689. $dir, getpwuid_any_os( $EFFECTIVE_USER_ID ), ($sb->mode & oct($PERMISSION_FILTER) ), getpwuid_any_os( $sb->uid ), $sb->uid( ) ) ;
  3690. return( 0 ) ;
  3691. }
  3692. # Trying to create it
  3693. myprint( "Creating directory $dir\n" ) ;
  3694. if ( ! eval { mkpath( $dir ) } ) {
  3695. myprint( "$EVAL_ERROR" ) if ( $EVAL_ERROR ) ;
  3696. }
  3697. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  3698. return( 0 ) ;
  3699. }
  3700. sub tests_do_valid_directory {
  3701. note( 'Entering tests_do_valid_directory()' ) ;
  3702. Readonly my $NB_UNIX_tests_do_valid_directory => 2 ;
  3703. SKIP: {
  3704. skip( 'Tests only for Unix', $NB_UNIX_tests_do_valid_directory ) if ( 'MSWin32' eq $OSNAME ) ;
  3705. ok( 1 == do_valid_directory( '.'), 'do_valid_directory: . good' ) ;
  3706. ok( 1 == do_valid_directory( './W/tmp/tests/valid/sub'), 'do_valid_directory: ./W/tmp/tests/valid/sub good' ) ;
  3707. }
  3708. Readonly my $NB_UNIX_tests_do_valid_directory_non_root => 2 ;
  3709. SKIP: {
  3710. skip( 'Tests only for Unix', $NB_UNIX_tests_do_valid_directory_non_root ) if ( 'MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) ;
  3711. diag( 'Error / not writable is on purpose' ) ;
  3712. ok( 0 == do_valid_directory( '/'), 'do_valid_directory: / bad' ) ;
  3713. diag( 'Error permission denied on /noway is on purpose' ) ;
  3714. ok( 0 == do_valid_directory( '/noway'), 'do_valid_directory: /noway bad' ) ;
  3715. }
  3716. note( 'Leaving tests_do_valid_directory()' ) ;
  3717. return ;
  3718. }
  3719. sub tests_match_a_pid_number {
  3720. is( undef, match_a_pid_number( ), 'match_a_pid_number: no args => undef' ) ;
  3721. is( undef, match_a_pid_number( '' ), 'match_a_pid_number: "" => undef' ) ;
  3722. is( undef, match_a_pid_number( 'lalala' ), 'match_a_pid_number: lalala => undef' ) ;
  3723. is( 1, match_a_pid_number( 1 ), 'match_a_pid_number: 1 => 1' ) ;
  3724. is( 1, match_a_pid_number( 123 ), 'match_a_pid_number: 123 => 1' ) ;
  3725. is( 1, match_a_pid_number( '123' ), 'match_a_pid_number: "123" => 1' ) ;
  3726. is( undef, match_a_pid_number( 'a123' ), 'match_a_pid_number: a123 => undef' ) ;
  3727. is( 1, match_a_pid_number( 65535 ), 'match_a_pid_number: 65535 => 1' ) ;
  3728. is( undef, match_a_pid_number( 0 ), 'match_a_pid_number: 0 => undef' ) ;
  3729. is( undef, match_a_pid_number( 65536 ), 'match_a_pid_number: 65536 => undef' ) ;
  3730. is( undef, match_a_pid_number( 99999 ), 'match_a_pid_number: 99999 => undef' ) ;
  3731. return ;
  3732. }
  3733. sub match_a_pid_number {
  3734. my $pid = shift ;
  3735. if ( ! $pid ) { return ; }
  3736. if ( ! match( $pid, '^\d+$' ) ) { return ; }
  3737. if ( 0 > $pid ) { return ; }
  3738. if ( 65535 < $pid ) { return ; }
  3739. return 1 ;
  3740. }
  3741. sub tests_remove_pidfile_not_running {
  3742. is( undef, remove_pidfile_not_running( ), 'remove_pidfile_not_running: no args => undef' ) ;
  3743. is( undef, remove_pidfile_not_running( './W' ), 'remove_pidfile_not_running: a dir => undef' ) ;
  3744. is( undef, remove_pidfile_not_running( 'noexists' ), 'remove_pidfile_not_running: noexists => undef' ) ;
  3745. is( 1, touch( 'W/tmp/tests/empty.pid' ), 'remove_pidfile_not_running: prepa empty W/tmp/tests/empty.pid' ) ;
  3746. is( undef, remove_pidfile_not_running( 'W/tmp/tests/empty.pid' ), 'remove_pidfile_not_running: W/tmp/tests/empty.pid => undef' ) ;
  3747. is( 'lalala', string_to_file( 'lalala', 'W/tmp/tests/lalala.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/lalala.pid' ) ;
  3748. is( undef, remove_pidfile_not_running( 'W/tmp/tests/lalala.pid' ), 'remove_pidfile_not_running: W/tmp/tests/lalala.pid => undef' ) ;
  3749. is( '55555', string_to_file( '55555', 'W/tmp/tests/notrunning.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/notrunning.pid' ) ;
  3750. is( 1, remove_pidfile_not_running( 'W/tmp/tests/notrunning.pid' ), 'remove_pidfile_not_running: W/tmp/tests/notrunning.pid => 1' ) ;
  3751. is( $PROCESS_ID, string_to_file( $PROCESS_ID, 'W/tmp/tests/running.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/running.pid' ) ;
  3752. is( undef, remove_pidfile_not_running( 'W/tmp/tests/running.pid' ), 'remove_pidfile_not_running: W/tmp/tests/running.pid => undef' ) ;
  3753. return ;
  3754. }
  3755. sub remove_pidfile_not_running {
  3756. #
  3757. my $pid_filename = shift ;
  3758. if ( ! $pid_filename ) { return } ;
  3759. if ( ! -e $pid_filename ) { return } ;
  3760. if ( ! -f $pid_filename ) { return } ;
  3761. my $pid = firstline( $pid_filename ) ;
  3762. if ( ! match_a_pid_number( $pid ) ) { return } ;
  3763. # can't kill myself => do nothing
  3764. if ( ! kill 'ZERO', $PROCESS_ID ) { return } ;
  3765. # can't kill the pid => it is gone or own by another user => remove pidfile
  3766. if ( ! kill 'ZERO', $pid ) {
  3767. myprint( "Removing old $pid_filename since its PID $pid is not running anymore (oo-killed?)\n" ) ;
  3768. if ( unlink $pid_filename ) {
  3769. myprint( "Removed old $pid_filename\n" ) ;
  3770. return 1 ;
  3771. }else{
  3772. myprint( "Could not remove old $pid_filename because $!\n" ) ;
  3773. return ;
  3774. }
  3775. }
  3776. myprint( "Another imapsync process $pid is running as says pidfile $pid_filename\n" ) ;
  3777. return ;
  3778. }
  3779. sub tests_write_pidfile {
  3780. my $mysync ;
  3781. is( 1, write_pidfile( ), 'write_pidfile: no args => 1' ) ;
  3782. $mysync->{pidfile} = '/no/no/no.pid' ;
  3783. is( 1, write_pidfile( $mysync ), 'write_pidfile: no permission for /no/no/no.pid, no lock => 1' ) ;
  3784. $mysync->{pidfilelocking} = 1 ;
  3785. is( undef, write_pidfile( $mysync ), 'write_pidfile: no permission for /no/no/no.pid + lock => undef' ) ;
  3786. $mysync->{pidfile} = 'W/tmp/tests/test.pid' ;
  3787. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'write_pidfile: mkpath W/tmp/tests/' ) ;
  3788. is( 1, touch( $mysync->{pidfile} ), 'write_pidfile: lock prepa' ) ;
  3789. $mysync->{pidfilelocking} = 0 ;
  3790. is( 1, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid => 1' ) ;
  3791. is( $PROCESS_ID, firstline( 'W/tmp/tests/test.pid' ), "write_pidfile: W/tmp/tests/test.pid contains $PROCESS_ID" ) ;
  3792. $mysync->{pidfilelocking} = 1 ;
  3793. is( undef, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + lock => undef' ) ;
  3794. return ;
  3795. }
  3796. sub write_pidfile {
  3797. # returns undef if something is considered fatal
  3798. # returns 1 otherwise
  3799. if ( ! @ARG ) { return 1 ; }
  3800. my $mysync = shift ;
  3801. # Do not write the pid file if this process goal is to abort the process designed by the pid file
  3802. if ( $mysync->{abort} ) { return 1 ; }
  3803. #
  3804. my $pid_filename = $mysync->{pidfile} ;
  3805. my $lock = $mysync->{pidfilelocking} ;
  3806. myprint( "PID file is $pid_filename ( to change it use --pidfile filepath ; to avoid it use --pidfile \"\" )\n" ) ;
  3807. if ( -e $pid_filename and $lock ) {
  3808. myprint( "$pid_filename already exists, another imapsync may be curently running. Aborting imapsync.\n" ) ;
  3809. return ;
  3810. }
  3811. if ( -e $pid_filename ) {
  3812. myprint( "$pid_filename already exists, overwriting it ( use --pidfilelocking to avoid concurrent runs )\n" ) ;
  3813. }
  3814. if ( open my $FILE_HANDLE, '>', $pid_filename ) {
  3815. myprint( "Writing my PID $PROCESS_ID in $pid_filename\n" ) ;
  3816. print $FILE_HANDLE $PROCESS_ID ;
  3817. close $FILE_HANDLE ;
  3818. return( 1 ) ;
  3819. } else {
  3820. myprint( "Could not open $pid_filename for writing. Check permissions or disk space.\n" ) ;
  3821. if ( $lock ) {
  3822. return ;
  3823. }else{
  3824. return( 1 ) ;
  3825. }
  3826. }
  3827. }
  3828. sub remove_tmp_files {
  3829. my $mysync = shift or return ;
  3830. $mysync->{pidfile} or return ;
  3831. if ( -e $mysync->{pidfile} ) {
  3832. unlink $mysync->{pidfile} ;
  3833. }
  3834. return ;
  3835. }
  3836. sub exit_clean {
  3837. my $mysync = shift ;
  3838. my $status = shift ;
  3839. $status = defined $status ? $status : $EXIT_UNKNOWN ;
  3840. remove_tmp_files( $mysync ) ;
  3841. myprint( "Exiting with return value $status\n" ) ;
  3842. if ( $mysync->{log} ) {
  3843. myprint( "Log file is $mysync->{logfile} ( to change it, use --logfile filepath ; or use --nolog to turn off logging )\n" ) ;
  3844. close $mysync->{logfile_handle} ;
  3845. }
  3846. exit $status ;
  3847. }
  3848. sub die_clean {
  3849. my @messages = @_ ;
  3850. remove_tmp_files( $sync ) ;
  3851. myprint( @messages ) ;
  3852. exit 255 ;
  3853. }
  3854. sub missing_option {
  3855. my ( $option ) = @_ ;
  3856. die_clean( "$option option is mandatory, for help run $PROGRAM_NAME --help\n" ) ;
  3857. return ;
  3858. }
  3859. sub fix_Inbox_INBOX_mapping {
  3860. my( $h1_all, $h2_all ) = @_ ;
  3861. my $regex = q{} ;
  3862. SWITCH: {
  3863. if ( exists $h1_all->{INBOX} and exists $h2_all->{INBOX} ) { $regex = q{} ; last SWITCH ; } ;
  3864. if ( exists $h1_all->{Inbox} and exists $h2_all->{Inbox} ) { $regex = q{} ; last SWITCH ; } ;
  3865. if ( exists $h1_all->{INBOX} and exists $h2_all->{Inbox} ) { $regex = q{s/^INBOX$/Inbox/x} ; last SWITCH ; } ;
  3866. if ( exists $h1_all->{Inbox} and exists $h2_all->{INBOX} ) { $regex = q{s/^Inbox$/INBOX/x} ; last SWITCH ; } ;
  3867. } ;
  3868. return( $regex ) ;
  3869. }
  3870. sub tests_fix_Inbox_INBOX_mapping {
  3871. note( 'Entering tests_fix_Inbox_INBOX_mapping()' ) ;
  3872. my( $h1_all, $h2_all ) ;
  3873. $h1_all = { 'INBOX' => q{} } ;
  3874. $h2_all = { 'INBOX' => q{} } ;
  3875. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX INBOX' ) ;
  3876. $h1_all = { 'Inbox' => q{} } ;
  3877. $h2_all = { 'Inbox' => q{} } ;
  3878. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox Inbox' ) ;
  3879. $h1_all = { 'INBOX' => q{} } ;
  3880. $h2_all = { 'Inbox' => q{} } ;
  3881. ok( q{s/^INBOX$/Inbox/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX Inbox' ) ;
  3882. $h1_all = { 'Inbox' => q{} } ;
  3883. $h2_all = { 'INBOX' => q{} } ;
  3884. ok( q{s/^Inbox$/INBOX/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox INBOX' ) ;
  3885. $h1_all = { 'INBOX' => q{} } ;
  3886. $h2_all = { 'rrrrr' => q{} } ;
  3887. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX rrrrrr' ) ;
  3888. $h1_all = { 'rrrrr' => q{} } ;
  3889. $h2_all = { 'Inbox' => q{} } ;
  3890. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: rrrrr Inbox' ) ;
  3891. note( 'Leaving tests_fix_Inbox_INBOX_mapping()' ) ;
  3892. return ;
  3893. }
  3894. sub jux_utf8_list {
  3895. my @s_inp = @_ ;
  3896. my $s_out = q{} ;
  3897. foreach my $s ( @s_inp ) {
  3898. $s_out .= jux_utf8( $s ) . "\n" ;
  3899. }
  3900. return( $s_out ) ;
  3901. }
  3902. sub tests_jux_utf8_list {
  3903. note( 'Entering tests_jux_utf8_list()' ) ;
  3904. ok( q{} eq jux_utf8_list( ), 'jux_utf8_list: void' ) ;
  3905. ok( "[]\n" eq jux_utf8_list( q{} ), 'jux_utf8_list: empty string' ) ;
  3906. ok( "[INBOX]\n" eq jux_utf8_list( 'INBOX' ), 'jux_utf8_list: INBOX' ) ;
  3907. ok( "[&ANY-] = [Ö]\n" eq jux_utf8_list( '&ANY-' ), 'jux_utf8_list: &ANY-' ) ;
  3908. note( 'Leaving tests_jux_utf8_list()' ) ;
  3909. return( 0 ) ;
  3910. }
  3911. sub jux_utf8 {
  3912. # juxtapose utf8 at the right if different
  3913. my ( $s_utf7 ) = shift ;
  3914. my ( $s_utf8 ) = imap_utf7_decode( $s_utf7 ) ;
  3915. if ( $s_utf7 eq $s_utf8 ) {
  3916. #myprint( "[$s_utf7]\n" ) ;
  3917. return( "[$s_utf7]" ) ;
  3918. }else{
  3919. #myprint( "[$s_utf7] = [$s_utf8]\n" ) ;
  3920. return( "[$s_utf7] = [$s_utf8]" ) ;
  3921. }
  3922. }
  3923. # editing utf8 can be tricky without an utf8 editor
  3924. sub tests_jux_utf8 {
  3925. note( 'Entering tests_jux_utf8()' ) ;
  3926. ok( '[INBOX]' eq jux_utf8( 'INBOX'), 'jux_utf8: INBOX => [INBOX]' ) ;
  3927. ok( '[&ZTZO9nux-] = [收件箱]' eq jux_utf8( '&ZTZO9nux-'), 'jux_utf8: => [&ZTZO9nux-] = [收件箱]' ) ;
  3928. ok( '[&ANY-] = [Ö]' eq jux_utf8( '&ANY-'), 'jux_utf8: &ANY- => [&ANY-] = [Ö]' ) ;
  3929. ok( '[]' eq jux_utf8( q{} ), 'jux_utf8: void => []' ) ;
  3930. ok( '[+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]' eq jux_utf8( '+BD8EQAQ1BDQEOwQ+BDM-' ), 'jux_utf8: => [+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]' ) ;
  3931. ok( '[&BB8EQAQ+BDUEOgRC-] = [Проект]' eq jux_utf8( '&BB8EQAQ+BDUEOgRC-' ), 'jux_utf8: => [&BB8EQAQ+BDUEOgRC-] = [Проект]' ) ;
  3932. note( 'Leaving tests_jux_utf8()' ) ;
  3933. return ;
  3934. }
  3935. # Copied from http://cpansearch.perl.org/src/FABPOT/Unicode-IMAPUtf7-2.01/lib/Unicode/IMAPUtf7.pm
  3936. # and then fixed with
  3937. # https://rt.cpan.org/Public/Bug/Display.html?id=11172
  3938. sub imap_utf7_decode {
  3939. my ( $s ) = shift ;
  3940. # Algorithm
  3941. # On remplace , par / dans les BASE 64 (, entre & et -)
  3942. # On remplace les &, non suivi d'un - par +
  3943. # On remplace les &- par &
  3944. $s =~ s/&([^,&\-]*),([^,\-&]*)\-/&$1\/$2\-/xg ;
  3945. $s =~ s/&(?!\-)/\+/xg ;
  3946. $s =~ s/&\-/&/xg ;
  3947. return( Unicode::String::utf7( $s )->utf8 ) ;
  3948. }
  3949. sub imap_utf7_encode {
  3950. my ( $s ) = @_ ;
  3951. $s = Unicode::String::utf8( $s )->utf7 ;
  3952. $s =~ s/\+([^\/&\-]*)\/([^\/\-&]*)\-/\+$1,$2\-/xg ;
  3953. $s =~ s/&/&\-/xg ;
  3954. $s =~ s/\+([^+\-]+)?\-/&$1\-/xg ;
  3955. return( $s ) ;
  3956. }
  3957. sub select_folder {
  3958. my ( $imap, $folder, $hostside ) = @_ ;
  3959. if ( ! $imap->select( $folder ) ) {
  3960. my $error = join q{},
  3961. "$hostside folder $folder: Could not select: ",
  3962. $imap->LastError, "\n" ;
  3963. errors_incr( $sync, $error ) ;
  3964. return( 0 ) ;
  3965. }else{
  3966. # ok select succeeded
  3967. return( 1 ) ;
  3968. }
  3969. }
  3970. sub examine_folder {
  3971. my ( $imap, $folder, $hostside ) = @_ ;
  3972. if ( ! $imap->examine( $folder ) ) {
  3973. my $error = join q{},
  3974. "$hostside folder $folder: Could not examine: ",
  3975. $imap->LastError, "\n" ;
  3976. errors_incr( $sync, $error ) ;
  3977. return( 0 ) ;
  3978. }else{
  3979. # ok select succeeded
  3980. return( 1 ) ;
  3981. }
  3982. }
  3983. sub count_from_select {
  3984. my @lines = @_ ;
  3985. my $count ;
  3986. foreach my $line ( @lines ) {
  3987. #myprint( "line = [$line]\n" ) ;
  3988. if ( $line =~ m/^\*\s+(\d+)\s+EXISTS/x ) {
  3989. $count = $1 ;
  3990. return( $count ) ;
  3991. }
  3992. }
  3993. return( undef ) ;
  3994. }
  3995. sub create_folder_old {
  3996. my( $imap, $h2_fold, $h1_fold ) = @_ ;
  3997. myprint( "Creating (old way) folder [$h2_fold] on host2\n" ) ;
  3998. if ( ( 'INBOX' eq uc $h2_fold )
  3999. and ( $imap->exists( $h2_fold ) ) ) {
  4000. myprint( "Folder [$h2_fold] already exists\n" ) ;
  4001. return( 1 ) ;
  4002. }
  4003. if ( ! $sync->{dry} ){
  4004. if ( ! $imap->create( $h2_fold ) ) {
  4005. my $error = join q{},
  4006. "Could not create folder [$h2_fold] from [$h1_fold]: ",
  4007. $imap->LastError( ), "\n" ;
  4008. errors_incr( $sync, $error ) ;
  4009. # success if folder exists ("already exists" error)
  4010. return( 1 ) if $imap->exists( $h2_fold ) ;
  4011. # failure since create failed
  4012. return( 0 ) ;
  4013. }else{
  4014. #create succeeded
  4015. myprint( "Created ( the old way ) folder [$h2_fold] on host2\n" ) ;
  4016. return( 1 ) ;
  4017. }
  4018. }else{
  4019. # dry mode, no folder so many imap will fail, assuming failure
  4020. myprint( "Created ( the old way ) folder [$h2_fold] on host2 $sync->{dry_message}\n" ) ;
  4021. return( 0 ) ;
  4022. }
  4023. }
  4024. sub create_folder {
  4025. my( $imap2 , $h2_fold , $h1_fold ) = @_ ;
  4026. my( @parts , $parent ) ;
  4027. if ( $imap2->IsUnconnected( ) ) {
  4028. myprint( "Host2: Unconnected state\n" ) ;
  4029. return( 0 ) ;
  4030. }
  4031. if ( $create_folder_old ) {
  4032. return( create_folder_old( $imap2 , $h2_fold , $h1_fold ) ) ;
  4033. }
  4034. myprint( "Creating folder [$h2_fold] on host2\n" ) ;
  4035. if ( ( 'INBOX' eq uc $h2_fold )
  4036. and ( $imap2->exists( $h2_fold ) ) ) {
  4037. myprint( "Folder [$h2_fold] already exists\n" ) ;
  4038. return( 1 ) ;
  4039. }
  4040. if ( $mixfolders and $imap2->exists( $h2_fold ) ) {
  4041. myprint( "Folder [$h2_fold] already exists (--nomixfolders is not set)\n" ) ;
  4042. return( 1 ) ;
  4043. }
  4044. if ( ( not $mixfolders ) and ( $imap2->exists( $h2_fold ) ) ) {
  4045. myprint( "Folder [$h2_fold] already exists and --nomixfolders is set\n" ) ;
  4046. return( 0 ) ;
  4047. }
  4048. @parts = split /\Q$h2_sep\E/x, $h2_fold ;
  4049. pop @parts ;
  4050. $parent = join $h2_sep, @parts ;
  4051. $parent =~ s/^\s+|\s+$//xg ;
  4052. if ( ( $parent ne q{} ) and ( ! $imap2->exists( $parent ) ) ) {
  4053. create_folder( $imap2 , $parent , $h1_fold ) ;
  4054. }
  4055. if ( ! $sync->{dry} ) {
  4056. if ( ! $imap2->create( $h2_fold ) ) {
  4057. my $error = join q{},
  4058. "Could not create folder [$h2_fold] from [$h1_fold]: " ,
  4059. $imap2->LastError( ), "\n" ;
  4060. errors_incr( $sync, $error ) ;
  4061. # success if folder exists ("already exists" error)
  4062. return( 1 ) if $imap2->exists( $h2_fold ) ;
  4063. # failure since create failed
  4064. return( 0 ) ;
  4065. }else{
  4066. #create succeeded
  4067. myprint( "Created folder [$h2_fold] on host2\n" ) ;
  4068. return( 1 ) ;
  4069. }
  4070. }else{
  4071. # dry mode, no folder so many imap will fail, assuming failure
  4072. myprint( "Created folder [$h2_fold] on host2 $sync->{dry_message}\n" ) ;
  4073. if ( ! $justfolders ) {
  4074. myprint( "Since --dry mode is on and folder [$h2_fold] on host2 does not exist yet, syncing messages will not be simulated.\n"
  4075. . "To simulate message syncing, use --justfolders without --dry to first create the missing folders then rerun the --dry sync.\n" ) ;
  4076. }
  4077. return( 0 ) ;
  4078. }
  4079. }
  4080. sub tests_folder_routines {
  4081. note( 'Entering tests_folder_routines()' ) ;
  4082. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 1' );
  4083. ok( add_to_requested_folders('folder_foo'), 'add_to_requested_folders folder_foo' );
  4084. ok( is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 2' );
  4085. ok( !is_requested_folder('folder_NO_EXIST'), 'is_requested_folder folder_NO_EXIST' );
  4086. ok( !remove_from_requested_folders('folder_foo'), 'removed folder_foo' );
  4087. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 3' );
  4088. my @f ;
  4089. ok( @f = add_to_requested_folders('folder_bar', 'folder_toto'), "add result: @f" );
  4090. ok( is_requested_folder('folder_bar'), 'is_requested_folder 4' );
  4091. ok( is_requested_folder('folder_toto'), 'is_requested_folder 5' );
  4092. ok( remove_from_requested_folders('folder_toto'), 'remove_from_requested_folders: ' );
  4093. ok( !is_requested_folder('folder_toto'), 'is_requested_folder 6' );
  4094. ok( !remove_from_requested_folders('folder_bar'), 'remove_from_requested_folders: empty' ) ;
  4095. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [] ), 'sort_requested_folders: all empty' ) ;
  4096. ok( add_to_requested_folders('M_55'), 'add_to_requested_folders M_55' );
  4097. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'M_55' ] ), 'sort_requested_folders: middle' ) ;
  4098. @folderfirst = ( 'Z_11' ) ;
  4099. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_55' ] ), 'sort_requested_folders: first+middle' ) ;
  4100. @folderlast = ( 'A_99' ) ;
  4101. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_55', 'A_99' ] ), 'sort_requested_folders: first+middle+last 1' ) ;
  4102. ok( add_to_requested_folders('M_55', 'M_44',), 'add_to_requested_folders M_55 M_44' );
  4103. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_44', 'M_55', 'A_99' ] ), 'sort_requested_folders: first+middle+last 2' ) ;
  4104. @folderfirst = qw( Z_22 Z_11 ) ;
  4105. @folderlast = qw( A_99 A_88 ) ;
  4106. 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' ) ;
  4107. note( 'Leaving tests_folder_routines()' ) ;
  4108. return ;
  4109. }
  4110. sub sort_requested_folders {
  4111. my @requested_folders_sorted = () ;
  4112. foreach my $folder ( @folderfirst ) {
  4113. remove_from_requested_folders( $folder ) ;
  4114. }
  4115. foreach my $folder ( @folderlast ) {
  4116. remove_from_requested_folders( $folder ) ;
  4117. }
  4118. my @middle = sort keys %requested_folder ;
  4119. @requested_folders_sorted = ( @folderfirst, @middle, @folderlast ) ;
  4120. return( @requested_folders_sorted ) ;
  4121. }
  4122. sub is_requested_folder {
  4123. my ( $folder ) = @_;
  4124. return( defined $requested_folder{ $folder } ) ;
  4125. }
  4126. sub add_to_requested_folders {
  4127. my @wanted_folders = @_ ;
  4128. foreach my $folder ( @wanted_folders ) {
  4129. ++$requested_folder{ $folder } ;
  4130. }
  4131. return( keys %requested_folder ) ;
  4132. }
  4133. sub remove_from_requested_folders {
  4134. my @wanted_folders = @_ ;
  4135. foreach my $folder ( @wanted_folders ) {
  4136. delete $requested_folder{ $folder } ;
  4137. }
  4138. return( keys %requested_folder ) ;
  4139. }
  4140. sub compare_lists {
  4141. my ($list_1_ref, $list_2_ref) = @_;
  4142. return($MINUS_ONE) if ((not defined $list_1_ref) and defined $list_2_ref);
  4143. return(0) if ((not defined $list_1_ref) and not defined $list_2_ref); # end if no list
  4144. return(1) if (not defined $list_2_ref); # end if only one list
  4145. if (not ref $list_1_ref ) {$list_1_ref = [$list_1_ref]};
  4146. if (not ref $list_2_ref ) {$list_2_ref = [$list_2_ref]};
  4147. my $last_used_indice = $MINUS_ONE;
  4148. ELEMENT:
  4149. foreach my $indice ( 0 .. $#{ $list_1_ref } ) {
  4150. $last_used_indice = $indice ;
  4151. # End of list_2
  4152. return 1 if ($indice > $#{ $list_2_ref } ) ;
  4153. my $element_list_1 = $list_1_ref->[$indice] ;
  4154. my $element_list_2 = $list_2_ref->[$indice] ;
  4155. my $balance = $element_list_1 cmp $element_list_2 ;
  4156. next ELEMENT if ($balance == 0) ;
  4157. return $balance ;
  4158. }
  4159. # each element equal until last indice of list_1
  4160. return $MINUS_ONE if ($last_used_indice < $#{ $list_2_ref } ) ;
  4161. # same size, each element equal
  4162. return 0 ;
  4163. }
  4164. sub tests_compare_lists {
  4165. note( 'Entering tests_compare_lists()' ) ;
  4166. my $empty_list_ref = [];
  4167. ok( 0 == compare_lists() , 'compare_lists, no args');
  4168. ok( 0 == compare_lists(undef) , 'compare_lists, undef = nothing');
  4169. ok( 0 == compare_lists(undef, undef) , 'compare_lists, undef = undef');
  4170. ok($MINUS_ONE == compare_lists(undef , []) , 'compare_lists, undef < []');
  4171. ok($MINUS_ONE == compare_lists(undef , [1]) , 'compare_lists, undef < [1]');
  4172. ok($MINUS_ONE == compare_lists(undef , [0]) , 'compare_lists, undef < [0]');
  4173. ok(+1 == compare_lists([]) , 'compare_lists, [] > nothing');
  4174. ok(+1 == compare_lists([], undef) , 'compare_lists, [] > undef');
  4175. ok( 0 == compare_lists([] , []) , 'compare_lists, [] = []');
  4176. ok($MINUS_ONE == compare_lists([] , [1]) , 'compare_lists, [] < [1]');
  4177. ok(+1 == compare_lists([1] , []) , 'compare_lists, [1] > []');
  4178. ok( 0 == compare_lists([1], 1 ) , 'compare_lists, [1] = 1 ') ;
  4179. ok( 0 == compare_lists( 1 , [1]) , 'compare_lists, 1 = [1]') ;
  4180. ok( 0 == compare_lists( 1 , 1 ) , 'compare_lists, 1 = 1 ') ;
  4181. ok($MINUS_ONE == compare_lists( 0 , 1 ) , 'compare_lists, 0 < 1 ') ;
  4182. ok($MINUS_ONE == compare_lists($MINUS_ONE , 0 ) , 'compare_lists, -1 < 0 ') ;
  4183. ok($MINUS_ONE == compare_lists( 1 , 2 ) , 'compare_lists, 1 < 2 ') ;
  4184. ok(+1 == compare_lists( 2 , 1 ) , 'compare_lists, 2 > 1 ') ;
  4185. ok( 0 == compare_lists([1,2], [1,2]) , 'compare_lists, [1,2] = [1,2]' ) ;
  4186. ok($MINUS_ONE == compare_lists([1], [1,2]) , 'compare_lists, [1] < [1,2]' ) ;
  4187. ok(+1 == compare_lists([2], [1,2]) , 'compare_lists, [2] > [1,2]' ) ;
  4188. ok($MINUS_ONE == compare_lists([1], [1,1]) , 'compare_lists, [1] < [1,1]' ) ;
  4189. ok(+1 == compare_lists([1, 1], [1]) , 'compare_lists, [1, 1] > [1]' ) ;
  4190. ok( 0 == compare_lists([1 .. $NUMBER_20_000] , [1 .. $NUMBER_20_000])
  4191. , 'compare_lists, [1..20_000] = [1..20_000]' ) ;
  4192. ok($MINUS_ONE == compare_lists([1], [2]) , 'compare_lists, [1] < [2]') ;
  4193. ok( 0 == compare_lists([2], [2]) , 'compare_lists, [0] = [2]') ;
  4194. ok(+1 == compare_lists([2], [1]) , 'compare_lists, [2] > [1]') ;
  4195. ok($MINUS_ONE == compare_lists(['a'], ['b']) , 'compare_lists, ["a"] < ["b"]') ;
  4196. ok( 0 == compare_lists(['a'], ['a']) , 'compare_lists, ["a"] = ["a"]') ;
  4197. ok( 0 == compare_lists(['ab'], ['ab']) , 'compare_lists, ["ab"] = ["ab"]') ;
  4198. ok(+1 == compare_lists(['b'], ['a']) , 'compare_lists, ["b"] > ["a"]') ;
  4199. ok($MINUS_ONE == compare_lists(['a'], ['aa']) , 'compare_lists, ["a"] < ["aa"]') ;
  4200. ok($MINUS_ONE == compare_lists(['a'], ['a', 'a']), 'compare_lists, ["a"] < ["a", "a"]') ;
  4201. ok( 0 == compare_lists([split q{ }, 'a b' ], ['a', 'b']), 'compare_lists, split') ;
  4202. ok( 0 == compare_lists([sort split q{ }, 'b a' ], ['a', 'b']), 'compare_lists, sort split') ;
  4203. note( 'Leaving tests_compare_lists()' ) ;
  4204. return ;
  4205. }
  4206. sub guess_prefix {
  4207. my @foldernames = @_ ;
  4208. my $prefix_guessed = q{} ;
  4209. foreach my $folder ( @foldernames ) {
  4210. next if ( $folder =~ m{^INBOX$}xi ) ; # no guessing from INBOX
  4211. if ( $folder !~ m{^INBOX}xi ) {
  4212. $prefix_guessed = q{} ; # prefix empty guessed
  4213. last ;
  4214. }
  4215. if ( $folder =~ m{^(INBOX(?:\.|\/))}xi ) {
  4216. $prefix_guessed = $1 ; # prefix Inbox/ or INBOX. guessed
  4217. }
  4218. }
  4219. return( $prefix_guessed ) ;
  4220. }
  4221. sub tests_guess_prefix {
  4222. note( 'Entering tests_guess_prefix()' ) ;
  4223. is( guess_prefix( ), q{}, 'guess_prefix: no args => empty string' ) ;
  4224. is( q{} , guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  4225. is( q{} , guess_prefix( 'Inbox' ), 'guess_prefix: Inbox alone' ) ;
  4226. is( q{} , guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  4227. is( 'INBOX/' , guess_prefix( 'INBOX', 'INBOX/Junk' ), 'guess_prefix: INBOX INBOX/Junk' ) ;
  4228. is( 'INBOX.' , guess_prefix( 'INBOX', 'INBOX.Junk' ), 'guess_prefix: INBOX INBOX.Junk' ) ;
  4229. is( 'Inbox/' , guess_prefix( 'Inbox', 'Inbox/Junk' ), 'guess_prefix: Inbox Inbox/Junk' ) ;
  4230. is( 'Inbox.' , guess_prefix( 'Inbox', 'Inbox.Junk' ), 'guess_prefix: Inbox Inbox.Junk' ) ;
  4231. is( 'INBOX/' , guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr' ) ;
  4232. is( q{} , guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr', 'zzz' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr zzz' ) ;
  4233. is( q{} , guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  4234. is( q{} , guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  4235. note( 'Leaving tests_guess_prefix()' ) ;
  4236. return ;
  4237. }
  4238. sub get_prefix {
  4239. my( $imap, $prefix_in, $prefix_opt, $Side, $folders_ref ) = @_ ;
  4240. my( $prefix_out, $prefix_guessed ) ;
  4241. ( $debug or $sync->{debugfolders} ) and myprint( "$Side: Getting prefix\n" ) ;
  4242. $prefix_guessed = guess_prefix( @{ $folders_ref } ) ;
  4243. myprint( "$Side: guessing prefix from folder listing: [$prefix_guessed]\n" ) ;
  4244. ( $debug or $sync->{debugfolders} ) and myprint( "$Side: Calling namespace capability\n" ) ;
  4245. if ( $imap->has_capability( 'namespace' ) ) {
  4246. my $r_namespace = $imap->namespace( ) ;
  4247. $prefix_out = $r_namespace->[0][0][0] ;
  4248. myprint( "$Side: prefix given by NAMESPACE: [$prefix_out]\n" ) ;
  4249. if ( defined $prefix_in ) {
  4250. myprint( "$Side: but using [$prefix_in] given by $prefix_opt\n" ) ;
  4251. $prefix_out = $prefix_in ;
  4252. return( $prefix_out ) ;
  4253. }else{
  4254. # all good
  4255. return( $prefix_out ) ;
  4256. }
  4257. }
  4258. else{
  4259. if ( defined $prefix_in ) {
  4260. myprint( "$Side: using [$prefix_in] given by $prefix_opt\n" ) ;
  4261. $prefix_out = $prefix_in ;
  4262. return( $prefix_out ) ;
  4263. }else{
  4264. myprint(
  4265. "$Side: No NAMESPACE capability so using guessed prefix [$prefix_guessed]\n",
  4266. help_to_guess_prefix( $imap, $prefix_opt ) ) ;
  4267. return( $prefix_guessed ) ;
  4268. }
  4269. }
  4270. return ;
  4271. }
  4272. sub guess_separator {
  4273. my @foldernames = @_ ;
  4274. #return( undef ) unless ( @foldernames ) ;
  4275. my $sep_guessed ;
  4276. my %counter ;
  4277. foreach my $folder ( @foldernames ) {
  4278. $counter{'/'}++ while ( $folder =~ m{/}xg ) ; # count /
  4279. $counter{'.'}++ while ( $folder =~ m{\.}xg ) ; # count .
  4280. $counter{'\\\\'}++ while ( $folder =~ m{(\\){2}}xg ) ; # count \\
  4281. $counter{'\\'}++ while ( $folder =~ m{[^\\](\\){1}(?=[^\\])}xg ) ; # count \
  4282. }
  4283. my @race_sorted = sort { $counter{ $b } <=> $counter{ $a } } keys %counter ;
  4284. $debug and myprint( "@foldernames\n@race_sorted\n", %counter, "\n" ) ;
  4285. $sep_guessed = shift @race_sorted || $LAST_RESSORT_SEPARATOR ; # / when nothing found.
  4286. return( $sep_guessed ) ;
  4287. }
  4288. sub tests_guess_separator {
  4289. note( 'Entering tests_guess_separator()' ) ;
  4290. ok( '/' eq guess_separator( ), 'guess_separator: no args' ) ;
  4291. ok( '/' eq guess_separator( 'abcd' ), 'guess_separator: abcd' ) ;
  4292. ok( '/' eq guess_separator( 'a/b/c.d' ), 'guess_separator: a/b/c.d' ) ;
  4293. ok( '.' eq guess_separator( 'a.b/c.d' ), 'guess_separator: a.b/c.d' ) ;
  4294. ok( '\\\\' eq guess_separator( 'a\\\\b\\\\c.c\\\\d/e/f' ), 'guess_separator: a\\\\b\\\\c.c\\\\d/e/f' ) ;
  4295. ok( '\\' eq guess_separator( 'a\\b\\c.c\\d/e/f' ), 'guess_separator: a\\b\\c.c\\d/e/f' ) ;
  4296. ok( '\\' eq guess_separator( 'a\\b' ), 'guess_separator: a\\b' ) ;
  4297. ok( '\\' eq guess_separator( 'a\\b\\c' ), 'guess_separator: a\\b\\c' ) ;
  4298. note( 'Leaving tests_guess_separator()' ) ;
  4299. return ;
  4300. }
  4301. sub get_separator {
  4302. my( $imap, $sep_in, $sep_opt, $Side, $folders_ref ) = @_ ;
  4303. my( $sep_out, $sep_guessed ) ;
  4304. ( $debug or $sync->{debugfolders} ) and myprint( "$Side: Getting separator\n" ) ;
  4305. $sep_guessed = guess_separator( @{ $folders_ref } ) ;
  4306. myprint( "$Side: guessing separator from folder listing: [$sep_guessed]\n" ) ;
  4307. ( $debug or $sync->{debugfolders} ) and myprint( "$Side: calling namespace capability\n" ) ;
  4308. if ( $imap->has_capability( 'namespace' ) ) {
  4309. $sep_out = $imap->separator( ) ;
  4310. if ( defined $sep_out ) {
  4311. myprint( "$Side: separator given by NAMESPACE: [$sep_out]\n" ) ;
  4312. if ( defined $sep_in ) {
  4313. myprint( "$Side: but using [$sep_in] given by $sep_opt\n" ) ;
  4314. $sep_out = $sep_in ;
  4315. return( $sep_out ) ;
  4316. }else{
  4317. return( $sep_out ) ;
  4318. }
  4319. }else{
  4320. if ( defined $sep_in ) {
  4321. myprint( "$Side: NAMESPACE request failed but using [$sep_in] given by $sep_opt\n" ) ;
  4322. $sep_out = $sep_in ;
  4323. return( $sep_out ) ;
  4324. }else{
  4325. myprint(
  4326. "$Side: NAMESPACE request failed so using guessed separator [$sep_guessed]\n",
  4327. help_to_guess_sep( $imap, $sep_opt ) ) ;
  4328. return( $sep_guessed ) ;
  4329. }
  4330. }
  4331. }
  4332. else{
  4333. if ( defined $sep_in ) {
  4334. myprint( "$Side: No NAMESPACE capability but using [$sep_in] given by $sep_opt\n" ) ;
  4335. $sep_out = $sep_in ;
  4336. return( $sep_out ) ;
  4337. }else{
  4338. myprint(
  4339. "$Side: No NAMESPACE capability, so using guessed separator [$sep_guessed]\n",
  4340. help_to_guess_sep( $imap, $sep_opt ) ) ;
  4341. return( $sep_guessed ) ;
  4342. }
  4343. }
  4344. return ;
  4345. }
  4346. sub help_to_guess_sep {
  4347. my( $imap, $sep_opt ) = @_ ;
  4348. my $help_to_guess_sep = "You can set the separator character with the $sep_opt option,\n"
  4349. . "the complete listing of folders may help you to find it\n"
  4350. . folders_list_to_help( $imap ) ;
  4351. return( $help_to_guess_sep ) ;
  4352. }
  4353. sub help_to_guess_prefix {
  4354. my( $imap, $prefix_opt ) = @_ ;
  4355. my $help_to_guess_prefix = "You can set the prefix namespace with the $prefix_opt option,\n"
  4356. . "the folowing listing of folders may help you to find it:\n"
  4357. . folders_list_to_help( $imap ) ;
  4358. return( $help_to_guess_prefix ) ;
  4359. }
  4360. sub folders_list_to_help {
  4361. my( $imap ) = shift ;
  4362. my @folders = $imap->folders ;
  4363. my $listing = join q{}, map { "[$_]\n" } @folders ;
  4364. return( $listing ) ;
  4365. }
  4366. sub tests_imap2_folder_name {
  4367. note( 'Entering tests_imap2_folder_name()' ) ;
  4368. $sync->{ h1_prefix } = $sync->{ h2_prefix } = q{} ;
  4369. $h1_sep = '/';
  4370. $h2_sep = '.';
  4371. $debug and myprint( <<"EOS"
  4372. prefix1: [$sync->{ h1_prefix }]
  4373. prefix2: [$sync->{ h2_prefix }]
  4374. sep1:[$h1_sep]
  4375. sep2:[$h2_sep]
  4376. EOS
  4377. ) ;
  4378. $fixslash2 = 0 ;
  4379. ok(q{} eq imap2_folder_name(q{}), 'imap2_folder_name: empty string');
  4380. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla');
  4381. ok('spam.spam' eq imap2_folder_name('spam/spam'), 'imap2_folder_name: spam/spam');
  4382. ok('spam/spam' eq imap2_folder_name('spam.spam'), 'imap2_folder_name: spam.spam');
  4383. ok('spam.spam/spam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam');
  4384. ok('s pam.spam/sp am' eq imap2_folder_name('s pam/spam.sp am'), 'imap2_folder_name: s pam/spam.sp am');
  4385. $sync->{f1f2h}{ 'auto' } = 'moto' ;
  4386. ok( 'moto' eq imap2_folder_name( 'auto' ), 'imap2_folder_name: auto' ) ;
  4387. $sync->{f1f2h}{ 'auto/auto' } = 'moto x 2' ;
  4388. ok( 'moto x 2' eq imap2_folder_name( 'auto/auto' ), 'imap2_folder_name: auto/auto' ) ;
  4389. @regextrans2 = ('s,/,X,g');
  4390. ok(q{} eq imap2_folder_name(q{}), 'imap2_folder_name: empty string [s,/,X,g]');
  4391. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla [s,/,X,g]');
  4392. ok('spam.spam' eq imap2_folder_name('spam/spam'), 'imap2_folder_name: spam/spam [s,/,X,g]');
  4393. ok('spamXspam' eq imap2_folder_name('spam.spam'), 'imap2_folder_name: spam.spam [s,/,X,g]');
  4394. ok('spam.spamXspam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam [s,/,X,g]');
  4395. @regextrans2 = ( 's, ,_,g' ) ;
  4396. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla [s, ,_,g]');
  4397. ok('bla_bla' eq imap2_folder_name('bla bla'), 'imap2_folder_name: blabla [s, ,_,g]');
  4398. @regextrans2 = ( q{s,(.*),\U$1,} ) ;
  4399. ok( 'BLABLA' eq imap2_folder_name( 'blabla' ), q{imap2_folder_name: blabla [s,\U(.*)\E,$1,]} ) ;
  4400. $fixslash2 = 1 ;
  4401. @regextrans2 = ( ) ;
  4402. ok(q{} eq imap2_folder_name(q{}), 'imap2_folder_name: empty string');
  4403. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla');
  4404. ok('spam.spam' eq imap2_folder_name('spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  4405. ok('spam_spam' eq imap2_folder_name('spam.spam'), 'imap2_folder_name: spam.spam -> spam_spam');
  4406. ok('spam.spam_spam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam_spam');
  4407. 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');
  4408. $h1_sep = '.';
  4409. $h2_sep = '/';
  4410. ok(q{} eq imap2_folder_name(q{}), 'imap2_folder_name: empty string');
  4411. ok('blabla' eq imap2_folder_name('blabla'), 'imap2_folder_name: blabla');
  4412. ok('spam.spam' eq imap2_folder_name('spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  4413. ok('spam/spam' eq imap2_folder_name('spam.spam'), 'imap2_folder_name: spam.spam -> spam/spam');
  4414. ok('spam.spam/spam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam');
  4415. $fixslash2 = 0 ;
  4416. $sync->{ h1_prefix } = q{ };
  4417. ok('spam.spam/spam' eq imap2_folder_name('spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam');
  4418. ok('spam.spam/spam' eq imap2_folder_name(' spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam');
  4419. $h1_sep = '.' ;
  4420. $h2_sep = '/' ;
  4421. $sync->{ h1_prefix } = 'INBOX.' ;
  4422. $sync->{ h2_prefix } = q{} ;
  4423. @regextrans2 = ( q{s,(.*),\U$1,} ) ;
  4424. ok( 'BLABLA' eq imap2_folder_name( 'blabla' ), 'imap2_folder_name: blabla' ) ;
  4425. ok( 'TEST/TEST/TEST/TEST' eq imap2_folder_name( 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  4426. @regextrans2 = ( q{s,(.*),\L$1,} ) ;
  4427. ok( 'test/test/test/test' eq imap2_folder_name( 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  4428. note( 'Leaving tests_imap2_folder_name()' ) ;
  4429. return ;
  4430. }
  4431. # Global variables to remove:
  4432. # $debug
  4433. # $sync
  4434. sub imap2_folder_name {
  4435. my $mysync = $sync ; # will be soon next line
  4436. #my $mysync = shift ;
  4437. my ( $h1_fold ) = shift ;
  4438. my ( $h2_fold ) ;
  4439. if ( $mysync->{f1f2h}{ $h1_fold } ) {
  4440. $h2_fold = $mysync->{f1f2h}{ $h1_fold } ;
  4441. ( $debug or $mysync->{debugfolders} ) and myprint( "f1f2 [$h1_fold] -> [$h2_fold]\n" ) ;
  4442. return( $h2_fold ) ;
  4443. }
  4444. if ( $mysync->{f1f2auto}{ $h1_fold } ) {
  4445. $h2_fold = $mysync->{f1f2auto}{ $h1_fold } ;
  4446. ( $debug or $mysync->{debugfolders} ) and myprint( "automap [$h1_fold] -> [$h2_fold]\n" ) ;
  4447. return( $h2_fold ) ;
  4448. }
  4449. $h2_fold = prefix_seperator_invertion( $mysync, $h1_fold ) ;
  4450. $h2_fold = regextrans2( $h2_fold ) ;
  4451. return( $h2_fold ) ;
  4452. }
  4453. sub tests_prefix_seperator_invertion {
  4454. undef $h1_sep;
  4455. undef $h2_sep ;
  4456. is( undef, prefix_seperator_invertion( ), 'prefix_seperator_invertion: no args => undef' ) ;
  4457. is( q{}, prefix_seperator_invertion( undef, q{} ), 'prefix_seperator_invertion: empty string => empty string' ) ;
  4458. is( 'lalala', prefix_seperator_invertion( undef, 'lalala' ), 'prefix_seperator_invertion: lalala => lalala' ) ;
  4459. is( 'lal/ala', prefix_seperator_invertion( undef, 'lal/ala' ), 'prefix_seperator_invertion: lal/ala => lal/ala' ) ;
  4460. is( 'lal.ala', prefix_seperator_invertion( undef, 'lal.ala' ), 'prefix_seperator_invertion: lal.ala => lal.ala' ) ;
  4461. is( '////', prefix_seperator_invertion( undef, '////' ), 'prefix_seperator_invertion: //// => ////' ) ;
  4462. is( '.....', prefix_seperator_invertion( undef, '.....' ), 'prefix_seperator_invertion: ..... => .....' ) ;
  4463. my $mysync = {
  4464. h1_prefix => '',
  4465. h2_prefix => '',
  4466. h1_sep => '/',
  4467. h2_sep => '/',
  4468. } ;
  4469. is( q{}, prefix_seperator_invertion( $mysync, q{} ), 'prefix_seperator_invertion: $mysync empty string => empty string' ) ;
  4470. is( 'lalala', prefix_seperator_invertion( $mysync, 'lalala' ), 'prefix_seperator_invertion: $mysync lalala => lalala' ) ;
  4471. is( 'lal/ala', prefix_seperator_invertion( $mysync, 'lal/ala' ), 'prefix_seperator_invertion: $mysync lal/ala => lal/ala' ) ;
  4472. is( 'lal.ala', prefix_seperator_invertion( $mysync, 'lal.ala' ), 'prefix_seperator_invertion: $mysync lal.ala => lal.ala' ) ;
  4473. is( '////', prefix_seperator_invertion( $mysync, '////' ), 'prefix_seperator_invertion: $mysync //// => ////' ) ;
  4474. is( '.....', prefix_seperator_invertion( $mysync, '.....' ), 'prefix_seperator_invertion: $mysync ..... => .....' ) ;
  4475. $mysync = {
  4476. h1_prefix => 'PPP',
  4477. h2_prefix => 'QQQ',
  4478. h1_sep => 's',
  4479. h2_sep => 't',
  4480. } ;
  4481. is( q{QQQ}, prefix_seperator_invertion( $mysync, q{} ), 'prefix_seperator_invertion: PPPQQQst empty string => QQQ' ) ;
  4482. is( 'QQQlalala', prefix_seperator_invertion( $mysync, 'lalala' ), 'prefix_seperator_invertion: PPPQQQst lalala => QQQlalala' ) ;
  4483. is( 'QQQlal/ala', prefix_seperator_invertion( $mysync, 'lal/ala' ), 'prefix_seperator_invertion: PPPQQQst lal/ala => QQQlal/ala' ) ;
  4484. is( 'QQQlal.ala', prefix_seperator_invertion( $mysync, 'lal.ala' ), 'prefix_seperator_invertion: PPPQQQst lal.ala => QQQlal.ala' ) ;
  4485. is( 'QQQ////', prefix_seperator_invertion( $mysync, '////' ), 'prefix_seperator_invertion: PPPQQQst //// => QQQ////' ) ;
  4486. is( 'QQQ.....', prefix_seperator_invertion( $mysync, '.....' ), 'prefix_seperator_invertion: PPPQQQst ..... => QQQ.....' ) ;
  4487. is( 'QQQPlalala', prefix_seperator_invertion( $mysync, 'PPPPlalala' ), 'prefix_seperator_invertion: PPPQQQst PPPPlalala => QQQPlalala' ) ;
  4488. is( 'QQQ', prefix_seperator_invertion( $mysync, 'PPP' ), 'prefix_seperator_invertion: PPPQQQst PPP => QQQ' ) ;
  4489. is( 'QQQttt', prefix_seperator_invertion( $mysync, 'sss' ), 'prefix_seperator_invertion: PPPQQQst sss => QQQttt' ) ;
  4490. is( 'QQQt', prefix_seperator_invertion( $mysync, 's' ), 'prefix_seperator_invertion: PPPQQQst s => QQQt' ) ;
  4491. is( 'QQQtAAAtBBB', prefix_seperator_invertion( $mysync, 'PPPsAAAsBBB' ), 'prefix_seperator_invertion: PPPQQQst PPPsAAAsBBB => QQQtAAAtBBB' ) ;
  4492. return ;
  4493. }
  4494. # Global variables to remove:
  4495. # $h1_sep
  4496. # $h2_sep
  4497. # $debug
  4498. sub prefix_seperator_invertion {
  4499. my $mysync = shift ;
  4500. my $h1_fold = shift ;
  4501. my $h2_fold ;
  4502. if ( not defined $h1_fold ) { return ; }
  4503. my $my_h1_prefix = $mysync->{ h1_prefix } || q{} ;
  4504. my $my_h2_prefix = $mysync->{ h2_prefix } || q{} ;
  4505. my $my_h1_sep = $h1_sep || $mysync->{ h1_sep } || '/' ;
  4506. my $my_h2_sep = $h2_sep || $mysync->{ h2_sep } || '/' ;
  4507. # first we remove the prefix
  4508. $h1_fold =~ s/^\Q$my_h1_prefix\E//x ;
  4509. ( $debug or $mysync->{debugfolders} ) and myprint( "removed host1 prefix: [$h1_fold]\n" ) ;
  4510. $h2_fold = separator_invert( $h1_fold, $my_h1_sep, $my_h2_sep ) ;
  4511. ( $debug or $mysync->{debugfolders} ) and myprint( "inverted separators: [$h2_fold]\n" ) ;
  4512. # Adding the prefix supplied by namespace or the --prefix2 option
  4513. $h2_fold = $my_h2_prefix . $h2_fold
  4514. unless( ( $my_h2_prefix eq 'INBOX' . $my_h2_sep ) and ( $h2_fold =~ m/^INBOX$/xi ) ) ;
  4515. ( $debug or $mysync->{debugfolders} ) and myprint( "added host2 prefix: [$h2_fold]\n" ) ;
  4516. return( $h2_fold ) ;
  4517. }
  4518. sub tests_separator_invert {
  4519. note( 'Entering tests_separator_invert()' ) ;
  4520. $fixslash2 = 0 ;
  4521. ok( not( defined separator_invert( ) ), 'separator_invert: no args' ) ;
  4522. ok( not( defined separator_invert( q{} ) ), 'separator_invert: not enough args' ) ;
  4523. ok( not( defined separator_invert( q{}, q{} ) ), 'separator_invert: not enough args' ) ;
  4524. ok( q{} eq separator_invert( q{}, q{}, q{} ), 'separator_invert: 3 empty strings' ) ;
  4525. ok( 'lalala' eq separator_invert( 'lalala', q{}, q{} ), 'separator_invert: empty separator' ) ;
  4526. ok( 'lalala' eq separator_invert( 'lalala', '/', '/' ), 'separator_invert: same separator /' ) ;
  4527. ok( 'lal/ala' eq separator_invert( 'lal/ala', '/', '/' ), 'separator_invert: same separator / 2' ) ;
  4528. ok( 'lal.ala' eq separator_invert( 'lal/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  4529. ok( 'lal/ala' eq separator_invert( 'lal.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  4530. ok( 'la.l/ala' eq separator_invert( 'la/l.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  4531. ok( 'l/al.ala' eq separator_invert( 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  4532. $fixslash2 = 1 ;
  4533. ok( 'l_al.ala' eq separator_invert( 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  4534. note( 'Leaving tests_separator_invert()' ) ;
  4535. return ;
  4536. }
  4537. # Global variables to remove:
  4538. # $fixslash2
  4539. sub separator_invert {
  4540. my( $h1_fold, $h1_separator, $h2_separator ) = @_ ;
  4541. return( undef ) if ( not defined $h1_fold or not defined $h1_separator or not defined $h2_separator ) ;
  4542. # The separator we hope we'll never encounter: 00000000 == 0x00
  4543. my $o_sep = "\000" ;
  4544. my $h2_fold = $h1_fold ;
  4545. $h2_fold =~ s,\Q$h2_separator,$o_sep,xg ;
  4546. $h2_fold =~ s,\Q$h1_separator,$h2_separator,xg ;
  4547. $h2_fold =~ s,\Q$o_sep,$h1_separator,xg ;
  4548. $h2_fold =~ s,/,_,xg if( $fixslash2 and '/' ne $h2_separator and '/' eq $h1_separator ) ;
  4549. return( $h2_fold ) ;
  4550. }
  4551. sub regextrans2 {
  4552. my( $h2_fold ) = @_ ;
  4553. # Transforming the folder name by the --regextrans2 option(s)
  4554. foreach my $regextrans2 ( @regextrans2 ) {
  4555. my $h2_fold_before = $h2_fold ;
  4556. my $ret = eval "\$h2_fold =~ $regextrans2 ; 1 " ;
  4557. ( $debug or $sync->{debugfolders} ) and myprint( "[$h2_fold_before] -> [$h2_fold] using regextrans2 [$regextrans2]\n" ) ;
  4558. if ( not ( defined $ret ) or $EVAL_ERROR ) {
  4559. die_clean( "error: eval regextrans2 '$regextrans2': $EVAL_ERROR\n" ) ;
  4560. }
  4561. }
  4562. return( $h2_fold ) ;
  4563. }
  4564. sub tests_decompose_regex {
  4565. note( 'Entering tests_decompose_regex()' ) ;
  4566. ok( 1, 'decompose_regex 1' ) ;
  4567. ok( 0 == compare_lists( [ q{}, q{} ], [ decompose_regex( q{} ) ] ), 'decompose_regex empty string' ) ;
  4568. ok( 0 == compare_lists( [ '.*', 'lala' ], [ decompose_regex( 's/.*/lala/' ) ] ), 'decompose_regex s/.*/lala/' ) ;
  4569. note( 'Leaving tests_decompose_regex()' ) ;
  4570. return ;
  4571. }
  4572. sub decompose_regex {
  4573. my $regex = shift ;
  4574. my( $left_part, $right_part ) ;
  4575. ( $left_part, $right_part ) = $regex =~ m{^s/((?:[^/]|\\/)+)/((?:[^/]|\\/)+)/}x;
  4576. return( q{}, q{} ) if not $left_part ;
  4577. return( $left_part, $right_part ) ;
  4578. }
  4579. sub foldersizes {
  4580. my ( $side, $imap, $search_cmd, $abletosearch, @folders ) = @_ ;
  4581. my $total_size = 0 ;
  4582. my $total_nb = 0 ;
  4583. my $biggest_in_all = 0 ;
  4584. my $nb_folders = scalar @folders ;
  4585. my $ct_folders = 0 ; # folder counter.
  4586. myprint( "++++ Calculating sizes of $nb_folders folders on $side\n" ) ;
  4587. foreach my $folder ( @folders ) {
  4588. my $stot = 0 ;
  4589. my $nb_msgs = 0 ;
  4590. $ct_folders++ ;
  4591. myprintf( "$side folder %7s %-35s", "$ct_folders/$nb_folders", jux_utf8( $folder ) ) ;
  4592. if ( 'Host2' eq $side and not exists $h2_folders_all_UPPER{ uc $folder } ) {
  4593. myprint( " does not exist yet\n") ;
  4594. next ;
  4595. }
  4596. if ( 'Host1' eq $side and not exists $h1_folders_all{ $folder } ) {
  4597. myprint( " does not exist\n" ) ;
  4598. next ;
  4599. }
  4600. last if $imap->IsUnconnected( ) ;
  4601. # FTGate is RFC buggy with EXAMINE it does not act as SELECT
  4602. #unless ( $imap->examine( $folder ) ) {
  4603. unless ( $imap->select( $folder ) ) {
  4604. my $error = join q{},
  4605. "$side Folder $folder: Could not select: ",
  4606. $imap->LastError, "\n" ;
  4607. errors_incr( $sync, $error ) ;
  4608. next ;
  4609. }
  4610. last if $imap->IsUnconnected( ) ;
  4611. my $hash_ref = { } ;
  4612. my @msgs = select_msgs( $imap, undef, $search_cmd, $abletosearch, $folder ) ;
  4613. $nb_msgs = scalar @msgs ;
  4614. my $biggest_in_folder = 0 ;
  4615. @{ $hash_ref }{ @msgs } = ( undef ) if @msgs ;
  4616. last if $imap->IsUnconnected( ) ;
  4617. if ( $nb_msgs > 0 and @msgs ) {
  4618. if ( $abletosearch ) {
  4619. if ( ! $imap->fetch_hash( \@msgs, 'RFC822.SIZE', $hash_ref) ) {
  4620. my $error = "$side failure with fetch_hash: $EVAL_ERROR" ;
  4621. errors_incr( $sync, $error ) ;
  4622. return ;
  4623. }
  4624. }else{
  4625. my $uidnext = $imap->uidnext( $folder ) || $uidnext_default ;
  4626. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  4627. if ( ! $imap->fetch_hash( $fetch_hash_uids, 'RFC822.SIZE', $hash_ref ) ) {
  4628. my $error = "$side failure with fetch_hash: $EVAL_ERROR" ;
  4629. errors_incr( $sync, $error ) ;
  4630. return ;
  4631. }
  4632. }
  4633. for ( keys %{ $hash_ref } ) {
  4634. my $size = $hash_ref->{ $_ }->{ 'RFC822.SIZE' } ;
  4635. $stot += $size ;
  4636. $biggest_in_folder = max( $biggest_in_folder, $size ) ;
  4637. }
  4638. }
  4639. myprintf( ' Size: %9s', $stot ) ;
  4640. myprintf( ' Messages: %5s', $nb_msgs ) ;
  4641. myprintf( " Biggest: %9s\n", $biggest_in_folder ) ;
  4642. $total_size += $stot ;
  4643. $total_nb += $nb_msgs ;
  4644. $biggest_in_all = max( $biggest_in_all, $biggest_in_folder ) ;
  4645. }
  4646. myprintf( "%s Nb folders: %11s folders\n", $side, $nb_folders ) ;
  4647. myprintf( "%s Nb messages: %11s messages\n", $side, $total_nb ) ;
  4648. myprintf( "%s Total size: %11s bytes (%s)\n", $side, $total_size, bytes_display_string( $total_size ) ) ;
  4649. myprintf( "%s Biggest message: %11s bytes (%s)\n", $side, $biggest_in_all, bytes_display_string( $biggest_in_all ) ) ;
  4650. myprintf( "%s Time spent: %11.1f seconds\n", $side, timenext( ) ) ;
  4651. return( $total_nb, $total_size ) ;
  4652. }
  4653. sub timenext {
  4654. my ( $timenow, $timediff ) ;
  4655. # $timebefore is global, beurk !
  4656. $timenow = time ;
  4657. $timediff = $timenow - $timebefore ;
  4658. $timebefore = $timenow ;
  4659. return( $timediff ) ;
  4660. }
  4661. sub timesince {
  4662. my $timeinit = shift || 0 ;
  4663. my ( $timenow, $timediff ) ;
  4664. $timenow = time ;
  4665. $timediff = $timenow - $timeinit ;
  4666. # Often used in a division so no 0
  4667. return( max( 1, $timediff) ) ;
  4668. }
  4669. sub tests_flags_regex {
  4670. note( 'Entering tests_flags_regex()' ) ;
  4671. ok( q{} eq flags_regex(q{} ), 'flags_regex, null string q{}' ) ;
  4672. ok( q{\Seen NonJunk $Spam} eq flags_regex( q{\Seen NonJunk $Spam} ), q{flags_regex, nothing to do} ) ;
  4673. @regexflag = ('I am BAD' ) ;
  4674. ok( not ( defined flags_regex( q{} ) ), 'flags_regex, bad regex' ) ;
  4675. @regexflag = ( 's/NonJunk//g' ) ;
  4676. ok( q{\Seen $Spam} eq flags_regex( q{\Seen NonJunk $Spam} ), q{flags_regex, remove NonJunk: 's/NonJunk//g'} ) ;
  4677. @regexflag = ( q's/\$Spam//g' ) ;
  4678. ok( q{\Seen NonJunk } eq flags_regex( q{\Seen NonJunk $Spam} ), q{flags_regex, remove $Spam: 's/\$Spam//g'} ) ;
  4679. @regexflag = ( 's/\\\\Seen//g' ) ;
  4680. ok( q{ NonJunk $Spam} eq flags_regex( q{\Seen NonJunk $Spam} ), q{flags_regex, remove \Seen: 's/\\\\\\\\Seen//g'} ) ;
  4681. @regexflag = ( 's/(\s|^)[^\\\\]\w+//g' ) ;
  4682. ok( q{\Seen \Middle \End} eq flags_regex( q{\Seen NonJunk \Middle $Spam \End} ), q{flags_regex: only \word among \Seen NonJunk \Middle $Spam \End} ) ;
  4683. ok( q{ \Seen \Middle \End1} eq flags_regex( q{Begin \Seen NonJunk \Middle $Spam \End1 End} ),
  4684. q{flags_regex: only \word among Begin \Seen NonJunk \Middle $Spam \End1 End} ) ;
  4685. @regexflag = ( q{s/.*?(Keep1|Keep2|Keep3)/$1 /g} ) ;
  4686. ok( 'Keep1 Keep2 ReB' eq flags_regex('ReA Keep1 REM Keep2 ReB'), 'Keep only regex' ) ;
  4687. ok( 'Keep1 Keep2 ' eq flags_regex( 'REM REM Keep1 Keep2'), 'Keep only regex' ) ;
  4688. ok( 'Keep1 Keep2 ' eq flags_regex( 'Keep1 REM REM Keep2'), 'Keep only regex' ) ;
  4689. ok( 'Keep1 Keep2 ' eq flags_regex( 'REM Keep1 REM REM Keep2'), 'Keep only regex' ) ;
  4690. ok( 'Keep1 Keep2 ' eq flags_regex( 'Keep1 Keep2'), 'Keep only regex' ) ;
  4691. ok( 'Keep1 ' eq flags_regex( 'REM Keep1'), 'Keep only regex' ) ;
  4692. @regexflag = ( q{s/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g} ) ;
  4693. ok( 'Keep1 Keep2 ' eq flags_regex( 'Keep1 Keep2 ReB'), 'Keep only regex' ) ;
  4694. ok( 'Keep1 Keep2 ' eq flags_regex( 'Keep1 Keep2 REM REM REM'), 'Keep only regex' ) ;
  4695. ok( 'Keep2 ' eq flags_regex('Keep2 REM REM REM'), 'Keep only regex' ) ;
  4696. @regexflag = ( q{s/.*?(Keep1|Keep2|Keep3)/$1 /g},
  4697. 's/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g' ) ;
  4698. ok( 'Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2 REM'), 'Keep only regex' ) ;
  4699. ok( 'Keep1 Keep2 ' eq flags_regex('Keep1 REM Keep2 REM'), 'Keep only regex' ) ;
  4700. ok( 'Keep1 Keep2 ' eq flags_regex('REM Keep1 Keep2 REM'), 'Keep only regex' ) ;
  4701. ok( 'Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2'), 'Keep only regex' ) ;
  4702. ok( 'Keep1 Keep2 Keep3 ' eq flags_regex('REM Keep1 REM Keep2 REM REM Keep3 REM'), 'Keep only regex' ) ;
  4703. ok( 'Keep1 ' eq flags_regex('REM REM Keep1 REM REM REM '), 'Keep only regex' ) ;
  4704. ok( 'Keep1 Keep3 ' eq flags_regex('RE1 Keep1 RE2 Keep3 RE3 RE4 RE5 '), 'Keep only regex' ) ;
  4705. @regexflag = ( 's/(.*)/$1 jrdH8u/' ) ;
  4706. ok('REM REM REM REM REM jrdH8u' eq flags_regex('REM REM REM REM REM'), q{Keep only regex 's/(.*)/\$1 jrdH8u/'} ) ;
  4707. @regexflag = ('s/jrdH8u *//');
  4708. ok('REM REM REM REM REM ' eq flags_regex('REM REM REM REM REM jrdH8u'), q{Keep only regex s/jrdH8u *//} ) ;
  4709. @regexflag = (
  4710. 's/(.*)/$1 jrdH8u/',
  4711. 's/.*?(Keep1|Keep2|Keep3|jrdH8u)/$1 /g',
  4712. 's/(Keep1|Keep2|Keep3|jrdH8u) (?!(Keep1|Keep2|Keep3|jrdH8u)).*/$1 /g',
  4713. 's/jrdH8u *//'
  4714. );
  4715. ok('Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2 REM'), q{Keep only regex 'REM Keep1 REM Keep2 REM'} ) ;
  4716. ok('Keep1 Keep2 ' eq flags_regex('Keep1 REM Keep2 REM'), 'Keep only regex');
  4717. ok('Keep1 Keep2 ' eq flags_regex('REM Keep1 Keep2 REM'), 'Keep only regex');
  4718. ok('Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2'), 'Keep only regex');
  4719. ok('Keep1 Keep2 Keep3 ' eq flags_regex('REM Keep1 REM Keep2 REM REM Keep3 REM'), 'Keep only regex');
  4720. ok('Keep1 ' eq flags_regex('REM REM Keep1 REM REM REM '), 'Keep only regex');
  4721. ok('Keep1 Keep3 ' eq flags_regex('RE1 Keep1 RE2 Keep3 RE3 RE4 RE5 '), 'Keep only regex');
  4722. ok(q{} eq flags_regex('REM REM REM REM REM'), 'Keep only regex');
  4723. @regexflag = (
  4724. 's/(.*)/$1 jrdH8u/',
  4725. 's/.*?(\\\\Seen|\\\\Answered|\\\\Flagged|\\\\Deleted|\\\\Draft|jrdH8u)/$1 /g',
  4726. 's/(\\\\Seen|\\\\Answered|\\\\Flagged|\\\\Deleted|\\\\Draft|jrdH8u) (?!(\\\\Seen|\\\\Answered|\\\\Flagged|\\\\Deleted|\\\\Draft|jrdH8u)).*/$1 /g',
  4727. 's/jrdH8u *//'
  4728. );
  4729. ok('\\Deleted \\Answered '
  4730. eq flags_regex('Blabla $Junk \\Deleted machin \\Answered truc'), 'Keep only regex: Exchange case' ) ;
  4731. ok( q{} eq flags_regex( q{} ), 'Keep only regex: Exchange case, null string' ) ;
  4732. ok( q{}
  4733. eq flags_regex('Blabla $Junk machin truc'), 'Keep only regex: Exchange case, no accepted flags' ) ;
  4734. ok( '\\Deleted \\Answered \\Draft \\Flagged '
  4735. eq flags_regex('\\Deleted \\Answered \\Draft \\Flagged '), 'Keep only regex: Exchange case' ) ;
  4736. @regexflag = (
  4737. 's/.*?(?:(\\\\(?:Answered|Flagged|Deleted|Seen|Draft)\s?)|$)/defined($1)?$1:q()/eg'
  4738. );
  4739. ok( '\\Deleted \\Answered '
  4740. eq flags_regex('Blabla \$Junk \\Deleted machin \\Answered truc'),
  4741. 'Keep only regex: Exchange case (Phil)' ) ;
  4742. ok( q{} eq flags_regex( q{} ), 'Keep only regex: Exchange case, null string (Phil)' ) ;
  4743. ok( q{}
  4744. eq flags_regex('Blabla $Junk machin truc'),
  4745. 'Keep only regex: Exchange case, no accepted flags (Phil)' ) ;
  4746. ok('\\Deleted \\Answered \\Draft \\Flagged '
  4747. eq flags_regex('\\Deleted \\Answered \\Draft \\Flagged '),
  4748. 'Keep only regex: Exchange case (Phil)' ) ;
  4749. note( 'Leaving tests_flags_regex()' ) ;
  4750. return ;
  4751. }
  4752. sub flags_regex {
  4753. my ( $h1_flags ) = @_ ;
  4754. foreach my $regexflag ( @regexflag ) {
  4755. my $h1_flags_orig = $h1_flags ;
  4756. $debugflags and myprint( "eval \$h1_flags =~ $regexflag\n" ) ;
  4757. my $ret = eval "\$h1_flags =~ $regexflag ; 1 " ;
  4758. $debugflags and myprint( "regexflag $regexflag [$h1_flags_orig] -> [$h1_flags]\n" ) ;
  4759. if( not ( defined $ret ) or $EVAL_ERROR ) {
  4760. myprint( "Error: eval regexflag '$regexflag': $EVAL_ERROR\n" ) ;
  4761. return( undef ) ;
  4762. }
  4763. }
  4764. return( $h1_flags ) ;
  4765. }
  4766. sub acls_sync {
  4767. my($h1_fold, $h2_fold) = @_ ;
  4768. if ( $syncacls ) {
  4769. my $h1_hash = $imap1->getacl($h1_fold)
  4770. or myprint( "Could not getacl for $h1_fold: $EVAL_ERROR\n" ) ;
  4771. my $h2_hash = $imap2->getacl($h2_fold)
  4772. or myprint( "Could not getacl for $h2_fold: $EVAL_ERROR\n" ) ;
  4773. my %users = map { ($_, 1) } ( keys %{ $h1_hash} , keys %{ $h2_hash } ) ;
  4774. foreach my $user (sort keys %users ) {
  4775. my $acl = $h1_hash->{$user} || 'none' ;
  4776. myprint( "acl $user: [$acl]\n" ) ;
  4777. next if ($h1_hash->{$user} && $h2_hash->{$user} &&
  4778. $h1_hash->{$user} eq $h2_hash->{$user});
  4779. unless ($sync->{dry}) {
  4780. myprint( "setting acl $h2_fold $user $acl\n" ) ;
  4781. $imap2->setacl($h2_fold, $user, $acl)
  4782. or myprint( "Could not set acl: $EVAL_ERROR\n" ) ;
  4783. }
  4784. }
  4785. }
  4786. return ;
  4787. }
  4788. sub tests_permanentflags {
  4789. note( 'Entering tests_permanentflags()' ) ;
  4790. my $string;
  4791. ok(q{} eq permanentflags(' * OK [PERMANENTFLAGS (\* \Draft \Answered)] Limited'),
  4792. 'permanentflags \*');
  4793. ok('\Draft \Answered' eq permanentflags(' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited'),
  4794. 'permanentflags \Draft \Answered');
  4795. ok('\Draft \Answered'
  4796. eq permanentflags('Blabla',
  4797. ' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited',
  4798. 'Blabla'),
  4799. 'permanentflags \Draft \Answered'
  4800. );
  4801. ok(q{} eq permanentflags('Blabla'), 'permanentflags nothing');
  4802. note( 'Leaving tests_permanentflags()' ) ;
  4803. return ;
  4804. }
  4805. sub permanentflags {
  4806. my @lines = @_ ;
  4807. foreach my $line (@lines) {
  4808. if ( $line =~ m{\[PERMANENTFLAGS\s\(([^)]+?)\)\]}x ) {
  4809. ( $debugflags or $debug ) and myprint( "permanentflags: $line" ) ;
  4810. my $permanentflags = $1 ;
  4811. if ( $permanentflags =~ m{\\\*}x ) {
  4812. $permanentflags = q{} ;
  4813. }
  4814. return($permanentflags) ;
  4815. } ;
  4816. }
  4817. return( q{} ) ;
  4818. }
  4819. sub tests_flags_filter {
  4820. note( 'Entering tests_flags_filter()' ) ;
  4821. ok( '\Seen' eq flags_filter('\Seen', '\Draft \Seen \Answered'), 'flags_filter ' );
  4822. ok( q{} eq flags_filter('\Seen', '\Draft \Answered'), 'flags_filter ' );
  4823. ok( '\Seen' eq flags_filter('\Seen', '\Seen'), 'flags_filter ' );
  4824. ok( '\Seen' eq flags_filter('\Seen', ' \Seen '), 'flags_filter ' );
  4825. ok( '\Seen \Draft'
  4826. eq flags_filter('\Seen \Draft', '\Draft \Seen \Answered'), 'flags_filter ' );
  4827. ok( '\Seen \Draft'
  4828. eq flags_filter('\Seen \Draft', ' \Draft \Seen \Answered '), 'flags_filter ' );
  4829. note( 'Leaving tests_flags_filter()' ) ;
  4830. return ;
  4831. }
  4832. sub flags_filter {
  4833. my( $flags, $allowed_flags ) = @_ ;
  4834. my @flags = split /\s+/x, $flags ;
  4835. my %allowed_flags = map { $_ => 1 } split q{ }, $allowed_flags ;
  4836. my @flags_out = map { exists $allowed_flags{$_} ? $_ : () } @flags ;
  4837. my $flags_out = join q{ }, @flags_out ;
  4838. return( $flags_out ) ;
  4839. }
  4840. sub flagscase {
  4841. my $flags = shift ;
  4842. my @flags = split /\s+/x, $flags ;
  4843. my %rfc_flags = map { $_ => 1 } split q{ }, '\Answered \Flagged \Deleted \Seen \Draft' ;
  4844. my @flags_out = map { exists $rfc_flags{ ucsecond( lc $_ ) } ? ucsecond( lc $_ ) : $_ } @flags ;
  4845. my $flags_out = join q{ }, @flags_out ;
  4846. return( $flags_out ) ;
  4847. }
  4848. sub tests_flagscase {
  4849. note( 'Entering tests_flagscase()' ) ;
  4850. ok( '\Seen' eq flagscase( '\Seen' ), 'flagscase: \Seen -> \Seen' ) ;
  4851. ok( '\Seen' eq flagscase( '\SEEN' ), 'flagscase: \SEEN -> \Seen' ) ;
  4852. ok( '\Seen \Draft' eq flagscase( '\SEEN \DRAFT' ), 'flagscase: \SEEN \DRAFT -> \Seen \Draft' ) ;
  4853. ok( '\Draft \Seen' eq flagscase( '\DRAFT \SEEN' ), 'flagscase: \DRAFT \SEEN -> \Draft \Seen' ) ;
  4854. ok( '\Draft LALA \Seen' eq flagscase( '\DRAFT LALA \SEEN' ), 'flagscase: \DRAFT LALA \SEEN -> \Draft LALA \Seen' ) ;
  4855. ok( '\Draft lala \Seen' eq flagscase( '\DRAFT lala \SEEN' ), 'flagscase: \DRAFT lala \SEEN -> \Draft lala \Seen' ) ;
  4856. note( 'Leaving tests_flagscase()' ) ;
  4857. return ;
  4858. }
  4859. sub ucsecond {
  4860. my $string = shift ;
  4861. my $output ;
  4862. return( $string ) if ( 1 >= length $string ) ;
  4863. $output = ( substr( $string, 0, 1) ) . ( uc substr $string, 1, 1 ) . ( substr $string, 2 ) ;
  4864. #myprint( "UUU $string -> $output\n" ) ;
  4865. return( $output ) ;
  4866. }
  4867. sub tests_ucsecond {
  4868. note( 'Entering tests_ucsecond()' ) ;
  4869. ok( 'aBcde' eq ucsecond( 'abcde' ), 'ucsecond: abcde -> aBcde' ) ;
  4870. ok( 'ABCDE' eq ucsecond( 'ABCDE' ), 'ucsecond: ABCDE -> ABCDE' ) ;
  4871. ok( 'ABCDE' eq ucsecond( 'AbCDE' ), 'ucsecond: AbCDE -> ABCDE' ) ;
  4872. ok( 'ABCde' eq ucsecond( 'AbCde' ), 'ucsecond: AbCde -> ABCde' ) ;
  4873. ok( 'A' eq ucsecond( 'A' ), 'ucsecond: A -> A' ) ;
  4874. ok( 'AB' eq ucsecond( 'Ab' ), 'ucsecond: Ab -> AB' ) ;
  4875. ok( '\B' eq ucsecond( '\b' ), 'ucsecond: \b -> \B' ) ;
  4876. ok( '\Bcde' eq ucsecond( '\bcde' ), 'ucsecond: \bcde -> \Bcde' ) ;
  4877. note( 'Leaving tests_ucsecond()' ) ;
  4878. return ;
  4879. }
  4880. sub select_msgs {
  4881. my ( $imap, $msgs_all_hash_ref, $search_cmd, $abletosearch, $folder ) = @_ ;
  4882. my ( @msgs ) ;
  4883. if ( $abletosearch ) {
  4884. @msgs = select_msgs_by_search( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  4885. }else{
  4886. @msgs = select_msgs_by_fetch( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  4887. }
  4888. return( @msgs ) ;
  4889. }
  4890. sub select_msgs_by_search {
  4891. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  4892. my ( @msgs, @msgs_all ) ;
  4893. # Need to have the whole list in msgs_all_hash_ref
  4894. # without calling messages() several times.
  4895. # Need all messages list to avoid deleting useful cache part
  4896. # in case of --search or --minage or --maxage
  4897. if ( ( defined $msgs_all_hash_ref and $usecache )
  4898. or ( not defined $maxage and not defined $minage and not defined $search_cmd )
  4899. ) {
  4900. $debugdev and myprint( "Calling messages()\n" ) ;
  4901. @msgs_all = $imap->messages( ) ;
  4902. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  4903. if ( defined $msgs_all_hash_ref ) {
  4904. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  4905. }
  4906. # return all messages
  4907. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  4908. return( @msgs_all ) ;
  4909. }
  4910. }
  4911. if ( defined $search_cmd ) {
  4912. @msgs = $imap->search( $search_cmd ) ;
  4913. return( @msgs ) ;
  4914. }
  4915. # we are here only if $maxage or $minage is defined
  4916. @msgs = select_msgs_by_age( $imap ) ;
  4917. return( @msgs );
  4918. }
  4919. sub select_msgs_by_fetch {
  4920. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  4921. my ( @msgs, @msgs_all, %fetch ) ;
  4922. # Need to have the whole list in msgs_all_hash_ref
  4923. # without calling messages() several times.
  4924. # Need all messages list to avoid deleting useful cache part
  4925. # in case of --search or --minage or --maxage
  4926. $debugdev and myprint( "Calling fetch_hash()\n" ) ;
  4927. my $uidnext = $imap->uidnext( $folder ) || $uidnext_default ;
  4928. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  4929. %fetch = %{$imap->fetch_hash( $fetch_hash_uids, 'INTERNALDATE' ) } ;
  4930. @msgs_all = sort { $a <=> $b } keys %fetch ;
  4931. $debugdev and myprint( "Done fetch_hash()\n" ) ;
  4932. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  4933. if ( defined $msgs_all_hash_ref ) {
  4934. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  4935. }
  4936. # return all messages
  4937. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  4938. return( @msgs_all ) ;
  4939. }
  4940. if ( defined $search_cmd ) {
  4941. myprint( "Warning: strange to see --search with --noabletosearch, an error can happen\n" ) ;
  4942. @msgs = $imap->search( $search_cmd ) ;
  4943. return( @msgs ) ;
  4944. }
  4945. # we are here only if $maxage or $minage is defined
  4946. my( @max, @min, $maxage_epoch, $minage_epoch ) ;
  4947. if ( defined $maxage ) { $maxage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ; }
  4948. if ( defined $minage ) { $minage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ; }
  4949. foreach my $msg ( @msgs_all ) {
  4950. my $idate = $fetch{ $msg }->{'INTERNALDATE'} ;
  4951. #myprint( "$idate\n" ) ;
  4952. if ( defined $maxage and ( epoch( $idate ) >= $maxage_epoch ) ) {
  4953. push @max, $msg ;
  4954. }
  4955. if ( defined $minage and ( epoch( $idate ) <= $minage_epoch ) ) {
  4956. push @min, $msg ;
  4957. }
  4958. }
  4959. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  4960. return( @msgs ) ;
  4961. }
  4962. sub select_msgs_by_age {
  4963. my( $imap ) = @_ ;
  4964. my( @max, @min, @msgs, @inter, @union ) ;
  4965. if ( defined $maxage ) {
  4966. @max = $imap->sentsince( $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ) ;
  4967. }
  4968. if ( defined $minage ) {
  4969. @min = $imap->sentbefore( $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ) ;
  4970. }
  4971. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  4972. return( @msgs ) ;
  4973. }
  4974. sub msgs_from_maxmin {
  4975. my( $max_ref, $min_ref ) = @_ ;
  4976. my( @max, @min, @msgs, @inter, @union ) ;
  4977. @max = @{ $max_ref } ;
  4978. @min = @{ $min_ref } ;
  4979. SWITCH: {
  4980. unless( defined $minage ) { @msgs = @max ; last SWITCH } ;
  4981. unless( defined $maxage ) { @msgs = @min ; last SWITCH } ;
  4982. my ( %union, %inter ) ;
  4983. foreach my $m ( @min, @max ) { $union{ $m }++ && $inter{ $m }++ }
  4984. @inter = sort { $a <=> $b } keys %inter ;
  4985. @union = sort { $a <=> $b } keys %union ;
  4986. # normal case
  4987. if ( $minage <= $maxage ) { @msgs = @inter ; last SWITCH } ;
  4988. # just exclude messages between
  4989. if ( $minage > $maxage ) { @msgs = @union ; last SWITCH } ;
  4990. }
  4991. return( @msgs ) ;
  4992. }
  4993. sub tests_msgs_from_maxmin {
  4994. note( 'Entering tests_msgs_from_maxmin()' ) ;
  4995. my @msgs ;
  4996. $maxage = $NUMBER_200 ;
  4997. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  4998. ok( 0 == compare_lists( [ '1', '2' ], \@msgs ), 'msgs_from_maxmin: maxage++' ) ;
  4999. $minage = $NUMBER_100 ;
  5000. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  5001. ok( 0 == compare_lists( [ '2' ], \@msgs ), 'msgs_from_maxmin: -maxage++minage-' ) ;
  5002. $minage = $NUMBER_300 ;
  5003. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  5004. ok( 0 == compare_lists( [ '1', '2', '3' ], \@msgs ), 'msgs_from_maxmin: ++maxage-minage++' ) ;
  5005. $maxage = undef ;
  5006. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  5007. ok( 0 == compare_lists( [ '2', '3' ], \@msgs ), 'msgs_from_maxmin: ++minage-' ) ;
  5008. note( 'Leaving tests_msgs_from_maxmin()' ) ;
  5009. return ;
  5010. }
  5011. sub tests_info_date_from_uid {
  5012. return ;
  5013. }
  5014. sub info_date_from_uid {
  5015. #my $first_uid = $msgs_all[ 0 ] ;
  5016. #my $first_idate = $fetch{ $first_uid }->{'INTERNALDATE'} ;
  5017. #my $first_epoch = epoch( $first_idate ) ;
  5018. #my $first_days = ( $timestart_int - $first_epoch ) / $NB_SECONDS_IN_A_DAY ;
  5019. #myprint( "\nOldest msg has UID $first_uid INTERNALDATE $first_idate EPOCH $first_epoch DAYS AGO $first_days\n" ) ;
  5020. }
  5021. sub lastuid {
  5022. my $imap = shift ;
  5023. my $folder = shift ;
  5024. my $lastuid_guess = shift ;
  5025. my $lastuid ;
  5026. # rfc3501: The only reliable way to identify recent messages is to
  5027. # look at message flags to see which have the \Recent flag
  5028. # set, or to do a SEARCH RECENT.
  5029. # SEARCH RECENT doesn't work this way on courrier.
  5030. my @recent_messages ;
  5031. # SEARCH RECENT for each transfer can be expensive with a big folder
  5032. # Call commented for now
  5033. #@recent_messages = $imap->recent( ) ;
  5034. #myprint( "Recent: @recent_messages\n" ) ;
  5035. my $max_recent ;
  5036. $max_recent = max( @recent_messages ) ;
  5037. if ( defined $max_recent and ($lastuid_guess <= $max_recent ) ) {
  5038. $lastuid = $max_recent ;
  5039. }else{
  5040. $lastuid = $lastuid_guess
  5041. }
  5042. return( $lastuid ) ;
  5043. }
  5044. sub size_filtered {
  5045. my( $h1_size, $h1_msg, $h1_fold, $h2_fold ) = @_ ;
  5046. $h1_size = 0 if ( ! $h1_size ) ; # null if empty or undef
  5047. if (defined $maxsize and $h1_size > $maxsize) {
  5048. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size exceeds maxsize limit $maxsize bytes)\n" ) ;
  5049. $total_bytes_skipped += $h1_size;
  5050. $nb_msg_skipped += 1;
  5051. return( 1 ) ;
  5052. }
  5053. if (defined $minsize and $h1_size <= $minsize) {
  5054. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size smaller than minsize $minsize bytes)\n" ) ;
  5055. $total_bytes_skipped += $h1_size;
  5056. $nb_msg_skipped += 1;
  5057. return( 1 ) ;
  5058. }
  5059. return( 0 ) ;
  5060. }
  5061. sub message_exists {
  5062. my( $imap, $msg ) = @_ ;
  5063. return( 1 ) if not $imap->Uid( ) ;
  5064. my $search_uid ;
  5065. ( $search_uid ) = $imap->search( "UID $msg" ) ;
  5066. #myprint( "$search ? $msg\n" ) ;
  5067. return( 1 ) if ( $search_uid eq $msg ) ;
  5068. return( 0 ) ;
  5069. }
  5070. sub copy_message {
  5071. # copy
  5072. my ( $mysync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) = @_ ;
  5073. ( $debug or $mysync->{dry}) and myprint( "msg $h1_fold/$h1_msg copying to $h2_fold $mysync->{dry_message}\n" ) ;
  5074. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} || 0 ;
  5075. my $h1_flags = $h1_fir_ref->{$h1_msg}->{'FLAGS'} || q{} ;
  5076. my $h1_idate = $h1_fir_ref->{$h1_msg}->{'INTERNALDATE'} || q{} ;
  5077. if ( size_filtered( $h1_size, $h1_msg, $h1_fold, $h2_fold ) ) {
  5078. $h1_nb_msg_processed +=1 ;
  5079. return ;
  5080. }
  5081. debugsleep( $mysync ) ;
  5082. myprint( "- msg $h1_fold/$h1_msg S[$h1_size] F[$h1_flags] I[$h1_idate] has RFC822.SIZE null!\n" ) if ( ! $h1_size ) ;
  5083. if ( $checkmessageexists and not message_exists( $imap1, $h1_msg ) ) {
  5084. $total_bytes_skipped += $h1_size;
  5085. $nb_msg_skipped += 1;
  5086. $h1_nb_msg_processed +=1 ;
  5087. return ;
  5088. }
  5089. myprint( debugmemory( $sync, " at C1" ) ) ;
  5090. my ( $string, $string_len ) ;
  5091. ( $string_len ) = message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, \$string ) ;
  5092. myprint( debugmemory( $sync, " at C2" ) ) ;
  5093. # not defined or empty $string
  5094. if ( ( not $string ) or ( not $string_len ) ) {
  5095. myprint( "- msg $h1_fold/$h1_msg skipped.\n" ) ;
  5096. $total_bytes_skipped += $h1_size;
  5097. $nb_msg_skipped += 1;
  5098. $h1_nb_msg_processed += 1 ;
  5099. return ;
  5100. }
  5101. # Lines too long (or not enough) => do no copy or fix
  5102. if ( ( defined $maxlinelength ) or ( defined $minmaxlinelength ) ) {
  5103. $string = linelengthstuff( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) ;
  5104. if ( not defined $string ) {
  5105. $h1_nb_msg_processed +=1 ;
  5106. $total_bytes_skipped += $h1_size ;
  5107. $nb_msg_skipped += 1 ;
  5108. return ;
  5109. }
  5110. }
  5111. my $h1_date = date_for_host2( $h1_msg, $h1_idate ) ;
  5112. ( $debug or $debugflags ) and
  5113. myprint( "Host1 flags init msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  5114. $h1_flags = flags_for_host2( $h1_flags, $permanentflags2 ) ;
  5115. ( $debug or $debugflags ) and
  5116. myprint( "Host1 flags filt msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  5117. $h1_date = undef if ($h1_date eq q{});
  5118. my $new_id = append_message_on_host2( \$string, $h1_fold, $h1_msg, $string_len, $h2_fold, $h1_size, $h1_flags, $h1_date, $cache_dir ) ;
  5119. if ( $new_id and $syncflagsaftercopy ) {
  5120. sync_flags_after_copy( $h1_fold, $h1_msg, $h1_flags, $h2_fold, $new_id, $permanentflags2 ) ;
  5121. }
  5122. myprint( debugmemory( $sync, " at C3" ) ) ;
  5123. return $new_id ;
  5124. }
  5125. sub linelengthstuff {
  5126. my( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) = @_ ;
  5127. my $maxlinelength_string = max_line_length( $string ) ;
  5128. $debugmaxlinelength and myprint( "msg $h1_fold/$h1_msg maxlinelength: $maxlinelength_string\n" ) ;
  5129. if ( ( defined $minmaxlinelength ) and ( $maxlinelength_string <= $minmaxlinelength ) ) {
  5130. my $subject = subject( $string ) ;
  5131. $debugdev and myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  5132. . "(Subject:[$subject]) (max line length under minmaxlinelength $minmaxlinelength bytes)\n" ) ;
  5133. return ;
  5134. }
  5135. if ( ( defined $maxlinelength ) and ( $maxlinelength_string > $maxlinelength ) ) {
  5136. my $subject = subject( $string ) ;
  5137. if ( $maxlinelengthcmd ) {
  5138. $string = pipemess( $string, $maxlinelengthcmd ) ;
  5139. # string undef means something was bad.
  5140. if ( not ( defined $string ) ) {
  5141. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] "
  5142. . "(Subject:[$subject]) could not be successfully transformed by --maxlinelengthcmd option\n" ) ;
  5143. return ;
  5144. }else{
  5145. return $string ;
  5146. }
  5147. }
  5148. myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  5149. . "(Subject:[$subject]) (line length exceeds maxlinelength $maxlinelength bytes)\n" ) ;
  5150. return ;
  5151. }
  5152. return $string ;
  5153. }
  5154. sub message_for_host2 {
  5155. # global variable list:
  5156. # @skipmess
  5157. # @regexmess
  5158. # @pipemess
  5159. # $debugcontent
  5160. # $debug
  5161. #
  5162. # API current
  5163. #
  5164. # at failure:
  5165. # * return nothing ( will then be undef or () )
  5166. # * $string_ref content is undef or empty
  5167. # at success:
  5168. # * return string length ($string_ref content length)
  5169. # * $string_ref content filled with message
  5170. # API future
  5171. #
  5172. #
  5173. my ( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) = @_ ;
  5174. # abort when missing a parameter
  5175. if ( (!$sync) or (!$h1_msg) or (!$h1_fold) or (!$h1_size) or (!defined $h1_flags) or (!defined $h1_idate) or (!$h1_fir_ref) or (!$string_ref) ) {
  5176. return ;
  5177. }
  5178. myprint( debugmemory( $sync, " at M1" ) ) ;
  5179. my $imap1 = $mysync->{imap1} ;
  5180. my $string_ok = $imap1->message_to_file( $string_ref, $h1_msg ) ;
  5181. myprint( debugmemory( $sync, " at M2" ) ) ;
  5182. my $string_len = length_ref( $string_ref ) ;
  5183. unless ( defined $string_ok and $string_len ) {
  5184. # undef or 0 length
  5185. my $error = join q{},
  5186. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] could not be fetched: ",
  5187. $imap1->LastError || q{}, "\n" ;
  5188. errors_incr( $mysync, $error ) ;
  5189. $total_bytes_error += $h1_size if ( $h1_size ) ;
  5190. $h1_nb_msg_processed +=1 ;
  5191. return ;
  5192. }
  5193. if ( @skipmess ) {
  5194. my $match = skipmess( ${ $string_ref } ) ;
  5195. # string undef means the eval regex was bad.
  5196. if ( not ( defined $match ) ) {
  5197. myprint(
  5198. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  5199. . " could not be skipped by --skipmess option, bad regex\n" ) ;
  5200. return ;
  5201. }
  5202. if ( $match ) {
  5203. my $subject = subject( ${ $string_ref } ) ;
  5204. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  5205. . " (Subject:[$subject]) skipped by --skipmess\n" ) ;
  5206. return ;
  5207. }
  5208. }
  5209. if ( @regexmess ) {
  5210. ${ $string_ref } = regexmess( ${ $string_ref } ) ;
  5211. # string undef means the eval regex was bad.
  5212. if ( not ( defined ${ $string_ref } ) ) {
  5213. myprint(
  5214. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  5215. . " could not be transformed by --regexmess\n" ) ;
  5216. return ;
  5217. }
  5218. }
  5219. if ( @pipemess ) {
  5220. ${ $string_ref } = pipemess( ${ $string_ref }, @pipemess ) ;
  5221. # string undef means something was bad.
  5222. if ( not ( defined ${ $string_ref } ) ) {
  5223. myprint(
  5224. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  5225. . " could not be successfully transformed by --pipemess option\n" ) ;
  5226. return ;
  5227. }
  5228. }
  5229. if ( $mysync->{addheader} and defined $h1_fir_ref->{$h1_msg}->{'NO_HEADER'} ) {
  5230. my $header = add_header( $h1_msg ) ;
  5231. $debug and myprint( "msg $h1_fold/$h1_msg adding custom header [$header]\n" ) ;
  5232. ${ $string_ref } = $header . "\r\n" . ${ $string_ref } ;
  5233. }
  5234. $string_len = length_ref( $string_ref ) ;
  5235. $debugcontent and myprint(
  5236. q{=} x $STD_CHAR_PER_LINE, "\n",
  5237. "F message content begin next line ($string_len characters long)\n",
  5238. ${ $string_ref },
  5239. "F message content ended on previous line\n", q{=} x $STD_CHAR_PER_LINE, "\n" ) ;
  5240. myprint( debugmemory( $sync, " at M3" ) ) ;
  5241. return $string_len ;
  5242. }
  5243. sub tests_message_for_host2 {
  5244. note( 'Entering tests_message_for_host2()' ) ;
  5245. my ( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) ;
  5246. is( undef, message_for_host2( ), q{message_for_host2: no args} ) ;
  5247. is( undef, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ), q{message_for_host2: undef args} ) ;
  5248. require Test::MockObject ;
  5249. my $imapT = Test::MockObject->new( ) ;
  5250. $mysync->{imap1} = $imapT ;
  5251. my $string ;
  5252. $h1_msg = 1 ;
  5253. $h1_fold = 'FoldFoo';
  5254. $h1_size = 9 ;
  5255. $h1_flags = '' ;
  5256. $h1_idate = '10-Jul-2015 09:00:00 +0200' ;
  5257. $h1_fir_ref = {} ;
  5258. $string_ref = \$string ;
  5259. $imapT->mock( 'message_to_file',
  5260. sub {
  5261. my ( $imap, $mystring_ref, $msg ) = @_ ;
  5262. ${$mystring_ref} = 'blablabla' ;
  5263. return length ${$mystring_ref} ;
  5264. }
  5265. ) ;
  5266. is( 9, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  5267. q{message_for_host2: msg 1 == "blablabla", length} ) ;
  5268. is( 'blablabla', $string, q{message_for_host2: msg 1 == "blablabla", value} ) ;
  5269. # so far so good
  5270. # now the --pipemess stuff
  5271. SKIP: {
  5272. Readonly my $NB_WIN_tests_message_for_host2 => 0 ;
  5273. skip( 'Not on MSWin32', $NB_WIN_tests_message_for_host2 ) if ('MSWin32' ne $OSNAME) ;
  5274. # Windows
  5275. # "type" command does not accept redirection of STDIN with <
  5276. # "sort" does
  5277. } ;
  5278. SKIP: {
  5279. Readonly my $NB_UNX_tests_message_for_host2 => 6 ;
  5280. skip( 'Not on Unix', $NB_UNX_tests_message_for_host2 ) if ('MSWin32' eq $OSNAME) ;
  5281. # Unix
  5282. # no change by cat
  5283. @pipemess = ( 'cat' ) ;
  5284. is( 9, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  5285. q{message_for_host2: --pipemess 'cat', length} ) ;
  5286. is( 'blablabla', $string, q{message_for_host2: --pipemess 'cat', value} ) ;
  5287. # failure by false
  5288. @pipemess = ( 'false' ) ;
  5289. is( undef, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  5290. q{message_for_host2: --pipemess 'false', length} ) ;
  5291. is( undef, $string, q{message_for_host2: --pipemess 'false', value} ) ;
  5292. # failure by true since no output
  5293. @pipemess = ( 'true' ) ;
  5294. is( undef, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  5295. q{message_for_host2: --pipemess 'true', length} ) ;
  5296. is( undef, $string, q{message_for_host2: --pipemess 'true', value} ) ;
  5297. }
  5298. note( 'Leaving tests_message_for_host2()' ) ;
  5299. return ;
  5300. }
  5301. sub length_ref {
  5302. my $string_ref = shift ;
  5303. my $string_len = defined ${ $string_ref } ? length( ${ $string_ref } ) : q{} ; # length or empty string
  5304. return $string_len ;
  5305. }
  5306. sub tests_length_ref {
  5307. note( 'Entering tests_length_ref()' ) ;
  5308. my $notdefined ;
  5309. is( q{}, length_ref( \$notdefined ), q{length_ref: value not defined} ) ;
  5310. my $notref ;
  5311. is( q{}, length_ref( $notref ), q{length_ref: param not a ref} ) ;
  5312. my $lala = 'lala' ;
  5313. is( 4, length_ref( \$lala ), q{length_ref: lala length == 4} ) ;
  5314. is( 4, length_ref( \'lili' ), q{length_ref: lili length == 4} ) ;
  5315. note( 'Leaving tests_length_ref()' ) ;
  5316. return ;
  5317. }
  5318. sub date_for_host2 {
  5319. my( $h1_msg, $h1_idate ) = @_ ;
  5320. my $h1_date = q{} ;
  5321. if ( $syncinternaldates ) {
  5322. $h1_date = $h1_idate ;
  5323. $debug and myprint( "internal date from host1: [$h1_date]\n" ) ;
  5324. $h1_date = good_date( $h1_date ) ;
  5325. $debug and myprint( "internal date from host1: [$h1_date] (fixed)\n" ) ;
  5326. }
  5327. if ( $idatefromheader ) {
  5328. $h1_date = $imap1->get_header( $h1_msg, 'Date' ) ;
  5329. $debug and myprint( "header date from host1: [$h1_date]\n" ) ;
  5330. $h1_date = good_date( $h1_date ) ;
  5331. $debug and myprint( "header date from host1: [$h1_date] (fixed)\n" ) ;
  5332. }
  5333. return( $h1_date ) ;
  5334. }
  5335. sub flags_for_host2 {
  5336. my( $h1_flags, $permanentflags2 ) = @_ ;
  5337. # RFC 2060: This flag can not be altered by any client
  5338. $h1_flags =~ s@\\Recent\s?@@xgi ;
  5339. my $h1_flags_re ;
  5340. if ( @regexflag and defined( $h1_flags_re = flags_regex( $h1_flags ) ) ) {
  5341. $h1_flags = $h1_flags_re ;
  5342. }
  5343. $h1_flags = flagscase( $h1_flags ) if $flagscase ;
  5344. $h1_flags = flags_filter( $h1_flags, $permanentflags2) if ( $permanentflags2 and $filterflags ) ;
  5345. return( $h1_flags ) ;
  5346. }
  5347. sub subject {
  5348. my $string = shift ;
  5349. my $subject = q{} ;
  5350. my $header = extract_header( $string ) ;
  5351. if( $header =~ m/^Subject:\s*([^\n\r]*)\r?$/msx ) {
  5352. #myprint( "MMM[$1]\n" ) ;
  5353. $subject = $1 ;
  5354. }
  5355. return( $subject ) ;
  5356. }
  5357. sub tests_subject {
  5358. note( 'Entering tests_subject()' ) ;
  5359. ok( q{} eq subject( q{} ), 'subject: null') ;
  5360. ok( 'toto le hero' eq subject( 'Subject: toto le hero' ), 'subject: toto le hero') ;
  5361. ok( 'toto le hero' eq subject( 'Subject:toto le hero' ), 'subject: toto le hero blank') ;
  5362. ok( 'toto le hero' eq subject( "Subject:toto le hero\r\n" ), 'subject: toto le hero\r\n') ;
  5363. my $MESS ;
  5364. $MESS = <<'EOF';
  5365. From: lalala
  5366. Subject: toto le hero
  5367. Date: zzzzzz
  5368. Boogie boogie
  5369. EOF
  5370. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 2') ;
  5371. $MESS = <<'EOF';
  5372. Subject: toto le hero
  5373. From: lalala
  5374. Date: zzzzzz
  5375. Boogie boogie
  5376. EOF
  5377. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 3') ;
  5378. $MESS = <<'EOF';
  5379. From: lalala
  5380. Subject: cuicui
  5381. Date: zzzzzz
  5382. Subject: toto le hero
  5383. EOF
  5384. ok( 'cuicui' eq subject( $MESS ), 'subject: cuicui') ;
  5385. $MESS = <<'EOF';
  5386. From: lalala
  5387. Date: zzzzzz
  5388. Subject: toto le hero
  5389. EOF
  5390. ok( q{} eq subject( $MESS ), 'subject: null but body could') ;
  5391. note( 'Leaving tests_subject()' ) ;
  5392. return ;
  5393. }
  5394. # GlobVar
  5395. # $sync
  5396. # $max_msg_size_in_bytes
  5397. # $imap2
  5398. # $imap1
  5399. # $total_bytes_error
  5400. # $h1_nb_msg_processed
  5401. # $h2_uidguess
  5402. # ...
  5403. #
  5404. #
  5405. sub append_message_on_host2 {
  5406. my( $string_ref, $h1_fold, $h1_msg, $string_len, $h2_fold, $h1_size, $h1_flags, $h1_date, $cache_dir ) = @_ ;
  5407. myprint( debugmemory( $sync, " at A1" ) ) ;
  5408. my $new_id ;
  5409. if ( ! $sync->{dry} ) {
  5410. $max_msg_size_in_bytes = max( $h1_size, $max_msg_size_in_bytes ) ;
  5411. $new_id = $imap2->append_string( $h2_fold, ${ $string_ref }, $h1_flags, $h1_date ) ;
  5412. myprint( debugmemory( $sync, " at A2" ) ) ;
  5413. if ( ! $new_id){
  5414. my $subject = subject( ${ $string_ref } ) ;
  5415. my $error_imap = $imap2->LastError || q{} ;
  5416. my $error = "- msg $h1_fold/$h1_msg {$string_len} could not append ( Subject:[$subject], Date:[$h1_date], Size:[$h1_size] ) to folder $h2_fold: $error_imap\n" ;
  5417. errors_incr( $sync, $error ) ;
  5418. $total_bytes_error += $h1_size;
  5419. $h1_nb_msg_processed +=1 ;
  5420. return ;
  5421. }
  5422. else{
  5423. # good
  5424. # $new_id is an id if the IMAP server has the
  5425. # UIDPLUS capability else just a ref
  5426. if ( $new_id !~ m{^\d+$}x ) {
  5427. $new_id = lastuid( $imap2, $h2_fold, $h2_uidguess ) ;
  5428. }
  5429. $h2_uidguess += 1 ;
  5430. $sync->{total_bytes_transferred} += $h1_size ;
  5431. $sync->{nb_msg_transferred} += 1 ;
  5432. $h1_nb_msg_processed +=1 ;
  5433. my $time_spent = timesince( $sync->{begin_transfer_time} ) ;
  5434. my $rate = bytes_display_string( $sync->{total_bytes_transferred} / $time_spent ) ;
  5435. my $eta = eta( $time_spent,
  5436. $h1_nb_msg_processed, $h1_nb_msg_start, $sync->{nb_msg_transferred} ) ;
  5437. my $amount_transferred = bytes_display_string( $sync->{total_bytes_transferred} ) ;
  5438. myprintf( "msg %s/%-19s copied to %s/%-10s %.2f msgs/s %s/s %s copied %s\n",
  5439. $h1_fold, "$h1_msg {$string_len}", $h2_fold, $new_id, $sync->{nb_msg_transferred}/$time_spent, $rate,
  5440. $amount_transferred,
  5441. $eta );
  5442. sleep_if_needed( $sync ) ;
  5443. if ( $usecache and $cacheaftercopy and $new_id =~ m{^\d+$}x ) {
  5444. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$new_id\n" ) ;
  5445. touch( "$cache_dir/${h1_msg}_$new_id" )
  5446. or croak( "Couldn't touch $cache_dir/${h1_msg}_$new_id" ) ;
  5447. }
  5448. if ( $delete1 ) {
  5449. delete_message_on_host1( $h1_msg, $h1_fold ) ;
  5450. }
  5451. #myprint( "PRESS ENTER" ) and my $a = <> ;
  5452. return( $new_id ) ;
  5453. }
  5454. }
  5455. else{
  5456. $nb_msg_skipped_dry_mode += 1 ;
  5457. $h1_nb_msg_processed +=1 ;
  5458. }
  5459. return ;
  5460. }
  5461. sub tests_sleep_if_needed {
  5462. note( 'Entering tests_sleep_if_needed()' ) ;
  5463. is( undef, sleep_if_needed( ), 'sleep_if_needed: no args => undef' ) ;
  5464. my $mysync ;
  5465. is( undef, sleep_if_needed( $mysync ), 'sleep_if_needed: arg undef => undef' ) ;
  5466. $mysync->{maxbytespersecond} = 1000 ;
  5467. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: maxbytespersecond only => no sleep => 0' ) ;
  5468. $mysync->{begin_transfer_time} = time ; # now
  5469. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: begin_transfer_time now => no sleep => 0' ) ;
  5470. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before
  5471. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 0 => no sleep => 0' ) ;
  5472. $mysync->{total_bytes_transferred} = 2200 ;
  5473. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before
  5474. is( '0.20', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 2200 since 2s => sleep 0.2s' ) ;
  5475. is( '0', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 2200 since 2+2 == 4s => no sleep' ) ;
  5476. $mysync->{maxsleep} = 0.1 ;
  5477. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before again
  5478. is( '0.10', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 4000 since 2s but maxsleep 0.1s => sleep 0.1s' ) ;
  5479. $mysync->{maxbytesafter} = 4000 ;
  5480. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before again
  5481. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: maxbytesafter == total_bytes_transferred => no sleep => 0' ) ;
  5482. note( 'Leaving tests_sleep_if_needed()' ) ;
  5483. return ;
  5484. }
  5485. sub sleep_if_needed {
  5486. my( $mysync ) = shift ;
  5487. if ( ! $mysync ) {
  5488. return ;
  5489. }
  5490. # No need to go further if there is no limit set
  5491. if ( not ( $mysync->{maxmessagespersecond}
  5492. or $mysync->{maxbytespersecond} )
  5493. ) {
  5494. return ;
  5495. }
  5496. $mysync->{maxsleep} = defined $mysync->{maxsleep} ? $mysync->{maxsleep} : $MAX_SLEEP ;
  5497. # Must be positive
  5498. $mysync->{maxsleep} = max( 0, $mysync->{maxsleep} ) ;
  5499. my $time_spent = timesince( $mysync->{begin_transfer_time} ) ;
  5500. my $sleep_max_messages = sleep_max_messages( $mysync->{nb_msg_transferred}, $time_spent, $mysync->{maxmessagespersecond} ) ;
  5501. my $maxbytesafter = $mysync->{maxbytesafter} || 0 ;
  5502. my $total_bytes_transferred = $mysync->{total_bytes_transferred} || 0 ;
  5503. my $total_bytes_to_consider = $total_bytes_transferred - $maxbytesafter ;
  5504. #myprint( "maxbytesafter:$maxbytesafter\n" ) ;
  5505. #myprint( "total_bytes_to_consider:$total_bytes_to_consider\n" ) ;
  5506. my $sleep_max_bytes = sleep_max_bytes( $total_bytes_to_consider, $time_spent, $mysync->{maxbytespersecond} ) ;
  5507. my $sleep_max = min( $mysync->{maxsleep}, max( $sleep_max_messages, $sleep_max_bytes ) ) ;
  5508. $sleep_max = mysprintf( "%.2f", $sleep_max ) ; # round with 2 decimals.
  5509. if ( $sleep_max > 0 ) {
  5510. myprint( "sleeping $sleep_max s\n" ) ;
  5511. sleep $sleep_max ;
  5512. # Slept
  5513. return $sleep_max ;
  5514. }
  5515. # No sleep
  5516. return 0 ;
  5517. }
  5518. sub sleep_max_messages {
  5519. # how long we have to sleep to go under max_messages_per_second
  5520. my( $nb_msg_transferred, $time_spent, $maxmessagespersecond ) = @_ ;
  5521. if ( ( not defined $maxmessagespersecond ) or $maxmessagespersecond <= 0 ) { return( 0 ) } ;
  5522. my $sleep = ( $nb_msg_transferred / $maxmessagespersecond ) - $time_spent ;
  5523. # the sleep must be positive
  5524. return( max( 0, $sleep ) ) ;
  5525. }
  5526. sub tests_sleep_max_messages {
  5527. note( 'Entering tests_sleep_max_messages()' ) ;
  5528. ok( 0 == sleep_max_messages( 4, 2, undef ), 'sleep_max_messages: maxmessagespersecond = undef') ;
  5529. ok( 0 == sleep_max_messages( 4, 2, 0 ), 'sleep_max_messages: maxmessagespersecond = 0') ;
  5530. ok( 0 == sleep_max_messages( 4, 2, $MINUS_ONE ), 'sleep_max_messages: maxmessagespersecond = -1') ;
  5531. ok( 0 == sleep_max_messages( 4, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max reached') ;
  5532. ok( 2 == sleep_max_messages( 8, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max over') ;
  5533. ok( 0 == sleep_max_messages( 2, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max not reached') ;
  5534. note( 'Leaving tests_sleep_max_messages()' ) ;
  5535. return ;
  5536. }
  5537. sub sleep_max_bytes {
  5538. # how long we have to sleep to go under max_bytes_per_second
  5539. my( $total_bytes_to_consider, $time_spent, $maxbytespersecond ) = @_ ;
  5540. $total_bytes_to_consider ||= 0 ;
  5541. $time_spent ||= 0 ;
  5542. if ( ( not defined $maxbytespersecond ) or $maxbytespersecond <= 0 ) { return( 0 ) } ;
  5543. #myprint( "total_bytes_to_consider:$total_bytes_to_consider\n" ) ;
  5544. my $sleep = ( $total_bytes_to_consider / $maxbytespersecond ) - $time_spent ;
  5545. # the sleep must be positive
  5546. return( max( 0, $sleep ) ) ;
  5547. }
  5548. sub tests_sleep_max_bytes {
  5549. note( 'Entering tests_sleep_max_bytes()' ) ;
  5550. ok( 0 == sleep_max_bytes( 4000, 2, undef ), 'sleep_max_bytes: maxbytespersecond == undef => sleep 0' ) ;
  5551. ok( 0 == sleep_max_bytes( 4000, 2, 0 ), 'sleep_max_bytes: maxbytespersecond = 0 => sleep 0') ;
  5552. ok( 0 == sleep_max_bytes( 4000, 2, $MINUS_ONE ), 'sleep_max_bytes: maxbytespersecond = -1 => sleep 0') ;
  5553. ok( 0 == sleep_max_bytes( 4000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max reached sharp => sleep 0') ;
  5554. ok( 2 == sleep_max_bytes( 8000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max over => sleep a little') ;
  5555. ok( 0 == sleep_max_bytes( -8000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max not reached => sleep 0') ;
  5556. ok( 0 == sleep_max_bytes( 2000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max not reached => sleep 0') ;
  5557. ok( 0 == sleep_max_bytes( -2000, 2, 1000 ), 'sleep_max_bytes: maxbytespersecond = 1k max not reached => sleep 0') ;
  5558. note( 'Leaving tests_sleep_max_bytes()' ) ;
  5559. return ;
  5560. }
  5561. # 6 GlobVar: $sync $imap1 $h1_nb_msg_deleted $expunge1
  5562. sub delete_message_on_host1 {
  5563. my( $h1_msg, $h1_fold ) = @_ ;
  5564. my $expunge_message = q{} ;
  5565. $expunge_message = 'and expunged' if ( $expungeaftereach and $expunge1 ) ;
  5566. myprint( "Host1 msg $h1_fold/$h1_msg marked deleted $expunge_message $sync->{dry_message}\n" ) ;
  5567. if ( ! $sync->{dry} ) {
  5568. $imap1->delete_message( $h1_msg ) ;
  5569. $h1_nb_msg_deleted += 1 ;
  5570. $imap1->expunge( ) if ( $expungeaftereach and $expunge1 ) ;
  5571. }
  5572. return ;
  5573. }
  5574. sub eta {
  5575. my( $my_time_spent, $h1_nb_processed, $my_h1_nb_msg_start, $nb_transferred ) = @_ ;
  5576. return( q{} ) if not $foldersizes ;
  5577. my $time_remaining = time_remaining( $my_time_spent, $h1_nb_processed, $my_h1_nb_msg_start, $nb_transferred ) ;
  5578. my $nb_msg_remaining = $my_h1_nb_msg_start - $h1_nb_processed ;
  5579. my $eta_date = localtime( time + $time_remaining ) ;
  5580. return( mysprintf( 'ETA: %s %1.0f s %s/%s msgs left', $eta_date, $time_remaining, $nb_msg_remaining, $my_h1_nb_msg_start ) ) ;
  5581. }
  5582. sub time_remaining {
  5583. my( $my_time_spent, $h1_nb_processed, $my_h1_nb_msg_start, $nb_transferred ) = @_ ;
  5584. my $time_remaining = ( $my_time_spent / $nb_transferred ) * ( $my_h1_nb_msg_start - $h1_nb_processed ) ;
  5585. return( $time_remaining ) ;
  5586. }
  5587. sub tests_time_remaining {
  5588. note( 'Entering tests_time_remaining()' ) ;
  5589. ok( 1 == time_remaining( 1, 1, 2, 1 ), 'time_remaining: 1, 1, 2, 1 -> 1' ) ;
  5590. ok( 1 == time_remaining( 9, 9, 10, 9 ), 'time_remaining: 9, 9, 10, 9 -> 1' ) ;
  5591. ok( 9 == time_remaining( 1, 1, 10, 1 ), 'time_remaining: 1, 1, 10, 1 -> 1' ) ;
  5592. note( 'Leaving tests_time_remaining()' ) ;
  5593. return ;
  5594. }
  5595. sub cache_map {
  5596. my ( $cache_files_ref, $h1_msgs_ref, $h2_msgs_ref ) = @_;
  5597. my ( %map1_2, %map2_1, %done2 ) ;
  5598. my $h1_msgs_hash_ref = { } ;
  5599. my $h2_msgs_hash_ref = { } ;
  5600. @{ $h1_msgs_hash_ref }{ @{ $h1_msgs_ref } } = ( ) ;
  5601. @{ $h2_msgs_hash_ref }{ @{ $h2_msgs_ref } } = ( ) ;
  5602. foreach my $file ( sort @{ $cache_files_ref } ) {
  5603. $debugcache and myprint( "C12: $file\n" ) ;
  5604. ( $uid1, $uid2 ) = match_a_cache_file( $file ) ;
  5605. if ( exists( $h1_msgs_hash_ref->{ defined $uid1 ? $uid1 : q{} } )
  5606. and exists( $h2_msgs_hash_ref->{ defined $uid2 ? $uid2 : q{} } ) ) {
  5607. # keep only the greatest uid2
  5608. # 130_2301 and
  5609. # 130_231 => keep only 130 -> 2301
  5610. # keep only the greatest uid1
  5611. # 1601_260 and
  5612. # 161_260 => keep only 1601 -> 260
  5613. my $max_uid2 = max( $uid2, $map1_2{ $uid1 } || $MINUS_ONE ) ;
  5614. if ( exists $done2{ $max_uid2 } ) {
  5615. if ( $done2{ $max_uid2 } < $uid1 ) {
  5616. $map1_2{ $uid1 } = $max_uid2 ;
  5617. delete $map1_2{ $done2{ $max_uid2 } } ;
  5618. $done2{ $max_uid2 } = $uid1 ;
  5619. }
  5620. }else{
  5621. $map1_2{ $uid1 } = $max_uid2 ;
  5622. $done2{ $max_uid2 } = $uid1 ;
  5623. }
  5624. };
  5625. }
  5626. %map2_1 = reverse %map1_2 ;
  5627. return( \%map1_2, \%map2_1) ;
  5628. }
  5629. sub tests_cache_map {
  5630. note( 'Entering tests_cache_map()' ) ;
  5631. #$debugcache = 1 ;
  5632. my @cache_files = qw (
  5633. 100_200
  5634. 101_201
  5635. 120_220
  5636. 142_242
  5637. 143_243
  5638. 177_277
  5639. 177_278
  5640. 177_279
  5641. 155_255
  5642. 180_280
  5643. 181_280
  5644. 182_280
  5645. 130_231
  5646. 130_2301
  5647. 161_260
  5648. 1601_260
  5649. ) ;
  5650. my $msgs_1 = [120, 142, 143, 144, 161, 1601, 177, 182, 130 ];
  5651. my $msgs_2 = [ 242, 243, 260, 299, 377, 279, 255, 280, 231, 2301 ];
  5652. my( $c12, $c21 ) ;
  5653. ok( ( $c12, $c21 ) = cache_map( \@cache_files, $msgs_1, $msgs_2 ), 'cache_map: 02' );
  5654. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  5655. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  5656. ok( 0 == compare_lists( [ 130, 142, 143, 177, 182, 1601 ], $a1 ), 'cache_map: 03' );
  5657. ok( 0 == compare_lists( [ 242, 243, 260, 279, 280, 2301 ], $a2 ), 'cache_map: 04' );
  5658. ok( ! $c12->{161}, 'cache_map: ! 161 -> 260' );
  5659. ok( 260 == $c12->{1601}, 'cache_map: 1601 -> 260' );
  5660. ok( 2301 == $c12->{130}, 'cache_map: 130 -> 2301' );
  5661. #myprint( $c12->{1601}, "\n" ) ;
  5662. note( 'Leaving tests_cache_map()' ) ;
  5663. return ;
  5664. }
  5665. sub cache_dir_fix {
  5666. my $cache_dir = shift ;
  5667. $cache_dir =~ s/([;<>\*\|`&\$!#\(\)\[\]\{\}:'"\\])/\\$1/xg ;
  5668. #myprint( "cache_dir_fix: $cache_dir\n" ) ;
  5669. return( $cache_dir ) ;
  5670. }
  5671. sub tests_cache_dir_fix {
  5672. note( 'Entering tests_cache_dir_fix()' ) ;
  5673. ok( 'lalala' eq cache_dir_fix('lalala'), 'cache_dir_fix: lalala -> lalala' );
  5674. ok( 'ii\\\\ii' eq cache_dir_fix('ii\ii'), 'cache_dir_fix: ii\ii -> ii\\\\ii' );
  5675. ok( 'ii@ii' eq cache_dir_fix('ii@ii'), 'cache_dir_fix: ii@ii -> ii@ii' );
  5676. ok( 'ii@ii\\:ii' eq cache_dir_fix('ii@ii:ii'), 'cache_dir_fix: ii@ii:ii -> ii@ii\\:ii' );
  5677. ok( 'i\\\\i\\\\ii' eq cache_dir_fix('i\i\ii'), 'cache_dir_fix: i\i\ii -> i\\\\i\\\\ii' );
  5678. ok( 'i\\\\ii' eq cache_dir_fix('i\\ii'), 'cache_dir_fix: i\\ii -> i\\\\\\\\ii' );
  5679. ok( '\\\\ ' eq cache_dir_fix('\\ '), 'cache_dir_fix: \\ -> \\\\\ ' );
  5680. ok( '\\\\ ' eq cache_dir_fix('\ '), 'cache_dir_fix: \ -> \\\\\ ' );
  5681. ok( '\[bracket\]' eq cache_dir_fix('[bracket]'), 'cache_dir_fix: [bracket] -> \[bracket\]' );
  5682. note( 'Leaving tests_cache_dir_fix()' ) ;
  5683. return ;
  5684. }
  5685. sub cache_dir_fix_win {
  5686. my $cache_dir = shift ;
  5687. $cache_dir =~ s/(\[|\])/[$1]/xg ;
  5688. #myprint( "cache_dir_fix_win: $cache_dir\n" ) ;
  5689. return( $cache_dir ) ;
  5690. }
  5691. sub tests_cache_dir_fix_win {
  5692. note( 'Entering tests_cache_dir_fix_win()' ) ;
  5693. ok( 'lalala' eq cache_dir_fix_win('lalala'), 'cache_dir_fix_win: lalala -> lalala' );
  5694. ok( '[[]bracket[]]' eq cache_dir_fix_win('[bracket]'), 'cache_dir_fix_win: [bracket] -> [[]bracket[]]' );
  5695. note( 'Leaving tests_cache_dir_fix_win()' ) ;
  5696. return ;
  5697. }
  5698. sub get_cache {
  5699. my ( $cache_dir, $h1_msgs_ref, $h2_msgs_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_;
  5700. $debugcache and myprint( "Entering get_cache\n" ) ;
  5701. -d $cache_dir or return( undef ); # exit if cache directory doesn't exist
  5702. $debugcache and myprint( "cache_dir : $cache_dir\n" ) ;
  5703. if ( 'MSWin32' ne $OSNAME ) {
  5704. $cache_dir = cache_dir_fix( $cache_dir ) ;
  5705. }else{
  5706. $cache_dir = cache_dir_fix_win( $cache_dir ) ;
  5707. }
  5708. $debugcache and myprint( "cache_dir_fix: $cache_dir\n" ) ;
  5709. my @cache_files = bsd_glob( "$cache_dir/*" ) ;
  5710. #$debugcache and myprint( "cache_files: [@cache_files]\n" ) ;
  5711. $debugcache and myprint( 'cache_files: ', scalar @cache_files , " files found\n" ) ;
  5712. my( $cache_1_2_ref, $cache_2_1_ref )
  5713. = cache_map( \@cache_files, $h1_msgs_ref, $h2_msgs_ref ) ;
  5714. clean_cache( \@cache_files, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  5715. $debugcache and myprint( "Exiting get_cache\n" ) ;
  5716. return( $cache_1_2_ref, $cache_2_1_ref ) ;
  5717. }
  5718. sub tests_get_cache {
  5719. note( 'Entering tests_get_cache()' ) ;
  5720. ok( not( get_cache('/cache_no_exist') ), 'get_cache: /cache_no_exist' );
  5721. ok( ( not -d 'W/tmp/cache/F1/F2' or rmtree( 'W/tmp/cache/F1/F2' ) ), 'get_cache: rmtree W/tmp/cache/F1/F2' ) ;
  5722. ok( mkpath( 'W/tmp/cache/F1/F2' ), 'get_cache: mkpath W/tmp/cache/F1/F2' ) ;
  5723. my @test_files_cache = ( qw(
  5724. W/tmp/cache/F1/F2/100_200
  5725. W/tmp/cache/F1/F2/101_201
  5726. W/tmp/cache/F1/F2/120_220
  5727. W/tmp/cache/F1/F2/142_242
  5728. W/tmp/cache/F1/F2/143_243
  5729. W/tmp/cache/F1/F2/177_277
  5730. W/tmp/cache/F1/F2/177_377
  5731. W/tmp/cache/F1/F2/177_777
  5732. W/tmp/cache/F1/F2/155_255
  5733. ) ) ;
  5734. ok( touch( @test_files_cache ), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  5735. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  5736. # on live:
  5737. my $msgs_1 = [120, 142, 143, 144, 177 ];
  5738. my $msgs_2 = [ 242, 243, 299, 377, 777, 255 ];
  5739. my $msgs_all_1 = { 120 => 0, 142 => 0, 143 => 0, 144 => 0, 177 => 0 } ;
  5740. my $msgs_all_2 = { 242 => 0, 243 => 0, 299 => 0, 377 => 0, 777 => 0, 255 => 0 } ;
  5741. my( $c12, $c21 ) ;
  5742. ok( ( $c12, $c21 ) = get_cache( 'W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  5743. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  5744. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  5745. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: 03' );
  5746. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: 04' );
  5747. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  5748. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  5749. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file removed 100_200');
  5750. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file removed 101_201');
  5751. # test clean_cache executed
  5752. $maxage = 2 ;
  5753. ok( touch(@test_files_cache), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  5754. ok( ( $c12, $c21 ) = get_cache('W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  5755. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  5756. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  5757. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file NOT removed 100_200');
  5758. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file NOT removed 101_201');
  5759. # strange files
  5760. #$debugcache = 1 ;
  5761. $maxage = undef ;
  5762. ok( ( not -d 'W/tmp/cache/rr\uee' or rmtree( 'W/tmp/cache/rr\uee' )), 'get_cache: rmtree W/tmp/cache/rr\uee' ) ;
  5763. ok( mkpath( 'W/tmp/cache/rr\uee' ), 'get_cache: mkpath W/tmp/cache/rr\uee' ) ;
  5764. @test_files_cache = ( qw(
  5765. W/tmp/cache/rr\uee/100_200
  5766. W/tmp/cache/rr\uee/101_201
  5767. W/tmp/cache/rr\uee/120_220
  5768. W/tmp/cache/rr\uee/142_242
  5769. W/tmp/cache/rr\uee/143_243
  5770. W/tmp/cache/rr\uee/177_277
  5771. W/tmp/cache/rr\uee/177_377
  5772. W/tmp/cache/rr\uee/177_777
  5773. W/tmp/cache/rr\uee/155_255
  5774. ) ) ;
  5775. ok( touch(@test_files_cache), 'get_cache: touch strange W/tmp/cache/...' ) ;
  5776. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  5777. # on live:
  5778. $msgs_1 = [120, 142, 143, 144, 177 ] ;
  5779. $msgs_2 = [ 242, 243, 299, 377, 777, 255 ] ;
  5780. $msgs_all_1 = { 120 => q{}, 142 => q{}, 143 => q{}, 144 => q{}, 177 => q{} } ;
  5781. $msgs_all_2 = { 242 => q{}, 243 => q{}, 299 => q{}, 377 => q{}, 777 => q{}, 255 => q{} } ;
  5782. 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' );
  5783. $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  5784. $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  5785. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: strange path 03' );
  5786. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: strange path 04' );
  5787. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 142_242');
  5788. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 143_243');
  5789. ok( ! -f 'W/tmp/cache/rr\uee/100_200', 'get_cache: strange path file removed 100_200');
  5790. ok( ! -f 'W/tmp/cache/rr\uee/101_201', 'get_cache: strange path file removed 101_201');
  5791. note( 'Leaving tests_get_cache()' ) ;
  5792. return ;
  5793. }
  5794. sub match_a_cache_file {
  5795. my $file = shift ;
  5796. my ( $cache_uid1, $cache_uid2 ) ;
  5797. return( ( undef, undef ) ) if ( ! $file ) ;
  5798. if ( $file =~ m{(?:^|/)(\d+)_(\d+)$}x ) {
  5799. $cache_uid1 = $1 ;
  5800. $cache_uid2 = $2 ;
  5801. }
  5802. return( $cache_uid1, $cache_uid2 ) ;
  5803. }
  5804. sub tests_match_a_cache_file {
  5805. note( 'Entering tests_match_a_cache_file()' ) ;
  5806. my ( $tuid1, $tuid2 ) ;
  5807. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( ), 'match_a_cache_file: no arg' ) ;
  5808. ok( ! defined $tuid1 , 'match_a_cache_file: no arg 1' ) ;
  5809. ok( ! defined $tuid2 , 'match_a_cache_file: no arg 2' ) ;
  5810. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( q{} ), 'match_a_cache_file: empty arg' ) ;
  5811. ok( ! defined $tuid1 , 'match_a_cache_file: empty arg 1' ) ;
  5812. ok( ! defined $tuid2 , 'match_a_cache_file: empty arg 2' ) ;
  5813. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '000_000' ), 'match_a_cache_file: 000_000' ) ;
  5814. ok( '000' eq $tuid1, 'match_a_cache_file: 000_000 1' ) ;
  5815. ok( '000' eq $tuid2, 'match_a_cache_file: 000_000 2' ) ;
  5816. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '123_456' ), 'match_a_cache_file: 123_456' ) ;
  5817. ok( '123' eq $tuid1, 'match_a_cache_file: 123_456 1' ) ;
  5818. ok( '456' eq $tuid2, 'match_a_cache_file: 123_456 2' ) ;
  5819. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/tmp/truc/123_456' ), 'match_a_cache_file: /tmp/truc/123_456' ) ;
  5820. ok( '123' eq $tuid1, 'match_a_cache_file: /tmp/truc/123_456 1' ) ;
  5821. ok( '456' eq $tuid2, 'match_a_cache_file: /tmp/truc/123_456 2' ) ;
  5822. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/lala123_456' ), 'match_a_cache_file: NO /lala123_456' ) ;
  5823. ok( ! $tuid1, 'match_a_cache_file: /lala123_456 1' ) ;
  5824. ok( ! $tuid2, 'match_a_cache_file: /lala123_456 2' ) ;
  5825. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( 'la123_456' ), 'match_a_cache_file: NO la123_456' ) ;
  5826. ok( ! $tuid1, 'match_a_cache_file: la123_456 1' ) ;
  5827. ok( ! $tuid2, 'match_a_cache_file: la123_456 2' ) ;
  5828. note( 'Leaving tests_match_a_cache_file()' ) ;
  5829. return ;
  5830. }
  5831. sub clean_cache {
  5832. my ( $cache_files_ref, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_ ;
  5833. $debugcache and myprint( "Entering clean_cache\n" ) ;
  5834. $debugcache and myprint( map { "$_ -> " . $cache_1_2_ref->{ $_ } . "\n" } keys %{ $cache_1_2_ref } ) ;
  5835. foreach my $file ( @{ $cache_files_ref } ) {
  5836. $debugcache and myprint( "$file\n" ) ;
  5837. my ( $cache_uid1, $cache_uid2 ) = match_a_cache_file( $file ) ;
  5838. $debugcache and myprint( "u1: $cache_uid1 u2: $cache_uid2 c12: ", $cache_1_2_ref->{ $cache_uid1 } || q{}, "\n") ;
  5839. # or ( ! exists( $cache_1_2_ref->{ $cache_uid1 } ) )
  5840. # or ( ! ( $cache_uid2 == $cache_1_2_ref->{ $cache_uid1 } ) )
  5841. if ( ( not defined $cache_uid1 )
  5842. or ( not defined $cache_uid2 )
  5843. or ( not exists $h1_msgs_all_hash_ref->{ $cache_uid1 } )
  5844. or ( not exists $h2_msgs_all_hash_ref->{ $cache_uid2 } )
  5845. ) {
  5846. $debugcache and myprint( "remove $file\n" ) ;
  5847. unlink $file or myprint( "$OS_ERROR" ) ;
  5848. }
  5849. }
  5850. $debugcache and myprint( "Exiting clean_cache\n" ) ;
  5851. return( 1 ) ;
  5852. }
  5853. sub tests_clean_cache {
  5854. note( 'Entering tests_clean_cache()' ) ;
  5855. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache: rmtree W/tmp/cache/G1/G2' ) ;
  5856. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache: mkpath W/tmp/cache/G1/G2' ) ;
  5857. my @test_files_cache = ( qw(
  5858. W/tmp/cache/G1/G2/100_200
  5859. W/tmp/cache/G1/G2/101_201
  5860. W/tmp/cache/G1/G2/120_220
  5861. W/tmp/cache/G1/G2/142_242
  5862. W/tmp/cache/G1/G2/143_243
  5863. W/tmp/cache/G1/G2/177_277
  5864. W/tmp/cache/G1/G2/177_377
  5865. W/tmp/cache/G1/G2/177_777
  5866. W/tmp/cache/G1/G2/155_255
  5867. ) ) ;
  5868. ok( touch(@test_files_cache), 'clean_cache: touch W/tmp/cache/G1/G2/...' ) ;
  5869. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 before' );
  5870. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 before' );
  5871. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 before' );
  5872. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 before' );
  5873. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 before' );
  5874. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 before' );
  5875. my $cache = {
  5876. 142 => 242,
  5877. 177 => 777,
  5878. } ;
  5879. my $all_1 = {
  5880. 142 => q{},
  5881. 177 => q{},
  5882. } ;
  5883. my $all_2 = {
  5884. 200 => q{},
  5885. 242 => q{},
  5886. 777 => q{},
  5887. } ;
  5888. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache: ' ) ;
  5889. ok( ! -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 after' );
  5890. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 after' );
  5891. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 after' );
  5892. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 after' );
  5893. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 after' );
  5894. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 after' );
  5895. note( 'Leaving tests_clean_cache()' ) ;
  5896. return ;
  5897. }
  5898. sub tests_clean_cache_2 {
  5899. note( 'Entering tests_clean_cache_2()' ) ;
  5900. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache_2: rmtree W/tmp/cache/G1/G2' ) ;
  5901. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache_2: mkpath W/tmp/cache/G1/G2' ) ;
  5902. my @test_files_cache = ( qw(
  5903. W/tmp/cache/G1/G2/100_200
  5904. W/tmp/cache/G1/G2/101_201
  5905. W/tmp/cache/G1/G2/120_220
  5906. W/tmp/cache/G1/G2/142_242
  5907. W/tmp/cache/G1/G2/143_243
  5908. W/tmp/cache/G1/G2/177_277
  5909. W/tmp/cache/G1/G2/177_377
  5910. W/tmp/cache/G1/G2/177_777
  5911. W/tmp/cache/G1/G2/155_255
  5912. ) ) ;
  5913. ok( touch(@test_files_cache), 'clean_cache_2: touch W/tmp/cache/G1/G2/...' ) ;
  5914. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 before' );
  5915. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 before' );
  5916. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 before' );
  5917. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 before' );
  5918. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 before' );
  5919. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 before' );
  5920. my $cache = {
  5921. 142 => 242,
  5922. 177 => 777,
  5923. } ;
  5924. my $all_1 = {
  5925. $NUMBER_100 => q{},
  5926. 142 => q{},
  5927. 177 => q{},
  5928. } ;
  5929. my $all_2 = {
  5930. 200 => q{},
  5931. 242 => q{},
  5932. 777 => q{},
  5933. } ;
  5934. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache_2: ' ) ;
  5935. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 after' );
  5936. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 after' );
  5937. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 after' );
  5938. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 after' );
  5939. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 after' );
  5940. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 after' );
  5941. note( 'Leaving tests_clean_cache_2()' ) ;
  5942. return ;
  5943. }
  5944. sub tests_mkpath {
  5945. note( 'Entering tests_mkpath()' ) ;
  5946. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' )), 'mkpath: mkpath W/tmp/tests/' ) ;
  5947. SKIP: {
  5948. skip( 'Tests only for Unix', 10 ) if ( 'MSWin32' eq $OSNAME ) ;
  5949. my $long_path_unix = '123456789/' x 30 ;
  5950. ok( ( -d "W/tmp/tests/long/$long_path_unix" or mkpath( "W/tmp/tests/long/$long_path_unix" ) ), 'mkpath: mkpath 300 char' ) ;
  5951. ok( -d "W/tmp/tests/long/$long_path_unix", 'mkpath: mkpath > 300 char verified' ) ;
  5952. ok( ( -d "W/tmp/tests/long/$long_path_unix" and rmtree( 'W/tmp/tests/long/' ) ), 'mkpath: rmtree 300 char' ) ;
  5953. ok( ! -d "W/tmp/tests/long/$long_path_unix", 'mkpath: rmtree 300 char verified' ) ;
  5954. ok( ( -d 'W/tmp/tests/trailing_dots...' or mkpath( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: mkpath trailing_dots...' ) ;
  5955. ok( -d 'W/tmp/tests/trailing_dots...', 'mkpath: mkpath trailing_dots... verified' ) ;
  5956. ok( ( -d 'W/tmp/tests/trailing_dots...' and rmtree( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: rmtree trailing_dots...' ) ;
  5957. ok( ! -d 'W/tmp/tests/trailing_dots...', 'mkpath: rmtree trailing_dots... verified' ) ;
  5958. eval { ok( 1 / 0, 'mkpath: divide by 0' ) ; } or ok( 1, 'mkpath: can not divide by 0' ) ;
  5959. ok( 1, 'mkpath: still alive' ) ;
  5960. } ;
  5961. SKIP: {
  5962. skip( 'Tests only for MSWin32', 13 ) if ( 'MSWin32' ne $OSNAME ) ;
  5963. my $long_path_2_prefix = ".\\imapsync_tests" || '\\\?\\E:\\TEMP\\imapsync_tests' ;
  5964. myprint( "long_path_2_prefix: $long_path_2_prefix\n" ) ;
  5965. my $long_path_100 = $long_path_2_prefix . '\\' . '123456789\\' x 10 . 'END' ;
  5966. my $long_path_300 = $long_path_2_prefix . '\\' . '123456789\\' x 30 . 'END' ;
  5967. #myprint( "$long_path_100\n" ) ;
  5968. ok( ( -d $long_path_2_prefix or mkpath( $long_path_2_prefix ) ), 'mkpath: -d mkpath small path' ) ;
  5969. ok( ( -d $long_path_2_prefix ), 'mkpath: -d mkpath small path done' ) ;
  5970. ok( ( -d $long_path_100 or mkpath( $long_path_100 ) ), 'mkpath: mkpath > 100 char' ) ;
  5971. ok( ( -d $long_path_100 ), 'mkpath: -d mkpath > 200 char done' ) ;
  5972. ok( ( -d $long_path_2_prefix and rmtree( $long_path_2_prefix ) ), 'mkpath: rmtree > 100 char' ) ;
  5973. ok( (! -d $long_path_2_prefix ), 'mkpath: ! -d rmtree done' ) ;
  5974. # Without the eval the following mkpath 300 just kill the whole process without a whisper
  5975. #myprint( "$long_path_300\n" ) ;
  5976. eval { ok( ( -d $long_path_300 or mkpath( $long_path_300 ) ), 'mkpath: create a path with 300 characters' ) ; }
  5977. or ok( 1, 'mkpath: can not create a path with 300 characters' ) ;
  5978. ok( ( ( ! -d $long_path_300 ) or -d $long_path_300 and rmtree( $long_path_300 ) ), 'mkpath: rmtree the 300 character path' ) ;
  5979. ok( 1, 'mkpath: still alive' ) ;
  5980. ok( ( -d 'W/tmp/tests/trailing_dots...' or mkpath( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: mkpath trailing_dots...' ) ;
  5981. ok( -d 'W/tmp/tests/trailing_dots...', 'mkpath: mkpath trailing_dots... verified' ) ;
  5982. ok( ( -d 'W/tmp/tests/trailing_dots...' and rmtree( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: rmtree trailing_dots...' ) ;
  5983. ok( ! -d 'W/tmp/tests/trailing_dots...', 'mkpath: rmtree trailing_dots... verified' ) ;
  5984. } ;
  5985. note( 'Leaving tests_mkpath()' ) ;
  5986. # Keep this because of the eval used by the caller (failed badly?)
  5987. return 1 ;
  5988. }
  5989. sub tests_touch {
  5990. note( 'Entering tests_touch()' ) ;
  5991. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' )), 'touch: mkpath W/tmp/tests/' ) ;
  5992. ok( 1 == touch( 'W/tmp/tests/lala'), 'touch: W/tmp/tests/lala') ;
  5993. ok( 1 == touch( 'W/tmp/tests/\y'), 'touch: W/tmp/tests/\y') ;
  5994. ok( 0 == touch( '/no/no/no/aaa'), 'touch: not /aaa') ;
  5995. ok( 1 == touch( 'W/tmp/tests/lili', 'W/tmp/tests/lolo'), 'touch: 2 files') ;
  5996. ok( 0 == touch( 'W/tmp/tests/\y', '/no/no/aaa'), 'touch: 2 files, 1 fails' ) ;
  5997. note( 'Leaving tests_touch()' ) ;
  5998. return ;
  5999. }
  6000. sub touch {
  6001. my @files = @_ ;
  6002. my $failures = 0 ;
  6003. foreach my $file ( @files ) {
  6004. my $fh = IO::File->new ;
  6005. if ( $fh->open(">> $file" ) ) {
  6006. $fh->close ;
  6007. }else{
  6008. myprint( "Could not open file $file in write/append mode\n" ) ;
  6009. $failures++ ;
  6010. }
  6011. }
  6012. return( ! $failures );
  6013. }
  6014. sub tests_tmpdir_has_colon_bug {
  6015. note( 'Entering tests_tmpdir_has_colon_bug()' ) ;
  6016. ok( 0 == tmpdir_has_colon_bug( q{} ), 'tmpdir_has_colon_bug: ' ) ;
  6017. ok( 0 == tmpdir_has_colon_bug( '/tmp' ), 'tmpdir_has_colon_bug: /tmp' ) ;
  6018. ok( 1 == tmpdir_has_colon_bug( 'C:' ), 'tmpdir_has_colon_bug: C:' ) ;
  6019. ok( 1 == tmpdir_has_colon_bug( 'C:\temp' ), 'tmpdir_has_colon_bug: C:\temp' ) ;
  6020. note( 'Leaving tests_tmpdir_has_colon_bug()' ) ;
  6021. return ;
  6022. }
  6023. sub tmpdir_has_colon_bug {
  6024. my $path = shift ;
  6025. my $path_filtered = filter_forbidden_characters( $path ) ;
  6026. if ( $path_filtered ne $path ) {
  6027. ( -d $path_filtered ) and myprint( "Path $path was previously mistakely changed to $path_filtered\n" ) ;
  6028. return( 1 ) ;
  6029. }
  6030. return( 0 ) ;
  6031. }
  6032. sub tmpdir_fix_colon_bug {
  6033. my $mysync = shift ;
  6034. my $err = 0 ;
  6035. if ( not (-d $mysync->{ tmpdir } and -r _ and -w _) ) {
  6036. myprint( "tmpdir $mysync->{ tmpdir } is not valid\n" ) ;
  6037. return( 0 ) ;
  6038. }
  6039. my $cachedir_new = "$mysync->{ tmpdir }/imapsync_cache" ;
  6040. if ( not tmpdir_has_colon_bug( $cachedir_new ) ) { return( 0 ) } ;
  6041. # check if old cache directory already exists
  6042. my $cachedir_old = filter_forbidden_characters( $cachedir_new ) ;
  6043. if ( not ( -d $cachedir_old ) ) {
  6044. myprint( "Old cache directory $cachedir_new no exists, nothing to do\n" ) ;
  6045. return( 1 ) ;
  6046. }
  6047. # check if new cache directory already exists
  6048. if ( -d $cachedir_new ) {
  6049. myprint( "New fixed cache directory $cachedir_new already exists, not moving the old one $cachedir_old. Fix this manually.\n" ) ;
  6050. return( 0 ) ;
  6051. }else{
  6052. # move the old one to the new place
  6053. myprint( "Moving $cachedir_old to $cachedir_new Do not interrupt this task.\n" ) ;
  6054. File::Copy::Recursive::rmove( $cachedir_old, $cachedir_new )
  6055. or do {
  6056. myprint( "Could not move $cachedir_old to $cachedir_new\n" ) ;
  6057. $err++ ;
  6058. } ;
  6059. # check it succeeded
  6060. if ( -d $cachedir_new and -r _ and -w _ ) {
  6061. myprint( "New fixed cache directory $cachedir_new ok\n" ) ;
  6062. }else{
  6063. myprint( "New fixed cache directory $cachedir_new does not exist\n" ) ;
  6064. $err++ ;
  6065. }
  6066. if ( -d $cachedir_old ) {
  6067. myprint( "Old cache directory $cachedir_old still exists\n" ) ;
  6068. $err++ ;
  6069. }else{
  6070. myprint( "Old cache directory $cachedir_old successfuly moved\n" ) ;
  6071. }
  6072. }
  6073. return( not $err ) ;
  6074. }
  6075. sub tests_cache_folder {
  6076. note( 'Entering tests_cache_folder()' ) ;
  6077. ok( '/path/fold1/fold2' eq cache_folder( q{}, '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  6078. ok( '/pa_th/fold1/fold2' eq cache_folder( q{}, '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  6079. 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' ) ;
  6080. ok( 'D:/path/fold1/fold2' eq cache_folder( 'D:', '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  6081. ok( 'D:/pa_th/fold1/fold2' eq cache_folder( 'D:', '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  6082. 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' ) ;
  6083. ok( '//' eq cache_folder( q{}, q{}, q{}, q{}), 'cache_folder: -> //' ) ;
  6084. ok( '//_______' eq cache_folder( q{}, q{}, q{}, '*|?:"<>'), 'cache_folder: *|?:"<> -> //_______' ) ;
  6085. note( 'Leaving tests_cache_folder()' ) ;
  6086. return ;
  6087. }
  6088. sub cache_folder {
  6089. my( $cache_base, $cache_dir, $h1_fold, $h2_fold ) = @_ ;
  6090. my $sep_1 = $h1_sep || '/';
  6091. my $sep_2 = $h2_sep || '/';
  6092. #myprint( "$cache_dir h1_fold $h1_fold sep1 $sep_1 h2_fold $h2_fold sep2 $sep_2\n" ) ;
  6093. $h1_fold = convert_sep_to_slash( $h1_fold, $sep_1 ) ;
  6094. $h2_fold = convert_sep_to_slash( $h2_fold, $sep_2 ) ;
  6095. my $cache_folder = "$cache_base" . filter_forbidden_characters( "$cache_dir/$h1_fold/$h2_fold" ) ;
  6096. #myprint( "cache_folder [$cache_folder]\n" ) ;
  6097. return( $cache_folder ) ;
  6098. }
  6099. sub filter_forbidden_characters {
  6100. my $string = shift ;
  6101. if ( ! defined $string ) { return ; }
  6102. if ( 'MSWin32' eq $OSNAME ) {
  6103. # Move trailing whitespace to _ " a b /c d " -> " a b_/c d_"
  6104. $string =~ s{\ (/|$)}{_$1}xg ;
  6105. }
  6106. $string =~ s{[\Q*|?:"<>\E\t\r\n\\]}{_}xg ;
  6107. #myprint( "[$string]\n" ) ;
  6108. return( $string ) ;
  6109. }
  6110. sub tests_filter_forbidden_characters {
  6111. note( 'Entering tests_filter_forbidden_characters()' ) ;
  6112. ok( 'a_b' eq filter_forbidden_characters( 'a_b' ), 'filter_forbidden_characters: a_b -> a_b' ) ;
  6113. ok( 'a_b' eq filter_forbidden_characters( 'a*b' ), 'filter_forbidden_characters: a*b -> a_b' ) ;
  6114. ok( 'a_b' eq filter_forbidden_characters( 'a|b' ), 'filter_forbidden_characters: a|b -> a_b' ) ;
  6115. ok( 'a_b' eq filter_forbidden_characters( 'a?b' ), 'filter_forbidden_characters: a?b -> a_b' ) ;
  6116. ok( 'a_______b' eq filter_forbidden_characters( 'a*|?:"<>b' ), 'filter_forbidden_characters: a*|?:"<>b -> a_______b' ) ;
  6117. SKIP: {
  6118. skip( 'Not on MSWin32', 1 ) if ( 'MSWin32' eq $OSNAME ) ;
  6119. ok( ( 'a b ' eq filter_forbidden_characters( 'a b ' ) ), 'filter_forbidden_characters: "a b " -> "a b "' ) ;
  6120. } ;
  6121. SKIP: {
  6122. skip( 'Only on MSWin32', 2 ) if ( 'MSWin32' ne $OSNAME ) ;
  6123. ok( ( ' a b_' eq filter_forbidden_characters( ' a b ' ) ), 'filter_forbidden_characters: "a b " -> "a b_"' ) ;
  6124. ok( ( ' a b_/ c d_' eq filter_forbidden_characters( ' a b / c d ' ) ), 'filter_forbidden_characters: " a b / c d " -> "a b_/ c d_"' ) ;
  6125. } ;
  6126. ok( 'a_b' eq filter_forbidden_characters( "a\tb" ), 'filter_forbidden_characters: a\tb -> a_b' ) ;
  6127. ok( "a_b" eq filter_forbidden_characters( "a\rb" ), 'filter_forbidden_characters: a\rb -> a_b' ) ;
  6128. ok( "a_b" eq filter_forbidden_characters( "a\nb" ), 'filter_forbidden_characters: a\nb -> a_b' ) ;
  6129. ok( "a_b" eq filter_forbidden_characters( "a\\b" ), 'filter_forbidden_characters: a\b -> a_b' ) ;
  6130. note( 'Leaving tests_filter_forbidden_characters()' ) ;
  6131. return ;
  6132. }
  6133. sub convert_sep_to_slash {
  6134. my ( $folder, $sep ) = @_ ;
  6135. $folder =~ s{\Q$sep\E}{/}xg ;
  6136. return( $folder ) ;
  6137. }
  6138. sub tests_convert_sep_to_slash {
  6139. note( 'Entering tests_convert_sep_to_slash()' ) ;
  6140. ok(q{} eq convert_sep_to_slash(q{}, '/'), 'convert_sep_to_slash: no folder');
  6141. ok('INBOX' eq convert_sep_to_slash('INBOX', '/'), 'convert_sep_to_slash: INBOX');
  6142. ok('INBOX/foo' eq convert_sep_to_slash('INBOX/foo', '/'), 'convert_sep_to_slash: INBOX/foo');
  6143. ok('INBOX/foo' eq convert_sep_to_slash('INBOX_foo', '_'), 'convert_sep_to_slash: INBOX_foo');
  6144. ok('INBOX/foo/zob' eq convert_sep_to_slash('INBOX_foo_zob', '_'), 'convert_sep_to_slash: INBOX_foo_zob');
  6145. ok('INBOX/foo' eq convert_sep_to_slash('INBOX.foo', '.'), 'convert_sep_to_slash: INBOX.foo');
  6146. ok('INBOX/foo/hi' eq convert_sep_to_slash('INBOX.foo.hi', '.'), 'convert_sep_to_slash: INBOX.foo.hi');
  6147. note( 'Leaving tests_convert_sep_to_slash()' ) ;
  6148. return ;
  6149. }
  6150. sub tests_regexmess {
  6151. note( 'Entering tests_regexmess()' ) ;
  6152. ok( 'blabla' eq regexmess( 'blabla' ), 'regexmess, no regexmess, nothing to do' ) ;
  6153. @regexmess = ( 'lalala' ) ;
  6154. ok( not( defined regexmess( 'popopo' ) ), 'regexmess, bad regex lalala' ) ;
  6155. @regexmess = ( 's/p/Z/g' ) ;
  6156. ok( 'ZoZoZo' eq regexmess( 'popopo' ), 'regexmess, s/p/Z/g' ) ;
  6157. @regexmess = ( 's{c}{C}gxms' ) ;
  6158. ok("H1: abC\nH2: Cde\n\nBody abC"
  6159. eq regexmess( "H1: abc\nH2: cde\n\nBody abc"),
  6160. 'regexmess, c->C');
  6161. @regexmess = ( 's{\AFrom\ }{From:}gxms' ) ;
  6162. ok( q{}
  6163. eq regexmess(q{}),
  6164. 'From mbox 1 add colon blank');
  6165. ok( 'From:<tartanpion@machin.truc>'
  6166. eq regexmess('From <tartanpion@machin.truc>'),
  6167. 'From mbox 2 add colo');
  6168. ok( "\n" . 'From <tartanpion@machin.truc>'
  6169. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  6170. 'From mbox 3 add colo') ;
  6171. ok( "From: zzz\n" . 'From <tartanpion@machin.truc>'
  6172. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  6173. 'From mbox 4 add colo') ;
  6174. @regexmess = ( 's{\AFrom\ [^\n]*(\n)?}{}gxms' ) ;
  6175. ok( q{}
  6176. eq regexmess(q{}),
  6177. 'From mbox 1 remove, blank');
  6178. ok( q{}
  6179. eq regexmess('From <tartanpion@machin.truc>'),
  6180. 'From mbox 2 remove');
  6181. ok( "\n" . 'From <tartanpion@machin.truc>'
  6182. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  6183. 'From mbox 3 remove');
  6184. #myprint( "[", regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'), "]" ) ;
  6185. ok( q{} . 'From <tartanpion@machin.truc>'
  6186. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  6187. 'From mbox 4 remove');
  6188. ok(
  6189. <<'EOM'
  6190. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6191. From:<tartanpion@machin.truc>
  6192. Hello,
  6193. Bye.
  6194. EOM
  6195. eq regexmess(
  6196. <<'EOM'
  6197. From zzz
  6198. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6199. From:<tartanpion@machin.truc>
  6200. Hello,
  6201. Bye.
  6202. EOM
  6203. ), 'From mbox 5 remove');
  6204. @regexmess = ( 's{\A((?:[^\n]+\n)+|)^Disposition-Notification-To:[^\n]*\n(\r?\n|.*\n\r?\n)}{$1$2}xms' ) ; # SUPER SUPER BEST!
  6205. ok(
  6206. <<'EOM'
  6207. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6208. From:<tartanpion@machin.truc>
  6209. Hello,
  6210. Bye.
  6211. EOM
  6212. eq regexmess(
  6213. <<'EOM'
  6214. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6215. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6216. From:<tartanpion@machin.truc>
  6217. Hello,
  6218. Bye.
  6219. EOM
  6220. ),
  6221. 'regexmess: 1 Delete header Disposition-Notification-To:');
  6222. ok(
  6223. <<'EOM'
  6224. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6225. From:<tartanpion@machin.truc>
  6226. Hello,
  6227. Bye.
  6228. EOM
  6229. eq regexmess(
  6230. <<'EOM'
  6231. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6232. From:<tartanpion@machin.truc>
  6233. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6234. Hello,
  6235. Bye.
  6236. EOM
  6237. ),
  6238. 'regexmess: 2 Delete header Disposition-Notification-To:');
  6239. ok(
  6240. <<'EOM'
  6241. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6242. From:<tartanpion@machin.truc>
  6243. Hello,
  6244. Bye.
  6245. EOM
  6246. eq regexmess(
  6247. <<'EOM'
  6248. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6249. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6250. From:<tartanpion@machin.truc>
  6251. Hello,
  6252. Bye.
  6253. EOM
  6254. ),
  6255. 'regexmess: 3 Delete header Disposition-Notification-To:');
  6256. ok(
  6257. <<'EOM'
  6258. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6259. From:<tartanpion@machin.truc>
  6260. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6261. Bye.
  6262. EOM
  6263. eq regexmess(
  6264. <<'EOM'
  6265. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6266. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6267. From:<tartanpion@machin.truc>
  6268. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6269. Bye.
  6270. EOM
  6271. ),
  6272. 'regexmess: 4 Delete header Disposition-Notification-To:');
  6273. ok(
  6274. <<'EOM'
  6275. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6276. From:<tartanpion@machin.truc>
  6277. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6278. Bye.
  6279. EOM
  6280. eq regexmess(
  6281. <<'EOM'
  6282. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6283. From:<tartanpion@machin.truc>
  6284. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6285. Bye.
  6286. EOM
  6287. ),
  6288. 'regexmess: 5 Delete header Disposition-Notification-To:');
  6289. ok(
  6290. <<'EOM'
  6291. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6292. From:<tartanpion@machin.truc>
  6293. Hello,
  6294. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6295. Bye.
  6296. EOM
  6297. eq regexmess(
  6298. <<'EOM'
  6299. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6300. From:<tartanpion@machin.truc>
  6301. Hello,
  6302. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6303. Bye.
  6304. EOM
  6305. ),
  6306. 'regexmess: 6 Delete header Disposition-Notification-To:');
  6307. ok(
  6308. <<'EOM'
  6309. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6310. From:<tartanpion@machin.truc>
  6311. Hello,
  6312. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6313. Bye.
  6314. EOM
  6315. eq regexmess(
  6316. <<'EOM'
  6317. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6318. From:<tartanpion@machin.truc>
  6319. Hello,
  6320. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6321. Bye.
  6322. EOM
  6323. ),
  6324. 'regexmess: 7 Delete header Disposition-Notification-To:');
  6325. ok(
  6326. <<'EOM'
  6327. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6328. From:<tartanpion@machin.truc>
  6329. Hello,
  6330. Bye.
  6331. EOM
  6332. eq regexmess(
  6333. <<'EOM'
  6334. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6335. From:<tartanpion@machin.truc>
  6336. Hello,
  6337. Bye.
  6338. EOM
  6339. ),
  6340. 'regexmess: 8 Delete header Disposition-Notification-To:');
  6341. ok(
  6342. <<'EOM'
  6343. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6344. From:<tartanpion@machin.truc>
  6345. Hello,
  6346. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6347. Bye.
  6348. EOM
  6349. eq regexmess(
  6350. <<'EOM'
  6351. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6352. From:<tartanpion@machin.truc>
  6353. Hello,
  6354. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6355. Bye.
  6356. EOM
  6357. ),
  6358. 'regexmess: 9 Delete header Disposition-Notification-To:');
  6359. ok(
  6360. <<'EOM'
  6361. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6362. From:<tartanpion@machin.truc>
  6363. Hello,
  6364. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6365. Bye.
  6366. EOM
  6367. eq regexmess(
  6368. <<'EOM'
  6369. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6370. From:<tartanpion@machin.truc>
  6371. Hello,
  6372. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6373. Bye.
  6374. EOM
  6375. ),
  6376. 'regexmess: 10 Delete header Disposition-Notification-To:');
  6377. ok(
  6378. <<'EOM'
  6379. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6380. From:<tartanpion@machin.truc>
  6381. Hello,
  6382. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6383. Bye.
  6384. EOM
  6385. eq regexmess(
  6386. <<'EOM'
  6387. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6388. From:<tartanpion@machin.truc>
  6389. Hello,
  6390. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6391. Bye.
  6392. EOM
  6393. ),
  6394. 'regexmess: 11 Delete header Disposition-Notification-To:');
  6395. ok(
  6396. <<'EOM'
  6397. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6398. From:<tartanpion@machin.truc>
  6399. Hello,
  6400. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6401. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6402. Bye.
  6403. EOM
  6404. eq regexmess(
  6405. <<'EOM'
  6406. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6407. From:<tartanpion@machin.truc>
  6408. Hello,
  6409. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6410. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6411. Bye.
  6412. EOM
  6413. ),
  6414. 'regexmess: 12 Delete header Disposition-Notification-To:');
  6415. @regexmess = ( 's{\A(.*?(?! ^$))^Disposition-Notification-To:(.*?)$}{$1X-Disposition-Notification-To:$2}igxms' ) ; # BAD!
  6416. @regexmess = ( 's{\A((?:[^\n]+\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims' ) ;
  6417. ok(
  6418. <<'EOM'
  6419. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6420. From:<tartanpion@machin.truc>
  6421. Hello,
  6422. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6423. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6424. Bye.
  6425. EOM
  6426. eq regexmess(
  6427. <<'EOM'
  6428. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6429. From:<tartanpion@machin.truc>
  6430. Hello,
  6431. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6432. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6433. Bye.
  6434. EOM
  6435. ),
  6436. 'regexmess: 13 Delete header Disposition-Notification-To:');
  6437. ok(
  6438. <<'EOM'
  6439. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6440. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6441. From:<tartanpion@machin.truc>
  6442. Hello,
  6443. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6444. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6445. Bye.
  6446. EOM
  6447. eq regexmess(
  6448. <<'EOM'
  6449. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6450. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6451. From:<tartanpion@machin.truc>
  6452. Hello,
  6453. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6454. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6455. Bye.
  6456. EOM
  6457. ),
  6458. 'regexmess: 14 Delete header Disposition-Notification-To:');
  6459. ok(
  6460. <<'EOM'
  6461. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6462. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6463. From:<tartanpion@machin.truc>
  6464. Hello,
  6465. Bye.
  6466. EOM
  6467. eq regexmess(
  6468. <<'EOM'
  6469. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6470. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6471. From:<tartanpion@machin.truc>
  6472. Hello,
  6473. Bye.
  6474. EOM
  6475. ),
  6476. 'regexmess: 15 Delete header Disposition-Notification-To:');
  6477. ok(
  6478. <<'EOM'
  6479. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6480. From:<tartanpion@machin.truc>
  6481. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6482. Hello,
  6483. Bye.
  6484. EOM
  6485. eq regexmess(
  6486. <<'EOM'
  6487. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6488. From:<tartanpion@machin.truc>
  6489. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6490. Hello,
  6491. Bye.
  6492. EOM
  6493. ),
  6494. 'regexmess: 16 Delete header Disposition-Notification-To:');
  6495. ok(
  6496. <<'EOM'
  6497. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6498. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6499. From:<tartanpion@machin.truc>
  6500. Hello,
  6501. Bye.
  6502. EOM
  6503. eq regexmess(
  6504. <<'EOM'
  6505. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  6506. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6507. From:<tartanpion@machin.truc>
  6508. Hello,
  6509. Bye.
  6510. EOM
  6511. ),
  6512. 'regexmess: 17 Delete header Disposition-Notification-To:');
  6513. # regex to play with Date: from the FAQ
  6514. #@regexmess = 's{\A(.*?(?! ^$))^Date:(.*?)$}{$1Date:$2\nX-Date:$2}gxms'
  6515. note( 'Leaving tests_regexmess()' ) ;
  6516. return ;
  6517. }
  6518. sub regexmess {
  6519. my ( $string ) = @_ ;
  6520. foreach my $regexmess ( @regexmess ) {
  6521. $debug and myprint( "eval \$string =~ $regexmess\n" ) ;
  6522. my $ret = eval "\$string =~ $regexmess ; 1" ;
  6523. #myprint( "eval [$ret]\n" ) ;
  6524. if ( ( not $ret ) or $EVAL_ERROR ) {
  6525. myprint( "Error: eval regexmess '$regexmess': $EVAL_ERROR" ) ;
  6526. return( undef ) ;
  6527. }
  6528. }
  6529. $debug and myprint( "$string\n" ) ;
  6530. return( $string ) ;
  6531. }
  6532. sub tests_skipmess {
  6533. note( 'Entering tests_skipmess()' ) ;
  6534. ok( not( defined skipmess( 'blabla' ) ), 'skipmess, no skipmess, no skip' ) ;
  6535. @skipmess = ('[') ;
  6536. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex [' ) ;
  6537. @skipmess = ('lalala') ;
  6538. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex lalala' ) ;
  6539. @skipmess = ('/popopo/') ;
  6540. ok( 1 == skipmess( 'popopo' ), 'skipmess, popopo match regex /popopo/' ) ;
  6541. @skipmess = ('/popopo/') ;
  6542. ok( 0 == skipmess( 'rrrrrr' ), 'skipmess, rrrrrr does not match regex /popopo/' ) ;
  6543. @skipmess = ('m{^$}') ;
  6544. ok( 1 == skipmess( q{} ), 'skipmess: empty string yes' ) ;
  6545. ok( 0 == skipmess( 'Hi!' ), 'skipmess: empty string no' ) ;
  6546. @skipmess = ('m{i}') ;
  6547. ok( 1 == skipmess( 'Hi!' ), 'skipmess: i string yes' ) ;
  6548. ok( 0 == skipmess( 'Bye!' ), 'skipmess: i string no' ) ;
  6549. @skipmess = ('m{[\x80-\xff]}') ;
  6550. ok( 0 == skipmess( 'Hi!' ), 'skipmess: i 8bit no' ) ;
  6551. ok( 1 == skipmess( "\xff" ), 'skipmess: \xff 8bit yes' ) ;
  6552. @skipmess = ('m{A}', 'm{B}') ;
  6553. ok( 0 == skipmess( 'Hi!' ), 'skipmess: A or B no' ) ;
  6554. ok( 0 == skipmess( 'lala' ), 'skipmess: A or B no' ) ;
  6555. ok( 0 == skipmess( "\xff" ), 'skipmess: A or B no' ) ;
  6556. ok( 1 == skipmess( 'AB' ), 'skipmess: A or B yes' ) ;
  6557. ok( 1 == skipmess( 'BA' ), 'skipmess: A or B yes' ) ;
  6558. ok( 1 == skipmess( 'AA' ), 'skipmess: A or B yes' ) ;
  6559. ok( 1 == skipmess( 'Ok Bye' ), 'skipmess: A or B yes' ) ;
  6560. @skipmess = ( 'm#\A((?:[^\n]+\n)+|)^Content-Type: Message/Partial;[^\n]*\n(?:\n|.*\n\n)#ism' ) ; # SUPER BEST!
  6561. ok( 1 == skipmess(
  6562. <<'EOM'
  6563. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6564. Content-Type: Message/Partial; blabla
  6565. From:<tartanpion@machin.truc>
  6566. Hello!
  6567. Bye.
  6568. EOM
  6569. ),
  6570. 'skipmess: 1 match Content-Type: Message/Partial' ) ;
  6571. ok( 0 == skipmess(
  6572. <<'EOM'
  6573. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6574. From:<tartanpion@machin.truc>
  6575. Hello!
  6576. Bye.
  6577. EOM
  6578. ),
  6579. 'skipmess: 2 not match Content-Type: Message/Partial' ) ;
  6580. ok( 1 == skipmess(
  6581. <<'EOM'
  6582. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6583. From:<tartanpion@machin.truc>
  6584. Content-Type: Message/Partial; blabla
  6585. Hello!
  6586. Bye.
  6587. EOM
  6588. ),
  6589. 'skipmess: 3 match Content-Type: Message/Partial' ) ;
  6590. ok( 0 == skipmess(
  6591. <<'EOM'
  6592. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6593. From:<tartanpion@machin.truc>
  6594. Hello!
  6595. Content-Type: Message/Partial; blabla
  6596. Bye.
  6597. EOM
  6598. ),
  6599. 'skipmess: 4 not match Content-Type: Message/Partial' ) ;
  6600. ok( 0 == skipmess(
  6601. <<'EOM'
  6602. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6603. From:<tartanpion@machin.truc>
  6604. Hello!
  6605. Content-Type: Message/Partial; blabla
  6606. Bye.
  6607. EOM
  6608. ),
  6609. 'skipmess: 5 not match Content-Type: Message/Partial' ) ;
  6610. ok( 1 == skipmess(
  6611. <<'EOM'
  6612. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6613. Content-Type: Message/Partial; blabla
  6614. From:<tartanpion@machin.truc>
  6615. Hello!
  6616. Content-Type: Message/Partial; blabla
  6617. Bye.
  6618. EOM
  6619. ),
  6620. 'skipmess: 6 match Content-Type: Message/Partial' ) ;
  6621. ok( 1 == skipmess(
  6622. <<'EOM'
  6623. Date: Sat, 10 Jul 2010 05:34:45 -0700
  6624. Content-Type: Message/Partial;
  6625. From:<tartanpion@machin.truc>
  6626. Hello!
  6627. Bye.
  6628. EOM
  6629. ),
  6630. 'skipmess: 7 match Content-Type: Message/Partial' ) ;
  6631. ok( 1 == skipmess(
  6632. <<'EOM'
  6633. Date: Wed, 2 Jul 2014 02:26:40 +0000
  6634. MIME-Version: 1.0
  6635. Content-Type: message/partial;
  6636. id="TAN_U_P<1404267997.00007489ed17>";
  6637. number=3;
  6638. total=3
  6639. 6HQ6Hh3CdXj77qEGixerQ6zHx0OnQ/Cf5On4W0Y6vtU2crABZQtD46Hx1EOh8dDz4+OnTr1G
  6640. Hello!
  6641. Bye.
  6642. EOM
  6643. ),
  6644. 'skipmess: 8 match Content-Type: Message/Partial' ) ;
  6645. ok( 1 == skipmess(
  6646. <<'EOM'
  6647. Return-Path: <gilles@lamiral.info>
  6648. Received: by lamiral.info (Postfix, from userid 1000)
  6649. id 21EB12443BF; Mon, 2 Mar 2015 15:38:35 +0100 (CET)
  6650. Subject: test: aethaecohngiexao
  6651. To: <tata@petite.lamiral.info>
  6652. X-Mailer: mail (GNU Mailutils 2.2)
  6653. Message-Id: <20150302143835.21EB12443BF@lamiral.info>
  6654. Content-Type: message/partial;
  6655. id="TAN_U_P<1404267997.00007489ed17>";
  6656. number=3;
  6657. total=3
  6658. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  6659. From: gilles@lamiral.info (Gilles LAMIRAL)
  6660. test: aethaecohngiexao
  6661. EOM
  6662. ),
  6663. 'skipmess: 9 match Content-Type: Message/Partial' ) ;
  6664. ok( 1 == skipmess(
  6665. <<'EOM'
  6666. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  6667. From: gilles@lamiral.info (Gilles LAMIRAL)
  6668. Content-Type: message/partial;
  6669. id="TAN_U_P<1404267997.00007489ed17>";
  6670. number=3;
  6671. total=3
  6672. test: aethaecohngiexao
  6673. EOM
  6674. . "lalala\n" x 3_000_000
  6675. ),
  6676. 'skipmess: 10 match Content-Type: Message/Partial' ) ;
  6677. ok( 0 == skipmess(
  6678. <<'EOM'
  6679. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  6680. From: gilles@lamiral.info (Gilles LAMIRAL)
  6681. test: aethaecohngiexao
  6682. EOM
  6683. . "lalala\n" x 3_000_000
  6684. ),
  6685. 'skipmess: 11 match Content-Type: Message/Partial' ) ;
  6686. ok( 0 == skipmess(
  6687. <<"EOM"
  6688. From: fff\r
  6689. To: fff\r
  6690. Subject: Testing imapsync --skipmess\r
  6691. Date: Mon, 22 Aug 2011 08:40:20 +0800\r
  6692. Mime-Version: 1.0\r
  6693. Content-Type: text/plain; charset=iso-8859-1\r
  6694. Content-Transfer-Encoding: 7bit\r
  6695. \r
  6696. EOM
  6697. . qq{!#"d%&'()*+,-./0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg\r\n } x 32_730
  6698. ),
  6699. 'skipmess: 12 not match Content-Type: Message/Partial' ) ;
  6700. # Complex regular subexpression recursion limit (32766) exceeded with more lines
  6701. # exit;
  6702. note( 'Leaving tests_skipmess()' ) ;
  6703. return ;
  6704. }
  6705. sub skipmess {
  6706. my ( $string ) = @_ ;
  6707. my $match ;
  6708. #myprint( "$string\n" ) ;
  6709. foreach my $skipmess ( @skipmess ) {
  6710. $debug and myprint( "eval \$match = \$string =~ $skipmess\n" ) ;
  6711. my $ret = eval "\$match = \$string =~ $skipmess ; 1" ;
  6712. #myprint( "eval [$ret]\n" ) ;
  6713. $debug and myprint( "match [$match]\n" ) ;
  6714. if ( ( not $ret ) or $EVAL_ERROR ) {
  6715. myprint( "Error: eval skipmess '$skipmess': $EVAL_ERROR" ) ;
  6716. return( undef ) ;
  6717. }
  6718. return( $match ) if ( $match ) ;
  6719. }
  6720. return( $match ) ;
  6721. }
  6722. sub tests_bytes_display_string {
  6723. note( 'Entering tests_bytes_display_string()' ) ;
  6724. is( 'NA', bytes_display_string( ), 'bytes_display_string: no args => NA' ) ;
  6725. is( 'NA', bytes_display_string( undef ), 'bytes_display_string: undef => NA' ) ;
  6726. is( 'NA', bytes_display_string( 'blabla' ), 'bytes_display_string: blabla => NA' ) ;
  6727. ok( '0.000 KiB' eq bytes_display_string( 0 ), 'bytes_display_string: 0' ) ;
  6728. ok( '0.001 KiB' eq bytes_display_string( 1 ), 'bytes_display_string: 1' ) ;
  6729. ok( '0.010 KiB' eq bytes_display_string( 10 ), 'bytes_display_string: 10' ) ;
  6730. ok( '1.000 MiB' eq bytes_display_string( 1_048_575 ), 'bytes_display_string: 1_048_575' ) ;
  6731. ok( '1.000 MiB' eq bytes_display_string( 1_048_576 ), 'bytes_display_string: 1_048_576' ) ;
  6732. ok( '1.000 GiB' eq bytes_display_string( 1_073_741_823 ), 'bytes_display_string: 1_073_741_823 ' ) ;
  6733. ok( '1.000 GiB' eq bytes_display_string( 1_073_741_824 ), 'bytes_display_string: 1_073_741_824 ' ) ;
  6734. ok( '1.000 TiB' eq bytes_display_string( 1_099_511_627_775 ), 'bytes_display_string: 1_099_511_627_775' ) ;
  6735. ok( '1.000 TiB' eq bytes_display_string( 1_099_511_627_776 ), 'bytes_display_string: 1_099_511_627_776' ) ;
  6736. ok( '1.000 PiB' eq bytes_display_string( 1_125_899_906_842_623 ), 'bytes_display_string: 1_125_899_906_842_623' ) ;
  6737. ok( '1.000 PiB' eq bytes_display_string( 1_125_899_906_842_624 ), 'bytes_display_string: 1_125_899_906_842_624' ) ;
  6738. ok( '1024.000 PiB' eq bytes_display_string( 1_152_921_504_606_846_975 ), 'bytes_display_string: 1_152_921_504_606_846_975' ) ;
  6739. ok( '1024.000 PiB' eq bytes_display_string( 1_152_921_504_606_846_976 ), 'bytes_display_string: 1_152_921_504_606_846_976' ) ;
  6740. ok( '1048576.000 PiB' eq bytes_display_string( 1_180_591_620_717_411_303_424 ), 'bytes_display_string: 1_180_591_620_717_411_303_424' ) ;
  6741. #myprint( bytes_display_string( 1_180_591_620_717_411_303_424 ), "\n" ) ;
  6742. note( 'Leaving tests_bytes_display_string()' ) ;
  6743. return ;
  6744. }
  6745. sub bytes_display_string {
  6746. my ( $bytes ) = @_ ;
  6747. my $readable_value = q{} ;
  6748. if ( ! defined( $bytes ) ) {
  6749. return( 'NA' ) ;
  6750. }
  6751. if ( not match_number( $bytes ) ) {
  6752. return( 'NA' ) ;
  6753. }
  6754. SWITCH: {
  6755. if ( abs( $bytes ) < ( 1000 * $KIBI ) ) {
  6756. $readable_value = mysprintf( '%.3f KiB', $bytes / $KIBI) ;
  6757. last SWITCH ;
  6758. }
  6759. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI ) ) {
  6760. $readable_value = mysprintf( '%.3f MiB', $bytes / ($KIBI * $KIBI) ) ;
  6761. last SWITCH ;
  6762. }
  6763. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI) ) {
  6764. $readable_value = mysprintf( '%.3f GiB', $bytes / ($KIBI * $KIBI * $KIBI) ) ;
  6765. last SWITCH ;
  6766. }
  6767. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI * $KIBI) ) {
  6768. $readable_value = mysprintf( '%.3f TiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI) ) ;
  6769. last SWITCH ;
  6770. } else {
  6771. $readable_value = mysprintf( '%.3f PiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI * $KIBI) ) ;
  6772. }
  6773. # if you have exabytes (EiB) of email to transfer, you have too much email!
  6774. }
  6775. #myprint( "$bytes = $readable_value\n" ) ;
  6776. return( $readable_value ) ;
  6777. }
  6778. sub stats {
  6779. my $mysync = shift ;
  6780. if ( ! $mysync->{stats} ) {
  6781. return ;
  6782. }
  6783. my $timeend = time ;
  6784. my $timediff = $timeend - $mysync->{timestart} ;
  6785. my $timeend_str = localtime $timeend ;
  6786. my $memory_consumption_at_end = memory_consumption( ) || 0 ;
  6787. my $memory_consumption_at_start = $mysync->{ memory_consumption_at_start } || 0 ;
  6788. my $memory_ratio = ($max_msg_size_in_bytes) ?
  6789. mysprintf('%.1f', $memory_consumption_at_end / $max_msg_size_in_bytes) : 'NA' ;
  6790. myprint( "++++ Statistics\n" ) ;
  6791. myprint( "Transfer started on : $timestart_str\n" ) ;
  6792. myprint( "Transfer ended on : $timeend_str\n" ) ;
  6793. myprintf( "Transfer time : %.1f sec\n", $timediff ) ;
  6794. myprint( "Folders synced : $h1_folders_wanted_ct/$h1_folders_wanted_nb synced\n" ) ;
  6795. myprint( "Messages transferred : $mysync->{nb_msg_transferred} " ) ;
  6796. myprint( "(could be $nb_msg_skipped_dry_mode without dry mode)" ) if ( $mysync->{dry} ) ;
  6797. myprint( "\n" ) ;
  6798. myprint( "Messages skipped : $nb_msg_skipped\n" ) ;
  6799. myprint( "Messages found duplicate on host1 : $h1_nb_msg_duplicate\n" ) ;
  6800. myprint( "Messages found duplicate on host2 : $h2_nb_msg_duplicate\n" ) ;
  6801. myprint( "Messages void (noheader) on host1 : $h1_nb_msg_noheader\n" ) ;
  6802. myprint( "Messages void (noheader) on host2 : $h2_nb_msg_noheader\n" ) ;
  6803. myprint( "Messages deleted on host1 : $h1_nb_msg_deleted\n" ) ;
  6804. myprint( "Messages deleted on host2 : $h2_nb_msg_deleted\n" ) ;
  6805. myprintf( "Total bytes transferred : %s (%s)\n",
  6806. $mysync->{total_bytes_transferred},
  6807. bytes_display_string( $mysync->{total_bytes_transferred} ) ) ;
  6808. myprintf( "Total bytes duplicate host1 : %s (%s)\n",
  6809. $h1_total_bytes_duplicate,
  6810. bytes_display_string( $h1_total_bytes_duplicate) ) ;
  6811. myprintf( "Total bytes duplicate host2 : %s (%s)\n",
  6812. $h2_total_bytes_duplicate,
  6813. bytes_display_string( $h2_total_bytes_duplicate) ) ;
  6814. myprintf( "Total bytes skipped : %s (%s)\n",
  6815. $total_bytes_skipped,
  6816. bytes_display_string( $total_bytes_skipped ) ) ;
  6817. myprintf( "Total bytes error : %s (%s)\n",
  6818. $total_bytes_error,
  6819. bytes_display_string( $total_bytes_error ) ) ;
  6820. $timediff ||= 1 ; # No division per 0
  6821. myprintf("Message rate : %.1f messages/s\n", $mysync->{nb_msg_transferred} / $timediff ) ;
  6822. myprintf("Average bandwidth rate : %.1f KiB/s\n", $mysync->{total_bytes_transferred} / $KIBI / $timediff ) ;
  6823. myprint( "Reconnections to host1 : $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT}\n" ) ;
  6824. myprint( "Reconnections to host2 : $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT}\n" ) ;
  6825. myprintf("Memory consumption at the end : %.1f MiB (started with %.1f MiB)\n",
  6826. $memory_consumption_at_end / $KIBI / $KIBI,
  6827. $memory_consumption_at_start / $KIBI / $KIBI ) ;
  6828. myprintf("Biggest message : %s bytes (%s)\n",
  6829. $max_msg_size_in_bytes,
  6830. bytes_display_string( $max_msg_size_in_bytes) ) ;
  6831. myprint( "Memory/biggest message ratio : $memory_ratio\n" ) ;
  6832. if ( $foldersizesatend and $foldersizes ) {
  6833. my $nb_msg_start_diff = diff_or_NA( $h2_nb_msg_start, $h1_nb_msg_start ) ;
  6834. my $bytes_start_diff = diff_or_NA( $h2_bytes_start, $h1_bytes_start ) ;
  6835. myprintf("Start difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_start_diff,
  6836. $bytes_start_diff,
  6837. bytes_display_string( $bytes_start_diff ) ) ;
  6838. my $nb_msg_end_diff = diff_or_NA( $h2_nb_msg_end, $h1_nb_msg_end ) ;
  6839. my $bytes_end_diff = diff_or_NA( $h2_bytes_end, $h1_bytes_end ) ;
  6840. myprintf("Final difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_end_diff,
  6841. $bytes_end_diff,
  6842. bytes_display_string( $bytes_end_diff ) ) ;
  6843. }
  6844. myprint( "Detected $mysync->{nb_errors} errors\n\n" ) ;
  6845. myprint( $warn_release, "\n" ) ;
  6846. myprint( homepage( ), "\n" ) ;
  6847. return ;
  6848. }
  6849. sub diff_or_NA {
  6850. my( $n1, $n2 ) = @ARG ;
  6851. if ( not defined $n1 or not defined $n2 ) {
  6852. return 'NA' ;
  6853. }
  6854. if ( not match_number( $n1 )
  6855. or not match_number( $n2 ) ) {
  6856. return 'NA' ;
  6857. }
  6858. return( $n1 - $n2 ) ;
  6859. }
  6860. sub match_number {
  6861. my $n = shift @ARG ;
  6862. if ( not defined $n ) {
  6863. return 0 ;
  6864. }
  6865. if ( $n =~ /[0-9]+\.?[0-9]?/x ) {
  6866. return 1 ;
  6867. }
  6868. else {
  6869. return 0 ;
  6870. }
  6871. }
  6872. sub tests_match_number {
  6873. note( 'Entering tests_match_number()' ) ;
  6874. is( 0, match_number( ), 'match_number: no parameters => 0' ) ;
  6875. is( 0, match_number( undef ), 'match_number: undef => 0' ) ;
  6876. is( 0, match_number( 'blabla' ), 'match_number: blabla => 0' ) ;
  6877. is( 1, match_number( 0 ), 'match_number: 0 => 1' ) ;
  6878. is( 1, match_number( 1 ), 'match_number: 1 => 1' ) ;
  6879. is( 1, match_number( 1.0 ), 'match_number: 1.0 => 1' ) ;
  6880. is( 1, match_number( 0.0 ), 'match_number: 0.0 => 1' ) ;
  6881. note( 'Leaving tests_match_number()' ) ;
  6882. return ;
  6883. }
  6884. sub tests_diff_or_NA {
  6885. note( 'Entering tests_diff_or_NA()' ) ;
  6886. is( 'NA', diff_or_NA( ), 'diff_or_NA: no parameters => NA' ) ;
  6887. is( 'NA', diff_or_NA( undef ), 'diff_or_NA: undef => NA' ) ;
  6888. is( 'NA', diff_or_NA( undef, undef ), 'diff_or_NA: undef undef => NA' ) ;
  6889. is( 'NA', diff_or_NA( undef, 1 ), 'diff_or_NA: undef 1 => NA' ) ;
  6890. is( 'NA', diff_or_NA( 1, undef ), 'diff_or_NA: 1 undef => NA' ) ;
  6891. is( 'NA', diff_or_NA( 'blabla', 1 ), 'diff_or_NA: blabla 1 => NA' ) ;
  6892. is( 'NA', diff_or_NA( 1, 'blabla' ), 'diff_or_NA: 1 blabla => NA' ) ;
  6893. is( 0, diff_or_NA( 1, 1 ), 'diff_or_NA: 1 1 => 0' ) ;
  6894. is( 1, diff_or_NA( 1, 0 ), 'diff_or_NA: 1 0 => 1' ) ;
  6895. is( -1, diff_or_NA( 0, 1 ), 'diff_or_NA: 0 1 => -1' ) ;
  6896. is( 0, diff_or_NA( 1.0, 1 ), 'diff_or_NA: 1.0 1 => 0' ) ;
  6897. is( 1, diff_or_NA( 1.0, 0 ), 'diff_or_NA: 1.0 0 => 1' ) ;
  6898. is( -1, diff_or_NA( 0, 1.0 ), 'diff_or_NA: 0 1.0 => -1' ) ;
  6899. note( 'Leaving tests_diff_or_NA()' ) ;
  6900. return ;
  6901. }
  6902. sub homepage {
  6903. return( 'Homepage: https://imapsync.lamiral.info/' ) ;
  6904. }
  6905. sub load_modules {
  6906. if ( $sync->{ssl1}
  6907. or $sync->{ssl2}
  6908. or $sync->{tls1}
  6909. or $sync->{tls2}) {
  6910. if ( $sync->{inet4} ) {
  6911. IO::Socket::SSL->import( 'inet4' ) ;
  6912. }
  6913. if ( $sync->{inet6} ) {
  6914. IO::Socket::SSL->import( 'inet6' ) ;
  6915. }
  6916. }
  6917. return ;
  6918. }
  6919. sub parse_header_msg {
  6920. my ( $mysync, $imap, $m_uid, $s_heads, $s_fir, $side, $s_hash ) = @_ ;
  6921. my $head = $s_heads->{$m_uid} ;
  6922. my $headnum = scalar keys %{ $head } ;
  6923. $debug and myprint( "$side uid $m_uid head nb pass one: ", $headnum, "\n" ) ;
  6924. if ( ( ! $headnum ) and ( $wholeheaderifneeded ) ){
  6925. myprint( "$side uid $m_uid no header by parse_headers so taking whole header with BODY.PEEK[HEADER]\n" ) ;
  6926. $imap->fetch($m_uid, 'BODY.PEEK[HEADER]' ) ;
  6927. my $whole_header = $imap->_transaction_literals ;
  6928. #myprint( $whole_header ) ;
  6929. $head = decompose_header( $whole_header ) ;
  6930. $headnum = scalar keys %{ $head } ;
  6931. $debug and myprint( "$side uid $m_uid head nb pass two: ", $headnum, "\n" ) ;
  6932. }
  6933. #myprint( Data::Dumper->Dump( [ $head, \%useheader ] ) ) ;
  6934. my $headstr ;
  6935. $headstr = header_construct( $head, $side, $m_uid ) ;
  6936. if ( ( ! $headstr ) and ( $mysync->{addheader} ) and ( $side eq 'Host1' ) ) {
  6937. my $header = add_header( $m_uid ) ;
  6938. myprint( "Host1 uid $m_uid no header found so adding our own [$header]\n" ) ;
  6939. $headstr .= uc $header ;
  6940. $s_fir->{$m_uid}->{NO_HEADER} = 1;
  6941. }
  6942. return if ( ! $headstr ) ;
  6943. my $size = $s_fir->{$m_uid}->{'RFC822.SIZE'} ;
  6944. my $flags = $s_fir->{$m_uid}->{'FLAGS'} ;
  6945. my $idate = $s_fir->{$m_uid}->{'INTERNALDATE'} ;
  6946. $size = length $headstr unless ( $size ) ;
  6947. my $m_md5 = md5_base64( $headstr ) ;
  6948. $debug and myprint( "$side uid $m_uid sig $m_md5 size $size idate $idate\n" ) ;
  6949. my $key ;
  6950. if ($skipsize) {
  6951. $key = "$m_md5";
  6952. }
  6953. else {
  6954. $key = "$m_md5:$size";
  6955. }
  6956. # 0 return code is used to identify duplicate message hash
  6957. return 0 if exists $s_hash->{"$key"};
  6958. $s_hash->{"$key"}{'5'} = $m_md5;
  6959. $s_hash->{"$key"}{'s'} = $size;
  6960. $s_hash->{"$key"}{'D'} = $idate;
  6961. $s_hash->{"$key"}{'F'} = $flags;
  6962. $s_hash->{"$key"}{'m'} = $m_uid;
  6963. return( 1 ) ;
  6964. }
  6965. sub header_construct {
  6966. my( $head, $side, $m_uid ) = @_ ;
  6967. my $headstr ;
  6968. foreach my $h ( sort keys %{ $head } ) {
  6969. next if ( not ( exists $useheader{ uc $h } )
  6970. and ( not exists $useheader{ 'ALL' } )
  6971. ) ;
  6972. foreach my $val ( sort @{$head->{$h}} ) {
  6973. my $H = header_line_normalize( $h, $val ) ;
  6974. # show stuff in debug mode
  6975. $debug and myprint( "$side uid $m_uid header [$H]", "\n" ) ;
  6976. if ($skipheader and $H =~ m/$skipheader/xi) {
  6977. $debug and myprint( "$side uid $m_uid skipping header [$H]\n" ) ;
  6978. next ;
  6979. }
  6980. $headstr .= "$H" ;
  6981. }
  6982. }
  6983. return( $headstr ) ;
  6984. }
  6985. sub header_line_normalize {
  6986. my( $header_key, $header_val ) = @_ ;
  6987. # no 8-bit data in headers !
  6988. $header_val =~ s/[\x80-\xff]/X/xog;
  6989. # change tabulations to space (Gmail bug on with "Received:" on multilines)
  6990. $header_val =~ s/\t/\ /xgo ;
  6991. # remove the first blanks ( dbmail bug? )
  6992. $header_val =~ s/^\s*//xo;
  6993. # remove the last blanks ( Gmail bug )
  6994. $header_val =~ s/\s*$//xo;
  6995. # remove successive blanks ( Mailenable does it )
  6996. $header_val =~ s/\s+/ /xgo;
  6997. # remove Message-Id value domain part ( Mailenable changes it )
  6998. if ( ( $messageidnodomain ) and ( 'MESSAGE-ID' eq uc $header_key ) ) { $header_val =~ s/^([^@]+).*$/$1/xo ; }
  6999. # and uppercase header line
  7000. # (dbmail and dovecot)
  7001. my $header_line = uc "$header_key: $header_val" ;
  7002. return( $header_line ) ;
  7003. }
  7004. sub tests_header_line_normalize {
  7005. note( 'Entering tests_header_line_normalize()' ) ;
  7006. ok( ': ' eq header_line_normalize( q{}, q{} ), 'header_line_normalize: empty args' ) ;
  7007. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', 'vvv' ), 'header_line_normalize: hhh vvv ' ) ;
  7008. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', ' vvv' ), 'header_line_normalize: remove first blancs' ) ;
  7009. ok( 'HHH: AA BB CCC D' eq header_line_normalize( 'hhh', 'aa bb ccc d' ), 'header_line_normalize: remove succesive blanks' ) ;
  7010. ok( 'HHH: AA BB CCC' eq header_line_normalize( 'hhh', 'aa bb ccc ' ), 'header_line_normalize: remove last blanks' ) ;
  7011. ok( 'HHH: VVV XX YY' eq header_line_normalize( 'hhh', "vvv\t\txx\tyy" ), 'header_line_normalize: tabs' ) ;
  7012. ok( 'HHH: XABX' eq header_line_normalize( 'hhh', "\x80AB\xff" ), 'header_line_normalize: 8bit' ) ;
  7013. note( 'Leaving tests_header_line_normalize()' ) ;
  7014. return ;
  7015. }
  7016. sub firstline {
  7017. # extract the first line of a file (without \n)
  7018. my( $file ) = @_ ;
  7019. my $line = q{} ;
  7020. if ( ! -e $file ) {
  7021. myprint( "Cannot open file $file since it does not exist\n" ) ;
  7022. return ;
  7023. }
  7024. open my $FILE, '<', $file or do {
  7025. myprint( "Error opening file $file : $OS_ERROR\n" ) ;
  7026. return ;
  7027. } ;
  7028. $line = <$FILE> || q{} ;
  7029. close $FILE ;
  7030. chomp $line ;
  7031. return $line ;
  7032. }
  7033. sub tests_firstline {
  7034. note( 'Entering tests_firstline()' ) ;
  7035. is( undef , firstline( 'W/tmp/tests/noexist.txt' ), 'tests_firstline: not getting blabla from W/tmp/tests/noexist.txt' ) ;
  7036. is( "blabla\n" , string_to_file( "blabla\n", 'W/tmp/tests/firstline.txt' ), 'tests_firstline: put blabla in W/tmp/tests/firstline.txt' ) ;
  7037. is( 'blabla' , firstline( 'W/tmp/tests/firstline.txt' ), 'tests_firstline: get blabla from W/tmp/tests/firstline.txt' ) ;
  7038. is( q{} , string_to_file( q{}, 'W/tmp/tests/firstline2.txt' ), 'tests_firstline: put empty string in W/tmp/tests/firstline2.txt' ) ;
  7039. is( q{} , firstline( 'W/tmp/tests/firstline2.txt' ), 'tests_firstline: get empty string from W/tmp/tests/firstline2.txt' ) ;
  7040. is( "\n" , string_to_file( "\n", 'W/tmp/tests/firstline3.txt' ), 'tests_firstline: put CR in W/tmp/tests/firstline3.txt' ) ;
  7041. is( q{} , firstline( 'W/tmp/tests/firstline3.txt' ), 'tests_firstline: get empty string from W/tmp/tests/firstline3.txt' ) ;
  7042. note( 'Leaving tests_firstline()' ) ;
  7043. return ;
  7044. }
  7045. # Should be unit tested and then be used by file_to_string, refactoring file_to_string
  7046. sub file_to_array {
  7047. my( $file ) = shift ;
  7048. my @string ;
  7049. open my $FILE, '<', $file or do {
  7050. myprint( "Error reading file $file : $OS_ERROR" ) ;
  7051. return ;
  7052. } ;
  7053. @string = <$FILE> ;
  7054. close $FILE ;
  7055. return( @string ) ;
  7056. }
  7057. sub tests_file_to_string {
  7058. note( 'Entering tests_file_to_string()' ) ;
  7059. is( undef, file_to_string( ), 'file_to_string: no args => undef' ) ;
  7060. is( undef, file_to_string( '/noexist' ), 'file_to_string: /noexist => undef' ) ;
  7061. is( undef, file_to_string( '/' ), 'file_to_string: reading a directory => undef' ) ;
  7062. ok( file_to_string( $PROGRAM_NAME ), 'file_to_string: reading myself' ) ;
  7063. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'file_to_string: mkpath W/tmp/tests/' ) ;
  7064. is( 'lilili', string_to_file( 'lilili', 'W/tmp/tests/canbewritten' ), 'file_to_string: string_to_file filling W/tmp/tests/canbewritten with lilili' ) ;
  7065. is( 'lilili', file_to_string( 'W/tmp/tests/canbewritten' ), 'file_to_string: reading W/tmp/tests/canbewritten is lilili' ) ;
  7066. is( q{}, string_to_file( q{}, 'W/tmp/tests/empty' ), 'file_to_string: string_to_file filling W/tmp/tests/empty with empty string' ) ;
  7067. is( q{}, file_to_string( 'W/tmp/tests/empty' ), 'file_to_string: reading W/tmp/tests/empty is empty' ) ;
  7068. note( 'Leaving tests_file_to_string()' ) ;
  7069. return ;
  7070. }
  7071. sub file_to_string {
  7072. my $file = shift ;
  7073. if ( ! $file ) { return ; }
  7074. if ( ! -e $file ) { return ; }
  7075. if ( ! -f $file ) { return ; }
  7076. if ( ! -r $file ) { return ; }
  7077. my @string ;
  7078. if ( open my $FILE, '<', $file ) {
  7079. @string = <$FILE> ;
  7080. close $FILE ;
  7081. return( join q{}, @string ) ;
  7082. }else{
  7083. myprint( "Error reading file $file : $OS_ERROR\n" ) ;
  7084. return ;
  7085. }
  7086. }
  7087. sub tests_string_to_file {
  7088. note( 'Entering tests_string_to_file()' ) ;
  7089. is( undef, string_to_file( ), 'string_to_file: no args => undef' ) ;
  7090. is( undef, string_to_file( 'lalala' ), 'string_to_file: one arg => undef' ) ;
  7091. is( undef, string_to_file( 'lalala', '.' ), 'string_to_file: writing a directory => undef' ) ;
  7092. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'string_to_file: mkpath W/tmp/tests/' ) ;
  7093. is( 'lalala', string_to_file( 'lalala', 'W/tmp/tests/canbewritten' ), 'string_to_file: W/tmp/tests/canbewritten with lalala' ) ;
  7094. is( q{}, string_to_file( q{}, 'W/tmp/tests/empty' ), 'string_to_file: W/tmp/tests/empty with empty string' ) ;
  7095. SKIP: {
  7096. Readonly my $NB_UNX_tests_string_to_file => 1 ;
  7097. skip( 'Not on Unix non-root', $NB_UNX_tests_string_to_file ) if ('MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) ;
  7098. is( undef, string_to_file( 'lalala', '/cantouch' ), 'string_to_file: /cantouch denied => undef' ) ;
  7099. }
  7100. note( 'Leaving tests_string_to_file()' ) ;
  7101. return ;
  7102. }
  7103. sub string_to_file {
  7104. my( $string, $file ) = @_ ;
  7105. if( ! defined $string ) { return ; }
  7106. if( ! defined $file ) { return ; }
  7107. if ( ! -e $file && ! -w dirname( $file ) ) {
  7108. myprint( "string_to_file: directory of $file is not writable\n" ) ;
  7109. return ;
  7110. }
  7111. if ( ! sysopen( FILE, $file, O_WRONLY|O_TRUNC|O_CREAT, 0600) ) {
  7112. myprint( "string_to_file: failure writing to $file with error: $OS_ERROR\n" ) ;
  7113. return ;
  7114. }
  7115. print FILE $string ;
  7116. close FILE ;
  7117. return $string ;
  7118. }
  7119. q^
  7120. This is a multiline comment.
  7121. Based on David Carter discussion, to do:
  7122. * Call parameters stay the same.
  7123. * Now always "return( $string, $error )". Descriptions below.
  7124. OK * Still capture STDOUT via "1> $output_tmpfile" to finish in $string and "return( $string, $error )"
  7125. OK * Now also capture STDERR via "2> $error_tmpfile" to finish in $error and "return( $string, $error )"
  7126. OK * in case of CHILD_ERROR, return( undef, $error )
  7127. and print $error, with folder/UID/maybeSubject context,
  7128. on console and at the end with the final error listing. Count this as a sync error.
  7129. * in case of good command, take final $string as is, unless void. In case $error with value then print it.
  7130. * in case of good command and final $string empty, consider it like CHILD_ERROR =>
  7131. return( undef, $error ) and print $error, with folder/UID/maybeSubject context,
  7132. on console and at the end with the final error listing. Count this as a sync error.
  7133. ^ if 0 ; # End of multiline comment.
  7134. sub pipemess {
  7135. my ( $string, @commands ) = @_ ;
  7136. my $error = q{} ;
  7137. foreach my $command ( @commands ) {
  7138. my $input_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.inp.txt" ;
  7139. my $output_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.out.txt" ;
  7140. my $error_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.err.txt" ;
  7141. string_to_file( $string, $input_tmpfile ) ;
  7142. ` $command < $input_tmpfile 1> $output_tmpfile 2> $error_tmpfile ` ;
  7143. my $is_command_ko = $CHILD_ERROR ;
  7144. my $error_cmd = file_to_string( $error_tmpfile ) ;
  7145. chomp( $error_cmd ) ;
  7146. $string = file_to_string( $output_tmpfile ) ;
  7147. my $string_len = length( $string ) ;
  7148. unlink $input_tmpfile, $output_tmpfile, $error_tmpfile ;
  7149. if ( $is_command_ko or ( ! $string_len ) ) {
  7150. my $cmd_exit_value = $CHILD_ERROR >> 8 ;
  7151. my $cmd_end_signal = $CHILD_ERROR & 127 ;
  7152. my $signal_log = ( $cmd_end_signal ) ? " signal $cmd_end_signal and" : q{} ;
  7153. 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} ;
  7154. myprint( $error_log ) ;
  7155. if ( wantarray ) {
  7156. return @{ [ undef, $error_log ] }
  7157. }else{
  7158. return ;
  7159. }
  7160. }
  7161. if ( $error_cmd ) {
  7162. $error .= qq{STDERR of --pipemess "$command": $error_cmd\n} ;
  7163. myprint( qq{STDERR of --pipemess "$command": $error_cmd\n} ) ;
  7164. }
  7165. }
  7166. #myprint( "[$string]\n" ) ;
  7167. if ( wantarray ) {
  7168. return ( $string, $error ) ;
  7169. }else{
  7170. return $string ;
  7171. }
  7172. }
  7173. sub tests_pipemess {
  7174. note( 'Entering tests_pipemess()' ) ;
  7175. SKIP: {
  7176. Readonly my $NB_WIN_tests_pipemess => 3 ;
  7177. skip( 'Not on MSWin32', $NB_WIN_tests_pipemess ) if ('MSWin32' ne $OSNAME) ;
  7178. # Windows
  7179. # "type" command does not accept redirection of STDIN with <
  7180. # "sort" does
  7181. ok( "nochange\n" eq pipemess( 'nochange', 'sort' ), 'pipemess: nearly no change by sort' ) ;
  7182. ok( "nochange2\n" eq pipemess( 'nochange2', qw( sort sort ) ), 'pipemess: nearly no change by sort,sort' ) ;
  7183. # command not found
  7184. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  7185. ok( ! defined( pipemess( q{}, 'cacaprout' ) ), 'pipemess: command not found' ) ;
  7186. } ;
  7187. my ( $stringT, $errorT ) ;
  7188. SKIP: {
  7189. Readonly my $NB_UNX_tests_pipemess => 25 ;
  7190. skip( 'Not on Unix', $NB_UNX_tests_pipemess ) if ('MSWin32' eq $OSNAME) ;
  7191. # Unix
  7192. ok( 'nochange' eq pipemess( 'nochange', 'cat' ), 'pipemess: no change by cat' ) ;
  7193. ok( 'nochange2' eq pipemess( 'nochange2', 'cat', 'cat' ), 'pipemess: no change by cat,cat' ) ;
  7194. ok( " 1\tnumberize\n" eq pipemess( "numberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  7195. ok( " 1\tnumberize\n 2\tnumberize\n" eq pipemess( "numberize\nnumberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  7196. ok( "A\nB\nC\n" eq pipemess( "A\nC\nB\n", 'sort' ), 'pipemess: sort' ) ;
  7197. # command not found
  7198. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  7199. is( undef, pipemess( q{}, 'cacaprout' ), 'pipemess: command not found' ) ;
  7200. # success with true but no output at all
  7201. is( undef, pipemess( q{blabla}, 'true' ), 'pipemess: true but no output' ) ;
  7202. # failure with false and no output at all
  7203. is( undef, pipemess( q{blabla}, 'false' ), 'pipemess: false and no output' ) ;
  7204. # Failure since pipemess is not a real pipe, so first cat wait for standard input
  7205. is( q{blabla}, pipemess( q{blabla}, '( cat|cat ) ' ), 'pipemess: ok by ( cat|cat )' ) ;
  7206. ( $stringT, $errorT ) = pipemess( 'nochange', 'cat' ) ;
  7207. is( $stringT, 'nochange', 'pipemess: list context, no change by cat, string' ) ;
  7208. is( $errorT, q{}, 'pipemess: list context, no change by cat, no error' ) ;
  7209. ( $stringT, $errorT ) = pipemess( 'dontcare', 'true' ) ;
  7210. is( $stringT, undef, 'pipemess: list context, true but no output, string' ) ;
  7211. like( $errorT, qr{\QFailure: --pipemess command "true" ended with "0" characters exit value "0" and STDERR ""\E}xm, 'pipemess: list context, true but no output, error' ) ;
  7212. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false' ) ;
  7213. is( $stringT, undef, 'pipemess: list context, false and no output, string' ) ;
  7214. like( $errorT, qr{\QFailure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""\E}xm,
  7215. 'pipemess: list context, false and no output, error' ) ;
  7216. ( $stringT, $errorT ) = pipemess( 'dontcare', '/bin/echo -n blablabla' ) ;
  7217. is( $stringT, q{blablabla}, 'pipemess: list context, "echo -n blablabla", string' ) ;
  7218. is( $errorT, q{}, 'pipemess: list context, "echo blablabla", error' ) ;
  7219. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  7220. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla", string' ) ;
  7221. like( $errorT, qr{blablabla"}xm, 'pipemess: list context, "no output STDERR blablabla", error' ) ;
  7222. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )', 'false' ) ;
  7223. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla then false", string' ) ;
  7224. like( $errorT, qr{blablabla"}xm, 'pipemess: list context, "no output STDERR blablabla then false", error' ) ;
  7225. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  7226. is( $stringT, undef, 'pipemess: list context, "false then STDERR blablabla", string' ) ;
  7227. like( $errorT, qr{\QFailure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""\E}xm,
  7228. 'pipemess: list context, "false then STDERR blablabla", error' ) ;
  7229. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo rrrrr ; echo -n error_blablabla 3>&1 1>&2 2>&3 )' ) ;
  7230. like( $stringT, qr{rrrrr}xm, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", string' ) ;
  7231. like( $errorT, qr{STDERR.*error_blablabla}xm, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", error' ) ;
  7232. }
  7233. ( $stringT, $errorT ) = pipemess( 'dontcare', 'cacaprout' ) ;
  7234. is( $stringT, undef, 'pipemess: list context, cacaprout not found, string' ) ;
  7235. like( $errorT, qr{\QFailure: --pipemess command "cacaprout" ended with "0" characters exit value\E}xm,
  7236. 'pipemess: list context, cacaprout not found, error' ) ;
  7237. note( 'Leaving tests_pipemess()' ) ;
  7238. return ;
  7239. }
  7240. sub tests_is_a_release_number {
  7241. note( 'Entering tests_is_a_release_number()' ) ;
  7242. is( undef, is_a_release_number( ), 'is_a_release_number: no args => undef' ) ;
  7243. ok( is_a_release_number( $RELEASE_NUMBER_EXAMPLE_1 ), 'is_a_release_number 1.351' ) ;
  7244. ok( is_a_release_number( $RELEASE_NUMBER_EXAMPLE_2 ), 'is_a_release_number 42.4242' ) ;
  7245. ok( is_a_release_number( imapsync_version( $sync ) ), 'is_a_release_number imapsync_version( )' ) ;
  7246. ok( ! is_a_release_number( 'blabla' ), '! is_a_release_number blabla' ) ;
  7247. note( 'Leaving tests_is_a_release_number()' ) ;
  7248. return ;
  7249. }
  7250. sub is_a_release_number {
  7251. my $number = shift ;
  7252. if ( ! defined $number ) { return ; }
  7253. return( $number =~ m{^\d+\.\d+$}xo ) ;
  7254. }
  7255. sub imapsync_version_public {
  7256. my $local_version = imapsync_version( $sync ) ;
  7257. my $imapsync_basename = imapsync_basename( ) ;
  7258. my $agent_info = "$OSNAME system, perl "
  7259. . mysprintf( '%vd', $PERL_VERSION)
  7260. . ", Mail::IMAPClient $Mail::IMAPClient::VERSION"
  7261. . " $imapsync_basename" ;
  7262. my $sock = IO::Socket::INET->new(
  7263. PeerAddr => 'imapsync.lamiral.info',
  7264. PeerPort => 80,
  7265. Proto => 'tcp',
  7266. ) ;
  7267. return( 'unknown' ) if not $sock ;
  7268. print $sock
  7269. "GET /prj/imapsync/VERSION HTTP/1.0\r\n",
  7270. "User-Agent: imapsync/$local_version ($agent_info)\r\n",
  7271. "Host: ks.lamiral.info\r\n\r\n" ;
  7272. my @line = <$sock> ;
  7273. close $sock ;
  7274. my $last_release = $line[$LAST] ;
  7275. chomp $last_release ;
  7276. return( $last_release ) ;
  7277. }
  7278. sub not_long_imapsync_version_public {
  7279. #myprint( "Entering not_long_imapsync_version_public\n" ) ;
  7280. my $fake = shift ;
  7281. if ( $fake ) { return $fake }
  7282. my $val ;
  7283. # Doesn't work with gethostbyname (see perlipc)
  7284. #local $SIG{ALRM} = sub { die "alarm\n" } ;
  7285. if ('MSWin32' eq $OSNAME) {
  7286. local $SIG{ALRM} = sub { die "alarm\n" } ;
  7287. }else{
  7288. POSIX::sigaction(SIGALRM,
  7289. POSIX::SigAction->new(sub { croak 'alarm' } ) )
  7290. or myprint( "Error setting SIGALRM handler: $OS_ERROR\n" ) ;
  7291. }
  7292. my $ret = eval {
  7293. alarm 3 ;
  7294. {
  7295. $val = imapsync_version_public( ) ;
  7296. #sleep 4 ;
  7297. #myprint( "End of imapsync_version_public\n" ) ;
  7298. }
  7299. alarm 0 ;
  7300. 1 ;
  7301. } ;
  7302. #myprint( "eval [$ret]\n" ) ;
  7303. if ( ( not $ret ) or $EVAL_ERROR ) {
  7304. #myprint( "$EVAL_ERROR" ) ;
  7305. if ($EVAL_ERROR =~ /alarm/) {
  7306. # timed out
  7307. return('timeout') ;
  7308. }else{
  7309. alarm 0 ;
  7310. return( 'unknown' ) ; # propagate unexpected errors
  7311. }
  7312. }else {
  7313. # Good!
  7314. return( $val ) ;
  7315. }
  7316. }
  7317. sub tests_not_long_imapsync_version_public {
  7318. note( 'Entering tests_not_long_imapsync_version_public()' ) ;
  7319. is( 1, is_a_release_number( not_long_imapsync_version_public( ) ),
  7320. 'not_long_imapsync_version_public: public release is a number' ) ;
  7321. note( 'Leaving tests_not_long_imapsync_version_public()' ) ;
  7322. return ;
  7323. }
  7324. sub check_last_release {
  7325. my $fake = shift ;
  7326. my $public_release = not_long_imapsync_version_public( $fake ) ;
  7327. $debug and myprint( "check_last_release: [$public_release]\n" ) ;
  7328. my $inline_help_when_on = '( Use --noreleasecheck to avoid this release check. )' ;
  7329. if ( $public_release eq 'unknown' ) {
  7330. return( 'Imapsync public release is unknown.' . $inline_help_when_on ) ;
  7331. }
  7332. if ( $public_release eq 'timeout' ) {
  7333. return( 'Imapsync public release is unknown (timeout).' . $inline_help_when_on ) ;
  7334. }
  7335. if ( ! is_a_release_number( $public_release ) ) {
  7336. return( "Imapsync public release is unknown ($public_release)." . $inline_help_when_on ) ;
  7337. }
  7338. my $imapsync_here = imapsync_version( $sync ) ;
  7339. if ( $public_release > $imapsync_here ) {
  7340. return( 'This imapsync is not up to date. ' . "( local $imapsync_here < official $public_release )" . $inline_help_when_on ) ;
  7341. }else{
  7342. return( 'This imapsync is up to date. ' . "( local $imapsync_here >= official $public_release )" . $inline_help_when_on ) ;
  7343. }
  7344. return( 'really unknown' ) ; # Should never arrive here
  7345. }
  7346. sub tests_check_last_release {
  7347. note( 'Entering tests_check_last_release()' ) ;
  7348. diag( check_last_release( 1.1 ) ) ;
  7349. # \Q \E here to avoid putting \ before each space
  7350. like( check_last_release( 1.1 ), qr/\Qis up to date\E/mxs, 'check_last_release: up to date' ) ;
  7351. like( check_last_release( 1.1 ), qr/1\.1/mxs, 'check_last_release: up to date, include number' ) ;
  7352. diag( check_last_release( 999.999 ) ) ;
  7353. like( check_last_release( 999.999 ), qr/\Qnot up to date\E/mxs, 'check_last_release: not up to date' ) ;
  7354. like( check_last_release( 999.999 ), qr/999\.999/mxs, 'check_last_release: not up to date, include number' ) ;
  7355. like( check_last_release( 'unknown' ), qr/\QImapsync public release is unknown\E/mxs, 'check_last_release: unknown' ) ;
  7356. like( check_last_release( 'timeout' ), qr/\QImapsync public release is unknown (timeout)\E/mxs, 'check_last_release: timeout' ) ;
  7357. like( check_last_release( 'lalala' ), qr/\QImapsync public release is unknown (lalala)\E/mxs, 'check_last_release: lalala' ) ;
  7358. diag( check_last_release( ) ) ;
  7359. note( 'Leaving tests_check_last_release()' ) ;
  7360. return ;
  7361. }
  7362. sub imapsync_version {
  7363. my $mysync = shift ;
  7364. my $rcs = $mysync->{rcs} ;
  7365. my $version ;
  7366. $version = version_from_rcs( $rcs ) ;
  7367. return( $version ) ;
  7368. }
  7369. sub tests_version_from_rcs {
  7370. note( 'Entering tests_version_from_rcs()' ) ;
  7371. is( undef, version_from_rcs( ), 'version_from_rcs: no args => UNKNOWN' ) ;
  7372. is( 1.831, version_from_rcs( q{imapsync,v 1.831 2017/08/27} ), 'version_from_rcs: imapsync,v 1.831 2017/08/27 => 1.831' ) ;
  7373. is( 'UNKNOWN', version_from_rcs( 1.831 ), 'version_from_rcs: 1.831 => UNKNOWN' ) ;
  7374. note( 'Leaving tests_version_from_rcs()' ) ;
  7375. return ;
  7376. }
  7377. sub version_from_rcs {
  7378. my $rcs = shift ;
  7379. if ( ! $rcs ) { return ; }
  7380. my $version = 'UNKNOWN' ;
  7381. if ( $rcs =~ m{,v\s+(\d+\.\d+)}mxso ) {
  7382. $version = $1
  7383. }
  7384. return( $version ) ;
  7385. }
  7386. sub tests_imapsync_basename {
  7387. note( 'Entering tests_imapsync_basename()' ) ;
  7388. ok( imapsync_basename() =~ m/imapsync/, 'imapsync_basename: match imapsync');
  7389. ok( 'blabla' ne imapsync_basename(), 'imapsync_basename: do not equal blabla');
  7390. note( 'Leaving tests_imapsync_basename()' ) ;
  7391. return ;
  7392. }
  7393. sub imapsync_basename {
  7394. return basename( $PROGRAM_NAME ) ;
  7395. }
  7396. sub localhost_info {
  7397. my $mysync = shift ;
  7398. my( $infos ) = join( q{},
  7399. "Here is imapsync ", imapsync_version( $mysync ),
  7400. " on host " . hostname(),
  7401. ", a $OSNAME system with ",
  7402. ram_memory_info( ),
  7403. "\n",
  7404. 'with Perl ',
  7405. mysprintf( '%vd ', $PERL_VERSION),
  7406. "and Mail::IMAPClient $Mail::IMAPClient::VERSION",
  7407. ) ;
  7408. return( $infos ) ;
  7409. }
  7410. sub tests_cpu_number {
  7411. note( 'Entering tests_cpu_number()' ) ;
  7412. is( 1, is_an_integer( cpu_number( ) ), "cpu_number: is_an_integer" ) ;
  7413. ok( 1 <= cpu_number( ), "cpu_number: 1 or more" ) ;
  7414. is( 1, cpu_number( 1 ), "cpu_number: 1 => 1" ) ;
  7415. is( 1, cpu_number( $MINUS_ONE ), "cpu_number: -1 => 1" ) ;
  7416. is( 1, cpu_number( 'lalala' ), "cpu_number: lalala => 1" ) ;
  7417. is( $NUMBER_42, cpu_number( $NUMBER_42 ), "cpu_number: $NUMBER_42 => $NUMBER_42" ) ;
  7418. note( 'Leaving tests_cpu_number()' ) ;
  7419. return ;
  7420. }
  7421. sub cpu_number {
  7422. my $cpu_number_forced = shift ;
  7423. # Well, here 1 is better than 0 or undef
  7424. my $cpu_number = 1 ; # Default value, erased if better found
  7425. my @cpuinfo ;
  7426. if ( $ENV{"NUMBER_OF_PROCESSORS"} ) {
  7427. # might be under a Windows system
  7428. $cpu_number = $ENV{"NUMBER_OF_PROCESSORS"} ;
  7429. $debug and myprint( "Number of processors found by env var NUMBER_OF_PROCESSORS: $cpu_number\n" ) ;
  7430. }elsif ( 'darwin' eq $OSNAME ) {
  7431. $cpu_number = backtick( "sysctl -n hw.ncpu" ) ;
  7432. chomp( $cpu_number ) ;
  7433. $debug and myprint( "Number of processors found by cmd 'sysctl -n hw.ncpu': $cpu_number\n" ) ;
  7434. }elsif ( ! -e '/proc/cpuinfo' ) {
  7435. $debug and myprint( "Number of processors not found so I might assume there is only 1\n" ) ;
  7436. $cpu_number = 1 ;
  7437. }elsif( @cpuinfo = file_to_array( '/proc/cpuinfo' ) ) {
  7438. $cpu_number = grep { /^processor/mxs } @cpuinfo ;
  7439. $debug and myprint( "Number of processors found via /proc/cpuinfo: $cpu_number\n" ) ;
  7440. }
  7441. if ( defined $cpu_number_forced ) {
  7442. $cpu_number = $cpu_number_forced ;
  7443. }
  7444. return( integer_or_1( $cpu_number ) ) ;
  7445. }
  7446. sub tests_integer_or_1 {
  7447. is( 1, integer_or_1( ), 'integer_or_1: no args => 1' ) ;
  7448. is( 1, integer_or_1( undef ), 'integer_or_1: undef => 1' ) ;
  7449. is( $NUMBER_10, integer_or_1( $NUMBER_10 ), 'integer_or_1: 10 => 10' ) ;
  7450. is( 1, integer_or_1( q{} ), 'integer_or_1: empty string => 1' ) ;
  7451. is( 1, integer_or_1( 'lalala' ), 'integer_or_1: lalala => 1' ) ;
  7452. return ;
  7453. }
  7454. sub integer_or_1 {
  7455. my $number = shift ;
  7456. if ( is_an_integer( $number ) ) {
  7457. return $number ;
  7458. }
  7459. # else
  7460. return 1 ;
  7461. }
  7462. sub tests_is_an_integer {
  7463. note( 'Entering tests_is_an_integer()' ) ;
  7464. is( undef, is_an_integer( ), 'is_an_integer: no args => undef ' ) ;
  7465. ok( is_an_integer( 1 ), 'is_an_integer: 1 => yes ') ;
  7466. ok( is_an_integer( $NUMBER_42 ), 'is_an_integer: 42 => yes ') ;
  7467. ok( is_an_integer( "$NUMBER_42" ), 'is_an_integer: "$NUMBER_42" => yes ') ;
  7468. ok( is_an_integer( '42' ), 'is_an_integer: "42" => yes ') ;
  7469. ok( is_an_integer( $NUMBER_104_857_600 ), 'is_an_integer: 104_857_600 => yes') ;
  7470. ok( is_an_integer( "$NUMBER_104_857_600" ), 'is_an_integer: "$NUMBER_104_857_600" => yes') ;
  7471. ok( is_an_integer( '104857600' ), 'is_an_integer: 104857600 => yes') ;
  7472. ok( ! is_an_integer( 'blabla' ), 'is_an_integer: blabla => no' ) ;
  7473. ok( ! is_an_integer( q{} ), 'is_an_integer: empty string => no' ) ;
  7474. note( 'Leaving tests_is_an_integer()' ) ;
  7475. return ;
  7476. }
  7477. sub is_an_integer {
  7478. my $number = shift ;
  7479. if ( ! defined $number ) { return ; }
  7480. return( $number =~ m{^\d+$}xo ) ;
  7481. }
  7482. sub tests_loadavg {
  7483. note( 'Entering tests_loadavg()' ) ;
  7484. SKIP: {
  7485. skip( 'Tests for darwin', 2 ) if ('darwin' ne $OSNAME) ;
  7486. is( undef, loadavg( '/noexist' ), 'loadavg: /noexist => undef' ) ;
  7487. is_deeply( [ '0.11', '0.22', '0.33' ],
  7488. [ loadavg( 'W/t/loadavg.out' ) ],
  7489. 'loadavg W/t/loadavg.out => 0.11 0.22 0.33' ) ;
  7490. } ;
  7491. SKIP: {
  7492. skip( 'Tests for linux', 3 ) if ('linux' ne $OSNAME) ;
  7493. is( undef, loadavg( '/noexist' ), 'loadavg: /noexist => undef' ) ;
  7494. ok( loadavg( ), 'loadavg: no args' ) ;
  7495. is_deeply( [ '0.39', '0.30', '0.37', '1/602' ],
  7496. [ loadavg( '0.39 0.30 0.37 1/602 6073' ) ],
  7497. 'loadavg 0.39 0.30 0.37 1/602 6073 => [0.39, 0.30, 0.37, 1/602]' ) ;
  7498. } ;
  7499. SKIP: {
  7500. skip( 'Tests for Windows', 1 ) if ('MSWin32' ne $OSNAME) ;
  7501. is_deeply( [ 0 ],
  7502. [ loadavg( ) ],
  7503. 'loadavg on MSWin32 => 0' ) ;
  7504. } ;
  7505. note( 'Leaving tests_loadavg()' ) ;
  7506. return ;
  7507. }
  7508. sub loadavg {
  7509. if ( 'linux' eq $OSNAME ) {
  7510. return ( loadavg_linux( @ARG ) ) ;
  7511. }
  7512. if ( 'darwin' eq $OSNAME ) {
  7513. return ( loadavg_darwin( @ARG ) ) ;
  7514. }
  7515. if ( 'MSWin32' eq $OSNAME ) {
  7516. return ( loadavg_windows( @ARG ) ) ;
  7517. }
  7518. return( 'unknown' ) ;
  7519. }
  7520. sub loadavg_linux {
  7521. my $line = shift ;
  7522. if ( ! $line ) {
  7523. $line = firstline( '/proc/loadavg' ) or return ;
  7524. }
  7525. my ( $avg_1_min, $avg_5_min, $avg_15_min, $current_runs ) = split /\s/mxs, $line ;
  7526. if ( all_defined( $avg_1_min, $avg_5_min, $avg_15_min ) ) {
  7527. $debug and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min $current_runs\n" ) ;
  7528. return ( $avg_1_min, $avg_5_min, $avg_15_min, $current_runs ) ;
  7529. }
  7530. return ;
  7531. }
  7532. sub loadavg_darwin {
  7533. my $file = shift ;
  7534. # Example of output of command "sysctl vm.loadavg":
  7535. # vm.loadavg: { 0.15 0.08 0.08 }
  7536. my $loadavg ;
  7537. if ( ! defined $file ) {
  7538. eval {
  7539. $loadavg = `/usr/sbin/sysctl vm.loadavg` ;
  7540. #myprint( "LOADAVG DARWIN: $loadavg\n" ) ;
  7541. } ;
  7542. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  7543. }else{
  7544. $loadavg = firstline( $file ) or return ;
  7545. }
  7546. my ( $avg_1_min, $avg_5_min, $avg_15_min )
  7547. = $loadavg =~ /vm\.loadavg\s*[:=]\s*\{?\s*(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)/mxs ;
  7548. $debug and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min\n" ) ;
  7549. return ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  7550. }
  7551. sub loadavg_windows {
  7552. my $file = shift ;
  7553. # Example of output of command "wmic cpu get loadpercentage":
  7554. # LoadPercentage
  7555. # 12
  7556. my $loadavg ;
  7557. if ( ! defined $file ) {
  7558. eval {
  7559. #$loadavg = `CMD wmic cpu get loadpercentage` ;
  7560. $loadavg = "LoadPercentage\n0\n" ;
  7561. #myprint( "LOADAVG WIN: $loadavg\n" ) ;
  7562. } ;
  7563. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  7564. }else{
  7565. $loadavg = file_to_string( $file ) or return ;
  7566. #myprint( "$loadavg" ) ;
  7567. }
  7568. $loadavg =~ /LoadPercentage\n(\d+)/xms ;
  7569. my $num = $1 ;
  7570. $num /= 100 ;
  7571. $debug and myprint( "System load: $num\n" ) ;
  7572. return ( $num ) ;
  7573. }
  7574. sub tests_load_and_delay {
  7575. note( 'Entering tests_load_and_delay()' ) ;
  7576. is( undef, load_and_delay( ), 'load_and_delay: no args => undef ' ) ;
  7577. is( undef, load_and_delay( 1 ), 'load_and_delay: not 4 args => undef ' ) ;
  7578. is( undef, load_and_delay( 0, 1, 1, 1 ), 'load_and_delay: division per 0 => undef ' ) ;
  7579. is( 0, load_and_delay( 1, 1, 1, 1 ), 'load_and_delay: one core, loads are all 1 => ok ' ) ;
  7580. is( 0, load_and_delay( 2, 2, 2, 2 ), 'load_and_delay: two core, loads are all 2 => ok ' ) ;
  7581. is( 0, load_and_delay( 2, 2, 4, 5 ), 'load_and_delay: two core, load1m is 2 => ok ' ) ;
  7582. is( 0, load_and_delay( 1, 0, 0, 0 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=0 => 0 ' ) ;
  7583. is( 0, load_and_delay( 1, 0, 0, 2 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=2 => 0 ' ) ;
  7584. is( 0, load_and_delay( 1, 0, 2, 0 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=0 => 0 ' ) ;
  7585. is( 0, load_and_delay( 1, 0, 2, 2 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=2 => 0 ' ) ;
  7586. is( 1, load_and_delay( 1, 2, 0, 0 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=0 => 1 ' ) ;
  7587. is( 1, load_and_delay( 1, 2, 0, 2 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=2 => 1 ' ) ;
  7588. is( 5, load_and_delay( 1, 2, 2, 0 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=0 => 5 ' ) ;
  7589. is( 15, load_and_delay( 1, 2, 2, 2 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=2 => 15 ' ) ;
  7590. is( 0, load_and_delay( 4, 0, 2, 2 ), 'load_and_delay: four core, load1m=0 load5m=2 load15m=2 => 0 ' ) ;
  7591. is( 1, load_and_delay( 4, 8, 0, 0 ), 'load_and_delay: four core, load1m=2 load5m=0 load15m=0 => 1 ' ) ;
  7592. is( 1, load_and_delay( 4, 8, 0, 2 ), 'load_and_delay: four core, load1m=2 load5m=0 load15m=2 => 1 ' ) ;
  7593. is( 5, load_and_delay( 4, 8, 8, 0 ), 'load_and_delay: four core, load1m=2 load5m=2 load15m=0 => 5 ' ) ;
  7594. is( 15, load_and_delay( 4, 8, 8, 8 ), 'load_and_delay: four core, load1m=2 load5m=2 load15m=2 => 15 ' ) ;
  7595. is( 15, load_and_delay( 4, 8, 8, 8, 'lalala' ), 'load_and_delay: five arguments is ok' ) ;
  7596. note( 'Leaving tests_load_and_delay()' ) ;
  7597. return ;
  7598. }
  7599. sub load_and_delay {
  7600. # Basically return 0 if load is not heavy, ie <= 1 per processor
  7601. if ( 4 > scalar @ARG ) { return ; }
  7602. my ( $cpu_num, $avg_1_min, $avg_5_min, $avg_15_min ) = @ARG ;
  7603. if ( 0 == $cpu_num ) { return ; }
  7604. # Let divide by number of cores
  7605. ( $avg_1_min, $avg_5_min, $avg_15_min ) = map { $_ / $cpu_num } ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  7606. # One of avg ok => ok, for now it is a OR
  7607. if ( $avg_1_min <= 1 ) { return 0 ; }
  7608. if ( $avg_5_min <= 1 ) { return 1 ; } # Retry in 1 minute
  7609. if ( $avg_15_min <= 1 ) { return 5 ; } # Retry in 5 minutes
  7610. return 15 ; # Retry in 15 minutes
  7611. }
  7612. sub ram_memory_info {
  7613. # In GigaBytes so division by 1024 * 1024 * 1024
  7614. #
  7615. return(
  7616. sprintf( "%.1f/%.1f free GiB of RAM",
  7617. Sys::MemInfo::get("freemem") / ( $KIBI ** 3 ),
  7618. Sys::MemInfo::get("totalmem") / ( $KIBI ** 3 ),
  7619. )
  7620. ) ;
  7621. }
  7622. sub tests_memory_stress {
  7623. note( 'Entering tests_memory_stress()' ) ;
  7624. is( undef, memory_stress( ), 'memory_stress: => undef' ) ;
  7625. note( 'Leaving tests_memory_stress()' ) ;
  7626. return ;
  7627. }
  7628. sub memory_stress {
  7629. my $total_ram_in_MB = Sys::MemInfo::get("totalmem") / ( $KIBI * $KIBI ) ;
  7630. my $i = 1 ;
  7631. myprintf("Stress memory consumption before: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  7632. while ( $i < $total_ram_in_MB / 1.7 ) { $a .= "A" x 1000_000; $i++ } ;
  7633. myprintf("Stress memory consumption after: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  7634. return ;
  7635. }
  7636. sub tests_memory_consumption {
  7637. note( 'Entering tests_memory_consumption()' ) ;
  7638. like( memory_consumption( ), qr{\d+}xms,'memory_consumption no args') ;
  7639. like( memory_consumption( 1 ), qr{\d+}xms,'memory_consumption 1') ;
  7640. like( memory_consumption( $PROCESS_ID ), qr{\d+}xms,"memory_consumption_of_pids $PROCESS_ID") ;
  7641. like( memory_consumption_ratio(), qr{\d+}xms, 'memory_consumption_ratio' ) ;
  7642. like( memory_consumption_ratio(1), qr{\d+}xms, 'memory_consumption_ratio 1' ) ;
  7643. like( memory_consumption_ratio(10), qr{\d+}xms, 'memory_consumption_ratio 10' ) ;
  7644. like( memory_consumption(), qr{\d+}xms, "memory_consumption\n" ) ;
  7645. note( 'Leaving tests_memory_consumption()' ) ;
  7646. return ;
  7647. }
  7648. sub memory_consumption {
  7649. # memory consumed by imapsync until now in bytes
  7650. return( ( memory_consumption_of_pids( ) )[0] );
  7651. }
  7652. sub debugmemory {
  7653. my $mysync = shift ;
  7654. if ( ! $mysync->{debugmemory} ) { return q{} ; }
  7655. my $precision = shift ;
  7656. return( mysprintf( "Memory consumption$precision: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ) ;
  7657. }
  7658. sub memory_consumption_of_pids {
  7659. my @pid = @_;
  7660. @pid = ( @pid ) ? @pid : ( $PROCESS_ID ) ;
  7661. $debug and myprint( "memory_consumption_of_pids PIDs: @pid\n" ) ;
  7662. my @val ;
  7663. if ( 'MSWin32' eq $OSNAME ) {
  7664. @val = memory_consumption_of_pids_win32( @pid ) ;
  7665. }else{
  7666. # Unix
  7667. my @ps = qx{ ps -o vsz -p @pid } ;
  7668. #myprint( "ps: @ps" ) ;
  7669. # Use IPC::Open3 from perlcrit -3
  7670. # It stalls on Darwin, don't understand why!
  7671. #my @ps = backtick( "ps -o vsz -p @pid" ) ;
  7672. #myprint( "ps: @ps" ) ;
  7673. shift @ps; # First line is column name "VSZ"
  7674. chomp @ps;
  7675. # convert to octets
  7676. @val = map { $_ * $KIBI } @ps ;
  7677. }
  7678. $debug and myprint "@val\n" ;
  7679. return( @val ) ;
  7680. }
  7681. sub memory_consumption_of_pids_win32 {
  7682. # Windows
  7683. my @PID = @_;
  7684. my %PID;
  7685. # hash of pids as key values
  7686. map { $PID{$_}++ } @PID;
  7687. # Does not work but should work reading the tasklist documentation
  7688. #@ps = qx{ tasklist /FI "PID eq @PID" };
  7689. my @ps = qx{ tasklist /NH /FO CSV } ;
  7690. #my @ps = backtick( 'tasklist /NH /FO CSV' ) ;
  7691. #myprint( "-" x $STD_CHAR_PER_LINE, "\n", @ps, "-" x $STD_CHAR_PER_LINE, "\n" ) ;
  7692. my @val;
  7693. foreach my $line (@ps) {
  7694. my($name, $pid, $mem) = (split ',', $line )[0,1,4];
  7695. next if (! $pid);
  7696. #myprint( "[$name][$pid][$mem]" ) ;
  7697. if ($PID{remove_qq($pid)}) {
  7698. #myprint( "MATCH !\n" ) ;
  7699. chomp $mem ;
  7700. $mem = remove_qq($mem);
  7701. $mem = remove_Ko($mem);
  7702. $mem = remove_not_num($mem);
  7703. #myprint( "[$mem]\n" ) ;
  7704. push @val, $mem * $KIBI;
  7705. }
  7706. }
  7707. return(@val);
  7708. }
  7709. sub tests_backtick {
  7710. note( 'Entering tests_backtick()' ) ;
  7711. is( undef, backtick( ), 'backtick: no args' ) ;
  7712. is( undef, backtick( q{} ), 'backtick: empty command' ) ;
  7713. SKIP: {
  7714. skip( 'test for MSWin32', 5 ) if ('MSWin32' ne $OSNAME) ;
  7715. my @output ;
  7716. @output = backtick( 'echo Hello World!' ) ;
  7717. # Add \r on Windows.
  7718. ok( "Hello World!\r\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  7719. $debug and myprint( "[@output]" ) ;
  7720. @output = backtick( 'echo Hello & echo World!' ) ;
  7721. ok( "Hello \r\n" eq $output[0], 'backtick: echo Hello & echo World! line 1' ) ;
  7722. ok( "World!\r\n" eq $output[1], 'backtick: echo Hello & echo World! line 2' ) ;
  7723. $debug and myprint( "[@output][$output[0]][$output[1]]" ) ;
  7724. # Scalar context
  7725. ok( "Hello World!\r\n" eq backtick( 'echo Hello World!' ),
  7726. 'backtick: echo Hello World! scalar' ) ;
  7727. ok( "Hello \r\nWorld!\r\n" eq backtick( 'echo Hello & echo World!' ),
  7728. 'backtick: echo Hello & echo World! scalar 2 lines' ) ;
  7729. } ;
  7730. SKIP: {
  7731. skip( 'test for Unix', 7 ) if ('MSWin32' eq $OSNAME) ;
  7732. is( undef, backtick( 'aaaarrrg' ), 'backtick: aaaarrrg command not found' ) ;
  7733. # Array context
  7734. my @output ;
  7735. @output = backtick( 'echo Hello World!' ) ;
  7736. ok( "Hello World!\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  7737. $debug and myprint( "[@output]" ) ;
  7738. @output = backtick( "echo Hello\necho World!" ) ;
  7739. ok( "Hello\n" eq $output[0], 'backtick: echo Hello; echo World! line 1' ) ;
  7740. ok( "World!\n" eq $output[1], 'backtick: echo Hello; echo World! line 2' ) ;
  7741. $debug and myprint( "[@output]" ) ;
  7742. # Scalar context
  7743. ok( "Hello World!\n" eq backtick( 'echo Hello World!' ),
  7744. 'backtick: echo Hello World! scalar' ) ;
  7745. ok( "Hello\nWorld!\n" eq backtick( "echo Hello\necho World!" ),
  7746. 'backtick: echo Hello; echo World! scalar 2 lines' ) ;
  7747. # Return error positive value, that's ok
  7748. is( undef, backtick( 'false' ), 'backtick: false returns no output' ) ;
  7749. my $mem = backtick( "ps -o vsz -p $PROCESS_ID" ) ;
  7750. $debug and myprint "MEM=$mem\n" ;
  7751. }
  7752. note( 'Leaving tests_backtick()' ) ;
  7753. return ;
  7754. }
  7755. sub backtick {
  7756. my $command = shift ;
  7757. if ( ! $command ) { return ; }
  7758. my ( $writer, $reader, $err ) ;
  7759. my @output ;
  7760. my $pid ;
  7761. my $eval = eval {
  7762. $pid = IPC::Open3::open3( $writer, $reader, $err, $command ) ;
  7763. } ;
  7764. if ( $EVAL_ERROR ) {
  7765. myprint( $EVAL_ERROR ) ;
  7766. return ;
  7767. }
  7768. if ( ! $eval ) { return ; }
  7769. if ( ! $pid ) { return ; }
  7770. waitpid( $pid, 0 ) ;
  7771. @output = <$reader>; # Output here
  7772. #
  7773. #my @errors = <$err>; #Errors here, instead of the console
  7774. if ( not @output ) { return ; }
  7775. #myprint( @output ) ;
  7776. if ( $output[0] =~ /\Qopen3: exec of $command failed\E/mxs ) { return ; }
  7777. if ( wantarray ) {
  7778. return( @output ) ;
  7779. } else {
  7780. return( join( q{}, @output) ) ;
  7781. }
  7782. }
  7783. sub remove_not_num {
  7784. my $string = shift ;
  7785. $string =~ tr/0-9//cd ;
  7786. #myprint( "tr [$string]\n" ) ;
  7787. return( $string ) ;
  7788. }
  7789. sub tests_remove_not_num {
  7790. note( 'Entering tests_remove_not_num()' ) ;
  7791. ok( '123' eq remove_not_num( 123 ), 'remove_not_num( 123 )' ) ;
  7792. ok( '123' eq remove_not_num( '123' ), q{remove_not_num( '123' )} ) ;
  7793. ok( '123' eq remove_not_num( '12 3' ), q{remove_not_num( '12 3' )} ) ;
  7794. ok( '123' eq remove_not_num( 'a 12 3 Ko' ), q{remove_not_num( 'a 12 3 Ko' )} ) ;
  7795. note( 'Leaving tests_remove_not_num()' ) ;
  7796. return ;
  7797. }
  7798. sub remove_Ko {
  7799. my $string = shift;
  7800. if ($string =~ /^(.*)\sKo$/xo) {
  7801. return($1);
  7802. }else{
  7803. return($string);
  7804. }
  7805. }
  7806. sub remove_qq {
  7807. my $string = shift;
  7808. if ($string =~ /^"(.*)"$/xo) {
  7809. return($1);
  7810. }else{
  7811. return($string);
  7812. }
  7813. }
  7814. sub memory_consumption_ratio {
  7815. my ($base) = @_;
  7816. $base ||= 1;
  7817. my $consu = memory_consumption();
  7818. return($consu / $base);
  7819. }
  7820. sub date_from_rcs {
  7821. my $d = shift ;
  7822. 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 ) ;
  7823. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  7824. # Handles the following format
  7825. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  7826. #myprint( "$d\n" ) ;
  7827. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  7828. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  7829. $month = $num2mon{$month} ;
  7830. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  7831. #myprint( "$d\n" ) ;
  7832. }
  7833. return( $d ) ;
  7834. }
  7835. sub tests_date_from_rcs {
  7836. note( 'Entering tests_date_from_rcs()' ) ;
  7837. ok('19-Sep-2015 16:11:07 +0000'
  7838. eq date_from_rcs('Date: 2015/09/19 16:11:07 '), 'date_from_rcs from RCS date' ) ;
  7839. note( 'Leaving tests_date_from_rcs()' ) ;
  7840. return ;
  7841. }
  7842. sub good_date {
  7843. # two incoming formats:
  7844. # header Tue, 24 Aug 2010 16:00:00 +0200
  7845. # internal 24-Aug-2010 16:00:00 +0200
  7846. # outgoing format: internal date format
  7847. # 24-Aug-2010 16:00:00 +0200
  7848. my $d = shift ;
  7849. return(q{}) if not defined $d;
  7850. SWITCH: {
  7851. if ( $d =~ m{(\d?)(\d-...-\d{4})(\s\d{2}:\d{2}:\d{2})(\s(?:\+|-)\d{4})?}xo ) {
  7852. #myprint( "internal: [$1][$2][$3][$4]\n" ) ;
  7853. my ($day_1, $date_rest, $hour, $zone) = ($1,$2,$3,$4) ;
  7854. $day_1 = '0' if ($day_1 eq q{}) ;
  7855. $zone = ' +0000' if not defined $zone ;
  7856. $d = $day_1 . $date_rest . $hour . $zone ;
  7857. last SWITCH ;
  7858. }
  7859. 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 ) {
  7860. # Handles any combination of following formats
  7861. # Tue, 24 Aug 2010 16:00:00 +0200 -- Standard
  7862. # 24 Aug 2010 16:00:00 +0200 -- Missing Day of Week
  7863. # Tue, 24 Aug 97 16:00:00 +0200 -- Two digit year
  7864. # Tue, 24 Aug 1997 16.00.00 +0200 -- Periods instead of colons
  7865. # Tue, 24 Aug 1997 16:00:00 +0200 -- Extra whitespace between year and hour
  7866. # Tue, 24 Aug 1997 6:5:2 +0200 -- Single digit hour, min, or second
  7867. # Tue, 24, Aug 1997 16:00:00 +0200 -- Extra comma
  7868. #myprint( "header: [$1][$2][$3][$4][$5][$6][$7][$8]\n" ) ;
  7869. my ($day, $month, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7,$8);
  7870. $year = '19' . $year if length($year) == 2 && $year =~ m/^[789]/xo;
  7871. $year = '20' . $year if length($year) == 2;
  7872. $month = substr $month, 0, 3 if length($month) > 4;
  7873. $day = mysprintf( '%02d', $day);
  7874. $hour = mysprintf( '%02d', $hour);
  7875. $min = mysprintf( '%02d', $min);
  7876. $sec = '00' if not defined $sec ;
  7877. $sec = mysprintf( '%02d', $sec ) ;
  7878. $zone = '+0000' if not defined $zone ;
  7879. $d = "$day-$month-$year $hour:$min:$sec $zone" ;
  7880. last SWITCH ;
  7881. }
  7882. 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 ) {
  7883. # Handles any combination of following formats
  7884. # Sun Aug 20 11:55:09 2006
  7885. # Wed Jan 24 11:58:38 MST 2007
  7886. # Wed Jan 2 08:40:57 2008
  7887. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  7888. my ($month, $day, $hour, $min, $sec, $year) = ($1,$2,$3,$4,$5,$6);
  7889. $day = mysprintf( '%02d', $day ) ;
  7890. $hour = mysprintf( '%02d', $hour ) ;
  7891. $min = mysprintf( '%02d', $min ) ;
  7892. $sec = mysprintf( '%02d', $sec ) ;
  7893. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  7894. last SWITCH ;
  7895. }
  7896. 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 ) ;
  7897. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  7898. # Handles the following format
  7899. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  7900. #myprint( "$d\n" ) ;
  7901. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  7902. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  7903. $month = $num2mon{$month} ;
  7904. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  7905. #myprint( "$d\n" ) ;
  7906. last SWITCH ;
  7907. }
  7908. if ($d =~ m{(\d{2})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  7909. # Handles the following format
  7910. # 02/06/09 22:18:08 -- Generated by AVTECH TemPageR devices
  7911. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  7912. my ($month, $day, $year, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6);
  7913. $year = '20' . $year;
  7914. $month = $num2mon{$month};
  7915. $d = "$day-$month-$year $hour:$min:$sec +0000";
  7916. last SWITCH ;
  7917. }
  7918. 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 ) {
  7919. # Handles the following format
  7920. # Saturday, December 14, 2002 05:00 PM - KBtoys.com order confirmations
  7921. my ($month, $day, $year, $hour, $min, $apm) = ($1,$2,$3,$4,$5,$6);
  7922. $hour += 12 if $apm eq 'PM' ;
  7923. $day = mysprintf( '%02d', $day ) ;
  7924. $d = "$day-$month-$year $hour:$min:00 +0000" ;
  7925. last SWITCH ;
  7926. }
  7927. if ($d =~ m{(\w{3})\s(\d{1,2})\s(\d{4})\s(\d{2}):(\d{2}):(\d{2})\s((?:\+|-)\d{4})}xo ) {
  7928. # Handles the following format
  7929. # Saturday, December 14, 2002 05:00 PM - jr.com order confirmations
  7930. my ($month, $day, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7);
  7931. $day = mysprintf( '%02d', $day ) ;
  7932. $d = "$day-$month-$year $hour:$min:$sec $zone";
  7933. last SWITCH ;
  7934. }
  7935. if ($d =~ m{(\d{1,2})-(\w{3})-(\d{4})}xo ) {
  7936. # Handles the following format
  7937. # 21-Jun-2001 - register.com domain transfer email circa 2001
  7938. my ($day, $month, $year) = ($1,$2,$3);
  7939. $day = mysprintf( '%02d', $day);
  7940. $d = "$day-$month-$year 11:11:11 +0000";
  7941. last SWITCH ;
  7942. }
  7943. # unknown or unmatch => return same string
  7944. return($d);
  7945. }
  7946. $d = qq("$d") ;
  7947. return( $d ) ;
  7948. }
  7949. sub tests_good_date {
  7950. note( 'Entering tests_good_date()' ) ;
  7951. ok(q{} eq good_date(), 'good_date no arg');
  7952. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('24-Aug-2010 16:00:00 +0200'), 'good_date internal 2digit zone');
  7953. ok('"24-Aug-2010 16:00:00 +0000"' eq good_date('24-Aug-2010 16:00:00'), 'good_date internal 2digit no zone');
  7954. ok('"01-Sep-2010 16:00:00 +0200"' eq good_date( '1-Sep-2010 16:00:00 +0200'), 'good_date internal SP 1digit');
  7955. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('Tue, 24 Aug 2010 16:00:00 +0200'), 'good_date header 2digit zone');
  7956. ok('"01-Sep-2010 16:00:00 +0000"' eq good_date('Wed, 1 Sep 2010 16:00:00'), 'good_date header SP 1digit zone');
  7957. 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');
  7958. 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');
  7959. ok('"06-Feb-2009 22:18:08 +0000"' eq good_date('02/06/09 22:18:08'), 'good_date header TemPageR');
  7960. 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');
  7961. 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');
  7962. 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');
  7963. 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');
  7964. ok('"24-Aug-2067 16:00:00 +0200"' eq good_date('Tue, 24 Aug 67 16:00:00 +0200'), 'good_date header 2digit year');
  7965. ok('"24-Aug-1977 16:00:00 +0200"' eq good_date('Tue, 24 Aug 77 16:00:00 +0200'), 'good_date header 2digit year');
  7966. ok('"24-Aug-1987 16:00:00 +0200"' eq good_date('Tue, 24 Aug 87 16:00:00 +0200'), 'good_date header 2digit year');
  7967. ok('"24-Aug-1997 16:00:00 +0200"' eq good_date('Tue, 24 Aug 97 16:00:00 +0200'), 'good_date header 2digit year');
  7968. ok('"24-Aug-2004 16:00:00 +0200"' eq good_date('Tue, 24 Aug 04 16:00:00 +0200'), 'good_date header 2digit year');
  7969. 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');
  7970. 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');
  7971. 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');
  7972. ok('"24-Aug-1997 05:06:02 +0200"' eq good_date('Tue, 24, Aug 1997 05:06:02 +0200'), 'good_date header extra commas');
  7973. ok('"01-Oct-2003 12:45:24 +0000"' eq good_date('Wednesday, 01 October 2003 12:45:24 CDT'), 'good_date header no abbrev');
  7974. ok('"11-Jan-2005 17:58:27 -0500"' eq good_date('Tue, 11 Jan 2005 17:58:27 -0500'), 'good_date extra white space');
  7975. ok('"18-Dec-2002 15:07:00 +0000"' eq good_date('Wednesday, December 18, 2002 03:07 PM'), 'good_date kbtoys.com orders');
  7976. ok('"16-Dec-2004 02:01:49 -0500"' eq good_date('Dec 16 2004 02:01:49 -0500'), 'good_date jr.com orders');
  7977. ok('"21-Jun-2001 11:11:11 +0000"' eq good_date('21-Jun-2001'), 'good_date register.com domain transfer');
  7978. 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)');
  7979. ok('"19-Sep-2015 16:11:07 +0000"' eq good_date('Date: 2015/09/19 16:11:07 '), 'good_date from RCS date' ) ;
  7980. note( 'Leaving tests_good_date()' ) ;
  7981. return ;
  7982. }
  7983. sub tests_list_keys_in_2_not_in_1 {
  7984. note( 'Entering tests_list_keys_in_2_not_in_1()' ) ;
  7985. my @list;
  7986. ok( ! list_keys_in_2_not_in_1( {}, {}), 'list_keys_in_2_not_in_1: {} {}');
  7987. ok( 0 == compare_lists( [], [ list_keys_in_2_not_in_1( {}, {} ) ] ), 'list_keys_in_2_not_in_1: {} {}');
  7988. 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}');
  7989. 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}');
  7990. 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}');
  7991. 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}');
  7992. 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}');
  7993. note( 'Leaving tests_list_keys_in_2_not_in_1()' ) ;
  7994. return ;
  7995. }
  7996. sub list_keys_in_2_not_in_1 {
  7997. my $folders1_ref = shift;
  7998. my $folders2_ref = shift;
  7999. my @list;
  8000. foreach my $folder ( sort keys %{ $folders2_ref } ) {
  8001. next if exists $folders1_ref->{$folder};
  8002. push @list, $folder;
  8003. }
  8004. return(@list);
  8005. }
  8006. sub list_folders_in_2_not_in_1 {
  8007. my (@h2_folders_not_in_h1, %h2_folders_not_in_h1) ;
  8008. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h1_folders_all, \%h2_folders_all) ;
  8009. map { $h2_folders_not_in_h1{$_} = 1} @h2_folders_not_in_h1 ;
  8010. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h2_folders_from_1_all, \%h2_folders_not_in_h1) ;
  8011. return( reverse @h2_folders_not_in_h1 );
  8012. }
  8013. sub tests_match {
  8014. note( 'Entering tests_match()' ) ;
  8015. # undef serie
  8016. is( undef, match( ), 'match: no args => undef' ) ;
  8017. is( undef, match( 'lalala' ), 'match: one args => undef' ) ;
  8018. # This one gives 0 under a binary made by pp
  8019. # but 1 under "normal" Perl interpreter. So a PAR bug?
  8020. #is( 1, match( q{}, q{} ), 'match: q{} =~ q{} => 1' ) ;
  8021. is( 1, match( 'lalala', 'lalala' ), 'match: lalala =~ lalala => 1' ) ;
  8022. is( 1, match( 'lalala', '^lalala' ), 'match: lalala =~ ^lalala => 1' ) ;
  8023. is( 1, match( 'lalala', 'lalala$' ), 'match: lalala =~ lalala$ => 1' ) ;
  8024. is( 1, match( 'lalala', '^lalala$' ), 'match: lalala =~ ^lalala$ => 1' ) ;
  8025. is( 1, match( '_lalala_', 'lalala' ), 'match: _lalala_ =~ lalala => 1' ) ;
  8026. is( 1, match( 'lalala', '.*' ), 'match: lalala =~ .* => 1' ) ;
  8027. is( 1, match( 'lalala', '.' ), 'match: lalala =~ . => 1' ) ;
  8028. is( 1, match( '/lalala/', '/lalala/' ), 'match: /lalala/ =~ /lalala/ => 1' ) ;
  8029. is( 0, match( 'lalala', 'ooo' ), 'match: lalala =~ ooo => 0' ) ;
  8030. is( 0, match( 'lalala', 'lal_ala' ), 'match: lalala =~ lal_ala => 0' ) ;
  8031. is( 0, match( 'lalala', '\.' ), 'match: lalala =~ \. => 0' ) ;
  8032. is( 0, match( 'lalalaX', '^lalala$' ), 'match: lalalaX =~ ^lalala$ => 0' ) ;
  8033. is( 0, match( 'lalala', '/lalala/' ), 'match: lalala =~ /lalala/ => 1' ) ;
  8034. is( 1, match( 'LALALA', '(?i:lalala)' ), 'match: LALALA =~ (?i:lalala) => 1' ) ;
  8035. is( undef, match( 'LALALA', '(?{`ls /`})' ), 'match: LALALA =~ (?{`ls /`}) => undef' ) ;
  8036. is( undef, match( 'LALALA', '(?{print "CACA"})' ), 'match: LALALA =~ (?{print "CACA"}) => undef' ) ;
  8037. is( undef, match( 'CACA', '(??{print "CACA"})' ), 'match: CACA =~ (??{print "CACA"}) => undef' ) ;
  8038. note( 'Leaving tests_match()' ) ;
  8039. return ;
  8040. }
  8041. sub match {
  8042. my( $var, $regex ) = @ARG ;
  8043. # undef cases
  8044. if ( ( ! defined $var ) or ( ! defined $regex ) ) { return ; }
  8045. # normal cases
  8046. if ( eval { $var =~ $regex } ) {
  8047. return 1 ;
  8048. }elsif ( $EVAL_ERROR ) {
  8049. myprint( "Fatal regex $regex\n" ) ;
  8050. return ;
  8051. } else {
  8052. return 0 ;
  8053. }
  8054. return ;
  8055. }
  8056. sub tests_notmatch {
  8057. note( 'Entering tests_notmatch()' ) ;
  8058. # undef serie
  8059. is( undef, notmatch( ), 'notmatch: no args => undef' ) ;
  8060. is( undef, notmatch( 'lalala' ), 'notmatch: one args => undef' ) ;
  8061. is( 1, notmatch( 'lalala', '/lalala/' ), 'notmatch: lalala !~ /lalala/ => 1' ) ;
  8062. is( 0, notmatch( '/lalala/', '/lalala/' ), 'notmatch: /lalala/ !~ /lalala/ => 0' ) ;
  8063. is( 1, notmatch( 'lalala', '/ooo/' ), 'notmatch: lalala !~ /ooo/ => 1' ) ;
  8064. # This one gives 1 under a binary made by pp
  8065. # but 0 under "normal" Perl interpreter. So a PAR bug, same in tests_match .
  8066. #is( 0, notmatch( q{}, q{} ), 'notmatch: q{} !~ q{} => 0' ) ;
  8067. is( 0, notmatch( 'lalala', 'lalala' ), 'notmatch: lalala !~ lalala => 0' ) ;
  8068. is( 0, notmatch( 'lalala', '^lalala' ), 'notmatch: lalala !~ ^lalala => 0' ) ;
  8069. is( 0, notmatch( 'lalala', 'lalala$' ), 'notmatch: lalala !~ lalala$ => 0' ) ;
  8070. is( 0, notmatch( 'lalala', '^lalala$' ), 'notmatch: lalala !~ ^lalala$ => 0' ) ;
  8071. is( 0, notmatch( '_lalala_', 'lalala' ), 'notmatch: _lalala_ !~ lalala => 0' ) ;
  8072. is( 0, notmatch( 'lalala', '.*' ), 'notmatch: lalala !~ .* => 0' ) ;
  8073. is( 0, notmatch( 'lalala', '.' ), 'notmatch: lalala !~ . => 0' ) ;
  8074. is( 1, notmatch( 'lalala', 'ooo' ), 'notmatch: does not match regex => 1' ) ;
  8075. is( 1, notmatch( 'lalala', 'lal_ala' ), 'notmatch: does not match regex => 1' ) ;
  8076. is( 1, notmatch( 'lalala', '\.' ), 'notmatch: matches regex => 0' ) ;
  8077. is( 1, notmatch( 'lalalaX', '^lalala$' ), 'notmatch: does not match regex => 1' ) ;
  8078. note( 'Leaving tests_notmatch()' ) ;
  8079. return ;
  8080. }
  8081. sub notmatch {
  8082. my( $var, $regex ) = @ARG ;
  8083. # undef cases
  8084. if ( ( ! defined $var ) or ( ! defined $regex ) ) { return ; }
  8085. # normal cases
  8086. if ( eval { $var !~ $regex } ) {
  8087. return 1 ;
  8088. }elsif ( $EVAL_ERROR ) {
  8089. myprint( "Fatal regex $regex\n" ) ;
  8090. return ;
  8091. }else{
  8092. return 0 ;
  8093. }
  8094. return ;
  8095. }
  8096. sub delete_folders_in_2_not_in_1 {
  8097. foreach my $folder (@h2_folders_not_in_1) {
  8098. if ( defined $delete2foldersonly and eval "\$folder !~ $delete2foldersonly" ) {
  8099. myprint( "Not deleting $folder because of --delete2foldersonly $delete2foldersonly\n" ) ;
  8100. next ;
  8101. }
  8102. if ( defined $delete2foldersbutnot and eval "\$folder =~ $delete2foldersbutnot" ) {
  8103. myprint( "Not deleting $folder because of --delete2foldersbutnot $delete2foldersbutnot\n" ) ;
  8104. next ;
  8105. }
  8106. my $res = $sync->{dry} ; # always success in dry mode!
  8107. $imap2->unsubscribe( $folder ) if ( ! $sync->{dry} ) ;
  8108. $res = $imap2->delete( $folder ) if ( ! $sync->{dry} ) ;
  8109. if ( $res ) {
  8110. myprint( "Deleted $folder", "$sync->{dry_message}", "\n" ) ;
  8111. }else{
  8112. myprint( "Deleting $folder failed", "\n" ) ;
  8113. }
  8114. }
  8115. return ;
  8116. }
  8117. sub delete_folder {
  8118. my ( $mysync, $imap, $folder, $Side ) = @_ ;
  8119. if ( ! $mysync ) { return ; }
  8120. if ( ! $imap ) { return ; }
  8121. if ( ! $folder ) { return ; }
  8122. $Side ||= 'HostX' ;
  8123. my $res = $mysync->{dry} ; # always success in dry mode!
  8124. if ( ! $mysync->{dry} ) {
  8125. $imap->unsubscribe( $folder ) ;
  8126. $res = $imap->delete( $folder ) ;
  8127. }
  8128. if ( $res ) {
  8129. myprint( "$Side deleted $folder", $mysync->{dry_message}, "\n" ) ;
  8130. return 1 ;
  8131. }else{
  8132. myprint( "$Side deleting $folder failed", "\n" ) ;
  8133. return ;
  8134. }
  8135. }
  8136. sub delete1emptyfolders {
  8137. my $mysync = shift ;
  8138. if ( ! $mysync ) { return ; } # abort if no parameter
  8139. if ( ! $mysync->{delete1emptyfolders} ) { return ; } # abort if --delete1emptyfolders off
  8140. my $imap = $mysync->{imap1} ;
  8141. if ( ! $imap ) { return ; } # abort if no imap
  8142. if ( $imap->IsUnconnected( ) ) { return ; } # abort if disconnected
  8143. my %folders_kept ;
  8144. myprint( qq{Host1 deleting empty folders\n} ) ;
  8145. foreach my $folder ( reverse sort @{ $mysync->{h1_folders_wanted} } ) {
  8146. my $parenthood = $imap->is_parent( $folder ) ;
  8147. if ( defined $parenthood and $parenthood ) {
  8148. myprint( "Host1 folder $folder has subfolders\n" ) ;
  8149. $folders_kept{ $folder }++ ;
  8150. next ;
  8151. }
  8152. my $nb_messages_select = examine_folder_and_count( $imap, $folder, 'Host1' ) ;
  8153. if ( ! defined $nb_messages_select ) { next ; } # Select failed => Neither continue nor keep this folder }
  8154. my $nb_messages_search = scalar( @{ $imap->messages( ) } ) ;
  8155. if ( 0 != $nb_messages_select and 0 != $nb_messages_search ) {
  8156. myprint( "Host1 folder $folder has messages: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  8157. $folders_kept{ $folder }++ ;
  8158. next ;
  8159. }
  8160. if ( 0 != $nb_messages_select + $nb_messages_search ) {
  8161. myprint( "Host1 folder $folder odd messages count: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  8162. $folders_kept{ $folder }++ ;
  8163. next ;
  8164. }
  8165. # Here we must have 0 messages by messages() aka "SEARCH ALL" and also "EXAMINE"
  8166. if ( uc $folder eq 'INBOX' ) {
  8167. myprint( "Host1 Not deleting $folder\n" ) ;
  8168. $folders_kept{ $folder }++ ;
  8169. next ;
  8170. }
  8171. myprint( "Host1 deleting empty folder $folder\n" ) ;
  8172. # can not delete a SELECTed or EXAMINEd folder so closing it
  8173. # could changed be SELECT INBOX
  8174. $imap->close( ) ; # close after examine does not expunge; anyway expunging an empty folder...
  8175. if ( delete_folder( $mysync, $imap, $folder, 'Host1' ) ) {
  8176. next ; # Deleted, good!
  8177. }else{
  8178. $folders_kept{ $folder }++ ;
  8179. next ; # Not deleted, bad!
  8180. }
  8181. }
  8182. remove_deleted_folders_from_wanted_list( $mysync, %folders_kept ) ;
  8183. myprint( qq{Host1 ended deleting empty folders\n} ) ;
  8184. return ;
  8185. }
  8186. sub remove_deleted_folders_from_wanted_list {
  8187. my ( $mysync, %folders_kept ) = @ARG ;
  8188. my @h1_folders_wanted_init = @{ $mysync->{h1_folders_wanted} } ;
  8189. my @h1_folders_wanted_last ;
  8190. foreach my $folder ( @h1_folders_wanted_init ) {
  8191. if ( $folders_kept{ $folder } ) {
  8192. push @h1_folders_wanted_last, $folder ;
  8193. }
  8194. }
  8195. @{ $mysync->{h1_folders_wanted} } = @h1_folders_wanted_last ;
  8196. return ;
  8197. }
  8198. sub examine_folder_and_count {
  8199. my ( $imap, $folder, $Side ) = @_ ;
  8200. $Side ||= 'HostX' ;
  8201. if ( ! examine_folder( $imap, $folder, $Side ) ) {
  8202. return ;
  8203. }
  8204. my $nb_messages_select = count_from_select( $imap->History ) ;
  8205. return $nb_messages_select ;
  8206. }
  8207. sub tests_delete1emptyfolders {
  8208. note( 'Entering tests_delete1emptyfolders()' ) ;
  8209. is( undef, delete1emptyfolders( ), q{delete1emptyfolders: undef} ) ;
  8210. my $syncT ;
  8211. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef 2} ) ;
  8212. my $imapT ;
  8213. $syncT->{imap1} = $imapT ;
  8214. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef imap} ) ;
  8215. require Test::MockObject ;
  8216. $imapT = Test::MockObject->new( ) ;
  8217. $syncT->{imap1} = $imapT ;
  8218. $imapT->set_true( 'IsUnconnected' ) ;
  8219. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: Unconnected imap} ) ;
  8220. # Now connected tests
  8221. $imapT->set_false( 'IsUnconnected' ) ;
  8222. $imapT->mock( 'LastError', sub { q{LastError mocked} } ) ;
  8223. $syncT->{delete1emptyfolders} = 0 ;
  8224. tests_delete1emptyfolders_unit(
  8225. $syncT,
  8226. [ qw{ INBOX DELME1 DELME2 } ],
  8227. [ qw{ INBOX DELME1 DELME2 } ],
  8228. q{tests_delete1emptyfolders: --delete1emptyfolders OFF}
  8229. ) ;
  8230. # All are parents => no deletion at all
  8231. $imapT->set_true( 'is_parent' ) ;
  8232. $syncT->{delete1emptyfolders} = 1 ;
  8233. tests_delete1emptyfolders_unit(
  8234. $syncT,
  8235. [ qw{ INBOX DELME1 DELME2 } ],
  8236. [ qw{ INBOX DELME1 DELME2 } ],
  8237. q{tests_delete1emptyfolders: --delete1emptyfolders ON}
  8238. ) ;
  8239. # No parents but examine false for all => skip all
  8240. $imapT->set_false( 'is_parent', 'examine' ) ;
  8241. tests_delete1emptyfolders_unit(
  8242. $syncT,
  8243. [ qw{ INBOX DELME1 DELME2 } ],
  8244. [ ],
  8245. q{tests_delete1emptyfolders: EXAMINE fails}
  8246. ) ;
  8247. # examine ok for all but History bad => skip all
  8248. $imapT->set_true( 'examine' ) ;
  8249. $imapT->mock( 'History', sub { ( q{History badly mocked} ) } ) ;
  8250. tests_delete1emptyfolders_unit(
  8251. $syncT,
  8252. [ qw{ INBOX DELME1 DELME2 } ],
  8253. [ ],
  8254. q{tests_delete1emptyfolders: examine ok but History badly mocked so count messages fails}
  8255. ) ;
  8256. # History good but some messages EXISTS == messages() => no deletion
  8257. $imapT->mock( 'History', sub { ( q{* 2 EXISTS} ) } ) ;
  8258. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  8259. tests_delete1emptyfolders_unit(
  8260. $syncT,
  8261. [ qw{ INBOX DELME1 DELME2 } ],
  8262. [ qw{ INBOX DELME1 DELME2 } ],
  8263. q{tests_delete1emptyfolders: History EXAMINE ok, several messages}
  8264. ) ;
  8265. # 0 EXISTS but != messages() => no deletion
  8266. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  8267. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  8268. tests_delete1emptyfolders_unit(
  8269. $syncT,
  8270. [ qw{ INBOX DELME1 DELME2 } ],
  8271. [ qw{ INBOX DELME1 DELME2 } ],
  8272. q{tests_delete1emptyfolders: 0 EXISTS but 2 by messages()}
  8273. ) ;
  8274. # 1 EXISTS but != 0 == messages() => no deletion
  8275. $imapT->mock( 'History', sub { ( q{* 1 EXISTS} ) } ) ;
  8276. $imapT->mock( 'messages', sub { [ ] } ) ;
  8277. tests_delete1emptyfolders_unit(
  8278. $syncT,
  8279. [ qw{ INBOX DELME1 DELME2 } ],
  8280. [ qw{ INBOX DELME1 DELME2 } ],
  8281. q{tests_delete1emptyfolders: 1 EXISTS but 0 by messages()}
  8282. ) ;
  8283. # 0 EXISTS and 0 == messages() => deletion except INBOX
  8284. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  8285. $imapT->mock( 'messages', sub { [ ] } ) ;
  8286. $imapT->set_true( qw{ delete close unsubscribe } ) ;
  8287. $syncT->{dry_message} = q{ (not really since in a mocked test)} ;
  8288. tests_delete1emptyfolders_unit(
  8289. $syncT,
  8290. [ qw{ INBOX DELME1 DELME2 } ],
  8291. [ qw{ INBOX } ],
  8292. q{tests_delete1emptyfolders: 0 EXISTS 0 by messages() delete folders, keep INBOX}
  8293. ) ;
  8294. note( 'Leaving tests_delete1emptyfolders()' ) ;
  8295. return ;
  8296. }
  8297. sub tests_delete1emptyfolders_unit {
  8298. note( 'Entering tests_delete1emptyfolders_unit()' ) ;
  8299. my $syncT = shift ;
  8300. my $folders1wanted_init_ref = shift ;
  8301. my $folders1wanted_after_ref = shift ;
  8302. my $comment = shift || q{delete1emptyfolders:} ;
  8303. my @folders1wanted_init = @{ $folders1wanted_init_ref } ;
  8304. my @folders1wanted_after = @{ $folders1wanted_after_ref } ;
  8305. @{ $syncT->{h1_folders_wanted} } = @folders1wanted_init ;
  8306. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_init, qq{$comment, init check} ) ;
  8307. delete1emptyfolders( $syncT ) ;
  8308. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_after, qq{$comment, after check} ) ;
  8309. note( 'Leaving tests_delete1emptyfolders_unit()' ) ;
  8310. return ;
  8311. }
  8312. sub extract_header {
  8313. my $string = shift ;
  8314. my ( $header ) = split /\n\n/x, $string ;
  8315. if ( ! $header ) { return( q{} ) ; }
  8316. #myprint( "[$header]\n" ) ;
  8317. return( $header ) ;
  8318. }
  8319. sub tests_extract_header {
  8320. note( 'Entering tests_extract_header()' ) ;
  8321. my $h = <<'EOM';
  8322. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  8323. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  8324. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  8325. EOM
  8326. chomp $h ;
  8327. ok( $h eq extract_header(
  8328. <<'EOM'
  8329. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  8330. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  8331. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  8332. body
  8333. lalala
  8334. EOM
  8335. ), 'extract_header: 1') ;
  8336. note( 'Leaving tests_extract_header()' ) ;
  8337. return ;
  8338. }
  8339. sub decompose_header{
  8340. my $string = shift ;
  8341. # a hash, for a keyword header KEY value are list of strings [VAL1, VAL1_other, etc]
  8342. # Think of multiple "Received:" header lines.
  8343. my $header = { } ;
  8344. my ($key, $val ) ;
  8345. my @line = split /\n|\r\n/x, $string ;
  8346. foreach my $line ( @line ) {
  8347. #myprint( "DDD $line\n" ) ;
  8348. # End of header
  8349. last if ( $line =~ m{^$}xo ) ;
  8350. # Key: value
  8351. if ( $line =~ m/(^[^:]+):\s(.*)/xo ) {
  8352. $key = $1 ;
  8353. $val = $2 ;
  8354. $debugdev and myprint( "DDD KV [$key] [$val]\n" ) ;
  8355. push @{ $header->{ $key } }, $val ;
  8356. # blanc and value => value from previous line continues
  8357. }elsif( $line =~ m/^(\s+)(.*)/xo ) {
  8358. $val = $2 ;
  8359. $debugdev and myprint( "DDD V [$val]\n" ) ;
  8360. @{ $header->{ $key } }[ $LAST ] .= " $val" if $key ;
  8361. # dirty line?
  8362. }else{
  8363. next ;
  8364. }
  8365. }
  8366. #myprint( Data::Dumper->Dump( [ $header ] ) ) ;
  8367. return( $header ) ;
  8368. }
  8369. sub tests_decompose_header{
  8370. note( 'Entering tests_decompose_header()' ) ;
  8371. my $header_dec ;
  8372. $header_dec = decompose_header(
  8373. <<'EOH'
  8374. KEY_1: VAL_1
  8375. KEY_2: VAL_2
  8376. VAL_2_+
  8377. VAL_2_++
  8378. KEY_3: VAL_3
  8379. KEY_1: VAL_1_other
  8380. KEY_4: VAL_4
  8381. VAL_4_+
  8382. KEY_5 BLANC: VAL_5
  8383. KEY_6_BAD_BODY: VAL_6
  8384. EOH
  8385. ) ;
  8386. ok( 'VAL_3'
  8387. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: VAL_3' ) ;
  8388. ok( 'VAL_1'
  8389. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: VAL_1' ) ;
  8390. ok( 'VAL_1_other'
  8391. eq $header_dec->{ 'KEY_1' }[1], 'decompose_header: VAL_1_other' ) ;
  8392. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  8393. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: VAL_2 VAL_2_+ VAL_2_++' ) ;
  8394. ok( 'VAL_4 VAL_4_+'
  8395. eq $header_dec->{ 'KEY_4' }[0], 'decompose_header: VAL_4 VAL_4_+' ) ;
  8396. ok( ' VAL_5'
  8397. eq $header_dec->{ 'KEY_5 BLANC' }[0], 'decompose_header: KEY_5 BLANC' ) ;
  8398. ok( not( defined $header_dec->{ 'KEY_6_BAD_BODY' }[0] ), 'decompose_header: KEY_6_BAD_BODY' ) ;
  8399. $header_dec = decompose_header(
  8400. <<'EOH'
  8401. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  8402. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  8403. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  8404. EOH
  8405. ) ;
  8406. ok( '<20100428101817.A66CB162474E@plume.est.belle>'
  8407. eq $header_dec->{ 'Message-Id' }[0], 'decompose_header: 1' ) ;
  8408. $header_dec = decompose_header(
  8409. <<'EOH'
  8410. Return-Path: <gilles@louloutte.dyndns.org>
  8411. Received: by plume.est.belle (Postfix, from userid 1000)
  8412. id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)
  8413. Subject: test:eekahceishukohpe
  8414. EOH
  8415. ) ;
  8416. ok(
  8417. 'by plume.est.belle (Postfix, from userid 1000) id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)'
  8418. eq $header_dec->{ 'Received' }[0], 'decompose_header: 2' ) ;
  8419. $header_dec = decompose_header(
  8420. <<'EOH'
  8421. Received: from plume (localhost [127.0.0.1])
  8422. by plume.est.belle (Postfix) with ESMTP id C6EB73F6C9
  8423. for <gilles@localhost>; Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  8424. Received: from plume [192.168.68.7]
  8425. by plume with POP3 (fetchmail-6.3.6)
  8426. for <gilles@localhost> (single-drop); Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  8427. EOH
  8428. ) ;
  8429. ok(
  8430. '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)'
  8431. eq $header_dec->{ 'Received' }[0], 'decompose_header: 3' ) ;
  8432. ok(
  8433. '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)'
  8434. eq $header_dec->{ 'Received' }[1], 'decompose_header: 3' ) ;
  8435. # Bad header beginning with a blank character
  8436. $header_dec = decompose_header(
  8437. <<'EOH'
  8438. KEY_1: VAL_1
  8439. KEY_2: VAL_2
  8440. VAL_2_+
  8441. VAL_2_++
  8442. KEY_3: VAL_3
  8443. KEY_1: VAL_1_other
  8444. EOH
  8445. ) ;
  8446. ok( 'VAL_3'
  8447. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: Bad header VAL_3' ) ;
  8448. ok( 'VAL_1_other'
  8449. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: Bad header VAL_1_other' ) ;
  8450. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  8451. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: Bad header VAL_2 VAL_2_+ VAL_2_++' ) ;
  8452. note( 'Leaving tests_decompose_header()' ) ;
  8453. return ;
  8454. }
  8455. sub tests_epoch {
  8456. note( 'Entering tests_epoch()' ) ;
  8457. ok( '1282658400' eq epoch( '24-Aug-2010 16:00:00 +0200' ), 'epoch 24-Aug-2010 16:00:00 +0200 -> 1282658400' ) ;
  8458. ok( '1282658400' eq epoch( '24-Aug-2010 14:00:00 +0000' ), 'epoch 24-Aug-2010 14:00:00 +0000 -> 1282658400' ) ;
  8459. ok( '1282658400' eq epoch( '24-Aug-2010 12:00:00 -0200' ), 'epoch 24-Aug-2010 12:00:00 -0200 -> 1282658400' ) ;
  8460. ok( '1282658400' eq epoch( '24-Aug-2010 16:01:00 +0201' ), 'epoch 24-Aug-2010 16:01:00 +0201 -> 1282658400' ) ;
  8461. ok( '1282658400' eq epoch( '24-Aug-2010 14:01:00 +0001' ), 'epoch 24-Aug-2010 14:01:00 +0001 -> 1282658400' ) ;
  8462. ok( '1280671200' eq epoch( '1-Aug-2010 16:00:00 +0200' ), 'epoch 1-Aug-2010 16:00:00 +0200 -> 1280671200' ) ;
  8463. ok( '1280671200' eq epoch( '1-Aug-2010 14:00:00 +0000' ), 'epoch 1-Aug-2010 14:00:00 +0000 -> 1280671200' ) ;
  8464. ok( '1280671200' eq epoch( '1-Aug-2010 12:00:00 -0200' ), 'epoch 1-Aug-2010 12:00:00 -0200 -> 1280671200' ) ;
  8465. ok( '1280671200' eq epoch( '1-Aug-2010 16:01:00 +0201' ), 'epoch 1-Aug-2010 16:01:00 +0201 -> 1280671200' ) ;
  8466. ok( '1280671200' eq epoch( '1-Aug-2010 14:01:00 +0001' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  8467. is( '1280671200', epoch( '1-Aug-2010 14:01:00 +0001' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  8468. is( '946684800', epoch( '00-Jan-0000 00:00:00 +0000' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  8469. note( 'Leaving tests_epoch()' ) ;
  8470. return ;
  8471. }
  8472. sub epoch {
  8473. # incoming format:
  8474. # internal date 24-Aug-2010 16:00:00 +0200
  8475. # outgoing format: epoch
  8476. my $d = shift ;
  8477. return(q{}) if not defined $d;
  8478. my ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m ) ;
  8479. my $time ;
  8480. 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 ) {
  8481. #myprint( "internal: [$1][$2][$3][$4][$5][$6][$7][$8][$9]\n" ) ;
  8482. ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )
  8483. = ( $1, $2, $3, $4, $5, $6, $7, $8, $9 ) ;
  8484. #myprint( "( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )\n" ) ;
  8485. $sign = +1 if ( '+' eq $sign ) ;
  8486. $sign = $MINUS_ONE if ( '-' eq $sign ) ;
  8487. if ( 0 == $mday ) {
  8488. myprint( "buggy day in $d. Fixed to 01\n" ) ;
  8489. $mday = '01' ;
  8490. }
  8491. $time = timegm( $sec, $min, $hour, $mday, $month_abrev{$month}, $year )
  8492. - $sign * ( 3600 * $zone_h + 60 * $zone_m ) ;
  8493. #myprint( "$time ", scalar localtime($time), "\n");
  8494. }
  8495. return( $time ) ;
  8496. }
  8497. sub tests_add_header {
  8498. note( 'Entering tests_add_header()' ) ;
  8499. ok( 'Message-Id: <mistake@imapsync>' eq add_header(), 'add_header no arg' ) ;
  8500. ok( 'Message-Id: <123456789@imapsync>' eq add_header( '123456789' ), 'add_header 123456789' ) ;
  8501. note( 'Leaving tests_add_header()' ) ;
  8502. return ;
  8503. }
  8504. sub add_header {
  8505. my $header_uid = shift || 'mistake' ;
  8506. my $header_Message_Id = 'Message-Id: <' . $header_uid . '@imapsync>' ;
  8507. return( $header_Message_Id ) ;
  8508. }
  8509. sub tests_max_line_length {
  8510. note( 'Entering tests_max_line_length()' ) ;
  8511. ok( 0 == max_line_length( q{} ), 'max_line_length: 0 == null string' ) ;
  8512. ok( 1 == max_line_length( "\n" ), 'max_line_length: 1 == \n' ) ;
  8513. ok( 1 == max_line_length( "\n\n" ), 'max_line_length: 1 == \n\n' ) ;
  8514. ok( 1 == max_line_length( "\n" x 500 ), 'max_line_length: 1 == 500 \n' ) ;
  8515. ok( 1 == max_line_length( 'a' ), 'max_line_length: 1 == a' ) ;
  8516. ok( 2 == max_line_length( "a\na" ), 'max_line_length: 2 == a\na' ) ;
  8517. ok( 2 == max_line_length( "a\na\n" ), 'max_line_length: 2 == a\na\n' ) ;
  8518. ok( 3 == max_line_length( "a\nab\n" ), 'max_line_length: 3 == a\nab\n' ) ;
  8519. ok( 3 == max_line_length( "a\nab\n" x 1_000 ), 'max_line_length: 3 == 1_000 a\nab\n' ) ;
  8520. ok( 3 == max_line_length( "a\nab\nabc" ), 'max_line_length: 3 == a\nab\nabc' ) ;
  8521. ok( 4 == max_line_length( "a\nab\nabc\n" ), 'max_line_length: 4 == a\nab\nabc\n' ) ;
  8522. ok( 5 == max_line_length( "a\nabcd\nabc\n" ), 'max_line_length: 5 == a\nabcd\nabc\n' ) ;
  8523. 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' ) ;
  8524. note( 'Leaving tests_max_line_length()' ) ;
  8525. return ;
  8526. }
  8527. sub max_line_length {
  8528. my $string = shift ;
  8529. my $max = 0 ;
  8530. while ( $string =~ m/([^\n]*\n?)/msxg ) {
  8531. $max = max( $max, length $1 ) ;
  8532. }
  8533. return( $max ) ;
  8534. }
  8535. sub tests_setlogfile {
  8536. note( 'Entering tests_setlogfile()' ) ;
  8537. my $mysync = {} ;
  8538. $mysync->{logdir} = 'vallogdir' ;
  8539. $mysync->{logfile} = 'vallogfile.txt' ;
  8540. is( 'vallogdir/vallogfile.txt', setlogfile( $mysync ),
  8541. 'setlogfile: logdir vallogdir, logfile vallogfile.txt, vallogdir/vallogfile.txt' ) ;
  8542. SKIP: {
  8543. skip( 'Too hard to have a well known timezone on Windows', 9 ) if ( 'MSWin32' eq $OSNAME ) ;
  8544. local $ENV{TZ} = 'GMT' ;
  8545. $mysync = {
  8546. timestart => 2,
  8547. } ;
  8548. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000__.txt", setlogfile( $mysync ),
  8549. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000__.txt" ) ;
  8550. $mysync = {
  8551. timestart => 2,
  8552. user1 => 'user1',
  8553. user2 => 'user2',
  8554. abort => 1,
  8555. } ;
  8556. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_abort.txt", setlogfile( $mysync ),
  8557. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_abort.txt" ) ;
  8558. $mysync = {
  8559. timestart => 2,
  8560. user1 => 'user1',
  8561. user2 => 'user2',
  8562. remote => 'zzz',
  8563. } ;
  8564. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote.txt", setlogfile( $mysync ),
  8565. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote.txt" ) ;
  8566. $mysync = {
  8567. timestart => 2,
  8568. user1 => 'user1',
  8569. user2 => 'user2',
  8570. remote => 'zzz',
  8571. abort => 1,
  8572. } ;
  8573. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote_abort.txt", setlogfile( $mysync ),
  8574. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote_abort.txt" ) ;
  8575. $mysync = {
  8576. timestart => 2,
  8577. user1 => 'user1',
  8578. user2 => 'user2',
  8579. } ;
  8580. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt", setlogfile( $mysync ),
  8581. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt" ) ;
  8582. $mysync->{logdir} = undef ;
  8583. $mysync->{logfile} = undef ;
  8584. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt", setlogfile( $mysync ),
  8585. "setlogfile: logdir undef, $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt" ) ;
  8586. $mysync->{logdir} = q{} ;
  8587. $mysync->{logfile} = undef ;
  8588. is( '1970_01_01_00_00_02_000_user1_user2.txt', setlogfile( $mysync ),
  8589. 'setlogfile: logdir empty, 1970_01_01_00_00_02_000_user1_user2.txt' ) ;
  8590. $mysync->{logdir} = 'vallogdir' ;
  8591. $mysync->{logfile} = undef ;
  8592. is( 'vallogdir/1970_01_01_00_00_02_000_user1_user2.txt', setlogfile( $mysync ),
  8593. 'setlogfile: logdir vallogdir, vallogdir/1970_01_01_00_00_02_000_user1_user2.txt' ) ;
  8594. $mysync = {
  8595. user1 => 'us/er1a*|?:"<>b',
  8596. user2 => 'u/ser2a*|?:"<>b',
  8597. } ;
  8598. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_00_000_us_er1a_______b_u_ser2a_______b.txt", setlogfile( $mysync ),
  8599. "setlogfile: logdir undef, $DEFAULT_LOGDIR/1970_01_01_00_00_00_000_us_er1a_______b_u_ser2a_______b.txt" ) ;
  8600. } ;
  8601. note( 'Leaving tests_setlogfile()' ) ;
  8602. return ;
  8603. }
  8604. sub setlogfile {
  8605. my( $mysync ) = shift ;
  8606. # When aborting another process the log file name finishes with "_abort.txt"
  8607. my $abort_suffix = ( $mysync->{abort} ) ? '_abort' : q{} ;
  8608. # When acting as a proxy the log file name finishes with "_remote.txt"
  8609. # proxy mode is not done yet
  8610. my $remote_suffix = ( $mysync->{remote} ) ? '_remote' : q{} ;
  8611. my $suffix = ( filter_forbidden_characters( move_slash( $mysync->{user1} ) ) || q{} )
  8612. . '_'
  8613. . ( filter_forbidden_characters( move_slash( $mysync->{user2} ) ) || q{} )
  8614. . $remote_suffix . $abort_suffix ;
  8615. $mysync->{logdir} = defined $mysync->{logdir} ? $mysync->{logdir} : $DEFAULT_LOGDIR ;
  8616. $mysync->{logfile} = defined $mysync->{logfile}
  8617. ? "$mysync->{logdir}/$mysync->{logfile}"
  8618. : logfile( $mysync->{timestart}, $suffix, $mysync->{logdir} ) ;
  8619. return( $mysync->{logfile} ) ;
  8620. }
  8621. sub tests_logfile {
  8622. note( 'Entering tests_logfile()' ) ;
  8623. SKIP: {
  8624. # Too hard to have a well known timezone on Windows
  8625. skip( 'Too hard to have a well known timezone on Windows', 10 ) if ( 'MSWin32' eq $OSNAME ) ;
  8626. local $ENV{TZ} = 'GMT' ;
  8627. { POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  8628. is( '1970_01_01_00_00_00_000.txt', logfile( ), 'logfile: no args => 1970_01_01_00_00_00.txt' ) ;
  8629. is( '1970_01_01_00_00_00_000.txt', logfile( 0 ), 'logfile: 0 => 1970_01_01_00_00_00.txt' ) ;
  8630. is( '1970_01_01_00_01_01_000.txt', logfile( 61 ), 'logfile: 0 => 1970_01_01_00_01_01.txt' ) ;
  8631. is( '1970_01_01_00_01_01_234.txt', logfile( 61.234 ), 'logfile: 0 => 1970_01_01_00_01_01.txt' ) ;
  8632. is( '2010_08_24_14_00_00_000.txt', logfile( 1_282_658_400 ), 'logfile: 1_282_658_400 => 2010_08_24_14_00_00.txt' ) ;
  8633. is( '2010_08_24_14_01_01_000.txt', logfile( 1_282_658_461 ), 'logfile: 1_282_658_461 => 2010_08_24_14_01_01.txt' ) ;
  8634. is( '2010_08_24_14_01_01_000_poupinette.txt', logfile( 1_282_658_461, 'poupinette' ), 'logfile: 1_282_658_461 poupinette => 2010_08_24_14_01_01_poupinette.txt' ) ;
  8635. is( '2010_08_24_14_01_01_000_removeblanks.txt', logfile( 1_282_658_461, ' remove blanks ' ), 'logfile: 1_282_658_461 remove blanks => 2010_08_24_14_01_01_000_removeblanks' ) ;
  8636. is( '2010_08_24_14_01_01_234_poup.txt', logfile( 1_282_658_461.2347, 'poup' ),
  8637. 'logfile: 1_282_658_461.2347 poup => 2010_08_24_14_01_01_234_poup.txt' ) ;
  8638. is( 'dirdir/2010_08_24_14_01_01_234_poup.txt', logfile( 1_282_658_461.2347, 'poup', 'dirdir' ),
  8639. 'logfile: 1_282_658_461.2347 poup dirdir => dirdir/2010_08_24_14_01_01_234_poup.txt' ) ;
  8640. }
  8641. POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  8642. } ;
  8643. note( 'Leaving tests_logfile()' ) ;
  8644. return ;
  8645. }
  8646. sub logfile {
  8647. my ( $time, $suffix, $dir ) = @_ ;
  8648. $time ||= 0 ;
  8649. $suffix ||= q{} ;
  8650. $suffix =~ tr/ //ds ;
  8651. my $sep_suffix = ( $suffix ) ? '_' : q{} ;
  8652. $dir ||= q{} ;
  8653. my $sep_dir = ( $dir ) ? '/' : q{} ;
  8654. my $date_str = POSIX::strftime( '%Y_%m_%d_%H_%M_%S', localtime $time ) ;
  8655. # Because of ab tests or web access, more than one sync withing one second is possible
  8656. # so we add also milliseconds
  8657. $date_str .= sprintf "_%03d", ($time - int( $time ) ) * 1000 ; # without rounding
  8658. my $logfile = "${dir}${sep_dir}${date_str}${sep_suffix}${suffix}.txt" ;
  8659. return( $logfile ) ;
  8660. }
  8661. sub tests_move_slash {
  8662. note( 'Entering tests_move_slash()' ) ;
  8663. is( undef, move_slash( ), 'move_slash: no parameters => undef' ) ;
  8664. is( '_', move_slash( '/' ), 'move_slash: / => _' ) ;
  8665. is( '_abc_def_', move_slash( '/abc/def/' ), 'move_slash: /abc/def/ => _abc_def_' ) ;
  8666. note( 'Leaving tests_move_slash()' ) ;
  8667. return ;
  8668. }
  8669. sub move_slash {
  8670. my $string = shift ;
  8671. if ( ! defined $string ) { return ; }
  8672. $string =~ tr{/}{_} ;
  8673. return( $string ) ;
  8674. }
  8675. sub tests_million_folders_baby_2 {
  8676. note( 'Entering tests_million_folders_baby_2()' ) ;
  8677. my %long ;
  8678. @long{ 1 .. 900_000 } = (1) x 900_000 ;
  8679. #myprint( %long, "\n" ) ;
  8680. my $pasglop = 0 ;
  8681. foreach my $elem ( 1 .. 900_000 ) {
  8682. #$debug and myprint( "$elem " ) ;
  8683. if ( not exists $long{ $elem } ) {
  8684. $pasglop++ ;
  8685. }
  8686. }
  8687. ok( 0 == $pasglop, 'tests_million_folders_baby_2: search among 900_000' ) ;
  8688. # myprint( "$pasglop\n" ) ;
  8689. note( 'Leaving tests_million_folders_baby_2()' ) ;
  8690. return ;
  8691. }
  8692. sub tests_always_fail {
  8693. note( 'Entering tests_always_fail()' ) ;
  8694. is( 0, 1, 'always_fail: 0 is 1' ) ;
  8695. note( 'Leaving tests_always_fail()' ) ;
  8696. return ;
  8697. }
  8698. sub logfileprepa {
  8699. my $logfile = shift ;
  8700. my $dirname = dirname( $logfile ) ;
  8701. do_valid_directory( $dirname ) || return( 0 ) ;
  8702. return( 1 ) ;
  8703. }
  8704. sub teelaunch {
  8705. my $mysync = shift ;
  8706. my $logfile = $mysync->{logfile} ;
  8707. logfileprepa( $logfile ) || croak "Error no valid directory to write log file $logfile : $OS_ERROR" ;
  8708. open my $logfile_handle, '>', $logfile
  8709. or croak( "Can not open $logfile for write: $OS_ERROR" ) ;
  8710. my $tee = IO::Tee->new( $logfile_handle, \*STDOUT ) ;
  8711. #*STDERR = *$tee{IO} ;
  8712. #select $tee ;
  8713. $tee->autoflush( 1 ) ;
  8714. $mysync->{logfile_handle} = $logfile_handle ;
  8715. $mysync->{tee} = $tee ;
  8716. return $tee ;
  8717. }
  8718. sub getpwuid_any_os {
  8719. my $uid = shift ;
  8720. return( scalar getlogin ) if ( 'MSWin32' eq $OSNAME ) ; # Windows system
  8721. return( scalar getpwuid $uid ) ; # Unix system
  8722. }
  8723. sub simulong {
  8724. my $max_seconds = shift ;
  8725. my $division = 5 ;
  8726. my $last = $division * $max_seconds ;
  8727. foreach my $i ( 1 .. ( $last ) ) {
  8728. myprint( "Are you still here $i/$last\n" ) ;
  8729. #myprint( "Are you still here $i/$last\n" . ( "Ah" x 40 . "\n") x 4000 ) ;
  8730. sleep( 1 / $division ) ;
  8731. }
  8732. return ;
  8733. }
  8734. sub printenv {
  8735. myprint( "Environment variables listing:\n",
  8736. ( map { "$_ => $ENV{$_}\n" } sort keys %ENV),
  8737. "Environment variables listing end\n" ) ;
  8738. return ;
  8739. }
  8740. sub testsexit {
  8741. my $mysync = shift ;
  8742. if ( ! ( $mysync->{ tests } or $mysync->{ testsdebug } or $mysync->{ testsunit } ) ) {
  8743. return ;
  8744. }
  8745. my $test_builder = Test::More->builder ;
  8746. tests( $mysync ) ;
  8747. testsdebug( $mysync ) ;
  8748. testunitsession( $mysync ) ;
  8749. my @summary = $test_builder->summary() ;
  8750. my @details = $test_builder->details() ;
  8751. my $nb_tests_run = scalar( @summary ) ;
  8752. my $nb_tests_expected = $test_builder->expected_tests() ;
  8753. my $nb_tests_failed = count_0s( @summary ) ;
  8754. my $tests_failed = report_failures( @details ) ;
  8755. if ( $nb_tests_failed or ( $nb_tests_run != $nb_tests_expected ) ) {
  8756. #$test_builder->reset( ) ;
  8757. myprint( "Summary of tests: failed $nb_tests_failed tests, run $nb_tests_run tests, expected to run $nb_tests_expected tests.\n",
  8758. "List of failed tests:\n", $tests_failed ) ;
  8759. exit $EXIT_TESTS_FAILED ;
  8760. }
  8761. exit ;
  8762. #return ;
  8763. }
  8764. sub after_get_options {
  8765. my $mysync = shift ;
  8766. my $numopt = shift ;
  8767. # exit with --help option or no option at all
  8768. $debug and myprint( "numopt:$numopt\n" ) ;
  8769. if ( $help or not $numopt ) {
  8770. myprint( usage( $mysync ) ) ;
  8771. exit ;
  8772. }
  8773. return ;
  8774. }
  8775. sub easyany {
  8776. my $mysync = shift ;
  8777. # Gmail
  8778. if ( $mysync->{gmail1} and $mysync->{gmail2} ) {
  8779. $debug and myprint( "gmail1 gmail2\n") ;
  8780. gmail12( $mysync ) ;
  8781. return ;
  8782. }
  8783. if ( $mysync->{gmail1} ) {
  8784. $debug and myprint( "gmail1\n" ) ;
  8785. gmail1( $mysync ) ;
  8786. }
  8787. if ( $mysync->{gmail2} ) {
  8788. $debug and myprint( "gmail2\n" ) ;
  8789. gmail2( $mysync ) ;
  8790. }
  8791. # Office 365
  8792. if ( $mysync->{office1} ) {
  8793. office1( $mysync ) ;
  8794. }
  8795. if ( $mysync->{office2} ) {
  8796. office2( $mysync ) ;
  8797. }
  8798. # Domino
  8799. if ( $mysync->{domino1} ) {
  8800. domino1( $mysync ) ;
  8801. }
  8802. if ( $mysync->{domino2} ) {
  8803. domino2( $mysync ) ;
  8804. }
  8805. return ;
  8806. }
  8807. # From https://imapsync.lamiral.info/FAQ.d/FAQ.Gmail.txt
  8808. sub gmail12 {
  8809. my $mysync = shift ;
  8810. # Gmail at host1 and host2
  8811. $mysync->{host1} ||= 'imap.gmail.com' ;
  8812. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  8813. $mysync->{host2} ||= 'imap.gmail.com' ;
  8814. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  8815. $mysync->{maxbytespersecond} ||= 20_000 ; # should be 10_000 computed from by Gmail documentation
  8816. $mysync->{maxbytesafter} ||= 1_000_000_000 ;
  8817. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  8818. $mysync->{maxsleep} = $MAX_SLEEP ;
  8819. push @exclude, '\[Gmail\]$' ;
  8820. return ;
  8821. }
  8822. sub gmail1 {
  8823. my $mysync = shift ;
  8824. # Gmail at host2
  8825. $mysync->{host1} ||= 'imap.gmail.com' ;
  8826. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  8827. $mysync->{maxbytespersecond} ||= 40_000 ; # should be 20_000 computed from by Gmail documentation
  8828. $mysync->{maxbytesafter} ||= 2_500_000_000 ;
  8829. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  8830. $skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 1 ;
  8831. $mysync->{maxsleep} = $MAX_SLEEP ;
  8832. push @useheader, 'X-Gmail-Received', 'Message-Id' ;
  8833. push @regextrans2, 's,\[Gmail\].,,' ;
  8834. push @folderlast, '[Gmail]/All Mail' ;
  8835. return ;
  8836. }
  8837. sub gmail2 {
  8838. my $mysync = shift ;
  8839. # Gmail at host2
  8840. $mysync->{host2} ||= 'imap.gmail.com' ;
  8841. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  8842. $mysync->{maxbytespersecond} ||= 20_000 ; # should be 10_000 computed from by Gmail documentation
  8843. $mysync->{maxbytesafter} ||= 1_000_000_000 ; # In fact it is documented as half: 500_000_000
  8844. $maxsize ||= 25_000_000 ;
  8845. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  8846. $skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 1 ;
  8847. $expunge1 = ( defined $expunge1 ) ? $expunge1 : 1 ;
  8848. $mysync->{addheader} = ( defined $mysync->{addheader} ) ? $mysync->{addheader} : 1 ;
  8849. $mysync->{maxsleep} = $MAX_SLEEP ;
  8850. push @exclude, '\[Gmail\]$' ;
  8851. push @useheader, 'X-Gmail-Received', 'Message-Id' ;
  8852. push @regextrans2, 's,\[Gmail\].,,' ;
  8853. push @regextrans2, 's/[ ]+/_/g' ;
  8854. push @regextrans2, q{s/['\\^"]/_/g} ; # Verified this
  8855. push @folderlast, "[Gmail]/All Mail" ;
  8856. return ;
  8857. }
  8858. # From https://imapsync.lamiral.info/FAQ.d/FAQ.Exchange.txt
  8859. sub office1 {
  8860. # Office 365 at host1
  8861. my $mysync = shift ;
  8862. $debug and myprint( "office1 configuration\n" ) ;
  8863. $mysync->{host1} ||= 'outlook.office365.com' ;
  8864. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  8865. return ;
  8866. }
  8867. sub office2 {
  8868. # Office 365 at host1
  8869. my $mysync = shift ;
  8870. $mysync->{host2} ||= 'outlook.office365.com' ;
  8871. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  8872. $maxsize ||= 45_000_000 ;
  8873. $mysync->{maxmessagespersecond} ||= 4 ;
  8874. push @regexflag, 's/\\Flagged//g' ;
  8875. $disarmreadreceipts = ( defined $disarmreadreceipts ) ? $disarmreadreceipts : 1 ;
  8876. push @regexmess, 's,(.{10500}),$1\r\n,g' ;
  8877. return ;
  8878. }
  8879. sub exchange1 {
  8880. # Exchange 2010/2013 at host1
  8881. # Well nothing to do so far
  8882. return ;
  8883. }
  8884. sub exchange2 {
  8885. # Exchange 2010/2013 at host2
  8886. my $mysync = shift ;
  8887. $maxsize ||= 10_000_000 ;
  8888. $mysync->{maxmessagespersecond} ||= 4 ;
  8889. push @regexflag, 's/\\Flagged//g' ;
  8890. $disarmreadreceipts = ( defined $disarmreadreceipts ) ? $disarmreadreceipts : 1 ;
  8891. push @regexmess, 's,(.{10500}),$1\r\n,g' ;
  8892. return ;
  8893. }
  8894. sub domino1 {
  8895. # Domino at host1
  8896. my $mysync = shift ;
  8897. $sep1 = q{\\} ;
  8898. $prefix1 = q{} ;
  8899. $messageidnodomain = ( defined $messageidnodomain ) ? $messageidnodomain : 1 ;
  8900. return ;
  8901. }
  8902. sub domino2 {
  8903. # Domino at host1
  8904. my $mysync = shift ;
  8905. $sep2 = q{\\} ;
  8906. $prefix2 = q{} ;
  8907. $messageidnodomain = ( defined $messageidnodomain ) ? $messageidnodomain : 1 ;
  8908. push @regextrans2, 's,^Inbox\\\\(.*),$1,i' ;
  8909. return ;
  8910. }
  8911. sub tests_resolv {
  8912. note( 'Entering tests_resolv()' ) ;
  8913. # is( , resolv( ), 'resolv: => ' ) ;
  8914. is( undef, resolv( ), 'resolv: no args => undef' ) ;
  8915. is( undef, resolv( '' ), 'resolv: empty string => undef' ) ;
  8916. is( undef, resolv( 'hostnotexist' ), 'resolv: hostnotexist => undef' ) ;
  8917. is( '127.0.0.1', resolv( '127.0.0.1' ), 'resolv: 127.0.0.1 => 127.0.0.1' ) ;
  8918. is( '127.0.0.1', resolv( 'localhost' ), 'resolv: localhost => 127.0.0.1' ) ;
  8919. is( '5.135.158.182', resolv( 'imapsync.lamiral.info' ), 'resolv: imapsync.lamiral.info => 5.135.158.182' ) ;
  8920. # ip6-localhost ( in /etc/hosts )
  8921. is( '::1', resolv( 'ip6-localhost' ), 'resolv: ip6-localhost => ::1' ) ;
  8922. is( '::1', resolv( '::1' ), 'resolv: ::1 => ::1' ) ;
  8923. # ks2
  8924. is( '2001:41d0:8:d8b6::1', resolv( '2001:41d0:8:d8b6::1' ), 'resolv: 2001:41d0:8:d8b6::1 => 2001:41d0:8:d8b6::1' ) ;
  8925. is( '2001:41d0:8:d8b6::1', resolv( 'ks2ipv6.lamiral.info' ), 'resolv: ks2ipv6.lamiral.info => 2001:41d0:8:d8b6::1' ) ;
  8926. # ks3
  8927. is( '2001:41d0:8:bebd::1', resolv( '2001:41d0:8:bebd::1' ), 'resolv: 2001:41d0:8:bebd::1 => 2001:41d0:8:bebd::1' ) ;
  8928. is( '2001:41d0:8:bebd::1', resolv( 'ks3ipv6.lamiral.info' ), 'resolv: ks3ipv6.lamiral.info => 2001:41d0:8:bebd::1' ) ;
  8929. note( 'Leaving tests_resolv()' ) ;
  8930. return ;
  8931. }
  8932. sub resolv {
  8933. my $host = shift @ARG ;
  8934. if ( ! $host ) { return ; }
  8935. my $addr ;
  8936. if ( defined &Socket::getaddrinfo ) {
  8937. $addr = resolv_with_getaddrinfo( $host ) ;
  8938. return( $addr ) ;
  8939. }
  8940. my $iaddr = inet_aton( $host ) ;
  8941. if ( ! $iaddr ) { return ; }
  8942. $addr = inet_ntoa( $iaddr ) ;
  8943. return $addr ;
  8944. }
  8945. sub resolv_with_getaddrinfo {
  8946. my $host = shift @ARG ;
  8947. if ( ! $host ) { return ; }
  8948. my ( $err, @res ) = Socket::getaddrinfo( $host, "", { socktype => Socket::SOCK_RAW } ) ;
  8949. if ( $err ) {
  8950. myprint( "Cannot getaddrinfo of $host: $err\n" ) ;
  8951. return ;
  8952. }
  8953. my @addr ;
  8954. while( my $ai = shift @res ) {
  8955. my ( $err, $ipaddr ) = Socket::getnameinfo( $ai->{addr}, Socket::NI_NUMERICHOST(), Socket::NIx_NOSERV() ) ;
  8956. if ( $err ) {
  8957. myprint( "Cannot getnameinfo of $host: $err\n" ) ;
  8958. return ;
  8959. }
  8960. $debug and myprint( "$host => $ipaddr\n" ) ;
  8961. push @addr, $ipaddr ;
  8962. my ( $err_r, $reverse ) = Socket::getnameinfo( $ai->{addr}, 0, Socket::NIx_NOSERV() ) ;
  8963. $debug and myprint( "$host => $ipaddr => $reverse\n" ) ;
  8964. }
  8965. return $addr[0] ;
  8966. }
  8967. sub tests_resolvrev {
  8968. note( 'Entering tests_resolvrev()' ) ;
  8969. # is( , resolvrev( ), 'resolvrev: => ' ) ;
  8970. is( undef, resolvrev( ), 'resolvrev: no args => undef' ) ;
  8971. is( undef, resolvrev( '' ), 'resolvrev: empty string => undef' ) ;
  8972. is( undef, resolvrev( 'hostnotexist' ), 'resolvrev: hostnotexist => undef' ) ;
  8973. is( 'localhost', resolvrev( '127.0.0.1' ), 'resolvrev: 127.0.0.1 => localhost' ) ;
  8974. is( 'localhost', resolvrev( 'localhost' ), 'resolvrev: localhost => localhost' ) ;
  8975. is( 'ks.lamiral.info', resolvrev( 'imapsync.lamiral.info' ), 'resolvrev: imapsync.lamiral.info => ks.lamiral.info' ) ;
  8976. # ip6-localhost ( in /etc/hosts )
  8977. is( 'ip6-localhost', resolvrev( 'ip6-localhost' ), 'resolvrev: ip6-localhost => ip6-localhost' ) ;
  8978. is( 'ip6-localhost', resolvrev( '::1' ), 'resolvrev: ::1 => ip6-localhost' ) ;
  8979. # ks2
  8980. is( 'ks2ipv6.lamiral.info', resolvrev( '2001:41d0:8:d8b6::1' ), 'resolvrev: 2001:41d0:8:d8b6::1 => ks2ipv6.lamiral.info' ) ;
  8981. is( 'ks2ipv6.lamiral.info', resolvrev( 'ks2ipv6.lamiral.info' ), 'resolvrev: ks2ipv6.lamiral.info => ks2ipv6.lamiral.info' ) ;
  8982. # ks3
  8983. is( 'ks3ipv6.lamiral.info', resolvrev( '2001:41d0:8:bebd::1' ), 'resolvrev: 2001:41d0:8:bebd::1 => ks3ipv6.lamiral.info' ) ;
  8984. is( 'ks3ipv6.lamiral.info', resolvrev( 'ks3ipv6.lamiral.info' ), 'resolvrev: ks3ipv6.lamiral.info => ks3ipv6.lamiral.info' ) ;
  8985. note( 'Leaving tests_resolvrev()' ) ;
  8986. return ;
  8987. }
  8988. sub resolvrev {
  8989. my $host = shift @ARG ;
  8990. if ( ! $host ) { return ; }
  8991. if ( defined &Socket::getaddrinfo ) {
  8992. my $name = resolvrev_with_getaddrinfo( $host ) ;
  8993. return( $name ) ;
  8994. }
  8995. return ;
  8996. }
  8997. sub resolvrev_with_getaddrinfo {
  8998. my $host = shift @ARG ;
  8999. if ( ! $host ) { return ; }
  9000. my ( $err, @res ) = Socket::getaddrinfo( $host, "", { socktype => Socket::SOCK_RAW } ) ;
  9001. if ( $err ) {
  9002. myprint( "Cannot getaddrinfo of $host: $err\n" ) ;
  9003. return ;
  9004. }
  9005. my @name ;
  9006. while( my $ai = shift @res ) {
  9007. my ( $err, $reverse ) = Socket::getnameinfo( $ai->{addr}, 0, Socket::NIx_NOSERV() ) ;
  9008. if ( $err ) {
  9009. myprint( "Cannot getnameinfo of $host: $err\n" ) ;
  9010. return ;
  9011. }
  9012. $debug and myprint( "$host => $reverse\n" ) ;
  9013. push @name, $reverse ;
  9014. }
  9015. return $name[0] ;
  9016. }
  9017. sub tests_imapsping {
  9018. note( 'Entering tests_imapsping()' ) ;
  9019. is( undef, imapsping( ), 'imapsping: no args => undef' ) ;
  9020. is( undef, imapsping( 'hostnotexist' ), 'imapsping: hostnotexist => undef' ) ;
  9021. is( 1, imapsping( 'imapsync.lamiral.info' ), 'imapsping: imapsync.lamiral.info => 1' ) ;
  9022. is( 1, imapsping( 'ks2ipv6.lamiral.info' ), 'imapsping: ks2ipv6.lamiral.info => 1' ) ;
  9023. note( 'Leaving tests_imapsping()' ) ;
  9024. return ;
  9025. }
  9026. sub imapsping {
  9027. my $host = shift ;
  9028. return tcpping( $host, $IMAP_SSL_PORT ) ;
  9029. }
  9030. sub tests_tcpping {
  9031. note( 'Entering tests_tcpping()' ) ;
  9032. is( undef, tcpping( ), 'tcpping: no args => undef' ) ;
  9033. is( undef, tcpping( 'hostnotexist' ), 'tcpping: one arg => undef' ) ;
  9034. is( undef, tcpping( undef, 888 ), 'tcpping: arg undef, port => undef' ) ;
  9035. is( undef, tcpping( 'hostnotexist', 993 ), 'tcpping: hostnotexist 993 => undef' ) ;
  9036. is( undef, tcpping( 'hostnotexist', 888 ), 'tcpping: hostnotexist 888 => undef' ) ;
  9037. is( 1, tcpping( 'imapsync.lamiral.info', 993 ), 'tcpping: imapsync.lamiral.info 993 => 1' ) ;
  9038. is( 0, tcpping( 'imapsync.lamiral.info', 888 ), 'tcpping: imapsync.lamiral.info 888 => 0' ) ;
  9039. is( 1, tcpping( '5.135.158.182', 993 ), 'tcpping: 5.135.158.182 993 => 1' ) ;
  9040. is( 0, tcpping( '5.135.158.182', 888 ), 'tcpping: 5.135.158.182 888 => 0' ) ;
  9041. # Net::Ping supports ipv6 only after release 1.50
  9042. # http://cpansearch.perl.org/src/RURBAN/Net-Ping-2.59/Changes
  9043. # Anyway I plan to avoid Net-Ping for that too long standing feature
  9044. # Net-Ping is integrated in Perl itself, who knows ipv6 for a long time
  9045. is( 1, tcpping( '2001:41d0:8:d8b6::1', 993 ), 'tcpping: 2001:41d0:8:d8b6::1 993 => 1' ) ;
  9046. is( 0, tcpping( '2001:41d0:8:d8b6::1', 888 ), 'tcpping: 2001:41d0:8:d8b6::1 888 => 0' ) ;
  9047. note( 'Leaving tests_tcpping()' ) ;
  9048. return ;
  9049. }
  9050. sub tcpping {
  9051. if ( 2 != scalar( @ARG ) ) {
  9052. return ;
  9053. }
  9054. my ( $host, $port ) = @ARG ;
  9055. if ( ! $host ) { return ; }
  9056. if ( ! $port ) { return ; }
  9057. my $mytimeout = $TCP_PING_TIMEOUT ;
  9058. require Net::Ping ;
  9059. #my $p = Net::Ping->new( 'tcp' ) ;
  9060. my $p = Net::Ping->new( ) ;
  9061. $p->{port_num} = $port ;
  9062. $p->service_check( 1 ) ;
  9063. $p->hires( 1 ) ;
  9064. my ($ping_ok, $rtt, $ip ) = $p->ping( $host, $mytimeout ) ;
  9065. if ( ! defined $ping_ok ) { return ; }
  9066. my $rtt_approx = sprintf( "%.3f", $rtt ) ;
  9067. $debug and myprint( "Host $host timeout $mytimeout port $port ok $ping_ok ip $ip acked in $rtt_approx s\n" ) ;
  9068. $p->close( ) ;
  9069. if( $ping_ok ) {
  9070. return 1 ;
  9071. }else{
  9072. return 0 ;
  9073. }
  9074. }
  9075. sub tests_sslcheck {
  9076. note( 'Entering tests_sslcheck()' ) ;
  9077. my $mysync ;
  9078. is( undef, sslcheck( $mysync ), 'sslcheck: no sslcheck => undef' ) ;
  9079. $mysync = {
  9080. sslcheck => 1,
  9081. } ;
  9082. is( 0, sslcheck( $mysync ), 'sslcheck: no host => 0' ) ;
  9083. $mysync = {
  9084. sslcheck => 1,
  9085. host1 => 'imapsync.lamiral.info',
  9086. tls1 => 1,
  9087. } ;
  9088. is( 0, sslcheck( $mysync ), 'sslcheck: tls1 => 0' ) ;
  9089. $mysync = {
  9090. sslcheck => 1,
  9091. host1 => 'imapsync.lamiral.info',
  9092. } ;
  9093. is( 1, sslcheck( $mysync ), 'sslcheck: imapsync.lamiral.info => 1' ) ;
  9094. is( 1, $mysync->{ssl1}, 'sslcheck: imapsync.lamiral.info => ssl1 1' ) ;
  9095. $mysync->{sslcheck} = 0 ;
  9096. is( undef, sslcheck( $mysync ), 'sslcheck: sslcheck off => undef' ) ;
  9097. $mysync = {
  9098. sslcheck => 1,
  9099. host1 => 'imapsync.lamiral.info',
  9100. host2 => 'test2.lamiral.info',
  9101. } ;
  9102. is( 2, sslcheck( $mysync ), 'sslcheck: imapsync.lamiral.info + test2.lamiral.info => 2' ) ;
  9103. $mysync = {
  9104. sslcheck => 1,
  9105. host1 => 'imapsync.lamiral.info',
  9106. host2 => 'test2.lamiral.info',
  9107. tls1 => 1,
  9108. } ;
  9109. is( 1, sslcheck( $mysync ), 'sslcheck: imapsync.lamiral.info + test2.lamiral.info + tls1 => 1' ) ;
  9110. note( 'Leaving tests_sslcheck()' ) ;
  9111. return ;
  9112. }
  9113. sub sslcheck {
  9114. my $mysync = shift ;
  9115. if ( ! $mysync->{sslcheck} ) {
  9116. return ;
  9117. }
  9118. my $nb_on = 0 ;
  9119. $debug and myprint( "sslcheck\n" ) ;
  9120. if (
  9121. ( ! defined $mysync->{port1} )
  9122. and
  9123. ( ! defined $mysync->{tls1} )
  9124. and
  9125. ( ! defined $mysync->{ssl1} )
  9126. and
  9127. ( defined $mysync->{host1} )
  9128. ) {
  9129. myprint( "Host1: probing ssl on port $IMAP_SSL_PORT ( use --nosslcheck to avoid this ssl probe ) \n" ) ;
  9130. if ( probe_imapssl( $mysync->{host1} ) ) {
  9131. $mysync->{ssl1} = 1 ;
  9132. myprint( "Host1: sslcheck detected open ssl port $IMAP_SSL_PORT so turning ssl on (use --nossl1 --notls1 to turn off SSL and TLS wizardry)\n" ) ;
  9133. $nb_on++ ;
  9134. }else{
  9135. myprint( "Host1: sslcheck did not detected open ssl port $IMAP_SSL_PORT. Will use standard $IMAP_PORT port.\n" ) ;
  9136. }
  9137. }
  9138. if (
  9139. ( ! defined $mysync->{port2} )
  9140. and
  9141. ( ! defined $mysync->{tls2} )
  9142. and
  9143. ( ! defined $mysync->{ssl2} )
  9144. and
  9145. ( defined $mysync->{host2} )
  9146. ) {
  9147. myprint( "Host2: probing ssl on port $IMAP_SSL_PORT ( use --nosslcheck to avoid this ssl probe ) \n" ) ;
  9148. if ( probe_imapssl( $mysync->{host2} ) ) {
  9149. $mysync->{ssl2} = 1 ;
  9150. myprint( "Host2: sslcheck detected open ssl port $IMAP_SSL_PORT so turning ssl on (use --nossl2 --notls2 to turn off SSL and TLS wizardry)\n" ) ;
  9151. $nb_on++ ;
  9152. }else{
  9153. myprint( "Host2: sslcheck did not detected open ssl port $IMAP_SSL_PORT. Will use standard $IMAP_PORT port.\n" ) ;
  9154. }
  9155. }
  9156. return $nb_on ;
  9157. }
  9158. sub testslive {
  9159. my $mysync = shift ;
  9160. $mysync->{host1} = 'test1.lamiral.info' ;
  9161. $mysync->{user1} = 'test1' ;
  9162. $mysync->{password1} = 'secret1' ;
  9163. $mysync->{host2} = 'test2.lamiral.info' ;
  9164. $mysync->{user2} = 'test2' ;
  9165. $mysync->{password2} ='secret2' ;
  9166. return ;
  9167. }
  9168. sub testslive6 {
  9169. my $mysync = shift ;
  9170. $mysync->{host1} = 'ks2ipv6.lamiral.info' ;
  9171. $mysync->{user1} = 'test1' ;
  9172. $mysync->{password1} = 'secret1' ;
  9173. $mysync->{host2} = 'ks2ipv6.lamiral.info' ;
  9174. $mysync->{user2} = 'test2' ;
  9175. $mysync->{password2} ='secret2' ;
  9176. return ;
  9177. }
  9178. sub tests_backslash_caret {
  9179. note( 'Entering tests_backslash_caret()' ) ;
  9180. is( "lalala", backslash_caret( "lalala" ), 'backslash_caret: lalala => lalala' ) ;
  9181. is( "lalala\n", backslash_caret( "lalala\n" ), 'backslash_caret: lalala => lalala 2nd' ) ;
  9182. is( '^', backslash_caret( '\\' ), 'backslash_caret: \\ => ^' ) ;
  9183. is( "^\n", backslash_caret( "\\\n" ), 'backslash_caret: \\ => ^' ) ;
  9184. is( "\\lalala", backslash_caret( "\\lalala" ), 'backslash_caret: \\lalala => \\lalala' ) ;
  9185. is( "\\lal\\ala", backslash_caret( "\\lal\\ala" ), 'backslash_caret: \\lal\\ala => \\lal\\ala' ) ;
  9186. is( "\\lalala\n", backslash_caret( "\\lalala\n" ), 'backslash_caret: \\lalala => \\lalala 2nd' ) ;
  9187. is( "lalala^\n", backslash_caret( "lalala\\\n" ), 'backslash_caret: lalala\\\n => lalala^\n' ) ;
  9188. is( "lalala^\nlalala^\n", backslash_caret( "lalala\\\nlalala\\\n" ), 'backslash_caret: lalala\\\nlalala\\\n => lalala^\nlalala^\n' ) ;
  9189. is( "lal\\ala^\nlalala^\n", backslash_caret( "lal\\ala\\\nlalala\\\n" ), 'backslash_caret: lal\\ala\\\nlalala\\\n => lal\\ala^\nlalala^\n' ) ;
  9190. note( 'Leaving tests_backslash_caret()' ) ;
  9191. return ;
  9192. }
  9193. sub backslash_caret {
  9194. my $string = shift ;
  9195. $string =~ s{\\ $ }{^}gxms ;
  9196. return $string ;
  9197. }
  9198. sub tests_split_around_equal {
  9199. note( 'Entering tests_split_around_equal()' ) ;
  9200. is( undef, split_around_equal( ), 'split_around_equal: no args => undef' ) ;
  9201. is_deeply( { toto => 'titi' }, { split_around_equal( 'toto=titi' ) }, 'split_around_equal: toto=titi => toto => titi' ) ;
  9202. is_deeply( { A => 'B', C => 'D' }, { split_around_equal( 'A=B=C=D' ) }, 'split_around_equal: toto=titi => toto => titi' ) ;
  9203. is_deeply( { A => 'B', C => 'D' }, { split_around_equal( 'A=B', 'C=D' ) }, 'split_around_equal: A=B C=D => A => B, C=>D' ) ;
  9204. note( 'Leaving tests_split_around_equal()' ) ;
  9205. return ;
  9206. }
  9207. sub split_around_equal {
  9208. if ( ! @ARG ) { return ; } ;
  9209. return map { split /=/mxs, $_ } @ARG ;
  9210. }
  9211. sub tests_sig_install {
  9212. note( 'Entering tests_sig_install()' ) ;
  9213. my $mysync ;
  9214. is( undef, sig_install( ), 'sig_install: no args => undef' ) ;
  9215. is( undef, sig_install( $mysync ), 'sig_install: arg undef => undef' ) ;
  9216. $mysync = { } ;
  9217. is( undef, sig_install( $mysync ), 'sig_install: empty hash => undef' ) ;
  9218. SKIP: {
  9219. Readonly my $SKIP_15 => 15 ;
  9220. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests only for Unix', $SKIP_15 ) ; }
  9221. # Default to ignore USR1 USR2 in case future install fails
  9222. local $SIG{ USR1 } = local $SIG{ USR2 } = sub { } ;
  9223. kill( 'USR1', $PROCESS_ID ) ;
  9224. $mysync->{ debugsig } = 1 ;
  9225. # Assign USR1 to call sub tototo
  9226. # Surely a better value than undef should be returned when doing real signal stuff
  9227. is( undef, sig_install( $mysync, \&tototo, 'USR1' ), 'sig_install: USR1 tototo' ) ;
  9228. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 1' ) ;
  9229. is( 1, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 1' ) ;
  9230. # Assign USR2 to call sub tototo
  9231. is( undef, sig_install( $mysync, \&tototo, 'USR2' ), 'sig_install: USR2 tototo' ) ;
  9232. is( 1, kill( 'USR2', $PROCESS_ID ), 'sig_install: kill USR2 myself 1' ) ;
  9233. is( 2, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 2' ) ;
  9234. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 2' ) ;
  9235. is( 3, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 3' ) ;
  9236. local $SIG{ USR1 } = local $SIG{ USR2 } = sub { } ;
  9237. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 3' ) ;
  9238. is( 3, $mysync->{ tototo_calls }, 'sig_install: tototo call still nb 3' ) ;
  9239. # Assign USR1 + USR2 to call sub tototo
  9240. is( undef, sig_install( $mysync, \&tototo, 'USR1', 'USR2' ), 'sig_install: USR1 USR2 tototo' ) ;
  9241. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 4' ) ;
  9242. is( 4, $mysync->{ tototo_calls }, 'sig_install: tototo call now nb 4' ) ;
  9243. is( 1, kill( 'USR2', $PROCESS_ID ), 'sig_install: kill USR1 myself 2' ) ;
  9244. is( 5, $mysync->{ tototo_calls }, 'sig_install: tototo call now nb 5' ) ;
  9245. }
  9246. note( 'Leaving tests_sig_install()' ) ;
  9247. return ;
  9248. }
  9249. sub sig_install {
  9250. my $mysync = shift ;
  9251. if ( ! $mysync ) { return ; }
  9252. my $mysub = shift ;
  9253. if ( ! $mysub ) { return ; }
  9254. my @signals = @ARG ;
  9255. $mysync->{ debugsig } and myprint( "In sig_install with $mysync and $mysub\n" ) ;
  9256. my $subsignal = sub {
  9257. my $signame = shift ;
  9258. $mysync->{ debugsig } and myprint( "In subsignal with $signame and $mysync\n" ) ;
  9259. &$mysub( $mysync, $signame ) ;
  9260. } ;
  9261. foreach my $signal ( @signals ) {
  9262. $mysync->{ debugsig } and myprint( "Installing signal $signal for $subsignal\n") ;
  9263. output( $mysync, "kill -$signal $PROCESS_ID # special behavior\n" ) ;
  9264. $SIG{ $signal } = $subsignal ;
  9265. }
  9266. return ;
  9267. }
  9268. sub tototo {
  9269. my $mysync = shift ;
  9270. myprint("In tototo with @ARG\n" ) ;
  9271. $mysync->{ tototo_calls } += 1 ;
  9272. return ;
  9273. }
  9274. sub tests_toggle_sleep {
  9275. note( 'Entering tests_toggle_sleep()' ) ;
  9276. is( undef, toggle_sleep( ), 'toggle_sleep: no args => undef' ) ;
  9277. my $mysync ;
  9278. is( undef, toggle_sleep( $mysync ), 'toggle_sleep: undef => undef' ) ;
  9279. $mysync = { } ;
  9280. is( undef, toggle_sleep( $mysync ), 'toggle_sleep: no maxsleep => undef' ) ;
  9281. $mysync->{maxsleep} = 3 ;
  9282. is( 0, toggle_sleep( $mysync ), 'toggle_sleep: 3 => 0' ) ;
  9283. is( $MAX_SLEEP, toggle_sleep( $mysync ), "toggle_sleep: 0 => $MAX_SLEEP" ) ;
  9284. is( 0, toggle_sleep( $mysync ), "toggle_sleep: $MAX_SLEEP => 0" ) ;
  9285. is( $MAX_SLEEP, toggle_sleep( $mysync ), "toggle_sleep: 0 => $MAX_SLEEP" ) ;
  9286. is( 0, toggle_sleep( $mysync ), "toggle_sleep: $MAX_SLEEP => 0" ) ;
  9287. SKIP: {
  9288. Readonly my $SKIP_9 => 9 ;
  9289. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests only for Unix', $SKIP_9 ) ; }
  9290. # Default to ignore USR1 USR2 in case future install fails
  9291. local $SIG{ USR1 } = sub { } ;
  9292. kill( 'USR1', $PROCESS_ID ) ;
  9293. $mysync->{ debugsig } = 1 ;
  9294. # Assign USR1 to call sub toggle_sleep
  9295. is( undef, sig_install( $mysync, \&toggle_sleep, 'USR1' ), 'toggle_sleep: install USR1 toggle_sleep' ) ;
  9296. $mysync->{maxsleep} = 4 ;
  9297. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself' ) ;
  9298. is( 0, $mysync->{ maxsleep }, 'toggle_sleep: toggle_sleep called => sleeps are 0s' ) ;
  9299. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself again' ) ;
  9300. is( $MAX_SLEEP, $mysync->{ maxsleep }, "toggle_sleep: toggle_sleep called => sleeps are ${MAX_SLEEP}s" ) ;
  9301. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself' ) ;
  9302. is( 0, $mysync->{ maxsleep }, 'toggle_sleep: toggle_sleep called => sleeps are 0s' ) ;
  9303. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself again' ) ;
  9304. is( $MAX_SLEEP, $mysync->{ maxsleep }, "toggle_sleep: toggle_sleep called => sleeps are ${MAX_SLEEP}s" ) ;
  9305. }
  9306. note( 'Leaving tests_toggle_sleep()' ) ;
  9307. return ;
  9308. }
  9309. sub toggle_sleep {
  9310. my $mysync = shift ;
  9311. myprint("In toggle_sleep with @ARG\n" ) ;
  9312. if ( !defined( $mysync ) ) { return ; }
  9313. if ( !defined( $mysync->{maxsleep} ) ) { return ; }
  9314. $mysync->{ maxsleep } = max( 0, $MAX_SLEEP - $mysync->{maxsleep} ) ;
  9315. myprint("Resetting maxsleep to ", $mysync->{maxsleep}, "s\n" ) ;
  9316. return $mysync->{maxsleep} ;
  9317. }
  9318. sub mypod2usage {
  9319. my $fh_pod2usage = shift ;
  9320. pod2usage(
  9321. -exitval => 'NOEXIT',
  9322. -noperldoc => 1,
  9323. -verbose => 99,
  9324. -sections => [ qw(NAME VERSION USAGE OPTIONS) ],
  9325. -indent => 1,
  9326. -loose => 1,
  9327. -output => $fh_pod2usage,
  9328. ) ;
  9329. return ;
  9330. }
  9331. sub usage {
  9332. my $mysync = shift ;
  9333. if ( ! defined $mysync ) { return ; }
  9334. my $usage = q{} ;
  9335. my $usage_from_pod ;
  9336. my $usage_footer = usage_footer( $mysync ) ;
  9337. # pod2usage writes on a filehandle only and I want a variable
  9338. open my $fh_pod2usage, ">", \$usage_from_pod
  9339. or do { warn $OS_ERROR ; return ; } ;
  9340. mypod2usage( $fh_pod2usage ) ;
  9341. close $fh_pod2usage ;
  9342. if ( 'MSWin32' eq $OSNAME ) {
  9343. $usage_from_pod = backslash_caret( $usage_from_pod ) ;
  9344. }
  9345. $usage = join( q{}, $usage_from_pod, $usage_footer ) ;
  9346. return( $usage ) ;
  9347. }
  9348. sub tests_usage {
  9349. my $usage ;
  9350. like( $usage = usage( $sync ), qr/Name:/, 'usage: contains Name:' ) ;
  9351. myprint( $usage ) ;
  9352. like( $usage, qr/Version:/, 'usage: contains Version:' ) ;
  9353. like( $usage, qr/Usage:/, 'usage: contains Usage:' ) ;
  9354. like( $usage, qr/imapsync/, 'usage: contains imapsync' ) ;
  9355. is( undef, usage( ), 'usage: no args => undef' ) ;
  9356. return ;
  9357. }
  9358. sub usage_footer {
  9359. my $mysync = shift ;
  9360. my $footer = q{} ;
  9361. my $localhost_info = localhost_info( $mysync ) ;
  9362. my $rcs = $mysync->{rcs} ;
  9363. my $homepage = homepage( ) ;
  9364. my $imapsync_release = $STR_use_releasecheck ;
  9365. if ( $mysync->{releasecheck} ) {
  9366. $imapsync_release = check_last_release( ) ;
  9367. }
  9368. $footer = qq{$localhost_info
  9369. $rcs
  9370. $imapsync_release
  9371. $homepage
  9372. } ;
  9373. return( $footer ) ;
  9374. }
  9375. sub usage_complete {
  9376. # Unused, I guess this function could be deleted
  9377. my $usage = <<'EOF' ;
  9378. --skipheader reg : Don't take into account header keyword
  9379. matching reg ex: --skipheader 'X.*'
  9380. --skipsize : Don't take message size into account to compare
  9381. messages on both sides. On by default.
  9382. Use --no-skipsize for using size comparaison.
  9383. --allowsizemismatch : allow RFC822.SIZE != fetched msg size
  9384. consider also --skipsize to avoid duplicate messages
  9385. when running syncs more than one time per mailbox
  9386. --reconnectretry1 int : reconnect to host1 if connection is lost up to
  9387. int times per imap command (default is 3)
  9388. --reconnectretry2 int : same as --reconnectretry1 but for host2
  9389. --split1 int : split the requests in several parts on host1.
  9390. int is the number of messages handled per request.
  9391. default is like --split1 500.
  9392. --split2 int : same thing on host2.
  9393. --nofixInboxINBOX : Don't fix Inbox INBOX mapping.
  9394. EOF
  9395. return( $usage ) ;
  9396. }
  9397. sub myGetOptions {
  9398. # Started as a copy of Luke Ross Getopt::Long::CGI
  9399. # https://metacpan.org/release/Getopt-Long-CGI
  9400. # So this sub function is under the same license as Getopt-Long-CGI Luke Ross wants it,
  9401. # which was Perl 5.6 or later licenses at the date of the copy.
  9402. my $mysync = shift @ARG ;
  9403. my $arguments_ref = shift @ARG ;
  9404. my %options = @ARG ;
  9405. my $mycgi = $mysync->{cgi} ;
  9406. if ( not under_cgi_context() ) {
  9407. # Not CGI - pass upstream for normal command line handling
  9408. return Getopt::Long::GetOptionsFromArray( $arguments_ref, %options ) ;
  9409. }
  9410. # We must be in CGI context now
  9411. if ( !defined( $mycgi ) ) { return ; }
  9412. my $badthings = 0 ;
  9413. foreach my $key ( sort keys %options ) {
  9414. my $val = $options{$key} ;
  9415. if ( $key !~ m/^([\w\d\|]+)([=:][isf])?([\+!\@\%])?$/mxs ) {
  9416. $badthings++ ;
  9417. next ; # Unknown item
  9418. }
  9419. my $name = [ split '|', $1, 1 ]->[0] ;
  9420. if ( ( $3 || q{} ) eq '+' ) {
  9421. ${$val} = $mycgi->param( $name ) ; # "Incremental" integer
  9422. }
  9423. elsif ( $2 ) {
  9424. my @values = $mycgi->multi_param( $name ) ;
  9425. my $type = $2 ;
  9426. #myprint( "type[$type]values[@values]\$3[", $3 || q{}, "]val[$val]ref(val)[", ref($val), "]\n" ) ;
  9427. if ( ( $3 || q{} ) eq '%' or ref( $val ) eq 'HASH' ) {
  9428. my %values = map { split /=/mxs, $_ } @values ;
  9429. if ( $type =~ m/i$/mxs ) {
  9430. foreach my $k ( keys %values ) {
  9431. $values{$k} = int $values{$k} ;
  9432. }
  9433. }
  9434. elsif ( $type =~ m/f$/mxs ) {
  9435. foreach my $k ( keys %values ) {
  9436. $values{$k} = 0 + $values{$k};
  9437. }
  9438. }
  9439. if ( 'REF' eq ref $val ) {
  9440. %{ ${$val} } = %values ;
  9441. }
  9442. else {
  9443. %{$val} = %values ;
  9444. }
  9445. }
  9446. else {
  9447. if ( $type =~ m/i$/mxs ) {
  9448. @values = map { q{} ne $_ ? int $_ : undef } @values ;
  9449. }
  9450. elsif ( $type =~ m/f$/mxs ) {
  9451. @values = map { 0 + $_ } @values ;
  9452. }
  9453. if ( ( $3 || q{} ) eq '@' ) {
  9454. @{ ${$val} } = @values ;
  9455. }
  9456. elsif ( ref( $val ) eq 'ARRAY' ) {
  9457. @{$val} = @values ;
  9458. }
  9459. else {
  9460. ${$val} = $values[0] ;
  9461. }
  9462. }
  9463. }
  9464. else {
  9465. # Checkbox
  9466. # Considers only --name
  9467. # Should consider also --no-name and --noname
  9468. ${$val} = $mycgi->param( $name ) ? 1 : undef ;
  9469. }
  9470. }
  9471. if ( $badthings ) {
  9472. return ; # undef or ()
  9473. }
  9474. else {
  9475. return ( 1 ) ;
  9476. }
  9477. }
  9478. my @blabla ; # just used to check get_options_cgi() with an array
  9479. sub tests_get_options_cgi_context {
  9480. note( 'Entering tests_get_options_cgi()' ) ;
  9481. # Temporary, have to think harder about testing CGI context in command line --tests
  9482. # API:
  9483. # * input arguments: two ways, command line or CGI
  9484. # * the program arguments
  9485. # * QUERY_STRING env variable
  9486. # * return
  9487. # * QUERY_STRING length
  9488. # CGI context
  9489. local $ENV{SERVER_SOFTWARE} = 'Votre serviteur' ;
  9490. # Real full test
  9491. # = 'host1=test1.lamiral.info&user1=test1&password1=secret1&host2=test2.lamiral.info&user2=test2&password2=secret2&debugenv=on'
  9492. my $mysync ;
  9493. is( undef, get_options( $mysync ), 'get_options cgi context: no CGI module => undef' ) ;
  9494. require CGI ;
  9495. CGI->import( qw( -no_debug ) ) ;
  9496. is( undef, get_options( $mysync ), 'get_options cgi context: no CGI param => undef' ) ;
  9497. # Testing boolean
  9498. $mysync->{cgi} = CGI->new( 'version=on&debugenv=on' ) ;
  9499. local $ENV{'QUERY_STRING'} = 'version=on&debugenv=on' ;
  9500. is( 22, get_options( $mysync ), 'get_options cgi context: QUERY_STRING => 22' ) ;
  9501. is( 1, $mysync->{ version }, 'get_options cgi context: --version => 1' ) ;
  9502. # debugenv is not allowed in cgi context
  9503. is( undef, $mysync->{debugenv}, 'get_options cgi context: $mysync->{debugenv} => undef' ) ;
  9504. # QUERY_STRING in this test is only for return value of get_options
  9505. # Have to think harder, GET/POST context, is this return value a good thing?
  9506. local $ENV{'QUERY_STRING'} = 'host1=test1.lamiral.info&user1=test1' ;
  9507. $mysync->{cgi} = CGI->new( 'host1=test1.lamiral.info&user1=test1' ) ;
  9508. is( 36, get_options( $mysync, ), 'get_options cgi context: QUERY_STRING => 36' ) ;
  9509. is( 'test1', $mysync->{user1}, 'get_options cgi context: $mysync->{user1} => test1' ) ;
  9510. #local $ENV{'QUERY_STRING'} = undef ;
  9511. # Testing @
  9512. $mysync->{cgi} = CGI->new( 'blabla=fd1' ) ;
  9513. get_options( $mysync ) ;
  9514. is_deeply( [ 'fd1' ], [ @blabla ], 'get_options cgi context: @blabla => fd1' ) ;
  9515. $mysync->{cgi} = CGI->new( 'blabla=fd1&blabla=fd2' ) ;
  9516. get_options( $mysync ) ;
  9517. is_deeply( [ 'fd1', 'fd2' ], [ @blabla ], 'get_options cgi context: @blabla => fd1, fd2' ) ;
  9518. # Testing s@ as ref
  9519. $mysync->{cgi} = CGI->new( 'folder=fd1' ) ;
  9520. get_options( $mysync ) ;
  9521. is_deeply( [ 'fd1' ], $mysync->{folder}, 'get_options cgi context: $mysync->{folder} => fd1' ) ;
  9522. $mysync->{cgi} = CGI->new( 'folder=fd1&folder=fd2' ) ;
  9523. get_options( $mysync ) ;
  9524. is_deeply( [ 'fd1', 'fd2' ], $mysync->{folder}, 'get_options cgi context: $mysync->{folder} => fd1, fd2' ) ;
  9525. # Testing %
  9526. $mysync->{cgi} = CGI->new( 'f1f2h=s1=d1&f1f2h=s2=d2&f1f2h=s3=d3' ) ;
  9527. get_options( $mysync ) ;
  9528. is_deeply( { 's1' => 'd1', 's2' => 'd2', 's3' => 'd3' },
  9529. $mysync->{f1f2h}, 'get_options cgi context: f1f2h => s1=d1 s2=d2 s3=d3' ) ;
  9530. # Testing boolean ! with --noxxx, doesnot work
  9531. $mysync->{cgi} = CGI->new( 'nodry=on' ) ;
  9532. get_options( $mysync ) ;
  9533. is( undef, $mysync->{dry}, 'get_options cgi context: --nodry => $mysync->{dry} => undef' ) ;
  9534. $mysync->{cgi} = CGI->new( 'host1=example.com' ) ;
  9535. get_options( $mysync ) ;
  9536. is( 'example.com', $mysync->{host1}, 'get_options cgi context: --host1=example.com => $mysync->{host1} => example.com' ) ;
  9537. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  9538. $mysync->{cgi} = CGI->new( 'simulong=' ) ;
  9539. get_options( $mysync ) ;
  9540. is( undef, $mysync->{simulong}, 'get_options cgi context: --simulong= => $mysync->{simulong} => undef' ) ;
  9541. $mysync->{cgi} = CGI->new( 'simulong' ) ;
  9542. get_options( $mysync ) ;
  9543. is( undef, $mysync->{simulong}, 'get_options cgi context: --simulong => $mysync->{simulong} => undef' ) ;
  9544. $mysync->{cgi} = CGI->new( 'simulong=4' ) ;
  9545. get_options( $mysync ) ;
  9546. is( 4, $mysync->{simulong}, 'get_options cgi context: --simulong=4 => $mysync->{simulong} => 4' ) ;
  9547. is( undef, $mysync->{folder}, 'get_options cgi context: --simulong=4 => $mysync->{folder} => undef' ) ;
  9548. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  9549. note( 'Leaving tests_get_options_cgi_context()' ) ;
  9550. return ;
  9551. }
  9552. sub get_options_cgi {
  9553. # In CGI context arguments are not in @ARGV but in QUERY_STRING variable (with GET).
  9554. my $mysync = shift @ARG ;
  9555. $mysync->{cgi} || return ;
  9556. my @arguments = @ARG ;
  9557. # final 0 is used to print usage when no option is given
  9558. my $numopt = length $ENV{'QUERY_STRING'} || 1 ;
  9559. $mysync->{f1f2h} = {} ;
  9560. my $opt_ret = myGetOptions(
  9561. $mysync,
  9562. \@arguments,
  9563. 'abort' => \$mysync->{abort},
  9564. 'host1=s' => \$mysync->{host1},
  9565. 'host2=s' => \$mysync->{host2},
  9566. 'user1=s' => \$mysync->{user1},
  9567. 'user2=s' => \$mysync->{user2},
  9568. 'password1=s' => \$mysync->{password1},
  9569. 'password2=s' => \$mysync->{password2},
  9570. 'dry!' => \$mysync->{dry},
  9571. 'version' => \$mysync->{version},
  9572. 'ssl1!' => \$mysync->{ssl1},
  9573. 'ssl2!' => \$mysync->{ssl2},
  9574. 'tls1!' => \$mysync->{tls1},
  9575. 'tls2!' => \$mysync->{tls2},
  9576. 'justlogin!' => \$mysync->{justlogin},
  9577. 'justconnect!' => \$mysync->{justconnect},
  9578. 'addheader!' => \$mysync->{addheader},
  9579. 'automap!' => \$mysync->{automap},
  9580. 'justautomap!' => \$mysync->{justautomap},
  9581. 'gmail1' => \$mysync->{gmail1},
  9582. 'gmail2' => \$mysync->{gmail2},
  9583. 'office1' => \$mysync->{office1},
  9584. 'office2' => \$mysync->{office2},
  9585. 'exchange1' => \$mysync->{exchange1},
  9586. 'exchange2' => \$mysync->{exchange2},
  9587. 'domino1' => \$mysync->{domino1},
  9588. 'domino2' => \$mysync->{domino2},
  9589. 'f1f2=s@' => \$mysync->{f1f2},
  9590. 'f1f2h=s%' => \$mysync->{f1f2h},
  9591. 'folder=s@' => \$mysync->{folder},
  9592. 'blabla=s' => \@blabla,
  9593. 'testslive!' => \$mysync->{testslive},
  9594. 'testslive6!' => \$mysync->{testslive6},
  9595. 'releasecheck!' => \$mysync->{releasecheck},
  9596. 'simulong=i' => \$mysync->{simulong},
  9597. # blabla and f1f2h=s% could be removed but
  9598. # tests_get_options_cgi() should be split before
  9599. # with a sub tests_myGetOptions()
  9600. ) ;
  9601. $debug and output( $mysync, "get options: [$opt_ret][$numopt]\n" ) ;
  9602. if ( ! $opt_ret ) {
  9603. return ;
  9604. }
  9605. return $numopt ;
  9606. }
  9607. sub get_options_cmd {
  9608. my $mysync = shift @ARG ;
  9609. my @arguments = @ARG ;
  9610. my $mycgi = $mysync->{cgi} ;
  9611. # final 0 is used to print usage when no option is given on command line
  9612. my $numopt = scalar @arguments || 0 ;
  9613. my $argv = join "\x00", @arguments ;
  9614. if ( $argv =~ m/-delete\x002/x ) {
  9615. output( $mysync, "May be you mean --delete2 instead of --delete 2\n" ) ;
  9616. return ;
  9617. }
  9618. $mysync->{f1f2h} = {} ;
  9619. my $opt_ret = myGetOptions(
  9620. $mysync,
  9621. \@arguments,
  9622. 'debug!' => \$debug,
  9623. 'debuglist!' => \$debuglist,
  9624. 'debugcontent!' => \$debugcontent,
  9625. 'debugsleep=f' => \$mysync->{debugsleep},
  9626. 'debugflags!' => \$debugflags,
  9627. 'debugimap!' => \$debugimap,
  9628. 'debugimap1!' => \$debugimap1,
  9629. 'debugimap2!' => \$debugimap2,
  9630. 'debugdev!' => \$debugdev,
  9631. 'debugmemory!' => \$mysync->{debugmemory},
  9632. 'debugfolders!' => \$mysync->{debugfolders},
  9633. 'debugssl=i' => \$mysync->{debugssl},
  9634. 'debugcgi!' => \$debugcgi,
  9635. 'debugenv' => \$mysync->{debugenv},
  9636. 'debugsig' => \$mysync->{debugsig},
  9637. 'simulong=i' => \$mysync->{simulong},
  9638. 'abort' => \$mysync->{abort},
  9639. 'host1=s' => \$mysync->{host1},
  9640. 'host2=s' => \$mysync->{host2},
  9641. 'port1=i' => \$mysync->{port1},
  9642. 'port2=i' => \$mysync->{port2},
  9643. 'inet4|ipv4' => \$mysync->{inet4},
  9644. 'inet6|ipv6' => \$mysync->{inet6},
  9645. 'user1=s' => \$mysync->{user1},
  9646. 'user2=s' => \$mysync->{user2},
  9647. 'gmail1' => \$mysync->{gmail1},
  9648. 'gmail2' => \$mysync->{gmail2},
  9649. 'office1' => \$mysync->{office1},
  9650. 'office2' => \$mysync->{office2},
  9651. 'exchange1' => \$mysync->{exchange1},
  9652. 'exchange2' => \$mysync->{exchange2},
  9653. 'domino1' => \$mysync->{domino1},
  9654. 'domino2' => \$mysync->{domino2},
  9655. 'domain1=s' => \$domain1,
  9656. 'domain2=s' => \$domain2,
  9657. 'password1=s' => \$mysync->{password1},
  9658. 'password2=s' => \$mysync->{password2},
  9659. 'passfile1=s' => \$passfile1,
  9660. 'passfile2=s' => \$passfile2,
  9661. 'authmd5!' => \$authmd5,
  9662. 'authmd51!' => \$authmd51,
  9663. 'authmd52!' => \$authmd52,
  9664. 'sep1=s' => \$sep1,
  9665. 'sep2=s' => \$sep2,
  9666. 'folder=s@' => \$mysync->{folder},
  9667. 'folderrec=s' => \@folderrec,
  9668. 'include=s' => \@include,
  9669. 'exclude=s' => \@exclude,
  9670. 'folderfirst=s' => \@folderfirst,
  9671. 'folderlast=s' => \@folderlast,
  9672. 'prefix1=s' => \$prefix1,
  9673. 'prefix2=s' => \$prefix2,
  9674. 'subfolder2=s' => \$subfolder2,
  9675. 'fixslash2!' => \$fixslash2,
  9676. 'fixInboxINBOX!' => \$fixInboxINBOX,
  9677. 'regextrans2=s' => \@regextrans2,
  9678. 'mixfolders!' => \$mixfolders,
  9679. 'skipemptyfolders!' => \$skipemptyfolders,
  9680. 'regexmess=s' => \@regexmess,
  9681. 'skipmess=s' => \@skipmess,
  9682. 'pipemess=s' => \@pipemess,
  9683. 'pipemesscheck!' => \$pipemesscheck,
  9684. 'disarmreadreceipts!' => \$disarmreadreceipts,
  9685. 'regexflag=s' => \@regexflag,
  9686. 'filterflags!' => \$filterflags,
  9687. 'flagscase!' => \$flagscase,
  9688. 'syncflagsaftercopy!' => \$syncflagsaftercopy,
  9689. 'resyncflags!' => \$mysync->{resyncflags},
  9690. 'delete|delete1!' => \$delete1,
  9691. 'delete2!' => \$delete2,
  9692. 'delete2duplicates!' => \$delete2duplicates,
  9693. 'delete2folders!' => \$delete2folders,
  9694. 'delete2foldersonly=s' => \$delete2foldersonly,
  9695. 'delete2foldersbutnot=s' => \$delete2foldersbutnot,
  9696. 'syncinternaldates!' => \$syncinternaldates,
  9697. 'idatefromheader!' => \$idatefromheader,
  9698. 'syncacls!' => \$syncacls,
  9699. 'maxsize=i' => \$maxsize,
  9700. 'minsize=i' => \$minsize,
  9701. 'maxage=i' => \$maxage,
  9702. 'minage=i' => \$minage,
  9703. 'search=s' => \$search,
  9704. 'search1=s' => \$search1,
  9705. 'search2=s' => \$search2,
  9706. 'foldersizes!' => \$foldersizes,
  9707. 'foldersizesatend!' => \$foldersizesatend,
  9708. 'dry!' => \$mysync->{dry},
  9709. 'expunge1|expunge!' => \$expunge1,
  9710. 'expunge2!' => \$expunge2,
  9711. 'uidexpunge2!' => \$uidexpunge2,
  9712. 'subscribed!' => \$subscribed,
  9713. 'subscribe!' => \$subscribe,
  9714. 'subscribeall|subscribe_all!' => \$subscribeall,
  9715. 'justbanner!' => \$justbanner,
  9716. 'justfolders!'=> \$justfolders,
  9717. 'justfoldersizes!' => \$justfoldersizes,
  9718. 'fast!' => \$fast,
  9719. 'version' => \$mysync->{version},
  9720. 'help' => \$help,
  9721. 'timeout=i' => \$timeout,
  9722. 'timeout1=i' => \$mysync->{h1}->{timeout},
  9723. 'timeout2=i' => \$mysync->{h2}->{timeout},
  9724. 'skipheader=s' => \$skipheader,
  9725. 'useheader=s' => \@useheader,
  9726. 'wholeheaderifneeded!' => \$wholeheaderifneeded,
  9727. 'messageidnodomain!' => \$messageidnodomain,
  9728. 'skipsize!' => \$skipsize,
  9729. 'allowsizemismatch!' => \$allowsizemismatch,
  9730. 'fastio1!' => \$fastio1,
  9731. 'fastio2!' => \$fastio2,
  9732. 'sslcheck!' => \$mysync->{sslcheck},
  9733. 'ssl1!' => \$mysync->{ssl1},
  9734. 'ssl2!' => \$mysync->{ssl2},
  9735. 'ssl1_ssl_version=s' => \$mysync->{h1}->{sslargs}->{SSL_version},
  9736. 'ssl2_ssl_version=s' => \$mysync->{h2}->{sslargs}->{SSL_version},
  9737. 'sslargs1=s%' => \$mysync->{h1}->{sslargs},
  9738. 'sslargs2=s%' => \$mysync->{h2}->{sslargs},
  9739. 'tls1!' => \$mysync->{tls1},
  9740. 'tls2!' => \$mysync->{tls2},
  9741. 'uid1!' => \$uid1,
  9742. 'uid2!' => \$uid2,
  9743. 'authmech1=s' => \$authmech1,
  9744. 'authmech2=s' => \$authmech2,
  9745. 'authuser1=s' => \$authuser1,
  9746. 'authuser2=s' => \$authuser2,
  9747. 'proxyauth1' => \$proxyauth1,
  9748. 'proxyauth2' => \$proxyauth2,
  9749. 'split1=i' => \$split1,
  9750. 'split2=i' => \$split2,
  9751. 'buffersize=i' => \$buffersize,
  9752. 'reconnectretry1=i' => \$reconnectretry1,
  9753. 'reconnectretry2=i' => \$reconnectretry2,
  9754. 'tests!' => \$mysync->{ tests },
  9755. 'testsdebug|tests_debug!' => \$mysync->{ testsdebug },
  9756. 'testsunit=s@' => \$mysync->{testsunit},
  9757. 'testslive!' => \$mysync->{testslive},
  9758. 'testslive6!' => \$mysync->{testslive6},
  9759. 'justlogin!' => \$mysync->{justlogin},
  9760. 'justconnect!' => \$mysync->{justconnect},
  9761. 'tmpdir=s' => \$mysync->{ tmpdir },
  9762. 'pidfile=s' => \$mysync->{pidfile},
  9763. 'pidfilelocking!' => \$mysync->{pidfilelocking},
  9764. 'sigexit=s@' => \$mysync->{ sigexit },
  9765. 'sigreconnect=s@' => \$mysync->{ sigreconnect },
  9766. 'sigignore=s@' => \$mysync->{ sigignore },
  9767. 'releasecheck!' => \$mysync->{releasecheck},
  9768. 'modulesversion|modules_version!' => \$modulesversion,
  9769. 'usecache!' => \$usecache,
  9770. 'cacheaftercopy!' => \$cacheaftercopy,
  9771. 'debugcache!' => \$debugcache,
  9772. 'useuid!' => \$useuid,
  9773. 'addheader!' => \$mysync->{addheader},
  9774. 'exitwhenover=i' => \$exitwhenover,
  9775. 'checkselectable!' => \$mysync->{ checkselectable },
  9776. 'checkfoldersexist!' => \$mysync->{ checkfoldersexist },
  9777. 'checkmessageexists!' => \$checkmessageexists,
  9778. 'expungeaftereach!' => \$expungeaftereach,
  9779. 'abletosearch!' => \$mysync->{abletosearch},
  9780. 'abletosearch1!' => \$mysync->{abletosearch1},
  9781. 'abletosearch2!' => \$mysync->{abletosearch2},
  9782. 'showpasswords!' => \$mysync->{showpasswords},
  9783. 'maxlinelength=i' => \$maxlinelength,
  9784. 'maxlinelengthcmd=s' => \$maxlinelengthcmd,
  9785. 'minmaxlinelength=i' => \$minmaxlinelength,
  9786. 'debugmaxlinelength!' => \$debugmaxlinelength,
  9787. 'fixcolonbug!' => \$fixcolonbug,
  9788. 'create_folder_old!' => \$create_folder_old,
  9789. 'maxmessagespersecond=f' => \$mysync->{maxmessagespersecond},
  9790. 'maxbytespersecond=i' => \$mysync->{maxbytespersecond},
  9791. 'maxbytesafter=i' => \$mysync->{maxbytesafter},
  9792. 'maxsleep=f' => \$mysync->{maxsleep},
  9793. 'skipcrossduplicates!' => \$skipcrossduplicates,
  9794. 'debugcrossduplicates!' => \$debugcrossduplicates,
  9795. 'log!' => \$mysync->{log},
  9796. 'logfile=s' => \$mysync->{logfile},
  9797. 'logdir=s' => \$mysync->{logdir},
  9798. 'errorsmax=i' => \$mysync->{errorsmax},
  9799. 'errorsdump!' => \$mysync->{errorsdump},
  9800. 'fetch_hash_set=s' => \$fetch_hash_set,
  9801. 'automap!' => \$mysync->{automap},
  9802. 'justautomap!' => \$mysync->{justautomap},
  9803. 'id!' => \$mysync->{id},
  9804. 'f1f2=s@' => \$mysync->{f1f2},
  9805. 'f1f2h=s%' => \$mysync->{f1f2h},
  9806. 'justfolderlists!' => \$mysync->{justfolderlists},
  9807. 'delete1emptyfolders' => \$mysync->{delete1emptyfolders},
  9808. ) ;
  9809. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  9810. $debug and output( $mysync, "get options: [$opt_ret][$numopt]\n" ) ;
  9811. my $numopt_after = scalar @arguments ;
  9812. #myprint( "get options: [$opt_ret][$numopt][$numopt_after]\n" ) ;
  9813. if ( $numopt_after ) {
  9814. myprint( "Extra arguments found: @arguments\n", "It usually means a quoting issue in the command line\n" ) ;
  9815. return ;
  9816. }
  9817. if ( ! $opt_ret ) {
  9818. return ;
  9819. }
  9820. return $numopt ;
  9821. }
  9822. sub tests_get_options {
  9823. note( 'Entering tests_get_options()' ) ;
  9824. # CAVEAT: still setting global variables, be careful
  9825. # with tests, the context increases! $debug stays on for example.
  9826. # API:
  9827. # * input arguments: two ways, command line or CGI
  9828. # * the program arguments
  9829. # * QUERY_STRING env variable
  9830. # * return
  9831. # * undef if bad things happened like
  9832. # * options not known
  9833. # * --delete 2 input
  9834. # * number of arguments or QUERY_STRING length
  9835. my $mysync3 = { } ;
  9836. is( undef, get_options( $mysync3, qw( --noexist ) ), 'get_options: --noexist => undef' ) ;
  9837. is( undef, $mysync3->{ noexist }, 'get_options: --noexist => undef' ) ;
  9838. $mysync3 = { } ;
  9839. is( undef, get_options( $mysync3, qw( --lalala --noexist --version ) ), 'get_options: --lalala --noexist --version => undef' ) ;
  9840. is( 1, $mysync3->{ version }, 'get_options: --version => 1' ) ;
  9841. is( undef, $mysync3->{ noexist }, 'get_options: --noexist => undef' ) ;
  9842. $mysync3 = { } ;
  9843. is( 1, get_options( $mysync3, qw( --delete2 ) ), 'get_options: --delete2 => 1' ) ;
  9844. is( 1, $delete2, 'get_options: --delete2 => $delete2 = 1' ) ;
  9845. $mysync3 = { } ;
  9846. is( undef, get_options( $mysync3, qw( --delete 2 ) ), 'get_options: --delete 2 => undef' ) ;
  9847. is( undef, $delete1, 'get_options: --delete 2 => $delete1 still undef ; good!' ) ;
  9848. $mysync3 = { } ;
  9849. is( undef, get_options( $mysync3, "--delete 2" ), 'get_options: --delete 2 => undef' ) ;
  9850. is( 1, get_options( $mysync3, "--version" ), 'get_options: --version => 1' ) ;
  9851. is( 1, get_options( $mysync3, "--help" ), 'get_options: --help => 1' ) ;
  9852. is( undef, get_options( $mysync3, qw( --noexist --version ) ), 'get_options: --debug --noexist --version => undef' ) ;
  9853. is( 1, get_options( $mysync3, qw( --version ) ), 'get_options: --version => 1' ) ;
  9854. is( undef, get_options( $mysync3, qw( extra ) ), 'get_options: extra => undef' ) ;
  9855. is( undef, get_options( $mysync3, qw( extra1 --version extra2 ) ), 'get_options: extra1 --version extra2 => undef' ) ;
  9856. $mysync3 = { } ;
  9857. is( 2, get_options( $mysync3, qw( --host1 HOST_01) ), 'get_options: --host1 HOST_01 => 1' ) ;
  9858. is( 'HOST_01', $mysync3->{ host1 }, 'get_options: --host1 HOST_01 => HOST_01' ) ;
  9859. #myprint( Data::Dumper->Dump( [ $mysync3 ] ) ) ;
  9860. note( 'Leaving tests_get_options()' ) ;
  9861. return ;
  9862. }
  9863. sub get_options {
  9864. my $mysync = shift @ARG ;
  9865. my @arguments = @ARG ;
  9866. #myprint( "1 mysync: ", Data::Dumper->Dump( [ $mysync ] ) ) ;
  9867. my $ret ;
  9868. if ( under_cgi_context( ) ) {
  9869. # CGI context
  9870. $ret = get_options_cgi( $mysync, @arguments ) ;
  9871. }else{
  9872. # Command line context ;
  9873. $ret = get_options_cmd( $mysync, @arguments ) ;
  9874. } ;
  9875. #myprint( "2 mysync: ", Data::Dumper->Dump( [ $mysync ] ) ) ;
  9876. foreach my $key ( sort keys %{ $mysync } ) {
  9877. if ( ! defined $mysync->{$key} ) {
  9878. delete $mysync->{$key} ;
  9879. next ;
  9880. }
  9881. if ( 'ARRAY' eq ref( $mysync->{$key} )
  9882. and 0 == scalar( @{ $mysync->{$key} } ) ) {
  9883. delete $mysync->{$key} ;
  9884. }
  9885. }
  9886. return $ret ;
  9887. }
  9888. sub testunitsession {
  9889. my $mysync = shift ;
  9890. if ( ! $mysync ) { return ; }
  9891. if ( ! $mysync->{ testsunit } ) { return ; }
  9892. my @functions = @{ $mysync->{ testsunit } } ;
  9893. if ( ! @functions ) { return ; }
  9894. SKIP: {
  9895. if ( ! @functions ) { skip 'No test in normal run' ; }
  9896. testsunit( @functions ) ;
  9897. done_testing( ) ;
  9898. }
  9899. return ;
  9900. }
  9901. sub tests_count_0s {
  9902. note( 'Entering tests_count_zeros()' ) ;
  9903. is( 0, count_0s( ), 'count_0s: no parameters => 0' ) ;
  9904. is( 1, count_0s( 0 ), 'count_0s: 0 => 1' ) ;
  9905. is( 0, count_0s( 1 ), 'count_0s: 1 => 0' ) ;
  9906. is( 1, count_0s( 1, 0, 1 ), 'count_0s: 1, 0, 1 => 1' ) ;
  9907. is( 2, count_0s( 1, 0, 1, 0 ), 'count_0s: 1, 0, 1, 0 => 2' ) ;
  9908. note( 'Leaving tests_count_zeros()' ) ;
  9909. return ;
  9910. }
  9911. sub count_0s {
  9912. my @array = @ARG ;
  9913. if ( ! @array ) { return 0 ; }
  9914. my $nb_zeros = 0 ;
  9915. map { $_ == 0 and $nb_zeros += 1 } @array ;
  9916. return $nb_zeros ;
  9917. }
  9918. sub tests_report_failures {
  9919. note( 'Entering tests_report_failures()' ) ;
  9920. is( undef, report_failures( ), 'report_failures: no parameters => undef' ) ;
  9921. is( "nb 1 - first\n", report_failures( ({'ok' => 0, name => 'first'}) ), 'report_failures: "first" failed => nb 1 - first' ) ;
  9922. is( q{}, report_failures( ( {'ok' => 1, name => 'first'} ) ), 'report_failures: "first" success =>' ) ;
  9923. is( "nb 2 - second\n", report_failures( ( {'ok' => 1, name => 'second'}, {'ok' => 0, name => 'second'} ) ), 'report_failures: "second" failed => nb 2 - second' ) ;
  9924. is( "nb 1 - first\nnb 2 - second\n", report_failures( ( {'ok' => 0, name => 'first'}, {'ok' => 0, name => 'second'} ) ), 'report_failures: both failed => nb 1 - first nb 2 - second' ) ;
  9925. note( 'Leaving tests_report_failures()' ) ;
  9926. return ;
  9927. }
  9928. sub report_failures {
  9929. my @details = @ARG ;
  9930. if ( ! @details ) { return ; }
  9931. my $counter = 1 ;
  9932. my $report = q{} ;
  9933. foreach my $details ( @details ) {
  9934. if ( ! $details->{ 'ok' } ) {
  9935. my $name = $details->{ 'name' } || 'NONAME' ;
  9936. $report .= "nb $counter - $name\n" ;
  9937. }
  9938. $counter += 1 ;
  9939. }
  9940. return $report ;
  9941. }
  9942. sub tests_true {
  9943. note( 'Entering tests_true()' ) ;
  9944. is( 1, 1, 'true: 1 is 1' ) ;
  9945. note( 'Leaving tests_true()' ) ;
  9946. return ;
  9947. }
  9948. sub tests_testsunit {
  9949. note( 'Entering tests_testunit()' ) ;
  9950. is( undef, testsunit( ), 'testsunit: no parameters => undef' ) ;
  9951. is( undef, testsunit( undef ), 'testsunit: an undef parameter => undef' ) ;
  9952. is( undef, testsunit( q{} ), 'testsunit: an empty parameter => undef' ) ;
  9953. is( undef, testsunit( 'idonotexist' ), 'testsunit: a do not exist function as parameter => undef' ) ;
  9954. is( undef, testsunit( 'tests_true' ), 'testsunit: tests_true => undef' ) ;
  9955. note( 'Leaving tests_testunit()' ) ;
  9956. return ;
  9957. }
  9958. sub testsunit {
  9959. my @functions = @ARG ;
  9960. if ( ! @functions ) { #
  9961. myprint( "testsunit warning: no argument given\n" ) ;
  9962. return ;
  9963. }
  9964. foreach my $function ( @functions ) {
  9965. if ( ! $function ) {
  9966. myprint( "testsunit warning: argument is empty\n" ) ;
  9967. next ;
  9968. }
  9969. if ( ! exists &$function ) {
  9970. myprint( "testsunit warning: function $function does not exist\n" ) ;
  9971. next ;
  9972. }
  9973. if ( ! defined &$function ) {
  9974. myprint( "testsunit warning: function $function is not defined\n" ) ;
  9975. next ;
  9976. }
  9977. my $function_ref = \&{ $function } ;
  9978. &$function_ref() ;
  9979. }
  9980. return ;
  9981. }
  9982. sub testsdebug {
  9983. my $mysync = shift ;
  9984. if ( ! $mysync->{ testsdebug } ) { return ; }
  9985. SKIP: {
  9986. if ( ! $mysync->{ testsdebug } ) {
  9987. skip 'No test in normal run' ;
  9988. }
  9989. note( 'Entering testsdebug()' ) ;
  9990. ok( ( ( not -d 'W/tmp/tests' ) or rmtree( 'W/tmp/tests/' ) ), 'testsdebug: rmtree W/tmp/tests' ) ;
  9991. #tests_bytes_display_string( ) ;
  9992. #tests_ucsecond( ) ;
  9993. #tests_mkpath( ) ;
  9994. #tests_format_for_imap_arg( ) ;
  9995. #tests_is_a_release_number( ) ;
  9996. #tests_delete1emptyfolders( ) ;
  9997. #tests_memory_consumption( ) ;
  9998. #tests_imap2_folder_name() ;
  9999. #tests_length_ref( ) ;
  10000. #tests_diff_or_NA( ) ;
  10001. #tests_match_number( ) ;
  10002. #tests_all_defined( ) ;
  10003. #tests_guess_separator( ) ;
  10004. #tests_message_for_host2( ) ;
  10005. #tests_special_from_folders_hash( ) ;
  10006. #tests_do_valid_directory( ) ;
  10007. #tests_notmatch( ) ;
  10008. #tests_match( ) ;
  10009. #tests_get_options( ) ;
  10010. #tests_rand32( ) ;
  10011. #tests_string_to_file( ) ;
  10012. #tests_hashsynclocal( ) ;
  10013. #tests_output( ) ;
  10014. #tests_output_reset_with( ) ;
  10015. #tests_output_start( ) ;
  10016. #tests_hashsync( ) ;
  10017. #tests_check_last_release( ) ;
  10018. #tests_cpu_number( ) ;
  10019. #tests_load_and_delay( ) ;
  10020. #tests_loadavg( ) ;
  10021. #tests_backtick( ) ;
  10022. #tests_firstline( ) ;
  10023. #tests_pipemess( ) ;
  10024. #tests_not_long_imapsync_version_public( ) ;
  10025. #tests_get_options_cgi( ) ;
  10026. #tests_guess_special( ) ;
  10027. ####tests_reconnect_if_needed( ) ;
  10028. #tests_reconnect_12_if_needed( ) ;
  10029. #tests_sleep_max_bytes( ) ;
  10030. #tests_file_to_string( ) ;
  10031. #tests_under_cgi_context( ) ;
  10032. #tests_umask( ) ;
  10033. #tests_umask_str( ) ;
  10034. #tests_set_umask( ) ;
  10035. #tests_createhashfileifneeded( ) ;
  10036. #tests_filter_forbidden_characters( ) ;
  10037. #tests_logfile( ) ;
  10038. #tests_setlogfile( ) ;
  10039. #tests_move_slash( ) ;
  10040. #tests_testsunit( ) ;
  10041. #tests_always_fail( ) ;
  10042. #tests_count_0s( ) ;
  10043. #tests_report_failures( ) ;
  10044. #tests_max( ) ;
  10045. #tests_min( ) ;
  10046. #tests_sleep_if_needed( ) ;
  10047. #tests_imapsping( ) ;
  10048. #tests_tcpping( ) ;
  10049. #tests_sslcheck( ) ;
  10050. #tests_resolv( ) ;
  10051. #tests_resolvrev( ) ;
  10052. #tests_connect_socket( ) ;
  10053. #tests_probe_imapssl( ) ;
  10054. #tests_mailimapclient_connect( ) ;
  10055. #tests_guess_prefix( ) ;
  10056. #tests_usage( ) ;
  10057. #tests_version_from_rcs( ) ;
  10058. #tests_mailimapclient_connect_bug( ) ; # it fails with Mail-IMAPClient <= 3.39
  10059. #tests_backslash_caret( ) ;
  10060. tests_write_pidfile( ) ;
  10061. tests_remove_pidfile_not_running( ) ;
  10062. tests_match_a_pid_number( ) ;
  10063. note( 'Leaving testsdebug()' ) ;
  10064. done_testing( ) ;
  10065. }
  10066. return ;
  10067. }
  10068. sub tests_template {
  10069. note( 'Entering tests_template()' ) ;
  10070. is( undef, undef, 'template: undef is undef' ) ;
  10071. is_deeply( {}, {}, 'template: a hash is a hash' ) ;
  10072. is_deeply( [], [], 'template: an array is an array' ) ;
  10073. note( 'Leaving tests_template()' ) ;
  10074. return ;
  10075. }
  10076. sub tests {
  10077. my $mysync = shift ;
  10078. if ( ! $mysync->{ tests } ) { return ; }
  10079. SKIP: {
  10080. skip 'No test in normal run' if ( ! $mysync->{ tests } ) ;
  10081. note( 'Entering tests()' ) ;
  10082. tests_folder_routines( ) ;
  10083. tests_compare_lists( ) ;
  10084. tests_regexmess( ) ;
  10085. tests_skipmess( ) ;
  10086. tests_flags_regex();
  10087. tests_ucsecond( ) ;
  10088. tests_permanentflags();
  10089. tests_flags_filter( ) ;
  10090. tests_separator_invert( ) ;
  10091. tests_imap2_folder_name( ) ;
  10092. tests_command_line_nopassword( ) ;
  10093. tests_good_date( ) ;
  10094. tests_max( ) ;
  10095. tests_remove_not_num();
  10096. tests_memory_consumption( ) ;
  10097. tests_is_a_release_number();
  10098. tests_imapsync_basename();
  10099. tests_list_keys_in_2_not_in_1();
  10100. tests_convert_sep_to_slash( ) ;
  10101. tests_match_a_cache_file( ) ;
  10102. tests_cache_map( ) ;
  10103. tests_get_cache( ) ;
  10104. tests_clean_cache( ) ;
  10105. tests_clean_cache_2( ) ;
  10106. tests_touch( ) ;
  10107. tests_flagscase( ) ;
  10108. tests_mkpath( ) ;
  10109. tests_extract_header( ) ;
  10110. tests_decompose_header( ) ;
  10111. tests_epoch( ) ;
  10112. tests_add_header( ) ;
  10113. tests_cache_dir_fix( ) ;
  10114. tests_cache_dir_fix_win( ) ;
  10115. tests_filter_forbidden_characters( ) ;
  10116. tests_cache_folder( ) ;
  10117. tests_time_remaining( ) ;
  10118. tests_decompose_regex( ) ;
  10119. tests_backtick( ) ;
  10120. tests_bytes_display_string( ) ;
  10121. tests_header_line_normalize( ) ;
  10122. tests_fix_Inbox_INBOX_mapping( ) ;
  10123. tests_max_line_length( ) ;
  10124. tests_subject( ) ;
  10125. tests_msgs_from_maxmin( ) ;
  10126. tests_tmpdir_has_colon_bug( ) ;
  10127. tests_sleep_max_messages( ) ;
  10128. tests_sleep_max_bytes( ) ;
  10129. tests_logfile( ) ;
  10130. tests_setlogfile( ) ;
  10131. tests_jux_utf8( ) ;
  10132. tests_pipemess( ) ;
  10133. tests_jux_utf8_list( ) ;
  10134. tests_guess_prefix( ) ;
  10135. tests_guess_separator( ) ;
  10136. tests_format_for_imap_arg( ) ;
  10137. tests_imapsync_id( ) ;
  10138. tests_date_from_rcs( ) ;
  10139. tests_quota_extract_storage_limit_in_bytes( ) ;
  10140. tests_quota_extract_storage_current_in_bytes( ) ;
  10141. tests_guess_special( ) ;
  10142. tests_do_valid_directory( ) ;
  10143. tests_delete1emptyfolders( ) ;
  10144. tests_message_for_host2( ) ;
  10145. tests_length_ref( ) ;
  10146. tests_firstline( ) ;
  10147. tests_diff_or_NA( ) ;
  10148. tests_match_number( ) ;
  10149. tests_all_defined( ) ;
  10150. tests_special_from_folders_hash( ) ;
  10151. tests_notmatch( ) ;
  10152. tests_match( ) ;
  10153. tests_get_options( ) ;
  10154. tests_get_options_cgi_context( ) ;
  10155. tests_rand32( ) ;
  10156. tests_hashsynclocal( ) ;
  10157. tests_hashsync( ) ;
  10158. tests_output( ) ;
  10159. tests_output_reset_with( ) ;
  10160. tests_output_start( ) ;
  10161. tests_check_last_release( ) ;
  10162. tests_loadavg( ) ;
  10163. tests_cpu_number( ) ;
  10164. tests_load_and_delay( ) ;
  10165. #tests_imapsping( ) ;
  10166. #tests_tcpping( ) ;
  10167. tests_sslcheck( ) ;
  10168. tests_not_long_imapsync_version_public( ) ;
  10169. tests_reconnect_if_needed( ) ;
  10170. tests_reconnect_12_if_needed( ) ;
  10171. tests_sleep_if_needed( ) ;
  10172. tests_string_to_file( ) ;
  10173. tests_file_to_string( ) ;
  10174. tests_under_cgi_context( ) ;
  10175. tests_umask( ) ;
  10176. tests_umask_str( ) ;
  10177. tests_set_umask( ) ;
  10178. tests_createhashfileifneeded( ) ;
  10179. tests_move_slash( ) ;
  10180. tests_testsunit( ) ;
  10181. tests_count_0s( ) ;
  10182. tests_report_failures( ) ;
  10183. tests_min( ) ;
  10184. #tests_resolv( ) ;
  10185. #tests_resolvrev( ) ;
  10186. tests_connect_socket( ) ;
  10187. tests_probe_imapssl( ) ;
  10188. tests_mailimapclient_connect( ) ;
  10189. tests_usage( ) ;
  10190. tests_version_from_rcs( ) ;
  10191. tests_backslash_caret( ) ;
  10192. #tests_mailimapclient_connect_bug( ) ; # it fails with Mail-IMAPClient <= 3.39
  10193. tests_write_pidfile( ) ;
  10194. tests_remove_pidfile_not_running( ) ;
  10195. tests_match_a_pid_number( ) ;
  10196. tests_prefix_seperator_invertion( ) ;
  10197. tests_is_an_integer( ) ;
  10198. tests_integer_or_1( ) ;
  10199. tests_is_number( ) ;
  10200. tests_sig_install( ) ;
  10201. tests_template( ) ;
  10202. tests_split_around_equal( ) ;
  10203. tests_toggle_sleep( ) ;
  10204. #tests_always_fail( ) ;
  10205. done_testing( 1181 ) ;
  10206. note( 'Leaving tests()' ) ;
  10207. }
  10208. return ;
  10209. }