imapsync 723 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703
  1. #!/usr/bin/env perl
  2. # $Id: imapsync,v 2.148 2021/07/22 14:21:09 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, migrating
  17. and archiving email mailboxes between two imap servers, one way,
  18. and without duplicates.
  19. =head1 VERSION
  20. This documentation refers to Imapsync $Revision: 2.148 $
  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. If you don't understand the previous sentence, it's normal,
  36. it's pedantic computer-oriented jargon.
  37. All folders are transferred, recursively, meaning
  38. the whole folder hierarchy is taken, all messages in them,
  39. and all message flags (\Seen \Answered \Flagged etc.)
  40. are synced too.
  41. Imapsync reduces the amount of data transferred by not transferring
  42. a given message if it already resides on the destination side.
  43. Messages that are on the destination side but not on the
  44. source side stay as they are. See the --delete2
  45. option to have strict sync and delete them.
  46. How imapsync know a message is already on both sides?
  47. Same specific headers and the transfer is done only once.
  48. By default, the identification headers are
  49. "Message-Id:" and "Received:" lines
  50. but this choice can be changed with the --useheader option,
  51. most often a duplicate problem is solved by using
  52. --useheader "Message-Id"
  53. All flags are preserved, unread messages will stay unread,
  54. read ones will stay read, deleted will stay deleted.
  55. In the IMAP protocol, a deleted message is not really deleted,
  56. it is marked \Deleted and can be undelete. Real destruction
  57. comes with the EXPUNGE or UIDEXPUNGE IMAP commands.
  58. You can abort the transfer at any time and restart it later,
  59. imapsync works well with bad connections and interruptions,
  60. by design. On a terminal hit Ctr-c twice within two seconds
  61. to abort the program. Hit Ctr-c just once makes
  62. imapsync reconnect to both imap servers.
  63. How do you know the sync is finished and well done?
  64. When imapsync ends by itself it mentions it with lines like those:
  65. Exiting with return value 0 (EX_OK: successful termination) 0/50 nb_errors/max_errors PID 301
  66. Removing pidfile /tmp/imapsync.pid
  67. Log file is LOG_imapsync/2020_11_17_15_59_22_761_test1_test2.txt ( to change it, use --logfile filepath ; or use --nolog to turn off logging )
  68. If you don't have those lines it means that either the sync process is still
  69. running (or eventually hanging indefinitely) or that it ended without
  70. a whisper, a strong kill -9 on Linux for example.
  71. If you have those final lines then it means the sync process is properly
  72. finished. It may have encountered problems though.
  73. A good synchronization is mentioned by some lines above the last ones, especially
  74. those three lines:
  75. The sync looks good, all 1745 identified messages in host1 are on host2.
  76. There is no unidentified message on host1.
  77. Detected 0 errors
  78. A classical scenario is synchronizing a mailbox B from another mailbox A
  79. where you just want to keep a strict copy of A in B. Strict meaning
  80. all messages in A will be in B but no more.
  81. For this, option --delete2 can be used, it deletes messages in the host2
  82. folder B that are not in the host1 folder A. If you also need to destroy
  83. host2 folders that are not in host1 then use --delete2folders. See also
  84. --delete2foldersonly and --delete2foldersbutnot to set up exceptions
  85. on folders to destroy. INBOX will never be destroyed, it's a mandatory
  86. folder in IMAP so imapsync doesn't even try to remove it.
  87. A different scenario is to delete the messages from the source mailbox
  88. after a successful transfer, it can be a good feature when migrating
  89. mailboxes since messages will be only on one side. The source account
  90. will only have messages that are not on the destination yet, ie,
  91. messages that arrived after a sync or that failed to be transferred.
  92. In that case, use the --delete1 option. Option --delete1 implies also
  93. the option --expunge1 so all messages marked deleted on host1 will be
  94. deleted. In IMAP protocol deleting a message does not delete it,
  95. it marks it with the flag \Deleted, allowing an undelete. Expunging
  96. a folder removes, definitively, all the messages marked as \Deleted
  97. in this folder.
  98. You can also decide to remove empty folders once all of their messages
  99. have been transferred. Add --delete1emptyfolders to obtain this
  100. behavior.
  101. Imapsync is not adequate for maintaining two active imap accounts
  102. in synchronization when the user plays independently on both sides.
  103. Use offlineimap (written by John Goerzen) or mbsync (written by
  104. Michael R. Elkins) for a 2 ways synchronization.
  105. =head1 OPTIONS
  106. usage: imapsync [options]
  107. The standard options are the six values forming the credentials.
  108. Three values on each side are needed in order to login into the IMAP
  109. servers. These six values are a hostname, a username, and a password, two times.
  110. Conventions used in the following descriptions of the options:
  111. str means string
  112. int means integer number
  113. flo means float number
  114. reg means regular expression
  115. cmd means command
  116. --dry : Makes imapsync doing nothing for real; it just print what
  117. would be done without --dry.
  118. =head2 OPTIONS/credentials
  119. --host1 str : Source or "from" imap server.
  120. --port1 int : Port to connect on host1.
  121. Optional since default ports are the
  122. well known ports imap/143 or imaps/993.
  123. --user1 str : User to login on host1.
  124. --password1 str : Password of user1.
  125. --host2 str : "destination" imap server.
  126. --port2 int : Port to connect on host2. Optional
  127. --user2 str : User to login on host2.
  128. --password2 str : Password of user2.
  129. --showpasswords : Shows passwords on output instead of "MASKED".
  130. Useful to restart a complete run by just reading
  131. the command line used in the log,
  132. or to debug passwords.
  133. It's not a secure practice at all!
  134. --passfile1 str : Password file for the user1. It must contain the
  135. password on the first line. This option avoids showing
  136. the password on the command line like --password1 does.
  137. --passfile2 str : Password file for the user2.
  138. You can also pass the passwords in the environment variables
  139. IMAPSYNC_PASSWORD1 and IMAPSYNC_PASSWORD2. If you don't pass
  140. the user1 password via --password1 nor --passfile1 nor $IMAPSYNC_PASSWORD1
  141. then imapsync will prompt to enter the password on the terminal.
  142. Same thing for user2 password.
  143. =head2 OPTIONS/encryption
  144. --nossl1 : Do not use a SSL connection on host1.
  145. --ssl1 : Use a SSL connection on host1. On by default if possible.
  146. --nossl2 : Do not use a SSL connection on host2.
  147. --ssl2 : Use a SSL connection on host2. On by default if possible.
  148. --notls1 : Do not use a TLS connection on host1.
  149. --tls1 : Use a TLS connection on host1. On by default if possible.
  150. --notls2 : Do not use a TLS connection on host2.
  151. --tls2 : Use a TLS connection on host2. On by default if possible.
  152. --debugssl int : SSL debug mode from 0 to 4.
  153. --sslargs1 str : Pass any ssl parameter for host1 ssl or tls connection. Example:
  154. --sslargs1 SSL_verify_mode=1 --sslargs1 SSL_version=SSLv3
  155. See all possibilities in the new() method of IO::Socket::SSL
  156. http://search.cpan.org/perldoc?IO::Socket::SSL#Description_Of_Methods
  157. --sslargs2 str : Pass any ssl parameter for host2 ssl or tls connection.
  158. See --sslargs1
  159. --timeout1 flo : Connection timeout in seconds for host1.
  160. Default is 120 and 0 means no timeout at all.
  161. --timeout2 flo : Connection timeout in seconds for host2.
  162. Default is 120 and 0 means no timeout at all.
  163. Caveat, under CGI context, you may encounter a timeout
  164. from the webserver, killing imapsync and the imap connexions.
  165. See the document INSTALL.OnlineUI.txt and search
  166. for "Timeout" for how to deal with this issue.
  167. =head2 OPTIONS/authentication
  168. --authmech1 str : Auth mechanism to use with host1:
  169. PLAIN, LOGIN, CRAM-MD5 etc. Use UPPERCASE.
  170. --authmech2 str : Auth mechanism to use with host2. See --authmech1
  171. --authuser1 str : User to auth with on host1 (admin user).
  172. Avoid using --authmech1 SOMETHING with --authuser1.
  173. --authuser2 str : User to auth with on host2 (admin user).
  174. --proxyauth1 : Use proxyauth on host1. Requires --authuser1.
  175. Required by Sun/iPlanet/Netscape IMAP servers to
  176. be able to use an administrative user.
  177. --proxyauth2 : Use proxyauth on host2. Requires --authuser2.
  178. --authmd51 : Use MD5 authentication for host1.
  179. --authmd52 : Use MD5 authentication for host2.
  180. --domain1 str : Domain on host1 (NTLM authentication).
  181. --domain2 str : Domain on host2 (NTLM authentication).
  182. --oauthaccesstoken1 str : The access token to authenticate with OAUTH2.
  183. It will be combined with the --user1 value to form the
  184. string to pass with XOAUTH2 authentication.
  185. The password given by --password1 or --passfile1
  186. is ignored.
  187. Instead of the access token itself, the value can be a
  188. file containing the access token on the first line.
  189. If the value is a file, imapsync reads its first line
  190. and take this line as the access token. The advantage
  191. of the file is that if the access token changes then
  192. imapsync can read it again when it needs to reconnect
  193. during a run.
  194. --oauthaccesstoken2 str : same thing as --oauthaccesstoken1
  195. --oauthdirect1 str : The direct string to pass with XOAUTH2 authentication.
  196. The password given by --password1 or --passfile1 and
  197. the user given by --user1 are ignored.
  198. --oauthdirect2 str : same thing as oauthdirect1
  199. =head2 OPTIONS/folders
  200. --folder str : Sync this folder.
  201. --folder str : and this one, etc.
  202. --folderrec str : Sync this folder recursively.
  203. --folderrec str : and this one, etc.
  204. --folderfirst str : Sync this folder first. Ex. --folderfirst "INBOX"
  205. --folderfirst str : then this one, etc.
  206. --folderlast str : Sync this folder last. --folderlast "[Gmail]/All Mail"
  207. --folderlast str : then this one, etc.
  208. --nomixfolders : Do not merge folders when host1 is case-sensitive
  209. while host2 is not (like Exchange). Only the first
  210. similar folder is synced (example: with folders
  211. "Sent", "SENT" and "sent"
  212. on host1 only "Sent" will be synced to host2).
  213. --skipemptyfolders : Empty host1 folders are not created on host2.
  214. --include reg : Sync folders matching this regular expression
  215. --include reg : or this one, etc.
  216. If both --include --exclude options are used, then
  217. include is done before.
  218. --exclude reg : Skips folders matching this regular expression
  219. Several folders to avoid:
  220. --exclude 'fold1|fold2|f3' skips fold1, fold2 and f3.
  221. --exclude reg : or this one, etc.
  222. --automap : guesses folders mapping, for folders well known as
  223. "Sent", "Junk", "Drafts", "All", "Archive", "Flagged".
  224. --f1f2 str1=str2 : Force folder str1 to be synced to str2,
  225. --f1f2 overrides --automap and --regextrans2.
  226. Use several --f1f2 options to map several folders.
  227. Option --f1f2 is a one to one only folder mapping,
  228. str1 and str2 have to be full path folder names.
  229. --subfolder2 str : Syncs the whole host1 folders hierarchy under the
  230. host2 folder named str.
  231. It does it internally by adding three
  232. --regextrans2 options before all others.
  233. Add --debug to see what's really going on.
  234. --subfolder1 str : Syncs the host1 folders hierarchy which is under folder
  235. str to the root hierarchy of host2.
  236. It's the couterpart of a sync done by --subfolder2
  237. when doing it in the reverse order.
  238. Backup/Restore scenario:
  239. Use --subfolder2 str for a backup to the folder str
  240. on host2. Then use --subfolder1 str for restoring
  241. from the folder str, after inverting
  242. host1/host2 user1/user2 values.
  243. --subscribed : Transfers subscribed folders.
  244. --subscribe : Subscribe to the folders transferred on the
  245. host2 that are subscribed on host1. On by default.
  246. --subscribeall : Subscribe to the folders transferred on the
  247. host2 even if they are not subscribed on host1.
  248. --prefix1 str : Remove prefix str to all destination folders,
  249. usually "INBOX." or "INBOX/" or an empty string "".
  250. imapsync guesses the prefix if host1 imap server
  251. does not have NAMESPACE capability. So this option
  252. should not be used most of the time.
  253. --prefix2 str : Add prefix to all host2 folders. See --prefix1
  254. --sep1 str : Host1 separator. This option should not be used
  255. most of the time.
  256. Imapsync gets the separator from the server itself,
  257. by using NAMESPACE, or it tries to guess it
  258. from the folders listing (it counts
  259. characters / . \\ \ in folder names and choose the
  260. more frequent, or finally / if nothing is found.
  261. --sep2 str : Host2 separator. See --sep1
  262. --regextrans2 reg : Apply the whole regex to each destination folders.
  263. --regextrans2 reg : and this one. etc.
  264. When you play with the --regextrans2 option, first
  265. add also the safe options --dry --justfolders
  266. Then, when happy, remove --dry for a run, then
  267. remove --justfolders for the next ones.
  268. Have in mind that --regextrans2 is applied after
  269. the automatic prefix and separator inversion.
  270. For examples see:
  271. https://imapsync.lamiral.info/FAQ.d/FAQ.Folders_Mapping.txt
  272. =head2 OPTIONS/folders sizes
  273. --nofoldersizes : Do not calculate the size of each folder at the
  274. beginning of the sync. Default is to calculate them.
  275. --nofoldersizesatend: Do not calculate the size of each folder at the
  276. end of the sync. Default is to calculate them.
  277. --justfoldersizes : Exit after having printed the initial folder sizes.
  278. =head2 OPTIONS/tmp
  279. --tmpdir str : Where to store temporary files and subdirectories.
  280. Will be created if it doesn't exist.
  281. Default is system specific, Unix is /tmp but
  282. /tmp is often too small and deleted at reboot.
  283. --tmpdir /var/tmp should be better.
  284. --pidfile str : The file where imapsync pid is written,
  285. it can be dirname/filename complete path.
  286. The default name is imapsync.pid in tmpdir.
  287. --pidfilelocking : Abort if pidfile already exists. Useful to avoid
  288. concurrent transfers on the same mailbox.
  289. =head2 OPTIONS/log
  290. --nolog : Turn off logging on file
  291. --logfile str : Change the default log filename (can be dirname/filename).
  292. --logdir str : Change the default log directory. Default is LOG_imapsync/
  293. The default logfile name is for example
  294. LOG_imapsync/2019_12_22_23_57_59_532_user1_user2.txt
  295. where:
  296. 2019_12_22_23_57_59_532 is nearly the date of the start
  297. YYYY_MM_DD_HH_MM_SS_mmm
  298. year_month_day_hour_minute_seconde_millisecond
  299. and user1 user2 are the --user1 --user2 values.
  300. =head2 OPTIONS/messages
  301. --skipmess reg : Skips messages matching the regex.
  302. Example: 'm/[\x80-\xff]/' # to avoid 8bits messages.
  303. --skipmess is applied before --regexmess
  304. --skipmess reg : or this one, etc.
  305. --skipcrossduplicates : Avoid copying messages that are already copied
  306. in another folder, good from Gmail to XYZ when
  307. XYZ is not also Gmail.
  308. Activated with --gmail1 unless --noskipcrossduplicates
  309. --debugcrossduplicates : Prints which messages (UIDs) are skipped with
  310. --skipcrossduplicates and in what other folders
  311. they are.
  312. --pipemess cmd : Apply this cmd command to each message content
  313. before the copy.
  314. --pipemess cmd : and this one, etc.
  315. With several --pipemess, the output of each cmd
  316. command (STDOUT) is given to the input (STDIN)
  317. of the next command.
  318. For example,
  319. --pipemess cmd1 --pipemess cmd2 --pipemess cmd3
  320. is like a Unix pipe:
  321. "cat message | cmd1 | cmd2 | cmd3"
  322. --disarmreadreceipts : Disarms read receipts (host2 Exchange issue)
  323. --regexmess reg : Apply the whole regex to each message before transfer.
  324. Example: 's/\000/ /g' # to replace null characters
  325. by spaces.
  326. --regexmess reg : and this one, etc.
  327. =head2 OPTIONS/labels
  328. Gmail present labels as folders in imap. Imapsync can accelerate the sync
  329. by syncing X-GM-LABELS, it will avoid to transfer messages when they are
  330. already on host2 in another folder.
  331. --synclabels : Syncs also Gmail labels when a message is copied to host2.
  332. Activated by default with --gmail1 --gmail2 unless
  333. --nosynclabels is added.
  334. --resynclabels : Resyncs Gmail labels when a message is already on host2.
  335. Activated by default with --gmail1 --gmail2 unless
  336. --noresynclabels is added.
  337. For Gmail syncs, see also:
  338. https://imapsync.lamiral.info/FAQ.d/FAQ.Gmail.txt
  339. =head2 OPTIONS/flags
  340. If you encounter flag problems see also:
  341. https://imapsync.lamiral.info/FAQ.d/FAQ.Flags.txt
  342. --regexflag reg : Apply the whole regex to each flags list.
  343. Example: 's/"Junk"//g' # to remove "Junk" flag.
  344. --regexflag reg : then this one, etc.
  345. --resyncflags : Resync flags for already transferred messages.
  346. On by default.
  347. --noresyncflags : Do not resync flags for already transferred messages.
  348. May be useful when a user has already started to play
  349. with its host2 account.
  350. --filterbuggyflags : Filter flags known to be buggy and generators of errors
  351. "BAD Invalid system flag" or "NO APPEND Invalid flag list".
  352. =head2 OPTIONS/deletions
  353. --delete1 : Deletes messages on host1 server after a successful
  354. transfer. Option --delete1 has the following behavior:
  355. it marks messages as deleted with the IMAP flag
  356. \Deleted, then messages are really deleted with an
  357. EXPUNGE IMAP command. If expunging after each message
  358. slows down too much the sync then use
  359. --noexpungeaftereach to speed up, expunging will then be
  360. done only twice per folder, one at the beginning and
  361. one at the end of a folder sync.
  362. --expunge1 : Expunge messages on host1 just before syncing a folder.
  363. Expunge is done per folder.
  364. Expunge aims is to really delete messages marked deleted.
  365. An expunge is also done after each message copied
  366. if option --delete1 is set (unless --noexpungeaftereach).
  367. --noexpunge1 : Do not expunge messages on host1.
  368. --delete1emptyfolders : Deletes empty folders on host1, INBOX excepted.
  369. Useful with --delete1 since what remains on host1
  370. is only what failed to be synced.
  371. --delete2 : Delete messages in the host2 account that are not in
  372. the host1 account. Useful for backup or pre-sync.
  373. --delete2 implies --uidexpunge2
  374. --delete2duplicates : Deletes messages in host2 that are duplicates in host2.
  375. Works only without --useuid since duplicates are
  376. detected with an header part of each message.
  377. NB: --delete2duplicates is far less violent than --delete2
  378. since it removes only duplicates.
  379. --delete2folders : Delete folders in host2 that are not in host1.
  380. For safety, first try it like this, it is safe:
  381. --delete2folders --dry --justfolders --nofoldersizes
  382. and see what folders will be deleted.
  383. --delete2foldersonly reg : Delete only folders matching the regex reg.
  384. Example: --delete2foldersonly "/^Junk$|^INBOX.Junk$/"
  385. This option activates --delete2folders
  386. --delete2foldersbutnot reg : Do not delete folders matching the regex rex.
  387. Example: --delete2foldersbutnot "/Tasks$|Contacts$|Foo$/"
  388. This option activates --delete2folders
  389. --noexpunge2 : Do not expunge messages on host2.
  390. --nouidexpunge2 : Do not uidexpunge messages on the host2 account
  391. that are not on the host1 account.
  392. =head2 OPTIONS/dates
  393. If you encounter problems with dates, see also:
  394. https://imapsync.lamiral.info/FAQ.d/FAQ.Dates.txt
  395. --syncinternaldates : Sets the internal dates on host2 as the same as host1.
  396. Turned on by default. Internal date is the date
  397. a message arrived on a host (Unix mtime usually).
  398. --idatefromheader : Sets the internal dates on host2 as same as the
  399. ones in "Date:" headers.
  400. =head2 OPTIONS/message selection
  401. --maxsize int : Skip messages larger (or equal) than int bytes
  402. --minsize int : Skip messages smaller (or equal) than int bytes
  403. --maxage int : Skip messages older than int days.
  404. final stats (skipped) don't count older messages
  405. see also --minage
  406. --minage int : Skip messages newer than int days.
  407. final stats (skipped) don't count newer messages
  408. You can do (+ zone are the messages selected):
  409. past|----maxage+++++++++++++++>now
  410. past|+++++++++++++++minage---->now
  411. past|----maxage+++++minage---->now (intersection)
  412. past|++++minage-----maxage++++>now (union)
  413. --search str : Selects only messages returned by this IMAP SEARCH
  414. command. Applied on both sides.
  415. For a complete set of what can be search see
  416. https://imapsync.lamiral.info/FAQ.d/FAQ.Messages_Selection.txt
  417. --search1 str : Same as --search but for selecting host1 messages only.
  418. --search2 str : Same as --search but for selecting host2 messages only.
  419. So --search CRIT equals --search1 CRIT --search2 CRIT
  420. --noabletosearch : Makes --minage and --maxage options use the internal
  421. dates given by a FETCH imap command instead of the
  422. "Date:" header. Internal date is the arrival date
  423. in the mailbox.
  424. --noabletosearch equals --noabletosearch1 --noabletosearch2
  425. --noabletosearch1 : Like --noabletosearch but for host1 only.
  426. --noabletosearch2 : Like --noabletosearch but for host2 only.
  427. --maxlinelength int : skip messages with a line length longer than int bytes.
  428. RFC 2822 says it must be no more than 1000 bytes but
  429. real life servers and email clients do more.
  430. --useheader str : Use this header to compare messages on both sides.
  431. Example: "Message-Id" or "Received" or "Date".
  432. --useheader str and this one, etc.
  433. --syncduplicates : Sync also duplicates. Off by default.
  434. --usecache : Use cache to speed up next syncs. Off by default.
  435. --nousecache : Do not use cache. Caveat: --useuid --nousecache creates
  436. duplicates on multiple runs.
  437. --useuid : Use UIDs instead of headers as a criterion to recognize
  438. messages. Option --usecache is then implied unless
  439. --nousecache is used.
  440. =head2 OPTIONS/miscellaneous
  441. --syncacls : Synchronizes acls (Access Control Lists).
  442. Acls in IMAP are not standardized, be careful
  443. since one acl code on one side may signify something
  444. else on the other one.
  445. --nosyncacls : Does not synchronize acls. This is the default.
  446. --addheader : When a message has no headers to be identified,
  447. --addheader adds a "Message-Id" header,
  448. like "Message-Id: 12345@imapsync", where 12345
  449. is the imap UID of the message on the host1 folder.
  450. Useful to sync folders "Sent" or "Draft".
  451. =head2 OPTIONS/debugging
  452. --debug : Debug mode.
  453. --debugfolders : Debug mode for the folders part only.
  454. --debugcontent : Debug content of the messages transferred. Huge output.
  455. --debugflags : Debug mode for flags.
  456. --debugimap1 : IMAP debug mode for host1. Very verbose.
  457. --debugimap2 : IMAP debug mode for host2. Very verbose.
  458. --debugimap : IMAP debug mode for host1 and host2. Twice very verbose.
  459. --debugmemory : Debug mode showing memory consumption after each copy.
  460. --errorsmax int : Exit when int number of errors is reached. Default is 50.
  461. --tests : Run local non-regression tests. Exit code 0 means all ok.
  462. --testslive : Run a live test with test1.lamiral.info imap server.
  463. Useful to check the basics. Needs internet connection.
  464. --testslive6 : Run a live test with ks6ipv6.lamiral.info imap server.
  465. Useful to check the ipv6 connectivity. Needs internet.
  466. =head2 OPTIONS/specific
  467. --gmail1 : sets --host1 to Gmail and other options. See FAQ.Gmail.txt
  468. --gmail2 : sets --host2 to Gmail and other options. See FAQ.Gmail.txt
  469. --office1 : sets --host1 to Office365 and other options. See FAQ.Office365.txt
  470. --office2 : sets --host2 to Office365 and other options. See FAQ.Office365.txt
  471. --exchange1 : sets options for Exchange. See FAQ.Exchange.txt
  472. --exchange2 : sets options for Exchange. See FAQ.Exchange.txt
  473. --domino1 : sets options for Domino. See FAQ.Domino.txt
  474. --domino2 : sets options for Domino. See FAQ.Domino.txt
  475. =head2 OPTIONS/behavior
  476. --maxmessagespersecond flo : limits the average number of messages
  477. transferred per second.
  478. --maxbytespersecond int : limits the average transfer rate per second.
  479. --maxbytesafter int : starts --maxbytespersecond limitation only after
  480. --maxbytesafter amount of data transferred.
  481. --maxsleep flo : do not sleep more than int seconds.
  482. On by default, 2 seconds max, like --maxsleep 2
  483. --abort : terminates a previous call still running.
  484. It uses the pidfile to know what process to abort.
  485. --exitwhenover int : Stop syncing and exits when int total bytes
  486. transferred is reached.
  487. --version : Print only the software version.
  488. --noreleasecheck : Do not check for any new imapsync release.
  489. --releasecheck : Check for new imapsync release.
  490. it's an http request to
  491. http://imapsync.lamiral.info/prj/imapsync/VERSION
  492. --noid : Do not send/receive IMAP "ID" command to imap servers.
  493. --justconnect : Just connect to both servers and print useful
  494. information. Need only --host1 and --host2 options.
  495. Obsolete since "imapsync --host1 imaphost" alone
  496. implies --justconnect
  497. --justlogin : Just login to both host1 and host2 with users
  498. credentials, then exit.
  499. --justfolders : Do only things about folders (ignore messages).
  500. --help : print this help.
  501. Example: to synchronize imap account "test1" on "test1.lamiral.info"
  502. to imap account "test2" on "test2.lamiral.info"
  503. with test1 password "secret1"
  504. and test2 password "secret2"
  505. imapsync \
  506. --host1 test1.lamiral.info --user1 test1 --password1 secret1 \
  507. --host2 test2.lamiral.info --user2 test2 --password2 secret2
  508. =cut
  509. # comment
  510. =pod
  511. =head1 SECURITY
  512. You can use --passfile1 instead of --password1 to mention the
  513. password since it is safer. With --password1 option, on Linux,
  514. any user on your host can see the password by using the 'ps auxwwww'
  515. command. Using a variable (like IMAPSYNC_PASSWORD1) is also
  516. dangerous because of the 'ps auxwwwwe' command. So, saving
  517. the password in a well protected file (600 or rw-------) is
  518. the best solution.
  519. Imapsync activates ssl or tls encryption by default, if possible.
  520. What detailed behavior is under this "if possible"?
  521. Imapsync activates ssl if the well known port imaps port (993) is open
  522. on the imap servers. If the imaps port is closed then it open a
  523. normal (clear) connection on port 143 but it looks for TLS support
  524. in the CAPABILITY list of the servers. If TLS is supported
  525. then imapsync goes to encryption with STARTTLS.
  526. If the automatic ssl and the tls detections fail then imapsync will
  527. not protect against sniffing activities on the network, especially
  528. for passwords.
  529. If you want to force ssl or tls just use --ssl1 --ssl2 or --tls1 --tls2
  530. See also the document FAQ.Security.txt in the FAQ.d/ directory
  531. or at https://imapsync.lamiral.info/FAQ.d/FAQ.Security.txt
  532. =head1 EXIT STATUS
  533. Imapsync will exit with a 0 status (return code) if everything went good.
  534. Otherwise, it exits with a non-zero status. That's classical Unix behavior.
  535. Here is the list of the exit code values (an integer between 0 and 255).
  536. In Bourne Shells, this exit code value can be retrieved within the variable
  537. value "$?" if you read it just after the imapsync call.
  538. The names reflect their meaning:
  539. =for comment
  540. egrep '^Readonly my.*\$EX' imapsync | egrep -o 'EX.*' | sed 's_^_ _'
  541. EX_OK => 0 ; #/* successful termination */
  542. EX_USAGE => 64 ; #/* command line usage error */
  543. EX_NOINPUT => 66 ; #/* cannot open input */
  544. EX_UNAVAILABLE => 69 ; #/* service unavailable */
  545. EX_SOFTWARE => 70 ; #/* internal software error */
  546. EXIT_CATCH_ALL => 1 ; # Any other error
  547. EXIT_BY_SIGNAL => 6 ; # Should be 128+n where n is the sig_num
  548. EXIT_BY_FILE => 7 ;
  549. EXIT_PID_FILE_ERROR => 8 ;
  550. EXIT_CONNECTION_FAILURE => 10 ;
  551. EXIT_TLS_FAILURE => 12 ;
  552. EXIT_AUTHENTICATION_FAILURE => 16 ;
  553. EXIT_SUBFOLDER1_NO_EXISTS => 21 ;
  554. EXIT_WITH_ERRORS => 111 ;
  555. EXIT_WITH_ERRORS_MAX => 112 ;
  556. EXIT_OVERQUOTA => 113 ;
  557. EXIT_ERR_APPEND => 114 ;
  558. EXIT_ERR_FETCH => 115 ;
  559. EXIT_ERR_CREATE => 116 ;
  560. EXIT_ERR_SELECT => 117 ;
  561. EXIT_TRANSFER_EXCEEDED => 118 ;
  562. EXIT_ERR_APPEND_VIRUS => 119 ;
  563. EXIT_TESTS_FAILED => 254 ; # Like Test::More API
  564. EXIT_CONNECTION_FAILURE_HOST1 => 101 ;
  565. EXIT_CONNECTION_FAILURE_HOST2 => 102 ;
  566. EXIT_AUTHENTICATION_FAILURE_USER1 => 161 ;
  567. EXIT_AUTHENTICATION_FAILURE_USER2 => 162 ;
  568. =head1 LICENSE AND COPYRIGHT
  569. Imapsync is free, open, public but not always gratis software
  570. cover by the NOLIMIT Public License, now called NLPL.
  571. See the LICENSE file included in the distribution or just read this
  572. simple sentence as it IS the licence text:
  573. "No limits to do anything with this work and this license."
  574. In case it is not long enough, I repeat:
  575. "No limits to do anything with this work and this license."
  576. Look at https://imapsync.lamiral.info/LICENSE
  577. =head1 AUTHOR
  578. Gilles LAMIRAL <gilles@lamiral.info>
  579. Good feedback is always welcome.
  580. Bad feedback is very often welcome.
  581. Gilles LAMIRAL earns his living by writing, installing,
  582. configuring and sometimes teaching free, open and often gratis
  583. software. Imapsync used to be "always gratis" but now it is
  584. only "often gratis" because imapsync is sold by its author,
  585. your servitor, a good way to maintain and support free open public
  586. software tools over decades.
  587. =head1 BUGS AND LIMITATIONS
  588. See https://imapsync.lamiral.info/FAQ.d/FAQ.Reporting_Bugs.txt
  589. =head1 IMAP SERVERS supported
  590. See https://imapsync.lamiral.info/S/imapservers.shtml
  591. =head1 HUGE MIGRATION
  592. If you have many mailboxes to migrate think about a little
  593. shell program. Write a file called file.txt (for example)
  594. containing users and passwords.
  595. The separator used in this example is ';'
  596. The file.txt file contains:
  597. user001_1;password001_1;user001_2;password001_2
  598. user002_1;password002_1;user002_2;password002_2
  599. user003_1;password003_1;user003_2;password003_2
  600. user004_1;password004_1;user004_2;password004_2
  601. user005_1;password005_1;user005_2;password005_2
  602. ...
  603. On Unix the shell program can be:
  604. { while IFS=';' read u1 p1 u2 p2; do
  605. imapsync --host1 imap.side1.org --user1 "$u1" --password1 "$p1" \
  606. --host2 imap.side2.org --user2 "$u2" --password2 "$p2" ...
  607. done ; } < file.txt
  608. On Windows the batch program can be:
  609. FOR /F "tokens=1,2,3,4 delims=; eol=#" %%G IN (file.txt) DO imapsync ^
  610. --host1 imap.side1.org --user1 %%G --password1 %%H ^
  611. --host2 imap.side2.org --user2 %%I --password2 %%J ...
  612. The ... have to be replaced by nothing or any imapsync option.
  613. Welcome in shell or batch programming !
  614. You will find already written scripts at
  615. https://imapsync.lamiral.info/examples/
  616. =head1 INSTALL
  617. Imapsync works under any Unix with Perl.
  618. Imapsync works under most Windows (2000, XP, Vista, Seven, Eight, Ten
  619. and all Server releases 2000, 2003, 2008 and R2, 2012 and R2, 2016)
  620. as a standalone binary software called imapsync.exe,
  621. usually launched from a batch file in order to avoid always typing
  622. the options. There is also a 32bit binary called imapsync_32bit.exe
  623. Imapsync works under OS X as a standalone binary
  624. software called imapsync_bin_Darwin
  625. Purchase latest imapsync at
  626. https://imapsync.lamiral.info/
  627. You'll receive a link to a compressed tarball called imapsync-x.xx.tgz
  628. where x.xx is the version number. Untar the tarball where
  629. you want (on Unix):
  630. tar xzvf imapsync-x.xx.tgz
  631. Go into the directory imapsync-x.xx and read the INSTALL file.
  632. As mentioned at https://imapsync.lamiral.info/#install
  633. the INSTALL file can also be found at
  634. https://imapsync.lamiral.info/INSTALL.d/INSTALL.ANY.txt
  635. It is now split in several files for each system
  636. https://imapsync.lamiral.info/INSTALL.d/
  637. =head1 CONFIGURATION
  638. There is no specific configuration file for imapsync,
  639. everything is specified by the command line parameters
  640. and the default behavior.
  641. =head1 HACKING
  642. Feel free to hack imapsync as the NOLIMIT license permits it.
  643. =head1 SIMILAR SOFTWARE
  644. See also https://imapsync.lamiral.info/S/external.shtml
  645. for a better up to date list.
  646. List verified on Friday July 1, 2021.
  647. imapsync: https://github.com/imapsync/imapsync (this is an imapsync copy, sometimes delayed, with --noreleasecheck by default since release 1.592, 2014/05/22)
  648. imap_tools: https://web.archive.org/web/20161228145952/http://www.athensfbc.com/imap_tools/. The imap_tools code is now at https://github.com/andrewnimmo/rick-sanders-imap-tools
  649. imaputils: https://github.com/mtsatsenko/imaputils (very old imap_tools fork)
  650. Doveadm-Sync: https://wiki2.dovecot.org/Tools/Doveadm/Sync ( Dovecot sync tool )
  651. davmail: http://davmail.sourceforge.net/
  652. offlineimap: http://offlineimap.org/
  653. fdm: https://github.com/nicm/fdm
  654. mbsync: http://isync.sourceforge.net/
  655. mailsync: http://mailsync.sourceforge.net/
  656. mailutil: https://www.washington.edu/imap/ part of the UW IMAP toolkit. (well, seems abandoned now)
  657. imaprepl: https://bl0rg.net/software/ http://freecode.com/projects/imap-repl/
  658. imapcopy (Pascal): http://www.ardiehl.de/imapcopy/
  659. imapcopy (Java): https://code.google.com/archive/p/imapcopy/
  660. imapsize: http://www.broobles.com/imapsize/
  661. migrationtool: http://sourceforge.net/projects/migrationtool/
  662. imapmigrate: http://sourceforge.net/projects/cyrus-utils/
  663. larch: https://github.com/rgrove/larch (derived from wonko_imapsync, good at Gmail)
  664. wonko_imapsync: http://wonko.com/article/554 (superseded by larch)
  665. pop2imap: http://www.linux-france.org/prj/pop2imap/ (I wrote that too)
  666. exchange-away: http://exchange-away.sourceforge.net/
  667. SyncBackPro: http://www.2brightsparks.com/syncback/sbpro.html
  668. ImapSyncClient: https://github.com/ridaamirini/ImapSyncClient
  669. MailStore: https://www.mailstore.com/en/products/mailstore-home/
  670. mnIMAPSync: https://github.com/manusa/mnIMAPSync
  671. imap-upload: http://imap-upload.sourceforge.net/ (A tool for uploading a local mbox file to IMAP4 server)
  672. imapbackup: https://github.com/rcarmo/imapbackup (A Python script for incremental backups of IMAP mailboxes)
  673. BitRecover email-backup 99 USD, 299 USD https://www.bitrecover.com/email-backup/.
  674. ImportExportTools: https://addons.thunderbird.net/en-us/thunderbird/addon/importexporttools/ ImportExportTools for Mozilla Thunderbird by Paolo Kaosmos. ImportExportTools does not do IMAP.
  675. rximapmail: https://sourceforge.net/projects/rximapmail/
  676. CodeTwo: https://www.codetwo.com/ but CodeTwo does imap source to Office365 only.
  677. =head1 HISTORY
  678. I initially wrote imapsync in July 2001 because an enterprise,
  679. called BaSystemes, paid me to install a new imap server
  680. without losing huge old mailboxes located in a far
  681. away remote imap server, accessible by an
  682. often broken low-bandwidth ISDN link.
  683. I had to verify every mailbox was well transferred, all folders, all messages,
  684. without wasting bandwidth or creating duplicates upon resyncs. The imapsync
  685. design was made with the beautiful rsync command in mind.
  686. Imapsync started its life as a patch of the copy_folder.pl
  687. script. The script copy_folder.pl comes from the Mail-IMAPClient-2.1.3 perl
  688. module tarball source (more precisely in the examples/ directory of the
  689. Mail-IMAPClient tarball).
  690. So many changes happened since then that I wonder
  691. if it remains any lines of the original
  692. copy_folder.pl in imapsync source code.
  693. =cut
  694. # use pragmas
  695. #
  696. use strict ;
  697. use warnings ;
  698. use Carp ;
  699. use Cwd ;
  700. use Data::Dumper ;
  701. use Digest::HMAC_SHA1 qw( hmac_sha1 hmac_sha1_hex ) ;
  702. use Digest::MD5 qw( md5 md5_hex md5_base64 ) ;
  703. use Encode ;
  704. use Encode::IMAPUTF7 ;
  705. use English qw( -no_match_vars ) ;
  706. use Errno qw(EAGAIN EPIPE ECONNRESET) ;
  707. use Fcntl ;
  708. use File::Basename ;
  709. use File::Copy::Recursive ;
  710. use File::Glob qw( :glob ) ;
  711. use File::Path qw( mkpath rmtree ) ;
  712. use File::Spec ;
  713. use File::stat ;
  714. use Getopt::Long ( ) ;
  715. use IO::File ;
  716. use IO::Socket qw( :crlf SOL_SOCKET SO_KEEPALIVE ) ;
  717. use IO::Socket::INET6 ;
  718. use IO::Socket::SSL ;
  719. use IO::Tee ;
  720. use IPC::Open3 'open3' ;
  721. #use locale ;
  722. use Mail::IMAPClient 3.30 ;
  723. use MIME::Base64 ;
  724. use Pod::Usage qw(pod2usage) ;
  725. use POSIX qw( uname SIGALRM :sys_wait_h ) ;
  726. use Sys::Hostname ;
  727. use Term::ReadKey ;
  728. use Test::More ;
  729. use Time::HiRes qw( time sleep ) ;
  730. use Time::Local ;
  731. use Unicode::String ;
  732. use Readonly ;
  733. use Sys::MemInfo ;
  734. use Regexp::Common ;
  735. use Text::ParseWords ; # for quotewords()
  736. use File::Tail ;
  737. local $OUTPUT_AUTOFLUSH = 1 ;
  738. # constants
  739. # Let us do like sysexits.h
  740. # /usr/include/sysexits.h
  741. # and https://www.tldp.org/LDP/abs/html/exitcodes.html
  742. # Should avoid 2 126 127 128..128+64=192 255
  743. # Should use 0 1 3..125 193..254
  744. Readonly my $EX_OK => 0 ; #/* successful termination */
  745. Readonly my $EX_USAGE => 64 ; #/* command line usage error */
  746. #Readonly my $EX_DATAERR => 65 ; #/* data format error */
  747. Readonly my $EX_NOINPUT => 66 ; #/* cannot open input */
  748. #Readonly my $EX_NOUSER => 67 ; #/* addressee unknown */
  749. #Readonly my $EX_NOHOST => 68 ; #/* host name unknown */
  750. Readonly my $EX_UNAVAILABLE => 69 ; #/* service unavailable */
  751. Readonly my $EX_SOFTWARE => 70 ; #/* internal software error */
  752. #Readonly my $EX_OSERR => 71 ; #/* system error (e.g., can't fork) */
  753. #Readonly my $EX_OSFILE => 72 ; #/* critical OS file missing */
  754. #Readonly my $EX_CANTCREAT => 73 ; #/* can't create (user) output file */
  755. #Readonly my $EX_IOERR => 74 ; #/* input/output error */
  756. #Readonly my $EX_TEMPFAIL => 75 ; #/* temp failure; user is invited to retry */
  757. #Readonly my $EX_PROTOCOL => 76 ; #/* remote error in protocol */
  758. #Readonly my $EX_NOPERM => 77 ; #/* permission denied */
  759. #Readonly my $EX_CONFIG => 78 ; #/* configuration error */
  760. # Mine
  761. Readonly my $EXIT_CATCH_ALL => 1 ; # Any other error
  762. Readonly my $EXIT_BY_SIGNAL => 6 ; # Should be 128+n where n is the sig_num
  763. Readonly my $EXIT_BY_FILE => 7 ;
  764. Readonly my $EXIT_PID_FILE_ERROR => 8 ;
  765. Readonly my $EXIT_CONNECTION_FAILURE => 10 ;
  766. Readonly my $EXIT_TLS_FAILURE => 12 ;
  767. Readonly my $EXIT_AUTHENTICATION_FAILURE => 16 ;
  768. Readonly my $EXIT_SUBFOLDER1_NO_EXISTS => 21 ;
  769. Readonly my $EXIT_WITH_ERRORS => 111 ;
  770. Readonly my $EXIT_WITH_ERRORS_MAX => 112 ;
  771. Readonly my $EXIT_OVERQUOTA => 113 ;
  772. Readonly my $EXIT_ERR_APPEND => 114 ;
  773. Readonly my $EXIT_ERR_FETCH => 115 ;
  774. Readonly my $EXIT_ERR_CREATE => 116 ;
  775. Readonly my $EXIT_ERR_SELECT => 117 ;
  776. Readonly my $EXIT_TRANSFER_EXCEEDED => 118 ;
  777. Readonly my $EXIT_ERR_APPEND_VIRUS => 119 ;
  778. Readonly my $EXIT_TESTS_FAILED => 254 ; # Like Test::More API
  779. Readonly my $EXIT_CONNECTION_FAILURE_HOST1 => 101 ;
  780. Readonly my $EXIT_CONNECTION_FAILURE_HOST2 => 102 ;
  781. Readonly my $EXIT_AUTHENTICATION_FAILURE_USER1 => 161 ;
  782. Readonly my $EXIT_AUTHENTICATION_FAILURE_USER2 => 162 ;
  783. Readonly my %EXIT_TXT => (
  784. $EX_OK => 'EX_OK: successful termination',
  785. $EX_USAGE => 'EX_USAGE: command line usage error',
  786. $EX_NOINPUT => 'EX_NOINPUT: cannot open input',
  787. $EX_UNAVAILABLE => 'EX_UNAVAILABLE: service unavailable',
  788. $EX_SOFTWARE => 'EX_SOFTWARE: internal software error',
  789. $EXIT_CATCH_ALL => 'EXIT_CATCH_ALL',
  790. $EXIT_BY_SIGNAL => 'EXIT_BY_SIGNAL',
  791. $EXIT_BY_FILE => 'EXIT_BY_FILE',
  792. $EXIT_PID_FILE_ERROR => 'EXIT_PID_FILE_ERROR' ,
  793. $EXIT_CONNECTION_FAILURE => 'EXIT_CONNECTION_FAILURE',
  794. $EXIT_TLS_FAILURE => 'EXIT_TLS_FAILURE',
  795. $EXIT_AUTHENTICATION_FAILURE => 'EXIT_AUTHENTICATION_FAILURE',
  796. $EXIT_SUBFOLDER1_NO_EXISTS => 'EXIT_SUBFOLDER1_NO_EXISTS',
  797. $EXIT_WITH_ERRORS => 'EXIT_WITH_ERRORS',
  798. $EXIT_WITH_ERRORS_MAX => 'EXIT_WITH_ERRORS_MAX',
  799. $EXIT_OVERQUOTA => 'EXIT_OVERQUOTA',
  800. $EXIT_ERR_APPEND => 'EXIT_ERR_APPEND',
  801. $EXIT_ERR_APPEND_VIRUS => 'EXIT_ERR_APPEND_VIRUS',
  802. $EXIT_ERR_FETCH => 'EXIT_ERR_FETCH',
  803. $EXIT_ERR_CREATE => 'EXIT_ERR_CREATE',
  804. $EXIT_ERR_SELECT => 'EXIT_ERR_SELECT',
  805. $EXIT_TESTS_FAILED => 'EXIT_TESTS_FAILED',
  806. $EXIT_TRANSFER_EXCEEDED => 'EXIT_TRANSFER_EXCEEDED',
  807. $EXIT_CONNECTION_FAILURE_HOST1 => 'EXIT_CONNECTION_FAILURE_HOST1',
  808. $EXIT_CONNECTION_FAILURE_HOST2 => 'EXIT_CONNECTION_FAILURE_HOST2',
  809. $EXIT_AUTHENTICATION_FAILURE_USER1 => 'EXIT_AUTHENTICATION_FAILURE_USER1',
  810. $EXIT_AUTHENTICATION_FAILURE_USER2 => 'EXIT_AUTHENTICATION_FAILURE_USER2',
  811. ) ;
  812. Readonly my %EXIT_VALUE_OF_ERR_TYPE => (
  813. ERR_APPEND_SIZE => $EXIT_ERR_APPEND,
  814. ERR_OVERQUOTA => $EXIT_OVERQUOTA,
  815. ERR_APPEND => $EXIT_ERR_APPEND,
  816. ERR_APPEND_VIRUS => $EXIT_ERR_APPEND_VIRUS,
  817. ERR_CREATE => $EXIT_ERR_CREATE,
  818. ERR_SELECT => $EXIT_ERR_SELECT,
  819. ERR_Host1_FETCH => $EXIT_ERR_FETCH,
  820. ERR_UNCLASSIFIED => $EXIT_WITH_ERRORS,
  821. ERR_NOTHING_REPORTED => $EXIT_WITH_ERRORS,
  822. ERR_TRANSFER_EXCEEDED => $EXIT_TRANSFER_EXCEEDED,
  823. ERR_CONNECTION_FAILURE_HOST1 => $EXIT_CONNECTION_FAILURE_HOST1,
  824. ERR_CONNECTION_FAILURE_HOST2 => $EXIT_CONNECTION_FAILURE_HOST2,
  825. ERR_AUTHENTICATION_FAILURE_USER1 => $EXIT_AUTHENTICATION_FAILURE_USER1,
  826. ERR_AUTHENTICATION_FAILURE_USER2 => $EXIT_AUTHENTICATION_FAILURE_USER2,
  827. ERR_EXIT_TLS_FAILURE => $EXIT_TLS_FAILURE,
  828. ) ;
  829. Readonly my $DEFAULT_LOGDIR => 'LOG_imapsync' ;
  830. Readonly my $ERRORS_MAX => 50 ; # exit after 50 errors.
  831. Readonly my $ERRORS_MAX_CGI => 20 ; # exit after 20 errors in CGI context.
  832. Readonly my $INTERVAL_TO_EXIT => 2 ; # interval max to exit instead of reconnect
  833. Readonly my $SPLIT => 100 ; # By default, 100 at a time, not more.
  834. Readonly my $SPLIT_FACTOR => 10 ; # init_imap() calls Maxcommandlength( $SPLIT_FACTOR * $split )
  835. # which means default Maxcommandlength is 10*100 = 1000 characters ;
  836. Readonly my $IMAP_PORT => 143 ; # Well know port for IMAP
  837. Readonly my $IMAP_SSL_PORT => 993 ; # Well know port for IMAP over SSL
  838. Readonly my $LAST => -1 ;
  839. Readonly my $MINUS_ONE => -1 ;
  840. Readonly my $MINUS_TWO => -2 ;
  841. Readonly my $RELEASE_NUMBER_EXAMPLE_1 => '1.351' ;
  842. Readonly my $RELEASE_NUMBER_EXAMPLE_2 => 42.4242 ;
  843. Readonly my $TCP_PING_TIMEOUT => 5 ;
  844. Readonly my $DEFAULT_TIMEOUT => 120 ;
  845. Readonly my $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND => 3 ;
  846. Readonly my $DEFAULT_BUFFER_SIZE => 4096 ;
  847. Readonly my $MAX_SLEEP => 2 ; # 2 seconds max for limiting too long sleeps from --maxbytespersecond and --maxmessagespersecond
  848. Readonly my $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12 => 3600 ;
  849. Readonly my $PERMISSION_FILTER => 7777 ;
  850. Readonly my $KIBI => 1024 ;
  851. Readonly my $NUMBER_10 => 10 ;
  852. Readonly my $NUMBER_42 => 42 ;
  853. Readonly my $NUMBER_100 => 100 ;
  854. Readonly my $NUMBER_200 => 200 ;
  855. Readonly my $NUMBER_300 => 300 ;
  856. Readonly my $NUMBER_123456 => 123_456 ;
  857. Readonly my $NUMBER_654321 => 654_321 ;
  858. Readonly my $NUMBER_20_000 => 20_000 ;
  859. Readonly my $QUOTA_PERCENT_LIMIT => 90 ;
  860. Readonly my $NUMBER_104_857_600 => 104_857_600 ;
  861. Readonly my $SIZE_MAX_STR => 64 ;
  862. Readonly my $NB_SECONDS_IN_A_DAY => 86_400 ;
  863. Readonly my $STD_CHAR_PER_LINE => 80 ;
  864. Readonly my $TRUE => 1 ;
  865. Readonly my $FALSE => 0 ;
  866. Readonly my $LAST_RESSORT_SEPARATOR => q{/} ;
  867. Readonly my $CGI_TMPDIR_TOP => '/var/tmp/imapsync_cgi' ;
  868. Readonly my $CGI_HASHFILE => '/var/tmp/imapsync_hash' ;
  869. Readonly my $UMASK_PARANO => '0077' ;
  870. Readonly my $STR_use_releasecheck => q{Check if a new imapsync release is available by adding --releasecheck} ;
  871. Readonly my $GMAIL_MAXSIZE => 35_651_584 ;
  872. Readonly my $FORCE => 1 ;
  873. # if ( 'MSWin32' eq $OSNAME )
  874. # if ( 'darwin' eq $OSNAME )
  875. # if ( 'linux' eq $OSNAME )
  876. # global variables
  877. # Currently working to finish with only $sync, $acc1, $acc2
  878. # Not finished yet...
  879. my(
  880. $sync, $acc1, $acc2,
  881. $debugcontent, $debugflags,
  882. $debuglist, $debugdev, $debugmaxlinelength, $debugcgi,
  883. @include, @exclude, @folderrec,
  884. @folderfirst, @folderlast,
  885. @h1_folders_all, %h1_folders_all,
  886. @h2_folders_all, %h2_folders_all,
  887. @h2_folders_from_1_wanted, %h2_folders_from_1_all,
  888. %requested_folder,
  889. $h1_folders_wanted_nb, $h1_folders_wanted_ct,
  890. @h2_folders_not_in_1,
  891. %h1_subscribed_folder, %h2_subscribed_folder,
  892. %h2_folders_from_1_wanted,
  893. %h2_folders_from_1_several,
  894. $prefix1, $prefix2,
  895. @regexmess, @skipmess, @pipemess, $pipemesscheck,
  896. $syncflagsaftercopy,
  897. $syncinternaldates,
  898. $idatefromheader,
  899. $minsize, $maxage, $minage,
  900. $search,
  901. @useheader, %useheader,
  902. $skipsize, $allowsizemismatch, $buffersize,
  903. $authmd5, $authmd51, $authmd52,
  904. $subscribed, $subscribe, $subscribeall,
  905. $help,
  906. $fast,
  907. $nb_msg_skipped_dry_mode,
  908. $h2_nb_msg_noheader,
  909. $h1_bytes_processed,
  910. $h1_nb_msg_end, $h1_bytes_end,
  911. $h2_nb_msg_end, $h2_bytes_end,
  912. $timestart_int,
  913. $uid1, $uid2,
  914. $split1, $split2,
  915. $modulesversion,
  916. $delete2folders, $delete2foldersonly, $delete2foldersbutnot,
  917. $usecache, $debugcache, $cacheaftercopy,
  918. $wholeheaderifneeded, %h1_msgs_copy_by_uid, $useuid, $h2_uidguess,
  919. $checkmessageexists,
  920. $messageidnodomain,
  921. $fixInboxINBOX,
  922. $maxlinelength, $maxlinelengthcmd,
  923. $minmaxlinelength,
  924. $fixcolonbug,
  925. $create_folder_old,
  926. $skipcrossduplicates, $debugcrossduplicates,
  927. $disarmreadreceipts,
  928. $mixfolders,
  929. $fetch_hash_set,
  930. $cgidir,
  931. %month_abrev,
  932. $SSL_VERIFY_POLICY,
  933. $warn_release,
  934. ) ;
  935. single_sync( $sync, $acc1, $acc2 );
  936. sub single_sync
  937. {
  938. # main program
  939. # global variables initialization
  940. # I'm currently removing all global variables except $sync $acc1 $acc2
  941. # passing each of them under
  942. # $sync->{variable_name}
  943. # or $acc1->{variable_name}
  944. # or $acc1->{variable_name}
  945. #
  946. $acc1 = {} ;
  947. $acc2 = {} ;
  948. $sync->{ acc1 } = $acc1 ;
  949. $sync->{ acc2 } = $acc2 ;
  950. $acc1->{ Side } = 'Host1' ;
  951. $acc2->{ Side } = 'Host2' ;
  952. $sync->{timestart} = time ; # Is a float because of use Time::HiRres
  953. $sync->{rcs} = q{$Id: imapsync,v 2.148 2021/07/22 14:21:09 gilles Exp gilles $} ;
  954. $sync->{ memory_consumption_at_start } = memory_consumption( ) || 0 ;
  955. my @loadavg = loadavg( ) ;
  956. $sync->{ cpu_number } = cpu_number( ) ;
  957. $sync->{ loaddelay } = load_and_delay( $sync->{ cpu_number }, @loadavg ) ;
  958. $sync->{ loaddelay } = 0 ;
  959. $sync->{ loadavg } = join( q{ }, $loadavg[ 0 ] )
  960. . " on $sync->{cpu_number} cores and "
  961. . ram_memory_info( ) ;
  962. $sync->{ total_bytes_transferred } = 0 ;
  963. $sync->{ total_bytes_skipped } = 0 ;
  964. $sync->{ nb_msg_transferred } = 0 ;
  965. $sync->{ nb_msg_skipped } = $nb_msg_skipped_dry_mode = 0 ;
  966. $sync->{ acc1 }->{ nb_msg_deleted } = 0 ;
  967. $sync->{ acc2 }->{ nb_msg_deleted } = 0 ;
  968. $sync->{ acc1 }->{ nb_msg_duplicate } = 0 ;
  969. $sync->{ acc2 }->{ nb_msg_duplicate } = 0 ;
  970. $sync->{ h1_nb_msg_noheader } = 0 ;
  971. $h2_nb_msg_noheader = 0 ;
  972. $sync->{ h1_nb_msg_start } = 0 ;
  973. $sync->{ h1_bytes_start } = 0 ;
  974. $sync->{ h2_nb_msg_start } = 0 ;
  975. $sync->{ h2_bytes_start } = 0 ;
  976. $sync->{ h1_nb_msg_processed } = $h1_bytes_processed = 0 ;
  977. $sync->{ h2_nb_msg_crossdup } = 0 ;
  978. #$h1_nb_msg_end = $h1_bytes_end = 0 ;
  979. #$h2_nb_msg_end = $h2_bytes_end = 0 ;
  980. $sync->{ nb_errors } = 0;
  981. $sync->{ biggest_message_transferred } = 0;
  982. %month_abrev = (
  983. Jan => '00',
  984. Feb => '01',
  985. Mar => '02',
  986. Apr => '03',
  987. May => '04',
  988. Jun => '05',
  989. Jul => '06',
  990. Aug => '07',
  991. Sep => '08',
  992. Oct => '09',
  993. Nov => '10',
  994. Dec => '11',
  995. );
  996. # Just create a CGI object if under cgi context only.
  997. # Needed for the get_options() call
  998. cgibegin( $sync ) ;
  999. # In cgi context, printing must start by the header so we delay other prints by using output() storage
  1000. my $options_good = get_options( $sync, @ARGV ) ;
  1001. # Is it the first myprint?
  1002. cgibuildheader( $sync ) ;
  1003. docker_context( $sync ) ;
  1004. print_output_if_needed( $sync ) ;
  1005. output_reset_with( $sync ) ;
  1006. # don't go on if options are not all known.
  1007. if ( ! defined $options_good ) { exit $EX_USAGE ; }
  1008. # If you want releasecheck not to be done by default (like the github maintainer),
  1009. # then just uncomment the first "$sync->{releasecheck} =" line, the line ending with "0 ;",
  1010. # the second line (ending with "1 ;") can then stay active or be commented,
  1011. # the result will be the same: no releasecheck by default (because 0 is then the defined value).
  1012. #$sync->{releasecheck} = defined $sync->{releasecheck} ? $sync->{releasecheck} : 0 ;
  1013. $sync->{releasecheck} = defined $sync->{releasecheck} ? $sync->{releasecheck} : 1 ;
  1014. # just the version
  1015. if ( $sync->{ version } ) {
  1016. myprint( imapsync_version( $sync ), "\n" ) ;
  1017. return 0 ;
  1018. }
  1019. #$sync->{debugenv} = 1 ;
  1020. $sync->{debugenv} and printenv( $sync ) ; # if option --debugenv
  1021. load_modules( ) ;
  1022. # after_get_options call usage and exit if --help or options were not well got
  1023. after_get_options( $sync, $options_good ) ;
  1024. #local $ENV{TZ} = 'GMT' if ( under_cgi_context( $sync ) and 'MSWin32' ne $OSNAME ) ;
  1025. #output( $sync, localtime(time) . " " . gmtime(time) . "\n" ) ;
  1026. # Under CGI environment, fix caveat emptor potential issues
  1027. cgisetcontext( $sync ) ;
  1028. # --gmail --gmail --exchange --office etc.
  1029. easyany( $sync ) ;
  1030. $sync->{ sanitize } = defined $sync->{ sanitize } ? $sync->{ sanitize } : 1 ;
  1031. sanitize( $sync ) ;
  1032. $sync->{ tmpdir } ||= File::Spec->tmpdir( ) ;
  1033. # Unit tests
  1034. my $unittestssuite = unittestssuite( $sync ) ;
  1035. if ( condition_to_leave_after_tests( $sync ) )
  1036. {
  1037. return $unittestssuite ;
  1038. }
  1039. # init live varaiables
  1040. if ( $sync->{ testslive } )
  1041. {
  1042. testslive_init( $sync ) ;
  1043. }
  1044. if ( $sync->{ testslive6 } )
  1045. {
  1046. testslive6_init( $sync ) ;
  1047. }
  1048. define_pidfile( $sync ) ;
  1049. if ( $sync->{ abortbyfile } ) { $sync->{ abort } = 1 ; }
  1050. install_signals( $sync ) ;
  1051. $sync->{ log } = defined $sync->{ log } ? $sync->{ log } : 1 ;
  1052. $sync->{ errorsdump } = defined $sync->{ errorsdump } ? $sync->{ errorsdump } : 1 ;
  1053. $sync->{ errorsmax } = defined $sync->{ errorsmax } ? $sync->{ errorsmax } : $ERRORS_MAX ;
  1054. # log and output
  1055. binmode STDOUT, ":encoding(UTF-8)" ;
  1056. if ( $sync->{ log } ) {
  1057. setlogfile( $sync ) ;
  1058. teelaunch( $sync ) ;
  1059. # now $sync->{tee} is a filehandle to STDOUT and the logfile
  1060. }
  1061. #binmode STDERR, ":encoding(UTF-8)" ;
  1062. # STDERR goes to the same place: LOG and STDOUT (if logging is on)
  1063. # Useful only for --debugssl
  1064. $sync->{tee} and local *STDERR = *${$sync->{tee}}{IO} ;
  1065. $timestart_int = int( $sync->{timestart} ) ;
  1066. $sync->{timebefore} = $sync->{timestart} ;
  1067. $sync->{ timestart_str } = localtimez( $sync->{timestart} ) ;
  1068. # The prints in the log starts here
  1069. myprint( localhost_info( $sync ), "\n" ) ;
  1070. myprint( "Transfer started at $sync->{ timestart_str }\n" ) ;
  1071. myprint( "PID is $PROCESS_ID my PPID is ", mygetppid( ), "\n" ) ;
  1072. announcelogfile( $sync ) ;
  1073. myprint( "Load is " . ( join( q{ }, loadavg( ) ) || 'unknown' ), " on $sync->{cpu_number} cores\n" ) ;
  1074. #myprintf( "Memory consumption so far: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  1075. myprint( 'Current directory is ' . getcwd( ) . "\n" ) ;
  1076. myprint( 'Real user id is ' . getpwuid_any_os( $REAL_USER_ID ) . " (uid $REAL_USER_ID)\n" ) ;
  1077. myprint( 'Effective user id is ' . getpwuid_any_os( $EFFECTIVE_USER_ID ). " (euid $EFFECTIVE_USER_ID)\n" ) ;
  1078. $modulesversion = defined $modulesversion ? $modulesversion : 1 ;
  1079. $warn_release = ( $sync->{releasecheck} ) ? check_last_release( ) : $STR_use_releasecheck ;
  1080. $wholeheaderifneeded = defined $wholeheaderifneeded ? $wholeheaderifneeded : 1;
  1081. # Activate --usecache if --useuid is set and there is no --nousecache
  1082. $usecache = 1 if ( $useuid and ( ! defined $usecache ) ) ;
  1083. $cacheaftercopy = 1 if ( $usecache and ( ! defined $cacheaftercopy ) ) ;
  1084. $sync->{ checkfoldersexist } = defined $sync->{ checkfoldersexist } ? $sync->{ checkfoldersexist } : 1 ;
  1085. $checkmessageexists = defined $checkmessageexists ? $checkmessageexists : 0 ;
  1086. $sync->{ expungeaftereach } = defined $sync->{ expungeaftereach } ? $sync->{ expungeaftereach } : 1 ;
  1087. # abletosearch is on by default
  1088. $sync->{abletosearch} = defined $sync->{abletosearch} ? $sync->{abletosearch} : 1 ;
  1089. $sync->{abletosearch1} = defined $sync->{abletosearch1} ? $sync->{abletosearch1} : $sync->{abletosearch} ;
  1090. $sync->{abletosearch2} = defined $sync->{abletosearch2} ? $sync->{abletosearch2} : $sync->{abletosearch} ;
  1091. $checkmessageexists = 0 if ( not $sync->{abletosearch1} ) ;
  1092. $sync->{ trylogin } = defined $sync->{ trylogin } ? $sync->{ trylogin } : 1 ;
  1093. $sync->{showpasswords} = defined $sync->{showpasswords} ? $sync->{showpasswords} : 0 ;
  1094. $sync->{ fixslash2 } = defined $sync->{ fixslash2 } ? $sync->{ fixslash2 } : 1 ;
  1095. $fixInboxINBOX = defined $fixInboxINBOX ? $fixInboxINBOX : 1 ;
  1096. $create_folder_old = defined $create_folder_old ? $create_folder_old : 0 ;
  1097. $mixfolders = defined $mixfolders ? $mixfolders : 1 ;
  1098. $sync->{automap} = defined $sync->{automap} ? $sync->{automap} : 0 ;
  1099. $sync->{ delete2duplicates } = 1 if ( $sync->{ delete2 } and ( ! defined $sync->{ delete2duplicates } ) ) ;
  1100. $sync->{maxmessagespersecond} = defined $sync->{maxmessagespersecond} ? $sync->{maxmessagespersecond} : 0 ;
  1101. $sync->{maxbytespersecond} = defined $sync->{maxbytespersecond} ? $sync->{maxbytespersecond} : 0 ;
  1102. $sync->{sslcheck} = defined $sync->{sslcheck} ? $sync->{sslcheck} : 1 ;
  1103. myprint( banner_imapsync( $sync, @ARGV ) ) ;
  1104. myprint( "Temp directory is $sync->{ tmpdir } ( to change it use --tmpdir dirpath )\n" ) ;
  1105. myprint( output( $sync ) ) ;
  1106. output_reset_with( $sync ) ;
  1107. do_valid_directory( $sync->{ tmpdir } ) || croak "Error creating tmpdir $sync->{ tmpdir } : $OS_ERROR" ;
  1108. remove_pidfile_not_running( $sync->{ pidfile } ) ;
  1109. # if another imapsync is running then tail -f its logfile and exit
  1110. # useful in cgi context
  1111. if ( $sync->{ tail } and tail( $sync ) )
  1112. {
  1113. exit_clean( $sync, $EX_OK, "Tail -f finished. Now finishing myself processus $PROCESS_ID\n" ) ;
  1114. exit $EX_OK ;
  1115. }
  1116. if ( ! write_pidfile( $sync ) ) {
  1117. myprint( "Exiting with return value $EXIT_PID_FILE_ERROR ($EXIT_TXT{$EXIT_PID_FILE_ERROR}) $sync->{nb_errors}/$sync->{errorsmax} nb_errors/max_errors PID $PROCESS_ID\n" ) ;
  1118. exit $EXIT_PID_FILE_ERROR ;
  1119. }
  1120. # New place for abort
  1121. # abort before simulong in order to be able to abort a simulong sync
  1122. if ( $sync->{ abort } )
  1123. {
  1124. abort( $sync ) ;
  1125. # well, the abort job is done, because even when not succeeded
  1126. # in aborting another run, this run has to end without doing any
  1127. # thing else
  1128. exit $EX_OK ;
  1129. }
  1130. # simulong is just a loop printing some lines for xx seconds with option "--simulong xx".
  1131. simulong( $sync ) ;
  1132. # New place for cgiload 2019_03_03
  1133. # because I want to log it
  1134. # Can break here if load is too heavy
  1135. # Have in mind the CGI header has already a 503 Service Unavailable
  1136. cgiload( $sync ) ;
  1137. $fixcolonbug = defined $fixcolonbug ? $fixcolonbug : 1 ;
  1138. if ( $usecache and $fixcolonbug ) { tmpdir_fix_colon_bug( $sync ) } ;
  1139. $modulesversion and myprint( "Modules version list ( use --no-modulesversion to turn off printing this Perl modules list ):\n", modulesversion(), "\n" ) ;
  1140. check_lib_version( $sync ) or
  1141. croak "imapsync needs perl lib Mail::IMAPClient release 3.30 or superior.\n";
  1142. if ( $sync->{ justbanner } )
  1143. {
  1144. myprint( "Exiting because of --justbanner\n" ) ;
  1145. exit_clean( $sync, $EX_OK ) ;
  1146. }
  1147. # turn on RFC standard flags correction like \SEEN -> \Seen
  1148. $sync->{ flagscase } = defined $sync->{ flagscase } ? $sync->{ flagscase } : 1 ;
  1149. # Use PERMANENTFLAGS if available
  1150. $sync->{ filterflags } = defined $sync->{ filterflags } ? $sync->{ filterflags } : 1 ;
  1151. filterbuggyflags( $sync ) ;
  1152. # sync flags just after an APPEND, some servers ignore the flags given in the APPEND
  1153. # like MailEnable IMAP server.
  1154. # Off by default since it takes time.
  1155. $syncflagsaftercopy = defined $syncflagsaftercopy ? $syncflagsaftercopy : 0 ;
  1156. # update flags on host2 for already transferred messages
  1157. $sync->{resyncflags} = defined $sync->{resyncflags} ? $sync->{resyncflags} : 1 ;
  1158. if ( $sync->{resyncflags} ) {
  1159. myprint( "Info: will resync flags for already transferred messages. Use --noresyncflags to not resync flags.\n" ) ;
  1160. }else{
  1161. myprint( "Info: will not resync flags for already transferred messages. Use --resyncflags to resync flags.\n" ) ;
  1162. }
  1163. sslcheck( $sync ) ;
  1164. #print Data::Dumper->Dump( [ \$sync ] ) ;
  1165. $split1 ||= $SPLIT ;
  1166. $split2 ||= $SPLIT ;
  1167. #$sync->{host1} || missing_option( $sync, '--host1' ) ;
  1168. $sync->{host1} = sanitize_host( $sync->{host1} ) ;
  1169. $sync->{port1} ||= ( $sync->{ssl1} ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  1170. #$sync->{host2} || missing_option( $sync, '--host2' ) ;
  1171. $sync->{host2} = sanitize_host( $sync->{host2} ) ;
  1172. $sync->{port2} ||= ( $sync->{ssl2} ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  1173. $acc1->{ debugimap } = $acc2->{ debugimap } = 1 if ( $sync->{ debugimap } ) ;
  1174. # Set on debug mode if one of the imap dialogs are in debug.
  1175. # imap dialog without the debug mode is scary and useless.
  1176. $sync->{ debug } = 1 if ( $acc1->{ debugimap } or $acc2->{ debugimap } ) ;
  1177. # By default, don't take size to compare
  1178. $skipsize = (defined $skipsize) ? $skipsize : 1;
  1179. $uid1 = defined $uid1 ? $uid1 : 1;
  1180. $uid2 = defined $uid2 ? $uid2 : 1;
  1181. $subscribe = defined $subscribe ? $subscribe : 1;
  1182. # Allow size mismatch by default
  1183. $allowsizemismatch = defined $allowsizemismatch ? $allowsizemismatch : 1;
  1184. if ( defined $delete2foldersbutnot or defined $delete2foldersonly ) {
  1185. $delete2folders = 1 ;
  1186. }
  1187. my %SSL_VERIFY_STR ;
  1188. Readonly $SSL_VERIFY_POLICY => IO::Socket::SSL::SSL_VERIFY_NONE( ) ;
  1189. Readonly %SSL_VERIFY_STR => (
  1190. IO::Socket::SSL::SSL_VERIFY_NONE( ) => 'SSL_VERIFY_NONE, ie, do not check the certificate server.' ,
  1191. IO::Socket::SSL::SSL_VERIFY_PEER( ) => 'SSL_VERIFY_PEER, ie, check the certificate server' ,
  1192. ) ;
  1193. $IO::Socket::SSL::DEBUG = defined( $sync->{debugssl} ) ? $sync->{debugssl} : 1 ;
  1194. if ( $sync->{ssl1} or $sync->{ssl2} or $sync->{tls1} or $sync->{tls2}) {
  1195. 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" ) ;
  1196. }
  1197. if ( $sync->{ssl1} ) {
  1198. 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} ) ;
  1199. 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" ) ;
  1200. # $sync->{ acc1 }->{sslargs}->{SSL_verify_mode}
  1201. }
  1202. if ( $sync->{ssl2} ) {
  1203. 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} ) ;
  1204. 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" ) ;
  1205. }
  1206. # ID on by default since 1.832
  1207. $sync->{id} = defined $sync->{id} ? $sync->{id} : 1 ;
  1208. if ( $sync->{justconnect}
  1209. or not $sync->{user1}
  1210. or not $sync->{user2}
  1211. or not $sync->{host1}
  1212. or not $sync->{host2}
  1213. )
  1214. {
  1215. my $justconnect = justconnect( $sync ) ;
  1216. myprint( debugmemory( $sync, " after justconnect() call" ) ) ;
  1217. exit_clean( $sync, $EX_OK,
  1218. "Exiting after a justconnect on host(s): $justconnect\n"
  1219. ) ;
  1220. }
  1221. #$sync->{user1} || missing_option( $sync, '--user1' ) ;
  1222. #$sync->{user2} || missing_option( $sync, '--user2' ) ;
  1223. $syncinternaldates = defined $syncinternaldates ? $syncinternaldates : 1;
  1224. # Turn on expunge if there is not explicit option --noexpunge1 and option
  1225. # --delete1 is given.
  1226. # Done because --delete1 --noexpunge1 is very dangerous on the second run:
  1227. # the Deleted flag is then synced to all previously transferred messages.
  1228. # So --delete1 implies --expunge1 is a better usability default behavior.
  1229. if ( $sync->{ delete1 } ) {
  1230. if ( ! defined $sync->{ expunge1 } ) {
  1231. myprint( "Info: turning on --expunge1 because --delete1 --noexpunge1 is very dangerous on the second run.\n" ) ;
  1232. $sync->{ expunge1 } = 1 ;
  1233. }
  1234. myprint( "Info: if expunging after each message slows down too much the sync then use --noexpungeaftereach to speed up\n" ) ;
  1235. }
  1236. if ( $sync->{ uidexpunge2 } and not Mail::IMAPClient->can( 'uidexpunge' ) ) {
  1237. myprint( "Failure: uidexpunge not supported (IMAPClient release < 3.17), use nothing or --expunge2 instead\n" ) ;
  1238. $sync->{nb_errors}++ ;
  1239. exit_clean( $sync, $EX_SOFTWARE ) ;
  1240. }
  1241. if ( ( $sync->{ delete2 } or $sync->{ delete2duplicates } ) and not defined $sync->{ uidexpunge2 } ) {
  1242. if ( Mail::IMAPClient->can( 'uidexpunge' ) ) {
  1243. myprint( "Info: will act as --uidexpunge2\n" ) ;
  1244. $sync->{ uidexpunge2 } = 1 ;
  1245. }elsif ( not defined $sync->{ expunge2 } ) {
  1246. myprint( "Info: will act as --expunge2 (no uidexpunge support)\n" ) ;
  1247. $sync->{ expunge2 } = 1 ;
  1248. }
  1249. }
  1250. if ( $sync->{ delete1 } and $sync->{ delete2 } ) {
  1251. myprint( "Warning: using --delete1 and --delete2 together is almost always a bad idea. "
  1252. . "You should probably launch two runs, the first with --delete2 for a strict sync, "
  1253. . "then the second with --delete1 to remove messages from the source account. "
  1254. . "Exiting imapsync.\n" ) ;
  1255. $sync->{ nb_errors }++ ;
  1256. exit_clean( $sync, $EX_USAGE ) ;
  1257. }
  1258. if ( $idatefromheader ) {
  1259. myprint( 'Turned ON idatefromheader, ',
  1260. "will set the internal dates on host2 from the 'Date:' header line.\n" ) ;
  1261. $syncinternaldates = 0 ;
  1262. }
  1263. if ( $syncinternaldates ) {
  1264. myprint( 'Info: turned ON syncinternaldates, ',
  1265. "will set the internal dates (arrival dates) on host2 same as host1.\n" ) ;
  1266. }else{
  1267. myprint( "Info: turned OFF syncinternaldates\n" ) ;
  1268. }
  1269. if ( defined $authmd5 and $authmd5 ) {
  1270. $authmd51 = 1 ;
  1271. $authmd52 = 1 ;
  1272. }
  1273. if ( defined $authmd51 and $authmd51 ) {
  1274. $acc1->{ authmech } ||= 'CRAM-MD5' ;
  1275. }
  1276. else{
  1277. $acc1->{ authmech } ||= $acc1->{ authuser } ? 'PLAIN' : 'LOGIN' ;
  1278. }
  1279. if ( defined $authmd52 and $authmd52 ) {
  1280. $acc2->{ authmech } ||= 'CRAM-MD5';
  1281. }
  1282. else{
  1283. $acc2->{ authmech } ||= $acc2->{ authuser } ? 'PLAIN' : 'LOGIN';
  1284. }
  1285. $acc1->{ authmech } = uc $acc1->{ authmech } ;
  1286. $acc2->{ authmech } = uc $acc2->{ authmech } ;
  1287. if ( defined $acc1->{ proxyauth } && !$acc1->{ authuser } )
  1288. {
  1289. missing_option( $sync, 'With --proxyauth1, --authuser1' ) ;
  1290. }
  1291. if ( defined $acc2->{ proxyauth } && !$acc2->{ authuser } )
  1292. {
  1293. missing_option( $sync, 'With --proxyauth2, --authuser2' ) ;
  1294. }
  1295. myprint( "Host1: will try to use $acc1->{ authmech } authentication on host1\n") ;
  1296. myprint( "Host2: will try to use $acc2->{ authmech } authentication on host2\n") ;
  1297. $sync->{ timeout } = defined $sync->{ timeout } ?$sync->{ timeout } : $DEFAULT_TIMEOUT ;
  1298. $sync->{ acc1 }->{timeout} = defined $sync->{ acc1 }->{timeout} ? $sync->{ acc1 }->{timeout} : $sync->{ timeout } ;
  1299. myprint( "Host1: imap connection timeout is $sync->{ acc1 }->{timeout} seconds\n") ;
  1300. $sync->{ acc2 }->{timeout} = defined $sync->{ acc2 }->{timeout} ? $sync->{ acc2 }->{timeout} : $sync->{ timeout } ;
  1301. myprint( "Host2: imap connection timeout is $sync->{ acc2 }->{timeout} seconds\n" ) ;
  1302. if ( under_cgi_context( $sync ) )
  1303. {
  1304. myprint( "Under CGI context, a timeout can occur from the webserver, see https://imapsync.lamiral.info/INSTALL.d/INSTALL.OnlineUI.txt\n" ) ;
  1305. }
  1306. $sync->{ syncacls } = defined $sync->{ syncacls } ? $sync->{ syncacls } : 0 ;
  1307. # No folders sizes if --justfolders, unless really wanted.
  1308. if (
  1309. $sync->{ justfolders }
  1310. and not defined $sync->{ foldersizes }
  1311. and not $sync->{ justfoldersizes } )
  1312. {
  1313. $sync->{ foldersizes } = 0 ;
  1314. $sync->{ foldersizesatend } = 1 ;
  1315. }
  1316. $sync->{ foldersizes } = ( defined $sync->{ foldersizes } ) ? $sync->{ foldersizes } : 1 ;
  1317. $sync->{ foldersizesatend } = ( defined $sync->{ foldersizesatend } ) ? $sync->{ foldersizesatend } : $sync->{ foldersizes } ;
  1318. $sync->{ checknoabletosearch } = ( defined $sync->{ checknoabletosearch } ) ? $sync->{ checknoabletosearch } : 1 ;
  1319. $acc1->{ fastio } = defined $acc1->{ fastio } ? $acc1->{ fastio } : 0 ;
  1320. $acc2->{ fastio } = defined $acc2->{ fastio } ? $acc2->{ fastio } : 0 ;
  1321. $acc1->{ reconnectretry } = defined $acc1->{ reconnectretry } ? $acc1->{ reconnectretry } : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  1322. $acc2->{ reconnectretry } = defined $acc2->{ reconnectretry } ? $acc2->{ reconnectretry } : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  1323. if ( ! @useheader ) { @useheader = qw( Message-Id Received ) ; }
  1324. # Make a hash %useheader of each --useheader 'key' in uppercase
  1325. for ( @useheader ) { $sync->{useheader}->{ uc $_ } = undef } ;
  1326. #myprint( Data::Dumper->Dump( [ \%useheader ] ) ) ;
  1327. #exit ;
  1328. myprint( "Host1: IMAP server [$sync->{host1}] port [$sync->{port1}] user [$sync->{user1}]\n" ) ;
  1329. myprint( "Host2: IMAP server [$sync->{host2}] port [$sync->{port2}] user [$sync->{user2}]\n" ) ;
  1330. get_password1( $sync ) ;
  1331. get_password2( $sync ) ;
  1332. # --dry1 make imapsync not fetching messages from host1, it is on when --dry is on.
  1333. # Use --dry --nodry1 to make imapsync fetching messages from host1,
  1334. # It is useful when debugging transformation options like --pipemess or --regexmess
  1335. $sync->{dry1} = defined $sync->{dry1} ? $sync->{dry1} : $sync->{dry} ;
  1336. $sync->{dry_message} = q{} ;
  1337. if( $sync->{dry} ) {
  1338. $sync->{dry_message} = "\t(not really since --dry mode)" ;
  1339. }
  1340. $sync->{ search1 } ||= $search if ( $search ) ;
  1341. $sync->{ search2 } ||= $search if ( $search ) ;
  1342. if ( $disarmreadreceipts )
  1343. {
  1344. push @regexmess, q{s{\A((?:[^\n]+\r\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims} ;
  1345. }
  1346. $pipemesscheck = ( defined $pipemesscheck ) ? $pipemesscheck : 1 ;
  1347. if ( @pipemess and $pipemesscheck ) {
  1348. myprint( 'Checking each --pipemess command, '
  1349. . join( q{, }, @pipemess )
  1350. . ", with an space string. ( Can avoid this check with --nopipemesscheck )\n" ) ;
  1351. my $string = pipemess( q{ }, @pipemess ) ;
  1352. # string undef means something was bad.
  1353. if ( not ( defined $string ) ) {
  1354. $sync->{nb_errors}++ ;
  1355. exit_clean( $sync, $EX_USAGE,
  1356. "Error: one of --pipemess command is bad, check it\n"
  1357. ) ;
  1358. }
  1359. myprint( "Ok with each --pipemess @pipemess\n" ) ;
  1360. }
  1361. if ( $maxlinelengthcmd ) {
  1362. myprint( "Checking --maxlinelengthcmd command,
  1363. $maxlinelengthcmd, with an space string.\n"
  1364. ) ;
  1365. my $string = pipemess( q{ }, $maxlinelengthcmd ) ;
  1366. # string undef means something was bad.
  1367. if ( not ( defined $string ) ) {
  1368. $sync->{nb_errors}++ ;
  1369. exit_clean( $sync, $EX_USAGE,
  1370. "Error: --maxlinelengthcmd command is bad, check it\n"
  1371. ) ;
  1372. }
  1373. myprint( "Ok with --maxlinelengthcmd $maxlinelengthcmd\n" ) ;
  1374. }
  1375. if ( @regexmess ) {
  1376. my $string = regexmess( q{ } ) ;
  1377. myprint( "Checking each --regexmess command with an space string.\n" ) ;
  1378. # string undef means one of the eval regex was bad.
  1379. if ( not ( defined $string ) ) {
  1380. #errors_incr( $sync, 'Warning: one of --regexmess option may be bad, check them' ) ;
  1381. exit_clean( $sync, $EX_USAGE,
  1382. "Error: one of --regexmess option is bad, check it\n"
  1383. ) ;
  1384. }
  1385. myprint( "Ok with each --regexmess\n" ) ;
  1386. }
  1387. if ( @skipmess ) {
  1388. myprint( "Checking each --skipmess command with an space string.\n" ) ;
  1389. my $match = skipmess( q{ } ) ;
  1390. # match undef means one of the eval regex was bad.
  1391. if ( not ( defined $match ) ) {
  1392. $sync->{nb_errors}++ ;
  1393. exit_clean( $sync, $EX_USAGE,
  1394. "Error: one of --skipmess option is bad, check it\n"
  1395. ) ;
  1396. }
  1397. myprint( "Ok with each --skipmess\n" ) ;
  1398. }
  1399. if ( $sync->{ regexflag } ) {
  1400. myprint( "Checking each --regexflag command with an space string.\n" ) ;
  1401. my $string = regexflags( $sync, q{ } ) ;
  1402. # string undef means one of the eval regex was bad.
  1403. if ( not ( defined $string ) ) {
  1404. $sync->{nb_errors}++ ;
  1405. exit_clean( $sync, $EX_USAGE,
  1406. "Error: one of --regexflag option is bad, check it\n"
  1407. ) ;
  1408. }
  1409. myprint( "Ok with each --regexflag\n" ) ;
  1410. }
  1411. $sync->{imap1} = login_imap( $sync->{host1}, $sync->{port1}, $sync->{user1}, $sync->{password1},
  1412. $sync->{ssl1}, $sync->{tls1},
  1413. $uid1, $split1, $sync->{ acc1 }, $sync ) ;
  1414. $sync->{imap2} = login_imap( $sync->{host2}, $sync->{port2}, $sync->{user2}, $sync->{password2},
  1415. $sync->{ssl2}, $sync->{tls2},
  1416. $uid2, $split2, $sync->{ acc2 }, $sync ) ;
  1417. $sync->{ debug } and $sync->{imap1} and myprint( 'Host1 Buffer I/O: ', $sync->{imap1}->Buffer(), "\n" ) ;
  1418. $sync->{ debug } and $sync->{imap2} and myprint( 'Host2 Buffer I/O: ', $sync->{imap2}->Buffer(), "\n" ) ;
  1419. if ( ! $sync->{imap1} || ! $sync->{imap2} )
  1420. {
  1421. exit_most_errors( $sync ) ;
  1422. }
  1423. myprint( "Host1: state Authenticated\n" ) ;
  1424. myprint( "Host2: state Authenticated\n" ) ;
  1425. myprint( 'Host1 capability once authenticated: ', join(q{ }, @{ $sync->{imap1}->capability() || [] }), "\n" ) ;
  1426. #myprint( Data::Dumper->Dump( [ $sync->{imap1} ] ) ) ;
  1427. #myprint( "imap4rev1: " . $sync->{imap1}->imap4rev1() . "\n" ) ;
  1428. myprint( 'Host2 capability once authenticated: ', join(q{ }, @{ $sync->{imap2}->capability() || [] }), "\n" ) ;
  1429. imap_id_stuff( $sync ) ;
  1430. #quota( $sync, $sync->{imap1}, 'h1' ) ; # quota on host1 is useless and pollute host2 output.
  1431. quota( $sync, $sync->{imap2}, 'h2' ) ;
  1432. maxsize_setting( $sync ) ;
  1433. if ( $sync->{ justlogin } ) {
  1434. $sync->{imap1}->logout( ) ;
  1435. $sync->{imap2}->logout( ) ;
  1436. exit_clean( $sync, $EX_OK, "Exiting because of --justlogin\n" ) ;
  1437. }
  1438. #
  1439. # Folder stuff
  1440. #
  1441. $h1_folders_wanted_nb = 0 ; # counter of folders to be done.
  1442. $h1_folders_wanted_ct = 0 ; # counter of folders done.
  1443. # All folders on host1 and host2
  1444. @h1_folders_all = sort $sync->{imap1}->folders( ) ;
  1445. @h2_folders_all = sort $sync->{imap2}->folders( ) ;
  1446. myprint( 'Host1: found ', scalar @h1_folders_all , " folders.\n" ) ;
  1447. myprint( 'Host2: found ', scalar @h2_folders_all , " folders.\n" ) ;
  1448. foreach my $f ( @h1_folders_all )
  1449. {
  1450. $h1_folders_all{ $f } = 1
  1451. }
  1452. foreach my $f ( @h2_folders_all )
  1453. {
  1454. $h2_folders_all{ $f } = 1 ;
  1455. $sync->{h2_folders_all_UPPER}{ uc $f } = 1 ;
  1456. }
  1457. $sync->{h1_folders_all} = \%h1_folders_all ;
  1458. $sync->{h2_folders_all} = \%h2_folders_all ;
  1459. private_folders_separators_and_prefixes( ) ;
  1460. # Make a hash of subscribed folders in both servers.
  1461. for ( $sync->{imap1}->subscribed( ) ) { $h1_subscribed_folder{ $_ } = 1 } ;
  1462. for ( $sync->{imap2}->subscribed( ) ) { $h2_subscribed_folder{ $_ } = 1 } ;
  1463. if ( defined $sync->{ subfolder1 } ) {
  1464. subfolder1( $sync ) ;
  1465. }
  1466. if ( defined $sync->{ subfolder2 } ) {
  1467. subfolder2( $sync ) ;
  1468. }
  1469. if ( $fixInboxINBOX and ( my $reg = fix_Inbox_INBOX_mapping( \%h1_folders_all, \%h2_folders_all ) ) ) {
  1470. push @{ $sync->{ regextrans2 } }, $reg ;
  1471. }
  1472. if ( ( $sync->{ folder } and scalar @{ $sync->{ folder } } )
  1473. or $subscribed
  1474. or scalar @folderrec )
  1475. {
  1476. # folders given by option --folder
  1477. if ( $sync->{ folder } and scalar @{ $sync->{ folder } } ) {
  1478. add_to_requested_folders( @{ $sync->{ folder } } ) ;
  1479. }
  1480. # option --subscribed
  1481. if ( $subscribed ) {
  1482. add_to_requested_folders( keys %h1_subscribed_folder ) ;
  1483. }
  1484. # option --folderrec
  1485. if ( scalar @folderrec ) {
  1486. foreach my $folderrec ( @folderrec ) {
  1487. add_to_requested_folders( $sync->{imap1}->folders( $folderrec ) ) ;
  1488. }
  1489. }
  1490. }
  1491. else
  1492. {
  1493. # no include, no folder/subscribed/folderrec options => all folders
  1494. if ( not scalar @include ) {
  1495. 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" ) ;
  1496. add_to_requested_folders( @h1_folders_all ) ;
  1497. }
  1498. }
  1499. # consider (optional) includes and excludes
  1500. if ( scalar @include ) {
  1501. foreach my $include ( @include ) {
  1502. # No, do not add /x after the regex, never.
  1503. # Users would kill you!
  1504. my @included_folders = grep { /$include/ } @h1_folders_all ;
  1505. add_to_requested_folders( @included_folders ) ;
  1506. myprint( "Including folders matching pattern $include\n" . jux_utf8_list( @included_folders ) . "\n" ) ;
  1507. }
  1508. }
  1509. if ( scalar @exclude ) {
  1510. foreach my $exclude ( @exclude ) {
  1511. my @requested_folder = sort keys %requested_folder ;
  1512. # No, do not add /x after the regex, never.
  1513. # Users would kill you!
  1514. my @excluded_folders = grep { /$exclude/ } @requested_folder ;
  1515. remove_from_requested_folders( @excluded_folders ) ;
  1516. myprint( "Excluding folders matching pattern $exclude\n" . jux_utf8_list( @excluded_folders ) . "\n" ) ;
  1517. }
  1518. }
  1519. # sort before is not very powerful
  1520. # it adds --folderfirst and --folderlast even if they don't exist on host1
  1521. #@h1_folders_wanted = sort_requested_folders( ) ;
  1522. $sync->{h1_folders_wanted} = [ sort_requested_folders( ) ] ;
  1523. # Remove no selectable folders
  1524. if ( $sync->{ checkfoldersexist } ) {
  1525. my @h1_folders_wanted_exist ;
  1526. myprint( "Host1: Checking wanted folders exist. Use --nocheckfoldersexist to avoid this check (shared of public namespace targeted).\n" ) ;
  1527. foreach my $folder ( @{ $sync->{h1_folders_wanted} } ) {
  1528. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "Checking $folder exists on host1\n" ) ;
  1529. if ( ! exists $h1_folders_all{ $folder } ) {
  1530. myprint( "Host1: warning! ignoring folder $folder because it is not in host1 whole folders list.\n" ) ;
  1531. next ;
  1532. }else{
  1533. push @h1_folders_wanted_exist, $folder ;
  1534. }
  1535. }
  1536. @{ $sync->{h1_folders_wanted} } = @h1_folders_wanted_exist ;
  1537. }else{
  1538. myprint( "Host1: Not checking that wanted folders exist. Remove --nocheckfoldersexist to get this check.\n" ) ;
  1539. }
  1540. setcheckselectable( $sync ) ;
  1541. checkselectable( $sync ) ;
  1542. # Bugfix OpenFind folders named like "kk \*123" are in fact "kk *123" (no \)
  1543. #foreach my $folder ( @{ $sync->{ h1_folders_wanted } } )
  1544. #{
  1545. # $folder =~ s{ \\\*}{ *}g ;
  1546. #}
  1547. # this hack is because LWP post does not pass well a hash in the $form parameter
  1548. # but it does pass well an array
  1549. %{ $sync->{f1f2h} } = split_around_equal( @{ $sync->{f1f2} } ) ;
  1550. automap( $sync ) ;
  1551. foreach my $h1_fold ( @{ $sync->{h1_folders_wanted} } ) {
  1552. my $h2_fold ;
  1553. $h2_fold = imap2_folder_name( $sync, $h1_fold ) ;
  1554. $h2_folders_from_1_wanted{ $h2_fold }++ ;
  1555. if ( 1 < $h2_folders_from_1_wanted{ $h2_fold } ) {
  1556. $h2_folders_from_1_several{ $h2_fold }++ ;
  1557. }
  1558. }
  1559. @h2_folders_from_1_wanted = sort keys %h2_folders_from_1_wanted;
  1560. foreach my $h1_fold ( @h1_folders_all ) {
  1561. my $h2_fold ;
  1562. $h2_fold = imap2_folder_name( $sync, $h1_fold ) ;
  1563. $h2_folders_from_1_all{ $h2_fold }++ ;
  1564. # Follows a fix to avoid deleting folder $sync->{ subfolder2 }
  1565. # because it usually does not exist on host1.
  1566. if ( $sync->{ subfolder2 } )
  1567. {
  1568. $h2_folders_from_1_all{ $sync->{ h2_prefix } . $sync->{ subfolder2 } }++ ;
  1569. $h2_folders_from_1_all{ $sync->{ subfolder2 } }++ ;
  1570. }
  1571. }
  1572. myprint( << 'END_LISTING' ) ;
  1573. ++++ Listing folders
  1574. All foldernames are presented between brackets like [X] where X is the foldername.
  1575. When a foldername contains non-ASCII characters it is presented in the form
  1576. [X] = [Y] where
  1577. X is the imap foldername you have to use in command line options and
  1578. Y is the utf8 output just printed for convenience, to recognize it.
  1579. END_LISTING
  1580. myprint(
  1581. "Host1: folders list (first the raw imap format then the [X] = [Y]):\n",
  1582. $sync->{imap1}->list( ),
  1583. "\n",
  1584. jux_utf8_list( @h1_folders_all ),
  1585. "\n",
  1586. "Host2: folders list (first the raw imap format then the [X] = [Y]):\n",
  1587. $sync->{imap2}->list( ),
  1588. "\n",
  1589. jux_utf8_list( @h2_folders_all ),
  1590. "\n",
  1591. q{}
  1592. ) ;
  1593. if ( $subscribed ) {
  1594. myprint(
  1595. 'Host1 subscribed folders list: ',
  1596. jux_utf8_list( sort keys %h1_subscribed_folder ), "\n",
  1597. ) ;
  1598. }
  1599. @h2_folders_not_in_1 = list_folders_in_2_not_in_1( ) ;
  1600. if ( @h2_folders_not_in_1 ) {
  1601. myprint( "Folders in host2 not in host1:\n",
  1602. jux_utf8_list( @h2_folders_not_in_1 ), "\n" ) ;
  1603. }
  1604. if ( keys %{ $sync->{f1f2auto} } ) {
  1605. myprint( "Folders mapping from --automap feature (use --f1f2 to override any mapping):\n" ) ;
  1606. foreach my $h1_fold ( keys %{ $sync->{f1f2auto} } ) {
  1607. my $h2_fold = $sync->{f1f2auto}{$h1_fold} ;
  1608. myprintf( "%-40s -> %-40s\n",
  1609. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1610. }
  1611. myprint( "\n" ) ;
  1612. }
  1613. if ( keys %{ $sync->{f1f2h} } ) {
  1614. myprint( "Folders mapping from --f1f2 options, it overrides --automap:\n" ) ;
  1615. foreach my $h1_fold ( keys %{ $sync->{f1f2h} } ) {
  1616. my $h2_fold = $sync->{f1f2h}{$h1_fold} ;
  1617. my $warn = q{} ;
  1618. if ( not exists $h1_folders_all{ $h1_fold } ) {
  1619. $warn = "BUT $h1_fold does NOT exist on host1!" ;
  1620. }
  1621. myprintf( "%-40s -> %-40s %s\n",
  1622. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ), $warn ) ;
  1623. }
  1624. myprint( "\n" ) ;
  1625. }
  1626. exit_clean( $sync, $EX_OK, "Exiting because of --justfolderlists\n" ) if ( $sync->{ justfolderlists } ) ;
  1627. exit_clean( $sync, $EX_OK, "Exiting because of --justautomap\n" ) if ( $sync->{ justautomap } ) ;
  1628. debugsleep( $sync ) ;
  1629. if ( $sync->{ skipemptyfolders } )
  1630. {
  1631. myprint( "Host1: will not syncing empty folders on host1. Use --noskipemptyfolders to create them anyway on host2\n") ;
  1632. }
  1633. if ( $sync->{ checknoabletosearch } )
  1634. {
  1635. myprint( "Checking SEARCH ALL works on both accounts. To avoid that check, use --nochecknoabletosearch\n" ) ;
  1636. my $check1 = checknoabletosearch( $sync, $sync->{ imap1 }, 'INBOX', 'Host1' ) ;
  1637. my $check2 = checknoabletosearch( $sync, $sync->{ imap2 }, 'INBOX', 'Host2' ) ;
  1638. if ( $check1 or $check2 )
  1639. {
  1640. myprint( "At least one account can not SEARCH ALL. So acting like --noabletosearch\n" ) ;
  1641. $sync->{abletosearch} = 0 ;
  1642. $sync->{abletosearch1} = 0 ;
  1643. $sync->{abletosearch2} = 0 ;
  1644. }
  1645. else
  1646. {
  1647. myprint( "Good! SEARCH ALL works on both accounts.\n" ) ;
  1648. }
  1649. }
  1650. if ( $sync->{ foldersizes } ) {
  1651. foldersizes_at_the_beggining( $sync ) ;
  1652. #foldersizes_at_the_beggining_old( $sync ) ;
  1653. }
  1654. if ( $sync->{ justfoldersizes } )
  1655. {
  1656. exit_clean( $sync, $EX_OK, "Exiting because of --justfoldersizes\n" ) ;
  1657. }
  1658. $sync->{can_do_stats} = 1 ;
  1659. if ( $sync->{ delete1emptyfolders } ) {
  1660. delete1emptyfolders( $sync ) ;
  1661. }
  1662. delete_folders_in_2_not_in_1( ) if $delete2folders ;
  1663. # folder loop
  1664. $h1_folders_wanted_nb = scalar @{ $sync->{h1_folders_wanted} } ;
  1665. myprint( "++++ Looping on each one of $h1_folders_wanted_nb folders to sync\n" ) ;
  1666. $sync->{begin_transfer_time} = time ;
  1667. my %uid_candidate_for_deletion ;
  1668. my %uid_candidate_no_deletion ;
  1669. $sync->{ h2_folders_of_md5 } = { } ;
  1670. FOLDER: foreach my $h1_fold ( @{ $sync->{h1_folders_wanted} } )
  1671. {
  1672. $sync->{ h1_current_folder } = $h1_fold ;
  1673. eta_print( $sync ) ;
  1674. abortifneeded( $sync ) ;
  1675. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1676. my $h2_fold = imap2_folder_name( $sync, $h1_fold ) ;
  1677. $sync->{ h2_current_folder } = $h2_fold ;
  1678. $h1_folders_wanted_ct++ ;
  1679. myprintf( "Folder %7s %-35s -> %-35s\n", "$h1_folders_wanted_ct/$h1_folders_wanted_nb",
  1680. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1681. myprint( debugmemory( $sync, " at folder loop" ) ) ;
  1682. # host1 can not be fetched read only, select is needed because of expunge.
  1683. select_folder( $sync, $sync->{imap1}, $h1_fold, 'Host1' ) or next FOLDER ;
  1684. debugsleep( $sync ) ;
  1685. my $h1_msgs_all_hash_ref ;
  1686. my @h1_msgs ;
  1687. my $h1_msgs_nb ;
  1688. my $h1_msgs_nb_from_select ;
  1689. $h1_msgs_nb_from_select = count_from_select( $sync->{imap1}->History ) ;
  1690. myprint( "Host1: folder [$h1_fold] has $h1_msgs_nb_from_select messages in total (mentioned by SELECT)\n" ) ;
  1691. if ( $sync->{ skipemptyfolders } and 0 == $h1_msgs_nb_from_select ) {
  1692. myprint( "Host1: skipping empty host1 folder [$h1_fold]\n" ) ;
  1693. next FOLDER ;
  1694. }
  1695. # Code added from https://github.com/imapsync/imapsync/issues/95
  1696. # Thanks jh1995
  1697. # Goal: do not create folder if --search or --max/minage return 0 message.
  1698. # even if there are messages by SELECT (no not real empty, empty for the user point of vue).
  1699. if ( $sync->{ skipemptyfolders } or $sync->{ dry } )
  1700. {
  1701. $h1_msgs_all_hash_ref = { } ;
  1702. @h1_msgs = select_msgs( $sync->{imap1}, $h1_msgs_all_hash_ref, $sync->{ search1 }, $sync->{abletosearch1}, $h1_fold ) ;
  1703. $h1_msgs_nb = scalar( @h1_msgs ) ;
  1704. if ( 0 == $h1_msgs_nb and $sync->{ skipemptyfolders } ) {
  1705. myprint( "Host1: skipping empty host1 folder [$h1_fold] (0 message found by SEARCH)\n" ) ;
  1706. next FOLDER ;
  1707. }
  1708. }
  1709. if ( ! exists $h2_folders_all{ $h2_fold } ) {
  1710. # In --dry mode I could count the messages to be transfered instead of 0
  1711. # Messages transferred : 0 (could be 0 without dry mode)
  1712. if ( ! create_folder( $sync, $sync->{imap2}, $h2_fold, $h1_fold ) )
  1713. {
  1714. if ( $sync->{ dry } )
  1715. {
  1716. $nb_msg_skipped_dry_mode += $h1_msgs_nb ;
  1717. }
  1718. next FOLDER ;
  1719. }
  1720. }
  1721. acls_sync( $sync, $h1_fold, $h2_fold ) ;
  1722. # Sometimes the folder on host2 is listed (it exists) but is
  1723. # not selectable but becomes selectable by a create (Gmail)
  1724. select_folder( $sync, $sync->{imap2}, $h2_fold, 'Host2' )
  1725. or ( create_folder( $sync, $sync->{imap2}, $h2_fold, $h1_fold )
  1726. and select_folder( $sync, $sync->{imap2}, $h2_fold, 'Host2' ) )
  1727. or next FOLDER ;
  1728. my @select_results = $sync->{imap2}->Results( ) ;
  1729. my $h2_fold_nb_messages = count_from_select( @select_results ) ;
  1730. myprint( "Host2: folder [$h2_fold] has $h2_fold_nb_messages messages in total (mentioned by SELECT)\n" ) ;
  1731. my $permanentflags2 = permanentflags( @select_results ) ;
  1732. myprint( "Host2: folder [$h2_fold] permanentflags: $permanentflags2\n" ) ;
  1733. if ( $sync->{ expunge1 } )
  1734. {
  1735. myprint( "Host1: Expunging $h1_fold $sync->{dry_message}\n" ) ;
  1736. if ( ! $sync->{dry} )
  1737. {
  1738. $sync->{imap1}->expunge( ) ;
  1739. }
  1740. }
  1741. if ( ( ( $subscribe and exists $h1_subscribed_folder{ $h1_fold } ) or $subscribeall )
  1742. and not exists $h2_subscribed_folder{ $h2_fold } )
  1743. {
  1744. myprint( "Host2: Subscribing to folder $h2_fold\n" ) ;
  1745. if ( ! $sync->{dry} ) { $sync->{imap2}->subscribe( $h2_fold ) } ;
  1746. }
  1747. next FOLDER if ( $sync->{ justfolders } ) ;
  1748. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1749. if ( ! defined $h1_msgs_nb )
  1750. {
  1751. $h1_msgs_all_hash_ref = { } ;
  1752. @h1_msgs = select_msgs( $sync->{imap1}, $h1_msgs_all_hash_ref, $sync->{ search1 }, $sync->{abletosearch1}, $h1_fold );
  1753. $h1_msgs_nb = scalar @h1_msgs ;
  1754. }else{
  1755. # select_msgs already done.
  1756. }
  1757. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1758. myprint( "Host1: folder [$h1_fold] considering $h1_msgs_nb messages\n" ) ;
  1759. ( $sync->{ debug } or $debuglist ) and myprint( "Host1: folder [$h1_fold] considering $h1_msgs_nb messages, LIST gives: @h1_msgs\n" ) ;
  1760. $sync->{ debug } and myprint( "Host1: selecting messages of folder [$h1_fold] took ", timenext( $sync ), " s\n" ) ;
  1761. my $h2_msgs_all_hash_ref = { } ;
  1762. my @h2_msgs = select_msgs( $sync->{imap2}, $h2_msgs_all_hash_ref, $sync->{ search2 }, $sync->{abletosearch2}, $h2_fold ) ;
  1763. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1764. my $h2_msgs_nb = scalar @h2_msgs ;
  1765. myprint( "Host2: folder [$h2_fold] considering $h2_msgs_nb messages\n" ) ;
  1766. ( $sync->{ debug } or $debuglist ) and myprint( "Host2: folder [$h2_fold] considering $h2_msgs_nb messages, LIST gives: @h2_msgs\n" ) ;
  1767. $sync->{ debug } and myprint( "Host2: selecting messages of folder [$h2_fold] took ", timenext( $sync ), " s\n" ) ;
  1768. my $cache_base = "$sync->{ tmpdir }/imapsync_cache/" ;
  1769. my $cache_dir = cache_folder( $cache_base,
  1770. "$sync->{host1}/$sync->{user1}/$sync->{host2}/$sync->{user2}", $h1_fold, $h2_fold ) ;
  1771. my ( $cache_1_2_ref, $cache_2_1_ref ) = ( {}, {} ) ;
  1772. my $h1_uidvalidity = $sync->{imap1}->uidvalidity( ) || q{} ;
  1773. my $h2_uidvalidity = $sync->{imap2}->uidvalidity( ) || q{} ;
  1774. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1775. if ( $usecache ) {
  1776. myprint( "Local cache directory: $cache_dir ( " . length( $cache_dir ) . " characters long )\n" ) ;
  1777. mkpath( "$cache_dir" ) ;
  1778. ( $cache_1_2_ref, $cache_2_1_ref )
  1779. = get_cache( $cache_dir, \@h1_msgs, \@h2_msgs, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  1780. myprint( 'CACHE h1 h2: ', scalar keys %{ $cache_1_2_ref } , " files\n" ) ;
  1781. $sync->{ debug } and myprint( '[',
  1782. map ( { "$_->$cache_1_2_ref->{$_} " } keys %{ $cache_1_2_ref } ), " ]\n" ) ;
  1783. }
  1784. my %h1_hash = ( ) ;
  1785. my %h2_hash = ( ) ;
  1786. my ( %h1_msgs, %h2_msgs ) ;
  1787. @h1_msgs{ @h1_msgs } = ( ) ;
  1788. @h2_msgs{ @h2_msgs } = ( ) ;
  1789. my @h1_msgs_in_cache = sort { $a <=> $b } keys %{ $cache_1_2_ref } ;
  1790. my @h2_msgs_in_cache = sort { $a <=> $b } keys %{ $cache_2_1_ref } ;
  1791. my ( %h1_msgs_not_in_cache, %h2_msgs_not_in_cache ) ;
  1792. %h1_msgs_not_in_cache = %h1_msgs ;
  1793. %h2_msgs_not_in_cache = %h2_msgs ;
  1794. delete @h1_msgs_not_in_cache{ @h1_msgs_in_cache } ;
  1795. delete @h2_msgs_not_in_cache{ @h2_msgs_in_cache } ;
  1796. my @h1_msgs_not_in_cache = sort { $a <=> $b } keys %h1_msgs_not_in_cache ;
  1797. #myprint( "h1_msgs_not_in_cache: [@h1_msgs_not_in_cache]\n" ) ;
  1798. my @h2_msgs_not_in_cache = sort { $a <=> $b } keys %h2_msgs_not_in_cache ;
  1799. my @h2_msgs_delete2_not_in_cache = () ;
  1800. %h1_msgs_copy_by_uid = ( ) ;
  1801. if ( $useuid ) {
  1802. # use uid so we have to avoid getting header
  1803. @h1_msgs_copy_by_uid{ @h1_msgs_not_in_cache } = ( ) ;
  1804. @h2_msgs_delete2_not_in_cache = @h2_msgs_not_in_cache if $usecache ;
  1805. @h1_msgs_not_in_cache = ( ) ;
  1806. @h2_msgs_not_in_cache = ( ) ;
  1807. #myprint( "delete2: @h2_msgs_delete2_not_in_cache\n" ) ;
  1808. }
  1809. $sync->{ debug } and myprint( "Host1: parsing headers of folder [$h1_fold]\n" ) ;
  1810. my ($h1_heads_ref, $h1_fir_ref) = ({}, {});
  1811. $h1_heads_ref = $sync->{imap1}->parse_headers([@h1_msgs_not_in_cache], @useheader) if (@h1_msgs_not_in_cache);
  1812. $sync->{ debug } and myprint( "Host1: parsing headers of folder [$h1_fold] took ", timenext( $sync ), " s\n" ) ;
  1813. @{ $h1_fir_ref }{@h1_msgs} = ( undef ) ;
  1814. $sync->{ debug } and myprint( "Host1: getting flags idate and sizes of folder [$h1_fold]\n" ) ;
  1815. my @h1_common_fetch_param = ( 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE' ) ;
  1816. if ( $sync->{ synclabels } or $sync->{ resynclabels } ) { push @h1_common_fetch_param, 'X-GM-LABELS' ; }
  1817. if ( $sync->{abletosearch1} )
  1818. {
  1819. $h1_fir_ref = $sync->{imap1}->fetch_hash( \@h1_msgs, @h1_common_fetch_param, $h1_fir_ref )
  1820. if ( @h1_msgs ) ;
  1821. }
  1822. else
  1823. {
  1824. my $fetch_hash_uids = $fetch_hash_set || "1:*" ;
  1825. $h1_fir_ref = $sync->{imap1}->fetch_hash( $fetch_hash_uids, @h1_common_fetch_param, $h1_fir_ref )
  1826. if ( @h1_msgs ) ;
  1827. }
  1828. $sync->{ debug } and myprint( "Host1: getting flags idate and sizes of folder [$h1_fold] took ", timenext( $sync ), " s\n" ) ;
  1829. if ( ! $h1_fir_ref )
  1830. {
  1831. my $error = join( q{}, "Host1: folder $h1_fold : Could not fetch_hash ",
  1832. scalar @h1_msgs, ' msgs: ', $sync->{imap1}->LastError || q{}, "\n" ) ;
  1833. errors_incr( $sync, $error ) ;
  1834. next FOLDER ;
  1835. }
  1836. my @h1_msgs_duplicate;
  1837. foreach my $m ( @h1_msgs_not_in_cache )
  1838. {
  1839. my $rc = parse_header_msg( $sync, $sync->{imap1}, $m, $h1_heads_ref, $h1_fir_ref, 'Host1', \%h1_hash ) ;
  1840. if ( ! defined $rc )
  1841. {
  1842. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1843. myprint( "Host1: $h1_fold/$m size $h1_size ignored (no wanted headers so we ignore this message. To solve this: use --addheader)\n" ) ;
  1844. $sync->{ total_bytes_skipped } += $h1_size ;
  1845. $sync->{ nb_msg_skipped } += 1 ;
  1846. $sync->{ h1_nb_msg_noheader } +=1 ;
  1847. $sync->{ h1_nb_msg_processed } +=1 ;
  1848. } elsif( 0 == $rc )
  1849. {
  1850. # duplicate
  1851. push @h1_msgs_duplicate, $m;
  1852. # duplicate, same id same size?
  1853. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1854. $sync->{ acc1 }->{ nb_msg_duplicate } += 1;
  1855. if ( ! $sync->{ syncduplicates } ) {
  1856. $sync->{ nb_msg_skipped } += 1 ;
  1857. $sync->{ h1_nb_msg_processed } +=1 ;
  1858. }
  1859. }
  1860. }
  1861. my $h1_msgs_duplicate_nb = scalar @h1_msgs_duplicate ;
  1862. myprint( "Host1: folder [$h1_fold] selected $h1_msgs_nb messages, duplicates $h1_msgs_duplicate_nb\n" ) ;
  1863. $sync->{ debug } and myprint( 'Host1: whole time parsing headers took ', timenext( $sync ), " s\n" ) ;
  1864. # Getting headers and metada can be so long that host2 might be disconnected here
  1865. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1866. $sync->{ debug } and myprint( "Host2: parsing headers of folder [$h2_fold]\n" ) ;
  1867. my ($h2_heads_ref, $h2_fir_ref) = ( {}, {} );
  1868. $h2_heads_ref = $sync->{imap2}->parse_headers([@h2_msgs_not_in_cache], @useheader) if (@h2_msgs_not_in_cache);
  1869. $sync->{ debug } and myprint( "Host2: parsing headers of folder [$h2_fold] took ", timenext( $sync ), " s\n" ) ;
  1870. $sync->{ debug } and myprint( "Host2: getting flags idate and sizes of folder [$h2_fold]\n" ) ;
  1871. @{ $h2_fir_ref }{@h2_msgs} = ( ); # fetch_hash can select by uid with last arg as ref
  1872. my @h2_common_fetch_param = ( 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE' ) ;
  1873. if ( $sync->{ synclabels } or $sync->{ resynclabels } ) { push @h2_common_fetch_param, 'X-GM-LABELS' ; }
  1874. if ( $sync->{abletosearch2} and scalar( @h2_msgs ) ) {
  1875. $h2_fir_ref = $sync->{imap2}->fetch_hash( \@h2_msgs, @h2_common_fetch_param, $h2_fir_ref) ;
  1876. }else{
  1877. my $fetch_hash_uids = $fetch_hash_set || "1:*" ;
  1878. $h2_fir_ref = $sync->{imap2}->fetch_hash( $fetch_hash_uids, @h2_common_fetch_param, $h2_fir_ref )
  1879. if ( @h2_msgs ) ;
  1880. }
  1881. $sync->{ debug } and myprint( "Host2: getting flags idate and sizes of folder [$h2_fold] took ", timenext( $sync ), " s\n" ) ;
  1882. my @h2_msgs_duplicate;
  1883. foreach my $m (@h2_msgs_not_in_cache) {
  1884. my $rc = parse_header_msg( $sync, $sync->{imap2}, $m, $h2_heads_ref, $h2_fir_ref, 'Host2', \%h2_hash ) ;
  1885. my $h2_size = $h2_fir_ref->{$m}->{'RFC822.SIZE'} || 0 ;
  1886. if (! defined $rc ) {
  1887. myprint( "Host2: $h2_fold/$m size $h2_size ignored (no wanted headers so we ignore this message)\n" ) ;
  1888. $h2_nb_msg_noheader += 1 ;
  1889. } elsif( 0 == $rc ) {
  1890. # duplicate
  1891. $sync->{ acc2 }->{ nb_msg_duplicate } += 1 ;
  1892. push @h2_msgs_duplicate, $m ;
  1893. }
  1894. }
  1895. # %h2_folders_of_md5
  1896. foreach my $md5 ( keys %h2_hash ) {
  1897. $sync->{ h2_folders_of_md5 }->{ $md5 }->{ $h2_fold } ++ ;
  1898. }
  1899. # %h1_folders_of_md5
  1900. foreach my $md5 ( keys %h1_hash ) {
  1901. $sync->{ h1_folders_of_md5 }->{ $md5 }->{ $h2_fold } ++ ;
  1902. }
  1903. my $h2_msgs_duplicate_nb = scalar @h2_msgs_duplicate ;
  1904. myprint( "Host2: folder [$h2_fold] selected $h2_msgs_nb messages, duplicates $h2_msgs_duplicate_nb\n" ) ;
  1905. $sync->{ debug } and myprint( 'Host2 whole time parsing headers took ', timenext( $sync ), " s\n" ) ;
  1906. $sync->{ debug } and myprint( "++++ Verifying [$h1_fold] -> [$h2_fold]\n" ) ;
  1907. # messages in host1 that are not in host2
  1908. my @h1_hash_keys_sorted_by_uid
  1909. = sort {$h1_hash{$a}{'m'} <=> $h1_hash{$b}{'m'}} keys %h1_hash;
  1910. #myprint( map { $h1_hash{$_}{'m'} . q{ }} @h1_hash_keys_sorted_by_uid ) ;
  1911. my @h2_hash_keys_sorted_by_uid
  1912. = sort {$h2_hash{$a}{'m'} <=> $h2_hash{$b}{'m'}} keys %h2_hash;
  1913. # Deletions on account2.
  1914. if( $sync->{ delete2duplicates } and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  1915. my @h2_expunge ;
  1916. foreach my $h2_msg ( @h2_msgs_duplicate ) {
  1917. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted [duplicate] on host2 $sync->{dry_message}\n" ) ;
  1918. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 } ;
  1919. if ( ! $sync->{ dry } ) {
  1920. $sync->{ imap2 }->delete_message( $h2_msg ) ;
  1921. $sync->{ acc2 }->{ nb_msg_deleted } += 1 ;
  1922. }
  1923. }
  1924. my $cnt = scalar @h2_expunge ;
  1925. if( @h2_expunge and not $sync->{ expunge2 } ) {
  1926. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  1927. $sync->{imap2}->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  1928. }
  1929. if ( $sync->{ expunge2 } ){
  1930. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  1931. $sync->{imap2}->expunge( ) if ! $sync->{dry} ;
  1932. }
  1933. }
  1934. if( $sync->{ delete2 } and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  1935. # No host1 folders f1a f1b ... going all to same f2 (via --regextrans2)
  1936. my @h2_expunge;
  1937. foreach my $m_id (@h2_hash_keys_sorted_by_uid) {
  1938. #myprint( "$m_id " ) ;
  1939. if ( ! exists $h1_hash{$m_id} ) {
  1940. my $h2_msg = $h2_hash{$m_id}{'m'};
  1941. my $h2_flags = $h2_hash{$m_id}{'F'} || q{};
  1942. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0;
  1943. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted on host2 [$m_id] $sync->{dry_message}\n" )
  1944. if ! $isdel;
  1945. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 };
  1946. if ( ! ( $sync->{ dry } or $isdel ) ) {
  1947. $sync->{ imap2 }->delete_message( $h2_msg );
  1948. $sync->{ acc2 }->{ nb_msg_deleted } += 1;
  1949. }
  1950. }
  1951. }
  1952. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  1953. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted [not in cache] on host2 $sync->{dry_message}\n" ) ;
  1954. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 };
  1955. if ( ! $sync->{dry} ) {
  1956. $sync->{ imap2 }->delete_message( $h2_msg );
  1957. $sync->{ acc2 }->{ nb_msg_deleted } += 1;
  1958. }
  1959. }
  1960. my $cnt = scalar @h2_expunge ;
  1961. if( @h2_expunge and not $sync->{ expunge2 } ) {
  1962. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  1963. $sync->{imap2}->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  1964. }
  1965. if ( $sync->{ expunge2 } ) {
  1966. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  1967. $sync->{imap2}->expunge( ) if ! $sync->{dry} ;
  1968. }
  1969. }
  1970. if( $sync->{ delete2 } and exists $h2_folders_from_1_several{ $h2_fold } ) {
  1971. myprint( "Host2: folder $h2_fold $h2_folders_from_1_several{ $h2_fold } folders left to sync there\n" ) ;
  1972. my @h2_expunge;
  1973. foreach my $m_id ( @h2_hash_keys_sorted_by_uid ) {
  1974. my $h2_msg = $h2_hash{ $m_id }{ 'm' } ;
  1975. if ( ! exists $h1_hash{ $m_id } ) {
  1976. my $h2_flags = $h2_hash{ $m_id }{ 'F' } || q{} ;
  1977. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0 ;
  1978. if ( ! $isdel ) {
  1979. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [$m_id]\n" ) ;
  1980. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  1981. }
  1982. }else{
  1983. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [$m_id]\n" ) ;
  1984. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1985. }
  1986. }
  1987. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  1988. myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [not in cache]\n" ) ;
  1989. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  1990. }
  1991. foreach my $h2_msg ( @h2_msgs_in_cache ) {
  1992. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [in cache]\n" ) ;
  1993. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1994. }
  1995. if ( 0 == $h2_folders_from_1_several{ $h2_fold } ) {
  1996. # last host1 folder going to $h2_fold
  1997. myprint( "Last host1 folder going to $h2_fold\n" ) ;
  1998. foreach my $h2_msg ( keys %{ $uid_candidate_for_deletion{ $h2_fold } } ) {
  1999. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion\n" ) ;
  2000. if ( exists $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg } ) {
  2001. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg canceled deletion\n" ) ;
  2002. }else{
  2003. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted $sync->{dry_message}\n" ) ;
  2004. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 } ;
  2005. if ( ! $sync->{ dry} ) {
  2006. $sync->{ imap2 }->delete_message( $h2_msg ) ;
  2007. $sync->{ acc2 }->{ nb_msg_deleted } += 1 ;
  2008. }
  2009. }
  2010. }
  2011. }
  2012. my $cnt = scalar @h2_expunge ;
  2013. if( @h2_expunge and not $sync->{ expunge2 } ) {
  2014. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  2015. $sync->{imap2}->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  2016. }
  2017. if ( $sync->{ expunge2 } ) {
  2018. myprint( "Host2: Expunging host2 folder $h2_fold $sync->{dry_message}\n" ) ;
  2019. $sync->{imap2}->expunge( ) if ! $sync->{dry} ;
  2020. }
  2021. $h2_folders_from_1_several{ $h2_fold }-- ;
  2022. }
  2023. my $h2_uidnext = $sync->{imap2}->uidnext( $h2_fold ) ;
  2024. $sync->{ debug } and myprint( "Host2: uidnext is $h2_uidnext\n" ) ;
  2025. $h2_uidguess = $h2_uidnext ;
  2026. # Getting host2 headers, metada and delete2 stuff can be so long that host1 might be disconnected here
  2027. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2028. my @h1_msgs_to_delete ;
  2029. MESS: foreach my $m_id (@h1_hash_keys_sorted_by_uid) {
  2030. abortifneeded( $sync ) ;
  2031. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2032. #myprint( "h1_nb_msg_processed: $sync->{ h1_nb_msg_processed }\n" ) ;
  2033. my $h1_size = $h1_hash{$m_id}{'s'};
  2034. my $h1_msg = $h1_hash{$m_id}{'m'};
  2035. my $h1_idate = $h1_hash{$m_id}{'D'};
  2036. #my $labels = labels( $sync->{imap1}, $h1_msg ) ;
  2037. #print "LABELS: $labels\n" ;
  2038. if ( ( not exists $h2_hash{ $m_id } )
  2039. and ( not ( exists $sync->{ h2_folders_of_md5 }->{ $m_id } )
  2040. or not $skipcrossduplicates ) )
  2041. {
  2042. # copy
  2043. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  2044. if ( $h2_msg and $sync->{ delete1 } and not $sync->{ expungeaftereach } ) {
  2045. # not expunged
  2046. push @h1_msgs_to_delete, $h1_msg ;
  2047. }
  2048. # A bug here with imapsync 1.920, fixed in 1.921
  2049. # Added $h2_msg in the condition. Errors of APPEND were not counted as missing messages on host2!
  2050. if ( $h2_msg and not $sync->{ dry } )
  2051. {
  2052. $sync->{ h2_folders_of_md5 }->{ $m_id }->{ $h2_fold } ++ ;
  2053. }
  2054. #
  2055. if( $sync->{ delete2 } and ( exists $h2_folders_from_1_several{ $h2_fold } ) and $h2_msg ) {
  2056. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  2057. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  2058. }
  2059. if ( total_bytes_max_reached( $sync ) ) {
  2060. # Still a bug when using --delete1 --noexpungeaftereach
  2061. # same thing below on all total_bytes_max_reached!
  2062. last FOLDER ;
  2063. }
  2064. next MESS;
  2065. }
  2066. else
  2067. {
  2068. # already on host2
  2069. if ( exists $h2_hash{ $m_id } )
  2070. {
  2071. my $h2_msg = $h2_hash{$m_id}{'m'} ;
  2072. $sync->{ debug } and myprint( "Host1: found that msg $h1_fold/$h1_msg equals Host2 $h2_fold/$h2_msg\n" ) ;
  2073. if ( $usecache )
  2074. {
  2075. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$h2_msg\n" ) ;
  2076. touch( "$cache_dir/${h1_msg}_$h2_msg" )
  2077. or croak( "Couldn't touch $cache_dir/${h1_msg}_$h2_msg" ) ;
  2078. }
  2079. }
  2080. elsif( exists $sync->{ h2_folders_of_md5 }->{ $m_id } )
  2081. {
  2082. my @folders_dup = keys %{ $sync->{ h2_folders_of_md5 }->{ $m_id } } ;
  2083. ( $sync->{ debug } or $debugcrossduplicates ) and myprint( "Host1: found that msg $h1_fold/$h1_msg is also in Host2 folders @folders_dup\n" ) ;
  2084. $sync->{ h2_nb_msg_crossdup } +=1 ;
  2085. }
  2086. $sync->{ total_bytes_skipped } += $h1_size ;
  2087. $sync->{ nb_msg_skipped } += 1 ;
  2088. $sync->{ h1_nb_msg_processed } +=1 ;
  2089. }
  2090. if ( exists $h2_hash{ $m_id } ) {
  2091. #$debug and myprint( "MESSAGE $m_id\n" ) ;
  2092. my $h2_msg = $h2_hash{$m_id}{'m'};
  2093. if ( $sync->{resyncflags} ) {
  2094. sync_flags_fir( $sync, $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  2095. }
  2096. # Good
  2097. my $h2_size = $h2_hash{$m_id}{'s'};
  2098. $sync->{ debug } and myprint(
  2099. "Host1: size msg $h1_fold/$h1_msg = $h1_size <> $h2_size = Host2 $h2_fold/$h2_msg\n" ) ;
  2100. if ( $sync->{ resynclabels } )
  2101. {
  2102. resynclabels( $sync, $h1_msg, $h2_msg, $h1_fir_ref, $h2_fir_ref, $h1_fold )
  2103. }
  2104. }
  2105. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2106. if ( $sync->{ delete1 } ) {
  2107. push @h1_msgs_to_delete, $h1_msg ;
  2108. }
  2109. }
  2110. # END MESS: loop
  2111. # @h1_msgs_in_cache are already synced too.
  2112. delete_message_on_host1( $sync, $h1_fold, $sync->{ expunge1 }, @h1_msgs_to_delete, @h1_msgs_in_cache ) ;
  2113. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2114. # MESS_IN_CACHE:
  2115. if ( ! $sync->{ delete1 } )
  2116. {
  2117. foreach my $h1_msg ( @h1_msgs_in_cache )
  2118. {
  2119. my $h2_msg = $cache_1_2_ref->{ $h1_msg } ;
  2120. $debugcache and myprint( "cache messages update flags $h1_msg->$h2_msg\n" ) ;
  2121. if ( $sync->{resyncflags} )
  2122. {
  2123. sync_flags_fir( $sync, $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  2124. }
  2125. my $h1_size = $h1_fir_ref->{ $h1_msg }->{ 'RFC822.SIZE' } || 0 ;
  2126. $sync->{ total_bytes_skipped } += $h1_size;
  2127. $sync->{ nb_msg_skipped } += 1;
  2128. $sync->{ h1_nb_msg_processed } +=1 ;
  2129. }
  2130. }
  2131. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2132. @h1_msgs_to_delete = ( ) ;
  2133. #myprint( "Messages by uid: ", map { "$_ " } keys %h1_msgs_copy_by_uid, "\n" ) ;
  2134. # MESS_BY_UID:
  2135. foreach my $h1_msg ( sort { $a <=> $b } keys %h1_msgs_copy_by_uid )
  2136. {
  2137. abortifneeded( $sync ) ;
  2138. $sync->{ debug } and myprint( "Copy by uid $h1_fold/$h1_msg\n" ) ;
  2139. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2140. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  2141. if( $sync->{ delete2 } and exists $h2_folders_from_1_several{ $h2_fold } and $h2_msg ) {
  2142. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  2143. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  2144. }
  2145. last FOLDER if total_bytes_max_reached( $sync ) ;
  2146. }
  2147. if ( $sync->{ expunge1 } ){
  2148. myprint( "Host1: Expunging folder $h1_fold $sync->{dry_message}\n" ) ;
  2149. if ( ! $sync->{dry} ) { $sync->{imap1}->expunge( ) } ;
  2150. }
  2151. if ( $sync->{ expunge2 } ){
  2152. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  2153. if ( ! $sync->{dry} ) { $sync->{imap2}->expunge( ) } ;
  2154. }
  2155. $sync->{ debug } and myprint( 'Time: ', timenext( $sync ), " s\n" ) ;
  2156. }
  2157. eta_print( $sync ) ;
  2158. myprint( "++++ End looping on each folder\n" ) ;
  2159. if ( $sync->{ delete1 } and $sync->{ delete1emptyfolders } ) {
  2160. delete1emptyfolders( $sync ) ;
  2161. }
  2162. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( 'Time: ', timenext( $sync ), " s\n" ) ;
  2163. if ( $sync->{ foldersizesatend } ) {
  2164. myprint( << 'END_SIZE' ) ;
  2165. Folders sizes after the synchronization.
  2166. You can remove this foldersizes listing by using "--nofoldersizesatend"
  2167. END_SIZE
  2168. foldersizesatend( $sync ) ;
  2169. }
  2170. #$sync->{imap1}->State( 0 ); # Unconnected
  2171. if ( ! lost_connection( $sync, $sync->{imap1}, "for host1 [$sync->{host1}]" ) ) { $sync->{imap1}->logout( ) ; }
  2172. if ( ! lost_connection( $sync, $sync->{imap2}, "for host2 [$sync->{host2}]" ) ) { $sync->{imap2}->logout( ) ; }
  2173. do_and_print_stats( $sync ) ;
  2174. if ( $sync->{errorsdump} and $sync->{nb_errors} )
  2175. {
  2176. myprint( errors_listing( $sync ) ) ;
  2177. }
  2178. if ( $sync->{testslive} or $sync->{testslive6} )
  2179. {
  2180. tests_live_result( $sync->{nb_errors} ) ;
  2181. }
  2182. if ( $sync->{nb_errors} )
  2183. {
  2184. my $exit_value = $EXIT_VALUE_OF_ERR_TYPE{ $sync->{most_common_error} } || $EXIT_CATCH_ALL ;
  2185. exit_clean( $sync, $exit_value ) ;
  2186. }
  2187. else
  2188. {
  2189. exit_clean( $sync, $EX_OK ) ;
  2190. }
  2191. return ;
  2192. }
  2193. # END of sub single_sync
  2194. # subroutines
  2195. sub myprint
  2196. {
  2197. #print @ARG ;
  2198. print { $sync->{ tee } || \*STDOUT } @ARG ;
  2199. return ;
  2200. }
  2201. sub myprintf
  2202. {
  2203. printf { $sync->{ tee } || \*STDOUT } @ARG ;
  2204. return ;
  2205. }
  2206. sub mysprintf
  2207. {
  2208. my( $format, @list ) = @ARG ;
  2209. return sprintf $format, @list ;
  2210. }
  2211. sub output_start
  2212. {
  2213. my $mysync = shift @ARG ;
  2214. if ( not $mysync ) { return ; }
  2215. my @output = @ARG ;
  2216. $mysync->{ output } = join( q{}, @output ) . ( $mysync->{ output } || q{} ) ;
  2217. return $mysync->{ output } ;
  2218. }
  2219. sub tests_output_start
  2220. {
  2221. note( 'Entering tests_output_start()' ) ;
  2222. my $mysync = { } ;
  2223. is( undef, output_start( ), 'output_start: no args => undef' ) ;
  2224. is( q{}, output_start( $mysync ), 'output_start: one arg => ""' ) ;
  2225. is( 'rrrr', output_start( $mysync, 'rrrr' ), 'output_start: rrrr => rrrr' ) ;
  2226. is( 'aaaarrrr', output_start( $mysync, 'aaaa' ), 'output_start: aaaa => aaaarrrr' ) ;
  2227. is( "\naaaarrrr", output_start( $mysync, "\n" ), 'output_start: \n => \naaaarrrr' ) ;
  2228. is( "ABC\naaaarrrr", output_start( $mysync, 'A', 'B', 'C' ), 'output_start: A B C => ABC\naaaarrrr' ) ;
  2229. note( 'Leaving tests_output_start()' ) ;
  2230. return ;
  2231. }
  2232. sub tests_output
  2233. {
  2234. note( 'Entering tests_output()' ) ;
  2235. my $mysync = { } ;
  2236. is( undef, output( ), 'output: no args => undef' ) ;
  2237. is( q{}, output( $mysync ), 'output: one arg => ""' ) ;
  2238. is( 'rrrr', output( $mysync, 'rrrr' ), 'output: rrrr => rrrr' ) ;
  2239. is( 'rrrraaaa', output( $mysync, 'aaaa' ), 'output: aaaa => rrrraaaa' ) ;
  2240. is( "rrrraaaa\n", output( $mysync, "\n" ), 'output: \n => rrrraaaa\n' ) ;
  2241. is( "rrrraaaa\nABC", output( $mysync, 'A', 'B', 'C' ), 'output: A B C => rrrraaaaABC\n' ) ;
  2242. note( 'Leaving tests_output()' ) ;
  2243. return ;
  2244. }
  2245. sub output
  2246. {
  2247. my $mysync = shift @ARG ;
  2248. if ( not $mysync ) { return ; }
  2249. my @output = @ARG ;
  2250. $mysync->{ output } .= join( q{}, @output ) ;
  2251. return $mysync->{ output } ;
  2252. }
  2253. sub tests_output_reset_with
  2254. {
  2255. note( 'Entering tests_output_reset_with()' ) ;
  2256. my $mysync = { } ;
  2257. is( undef, output_reset_with( ), 'output_reset_with: no args => undef' ) ;
  2258. is( q{}, output_reset_with( $mysync ), 'output_reset_with: one arg => ""' ) ;
  2259. is( 'rrrr', output_reset_with( $mysync, 'rrrr' ), 'output_reset_with: rrrr => rrrr' ) ;
  2260. is( 'aaaa', output_reset_with( $mysync, 'aaaa' ), 'output_reset_with: aaaa => aaaa' ) ;
  2261. is( "\n", output_reset_with( $mysync, "\n" ), 'output_reset_with: \n => \n' ) ;
  2262. note( 'Leaving tests_output_reset_with()' ) ;
  2263. return ;
  2264. }
  2265. sub output_reset_with
  2266. {
  2267. my $mysync = shift @ARG ;
  2268. if ( not $mysync ) { return ; }
  2269. my @output = @ARG ;
  2270. $mysync->{ output } = join( q{}, @output ) ;
  2271. return $mysync->{ output } ;
  2272. }
  2273. sub tests_print_output_if_needed
  2274. {
  2275. note( 'Entering tests_print_output_if_needed()' ) ;
  2276. is( undef, print_output_if_needed( ), 'print_output_if_needed: no args => undef' ) ;
  2277. my $mysync = { } ;
  2278. is( q{}, print_output_if_needed( $mysync ), 'print_output_if_needed: undef => undef' ) ;
  2279. output( $mysync, "Hello\n" ) ;
  2280. is( "Hello\n", print_output_if_needed( $mysync ), 'print_output_if_needed: Hello => Hello' ) ;
  2281. $mysync->{ dockercontext } = 1 ;
  2282. is( "Hello\n", print_output_if_needed( $mysync ), 'print_output_if_needed: dockercontext + Hello => Hello' ) ;
  2283. $mysync->{ version } = 1 ;
  2284. is( q{}, print_output_if_needed( $mysync ), 'print_output_if_needed: dockercontext + Hello + --version => ""' ) ;
  2285. $mysync->{ dockercontext } = 0 ;
  2286. is( "Hello\n", print_output_if_needed( $mysync ), 'print_output_if_needed: Hello + --version => Hello' ) ;
  2287. note( 'Leaving tests_print_output_if_needed()' ) ;
  2288. return ;
  2289. }
  2290. sub print_output_if_needed
  2291. {
  2292. my $mysync = shift @ARG ;
  2293. if ( ! defined $mysync ) { return ; }
  2294. my $output = output( $mysync ) ;
  2295. if ( $mysync->{ version } && under_docker_context( $mysync ) )
  2296. {
  2297. return q{} ;
  2298. }
  2299. else
  2300. {
  2301. myprint( $output ) ;
  2302. return $output ;
  2303. }
  2304. }
  2305. sub define_pidfile
  2306. {
  2307. my $mysync = shift @ARG ;
  2308. $mysync->{ pidfilelocking } = defined $mysync->{ pidfilelocking } ? $mysync->{ pidfilelocking } : 0 ;
  2309. my $host1 = $mysync->{ host1 } || q{} ;
  2310. my $user1 = $mysync->{ user1 } || q{} ;
  2311. my $host2 = $mysync->{ host2 } || q{} ;
  2312. my $user2 = $mysync->{ user2 } || q{} ;
  2313. my $account1_filtered = filter_forbidden_characters( slash_to_underscore( $host1 . '_' . $user1 ) ) || q{} ;
  2314. my $account2_filtered = filter_forbidden_characters( slash_to_underscore( $host2 . '_' . $user2 ) ) || q{} ;
  2315. my $pidfile_basename ;
  2316. if ( $ENV{ 'NET_SERVER_SOFTWARE' } and ( $ENV{ 'NET_SERVER_SOFTWARE' } =~ /Net::Server::HTTP/ ) )
  2317. {
  2318. # under local webserver
  2319. $pidfile_basename = 'imapsync' . '_' . $account1_filtered . '_' . $account2_filtered . '.pid' ;
  2320. }
  2321. else
  2322. {
  2323. $pidfile_basename = 'imapsync.pid' ;
  2324. }
  2325. $mysync->{ pidfile } = defined $mysync->{ pidfile } ? $mysync-> { pidfile } : $mysync->{ tmpdir } . "/$pidfile_basename" ;
  2326. $mysync->{ abortfile } = abortfile( $mysync, $PROCESS_ID ) ;
  2327. return ;
  2328. }
  2329. sub abortfile
  2330. {
  2331. my $mysync = shift @ARG ;
  2332. my $pid = shift @ARG ;
  2333. my $abortfile ;
  2334. if ( $mysync->{ abort } )
  2335. {
  2336. $abortfile = $mysync->{ pidfile } . "abort$pid" ;
  2337. }
  2338. else
  2339. {
  2340. $abortfile = $mysync->{ pidfile } . "abort$PROCESS_ID" ;
  2341. }
  2342. return $abortfile ;
  2343. }
  2344. sub tests_kill_zero
  2345. {
  2346. note( 'Entering tests_kill_zero()' ) ;
  2347. SKIP: {
  2348. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests tests_kill_zero avoided on Windows', 8 ) ; }
  2349. is( 1, kill( 'ZERO', $PROCESS_ID ), "kill ZERO : myself $PROCESS_ID => 1" ) ;
  2350. is( 2, kill( 'ZERO', $PROCESS_ID, $PROCESS_ID ), "kill ZERO : myself $PROCESS_ID $PROCESS_ID => 2" ) ;
  2351. if ( (-e '/.dockerenv' ) or ( 0 == $EFFECTIVE_USER_ID) )
  2352. {
  2353. is( 1, kill( 'ZERO', 1 ), "kill ZERO : pid 1 => 1 (docker context or root)" ) ;
  2354. is( 2, kill( 'ZERO', $PROCESS_ID, 1 ), "kill ZERO : myself + pid 1, $PROCESS_ID 1 => 2 (docker context or root)" ) ;
  2355. }
  2356. else
  2357. {
  2358. is( 0, kill( 'ZERO', 1 ), "kill ZERO : pid 1 => 0 (non root)" ) ;
  2359. is( 1, kill( 'ZERO', $PROCESS_ID, 1 ), "kill ZERO : myself + pid 1, $PROCESS_ID 1 => 1 (one is non root)" ) ;
  2360. }
  2361. my $pid_1 = fork( ) ;
  2362. if ( $pid_1 )
  2363. {
  2364. # parent
  2365. }
  2366. else
  2367. {
  2368. # child
  2369. sleep 3 ;
  2370. exit ;
  2371. }
  2372. my $pid_2 ;
  2373. $pid_2 = fork( ) ;
  2374. if ( $pid_2 )
  2375. {
  2376. # I am the parent
  2377. ok( defined( $pid_2 ), "kill_zero: initial fork ok. I am the parent $PROCESS_ID" ) ;
  2378. ok( $pid_2 , "kill_zero: initial fork ok, child pid is $pid_2" ) ;
  2379. is( 3, kill( 'ZERO', $PROCESS_ID, $pid_2, $pid_1 ), "kill ZERO : myself $PROCESS_ID and child $pid_2 and brother $pid_1 => 3" ) ;
  2380. is( $pid_2, waitpid( $pid_2, 0 ), "kill_zero: child $pid_2 no more there => waitpid return $pid_2" ) ;
  2381. }
  2382. else
  2383. {
  2384. # I am the child
  2385. note( 'This one fails under Windows, kill ZERO returns 0 instead of 2' ) ;
  2386. is( 2, kill( 'ZERO', $PROCESS_ID, $pid_1 ), "kill ZERO : myself child $PROCESS_ID brother $pid_1 => 2" ) ;
  2387. myprint( "I am the child pid $PROCESS_ID, Exiting\n" ) ;
  2388. exit ;
  2389. }
  2390. wait( ) ;
  2391. # End of SKIP block
  2392. }
  2393. note( 'Leaving tests_kill_zero()' ) ;
  2394. return ;
  2395. }
  2396. sub tests_killpid_by_parent
  2397. {
  2398. note( 'Entering tests_killpid_by_parent()' ) ;
  2399. SKIP: {
  2400. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests tests_killpid_by_parent avoided on Windows', 7 ) ; }
  2401. is( undef, killpid( ), 'killpid: no args => undef' ) ;
  2402. note( "killpid: trying to kill myself pid $PROCESS_ID, hope I will not succeed" ) ;
  2403. is( undef, killpid( $PROCESS_ID ), 'killpid: myself => undef' ) ;
  2404. local $SIG{'QUIT'} = sub { myprint "GOT SIG QUIT! I am PID $PROCESS_ID. Exiting\n" ; exit ; } ;
  2405. my $pid ;
  2406. $pid = fork( ) ;
  2407. if ( $pid )
  2408. {
  2409. # I am the parent
  2410. ok( defined( $pid ), "killpid: initial fork ok. I am the parent $PROCESS_ID" ) ;
  2411. ok( $pid , "killpid: initial fork ok, child pid is $pid" ) ;
  2412. is( 2, kill( 'ZERO', $PROCESS_ID, $pid ), "kill ZERO : myself $PROCESS_ID and child $pid => 2" ) ;
  2413. is( 1, killpid( $pid ), "killpid: child $pid killed => 1" ) ;
  2414. is( -1, waitpid( $pid, 0 ), "killpid: child $pid no more there => waitpid return -1" ) ;
  2415. }
  2416. else
  2417. {
  2418. # I am the child
  2419. myprint( "I am the child pid $PROCESS_ID, sleeping 1 + 3 seconds then kill myself\n" ) ;
  2420. sleep 1 ;
  2421. myprint( "I am the child pid $PROCESS_ID, slept 1 second, should be killed by my parent now, PPID " . mygetppid( ) . "\n" ) ;
  2422. sleep 3 ;
  2423. # this test should not be run. If it happens => failure.
  2424. ok( 0 == 1, "killpid: child pid $PROCESS_ID not dead => failure" ) ;
  2425. myprint( "I am the child pid $PROCESS_ID, killing myself failure... Exiting\n" ) ;
  2426. exit ;
  2427. }
  2428. # End of SKIP block
  2429. }
  2430. note( 'Leaving tests_killpid_by_parent()' ) ;
  2431. return ;
  2432. }
  2433. sub tests_killpid_by_brother
  2434. {
  2435. note( 'Entering tests_killpid_by_brother()' ) ;
  2436. SKIP: {
  2437. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests tests_killpid_by_brother avoided on Windows', 2 ) ; }
  2438. local $SIG{'QUIT'} = sub { myprint "GOT SIG QUIT! I am PID $PROCESS_ID. Exiting\n" ; exit ; } ;
  2439. my $pid_parent = $PROCESS_ID ;
  2440. myprint( "I am the parent pid $pid_parent\n" ) ;
  2441. my $pid_1 = fork( ) ;
  2442. if ( $pid_1 )
  2443. {
  2444. # parent
  2445. }
  2446. else
  2447. {
  2448. # child
  2449. #while ( 1 ) { } ;
  2450. sleep 2 ;
  2451. sleep 2 ;
  2452. # this test should not be run. If it happens => failure.
  2453. # Well under Windows this always fails, shit!
  2454. ok( 0 == 1 or ( 'MSWin32' eq $OSNAME ) , "killpid: child pid $PROCESS_ID killing by brother but not dead => failure" ) ;
  2455. myprint( "I am the child pid $PROCESS_ID, killing by brother failed... Exiting\n" ) ;
  2456. exit ;
  2457. }
  2458. my $pid_2 ;
  2459. $pid_2 = fork( ) ;
  2460. if ( $pid_2 )
  2461. {
  2462. # parent
  2463. }
  2464. else
  2465. {
  2466. # I am the child
  2467. myprint( "I am the child pid $PROCESS_ID, my brother has pid $pid_1\n" ) ;
  2468. is( 1, killpid( $pid_1 ), "killpid: brother $pid_1 killed => 1" ) ;
  2469. sleep 2 ;
  2470. exit ;
  2471. }
  2472. #sleep 1 ;
  2473. is( $pid_1, waitpid( $pid_1, 0), "I am the parent $PROCESS_ID waitpid _1( $pid_1 )" ) ;
  2474. is( $pid_2, waitpid( $pid_2, 0 ), "I am the parent $PROCESS_ID waitpid _2( $pid_2 )" ) ;
  2475. # End of SKIP block
  2476. }
  2477. note( 'Leaving tests_killpid_by_brother()' ) ;
  2478. return ;
  2479. }
  2480. sub killpid
  2481. {
  2482. my $pidtokill = shift ;
  2483. if ( ! $pidtokill ) {
  2484. myprint( "No process to kill.\n" ) ;
  2485. return ;
  2486. }
  2487. if ( $PROCESS_ID == $pidtokill ) {
  2488. myprint( "I will not kill myself pid $PROCESS_ID via killpid. Sractch it!\n" ) ;
  2489. return ;
  2490. }
  2491. # First ask for suicide
  2492. if ( kill( 'ZERO', $pidtokill ) or ( 'MSWin32' eq $OSNAME ) ) {
  2493. myprint( "Sending signal QUIT to PID $pidtokill \n" ) ;
  2494. kill 'QUIT', $pidtokill ;
  2495. sleep 3 ;
  2496. waitpid( $pidtokill, WNOHANG) ;
  2497. }else{
  2498. myprint( "Can not send signal kill ZERO to PID $pidtokill.\n" ) ;
  2499. return ;
  2500. }
  2501. #while ( waitpid( $pidtokill, WNOHANG) > 0 ) { } ;
  2502. # Then murder
  2503. if ( kill( 'ZERO', $pidtokill ) or ( 'MSWin32' eq $OSNAME ) ) {
  2504. myprint( "Sending signal KILL to PID $pidtokill \n" ) ;
  2505. kill 'KILL', $pidtokill ;
  2506. sleep 1 ;
  2507. waitpid( $pidtokill, WNOHANG) ;
  2508. }else{
  2509. myprint( "Process PID $pidtokill ended.\n" ) ;
  2510. return 1;
  2511. }
  2512. # Well ...
  2513. if ( kill( 'ZERO', $pidtokill ) or ( 'xMSWin32' eq $OSNAME ) ) {
  2514. myprint( "Process PID $pidtokill seems still there. Can not do much.\n" ) ;
  2515. return ;
  2516. }else{
  2517. myprint( "Process PID $pidtokill ended.\n" ) ;
  2518. return 1;
  2519. }
  2520. return ;
  2521. }
  2522. sub tests_abort
  2523. {
  2524. note( 'Entering tests_abort()' ) ;
  2525. # Well, the abort behavior is tested by test.sh
  2526. is( undef, abort( ), 'abort: no args => undef' ) ;
  2527. note( 'Leaving tests_abort()' ) ;
  2528. return ;
  2529. }
  2530. sub abort
  2531. {
  2532. my $mysync = shift @ARG ;
  2533. myprint( "In abort\n" ) ;
  2534. if ( not $mysync ) { return ; }
  2535. if ( ! -r $mysync->{pidfile} ) {
  2536. myprint( "In abort: Can not read pidfile $mysync->{pidfile}\n" ) ;
  2537. return ;
  2538. }
  2539. my $pidtokill = firstline( $mysync->{pidfile} ) ;
  2540. if ( ! $pidtokill ) {
  2541. myprint( "In abort: No process to abort in $mysync->{pidfile}\n" ) ;
  2542. return ;
  2543. }
  2544. if ( ! match_a_pid_number( $pidtokill ) )
  2545. {
  2546. myprint( "In abort: pid $pidtokill in $mysync->{pidfile} is not a pid number\n" ) ;
  2547. return ;
  2548. }
  2549. if ( $mysync->{abortbyfile} )
  2550. {
  2551. abortbyfile( $mysync, $pidtokill ) ;
  2552. }
  2553. else
  2554. {
  2555. killpid( $pidtokill ) ;
  2556. }
  2557. return ;
  2558. }
  2559. sub abortbyfile
  2560. {
  2561. my $mysync = shift @ARG ;
  2562. my $pidtokill = shift @ARG ;
  2563. my $abortfile = abortfile( $mysync, $pidtokill ) ;
  2564. myprint( "touching $abortfile\n" ) ;
  2565. touch( $abortfile ) ;
  2566. return ;
  2567. }
  2568. sub tests_under_docker_context
  2569. {
  2570. note( 'Entering tests_under_docker_context()' ) ;
  2571. is( undef, under_docker_context( ), 'under_docker_context: no args => undef' ) ;
  2572. my $mysync = { } ;
  2573. $mysync->{ dockercontext } = 1 ;
  2574. is( 1, under_docker_context( $mysync ), 'under_docker_context: --dockercontext => 1' ) ;
  2575. $mysync->{ dockercontext } = 0 ;
  2576. is( 0, under_docker_context( $mysync ), 'under_docker_context: --nodockercontext => 0' ) ;
  2577. $mysync = { } ;
  2578. # Is not it a stupid test?
  2579. if ( under_docker_context( $mysync ) )
  2580. {
  2581. is( 1, under_docker_context( $mysync ), 'under_docker_context: docker context => 1' ) ;
  2582. }
  2583. else
  2584. {
  2585. is( 0, under_docker_context( $mysync ), 'under_docker_context: not docker context => 0' ) ;
  2586. }
  2587. note( 'Leaving tests_under_docker_context()' ) ;
  2588. return ;
  2589. }
  2590. sub under_docker_context
  2591. {
  2592. my $mysync = shift ;
  2593. if ( ! defined $mysync ) { return ; }
  2594. if ( defined $mysync->{ dockercontext } )
  2595. {
  2596. return( $mysync->{ dockercontext } ) ;
  2597. }
  2598. if ( -e '/.dockerenv' )
  2599. {
  2600. return 1 ;
  2601. }
  2602. else
  2603. {
  2604. return 0 ;
  2605. }
  2606. return ;
  2607. }
  2608. sub docker_context
  2609. {
  2610. my $mysync = shift ;
  2611. if ( ! under_docker_context( $mysync ) )
  2612. {
  2613. return ;
  2614. }
  2615. output( $mysync, "Docker context detected with the file /.dockerenv\n" ) ;
  2616. # No pidfile by default
  2617. $mysync->{ pidfile } = defined( $mysync->{ pidfile } ) ? $mysync->{ pidfile } : q{} ;
  2618. # No log by default
  2619. if ( defined( $mysync->{ log } ) )
  2620. {
  2621. output( $mysync, "Logging in Docker context. Be sure you added access to it with a mount or similar. See https://docs.docker.com/storage/volumes/\n" ) ;
  2622. }
  2623. else
  2624. {
  2625. output( $mysync, "No log by default in Docker context. Use --log to trigger logging to the logfile.\n" ) ;
  2626. $mysync->{ log } = 0 ;
  2627. }
  2628. # In case something is written relatively to .
  2629. output( $mysync, "Changing current directory to /var/tmp/\n" ) ;
  2630. chdir '/var/tmp/' ;
  2631. return ;
  2632. }
  2633. sub cgibegin
  2634. {
  2635. my $mysync = shift ;
  2636. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2637. require CGI ;
  2638. CGI->import( qw( -no_debug -utf8 ) ) ;
  2639. require CGI::Carp ;
  2640. CGI::Carp->import( qw( fatalsToBrowser ) ) ;
  2641. $mysync->{cgi} = CGI->new( ) ;
  2642. return ;
  2643. }
  2644. sub tests_under_cgi_context
  2645. {
  2646. note( 'Entering tests_under_cgi_context()' ) ;
  2647. # $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  2648. do {
  2649. # Not in cgi context
  2650. delete local $ENV{SERVER_SOFTWARE} ;
  2651. is( undef, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE unset => not in cgi context' ) ;
  2652. } ;
  2653. do {
  2654. # In cgi context
  2655. local $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  2656. is( 1, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE set => in cgi context' ) ;
  2657. } ;
  2658. do {
  2659. # Not in cgi context
  2660. delete local $ENV{SERVER_SOFTWARE} ;
  2661. is( undef, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE unset => not in cgi context' ) ;
  2662. } ;
  2663. do {
  2664. # In cgi context
  2665. local $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  2666. is( 1, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE set => in cgi context' ) ;
  2667. } ;
  2668. note( 'Leaving tests_under_cgi_context()' ) ;
  2669. return ;
  2670. }
  2671. sub under_cgi_context
  2672. {
  2673. my $mysync = shift ;
  2674. # Under cgi context
  2675. if ( $ENV{SERVER_SOFTWARE} ) {
  2676. return 1 ;
  2677. }
  2678. # Not in cgi context
  2679. return ;
  2680. }
  2681. sub cgibuildheader
  2682. {
  2683. my $mysync = shift ;
  2684. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2685. my $imapsync_runs = $mysync->{cgi}->cookie( 'imapsync_runs' ) || 0 ;
  2686. my $cookie = $mysync->{cgi}->cookie(
  2687. -name => 'imapsync_runs',
  2688. -value => 1 + $imapsync_runs,
  2689. -expires => '+20y',
  2690. -path => '/cgi-bin/imapsync',
  2691. ) ;
  2692. my $httpheader ;
  2693. if ( $mysync->{ abort } ) {
  2694. $httpheader = $mysync->{cgi}->header(
  2695. -type => 'text/plain; charset=UTF-8',
  2696. -status => '200 OK to abort syncing IMAP boxes' . ". Here is " . hostname(),
  2697. ) ;
  2698. }elsif( $mysync->{ loaddelay } ) {
  2699. # https://tools.ietf.org/html/rfc2616#section-10.5.4
  2700. # 503 Service Unavailable
  2701. # The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
  2702. $httpheader = $mysync->{cgi}->header(
  2703. -type => 'text/plain; charset=UTF-8',
  2704. -status => '503 Service Unavailable' . ". Be back in $mysync->{ loaddelay } min. Load on " . hostname() . " is $mysync->{ loadavg }",
  2705. ) ;
  2706. }else{
  2707. $httpheader = $mysync->{cgi}->header(
  2708. -type => 'text/plain; charset=UTF-8',
  2709. -status => '200 OK to sync IMAP boxes' . ". Load on " . hostname() . " is $mysync->{ loadavg }",
  2710. -cookie => $cookie,
  2711. ) ;
  2712. }
  2713. output_start( $mysync, $httpheader ) ;
  2714. return ;
  2715. }
  2716. sub cgiload
  2717. {
  2718. # Exit on heavy load in CGI context
  2719. my $mysync = shift ;
  2720. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2721. if ( $mysync->{ abort } ) { return ; } # keep going to abort since some ressources will be free soon
  2722. if ( $mysync->{ loaddelay } )
  2723. {
  2724. $mysync->{nb_errors}++ ;
  2725. exit_clean( $mysync, $EX_UNAVAILABLE,
  2726. "Server is on heavy load. Be back in $mysync->{ loaddelay } min. Load is $mysync->{ loadavg }\n"
  2727. ) ;
  2728. }
  2729. return ;
  2730. }
  2731. sub tests_set_umask
  2732. {
  2733. note( 'Entering tests_set_umask()' ) ;
  2734. my $save_umask = umask ;
  2735. my $mysync = {} ;
  2736. if ( 'MSWin32' eq $OSNAME ) {
  2737. is( undef, set_umask( $mysync ), "set_umask: set failure to $UMASK_PARANO on MSWin32" ) ;
  2738. }else{
  2739. is( 1, set_umask( $mysync ), "set_umask: set to $UMASK_PARANO" ) ;
  2740. }
  2741. umask $save_umask ;
  2742. note( 'Leaving tests_set_umask()' ) ;
  2743. return ;
  2744. }
  2745. sub set_umask
  2746. {
  2747. my $mysync = shift ;
  2748. my $previous_umask = umask_str( ) ;
  2749. my $new_umask = umask_str( $UMASK_PARANO ) ;
  2750. output( $mysync, "Umask set with $new_umask (was $previous_umask)\n" ) ;
  2751. if ( $new_umask eq $UMASK_PARANO ) {
  2752. return 1 ;
  2753. }
  2754. return ;
  2755. }
  2756. sub tests_umask_str
  2757. {
  2758. note( 'Entering tests_umask_str()' ) ;
  2759. my $save_umask = umask ;
  2760. is( umask_str( ), umask_str( ), 'umask_str: no parameters => idopotent' ) ;
  2761. is( my $save_umask_str = umask_str( ), umask_str( ), 'umask_str: no parameters => idopotent + save' ) ;
  2762. is( '0000', umask_str( q{ } ), 'umask_str: q{ } => 0000' ) ;
  2763. is( '0000', umask_str( q{} ), 'umask_str: q{} => 0000' ) ;
  2764. is( '0000', umask_str( '0000' ), 'umask_str: 0000 => 0000' ) ;
  2765. is( '0000', umask_str( '0' ), 'umask_str: 0 => 0000' ) ;
  2766. is( '0200', umask_str( '0200' ), 'umask_str: 0200 => 0200' ) ;
  2767. is( '0400', umask_str( '0400' ), 'umask_str: 0400 => 0400' ) ;
  2768. is( '0600', umask_str( '0600' ), 'umask_str: 0600 => 0600' ) ;
  2769. SKIP: {
  2770. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests success only for Unix', 6 ) ; }
  2771. is( '0100', umask_str( '0100' ), 'umask_str: 0100 => 0100' ) ;
  2772. is( '0001', umask_str( '0001' ), 'umask_str: 0001 => 0001' ) ;
  2773. is( '0777', umask_str( '0777' ), 'umask_str: 0777 => 0777' ) ;
  2774. is( '0777', umask_str( '00777' ), 'umask_str: 00777 => 0777' ) ;
  2775. is( '0777', umask_str( ' 777 ' ), 'umask_str: 777 => 0777' ) ;
  2776. is( "$UMASK_PARANO", umask_str( $UMASK_PARANO ), "umask_str: UMASK_PARANO $UMASK_PARANO => $UMASK_PARANO" ) ;
  2777. }
  2778. is( $save_umask_str, umask_str( $save_umask_str ), 'umask_str: restore with str' ) ;
  2779. is( $save_umask, umask, 'umask_str: umask is restored, controlled by direct umask' ) ;
  2780. is( $save_umask, umask $save_umask, 'umask_str: umask is restored by direct umask' ) ;
  2781. is( $save_umask, umask, 'umask_str: umask initial controlled by direct umask' ) ;
  2782. note( 'Leaving tests_umask_str()' ) ;
  2783. return ;
  2784. }
  2785. sub umask_str
  2786. {
  2787. my $value = shift ;
  2788. if ( defined $value ) {
  2789. umask oct( $value ) ;
  2790. }
  2791. my $current = umask ;
  2792. return( sprintf( '%#04o', $current ) ) ;
  2793. }
  2794. sub tests_umask
  2795. {
  2796. note( 'Entering tests_umask()' ) ;
  2797. my $save_umask ;
  2798. is( umask, umask, 'umask: umask is umask' ) ;
  2799. is( $save_umask = umask, umask, "umask: umask is umask again + save it: $save_umask" ) ;
  2800. is( $save_umask, umask oct(0000), 'umask: umask 0000' ) ;
  2801. is( oct(0000), umask, 'umask: umask is now 0000' ) ;
  2802. is( oct(0000), umask oct(777), 'umask: umask 0777 call, previous 0000' ) ;
  2803. SKIP: {
  2804. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests success only for Unix', 2 ) ; }
  2805. is( oct(777), umask, 'umask: umask is now 0777' ) ;
  2806. is( oct(777), umask $save_umask, "umask: umask $save_umask restore inital value, previous 0777" ) ;
  2807. }
  2808. ok( defined umask $save_umask, "umask: umask $save_umask restore inital value, previous defined" ) ;
  2809. is( $save_umask, umask, 'umask: umask is umask restored' ) ;
  2810. note( 'Leaving tests_umask()' ) ;
  2811. return ;
  2812. }
  2813. sub buggyflagsregex
  2814. {
  2815. # From /X analyse
  2816. # cut -d: -f1 Error_112_all_syncs.txt | xargs egrep -oih 'Invalid system flag [^( ]+' | sort | uniq -c | sort -g
  2817. my @buggyflagsregex = ( 's/\\\\RECEIPTCHECKED|\\\\Indexed|\\\\X-EON-HAS-ATTACHMENT|\\\\UNSEEN|\\\\ATTACHED|\\\\X-HAS-ATTACH|\\\\FORWARDED|\\\\FORWARD|\\\\X-FORWARDED|\\\\\$FORWARDED|\\\\PRIORITY|\\\\READRCPT//g' ) ;
  2818. return( @buggyflagsregex ) ;
  2819. }
  2820. sub cgisetcontext
  2821. {
  2822. my $mysync = shift ;
  2823. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2824. output( $mysync, "Under cgi context\n" ) ;
  2825. set_umask( $mysync ) ;
  2826. # Remove all content in unsafe evaled options
  2827. @{ $mysync->{ regextrans2 } } = ( ) ;
  2828. @{ $mysync->{ regexflag } } = buggyflagsregex( ) ;
  2829. @regexmess = ( ) ;
  2830. @skipmess = ( ) ;
  2831. @pipemess = ( ) ;
  2832. $delete2foldersonly = undef ;
  2833. $delete2foldersbutnot = undef ;
  2834. $maxlinelengthcmd = undef ;
  2835. # Set safe default values (I hope...)
  2836. #$mysync->{pidfile} = 'imapsync.pid' ;
  2837. $mysync->{ pidfilelocking } = 1 ;
  2838. $mysync->{ errorsmax } = $ERRORS_MAX_CGI ;
  2839. $modulesversion = 0 ;
  2840. $mysync->{ releasecheck } = defined $mysync->{ releasecheck } ? $mysync->{ releasecheck } : 1 ;
  2841. $usecache = 0 ;
  2842. $mysync->{ showpasswords } = 0 ;
  2843. $mysync->{ acc1 }->{ debugimap } = 0 ;
  2844. $mysync->{ acc2 }->{ debugimap } = 0 ;
  2845. $mysync->{ acc1 }->{ reconnectretry } = $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  2846. $mysync->{ acc2 }->{ reconnectretry } = $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  2847. $pipemesscheck = 0 ;
  2848. $mysync->{ hashfile } = $CGI_HASHFILE ;
  2849. my $hashsynclocal = hashsynclocal( $mysync ) || die "Can not get hashsynclocal. Exiting\n" ;
  2850. if ( $ENV{ 'NET_SERVER_SOFTWARE' } and ( $ENV{ 'NET_SERVER_SOFTWARE' } =~ /Net::Server::HTTP/ ) )
  2851. {
  2852. # under local webserver
  2853. $cgidir = q{.} ;
  2854. }
  2855. else
  2856. {
  2857. $cgidir = $CGI_TMPDIR_TOP . '/' . $hashsynclocal ;
  2858. }
  2859. -d $cgidir or mkpath $cgidir or die "Can not create $cgidir: $OS_ERROR\n" ;
  2860. $mysync->{ tmpdir } = $cgidir ;
  2861. $mysync->{ logdir } = '' ;
  2862. chdir $cgidir or die "Can not cd to $cgidir: $OS_ERROR\n" ;
  2863. cgioutputenvcontext( $mysync ) ;
  2864. $mysync->{ debug } and output( $mysync, 'Current directory is ' . getcwd( ) . "\n" ) ;
  2865. $mysync->{ debug } and output( $mysync, 'Real user id is ' . getpwuid_any_os( $REAL_USER_ID ) . " (uid $REAL_USER_ID)\n" ) ;
  2866. $mysync->{ debug } and output( $mysync, 'Effective user id is ' . getpwuid_any_os( $EFFECTIVE_USER_ID ). " (euid $EFFECTIVE_USER_ID)\n" ) ;
  2867. $mysync->{ skipemptyfolders } = defined $mysync->{ skipemptyfolders } ? $mysync->{ skipemptyfolders } : 1 ;
  2868. # Out of memory with messages over 1 GB ?
  2869. $mysync->{ maxsize } = defined $mysync->{ maxsize } ? $mysync->{ maxsize } : 1_000_000_000 ;
  2870. # tail -f behaviour on by default
  2871. $mysync->{ tail } = defined $mysync->{ tail } ? $mysync->{ tail } : 1 ;
  2872. # not sure it's for good
  2873. @useheader = qw( Message-Id Received ) ;
  2874. # addheader on by default
  2875. $mysync->{ addheader } = defined $mysync->{ addheader } ? $mysync->{ addheader } : 1 ;
  2876. # sync duplicates by default in cgi context
  2877. $mysync->{ syncduplicates } = defined $mysync->{ syncduplicates } ? $mysync->{ syncduplicates } : 1 ;
  2878. # log the logfile name by default in cgi context
  2879. $mysync->{ loglogfile } = defined $mysync->{ loglogfile } ? $mysync->{ loglogfile } : 1 ;
  2880. return ;
  2881. }
  2882. sub cgioutputenvcontext
  2883. {
  2884. my $mysync = shift @ARG ;
  2885. for my $envvar ( qw( REMOTE_ADDR REMOTE_HOST HTTP_REFERER HTTP_USER_AGENT SERVER_SOFTWARE SERVER_PORT HTTP_COOKIE ) ) {
  2886. my $envval = $ENV{ $envvar } || q{} ;
  2887. if ( $envval ) { output( $mysync, "$envvar is $envval\n" ) } ;
  2888. }
  2889. return ;
  2890. }
  2891. sub announcelogfile
  2892. {
  2893. my $mysync = shift ;
  2894. if ( $mysync->{ log } )
  2895. {
  2896. myprint( "Log file is $mysync->{ logfile } ( to change it, use --logfile path ; or use --nolog to turn off logging )\n" ) ;
  2897. loglogfile( $mysync ) ;
  2898. }
  2899. else
  2900. {
  2901. myprint( "No log file because of option --nolog\n" ) ;
  2902. }
  2903. return ;
  2904. }
  2905. sub loglogfile
  2906. {
  2907. my $mysync = shift ;
  2908. if ( ! $mysync->{ loglogfile } ) { return ; }
  2909. if ( ! $mysync->{ log } ) { return ; }
  2910. my $cwd = getcwd( ) ;
  2911. my $absolutelogfilepath ;
  2912. # Fixme: add case when the logfile name is already absolute
  2913. $absolutelogfilepath = "$cwd/$mysync->{ logfile }" ;
  2914. my $loglogfilename = '../list_all_logs_auto.txt' ;
  2915. myprint( "Writing log file name $absolutelogfilepath to $loglogfilename\n" ) ;
  2916. if ( open( my $fh, '>>', $loglogfilename ) )
  2917. {
  2918. print $fh "$absolutelogfilepath\n" ;
  2919. close $fh ;
  2920. }
  2921. else
  2922. {
  2923. myprint( "Could not open loglogfile $loglogfilename $!\n" ) ;
  2924. }
  2925. return ;
  2926. }
  2927. sub checkselectable
  2928. {
  2929. my $mysync = shift ;
  2930. if ( $mysync->{ checkselectable } ) {
  2931. my @h1_folders_wanted_selectable ;
  2932. myprint( "Host1: Checking wanted folders are selectable. Use --nocheckselectable to avoid this check.\n" ) ;
  2933. foreach my $folder ( @{ $mysync->{ h1_folders_wanted } } )
  2934. {
  2935. ( $mysync->{ debug } or $mysync->{ debugfolders } ) and myprint( "Checking $folder is selectable on host1\n" ) ;
  2936. # It does an imap command LIST "" $folder and then search for no \Noselect
  2937. if ( ! $mysync->{ imap1 }->selectable( $folder ) )
  2938. {
  2939. myprint( "Host1: warning! ignoring folder $folder because it is not selectable\n" ) ;
  2940. }else
  2941. {
  2942. push @h1_folders_wanted_selectable, $folder ;
  2943. }
  2944. }
  2945. @{ $mysync->{ h1_folders_wanted } } = @h1_folders_wanted_selectable ;
  2946. ( $mysync->{ debug } or $mysync->{ debugfolders } )
  2947. and myprint( 'Host1: checking folders took ', timenext( $mysync ), " s\n" ) ;
  2948. }
  2949. else
  2950. {
  2951. myprint( "Host1: Not checking that wanted folders are selectable. Use --checkselectable to force this check.\n" ) ;
  2952. }
  2953. return ;
  2954. }
  2955. sub setcheckselectable
  2956. {
  2957. my $mysync = shift ;
  2958. my $h1_folders_wanted_nb = scalar @{ $mysync->{ h1_folders_wanted } } ;
  2959. # 152 because 98% of host1 accounts have less than 152 folders on /X service.
  2960. # command to get this value:
  2961. # datamash_file_op_index G_Host1_Nb_folders.txt perc:98 4 %16.1f
  2962. if ( ! defined $mysync->{ checkselectable } )
  2963. {
  2964. if ( 152 >= $h1_folders_wanted_nb )
  2965. {
  2966. $mysync->{ checkselectable } = 1 ;
  2967. }else{
  2968. myprint( "Host1: Not checking that $h1_folders_wanted_nb wanted folders are selectable. Use --checkselectable to force this check.\n" ) ;
  2969. $mysync->{ checkselectable } = 0 ;
  2970. }
  2971. }
  2972. return ;
  2973. }
  2974. sub debugsleep
  2975. {
  2976. my $mysync = shift @ARG ;
  2977. if ( defined $mysync->{debugsleep} ) {
  2978. myprint( "Info: sleeping $mysync->{debugsleep}s\n" ) ;
  2979. sleep $mysync->{debugsleep} ;
  2980. }
  2981. return ;
  2982. }
  2983. sub tests_foldersize
  2984. {
  2985. note( 'Entering tests_foldersize()' ) ;
  2986. is( undef, foldersize( ), 'foldersize: no args => undef' ) ;
  2987. #is_deeply( {}, {}, 'foldersize: a hash is a hash' ) ;
  2988. #is_deeply( [], [], 'foldersize: an array is an array' ) ;
  2989. note( 'Leaving tests_foldersize()' ) ;
  2990. return ;
  2991. }
  2992. # Globals:
  2993. # $fetch_hash_set
  2994. #
  2995. sub foldersize
  2996. {
  2997. # size of one folder
  2998. my ( $mysync, $side, $imap, $search_cmd, $abletosearch, $folder ) = @ARG ;
  2999. if ( ! all_defined( $mysync, $side, $imap, $folder ) )
  3000. {
  3001. return ;
  3002. }
  3003. # FTGate is RFC buggy with EXAMINE it does not act as SELECT
  3004. #if ( ! $imap->examine( $folder ) ) {
  3005. if ( ! $imap->select( $folder ) ) {
  3006. my $error = join q{},
  3007. "$side Folder $folder: Could not select: ",
  3008. $imap->LastError, "\n" ;
  3009. errors_incr( $mysync, $error ) ;
  3010. return ;
  3011. }
  3012. if ( $imap->IsUnconnected( ) )
  3013. {
  3014. return ;
  3015. }
  3016. my $hash_ref = { } ;
  3017. my @msgs = select_msgs( $imap, undef, $search_cmd, $abletosearch, $folder ) ;
  3018. my $nb_msgs = scalar @msgs ;
  3019. my $biggest_in_folder = 0 ;
  3020. @{ $hash_ref }{ @msgs } = ( undef ) if @msgs ;
  3021. my $stot = 0 ;
  3022. if ( $imap->IsUnconnected( ) )
  3023. {
  3024. return ;
  3025. }
  3026. if ( $nb_msgs > 0 and @msgs ) {
  3027. if ( $abletosearch ) {
  3028. if ( ! $imap->fetch_hash( \@msgs, 'RFC822.SIZE', $hash_ref) ) {
  3029. my $error = "$side failure with fetch_hash: $EVAL_ERROR\n" ;
  3030. errors_incr( $mysync, $error ) ;
  3031. return ;
  3032. }
  3033. }
  3034. else
  3035. {
  3036. my $fetch_hash_uids = $fetch_hash_set || "1:*" ;
  3037. if ( ! $imap->fetch_hash( $fetch_hash_uids, 'RFC822.SIZE', $hash_ref ) ) {
  3038. my $error = "$side failure with fetch_hash: $EVAL_ERROR\n" ;
  3039. errors_incr( $mysync, $error ) ;
  3040. return ;
  3041. }
  3042. }
  3043. for ( keys %{ $hash_ref } ) {
  3044. my $size = $hash_ref->{ $_ }->{ 'RFC822.SIZE' } ;
  3045. if ( defined $size )
  3046. {
  3047. $stot += $size ;
  3048. $biggest_in_folder = max( $biggest_in_folder, $size ) ;
  3049. }
  3050. }
  3051. }
  3052. return( $stot, $nb_msgs, $biggest_in_folder ) ;
  3053. }
  3054. # The old subroutine that performed just one side at a time.
  3055. # Still here for a while, until confident with sub foldersize_diff_compute()
  3056. sub foldersizes
  3057. {
  3058. my ( $mysync, $side, $imap, $search_cmd, $abletosearch, @folders ) = @_ ;
  3059. my $total_size = 0 ;
  3060. my $total_nb = 0 ;
  3061. my $biggest_in_all = 0 ;
  3062. my $nb_folders = scalar @folders ;
  3063. my $ct_folders = 0 ; # folder counter.
  3064. myprint( "++++ Calculating sizes of $nb_folders folders on $side\n" ) ;
  3065. foreach my $folder ( @folders ) {
  3066. my $stot = 0 ;
  3067. my $nb_msgs = 0 ;
  3068. my $biggest_in_folder = 0 ;
  3069. $ct_folders++ ;
  3070. myprintf( "$side folder %7s %-35s", "$ct_folders/$nb_folders", jux_utf8( $folder ) ) ;
  3071. if ( 'Host2' eq $side and not exists $mysync->{h2_folders_all_UPPER}{ uc $folder } ) {
  3072. myprint( " does not exist yet\n") ;
  3073. next ;
  3074. }
  3075. if ( 'Host1' eq $side and not exists $h1_folders_all{ $folder } ) {
  3076. myprint( " does not exist\n" ) ;
  3077. next ;
  3078. }
  3079. last if $imap->IsUnconnected( ) ;
  3080. ( $stot, $nb_msgs, $biggest_in_folder ) = foldersize( $mysync, $side, $imap, $search_cmd, $abletosearch, $folder ) ;
  3081. myprintf( ' Size: %9s', $stot ) ;
  3082. myprintf( ' Messages: %5s', $nb_msgs ) ;
  3083. myprintf( " Biggest: %9s\n", $biggest_in_folder ) ;
  3084. $total_size += $stot ;
  3085. $total_nb += $nb_msgs ;
  3086. $biggest_in_all = max( $biggest_in_all, $biggest_in_folder ) ;
  3087. }
  3088. myprintf( "%s Nb folders: %11s folders\n", $side, $nb_folders ) ;
  3089. myprintf( "%s Nb messages: %11s messages\n", $side, $total_nb ) ;
  3090. myprintf( "%s Total size: %11s bytes (%s)\n", $side, $total_size, bytes_display_string( $total_size ) ) ;
  3091. myprintf( "%s Biggest message: %11s bytes (%s)\n", $side, $biggest_in_all, bytes_display_string( $biggest_in_all ) ) ;
  3092. myprintf( "%s Time spent on sizing: %11.1f seconds\n", $side, timenext( $mysync ) ) ;
  3093. return( $total_nb, $total_size ) ;
  3094. }
  3095. sub foldersize_diff_present
  3096. {
  3097. my $mysync = shift ;
  3098. my $folder1 = shift ;
  3099. my $folder2 = shift ;
  3100. my $counter_str = shift ;
  3101. my $force = shift ;
  3102. my $values1_str ;
  3103. my $values2_str ;
  3104. if ( ! defined $mysync->{ folder1 }->{ $folder1 }->{ size } || $force )
  3105. {
  3106. foldersize_diff_compute( $mysync, $folder1, $folder2, $force ) ;
  3107. }
  3108. # again, but this time it means no availaible data.
  3109. if ( defined $mysync->{ folder1 }->{ $folder1 }->{ size } )
  3110. {
  3111. $values1_str = sprintf( "Size: %9s Messages: %5s Biggest: %9s\n",
  3112. $mysync->{ folder1 }->{ $folder1 }->{ size },
  3113. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs },
  3114. $mysync->{ folder1 }->{ $folder1 }->{ biggest },
  3115. ) ;
  3116. }
  3117. else
  3118. {
  3119. $values1_str = " does not exist\n" ;
  3120. }
  3121. if ( defined $mysync->{ folder2 }->{ $folder2 }->{ size } )
  3122. {
  3123. $values2_str = sprintf( "Size: %9s Messages: %5s Biggest: %9s\n",
  3124. $mysync->{ folder2 }->{ $folder2 }->{ size },
  3125. $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs },
  3126. $mysync->{ folder2 }->{ $folder2 }->{ biggest },
  3127. ) ;
  3128. }
  3129. else
  3130. {
  3131. $values2_str = " does not exist yet\n" ;
  3132. }
  3133. myprintf( "Host1 folder %7s %-35s %s",
  3134. "$counter_str",
  3135. jux_utf8( $folder1 ),
  3136. $values1_str
  3137. ) ;
  3138. myprintf( "Host2 folder %7s %-35s %s",
  3139. "$counter_str",
  3140. jux_utf8( $folder2 ),
  3141. $values2_str
  3142. ) ;
  3143. myprintf( "Host2-Host1 %7s %-35s %9s %5s %9s\n\n",
  3144. "",
  3145. "",
  3146. $mysync->{ folder1 }->{ $folder1 }->{ size_diff },
  3147. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs_diff },
  3148. $mysync->{ folder1 }->{ $folder1 }->{ biggest_diff },
  3149. ) ;
  3150. return ;
  3151. }
  3152. sub foldersize_diff_compute
  3153. {
  3154. my $mysync = shift ;
  3155. my $folder1 = shift ;
  3156. my $folder2 = shift ;
  3157. my $force = shift ;
  3158. my ( $size_1, $nb_msgs_1, $biggest_1 ) ;
  3159. # memoization
  3160. if (
  3161. exists $h1_folders_all{ $folder1 }
  3162. &&
  3163. (
  3164. ! defined $mysync->{ folder1 }->{ $folder1 }->{ size }
  3165. || $force
  3166. )
  3167. )
  3168. {
  3169. #myprint( "foldersize folder1 $h1_folders_all{ $folder1 }\n" ) ;
  3170. ( $size_1, $nb_msgs_1, $biggest_1 ) =
  3171. foldersize( $mysync,
  3172. 'Host1',
  3173. $mysync->{ imap1 },
  3174. $mysync->{ search1 },
  3175. $mysync->{ abletosearch1 },
  3176. $folder1
  3177. ) ;
  3178. $mysync->{ folder1 }->{ $folder1 }->{ size } = $size_1 ;
  3179. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs } = $nb_msgs_1 ;
  3180. $mysync->{ folder1 }->{ $folder1 }->{ biggest } = $biggest_1 ;
  3181. }
  3182. else
  3183. {
  3184. $size_1 = $mysync->{ folder1 }->{ $folder1 }->{ size } ;
  3185. $nb_msgs_1 = $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs } ;
  3186. $biggest_1 = $mysync->{ folder1 }->{ $folder1 }->{ biggest } ;
  3187. }
  3188. my ( $size_2, $nb_msgs_2, $biggest_2 ) ;
  3189. if (
  3190. exists $mysync->{ h2_folders_all_UPPER }{ uc $folder2 }
  3191. &&
  3192. (
  3193. ! defined $mysync->{ folder2 }->{ $folder2 }->{ size }
  3194. || $force
  3195. )
  3196. )
  3197. {
  3198. #myprint( "foldersize folder2\n" ) ;
  3199. ( $size_2, $nb_msgs_2, $biggest_2 ) =
  3200. foldersize( $mysync,
  3201. 'Host2',
  3202. $mysync->{ imap2 },
  3203. $mysync->{ search2 },
  3204. $mysync->{ abletosearch2 },
  3205. $folder2
  3206. ) ;
  3207. $mysync->{ folder2 }->{ $folder2 }->{ size } = $size_2 ;
  3208. $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs } = $nb_msgs_2 ;
  3209. $mysync->{ folder2 }->{ $folder2 }->{ biggest } = $biggest_2 ;
  3210. }
  3211. else
  3212. {
  3213. $size_2 = $mysync->{ folder2 }->{ $folder2 }->{ size } ;
  3214. $nb_msgs_2 = $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs } ;
  3215. $biggest_2 = $mysync->{ folder2 }->{ $folder2 }->{ biggest } ;
  3216. }
  3217. my $size_diff = diff( $size_2, $size_1 ) ;
  3218. my $nb_msgs_diff = diff( $nb_msgs_2, $nb_msgs_1 ) ;
  3219. my $biggest_diff = diff( $biggest_2, $biggest_1 ) ;
  3220. $mysync->{ folder1 }->{ $folder1 }->{ size_diff } = $size_diff ;
  3221. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs_diff } = $nb_msgs_diff ;
  3222. $mysync->{ folder1 }->{ $folder1 }->{ biggest_diff } = $biggest_diff ;
  3223. # It's redundant but easier to access later
  3224. $mysync->{ folder2 }->{ $folder2 }->{ size_diff } = $size_diff ;
  3225. $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs_diff } = $nb_msgs_diff ;
  3226. $mysync->{ folder2 }->{ $folder2 }->{ biggest_diff } = $biggest_diff ;
  3227. return ;
  3228. }
  3229. sub diff
  3230. {
  3231. my $x = shift ;
  3232. my $y = shift ;
  3233. $x ||= 0 ;
  3234. $y ||= 0 ;
  3235. return $x - $y ;
  3236. }
  3237. sub add
  3238. {
  3239. my $x = shift ;
  3240. my $y = shift ;
  3241. $x ||= 0 ;
  3242. $y ||= 0 ;
  3243. return $x + $y ;
  3244. }
  3245. sub tests_checknoabletosearch
  3246. {
  3247. note( 'Entering checknoabletosearch()' ) ;
  3248. is( undef, checknoabletosearch( ), 'checknoabletosearch: no args => undef' ) ;
  3249. note( 'Leaving checknoabletosearch()' ) ;
  3250. return ;
  3251. }
  3252. sub checknoabletosearch
  3253. {
  3254. # call example: checknoabletosearch( $sync, $sync->{ imap1 }, 'INBOX', 'Host1' ) ;
  3255. # output:
  3256. # * undef if something is not ok to decide
  3257. # * 1 if SEARCH ALL failed
  3258. my( $mysync, $imap, $folder, $HostX ) = @ARG ;
  3259. if ( ! all_defined( $mysync, $imap, $folder, $HostX ) )
  3260. {
  3261. return ;
  3262. }
  3263. myprint( "$HostX: checking if SEARCH ALL works on $folder\n" ) ;
  3264. if ( ! select_folder( $mysync, $imap, $folder, $HostX ) )
  3265. {
  3266. myprint( "$HostX: can not SELECT folder [$folder]\n" ) ;
  3267. return ;
  3268. }
  3269. my $count_from_select = count_from_select( $imap->History ) ;
  3270. myprint( "$HostX: folder [$folder] has $count_from_select messages mentioned by SELECT\n" ) ;
  3271. my $msgs_all = $imap->messages( ) ;
  3272. if ( ! $msgs_all )
  3273. {
  3274. myprint( "$HostX: can not SEARCH ALL folder [$folder]\n" ) ;
  3275. myprint( "$HostX: ", $imap->LastError(), "\n" ) ;
  3276. return 1 ;
  3277. }
  3278. my $count_from_search_all = scalar( @{ $msgs_all } ) ;
  3279. myprint( "$HostX: folder [$folder] has $count_from_search_all messages found by SEARCH ALL\n" ) ;
  3280. if ( $count_from_select == $count_from_search_all )
  3281. {
  3282. myprint( "$HostX: folder [$folder] has the same messages count ($count_from_select) by SELECT and SEARCH ALL\n" ) ;
  3283. }
  3284. else
  3285. {
  3286. myprint( "$HostX: Warning, folder [$folder] has not the same count by SELECT ($count_from_select) and SEARCH ALL ($count_from_search_all)\n" ) ;
  3287. return 1 ;
  3288. }
  3289. return ;
  3290. }
  3291. sub foldersizes_diff_list
  3292. {
  3293. my $mysync = shift ;
  3294. my $force = shift ;
  3295. my @folders = @{ $mysync->{h1_folders_wanted} } ;
  3296. my $nb_folders = scalar @folders ;
  3297. my $ct_folders = 0 ; # folder counter.
  3298. foreach my $folder1 ( @folders )
  3299. {
  3300. $ct_folders++ ;
  3301. my $counter_str = "$ct_folders/$nb_folders" ;
  3302. my $folder2 = imap2_folder_name( $mysync, $folder1 ) ;
  3303. foldersize_diff_present( $mysync, $folder1, $folder2, $counter_str, $force ) ;
  3304. }
  3305. return ;
  3306. }
  3307. sub foldersizes_total
  3308. {
  3309. my $mysync = shift ;
  3310. my @folders_1 = @{ $mysync->{h1_folders_wanted} } ;
  3311. my @folders_2 = @h2_folders_from_1_wanted ;
  3312. my $nb_folders_1 = scalar( @folders_1 ) ;
  3313. my $nb_folders_2 = scalar( @folders_2 ) ;
  3314. my ( $total_size_1, $total_nb_1, $biggest_in_all_1 ) = ( 0, 0, 0 ) ;
  3315. my ( $total_size_2, $total_nb_2, $biggest_in_all_2 ) = ( 0, 0, 0 ) ;
  3316. foreach my $folder1 ( @folders_1 )
  3317. {
  3318. $total_size_1 = add( $total_size_1, $mysync->{ folder1 }->{ $folder1 }->{ size } ) ;
  3319. $total_nb_1 = add( $total_nb_1, $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs } ) ;
  3320. $biggest_in_all_1 = max( $biggest_in_all_1 , $mysync->{ folder1 }->{ $folder1 }->{ biggest } ) ;
  3321. }
  3322. foreach my $folder2 ( @folders_2 )
  3323. {
  3324. $total_size_2 = add( $total_size_2, $mysync->{ folder2 }->{ $folder2 }->{ size } ) ;
  3325. $total_nb_2 = add( $total_nb_2, $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs } ) ;
  3326. $biggest_in_all_2 = max( $biggest_in_all_2 , $mysync->{ folder2 }->{ $folder2 }->{ biggest } ) ;
  3327. }
  3328. myprintf( "Host1 Nb folders: %11s folders\n", $nb_folders_1 ) ;
  3329. myprintf( "Host2 Nb folders: %11s folders\n", $nb_folders_2 ) ;
  3330. myprint( "\n" ) ;
  3331. myprintf( "Host1 Nb messages: %11s messages\n", $total_nb_1 ) ;
  3332. myprintf( "Host2 Nb messages: %11s messages\n", $total_nb_2 ) ;
  3333. myprint( "\n" ) ;
  3334. myprintf( "Host1 Total size: %11s bytes (%s)\n", $total_size_1, bytes_display_string( $total_size_1 ) ) ;
  3335. myprintf( "Host2 Total size: %11s bytes (%s)\n", $total_size_2, bytes_display_string( $total_size_2 ) ) ;
  3336. myprint( "\n" ) ;
  3337. myprintf( "Host1 Biggest message: %11s bytes (%s)\n", $biggest_in_all_1, bytes_display_string( $biggest_in_all_1 ) ) ;
  3338. myprintf( "Host2 Biggest message: %11s bytes (%s)\n", $biggest_in_all_2, bytes_display_string( $biggest_in_all_2 ) ) ;
  3339. myprint( "\n" ) ;
  3340. myprintf( "Time spent on sizing: %11.1f seconds\n", timenext( $mysync ) ) ;
  3341. my @total_1_2 = ( $total_nb_1, $total_size_1, $total_nb_2, $total_size_2 ) ;
  3342. return @total_1_2 ;
  3343. }
  3344. sub foldersizesatend_old
  3345. {
  3346. my $mysync = shift ;
  3347. timenext( $mysync ) ;
  3348. return if ( $mysync->{imap1}->IsUnconnected( ) ) ;
  3349. return if ( $mysync->{imap2}->IsUnconnected( ) ) ;
  3350. # Get all folders on host2 again since new were created
  3351. @h2_folders_all = sort $mysync->{imap2}->folders();
  3352. for ( @h2_folders_all ) {
  3353. $h2_folders_all{ $_ } = 1 ;
  3354. $mysync->{h2_folders_all_UPPER}{ uc $_ } = 1 ;
  3355. } ;
  3356. ( $h1_nb_msg_end, $h1_bytes_end ) = foldersizes( $mysync, 'Host1', $mysync->{imap1}, $mysync->{ search1 }, $mysync->{abletosearch1}, @{ $mysync->{h1_folders_wanted} } ) ;
  3357. ( $h2_nb_msg_end, $h2_bytes_end ) = foldersizes( $mysync, 'Host2', $mysync->{imap2}, $mysync->{ search2 }, $mysync->{abletosearch2}, @h2_folders_from_1_wanted ) ;
  3358. if ( not all_defined( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end ) ) {
  3359. my $error = "Failure getting foldersizes, final differences will not be calculated\n" ;
  3360. errors_incr( $mysync, $error ) ;
  3361. }
  3362. return ;
  3363. }
  3364. sub foldersizesatend
  3365. {
  3366. my $mysync = shift ;
  3367. timenext( $mysync ) ;
  3368. return if ( $mysync->{imap1}->IsUnconnected( ) ) ;
  3369. return if ( $mysync->{imap2}->IsUnconnected( ) ) ;
  3370. # Get all folders on host2 again since new were created
  3371. @h2_folders_all = sort $mysync->{imap2}->folders();
  3372. for ( @h2_folders_all ) {
  3373. $h2_folders_all{ $_ } = 1 ;
  3374. $mysync->{h2_folders_all_UPPER}{ uc $_ } = 1 ;
  3375. } ;
  3376. foldersizes_diff_list( $mysync, $FORCE ) ;
  3377. ( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end )
  3378. = foldersizes_total( $mysync ) ;
  3379. if ( not all_defined( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end ) ) {
  3380. my $error = "Failure getting foldersizes, final differences will not be calculated\n" ;
  3381. errors_incr( $mysync, $error ) ;
  3382. }
  3383. return ;
  3384. }
  3385. sub foldersizes_at_the_beggining
  3386. {
  3387. my $mysync = shift ;
  3388. myprint( << 'END_SIZE' ) ;
  3389. Folders sizes before the synchronization.
  3390. You can remove foldersizes listings by using "--nofoldersizes" and "--nofoldersizesatend"
  3391. but then you will also lose the ETA (Estimation Time of Arrival) given after each message copy.
  3392. END_SIZE
  3393. foldersizes_diff_list( $mysync ) ;
  3394. ( $mysync->{ h1_nb_msg_start }, $mysync->{ h1_bytes_start },
  3395. $mysync->{ h2_nb_msg_start }, $mysync->{ h2_bytes_start } )
  3396. = foldersizes_total( $mysync ) ;
  3397. if ( not all_defined(
  3398. $mysync->{ h1_nb_msg_start },
  3399. $mysync->{ h1_bytes_start },
  3400. $mysync->{ h2_nb_msg_start },
  3401. $mysync->{ h2_bytes_start } ) )
  3402. {
  3403. my $error = "Failure getting foldersizes, ETA and final diff will not be displayed\n" ;
  3404. errors_incr( $mysync, $error ) ;
  3405. $mysync->{ foldersizes } = 0 ;
  3406. $mysync->{ foldersizesatend } = 0 ;
  3407. return ;
  3408. }
  3409. my $h2_bytes_limit = $mysync->{ acc2 }->{quota_limit_bytes} || 0 ;
  3410. if ( $h2_bytes_limit and ( $h2_bytes_limit < $mysync->{ h1_bytes_start } ) )
  3411. {
  3412. my $quota_percent = mysprintf( '%.0f', $NUMBER_100 * $mysync->{ h1_bytes_start } / $h2_bytes_limit ) ;
  3413. my $error = "Host2: Quota limit will be exceeded! Over $quota_percent % ( $mysync->{ h1_bytes_start } bytes / $h2_bytes_limit bytes )\n" ;
  3414. errors_incr( $mysync, $error ) ;
  3415. }
  3416. return ;
  3417. }
  3418. # Globals:
  3419. # @h2_folders_from_1_wanted
  3420. sub foldersizes_at_the_beggining_old
  3421. {
  3422. my $mysync = shift ;
  3423. myprint( << 'END_SIZE' ) ;
  3424. Folders sizes before the synchronization.
  3425. You can remove foldersizes listings by using "--nofoldersizes" and "--nofoldersizesatend"
  3426. but then you will also lose the ETA (Estimation Time of Arrival) given after each message copy.
  3427. END_SIZE
  3428. ( $mysync->{ h1_nb_msg_start }, $mysync->{ h1_bytes_start } ) =
  3429. foldersizes( $mysync, 'Host1', $mysync->{imap1}, $mysync->{ search1 },
  3430. $mysync->{abletosearch1}, @{ $mysync->{h1_folders_wanted} } ) ;
  3431. ( $mysync->{ h2_nb_msg_start }, $mysync->{ h2_bytes_start } ) =
  3432. foldersizes( $mysync, 'Host2', $mysync->{imap2}, $mysync->{ search2 },
  3433. $mysync->{abletosearch2}, @h2_folders_from_1_wanted ) ;
  3434. if ( not all_defined( $mysync->{ h1_nb_msg_start },
  3435. $mysync->{ h1_bytes_start }, $mysync->{ h2_nb_msg_start }, $mysync->{ h2_bytes_start } ) )
  3436. {
  3437. my $error = "Failure getting foldersizes, ETA and final diff will not be displayed\n" ;
  3438. errors_incr( $mysync, $error ) ;
  3439. $mysync->{ foldersizes } = 0 ;
  3440. $mysync->{ foldersizesatend } = 0 ;
  3441. return ;
  3442. }
  3443. my $h2_bytes_limit = $mysync->{ acc2 }->{quota_limit_bytes} || 0 ;
  3444. if ( $h2_bytes_limit and ( $h2_bytes_limit < $mysync->{ h1_bytes_start } ) )
  3445. {
  3446. my $quota_percent = mysprintf( '%.0f', $NUMBER_100 * $mysync->{ h1_bytes_start } / $h2_bytes_limit ) ;
  3447. my $error = "Host2: Quota limit will be exceeded! Over $quota_percent % ( $mysync->{ h1_bytes_start } bytes / $h2_bytes_limit bytes )\n" ;
  3448. errors_incr( $mysync, $error ) ;
  3449. }
  3450. return ;
  3451. }
  3452. sub tests_total_bytes_max_reached
  3453. {
  3454. note( 'Entering tests_total_bytes_max_reached()' ) ;
  3455. is( undef, total_bytes_max_reached( ), 'total_bytes_max_reached: no args => undef' ) ;
  3456. my $mysync = {} ;
  3457. is( undef, total_bytes_max_reached( $mysync ), 'total_bytes_max_reached: no exitwhenover => undef' ) ;
  3458. $mysync->{ exitwhenover } = 300 ;
  3459. is( undef, total_bytes_max_reached( $mysync ), 'total_bytes_max_reached: exitwhenover 300 but no total_bytes_transferred => undef' ) ;
  3460. $mysync->{ total_bytes_transferred } = 200 ;
  3461. is( undef, total_bytes_max_reached( $mysync ), 'total_bytes_max_reached: exitwhenover 300 but total_bytes_transferred 200 => undef' ) ;
  3462. $mysync->{ total_bytes_transferred } = 400 ;
  3463. is( 1, total_bytes_max_reached( $mysync ), 'total_bytes_max_reached: exitwhenover 300 but total_bytes_transferred 400 => 1' ) ;
  3464. note( 'Leaving tests_total_bytes_max_reached()' ) ;
  3465. return ;
  3466. }
  3467. sub total_bytes_max_reached
  3468. {
  3469. my $mysync = shift ;
  3470. if ( ! defined $mysync ) { return ; }
  3471. if ( ! $mysync->{ exitwhenover } )
  3472. {
  3473. return ;
  3474. }
  3475. if ( ! $mysync->{ total_bytes_transferred } )
  3476. {
  3477. return ;
  3478. }
  3479. if ( $mysync->{ total_bytes_transferred } >= $mysync->{ exitwhenover } )
  3480. {
  3481. my $error = "Maximum bytes transferred reached, $mysync->{total_bytes_transferred} >= $mysync->{ exitwhenover }, ending sync\n" ;
  3482. errors_incr( $mysync, $error ) ;
  3483. return( 1 ) ;
  3484. }
  3485. return ;
  3486. }
  3487. sub tests_mock_capability
  3488. {
  3489. note( 'Entering tests_mock_capability()' ) ;
  3490. my $myimap ;
  3491. ok( $myimap = mock_capability( ),
  3492. 'mock_capability: (1) no args => a Test::MockObject'
  3493. ) ;
  3494. ok( $myimap->isa( 'Test::MockObject' ),
  3495. 'mock_capability: (2) no args => a Test::MockObject'
  3496. ) ;
  3497. is( undef, $myimap->capability( ),
  3498. 'mock_capability: (3) no args => capability undef'
  3499. ) ;
  3500. ok( mock_capability( $myimap ),
  3501. 'mock_capability: (1) one arg => MockObject'
  3502. ) ;
  3503. is( undef, $myimap->capability( ),
  3504. 'mock_capability: (2) one arg OO style => capability undef'
  3505. ) ;
  3506. ok( mock_capability( $myimap, $NUMBER_123456 ),
  3507. 'mock_capability: (1) two args 123456 => capability 123456'
  3508. ) ;
  3509. is( $NUMBER_123456, $myimap->capability( ),
  3510. 'mock_capability: (2) two args 123456 => capability 123456'
  3511. ) ;
  3512. ok( mock_capability( $myimap, 'ABCD' ),
  3513. 'mock_capability: (1) two args ABCD => capability ABCD'
  3514. ) ;
  3515. is( 'ABCD', $myimap->capability( ),
  3516. 'mock_capability: (2) two args ABCD => capability ABCD'
  3517. ) ;
  3518. ok( mock_capability( $myimap, [ 'ABCD' ] ),
  3519. 'mock_capability: (1) two args [ ABCD ] => capability [ ABCD ]'
  3520. ) ;
  3521. is_deeply( [ 'ABCD' ], $myimap->capability( ),
  3522. 'mock_capability: (2) two args [ ABCD ] => capability [ ABCD ]'
  3523. ) ;
  3524. ok( mock_capability( $myimap, [ 'ABC', 'DEF' ] ),
  3525. 'mock_capability: (1) two args [ ABC, DEF ] => capability [ ABC, DEF ]'
  3526. ) ;
  3527. is_deeply( [ 'ABC', 'DEF' ], $myimap->capability( ),
  3528. 'mock_capability: (2) two args [ ABC, DEF ] => capability capability [ ABC, DEF ]'
  3529. ) ;
  3530. ok( mock_capability( $myimap, 'ABC', 'DEF' ),
  3531. 'mock_capability: (1) two args ABC, DEF => capability [ ABC, DEF ]'
  3532. ) ;
  3533. is_deeply( [ 'ABC', 'DEF' ], [ $myimap->capability( ) ],
  3534. 'mock_capability: (2) two args ABC, DEF => capability capability [ ABC, DEF ]'
  3535. ) ;
  3536. ok( mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ),
  3537. 'mock_capability: (1) two args IMAP4rev1, APPENDLIMIT=123456 => capability [ IMAP4rev1, APPENDLIMIT=123456 ]'
  3538. ) ;
  3539. is_deeply( [ 'IMAP4rev1', 'APPENDLIMIT=123456' ], [ $myimap->capability( ) ],
  3540. 'mock_capability: (2) two args IMAP4rev1, APPENDLIMIT=123456 => capability capability [ IMAP4rev1, APPENDLIMIT=123456 ]'
  3541. ) ;
  3542. note( 'Leaving tests_mock_capability()' ) ;
  3543. return ;
  3544. }
  3545. sub sig_install_toggle_sleep
  3546. {
  3547. my $mysync = shift ;
  3548. if ( 'MSWin32' ne $OSNAME ) {
  3549. #myprint( "sig_install( $mysync, \&toggle_sleep, 'USR1' )\n" ) ;
  3550. sig_install( $mysync, 'toggle_sleep', 'USR1' ) ;
  3551. }
  3552. #myprint( "Leaving sig_install_toggle_sleep\n" ) ;
  3553. return ;
  3554. }
  3555. sub mock_capability
  3556. {
  3557. my $myimap = shift ;
  3558. my @has_capability_value = @ARG ;
  3559. my ( $has_capability_value ) = @has_capability_value ;
  3560. if ( ! $myimap )
  3561. {
  3562. require_ok( "Test::MockObject" ) ;
  3563. $myimap = Test::MockObject->new( ) ;
  3564. }
  3565. $myimap->mock(
  3566. 'capability',
  3567. sub { return wantarray ?
  3568. @has_capability_value
  3569. : $has_capability_value ;
  3570. }
  3571. ) ;
  3572. return $myimap ;
  3573. }
  3574. sub tests_capability_of
  3575. {
  3576. note( 'Entering tests_capability_of()' ) ;
  3577. is( undef, capability_of( ),
  3578. 'capability_of: no args => undef' ) ;
  3579. my $myimap ;
  3580. is( undef, capability_of( $myimap ),
  3581. 'capability_of: undef => undef' ) ;
  3582. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3583. is( undef, capability_of( $myimap, 'CACA' ),
  3584. 'capability_of: two args unknown capability => undef' ) ;
  3585. is( $NUMBER_123456, capability_of( $myimap, 'APPENDLIMIT' ),
  3586. 'capability_of: two args APPENDLIMIT 123456 => 123456 yeah!' ) ;
  3587. note( 'Leaving tests_capability_of()' ) ;
  3588. return ;
  3589. }
  3590. sub capability_of
  3591. {
  3592. my $imap = shift || return ;
  3593. my $capability_keyword = shift || return ;
  3594. my @capability = $imap->capability ;
  3595. if ( ! @capability ) { return ; }
  3596. my $capability_value = search_in_array( $capability_keyword, @capability ) ;
  3597. return $capability_value ;
  3598. }
  3599. sub tests_search_in_array
  3600. {
  3601. note( 'Entering tests_search_in_array()' ) ;
  3602. is( undef, search_in_array( 'KA' ),
  3603. 'search_in_array: no array => undef ' ) ;
  3604. is( 'VA', search_in_array( 'KA', ( 'KA=VA' ) ),
  3605. 'search_in_array: KA KA=VA => VA ' ) ;
  3606. is( 'VA', search_in_array( 'KA', ( 'KA=VA', 'KB=VB' ) ),
  3607. 'search_in_array: KA KA=VA KB=VB => VA ' ) ;
  3608. is( 'VB', search_in_array( 'KB', ( 'KA=VA', 'KB=VB' ) ),
  3609. 'search_in_array: KA=VA KB=VB => VB ' ) ;
  3610. note( 'Leaving tests_search_in_array()' ) ;
  3611. return ;
  3612. }
  3613. sub search_in_array
  3614. {
  3615. my ( $key, @array ) = @ARG ;
  3616. foreach my $item ( @array )
  3617. {
  3618. if ( $item =~ /([^=]+)=(.*)/ )
  3619. {
  3620. if ( $1 eq $key )
  3621. {
  3622. return $2 ;
  3623. }
  3624. }
  3625. }
  3626. return ;
  3627. }
  3628. sub tests_appendlimit_from_capability
  3629. {
  3630. note( 'Entering tests_appendlimit_from_capability()' ) ;
  3631. is( undef, appendlimit_from_capability( ),
  3632. 'appendlimit_from_capability: no args => undef'
  3633. ) ;
  3634. my $myimap ;
  3635. is( undef, appendlimit_from_capability( $myimap ),
  3636. 'appendlimit_from_capability: undef arg => undef'
  3637. ) ;
  3638. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3639. # Normal behavior
  3640. is( $NUMBER_123456, appendlimit_from_capability( $myimap ),
  3641. 'appendlimit_from_capability: APPENDLIMIT=123456 => 123456'
  3642. ) ;
  3643. # Not a number
  3644. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=ABC' ) ;
  3645. is( undef, appendlimit_from_capability( $myimap ),
  3646. 'appendlimit_from_capability: not a number => undef'
  3647. ) ;
  3648. note( 'Leaving tests_appendlimit_from_capability()' ) ;
  3649. return ;
  3650. }
  3651. sub appendlimit_from_capability
  3652. {
  3653. my $myimap = shift ;
  3654. if ( ! $myimap )
  3655. {
  3656. myprint( "Warn: no imap with call to appendlimit_from_capability\n" ) ;
  3657. return ;
  3658. }
  3659. #myprint( Data::Dumper->Dump( [ \$myimap ] ) ) ;
  3660. my $appendlimit = capability_of( $myimap, 'APPENDLIMIT' ) ;
  3661. #myprint( "has_capability APPENDLIMIT $appendlimit\n" ) ;
  3662. if ( is_integer( $appendlimit ) )
  3663. {
  3664. return $appendlimit ;
  3665. }
  3666. return ;
  3667. }
  3668. sub tests_appendlimit
  3669. {
  3670. note( 'Entering tests_appendlimit()' ) ;
  3671. is( undef, appendlimit( ),
  3672. 'appendlimit: no args => undef'
  3673. ) ;
  3674. my $mysync = { } ;
  3675. is( undef, appendlimit( $mysync ),
  3676. 'appendlimit: no imap2 => undef'
  3677. ) ;
  3678. my $myimap ;
  3679. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3680. $mysync->{ imap2 } = $myimap ;
  3681. is( 123456, appendlimit( $mysync ),
  3682. 'appendlimit: imap2 with APPENDLIMIT=123456 => 123456'
  3683. ) ;
  3684. note( 'Leaving tests_appendlimit()' ) ;
  3685. return ;
  3686. }
  3687. sub appendlimit
  3688. {
  3689. my $mysync = shift || return ;
  3690. my $myimap = $mysync->{ imap2 } ;
  3691. my $appendlimit = appendlimit_from_capability( $myimap ) ;
  3692. if ( defined $appendlimit )
  3693. {
  3694. myprint( "Host2: found APPENDLIMIT=$appendlimit in CAPABILITY (use --appendlimit xxxx to override this automatic setting)\n" ) ;
  3695. return $appendlimit ;
  3696. }
  3697. return ;
  3698. }
  3699. sub tests_maxsize_setting
  3700. {
  3701. note( 'Entering tests_maxsize_setting()' ) ;
  3702. is( undef, maxsize_setting( ),
  3703. 'maxsize_setting: no args => undef'
  3704. ) ;
  3705. my $mysync ;
  3706. is( undef, maxsize_setting( $mysync ),
  3707. 'maxsize_setting: undef arg => undef'
  3708. ) ;
  3709. $mysync = { } ;
  3710. $mysync->{ maxsize } = $NUMBER_123456 ;
  3711. # --maxsize alone
  3712. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3713. 'maxsize_setting: --maxsize 123456 alone => 123456'
  3714. ) ;
  3715. $mysync = { } ;
  3716. my $myimap ;
  3717. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=654321' ) ;
  3718. $mysync->{ imap2 } = $myimap ;
  3719. # APPENDLIMIT alone
  3720. is( $NUMBER_654321, maxsize_setting( $mysync ),
  3721. 'maxsize_setting: APPENDLIMIT 654321 alone => 654321'
  3722. ) ;
  3723. is( $NUMBER_654321, $mysync->{ maxsize },
  3724. 'maxsize_setting: APPENDLIMIT 654321 alone => maxsize 654321'
  3725. ) ;
  3726. # APPENDLIMIT with --appendlimit => --appendlimit wins
  3727. $mysync->{ appendlimit } = $NUMBER_123456 ;
  3728. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3729. 'maxsize_setting: APPENDLIMIT 654321 + --appendlimit 123456 => 123456'
  3730. ) ;
  3731. is( $NUMBER_123456, $mysync->{ maxsize },
  3732. 'maxsize_setting: APPENDLIMIT 654321 + --appendlimit 123456 => maxsize 123456'
  3733. ) ;
  3734. # Fresh
  3735. $mysync = { } ;
  3736. $mysync->{ imap2 } = $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=654321' ) ;
  3737. # Case: "APPENDLIMIT >= --maxsize" => maxsize.
  3738. $mysync->{ maxsize } = $NUMBER_123456 ;
  3739. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3740. 'maxsize_setting: APPENDLIMIT 654321 --maxsize 123456 => 123456'
  3741. ) ;
  3742. # Case: "APPENDLIMIT < --maxsize" => APPENDLIMIT.
  3743. # Fresh
  3744. $mysync = { } ;
  3745. $mysync->{ imap2 } = $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3746. $mysync->{ maxsize } = $NUMBER_654321 ;
  3747. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3748. 'maxsize_setting: APPENDLIMIT 123456 --maxsize 654321 => 123456 '
  3749. ) ;
  3750. # Now --truncmess stuff
  3751. note( 'Leaving tests_maxsize_setting()' ) ;
  3752. return ;
  3753. }
  3754. # Three variables to take account of
  3755. # appendlimit (given by --appendlimit or CAPABILITY...)
  3756. # maxsize
  3757. # truncmess
  3758. sub maxsize_setting
  3759. {
  3760. my $mysync = shift || return ;
  3761. if ( defined $mysync->{ appendlimit } )
  3762. {
  3763. myprint( "Host2: Getting appendlimit from --appendlimit $mysync->{ appendlimit }\n" ) ;
  3764. }
  3765. else
  3766. {
  3767. $mysync->{ appendlimit } = appendlimit( $mysync ) ;
  3768. }
  3769. if ( all_defined( $mysync->{ appendlimit }, $mysync->{ maxsize } ) )
  3770. {
  3771. my $min_maxsize_appendlimit = min( $mysync->{ maxsize }, $mysync->{ appendlimit } ) ;
  3772. myprint( "Host2: Setting maxsize to $min_maxsize_appendlimit (min of --maxsize $mysync->{ maxsize } and appendlimit $mysync->{ appendlimit }\n" ) ;
  3773. $mysync->{ maxsize } = $min_maxsize_appendlimit ;
  3774. return $mysync->{ maxsize } ;
  3775. }
  3776. elsif ( defined $mysync->{ appendlimit } )
  3777. {
  3778. myprint( "Host2: Setting maxsize to appendlimit $mysync->{ appendlimit }\n" ) ;
  3779. $mysync->{ maxsize } = $mysync->{ appendlimit } ;
  3780. return $mysync->{ maxsize } ;
  3781. }elsif ( defined $mysync->{ maxsize } )
  3782. {
  3783. return $mysync->{ maxsize } ;
  3784. }else
  3785. {
  3786. return ;
  3787. }
  3788. }
  3789. sub all_defined
  3790. {
  3791. if ( not @ARG ) {
  3792. return 0 ;
  3793. }
  3794. foreach my $elem ( @ARG ) {
  3795. if ( not defined $elem ) {
  3796. return 0 ;
  3797. }
  3798. }
  3799. return 1 ;
  3800. }
  3801. sub tests_all_defined
  3802. {
  3803. note( 'Entering tests_all_defined()' ) ;
  3804. is( 0, all_defined( ), 'all_defined: no param => 0' ) ;
  3805. is( 0, all_defined( () ), 'all_defined: void list => 0' ) ;
  3806. is( 0, all_defined( undef ), 'all_defined: undef => 0' ) ;
  3807. is( 0, all_defined( undef, undef ), 'all_defined: undef => 0' ) ;
  3808. is( 0, all_defined( 1, undef ), 'all_defined: 1 undef => 0' ) ;
  3809. is( 0, all_defined( undef, 1 ), 'all_defined: undef 1 => 0' ) ;
  3810. is( 1, all_defined( 1, 1 ), 'all_defined: 1 1 => 1' ) ;
  3811. is( 1, all_defined( (1, 1) ), 'all_defined: (1 1) => 1' ) ;
  3812. note( 'Leaving tests_all_defined()' ) ;
  3813. return ;
  3814. }
  3815. sub tests_hashsynclocal
  3816. {
  3817. note( 'Entering tests_hashsynclocal()' ) ;
  3818. my $mysync = {
  3819. host1 => q{},
  3820. user1 => q{},
  3821. password1 => q{},
  3822. host2 => q{},
  3823. user2 => q{},
  3824. password2 => q{},
  3825. } ;
  3826. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: no hashfile name' ) ;
  3827. $mysync->{ hashfile } = q{} ;
  3828. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: empty hashfile name' ) ;
  3829. $mysync->{ hashfile } = './noexist/rrr' ;
  3830. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: no exists hashfile dir' ) ;
  3831. SKIP: {
  3832. if ( 'MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) { skip( 'Tests only for non-root Unix', 1 ) ; }
  3833. $mysync->{ hashfile } = '/rrr' ;
  3834. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: permission denied' ) ;
  3835. }
  3836. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'hashsynclocal: mkpath W/tmp/tests/' ) ;
  3837. $mysync->{ hashfile } = 'W/tmp/tests/imapsync_hash' ;
  3838. ok( ! -e 'W/tmp/tests/imapsync_hash' || unlink 'W/tmp/tests/imapsync_hash', 'hashsynclocal: unlink W/tmp/tests/imapsync_hash' ) ;
  3839. ok( ! -e 'W/tmp/tests/imapsync_hash', 'hashsynclocal: verify there is no W/tmp/tests/imapsync_hash' ) ;
  3840. is( 'ecdeb4ede672794d173da4e08c52b8ee19b7d252', hashsynclocal( $mysync, 'mukksyhpmbixkxkpjlqivmlqsulpictj' ), 'hashsynclocal: creating/reading W/tmp/tests/imapsync_hash' ) ;
  3841. # A second time now
  3842. is( 'ecdeb4ede672794d173da4e08c52b8ee19b7d252', hashsynclocal( $mysync ), 'hashsynclocal: reading W/tmp/tests/imapsync_hash second time => same' ) ;
  3843. note( 'Leaving tests_hashsynclocal()' ) ;
  3844. return ;
  3845. }
  3846. sub hashsynclocal
  3847. {
  3848. my $mysync = shift ;
  3849. my $hashkey = shift ; # Optional, only there for tests
  3850. my $hashfile = $mysync->{ hashfile } ;
  3851. $hashfile = createhashfileifneeded( $hashfile, $hashkey ) ;
  3852. if ( ! $hashfile ) {
  3853. return ;
  3854. }
  3855. $hashkey = firstline( $hashfile ) ;
  3856. if ( ! $hashkey ) {
  3857. myprint( "No hashkey!\n" ) ;
  3858. return ;
  3859. }
  3860. my $hashsynclocal = hashsync( $mysync, $hashkey ) ;
  3861. return( $hashsynclocal ) ;
  3862. }
  3863. sub tests_hashsync
  3864. {
  3865. note( 'Entering tests_hashsync()' ) ;
  3866. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hashsync( ), 'hashsync: no args' ) ;
  3867. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hashsync( {}, q{} ), 'hashsync: empty args' ) ;
  3868. my $mysync ;
  3869. $mysync->{ host1 } = 'zzz' ;
  3870. is( 'e86a28a3611c1e7bbaf8057cd00ae122781a11fe', hashsync( $mysync, q{} ), 'hashsync: host1 zzz => ' ) ;
  3871. is( '6a7b451ac99eab1531ad8e6cd544b32420c552ac', hashsync( $mysync, q{A} ), 'hashsync: host1 zzz => ' ) ;
  3872. $mysync->{ host2 } = 'zzz' ;
  3873. is( '15959573e4a86763253a7aedb1a2b0c60d133dc2', hashsync( $mysync, q{} ), 'hashsync: + host2 zzz => ' ) ;
  3874. is( 'b8d4ab541b209c75928528020ca28ee43488bd8f', hashsync( $mysync, 'A' ), 'hashsync: + hashkey A => ' ) ;
  3875. $mysync = undef ;
  3876. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hashsync( $mysync, q{} ), 'hashsync: undef $mysync' ) ;
  3877. $mysync->{ password1 } = 'abcd' ;
  3878. is( 'afa29ab8534495251ac8346a985717c54bc49c26', hashsync( $mysync, q{} ), 'hashsync: password1: abcd' ) ;
  3879. # A user reported a massive failure on /X (Thomas V. 21/04/2020 Ã 21:41 Subject: Error)
  3880. # "Wide character in subroutine entry at /usr/local/lib/perl5/site_perl/Digest/HMAC.pm"
  3881. # I can reproduce it now
  3882. # The eval is there to avoid a complete crash
  3883. # this one is fatal so it is commented
  3884. # is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', 1 / 0 , 'hashsync: 1 / 0 fatal' ) ;
  3885. my $eval ;
  3886. # this one is not fatal
  3887. is( undef, $eval = eval { 1 / 0 } , 'hashsync: 1/0 not fatal' ) ;
  3888. # this one neither
  3889. $mysync->{ password1 } = 'Ö' ;
  3890. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', $eval = eval { hashsync( $mysync, q{} ) } , 'hashsync: password1: Ö with eval' ) ;
  3891. $mysync->{ password1 } = 'Ö' ;
  3892. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hashsync( $mysync, q{} ), 'hashsync: password1: Ö without eval' ) ;
  3893. $mysync->{ password1 } = qq{\x{00D6}} ;
  3894. is( 'bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a', $eval = eval { hashsync( $mysync, q{} ) }, 'hashsync: password1: \x{00D6}' ) ; #
  3895. print qq{1 00D6:Ö\n} ;
  3896. print encode_utf8( qq{2 00D6:Ö\n} ) ;
  3897. print qq{3 00D6:\x{00D6}\n} ;
  3898. print encode_utf8( qq{4 00D6:\x{00D6}\n} ) ;
  3899. print qq{5 6536:æ”¶\n} ;
  3900. print encode_utf8( qq{6 6536:æ”¶\n} ) ;
  3901. # the next one prints "Wide character in print at ./imapsync line xxxx"
  3902. print qq{7 6536:\x{6536}\n} ;
  3903. print encode_utf8( qq{8 6536:\x{6536}\n} ) ;
  3904. $mysync->{ password1 } = qq{æ”¶} ;
  3905. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hashsync( $mysync, q{} ), 'hashsync: password1: æ”¶' ) ;
  3906. $mysync->{ password1 } = qq{\x{6536}} ;
  3907. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', $eval = eval{ hashsync( $mysync, q{} ) }, 'hashsync: password1: \x{6536} with eval' ) ;
  3908. # No side effect.
  3909. $mysync->{ password1 } = 'abcd' ;
  3910. is( 'afa29ab8534495251ac8346a985717c54bc49c26', hashsync( $mysync, q{} ), 'hashsync: password1: abcd again' ) ;
  3911. note( 'Leaving tests_hashsync()' ) ;
  3912. return ;
  3913. }
  3914. sub hashsync
  3915. {
  3916. my $mysync = shift ;
  3917. my $hashkey = shift ;
  3918. my $mystring = join( q{},
  3919. $mysync->{ host1 } || q{},
  3920. $mysync->{ user1 } || q{},
  3921. $mysync->{ password1 } || q{},
  3922. $mysync->{ host2 } || q{},
  3923. $mysync->{ user2 } || q{},
  3924. $mysync->{ password2 } || q{},
  3925. ) ;
  3926. #my $hashsync = hmac_sha1_hex( $mystring, $hashkey ) ;
  3927. my $hashsync = hmac_sha1_hex_robust( $mystring, $hashkey ) ;
  3928. #myprint( "$hashsync\n" ) ;
  3929. return( $hashsync ) ;
  3930. }
  3931. sub tests_hmac_sha1_hex
  3932. {
  3933. note( 'Entering tests_hmac_sha1_hex()' ) ;
  3934. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex( ), 'hmac_sha1_hex: no args => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  3935. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex( '' ), 'hmac_sha1_hex: empty string => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  3936. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex( '', '' ), 'hmac_sha1_hex: empty strings => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  3937. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex( '', '', 'caca' ), 'hmac_sha1_hex: empty strings + caca => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  3938. # Good
  3939. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hmac_sha1_hex( 'Ö' ), 'hmac_sha1_hex: Ö => f1a3f3dac3f137fd658027c11678b895f773ce55' ) ;
  3940. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hmac_sha1_hex( encode_utf8(qq{\x{00D6}}) ), 'hmac_sha1_hex: encode_utf8 \x{00D6} => f1a3f3dac3f137fd658027c11678b895f773ce55' ) ;
  3941. # Bad
  3942. is( 'fe8dc3b9ba3e8850bb4a7b070b2279e911003af2', hmac_sha1_hex( encode_utf8( 'Ö' ) ), 'hmac_sha1_hex: encode_utf8 Ö => fe8dc3b9ba3e8850bb4a7b070b2279e911003af2' ) ;
  3943. is( 'bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a', hmac_sha1_hex( qq{\x{00D6}} ), 'hmac_sha1_hex: qq{\x{00D6}} => bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a' ) ;
  3944. # Good
  3945. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex( 'A' ), 'hmac_sha1_hex: A => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  3946. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex( encode_utf8(qq{\x{0041}}) ), 'hmac_sha1_hex: encode_utf8 \x{0041} => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  3947. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex( encode_utf8( 'A' ) ), 'hmac_sha1_hex: encode_utf8 A => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  3948. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex( qq{\x{0041}} ), 'hmac_sha1_hex: \x{0041} => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  3949. # Good
  3950. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex( 'A', 'B' ), 'hmac_sha1_hex: A B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  3951. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex( encode_utf8(qq{\x{0041}}), 'B' ), 'hmac_sha1_hex: encode_utf8 \x{0041} B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  3952. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex( encode_utf8( 'A' ), 'B' ), 'hmac_sha1_hex: encode_utf8 A B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  3953. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex( qq{\x{0041}}, 'B' ), 'hmac_sha1_hex: \x{0041} B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  3954. # http://unicode.scarfboy.com/?s=U%2B6536
  3955. # Good
  3956. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex( 'æ”¶' ), 'hmac_sha1_hex: æ”¶ => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  3957. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex( encode_utf8(qq{\x{6536}}) ), 'hmac_sha1_hex: encode_utf8 \x{6536} => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  3958. # Bad
  3959. is( 'e82217119628ad03e659cc89671d05ea4cee7238', hmac_sha1_hex( encode_utf8( 'æ”¶' ) ), 'hmac_sha1_hex: encode_utf8 æ”¶ => e82217119628ad03e659cc89671d05ea4cee7238' ) ;
  3960. # Very very bad, perl dies...
  3961. #is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex( qq{\x{6536}} ), 'hmac_sha1_hex: \x{6536} => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  3962. # Ok but well, bad indeed
  3963. is( undef, my $eval = eval{ hmac_sha1_hex( qq{\x{6536}} ) }, 'hmac_sha1_hex: \x{6536} => undef' ) ;
  3964. note( 'Leaving tests_hmac_sha1_hex()' ) ;
  3965. return ;
  3966. }
  3967. sub tests_hmac_sha1_hex_robust
  3968. {
  3969. note( 'Entering tests_hmac_sha1_hex_robust()' ) ;
  3970. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex_robust( ), 'hmac_sha1_hex_robust: no args => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  3971. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex_robust( '' ), 'hmac_sha1_hex_robust: empty string => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  3972. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex_robust( '', '' ), 'hmac_sha1_hex_robust: empty strings => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  3973. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex_robust( '', '', 'caca' ), 'hmac_sha1_hex_robust: empty strings + caca => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  3974. # Good
  3975. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hmac_sha1_hex_robust( 'Ö' ), 'hmac_sha1_hex_robust: Ö => f1a3f3dac3f137fd658027c11678b895f773ce55' ) ;
  3976. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hmac_sha1_hex_robust( encode_utf8(qq{\x{00D6}}) ), 'hmac_sha1_hex_robust: encode_utf8 \x{00D6} => f1a3f3dac3f137fd658027c11678b895f773ce55' ) ;
  3977. # Bad
  3978. is( 'fe8dc3b9ba3e8850bb4a7b070b2279e911003af2', hmac_sha1_hex_robust( encode_utf8( 'Ö' ) ), 'hmac_sha1_hex_robust: encode_utf8 Ö => fe8dc3b9ba3e8850bb4a7b070b2279e911003af2' ) ;
  3979. is( 'bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a', hmac_sha1_hex_robust( qq{\x{00D6}} ), 'hmac_sha1_hex_robust: qq{\x{00D6}} => bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a' ) ;
  3980. # Good
  3981. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex_robust( 'A' ), 'hmac_sha1_hex_robust: A => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  3982. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex_robust( encode_utf8(qq{\x{0041}}) ), 'hmac_sha1_hex_robust: encode_utf8 \x{0041} => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  3983. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex_robust( encode_utf8( 'A' ) ), 'hmac_sha1_hex_robust: encode_utf8 A => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  3984. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex_robust( qq{\x{0041}} ), 'hmac_sha1_hex_robust: \x{0041} => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  3985. # Good
  3986. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex_robust( 'A', 'B' ), 'hmac_sha1_hex_robust: A B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  3987. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex_robust( encode_utf8(qq{\x{0041}}), 'B' ), 'hmac_sha1_hex_robust: encode_utf8 \x{0041} B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  3988. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex_robust( encode_utf8( 'A' ), 'B' ), 'hmac_sha1_hex_robust: encode_utf8 A B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  3989. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex_robust( qq{\x{0041}}, 'B' ), 'hmac_sha1_hex_robust: \x{0041} B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  3990. # http://unicode.scarfboy.com/?s=U%2B6536
  3991. # Good
  3992. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex_robust( 'æ”¶' ), 'hmac_sha1_hex_robust: æ”¶ => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  3993. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex_robust( encode_utf8(qq{\x{6536}}) ), 'hmac_sha1_hex_robust: encode_utf8 \x{6536} => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  3994. # Bad
  3995. is( 'e82217119628ad03e659cc89671d05ea4cee7238', hmac_sha1_hex_robust( encode_utf8( 'æ”¶' ) ), 'hmac_sha1_hex_robust: encode_utf8 æ”¶ => e82217119628ad03e659cc89671d05ea4cee7238' ) ;
  3996. # Good
  3997. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex_robust( qq{\x{6536}} ), 'hmac_sha1_hex_robust: \x{6536} => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  3998. # Good again
  3999. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', my $eval = eval{ hmac_sha1_hex_robust( qq{\x{6536}} ) }, 'hmac_sha1_hex_robust: \x{6536} => undef' ) ;
  4000. note( 'Leaving tests_hmac_sha1_hex_robust()' ) ;
  4001. return ;
  4002. }
  4003. sub hmac_sha1_hex_robust
  4004. {
  4005. my $string = shift ;
  4006. my $val ;
  4007. if ( defined( $val = eval{ hmac_sha1_hex( $string, @ARG ) } ) )
  4008. {
  4009. return $val ;
  4010. }
  4011. elsif( defined( $val = eval{ hmac_sha1_hex( encode_utf8( $string ), @ARG ) } ) )
  4012. {
  4013. return $val ;
  4014. }
  4015. else
  4016. {
  4017. return ;
  4018. }
  4019. }
  4020. sub tests_createhashfileifneeded
  4021. {
  4022. note( 'Entering tests_createhashfileifneeded()' ) ;
  4023. is( undef, createhashfileifneeded( ), 'createhashfileifneeded: no parameters => undef' ) ;
  4024. note( 'Leaving tests_createhashfileifneeded()' ) ;
  4025. return ;
  4026. }
  4027. sub createhashfileifneeded
  4028. {
  4029. my $hashfile = shift ;
  4030. my $hashkey = shift || rand32( ) ;
  4031. # no name
  4032. if ( ! $hashfile ) {
  4033. return ;
  4034. }
  4035. # already there
  4036. if ( -e -r $hashfile ) {
  4037. return $hashfile ;
  4038. }
  4039. # not creatable
  4040. if ( ! -w dirname( $hashfile ) ) {
  4041. return ;
  4042. }
  4043. # creatable
  4044. open my $FILE_HANDLE, '>', $hashfile
  4045. or do {
  4046. myprint( "Could not open $hashfile for writing. Check permissions or disk space." ) ;
  4047. return ;
  4048. } ;
  4049. myprint( "Writing random hashkey in $hashfile, once for all times\n" ) ;
  4050. print $FILE_HANDLE $hashkey ;
  4051. close $FILE_HANDLE ;
  4052. # Should be there now
  4053. if ( -e -r $hashfile ) {
  4054. return $hashfile ;
  4055. }
  4056. # unknown failure
  4057. return ;
  4058. }
  4059. sub tests_rand32
  4060. {
  4061. note( 'Entering tests_rand32()' ) ;
  4062. my $string = rand32( ) ;
  4063. myprint( "$string\n" ) ;
  4064. is( 32, length( $string ), 'rand32: 32 characters long' ) ;
  4065. is( 32, length( rand32( ) ), 'rand32: 32 characters long, another one' ) ;
  4066. note( 'Leaving tests_rand32()' ) ;
  4067. return ;
  4068. }
  4069. sub rand32
  4070. {
  4071. my @chars = ( "a".."z" ) ;
  4072. my $string;
  4073. $string .= $chars[rand @chars] for 1..32 ;
  4074. return $string ;
  4075. }
  4076. sub imap_id_stuff
  4077. {
  4078. my $mysync = shift ;
  4079. if ( not $mysync->{id} ) { return ; } ;
  4080. $mysync->{h1_imap_id} = imap_id( $mysync, $mysync->{imap1}, 'Host1' ) ;
  4081. #myprint( 'Host1: ' . $mysync->{h1_imap_id} ) ;
  4082. $mysync->{h2_imap_id} = imap_id( $mysync, $mysync->{imap2}, 'Host2' ) ;
  4083. #myprint( 'Host2: ' . $mysync->{h2_imap_id} ) ;
  4084. return ;
  4085. }
  4086. sub imap_id
  4087. {
  4088. my ( $mysync, $imap, $Side ) = @_ ;
  4089. if ( not $mysync->{id} ) { return q{} ; } ;
  4090. $Side ||= q{} ;
  4091. my $imap_id_response = q{} ;
  4092. if ( not $imap->has_capability( 'ID' ) ) {
  4093. $imap_id_response = 'No ID capability' ;
  4094. myprint( "$Side: No ID capability\n" ) ;
  4095. }else{
  4096. my $id_inp = imapsync_id( $mysync, { side => lc $Side } ) ;
  4097. myprint( "\n$Side: found ID capability. Sending/receiving ID, presented in raw IMAP for now.\n"
  4098. . "In order to avoid sending/receiving ID, use option --noid\n" ) ;
  4099. my $debug_before = $imap->Debug( ) ;
  4100. $imap->Debug( 1 ) ;
  4101. my $id_out = $imap->tag_and_run( 'ID ' . $id_inp ) ;
  4102. #my $id_out = $imap->tag_and_run( 'ID NIL' ) ;
  4103. myprint( "\n" ) ;
  4104. $imap->Debug( $debug_before ) ;
  4105. #$imap_id_response = Data::Dumper->Dump( [ $id_out ], [ 'IMAP_ID' ] ) ;
  4106. }
  4107. return( $imap_id_response ) ;
  4108. }
  4109. sub imapsync_id
  4110. {
  4111. my $mysync = shift ;
  4112. my $overhashref = shift ;
  4113. # See http://tools.ietf.org/html/rfc2971.html
  4114. my $imapsync_id = { } ;
  4115. my $imapsync_id_lamiral = {
  4116. name => 'imapsync',
  4117. version => imapsync_version( $mysync ),
  4118. os => $OSNAME,
  4119. vendor => 'Gilles LAMIRAL',
  4120. 'support-url' => 'https://imapsync.lamiral.info/',
  4121. # Example of date-time: 19-Sep-2015 08:56:07
  4122. date => date_from_rcs( q{$Date: 2021/07/22 14:21:09 $ } ),
  4123. } ;
  4124. my $imapsync_id_github = {
  4125. name => 'imapsync',
  4126. version => imapsync_version( $mysync ),
  4127. os => $OSNAME,
  4128. vendor => 'github',
  4129. 'support-url' => 'https://github.com/imapsync/imapsync',
  4130. date => date_from_rcs( q{$Date: 2021/07/22 14:21:09 $ } ),
  4131. } ;
  4132. $imapsync_id = $imapsync_id_lamiral ;
  4133. #$imapsync_id = $imapsync_id_github ;
  4134. my %mix = ( %{ $imapsync_id }, %{ $overhashref } ) ;
  4135. my $imapsync_id_str = format_for_imap_arg( \%mix ) ;
  4136. #myprint( "$imapsync_id_str\n" ) ;
  4137. return( $imapsync_id_str ) ;
  4138. }
  4139. sub tests_imapsync_id
  4140. {
  4141. note( 'Entering tests_imapsync_id()' ) ;
  4142. my $mysync ;
  4143. ok( '("name" "imapsync" "version" "111" "os" "beurk" "vendor" "Gilles LAMIRAL" "support-url" "https://imapsync.lamiral.info/" "date" "22-12-1968" "side" "host1")'
  4144. eq imapsync_id( $mysync,
  4145. {
  4146. version => 111,
  4147. os => 'beurk',
  4148. date => '22-12-1968',
  4149. side => 'host1'
  4150. }
  4151. ),
  4152. 'tests_imapsync_id override'
  4153. ) ;
  4154. note( 'Leaving tests_imapsync_id()' ) ;
  4155. return ;
  4156. }
  4157. sub format_for_imap_arg
  4158. {
  4159. my $ref = shift ;
  4160. my $string = q{} ;
  4161. my %terms = %{ $ref } ;
  4162. my @terms = ( ) ;
  4163. if ( not ( %terms ) ) { return( 'NIL' ) } ;
  4164. # sort like in RFC then add extra key/values
  4165. foreach my $key ( qw( name version os os-version vendor support-url address date command arguments environment) ) {
  4166. if ( $terms{ $key } ) {
  4167. push @terms, $key, $terms{ $key } ;
  4168. delete $terms{ $key } ;
  4169. }
  4170. }
  4171. push @terms, %terms ;
  4172. $string = '(' . ( join q{ }, map { '"' . $_ . '"' } @terms ) . ')' ;
  4173. return( $string ) ;
  4174. }
  4175. sub tests_format_for_imap_arg
  4176. {
  4177. note( 'Entering tests_format_for_imap_arg()' ) ;
  4178. ok( 'NIL' eq format_for_imap_arg( { } ), 'format_for_imap_arg empty hash ref' ) ;
  4179. ok( '("name" "toto")' eq format_for_imap_arg( { name => 'toto' } ), 'format_for_imap_arg { name => toto }' ) ;
  4180. ok( '("name" "toto" "key" "val")' eq format_for_imap_arg( { name => 'toto', key => 'val' } ), 'format_for_imap_arg 2 x key val' ) ;
  4181. note( 'Leaving tests_format_for_imap_arg()' ) ;
  4182. return ;
  4183. }
  4184. sub quota
  4185. {
  4186. my ( $mysync, $imap, $side ) = @_ ;
  4187. my %side = (
  4188. h1 => 'Host1',
  4189. h2 => 'Host2',
  4190. ) ;
  4191. my $Side = $side{ $side } ;
  4192. my $debug_before = $imap->Debug( ) ;
  4193. $imap->Debug( 1 ) ;
  4194. if ( not $imap->has_capability( 'QUOTA' ) ) {
  4195. $imap->Debug( $debug_before ) ;
  4196. return ;
  4197. } ;
  4198. myprint( "\n$Side: found quota, presented in raw IMAP\n" ) ;
  4199. my $getquotaroot = $imap->getquotaroot( 'INBOX' ) ;
  4200. # Gmail INBOX quotaroot is "" but with it Mail::IMAPClient does a literal GETQUOTA {2} \n ""
  4201. #$imap->quota( 'ROOT' ) ;
  4202. #$imap->quota( '""' ) ;
  4203. myprint( "\n" ) ;
  4204. $imap->Debug( $debug_before ) ;
  4205. my $quota_limit_bytes = quota_extract_storage_limit_in_bytes( $mysync, $getquotaroot ) ;
  4206. my $quota_current_bytes = quota_extract_storage_current_in_bytes( $mysync, $getquotaroot ) ;
  4207. $mysync->{$side}->{quota_limit_bytes} = $quota_limit_bytes ;
  4208. $mysync->{$side}->{quota_current_bytes} = $quota_current_bytes ;
  4209. my $quota_percent ;
  4210. if ( $quota_limit_bytes > 0 ) {
  4211. $quota_percent = mysprintf( '%.2f', $NUMBER_100 * $quota_current_bytes / $quota_limit_bytes ) ;
  4212. }else{
  4213. $quota_percent = 0 ;
  4214. }
  4215. myprint( "$Side: Quota current storage is $quota_current_bytes bytes. Limit is $quota_limit_bytes bytes. So $quota_percent % full\n" ) ;
  4216. if ( $QUOTA_PERCENT_LIMIT < $quota_percent ) {
  4217. my $error = "$Side: $quota_percent % full: it is time to find a bigger place! ( $quota_current_bytes bytes / $quota_limit_bytes bytes )\n" ;
  4218. errors_incr( $mysync, $error ) ;
  4219. }
  4220. return ;
  4221. }
  4222. sub tests_quota_extract_storage_limit_in_bytes
  4223. {
  4224. note( 'Entering tests_quota_extract_storage_limit_in_bytes()' ) ;
  4225. my $mysync = {} ;
  4226. my $imap_output = [
  4227. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  4228. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  4229. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  4230. '5 OK Getquotaroot completed.'
  4231. ] ;
  4232. ok( $NUMBER_104_857_600 * $KIBI == quota_extract_storage_limit_in_bytes( $mysync, $imap_output ), 'quota_extract_storage_limit_in_bytes ') ;
  4233. note( 'Leaving tests_quota_extract_storage_limit_in_bytes()' ) ;
  4234. return ;
  4235. }
  4236. sub quota_extract_storage_limit_in_bytes
  4237. {
  4238. my $mysync = shift ;
  4239. my $imap_output = shift ;
  4240. my $limit_kb ;
  4241. $limit_kb = ( map { /.*\(\s*STORAGE\s+\d+\s+(\d+)\s*\)/x ? $1 : () } @{ $imap_output } )[0] ;
  4242. $limit_kb ||= 0 ;
  4243. $mysync->{ debug } and myprint( "storage_limit_kb = $limit_kb\n" ) ;
  4244. return( $KIBI * $limit_kb ) ;
  4245. }
  4246. sub tests_quota_extract_storage_current_in_bytes
  4247. {
  4248. note( 'Entering tests_quota_extract_storage_current_in_bytes()' ) ;
  4249. my $mysync = {} ;
  4250. my $imap_output = [
  4251. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  4252. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  4253. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  4254. '5 OK Getquotaroot completed.'
  4255. ] ;
  4256. ok( 1*$KIBI == quota_extract_storage_current_in_bytes( $mysync, $imap_output ), 'quota_extract_storage_current_in_bytes: 1 => 1024 ') ;
  4257. note( 'Leaving tests_quota_extract_storage_current_in_bytes()' ) ;
  4258. return ;
  4259. }
  4260. sub quota_extract_storage_current_in_bytes
  4261. {
  4262. my $mysync = shift ;
  4263. my $imap_output = shift ;
  4264. my $current_kb ;
  4265. $current_kb = ( map { /.*\(\s*STORAGE\s+(\d+)\s+\d+\s*\)/x ? $1 : () } @{ $imap_output } )[0] ;
  4266. $current_kb ||= 0 ;
  4267. $mysync->{ debug } and myprint( "storage_current_kb = $current_kb\n" ) ;
  4268. return( $KIBI * $current_kb ) ;
  4269. }
  4270. sub automap
  4271. {
  4272. my ( $mysync ) = @_ ;
  4273. if ( $mysync->{automap} ) {
  4274. myprint( "Turned on automapping folders ( use --noautomap to turn off automapping )\n" ) ;
  4275. }else{
  4276. myprint( "Turned off automapping folders ( use --automap to turn on automapping )\n" ) ;
  4277. return ;
  4278. }
  4279. $mysync->{h1_special} = special_from_folders_hash( $mysync, $mysync->{imap1}, 'Host1' ) ;
  4280. $mysync->{h2_special} = special_from_folders_hash( $mysync, $mysync->{imap2}, 'Host2' ) ;
  4281. build_possible_special( $mysync ) ;
  4282. build_guess_special( $mysync ) ;
  4283. build_automap( $mysync ) ;
  4284. return ;
  4285. }
  4286. sub build_guess_special
  4287. {
  4288. my ( $mysync ) = shift ;
  4289. foreach my $h1_fold ( sort keys %{ $mysync->{h1_folders_all} } ) {
  4290. my $special = guess_special( $h1_fold, $mysync->{possible_special}, $mysync->{h1_prefix} ) ;
  4291. if ( $special ) {
  4292. $mysync->{h1_special_guessed}{$h1_fold} = $special ;
  4293. my $already_guessed = $mysync->{h1_special_guessed}{$special} ;
  4294. if ( $already_guessed ) {
  4295. myprint( "Host1: $h1_fold not $special because set to $already_guessed\n" ) ;
  4296. }else{
  4297. $mysync->{h1_special_guessed}{$special} = $h1_fold ;
  4298. }
  4299. }
  4300. }
  4301. foreach my $h2_fold ( sort keys %{ $mysync->{h2_folders_all} } ) {
  4302. my $special = guess_special( $h2_fold, $mysync->{possible_special}, $mysync->{h2_prefix} ) ;
  4303. if ( $special ) {
  4304. $mysync->{h2_special_guessed}{$h2_fold} = $special ;
  4305. my $already_guessed = $mysync->{h2_special_guessed}{$special} ;
  4306. if ( $already_guessed ) {
  4307. myprint( "Host2: $h2_fold not $special because set to $already_guessed\n" ) ;
  4308. }else{
  4309. $mysync->{h2_special_guessed}{$special} = $h2_fold ;
  4310. }
  4311. }
  4312. }
  4313. return ;
  4314. }
  4315. sub guess_special
  4316. {
  4317. my( $folder, $possible_special_ref, $prefix ) = @_ ;
  4318. my $folder_no_prefix = $folder ;
  4319. $folder_no_prefix =~ s/\Q${prefix}\E//xms ;
  4320. #$debug and myprint( "folder_no_prefix: $folder_no_prefix\n" ) ;
  4321. my $guess_special = $possible_special_ref->{ $folder }
  4322. || $possible_special_ref->{ $folder_no_prefix }
  4323. || q{} ;
  4324. return( $guess_special ) ;
  4325. }
  4326. sub tests_guess_special
  4327. {
  4328. note( 'Entering tests_guess_special()' ) ;
  4329. my $possible_special_ref = build_possible_special( my $mysync ) ;
  4330. ok( '\Sent' eq guess_special( 'Sent', $possible_special_ref, q{} ) ,'guess_special: Sent => \Sent' ) ;
  4331. ok( q{} eq guess_special( 'Blabla', $possible_special_ref, q{} ) ,'guess_special: Blabla => q{}' ) ;
  4332. ok( '\Sent' eq guess_special( 'INBOX.Sent', $possible_special_ref, 'INBOX.' ) ,'guess_special: INBOX.Sent => \Sent' ) ;
  4333. ok( '\Sent' eq guess_special( 'IN BOX.Sent', $possible_special_ref, 'IN BOX.' ) ,'guess_special: IN BOX.Sent => \Sent' ) ;
  4334. note( 'Leaving tests_guess_special()' ) ;
  4335. return ;
  4336. }
  4337. sub build_automap
  4338. {
  4339. my $mysync = shift ;
  4340. $mysync->{ debug } and myprint( "Entering build_automap\n" ) ;
  4341. foreach my $h1_fold ( @{ $mysync->{h1_folders_wanted} } ) {
  4342. my $h2_fold ;
  4343. my $h1_special = $mysync->{h1_special}{$h1_fold} ;
  4344. my $h1_special_guessed = $mysync->{h1_special_guessed}{$h1_fold} ;
  4345. # Case 1: special on both sides.
  4346. if ( $h1_special
  4347. and exists $mysync->{h2_special}{$h1_special} ) {
  4348. $h2_fold = $mysync->{h2_special}{$h1_special} ;
  4349. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  4350. next ;
  4351. }
  4352. # Case 2: special on host1, not on host2
  4353. if ( $h1_special
  4354. and ( not exists $mysync->{h2_special}{$h1_special} )
  4355. and ( exists $mysync->{h2_special_guessed}{$h1_special} )
  4356. ) {
  4357. # special_guessed on host2
  4358. $h2_fold = $mysync->{h2_special_guessed}{$h1_special} ;
  4359. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  4360. next ;
  4361. }
  4362. # Case 3: no special on host1, special on host2
  4363. if ( ( not $h1_special )
  4364. and ( $h1_special_guessed )
  4365. and ( exists $mysync->{h2_special}{$h1_special_guessed} )
  4366. ) {
  4367. $h2_fold = $mysync->{h2_special}{$h1_special_guessed} ;
  4368. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  4369. next ;
  4370. }
  4371. # Case 4: no special on both sides.
  4372. if ( ( not $h1_special )
  4373. and ( $h1_special_guessed )
  4374. and ( not exists $mysync->{h2_special}{$h1_special_guessed} )
  4375. and ( exists $mysync->{h2_special_guessed}{$h1_special_guessed} )
  4376. ) {
  4377. $h2_fold = $mysync->{h2_special_guessed}{$h1_special_guessed} ;
  4378. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  4379. next ;
  4380. }
  4381. }
  4382. return( $mysync->{f1f2auto} ) ;
  4383. }
  4384. # I will not add what there is at:
  4385. # http://stackoverflow.com/questions/2185391/localized-gmail-imap-folders/2185548#2185548
  4386. # because it works well without
  4387. sub build_possible_special
  4388. {
  4389. my $mysync = shift ;
  4390. my $possible_special = { } ;
  4391. # All|Archive|Drafts|Flagged|Junk|Sent|Trash
  4392. $possible_special->{'\All'} = [ 'All', 'All Messages', '&BBIEQQQ1-' ] ;
  4393. $possible_special->{'\Archive'} = [ 'Archive', 'Archives', '&BBAEQARFBDgEMg-' ] ;
  4394. $possible_special->{'\Drafts'} = [ 'Drafts', 'DRAFTS', '&BCcENQRABD0EPgQyBDgEOgQ4-', 'Szkice', 'Wersje robocze' ] ;
  4395. $possible_special->{'\Flagged'} = [ 'Flagged', 'Starred', '&BB8EPgQ8BDUERwQ1BD0EPQRLBDU-' ] ;
  4396. $possible_special->{'\Junk'} = [ 'Junk', 'junk', 'Spam', 'SPAM', '&BCEEPwQwBDw-',
  4397. 'Potwierdzony spam', 'Wiadomo&AVs-ci-&AVs-mieci',
  4398. 'Junk E-Mail', 'Junk Email'] ;
  4399. $possible_special->{'\Sent'} = [ 'Sent', 'Sent Messages', 'Sent Items',
  4400. 'Gesendete Elemente', 'Gesendete Objekte',
  4401. '&AMk-l&AOk-ments envoy&AOk-s', 'Envoy&AOk-', 'Objets envoy&AOk-s',
  4402. 'Elementos enviados',
  4403. '&kAFP4W4IMH8wojCkMMYw4A-',
  4404. '&BB4EQgQ,BEAEMAQyBDsENQQ9BD0ESwQ1-',
  4405. 'Elementy wys&AUI-ane'] ;
  4406. $possible_special->{'\Trash'} = [ 'Trash', 'TRASH',
  4407. '&BCMENAQwBDsENQQ9BD0ESwQ1-', '&BBoEPgRABDcEOAQ9BDA-',
  4408. 'Kosz',
  4409. 'Deleted Items', 'Deleted Messages' ] ;
  4410. foreach my $special ( qw( \All \Archive \Drafts \Flagged \Junk \Sent \Trash ) ){
  4411. foreach my $possible_folder ( @{ $possible_special->{$special} } ) {
  4412. $possible_special->{ $possible_folder } = $special ;
  4413. } ;
  4414. }
  4415. $mysync->{possible_special} = $possible_special ;
  4416. $mysync->{ debug } and myprint( Data::Dumper->Dump( [ $possible_special ], [ 'possible_special' ] ) ) ;
  4417. return( $possible_special ) ;
  4418. }
  4419. sub tests_special_from_folders_hash
  4420. {
  4421. note( 'Entering tests_special_from_folders_hash()' ) ;
  4422. my $mysync = {} ;
  4423. require_ok( "Test::MockObject" ) ;
  4424. my $imapT = Test::MockObject->new( ) ;
  4425. is( undef, special_from_folders_hash( ), 'special_from_folders_hash: no args' ) ;
  4426. is( undef, special_from_folders_hash( $mysync ), 'special_from_folders_hash: undef args' ) ;
  4427. is_deeply( {}, special_from_folders_hash( $mysync, $imapT ), 'special_from_folders_hash: $imap void' ) ;
  4428. $imapT->mock( 'folders_hash', sub { return( [ { name => 'Sent', attrs => [ '\Sent' ] } ] ) } ) ;
  4429. is_deeply( { Sent => '\Sent', '\Sent' => 'Sent' },
  4430. special_from_folders_hash( $mysync, $imapT ), 'special_from_folders_hash: $imap \Sent' ) ;
  4431. note( 'Leaving tests_special_from_folders_hash()' ) ;
  4432. return( ) ;
  4433. }
  4434. sub special_from_folders_hash
  4435. {
  4436. my ( $mysync, $imap, $side ) = @_ ;
  4437. my %special = ( ) ;
  4438. if ( ! defined $imap ) { return ; }
  4439. $side = defined $side ? $side : 'Host?' ;
  4440. if ( ! $imap->can( 'folders_hash' ) ) {
  4441. my $error = "$side: To have automagic rfc6154 folder mapping, upgrade Mail::IMAPClient >= 3.34\n" ;
  4442. errors_incr( $mysync, $error ) ;
  4443. return( \%special ) ; # empty hash ref
  4444. }
  4445. my $folders_hash = $imap->folders_hash( ) ;
  4446. foreach my $fhash (@{ $folders_hash } ) {
  4447. my @special = grep { /\\(?:All|Archive|Drafts|Flagged|Junk|Sent|Trash)/x } @{ $fhash->{attrs} } ;
  4448. if ( @special ) {
  4449. my $special = $special[0] ; # keep first one. Could be not very good.
  4450. if ( exists $special{ $special } ) {
  4451. myprintf( "%s: special %-20s = %s already assigned to %s\n",
  4452. $side, $fhash->{name}, join( q{ }, @special ), $special{ $special } ) ;
  4453. }else{
  4454. myprintf( "%s: special %-20s = %s\n",
  4455. $side, $fhash->{name}, join( q{ }, @special ) ) ;
  4456. $special{ $special } = $fhash->{name} ;
  4457. $special{ $fhash->{name} } = $special ; # double entry value => key
  4458. }
  4459. }
  4460. }
  4461. myprint( "\n" ) if ( %special ) ;
  4462. return( \%special ) ;
  4463. }
  4464. sub errors_incr
  4465. {
  4466. my ( $mysync, @error ) = @ARG ;
  4467. $mysync->{nb_errors}++ ;
  4468. if ( @error ) {
  4469. errors_log( $mysync, @error ) ;
  4470. myprint( @error ) ;
  4471. }
  4472. $mysync->{errorsmax} ||= $ERRORS_MAX ;
  4473. if ( $mysync->{nb_errors} >= $mysync->{errorsmax} ) {
  4474. myprint( "Maximum number of errors $mysync->{errorsmax} reached ( you can change $mysync->{errorsmax} to any value, for example 100 with --errorsmax 100 ). Exiting.\n" ) ;
  4475. my $most_common_error = errorsanalyse( errors_log( $mysync ) ) ;
  4476. if ( $mysync->{errorsdump} ) {
  4477. myprint( errorsdump( errors_log( $mysync ) ) ) ;
  4478. myprint( "The most frequent error is $most_common_error\n" ) ;
  4479. # again since errorsdump( ) can be very verbose and masquerade previous warning
  4480. myprint( "Maximum number of errors $mysync->{errorsmax} reached ( you can change $mysync->{errorsmax} to any value, for example 100 with --errorsmax 100 ). Exiting.\n" ) ;
  4481. }
  4482. my $exit_value = $EXIT_VALUE_OF_ERR_TYPE{ $most_common_error } || $EXIT_CATCH_ALL ;
  4483. #exit_clean( $mysync, $EXIT_WITH_ERRORS_MAX ) ;
  4484. exit_clean( $mysync, $exit_value ) ;
  4485. }
  4486. return ;
  4487. }
  4488. sub tests_errors_log
  4489. {
  4490. note( 'Entering tests_errors_log()' ) ;
  4491. is( undef, errors_log( ), 'errors_log: no args => undef' ) ;
  4492. my $mysync = {} ;
  4493. is( undef, errors_log( $mysync ), 'errors_log: empty => undef' ) ;
  4494. is_deeply( [ 'aieaie' ], [ errors_log( $mysync, 'aieaie' ) ], 'errors_log: aieaie => aieaie' ) ;
  4495. # cumulative
  4496. is_deeply( [ 'aieaie' ], [ errors_log( $mysync ) ], 'errors_log: nothing more => aieaie' ) ;
  4497. is_deeply( [ 'aieaie', 'ouille' ], [ errors_log( $mysync, 'ouille' ) ], 'errors_log: ouille => aieaie ouille' ) ;
  4498. is_deeply( [ 'aieaie', 'ouille' ], [ errors_log( $mysync ) ], 'errors_log: nothing more => aieaie ouille' ) ;
  4499. note( 'Leaving tests_errors_log()' ) ;
  4500. return ;
  4501. }
  4502. sub errors_log
  4503. {
  4504. my ( $mysync, @error ) = @ARG ;
  4505. if ( ! $mysync->{errors_log} ) {
  4506. $mysync->{errors_log} = [] ;
  4507. }
  4508. if ( @error ) {
  4509. push @{ $mysync->{errors_log} }, join( q{}, @error ) ;
  4510. }
  4511. if ( @{ $mysync->{errors_log} } ) {
  4512. return @{ $mysync->{errors_log} } ;
  4513. }
  4514. else {
  4515. return ;
  4516. }
  4517. }
  4518. sub tests_error_type
  4519. {
  4520. note( 'Entering tests_error_type()' ) ;
  4521. is( 'ERR_NOTHING_REPORTED', error_type( ), 'error_type: no args => ERR_NOTHING_REPORTED' ) ;
  4522. is( 'ERR_NOTHING_REPORTED', error_type( '' ), 'error_type: empty string => ERR_NOTHING_REPORTED' ) ;
  4523. is( 'ERR_UNCLASSIFIED', error_type( 'ERR_UNCLASSIFIED' ), 'error_type: ERR_UNCLASSIFIED => ERR_UNCLASSIFIED' ) ;
  4524. is( 'ERR_UNCLASSIFIED', error_type( 'aie' ), 'error_type: aie => ERR_UNCLASSIFIED' ) ;
  4525. is( 'ERR_UNCLASSIFIED', error_type( 'ouille' ), 'error_type: ouille => ERR_UNCLASSIFIED' ) ;
  4526. is( 'ERR_Host1_FETCH', error_type( 'Message xxx could not be fetched: blabla' ),
  4527. 'error_type: could not be fetched => ERR_Host1_FETCH'
  4528. ) ;
  4529. is( 'ERR_APPEND_SIZE',
  4530. error_type( 'could not append message xxx: BAD maximum message size exceeded' ),
  4531. 'error_type: could not append message xxx: BAD maximum message size exceeded => ERR_APPEND_SIZE'
  4532. ) ;
  4533. is( 'ERR_OVERQUOTA',
  4534. error_type( 'Quota limit will be exceeded' ),
  4535. 'error_type: Quota limit will be exceeded => ERR_OVERQUOTA'
  4536. ) ;
  4537. is( 'ERR_APPEND', error_type( 'could not append' ), 'error_type: could not append => ERR_APPEND' ) ;
  4538. is( 'ERR_CREATE',
  4539. error_type( 'Could not create folder' ),
  4540. 'error_type: Could not create folder => ERR_CREATE'
  4541. ) ;
  4542. is( 'ERR_SELECT',
  4543. error_type( 'Could not select: blabla' ),
  4544. 'error_type: Could not select: blabla => ERR_SELECT'
  4545. ) ;
  4546. #
  4547. #Maximum bytes transferred reached, 423 >= 100, ending sync
  4548. is( 'ERR_TRANSFER_EXCEEDED',
  4549. error_type( 'Maximum bytes transferred reached, blabla' ),
  4550. 'error_type: Maximum bytes transferred reached, blabla => ERR_TRANSFER_EXCEEDED'
  4551. ) ;
  4552. #
  4553. is( 'ERR_CONNECTION_FAILURE_HOST1',
  4554. error_type( 'Host1 failure: can not open imap connection on host1 [badhostkaka] with user [tata]: Unable to connect to badhostkaka: Invalid argument' ),
  4555. 'error_type: can not open imap connection on host1 => ERR_CONNECTION_FAILURE_HOST1'
  4556. ) ;
  4557. is( 'ERR_CONNECTION_FAILURE_HOST2',
  4558. error_type( 'Host2 failure: can not open imap connection on host2 [badhostkiki] with user [titi]: Unable to connect to badhostkiki: Invalid argument' ),
  4559. 'error_type: can not open imap connection on host2 => ERR_CONNECTION_FAILURE_HOST2'
  4560. ) ;
  4561. is( 'ERR_APPEND_VIRUS',
  4562. error_type( 'could not append ( Subject:[For Your Consideration], Date:["29-Nov-2016 03:21:10 -0800"], Size:[5505], Flags:[\Seen] ) to folder INBOX: 275 NO Message refused because it contains a virus' ),
  4563. 'error_type: could not append ... virus => ERR_APPEND_VIRUS'
  4564. ) ;
  4565. note( 'Leaving tests_error_type()' ) ;
  4566. return ;
  4567. }
  4568. # Could be implemented with https://metacpan.org/pod/Tie::RegexpHash
  4569. # with just a hash of error regexes as keys and types as values.
  4570. sub error_type
  4571. {
  4572. my $error = shift ;
  4573. if ( ! defined $error ) { return 'ERR_NOTHING_REPORTED' ; }
  4574. if ( ! $error ) { return 'ERR_NOTHING_REPORTED' ; }
  4575. #
  4576. if ( $error =~ m{Host1 failure: Error login on} ) { return 'ERR_AUTHENTICATION_FAILURE_USER1' } ;
  4577. if ( $error =~ m{Host2 failure: Error login on} ) { return 'ERR_AUTHENTICATION_FAILURE_USER2' } ;
  4578. if ( $error =~ m{Host. failure: Can not go to tls encryption on host.} ) { return 'ERR_EXIT_TLS_FAILURE' } ;
  4579. #
  4580. if ( $error =~ m{could not be fetched:} ) { return 'ERR_Host1_FETCH' } ;
  4581. # could not append .*BAD maximum message size exceeded
  4582. # could not append.*Maximum size of appendable message has been exceeded
  4583. if ( $error =~ m{could not append .*BAD maximum message size exceeded} )
  4584. { return 'ERR_APPEND_SIZE' ; } ;
  4585. if ( $error =~ m{could not append.*Maximum size of appendable message has been exceeded} )
  4586. { return 'ERR_APPEND_SIZE' ; } ;
  4587. # Could not create folder *[OVERQUOTA] Not enough disk quota
  4588. # could not append .*[OVERQUOTA] Not enough disk quota
  4589. # could not append .*[OVERQUOTA] Mailbox is full / Blocks limit exceeded / Inode limit exceeded
  4590. if ( $error =~ m{OVERQUOTA} ) { return 'ERR_OVERQUOTA' ; } ;
  4591. if ( $error =~ m{Quota limit will be exceeded} ) { return 'ERR_OVERQUOTA' ; } ;
  4592. if ( $error =~ m{full: it is time to find a bigger place} ) { return 'ERR_OVERQUOTA' ; } ;
  4593. # could not append ... to folder INBOX: 276 NO Message refused because it contains a virus
  4594. if ( $error =~ m{could not append.*virus} )
  4595. { return 'ERR_APPEND_VIRUS' ; } ;
  4596. # could not append .*Write failed 'Broken pipe'
  4597. # could not append .*timeout waiting .* for data from server
  4598. # could not append .*BAD Invalid Arguments: Unable to parse message
  4599. # could not append .*BAD Command Argument Error. 11
  4600. # could not append .*NO header limit reached
  4601. if ( $error =~ m{could not append} ) { return 'ERR_APPEND' ; } ;
  4602. # Could not create folder .*Invalid mailbox name
  4603. if ( $error =~ m{Could not create folder} ) { return 'ERR_CREATE' ; } ;
  4604. # Could not select:.*NO [NOPERM] Permission denied
  4605. # Could not select:.*NO Mailbox doesn't exist
  4606. # Could not select:.*NO [SERVERBUG] Internal error occurred.
  4607. # Could not select:.*[CANNOT] Mailbox isn't a valid mbox file
  4608. if ( $error =~ m{Could not select:} ) { return 'ERR_SELECT' ; } ;
  4609. #Maximum bytes transferred reached, 423 >= 100, ending sync
  4610. if ( $error =~ m{Maximum bytes transferred reached} ) { return 'ERR_TRANSFER_EXCEEDED' ; } ;
  4611. if ( $error =~ m{can not open imap connection on host1} ) { return 'ERR_CONNECTION_FAILURE_HOST1' ; } ;
  4612. if ( $error =~ m{can not open imap connection on host2} ) { return 'ERR_CONNECTION_FAILURE_HOST2' ; } ;
  4613. # Default is ERR_UNCLASSIFIED
  4614. return 'ERR_UNCLASSIFIED' ;
  4615. }
  4616. sub tests_errorclassify
  4617. {
  4618. note( 'Entering tests_errorclassify()' ) ;
  4619. is( undef, errorclassify( ), 'errorclassify: no args => undef' ) ;
  4620. is_deeply( { 'ERR_UNCLASSIFIED' => 1 }, errorclassify( 'aie' ), 'errorclassify: aie => { ERR_UNCLASSIFIED => 1 }' ) ;
  4621. is_deeply( { 'ERR_UNCLASSIFIED' => 2 }, errorclassify( 'aie', 'ouille' ), 'errorclassify: aie ouille => { ERR_UNCLASSIFIED => 2 }' ) ;
  4622. is_deeply( { 'ERR_UNCLASSIFIED' => 2, 'ERR_NOTHING_REPORTED' => 1 }, errorclassify( 'aie', 'ouille', '' ), 'errorclassify: aie ouille "" => { ERR_UNCLASSIFIED => 2 }' ) ;
  4623. is_deeply( { 'ERR_UNCLASSIFIED' => 3 }, errorclassify( 'aie', 'ouille', 'aie' ), 'errorclassify: aie ouille aie => { ERR_UNCLASSIFIED => 3 }' ) ;
  4624. is_deeply( { 'ERR_UNCLASSIFIED' => 1, 'ERR_OVERQUOTA' => 2 }, errorclassify( 'aie', 'OVERQUOTA pipi', 'OVERQUOTA caca' ), 'errorclassify: aie OVERQUOTA OVERQUOTA' ) ;
  4625. is_deeply( { 'ERR_NOTHING_REPORTED' => 1 }, errorclassify( '' ), 'errorclassify: "" => { ERR_NOTHING_REPORTED => 1 }' ) ;
  4626. is_deeply( { 'ERR_NOTHING_REPORTED' => 2 }, errorclassify( '', '' ), 'errorclassify: "", "" => { ERR_NOTHING_REPORTED => 1 }' ) ;
  4627. note( 'Leaving tests_errorclassify()' ) ;
  4628. return ;
  4629. }
  4630. sub errorclassify
  4631. {
  4632. my @errors = @ARG ;
  4633. if ( ! @errors ) { return ; } ;
  4634. my $error_type_count = { } ;
  4635. foreach my $error ( @errors )
  4636. {
  4637. my $error_type = error_type( $error ) ;
  4638. $error_type_count->{ $error_type }++ ;
  4639. }
  4640. return $error_type_count ;
  4641. }
  4642. sub tests_most_common_error
  4643. {
  4644. note( 'Entering tests_most_common_error()' ) ;
  4645. is( 'ERR_NOTHING_REPORTED', most_common_error( ), 'most_common_error: no args => ERR_NOTHING_REPORTED' ) ;
  4646. is( 'ERR_NOTHING_REPORTED', most_common_error( {} ), 'most_common_error: empty hash ref => ERR_NOTHING_REPORTED' ) ;
  4647. is( 'ERR_NOTHING_REPORTED', most_common_error( 'blabla' ), 'most_common_error: not a hash ref => ERR_NOTHING_REPORTED' ) ;
  4648. is( 'ERR_FOO', most_common_error( { ERR_FOO => 1 } ), 'most_common_error: { ERR_FOO => 1 } => ERR_FOO' ) ;
  4649. is( 'ERR_BAR', most_common_error( { ERR_FOO => 1, ERR_BAR => 2 } ), 'most_common_error: { ERR_FOO => 1, ERR_BAR => 2 } => ERR_BAR' ) ;
  4650. is( 'ERR_FOO', most_common_error( { ERR_FOO => 2, ERR_BAR => 1 } ), 'most_common_error: { ERR_FOO => 2, ERR_BAR => 1 } => ERR_FOO' ) ;
  4651. # exaequo => first lexical wins. ERR_BAR <= ERR_FOO
  4652. is( 'ERR_BAR', most_common_error( { ERR_FOO => 2, ERR_BAR => 2 } ), 'most_common_error: { ERR_FOO => 2, ERR_BAR => 2 } => ERR_BAR' ) ;
  4653. is( 'A', most_common_error( { A => 5, B => 5, C => 5 } ), 'most_common_error: { A => 5, B => 5, C => 5 } => A' ) ;
  4654. is( 'B', most_common_error( { A => 5, B => 6, C => 6 } ), 'most_common_error: { A => 5, B => 6, C => 6 } => B' ) ;
  4655. is( 'C', most_common_error( { A => 5, B => 5, C => 7 } ), 'most_common_error: { A => 5, B => 5, C => 7 } => C' ) ;
  4656. is( 'C', most_common_error( { A => 5, B => 6, C => 7 } ), 'most_common_error: { A => 5, B => 5, C => 7 } => C' ) ;
  4657. note( 'Leaving tests_most_common_error()' ) ;
  4658. return ;
  4659. }
  4660. sub most_common_error
  4661. {
  4662. my $errors_counted_ref = shift ;
  4663. if ( ! defined $errors_counted_ref ) { return 'ERR_NOTHING_REPORTED' ; }
  4664. if ( 'HASH' ne ref $errors_counted_ref ) { return 'ERR_NOTHING_REPORTED' ; }
  4665. # empty hash
  4666. if ( !%{ $errors_counted_ref } ) { return 'ERR_NOTHING_REPORTED' ; }
  4667. # non empty hash
  4668. my $most_common_error = ( sort
  4669. {
  4670. $errors_counted_ref->{$b} <=> $errors_counted_ref->{$a}
  4671. || $a cmp $b
  4672. } keys %{$errors_counted_ref} )[0] ;
  4673. return $most_common_error ;
  4674. }
  4675. sub tests_errorsanalyse
  4676. {
  4677. note( 'Entering tests_errorsanalyse()' ) ;
  4678. is( 'ERR_NOTHING_REPORTED', errorsanalyse( ), 'errorsanalyse: no args => ERR_NOTHING_REPORTED' ) ;
  4679. is( 'ERR_NOTHING_REPORTED', errorsanalyse( ( ) ), 'errorsanalyse: empty list => ERR_NOTHING_REPORTED' ) ;
  4680. is( 'ERR_UNCLASSIFIED', errorsanalyse( 'aie' ), 'errorsanalyse: aie => ERR_UNCLASSIFIED' ) ;
  4681. # in case of equality, empty wins
  4682. is( 'ERR_NOTHING_REPORTED', errorsanalyse( 'aie', '' ), 'errorsanalyse: aie => ERR_UNCLASSIFIED' ) ;
  4683. is( 'ERR_NOTHING_REPORTED', errorsanalyse( '', 'aie' ), 'errorsanalyse: aie => ERR_UNCLASSIFIED' ) ;
  4684. is( 'ERR_UNCLASSIFIED', errorsanalyse( 'aie', 'ouille' ), 'errorsanalyse: aie, ouille => ERR_UNCLASSIFIED' ) ;
  4685. is( 'ERR_UNCLASSIFIED', errorsanalyse( 'aie', 'ouille', '' ), 'errorsanalyse: aie, ouille, "" => ERR_UNCLASSIFIED' ) ;
  4686. is( 'ERR_UNCLASSIFIED', errorsanalyse( '', 'aie', 'ouille' ), 'errorsanalyse: aie, ouille, "" => ERR_UNCLASSIFIED' ) ;
  4687. is( 'ERR_NOTHING_REPORTED', errorsanalyse( '' ), 'errorsanalyse: "" => ERR_NOTHING_REPORTED' ) ;
  4688. is( 'ERR_NOTHING_REPORTED', errorsanalyse( ( '' ) ), 'errorsanalyse: ( "" ) => ERR_NOTHING_REPORTED' ) ;
  4689. is( 'ERR_NOTHING_REPORTED', errorsanalyse( ( '', '' ) ), 'errorsanalyse: ( "", "" ) => ERR_NOTHING_REPORTED' ) ;
  4690. note( 'Leaving tests_errorsanalyse()' ) ;
  4691. return ;
  4692. }
  4693. sub errorsanalyse
  4694. {
  4695. my @errors = @ARG ;
  4696. my $errors_types_counted = errorclassify( @errors ) ;
  4697. my $most_common_error = most_common_error( $errors_types_counted ) ;
  4698. return $most_common_error ;
  4699. }
  4700. sub tests_errorsdump
  4701. {
  4702. note( 'Entering tests_errorsdump()' ) ;
  4703. is( undef, errorsdump( ), 'errorsdump: no args => undef' ) ;
  4704. is( undef, errorsdump( ( ) ), 'errorsdump: empty list => undef' ) ;
  4705. is( "Err 1/1: ", errorsdump( '' ), 'errorsdump: one empty string => "Err 1/1: "' ) ;
  4706. is( "Err 1/1: aieaieaie", errorsdump( 'aieaieaie' ), 'errorsdump: aieaieaie => "Err 1/1: aieaieaie"' ) ;
  4707. is( "Err 1/2: Aie Err 2/2: Ouille", errorsdump( 'Aie ', 'Ouille' ), 'errorsdump: Aie Ouille => "Err 1/2: Aie Err 2/2: Ouille"' ) ;
  4708. note( 'Leaving tests_errorsdump()' ) ;
  4709. return ;
  4710. }
  4711. sub errorsdump
  4712. {
  4713. if ( ! @ARG ) { return ; }
  4714. my @errors_log = @ARG ;
  4715. my $nb_errors = @errors_log ;
  4716. my $error_num = 0 ;
  4717. my $errors_list = q{} ;
  4718. if ( @errors_log ) {
  4719. foreach my $error ( @errors_log )
  4720. {
  4721. $error_num++ ;
  4722. $errors_list .= "Err $error_num/$nb_errors: $error" ;
  4723. }
  4724. }
  4725. return( $errors_list ) ;
  4726. }
  4727. sub errors_listing
  4728. {
  4729. my $mysync = shift ;
  4730. $mysync->{most_common_error} = errorsanalyse( errors_log( $sync ) ) ;
  4731. my $errors_listing = join( '',
  4732. "++++ Listing $mysync->{nb_errors} errors encountered during the sync ( avoid this listing with --noerrorsdump ).\n",
  4733. errorsdump( errors_log( $mysync ) ),
  4734. "The most frequent error is $mysync->{most_common_error}\n",
  4735. ) ;
  4736. return $errors_listing ;
  4737. }
  4738. sub tests_live_result
  4739. {
  4740. note( 'Entering tests_live_result()' ) ;
  4741. my $nb_errors = shift ;
  4742. if ( $nb_errors ) {
  4743. myprint( "Live tests failed with $nb_errors errors\n" ) ;
  4744. } else {
  4745. myprint( "Live tests ended successfully\n" ) ;
  4746. }
  4747. note( 'Leaving tests_live_result()' ) ;
  4748. return ;
  4749. }
  4750. sub size_filtered_flag
  4751. {
  4752. my $mysync = shift ;
  4753. my $h1_size = shift ;
  4754. if ( defined $mysync->{ maxsize } and $h1_size >= $mysync->{ maxsize } ) {
  4755. return( 1 ) ;
  4756. }
  4757. if ( defined $minsize and $h1_size <= $minsize ) {
  4758. return( 1 ) ;
  4759. }
  4760. return( 0 ) ;
  4761. }
  4762. sub sync_flags_fir
  4763. {
  4764. my ( $mysync, $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) = @_ ;
  4765. if ( not defined $h1_msg ) { return } ;
  4766. if ( not defined $h2_msg ) { return } ;
  4767. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} ;
  4768. return if size_filtered_flag( $mysync, $h1_size ) ;
  4769. # used cached flag values for efficiency
  4770. my $h1_flags = $h1_fir_ref->{ $h1_msg }->{ 'FLAGS' } || q{} ;
  4771. my $h2_flags = $h2_fir_ref->{ $h2_msg }->{ 'FLAGS' } || q{} ;
  4772. sync_flags( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  4773. return ;
  4774. }
  4775. sub sync_flags_after_copy
  4776. {
  4777. # Activated with option --syncflagsaftercopy
  4778. my( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $permanentflags2 ) = @_ ;
  4779. if ( my @h2_flags = $mysync->{imap2}->flags( $h2_msg ) ) {
  4780. my $h2_flags = "@h2_flags" ;
  4781. ( $mysync->{ debug } or $debugflags ) and myprint( "Host2: msg $h2_fold/$h2_msg flags before sync flags after copy ( $h2_flags )\n" ) ;
  4782. sync_flags( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  4783. }else{
  4784. myprint( "Host2: msg $h2_fold/$h2_msg could not get its flags for sync flags after copy\n" ) ;
  4785. }
  4786. return ;
  4787. }
  4788. # Globals
  4789. # $debug
  4790. # $debugflags
  4791. # $permanentflags2
  4792. sub sync_flags
  4793. {
  4794. my( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) = @_ ;
  4795. ( $mysync->{ debug } or $debugflags ) and
  4796. myprint( "Host1: flags init msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 msg $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  4797. $h1_flags = flags_for_host2( $mysync, $h1_flags, $permanentflags2 ) ;
  4798. $h2_flags = flagscase( $h2_flags ) ;
  4799. ( $mysync->{ debug } or $debugflags ) and
  4800. myprint( "Host1: flags filt msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 msg $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  4801. # compare flags - set flags if there a difference
  4802. my @h1_flags = sort split(q{ }, $h1_flags );
  4803. my @h2_flags = sort split(q{ }, $h2_flags );
  4804. my $diff = compare_lists( \@h1_flags, \@h2_flags );
  4805. $diff and ( $mysync->{ debug } or $debugflags )
  4806. and myprint( "Host2: flags msg $h2_fold/$h2_msg replacing h2 flags( $h2_flags ) with h1 flags( $h1_flags )\n" ) ;
  4807. # This sets flags exactly. So flags can be removed with this.
  4808. # When you remove a \Seen flag on host1 you want it
  4809. # to be removed on host2. Just add flags is not what
  4810. # we need most of the time, so no + like in "+FLAGS.SILENT".
  4811. if ( not $mysync->{dry} and $diff and not $mysync->{imap2}->store( $h2_msg, "FLAGS.SILENT (@h1_flags)" ) ) {
  4812. my $error_msg = join q{}, "Host2: flags msg $h2_fold/$h2_msg could not add flags [@h1_flags]: ",
  4813. $mysync->{imap2}->LastError || q{}, "\n" ;
  4814. errors_incr( $mysync, $error_msg ) ;
  4815. }
  4816. return ;
  4817. }
  4818. sub _filter
  4819. {
  4820. my $mysync = shift ;
  4821. my $str = shift or return q{} ;
  4822. my $sz = $SIZE_MAX_STR ;
  4823. my $len = length $str ;
  4824. if ( not $mysync->{ debug } and $len > $sz*2 ) {
  4825. my $beg = substr $str, 0, $sz ;
  4826. my $end = substr $str, -$sz, $sz ;
  4827. $str = $beg . '...' . $end ;
  4828. }
  4829. $str =~ s/\012?\015$//x ;
  4830. return "(len=$len) " . $str ;
  4831. }
  4832. sub lost_connection
  4833. {
  4834. my( $mysync, $imap, $error_message ) = @_;
  4835. if ( $imap->IsUnconnected( ) ) {
  4836. $mysync->{nb_errors}++ ;
  4837. my $lcomm = $imap->LastIMAPCommand || q{} ;
  4838. my $einfo = imap_last_error( $imap ) ;
  4839. # if string is long try reduce to a more reasonable size
  4840. $lcomm = _filter( $mysync, $lcomm ) ;
  4841. $einfo = _filter( $mysync, $einfo ) ;
  4842. myprint( "Failure: last command: $lcomm\n") if ( $mysync->{ debug } && $lcomm) ;
  4843. myprint( "Failure: lost connection $error_message: ", $einfo, "\n") ;
  4844. return( 1 ) ;
  4845. }
  4846. else{
  4847. return( 0 ) ;
  4848. }
  4849. }
  4850. sub imap_last_error
  4851. {
  4852. my $imap = shift ;
  4853. my $einfo = $imap->LastError || @{$imap->History}[$LAST] || q{} ;
  4854. chomp( $einfo ) ;
  4855. return( $einfo ) ;
  4856. }
  4857. sub tests_max
  4858. {
  4859. note( 'Entering tests_max()' ) ;
  4860. is( 0, max( 0 ), 'max 0 => 0' ) ;
  4861. is( 1, max( 1 ), 'max 1 => 1' ) ;
  4862. is( $MINUS_ONE, max( $MINUS_ONE ), 'max -1 => -1') ;
  4863. is( undef, max( ), 'max no arg => undef' ) ;
  4864. is( undef, max( undef ), 'undef => undef' ) ;
  4865. is( undef, max( undef, undef ), 'undef, undef => undef' ) ;
  4866. is( $NUMBER_100, max( 1, $NUMBER_100 ), 'max 1 100 => 100' ) ;
  4867. is( $NUMBER_100, max( $NUMBER_100, 1 ), 'max 100 1 => 100' ) ;
  4868. is( $NUMBER_100, max( $NUMBER_100, $NUMBER_42, 1 ), 'max 100 42 1 => 100' ) ;
  4869. is( $NUMBER_100, max( $NUMBER_100, '42', 1 ), 'max 100 42 1 => 100' ) ;
  4870. is( $NUMBER_100, max( '100', '42', 1 ), 'max 100 42 1 => 100' ) ;
  4871. is( $NUMBER_100, max( $NUMBER_100, 'haha', 1 ), 'max 100 haha 1 => 100') ;
  4872. is( $NUMBER_100, max( 'bb', $NUMBER_100, 'haha' ), 'max bb 100 haha => 100') ;
  4873. is( $MINUS_ONE, max( q{}, $MINUS_ONE, 'haha' ), 'max "" -1 haha => -1') ;
  4874. is( $MINUS_ONE, max( q{}, $MINUS_ONE, $MINUS_TWO ), 'max "" -1 -2 => -1') ;
  4875. is( $MINUS_ONE, max( 'haha', $MINUS_ONE, $MINUS_TWO ), 'max haha -1 -2 => -1') ;
  4876. is( 1, max( $MINUS_ONE, 1 ), 'max -1 1 => 1') ;
  4877. is( 1, max( undef, 1 ), 'max undef 1 => 1' ) ;
  4878. is( 0, max( undef, 0 ), 'max undef 0 => 0' ) ;
  4879. is( 'haha', max( 'haha' ), 'max haha => haha') ;
  4880. is( 'bb', max( 'aa', 'bb' ), 'max aa bb => bb') ;
  4881. is( 'bb', max( 'bb', 'aa' ), 'max bb aa => bb') ;
  4882. is( 'bb', max( 'bb', 'aa', 'bb' ), 'max bb aa bb => bb') ;
  4883. note( 'Leaving tests_max()' ) ;
  4884. return ;
  4885. }
  4886. sub max
  4887. {
  4888. my @list = @_ ;
  4889. return( undef ) if ( 0 == scalar @list ) ;
  4890. my( @numbers, @notnumbers ) ;
  4891. foreach my $item ( @list )
  4892. {
  4893. if ( is_number( $item ) )
  4894. {
  4895. push @numbers, $item ;
  4896. }
  4897. elsif ( defined $item )
  4898. {
  4899. push @notnumbers, $item ;
  4900. }
  4901. }
  4902. my @sorted ;
  4903. if ( @numbers )
  4904. {
  4905. @sorted = sort { $a <=> $b } @numbers ;
  4906. }
  4907. elsif ( @notnumbers )
  4908. {
  4909. @sorted = sort { $a cmp $b } @notnumbers ;
  4910. }
  4911. else
  4912. {
  4913. return ;
  4914. }
  4915. return( pop @sorted ) ;
  4916. }
  4917. sub tests_is_number
  4918. {
  4919. note( 'Entering tests_is_number()' ) ;
  4920. is( undef, is_number( ), 'is_number: no args => undef ' ) ;
  4921. is( undef, is_number( undef ), 'is_number: undef => undef ' ) ;
  4922. ok( is_number( 1 ), 'is_number: 1 => 1' ) ;
  4923. ok( is_number( 1.1 ), 'is_number: 1.1 => 1' ) ;
  4924. ok( is_number( 0 ), 'is_number: 0 => 1' ) ;
  4925. ok( is_number( -1 ), 'is_number: -1 => 1' ) ;
  4926. ok( ! is_number( 1.1.1 ), 'is_number: 1.1.1 => no' ) ;
  4927. ok( ! is_number( q{} ), 'is_number: q{} => no' ) ;
  4928. ok( ! is_number( 'haha' ), 'is_number: haha => no' ) ;
  4929. ok( ! is_number( '0haha' ), 'is_number: 0haha => no' ) ;
  4930. ok( ! is_number( '2haha' ), 'is_number: 2haha => no' ) ;
  4931. ok( ! is_number( 'haha2' ), 'is_number: haha2 => no' ) ;
  4932. note( 'Leaving tests_is_number()' ) ;
  4933. return ;
  4934. }
  4935. sub is_number
  4936. {
  4937. my $item = shift ;
  4938. if ( ! defined $item ) { return ; }
  4939. if ( $item =~ /\A$RE{num}{real}\Z/ ) {
  4940. return 1 ;
  4941. }
  4942. return ;
  4943. }
  4944. sub tests_min
  4945. {
  4946. note( 'Entering tests_min()' ) ;
  4947. is( 0, min( 0 ), 'min 0 => 0' ) ;
  4948. is( 1, min( 1 ), 'min 1 => 1' ) ;
  4949. is( $MINUS_ONE, min( $MINUS_ONE ), 'min -1 => -1' ) ;
  4950. is( undef, min( ), 'min no arg => undef' ) ;
  4951. is( 1, min( 1, $NUMBER_100 ), 'min 1 100 => 1' ) ;
  4952. is( 1, min( $NUMBER_100, 1 ), 'min 100 1 => 1' ) ;
  4953. is( 1, min( $NUMBER_100, $NUMBER_42, 1 ), 'min 100 42 1 => 1' ) ;
  4954. is( 1, min( $NUMBER_100, '42', 1 ), 'min 100 42 1 => 1' ) ;
  4955. is( 1, min( '100', '42', 1 ), 'min 100 42 1 => 1' ) ;
  4956. is( 1, min( $NUMBER_100, 'haha', 1 ), 'min 100 haha 1 => 1') ;
  4957. is( $MINUS_ONE, min( $MINUS_ONE, 1 ), 'min -1 1 => -1') ;
  4958. is( 1, min( undef, 1 ), 'min undef 1 => 1' ) ;
  4959. is( 0, min( undef, 0 ), 'min undef 0 => 0' ) ;
  4960. is( 1, min( undef, 1 ), 'min undef 1 => 1' ) ;
  4961. is( 0, min( undef, 2, 0, 1 ), 'min undef, 2, 0, 1 => 0' ) ;
  4962. is( 'haha', min( 'haha' ), 'min haha => haha') ;
  4963. is( 'aa', min( 'aa', 'bb' ), 'min aa bb => aa') ;
  4964. is( 'aa', min( 'bb', 'aa' ), 'min bb aa bb => aa') ;
  4965. is( 'aa', min( 'bb', 'aa', 'bb' ), 'min bb aa bb => aa') ;
  4966. note( 'Leaving tests_min()' ) ;
  4967. return ;
  4968. }
  4969. sub min
  4970. {
  4971. my @list = @_ ;
  4972. return( undef ) if ( 0 == scalar @list ) ;
  4973. my( @numbers, @notnumbers ) ;
  4974. foreach my $item ( @list ) {
  4975. if ( is_number( $item ) ) {
  4976. push @numbers, $item ;
  4977. }else{
  4978. push @notnumbers, $item ;
  4979. }
  4980. }
  4981. my @sorted ;
  4982. if ( @numbers ) {
  4983. @sorted = sort { $a <=> $b } @numbers ;
  4984. }elsif( @notnumbers ) {
  4985. @sorted = sort { $a cmp $b } @notnumbers ;
  4986. }else{
  4987. return ;
  4988. }
  4989. return( shift @sorted ) ;
  4990. }
  4991. sub check_lib_version
  4992. {
  4993. my $mysync = shift ;
  4994. $mysync->{ debug } and myprint( "IMAPClient $Mail::IMAPClient::VERSION\n" ) ;
  4995. if ( '2.2.9' eq $Mail::IMAPClient::VERSION ) {
  4996. myprint( "imapsync no longer supports Mail::IMAPClient 2.2.9, upgrade it\n" ) ;
  4997. return 0 ;
  4998. }
  4999. else{
  5000. # 3.x.x is no longer buggy with imapsync.
  5001. # 3.30 or currently superior is imposed in the Perl "use Mail::IMAPClient line".
  5002. return 1 ;
  5003. }
  5004. return ;
  5005. }
  5006. sub module_version_str
  5007. {
  5008. my( $module_name, $module_version ) = @_ ;
  5009. my $str = mysprintf( "%-20s %s\n", $module_name, $module_version ) ;
  5010. return( $str ) ;
  5011. }
  5012. sub modulesversion
  5013. {
  5014. my @list_version;
  5015. my %modulesversion = (
  5016. 'Authen::NTLM' => sub { $Authen::NTLM::VERSION },
  5017. 'CGI' => sub { $CGI::VERSION },
  5018. 'Compress::Zlib' => sub { $Compress::Zlib::VERSION },
  5019. 'Crypt::OpenSSL::RSA' => sub { $Crypt::OpenSSL::RSA::VERSION },
  5020. 'Data::Uniqid' => sub { $Data::Uniqid::VERSION },
  5021. 'Digest::HMAC_MD5' => sub { $Digest::HMAC_MD5::VERSION },
  5022. 'Digest::HMAC_SHA1' => sub { $Digest::HMAC_SHA1::VERSION },
  5023. 'Digest::MD5' => sub { $Digest::MD5::VERSION },
  5024. 'Encode' => sub { $Encode::VERSION },
  5025. 'Encode::IMAPUTF7' => sub { $Encode::IMAPUTF7::VERSION },
  5026. 'File::Copy::Recursive' => sub { $File::Copy::Recursive::VERSION },
  5027. 'File::Spec' => sub { $File::Spec::VERSION },
  5028. 'Getopt::Long' => sub { $Getopt::Long::VERSION },
  5029. 'HTML::Entities' => sub { $HTML::Entities::VERSION },
  5030. 'IO::Socket' => sub { $IO::Socket::VERSION },
  5031. 'IO::Socket::INET' => sub { $IO::Socket::INET::VERSION },
  5032. 'IO::Socket::INET6' => sub { $IO::Socket::INET6::VERSION },
  5033. 'IO::Socket::IP' => sub { $IO::Socket::IP::VERSION },
  5034. 'IO::Socket::SSL' => sub { $IO::Socket::SSL::VERSION },
  5035. 'IO::Tee' => sub { $IO::Tee::VERSION },
  5036. 'JSON' => sub { $JSON::VERSION },
  5037. 'JSON::WebToken' => sub { $JSON::WebToken::VERSION },
  5038. 'LWP' => sub { $LWP::VERSION },
  5039. 'Mail::IMAPClient' => sub { $Mail::IMAPClient::VERSION },
  5040. 'MIME::Base64' => sub { $MIME::Base64::VERSION },
  5041. 'Net::Ping' => sub { $Net::Ping::VERSION },
  5042. 'Net::SSLeay' => sub { $Net::SSLeay::VERSION },
  5043. 'Term::ReadKey' => sub { $Term::ReadKey::VERSION },
  5044. 'Test::MockObject' => sub { $Test::MockObject::VERSION },
  5045. 'Time::HiRes' => sub { $Time::HiRes::VERSION },
  5046. 'Unicode::String' => sub { $Unicode::String::VERSION },
  5047. 'URI::Escape' => sub { $URI::Escape::VERSION },
  5048. #'Lalala' => sub { $Lalala::VERSION },
  5049. ) ;
  5050. foreach my $module_name ( sort keys %modulesversion ) {
  5051. # trick from http://www.perlmonks.org/?node_id=152122
  5052. my $file_name = $module_name . '.pm' ;
  5053. $file_name =~s,::,/,xmgs; # Foo::Bar::Baz => Foo/Bar/Baz.pm
  5054. my $v ;
  5055. eval {
  5056. require $file_name ;
  5057. $v = defined $modulesversion{ $module_name } ? $modulesversion{ $module_name }->() : q{?} ;
  5058. } or $v = q{Not installed} ;
  5059. push @list_version, module_version_str( $module_name, $v ) ;
  5060. }
  5061. return( @list_version ) ;
  5062. }
  5063. sub tests_command_line_nopassword
  5064. {
  5065. note( 'Entering tests_command_line_nopassword()' ) ;
  5066. ok( q{} eq command_line_nopassword(), 'command_line_nopassword void' );
  5067. my $mysync = {} ;
  5068. ok( '--blabla' eq command_line_nopassword( $mysync, '--blabla' ), 'command_line_nopassword --blabla' );
  5069. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  5070. ok( '--password1 MASKED' eq command_line_nopassword( $mysync, qw{ --password1 secret1}), 'command_line_nopassword --password1' );
  5071. ok( '--blabla --password1 MASKED --blibli'
  5072. eq command_line_nopassword( $mysync, qw{ --blabla --password1 secret1 --blibli } ), 'command_line_nopassword --password1 --blibli' );
  5073. $mysync->{showpasswords} = 1 ;
  5074. ok( q{} eq command_line_nopassword(), 'command_line_nopassword void' );
  5075. ok( '--blabla' eq command_line_nopassword( $mysync, '--blabla'), 'command_line_nopassword --blabla' );
  5076. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  5077. ok( '--password1 secret1' eq command_line_nopassword( $mysync, qw{ --password1 secret1} ), 'command_line_nopassword --password1' );
  5078. ok( '--blabla --password1 secret1 --blibli'
  5079. eq command_line_nopassword( $mysync, qw{ --blabla --password1 secret1 --blibli } ), 'command_line_nopassword --password1 --blibli' );
  5080. note( 'Leaving tests_command_line_nopassword()' ) ;
  5081. return ;
  5082. }
  5083. # Construct a command line copy with passwords replaced by MASKED.
  5084. sub command_line_nopassword
  5085. {
  5086. my $mysync = shift @ARG ;
  5087. my @argv = @ARG ;
  5088. my @argv_nopassword ;
  5089. if ( $mysync->{ cmdcgi } ) {
  5090. @argv_nopassword = mask_password_value( @{ $mysync->{ cmdcgi } } ) ;
  5091. return( "@argv_nopassword" ) ;
  5092. }
  5093. if ( $mysync->{showpasswords} )
  5094. {
  5095. return( "@argv" ) ;
  5096. }
  5097. @argv_nopassword = mask_password_value( @argv ) ;
  5098. return("@argv_nopassword") ;
  5099. }
  5100. sub mask_password_value
  5101. {
  5102. my @argv = @ARG ;
  5103. my @argv_nopassword ;
  5104. while ( @argv ) {
  5105. my $arg = shift @argv ; # option name or value
  5106. if ( $arg =~ m/-password[12]/x ) {
  5107. shift @argv ; # password value
  5108. push @argv_nopassword, $arg, 'MASKED' ; # option name and fake value
  5109. }else{
  5110. push @argv_nopassword, $arg ; # same option or value
  5111. }
  5112. }
  5113. return @argv_nopassword ;
  5114. }
  5115. sub tests_get_stdin_masked
  5116. {
  5117. note( 'Entering tests_get_stdin_masked()' ) ;
  5118. is( q{}, get_stdin_masked( ), 'get_stdin_masked: no args' ) ;
  5119. is( q{}, get_stdin_masked( 'Please ENTER: ' ), 'get_stdin_masked: ENTER' ) ;
  5120. note( 'Leaving tests_get_stdin_masked()' ) ;
  5121. return ;
  5122. }
  5123. #######################################################
  5124. # The issue is that prompt() does not prompt the prompt
  5125. # when the program is used like
  5126. # { sleep 2 ; echo blablabla ; } | ./imapsync ...--host1 lo --user1 tata --host2 lo --user2 titi
  5127. # use IO::Prompter ;
  5128. sub get_stdin_masked
  5129. {
  5130. my $prompt = shift || 'Say something: ' ;
  5131. local @ARGV = () ;
  5132. my $input = prompt(
  5133. -prompt => $prompt,
  5134. -echo => '*',
  5135. ) ;
  5136. #myprint( "You said: $input\n" ) ;
  5137. return $input ;
  5138. }
  5139. sub ask_for_password_new
  5140. {
  5141. my $prompt = shift ;
  5142. my $password = get_stdin_masked( $prompt ) ;
  5143. return $password ;
  5144. }
  5145. #########################################################
  5146. sub ask_for_password
  5147. {
  5148. my $prompt = shift ;
  5149. myprint( $prompt ) ;
  5150. Term::ReadKey::ReadMode( 2 ) ;
  5151. ## no critic (InputOutput::ProhibitExplicitStdin)
  5152. my $password = <STDIN> ;
  5153. chomp $password ;
  5154. myprint( "\nGot it\n" ) ;
  5155. Term::ReadKey::ReadMode( 0 ) ;
  5156. return $password ;
  5157. }
  5158. # Have to refactor get_password1() get_password2()
  5159. # to have only get_password() and two calls
  5160. sub get_password1
  5161. {
  5162. my $mysync = shift ;
  5163. $mysync->{ password1 }
  5164. || $mysync->{ passfile1 }
  5165. || 'PREAUTH' eq $mysync->{ acc1 }->{ authmech }
  5166. || 'EXTERNAL' eq $mysync->{ acc1 }->{ authmech }
  5167. || $ENV{IMAPSYNC_PASSWORD1}
  5168. || do
  5169. {
  5170. myprint( << 'FIN_PASSFILE' ) ;
  5171. If you are afraid of giving password on the command line arguments, you can put the
  5172. password of user1 in a file named file1 and use "--passfile1 file1" instead of typing it.
  5173. Then give this file restrictive permissions with the command "chmod 600 file1".
  5174. An other solution is to set the environment variable IMAPSYNC_PASSWORD1
  5175. FIN_PASSFILE
  5176. my $user = $mysync->{ acc1 }->{ authuser } || $mysync->{ user1 } ;
  5177. my $host = $mysync->{ host1 } ;
  5178. my $prompt = "What's the password for $user" . ' at ' . "$host? (not visible while you type, then enter RETURN) " ;
  5179. $mysync->{password1} = ask_for_password( $prompt ) ;
  5180. } ;
  5181. if ( defined $mysync->{ passfile1 } ) {
  5182. if ( ! -e -r $mysync->{ passfile1 } ) {
  5183. myprint( "Failure: file from parameter --passfile1 $mysync->{ passfile1 } does not exist or is not readable\n" ) ;
  5184. $mysync->{nb_errors}++ ;
  5185. exit_clean( $mysync, $EX_NOINPUT ) ;
  5186. }
  5187. # passfile1 readable
  5188. $mysync->{password1} = firstline ( $mysync->{ passfile1 } ) ;
  5189. return ;
  5190. }
  5191. if ( $ENV{IMAPSYNC_PASSWORD1} ) {
  5192. $mysync->{password1} = $ENV{IMAPSYNC_PASSWORD1} ;
  5193. return ;
  5194. }
  5195. return ;
  5196. }
  5197. sub get_password2
  5198. {
  5199. my $mysync = shift ;
  5200. $mysync->{password2}
  5201. || $mysync->{ passfile2 }
  5202. || 'PREAUTH' eq $mysync->{ acc2 }->{ authmech }
  5203. || 'EXTERNAL' eq $mysync->{ acc2 }->{ authmech }
  5204. || $ENV{IMAPSYNC_PASSWORD2}
  5205. || do
  5206. {
  5207. myprint( << 'FIN_PASSFILE' ) ;
  5208. If you are afraid of giving password on the command line arguments, you can put the
  5209. password of user2 in a file named file2 and use "--passfile2 file2" instead of typing it.
  5210. Then give this file restrictive permissions with the command "chmod 600 file2".
  5211. An other solution is to set the environment variable IMAPSYNC_PASSWORD2
  5212. FIN_PASSFILE
  5213. my $user = $mysync->{ acc2 }->{ authuser } || $mysync->{ user2 } ;
  5214. my $host = $mysync->{ host2 } ;
  5215. my $prompt = "What's the password for $user" . ' at ' . "$host? (not visible while you type, then enter RETURN) " ;
  5216. $mysync->{password2} = ask_for_password( $prompt ) ;
  5217. } ;
  5218. if ( defined $mysync->{ passfile2 } ) {
  5219. if ( ! -e -r $mysync->{ passfile2 } ) {
  5220. myprint( "Failure: file from parameter --passfile2 $mysync->{ passfile2 } does not exist or is not readable\n" ) ;
  5221. $mysync->{nb_errors}++ ;
  5222. exit_clean( $mysync, $EX_NOINPUT ) ;
  5223. }
  5224. # passfile2 readable
  5225. $mysync->{password2} = firstline ( $mysync->{ passfile2 } ) ;
  5226. return ;
  5227. }
  5228. if ( $ENV{IMAPSYNC_PASSWORD2} ) {
  5229. $mysync->{password2} = $ENV{IMAPSYNC_PASSWORD2} ;
  5230. return ;
  5231. }
  5232. return ;
  5233. }
  5234. sub remove_tmp_files
  5235. {
  5236. my $mysync = shift or return ;
  5237. $mysync->{pidfile} or return ;
  5238. if ( -e $mysync->{pidfile} ) {
  5239. myprint( "Removing pidfile $mysync->{pidfile}\n" ) ;
  5240. unlink $mysync->{pidfile} ;
  5241. }
  5242. if ( -e $mysync->{abortfile} ) {
  5243. myprint( "Removing pidfile $mysync->{abortfile}\n" ) ;
  5244. unlink $mysync->{abortfile} ;
  5245. }
  5246. return ;
  5247. }
  5248. sub cleanup_before_exit
  5249. {
  5250. my $mysync = shift ;
  5251. remove_tmp_files( $mysync ) ;
  5252. if ( $mysync->{imap1} and $mysync->{imap1}->IsConnected() )
  5253. {
  5254. myprint( "Disconnecting from host1 $mysync->{ host1 } user1 $mysync->{ user1 }\n" ) ;
  5255. $mysync->{imap1}->logout( ) ;
  5256. }
  5257. if ( $mysync->{imap2} and $mysync->{imap2}->IsConnected() )
  5258. {
  5259. myprint( "Disconnecting from host2 $mysync->{ host2 } user2 $mysync->{ user2 }\n" ) ;
  5260. $mysync->{imap2}->logout( ) ;
  5261. }
  5262. if ( $mysync->{log} ) {
  5263. myprint( "Log file is $mysync->{logfile} ( to change it, use --logfile filepath ; or use --nolog to turn off logging )\n" ) ;
  5264. }
  5265. else
  5266. {
  5267. myprint( "No log file because of option --nolog\n" ) ;
  5268. }
  5269. if ( $mysync->{log} and $mysync->{logfile_handle} ) {
  5270. #print( "Closing $mysync->{ logfile }\n" ) ;
  5271. teefinish( $mysync ) ;
  5272. }
  5273. return ;
  5274. }
  5275. sub exit_most_errors
  5276. {
  5277. my $mysync = shift @ARG ;
  5278. myprint( errors_listing( $mysync ) ) ;
  5279. my $exit_value = $EXIT_VALUE_OF_ERR_TYPE{ $mysync->{most_common_error} } || $EXIT_CATCH_ALL ;
  5280. exit_clean( $mysync, $exit_value ) ;
  5281. return ;
  5282. }
  5283. sub exit_clean
  5284. {
  5285. my $mysync = shift @ARG ;
  5286. my $status = shift @ARG ;
  5287. my @messages = @ARG ;
  5288. if ( @messages )
  5289. {
  5290. myprint( @messages ) ;
  5291. }
  5292. myprint( "Exiting with return value $status ($EXIT_TXT{$status}) $mysync->{nb_errors}/$mysync->{errorsmax} nb_errors/max_errors PID $PROCESS_ID\n" ) ;
  5293. cleanup_before_exit( $mysync ) ;
  5294. exit $status ;
  5295. }
  5296. sub missing_option
  5297. {
  5298. my $mysync = shift ;
  5299. my $option = shift ;
  5300. $mysync->{nb_errors}++ ;
  5301. exit_clean( $mysync, $EX_USAGE, "$option option is mandatory, for help run $PROGRAM_NAME --help\n" ) ;
  5302. return ;
  5303. }
  5304. sub catch_ignore
  5305. {
  5306. my $mysync = shift ;
  5307. my $signame = shift ;
  5308. my $sigcounter = ++$mysync->{ sigcounter }{ $signame } ;
  5309. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ),
  5310. "). Received $sigcounter $signame signals so far. Thanks!\n" ) ;
  5311. do_and_print_stats( $mysync ) ;
  5312. return ;
  5313. }
  5314. sub catch_exit
  5315. {
  5316. my $mysync = shift ;
  5317. my $signame = shift || q{} ;
  5318. if ( $signame ) {
  5319. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ),
  5320. "). Asked to terminate\n" ) ;
  5321. if ( $mysync->{can_do_stats} ) {
  5322. do_and_print_stats( $mysync ) ;
  5323. myprint( "Ended by a signal $signame (my PID is $PROCESS_ID my PPID is ",
  5324. getppid( ), "). I am asked to terminate immediately.\n" ) ;
  5325. }
  5326. myprint( "You should resynchronize those accounts by running a sync again,\n",
  5327. "since some messages and entire folders might still be missing on host2.\n"
  5328. ) ;
  5329. ## no critic (RequireLocalizedPunctuationVars)
  5330. # Well, restore default action does not work well
  5331. $SIG{ $signame } = 'DEFAULT'; # restore default action
  5332. #$SIG{ 'TERM' } = 'DEFAULT'; # restore default action
  5333. # kill myself with $signame
  5334. # https://www.cons.org/cracauer/sigint.html
  5335. myprint( "Killing myself with signal $signame\n" ) ;
  5336. #cleanup_before_exit( $mysync ) ;
  5337. kill( $signame, $PROCESS_ID ) ;
  5338. #kill( 'TERM', $PROCESS_ID ) ;
  5339. #sleep 1 ;
  5340. #while ( 1 ) { } ;
  5341. $mysync->{nb_errors}++ ;
  5342. exit_clean( $mysync, $EXIT_BY_SIGNAL,
  5343. "Still there after killing myself with signal $signame...\n"
  5344. ) ;
  5345. }
  5346. else
  5347. {
  5348. $mysync->{nb_errors}++ ;
  5349. exit_clean( $mysync, $EXIT_BY_SIGNAL, "Exiting in catch_exit with no signal...\n" ) ;
  5350. }
  5351. return ;
  5352. }
  5353. sub catch_print
  5354. {
  5355. my $mysync = shift ;
  5356. my $signame = shift ;
  5357. my $sigcounter = ++$mysync->{ sigcounter }{ $signame } ;
  5358. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ),
  5359. "). Received $sigcounter $signame signals so far. Thanks!\n" ) ;
  5360. return ;
  5361. }
  5362. sub here_twice
  5363. {
  5364. my $mysync = shift ;
  5365. my $now = time ;
  5366. my $previous = $mysync->{lastcatch} || 0 ;
  5367. $mysync->{lastcatch} = $now ;
  5368. if ( $INTERVAL_TO_EXIT >= $now - $previous ) {
  5369. return $TRUE ;
  5370. }else{
  5371. return $FALSE ;
  5372. }
  5373. }
  5374. sub catch_reconnect
  5375. {
  5376. my $mysync = shift ;
  5377. my $signame = shift ;
  5378. if ( here_twice( $mysync ) ) {
  5379. myprint( "Got two signals $signame within $INTERVAL_TO_EXIT seconds. Exiting...\n" ) ;
  5380. catch_exit( $mysync, $signame ) ;
  5381. }else{
  5382. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ), ")\n",
  5383. "Hit 2 ctr-c within 2 seconds to exit the program\n",
  5384. "Hit only 1 ctr-c to reconnect to both imap servers\n",
  5385. ) ;
  5386. myprint( "For now only one signal $signame within $INTERVAL_TO_EXIT seconds.\n" ) ;
  5387. if ( ! defined $mysync->{imap1} ) { return ; }
  5388. if ( ! defined $mysync->{imap2} ) { return ; }
  5389. myprint( "Info: reconnecting to host1 imap server $mysync->{host1}\n" ) ;
  5390. $mysync->{imap1}->State( Mail::IMAPClient::Unconnected ) ;
  5391. $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  5392. if ( $mysync->{imap1}->reconnect( ) )
  5393. {
  5394. myprint( "Info: reconnected to host1 imap server $mysync->{host1}\n" ) ;
  5395. }
  5396. else
  5397. {
  5398. $mysync->{nb_errors}++ ;
  5399. exit_clean( $mysync, $EXIT_CONNECTION_FAILURE ) ;
  5400. }
  5401. myprint( "Info: reconnecting to host2 imap server\n" ) ;
  5402. $mysync->{imap2}->State( Mail::IMAPClient::Unconnected ) ;
  5403. $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  5404. if ( $mysync->{imap2}->reconnect( ) )
  5405. {
  5406. myprint( "Info: reconnected to host2 imap server $mysync->{host2}\n" ) ;
  5407. }
  5408. else
  5409. {
  5410. $mysync->{nb_errors}++ ;
  5411. exit_clean( $mysync, $EXIT_CONNECTION_FAILURE ) ;
  5412. }
  5413. myprint( "Info: reconnected to both imap servers\n" ) ;
  5414. }
  5415. return ;
  5416. }
  5417. sub install_signals
  5418. {
  5419. my $mysync = shift ;
  5420. if ( under_docker_context( $mysync ) )
  5421. {
  5422. # output( $mysync, "Under docker context so leaving signals as they are\n" ) ;
  5423. output( $mysync, "Under docker context so installing only signals to exit\n" ) ;
  5424. @{ $mysync->{ sigexit } } = ( defined( $mysync->{ sigexit } ) ) ? @{ $mysync->{ sigexit } } : ( 'INT', 'QUIT', 'TERM' ) ;
  5425. sig_install( $mysync, 'catch_exit', @{ $mysync->{ sigexit } } ) ;
  5426. }
  5427. else
  5428. {
  5429. # Unix signals
  5430. @{ $mysync->{ sigexit } } = ( defined( $mysync->{ sigexit } ) ) ? @{ $mysync->{ sigexit } } : ( 'QUIT', 'TERM' ) ;
  5431. @{ $mysync->{ sigreconnect } } = ( defined( $mysync->{ sigreconnect } ) ) ? @{ $mysync->{ sigreconnect } } : ( 'INT' ) ;
  5432. @{ $mysync->{ sigprint } } = ( defined( $mysync->{ sigprint } ) ) ? @{ $mysync->{ sigprint } } : ( 'HUP' ) ;
  5433. @{ $mysync->{ sigignore } } = ( defined( $mysync->{ sigignore } ) ) ? @{ $mysync->{ sigignore } } : ( ) ;
  5434. #local %SIG = %SIG ;
  5435. sig_install( $mysync, 'catch_exit', @{ $mysync->{ sigexit } } ) ;
  5436. sig_install( $mysync, 'catch_reconnect', @{ $mysync->{ sigreconnect } } ) ;
  5437. sig_install( $mysync, 'catch_print', @{ $mysync->{ sigprint } } ) ;
  5438. # --sigignore can override sigexit, sigreconnect and sigprint (for the same signals only)
  5439. sig_install( $mysync, 'catch_ignore', @{ $mysync->{ sigignore } } ) ;
  5440. # remove/add sleeping mechanism when receiving USR1 signal (except on Win32)
  5441. sig_install_toggle_sleep( $mysync ) ;
  5442. }
  5443. return ;
  5444. }
  5445. sub tests_reconnect_12_if_needed
  5446. {
  5447. note( 'Entering tests_reconnect_12_if_needed()' ) ;
  5448. my $mysync ;
  5449. $mysync->{imap1} = Mail::IMAPClient->new( ) ;
  5450. $mysync->{imap2} = Mail::IMAPClient->new( ) ;
  5451. $mysync->{imap1}->Server( 'test1.lamiral.info' ) ;
  5452. $mysync->{imap2}->Server( 'test2.lamiral.info' ) ;
  5453. is( 2, reconnect_12_if_needed( $mysync ), 'reconnect_12_if_needed: test1&test2 .lamiral.info => 1' ) ;
  5454. is( 1, $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_12_if_needed: test1.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  5455. is( 1, $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_12_if_needed: test2.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  5456. note( 'Leaving tests_reconnect_12_if_needed()' ) ;
  5457. return ;
  5458. }
  5459. sub reconnect_12_if_needed
  5460. {
  5461. my $mysync = shift ;
  5462. #return 2 ;
  5463. if ( ! reconnect_if_needed( $mysync->{imap1} ) ) {
  5464. return ;
  5465. }
  5466. if ( ! reconnect_if_needed( $mysync->{imap2} ) ) {
  5467. return ;
  5468. }
  5469. # both were good
  5470. return 2 ;
  5471. }
  5472. sub tests_reconnect_if_needed
  5473. {
  5474. note( 'Entering tests_reconnect_if_needed()' ) ;
  5475. my $myimap ;
  5476. is( undef, reconnect_if_needed( ), 'reconnect_if_needed: no args => undef' ) ;
  5477. is( undef, reconnect_if_needed( $myimap ), 'reconnect_if_needed: undef arg => undef' ) ;
  5478. $myimap = Mail::IMAPClient->new( ) ;
  5479. $myimap->Debug( 1 ) ;
  5480. is( undef, reconnect_if_needed( $myimap ), 'reconnect_if_needed: empty new Mail::IMAPClient => undef' ) ;
  5481. $myimap->Server( 'test.lamiral.info' ) ;
  5482. is( 1, reconnect_if_needed( $myimap ), 'reconnect_if_needed: test.lamiral.info => 1' ) ;
  5483. is( 1, $myimap->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_if_needed: test.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  5484. note( 'Leaving tests_reconnect_if_needed()' ) ;
  5485. return ;
  5486. }
  5487. sub reconnect_if_needed
  5488. {
  5489. # return undef upon failure.
  5490. # return 1 upon connection success, with or without reconnection.
  5491. my $imap = shift ;
  5492. if ( ! defined $imap ) { return ; }
  5493. if ( ! $imap->Server( ) ) { return ; }
  5494. if ( $imap->IsUnconnected( ) ) {
  5495. $imap->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  5496. if ( $imap->reconnect( ) ) {
  5497. return 1 ;
  5498. }
  5499. }else{
  5500. return 1 ;
  5501. }
  5502. # A last forced one
  5503. $imap->State( Mail::IMAPClient::Unconnected ) ;
  5504. $imap->reconnect( ) ;
  5505. $imap->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  5506. if ( $imap->noop ) {
  5507. # NOOP is ok
  5508. return 1 ;
  5509. }
  5510. return ;
  5511. }
  5512. sub justconnect
  5513. {
  5514. my $mysync = shift ;
  5515. my $justconnect1 = justconnect1( $sync ) ;
  5516. my $justconnect2 = justconnect2( $sync ) ;
  5517. return "$justconnect1 $justconnect2";
  5518. }
  5519. sub justconnect1
  5520. {
  5521. my $mysync = shift ;
  5522. if ( $mysync->{host1} )
  5523. {
  5524. myprint( "Host1: Will just connect to $mysync->{host1} without login\n" ) ;
  5525. $mysync->{imap1} = connect_imap(
  5526. $mysync->{host1}, $mysync->{port1},
  5527. $mysync->{ssl1}, $mysync->{tls1},
  5528. $mysync->{ acc1 } ) ;
  5529. imap_id( $mysync, $mysync->{imap1}, $mysync->{ acc1 }->{ Side } ) ;
  5530. $mysync->{imap1}->logout( ) ;
  5531. return $mysync->{host1} ;
  5532. }
  5533. return q{} ;
  5534. }
  5535. sub justconnect2
  5536. {
  5537. my $mysync = shift ;
  5538. if ( $mysync->{host2} )
  5539. {
  5540. myprint( "Host2: Will just connect to $mysync->{host2} without login\n" ) ;
  5541. $mysync->{imap2} = connect_imap(
  5542. $mysync->{host2}, $mysync->{port2},
  5543. $mysync->{ssl2}, $mysync->{tls2},
  5544. $mysync->{ acc2 } ) ;
  5545. imap_id( $mysync, $mysync->{imap2}, $mysync->{ acc2 }->{ Side } ) ;
  5546. $mysync->{imap2}->logout( ) ;
  5547. return $mysync->{host2} ;
  5548. }
  5549. return q{} ;
  5550. }
  5551. sub skip_macosx
  5552. {
  5553. #return ;
  5554. # hostname used to be macosx.polarhome.com
  5555. return( 'macosx' eq hostname( ) && ( 'darwin' eq $OSNAME ) ) ;
  5556. }
  5557. sub skip_macosx_binary
  5558. {
  5559. #return ;
  5560. return( skip_macosx( ) && ( $PROGRAM_NAME =~ m{imapsync_bin_Darwin} ) ) ;
  5561. }
  5562. sub tests_mailimapclient_connect
  5563. {
  5564. note( 'Entering tests_mailimapclient_connect()' ) ;
  5565. my $imap ;
  5566. # ipv4
  5567. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv4: new' ) ;
  5568. is( 'Mail::IMAPClient', ref( $imap ), 'mailimapclient_connect ipv4: ref is Mail::IMAPClient' ) ;
  5569. # Mail::IMAPClient 3.40 die on this... So we skip it, thanks to "mature" IO::Socket::IP
  5570. # Mail::IMAPClient 3.42 is ok so this test is back.
  5571. is( undef, $imap->connect( ), 'mailimapclient_connect ipv4: connect with no server => failure' ) ;
  5572. is( 'test.lamiral.info', $imap->Server( 'test.lamiral.info' ), 'mailimapclient_connect ipv4: setting Server(test.lamiral.info)' ) ;
  5573. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4: setting Debug( 1 )' ) ;
  5574. is( 143, $imap->Port( 143 ), 'mailimapclient_connect ipv4: setting Port( 143 )' ) ;
  5575. is( 10, $imap->Timeout( 10 ), 'mailimapclient_connect ipv4: setting Timeout( 10 )' ) ;
  5576. like( ref( $imap->connect( ) ), qr/IO::Socket::INET|IO::Socket::IP/, 'mailimapclient_connect ipv4: connect to test.lamiral.info' ) ;
  5577. like( $imap->logout( ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv4: logout' ) ;
  5578. is( undef, undef $imap, 'mailimapclient_connect ipv4: free variable' ) ;
  5579. # ipv4 + ssl
  5580. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv4 + ssl: new' ) ;
  5581. is( 'test.lamiral.info', $imap->Server( 'test.lamiral.info' ), 'mailimapclient_connect ipv4 + ssl: setting Server(test.lamiral.info)' ) ;
  5582. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4 + ssl: setting Debug( 1 )' ) ;
  5583. ok( $imap->Ssl( [ SSL_verify_mode => SSL_VERIFY_NONE, SSL_cipher_list => 'DEFAULT:!DH' ] ), 'mailimapclient_connect ipv4 + ssl: setting Ssl( SSL_VERIFY_NONE )' ) ;
  5584. is( 993, $imap->Port( 993 ), 'mailimapclient_connect ipv4 + ssl: setting Port( 993 )' ) ;
  5585. like( ref( $imap->connect( ) ), qr/IO::Socket::SSL/, 'mailimapclient_connect ipv4 + ssl: connect to test.lamiral.info' ) ;
  5586. like( $imap->logout( ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv4 + ssl: logout in ssl does not cause failure' ) ;
  5587. is( undef, undef $imap, 'mailimapclient_connect ipv4 + ssl: free variable' ) ;
  5588. # ipv6 + ssl
  5589. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv6 + ssl: new' ) ;
  5590. is( 'petiteipv6.lamiral.info', $imap->Server( 'petiteipv6.lamiral.info' ), 'mailimapclient_connect ipv6 + ssl: setting Server petiteipv6.lamiral.info' ) ;
  5591. is( 10, $imap->Timeout( 10 ), 'mailimapclient_connect ipv6: setting Timeout( 10 )' ) ;
  5592. ok( $imap->Ssl( [ SSL_verify_mode => SSL_VERIFY_NONE, SSL_cipher_list => 'DEFAULT:!DH' ] ), 'mailimapclient_connect ipv6 + ssl: setting Ssl( SSL_VERIFY_NONE )' ) ;
  5593. is( 993, $imap->Port( 993 ), 'mailimapclient_connect ipv6 + ssl: setting Port( 993 )' ) ;
  5594. SKIP: {
  5595. if (
  5596. 'CUILLERE' eq hostname()
  5597. or
  5598. skip_macosx()
  5599. or
  5600. -e '/.dockerenv'
  5601. or
  5602. 'pcHPDV7-HP' eq hostname()
  5603. )
  5604. {
  5605. skip( 'Tests avoided on CUILLERE/pcHPDV7-HP/macosx.polarhome.com/docker cannot do ipv6', 4 ) ;
  5606. }
  5607. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4 + ssl: setting Debug( 1 )' ) ;
  5608. # It sounds stupid but it avoids failures on the next test about $imap->connect
  5609. is( '2a01:e34:ecde:70d0:223:54ff:fec2:36d7', resolv( 'petiteipv6.lamiral.info' ), 'resolv: petiteipv6.lamiral.info => 2001:41d0:8:bebd::1' ) ;
  5610. like( ref( $imap->connect( ) ), qr/IO::Socket::SSL/, 'mailimapclient_connect ipv6 + ssl: connect to petiteipv6.lamiral.info' ) ;
  5611. # This one is ok on petite, not on ks2, do not know why, so commented.
  5612. like( ref( $imap->logout( ) ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv6 + ssl: logout in ssl is ok on petiteipv6.lamiral.info' ) ;
  5613. }
  5614. is( undef, undef $imap, 'mailimapclient_connect ipv6 + ssl: free variable' ) ;
  5615. note( 'Leaving tests_mailimapclient_connect()' ) ;
  5616. return ;
  5617. }
  5618. sub tests_mailimapclient_connect_bug
  5619. {
  5620. note( 'Entering tests_mailimapclient_connect_bug()' ) ;
  5621. my $imap ;
  5622. # ipv6
  5623. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect_bug ipv6: new' ) ;
  5624. is( 'ks6ipv6.lamiral.info', $imap->Server( 'ks6ipv6.lamiral.info' ), 'mailimapclient_connect_bug ipv6: setting Server(ks6ipv6.lamiral.info)' ) ;
  5625. is( 143, $imap->Port( 143 ), 'mailimapclient_connect_bug ipv6: setting Port( 993 )' ) ;
  5626. SKIP: {
  5627. if (
  5628. 'CUILLERE' eq hostname()
  5629. or
  5630. skip_macosx()
  5631. or
  5632. -e '/.dockerenv'
  5633. or
  5634. 'pcHPDV7-HP' eq hostname()
  5635. )
  5636. {
  5637. skip( 'Tests avoided on CUILLERE/pcHPDV7-HP/macosx.polarhome.com/docker cannot do ipv6', 1 ) ;
  5638. }
  5639. like( ref( $imap->connect( ) ), qr/IO::Socket::INET/, 'mailimapclient_connect_bug ipv6: connect to ks6ipv6.lamiral.info' )
  5640. or diag( 'mailimapclient_connect_bug ipv6: ', $imap->LastError( ), $!, ) ;
  5641. }
  5642. #is( $imap->logout( ), undef, 'mailimapclient_connect_bug ipv6: logout in ssl causes failure' ) ;
  5643. is( undef, undef $imap, 'mailimapclient_connect_bug ipv6: free variable' ) ;
  5644. note( 'Leaving tests_mailimapclient_connect_bug()' ) ;
  5645. return ;
  5646. }
  5647. sub tests_connect_socket
  5648. {
  5649. note( 'Entering tests_connect_socket()' ) ;
  5650. is( undef, connect_socket( ), 'connect_socket: no args' ) ;
  5651. my $socket ;
  5652. my $imap ;
  5653. SKIP: {
  5654. if (
  5655. 'CUILLERE' eq hostname()
  5656. or
  5657. skip_macosx()
  5658. or
  5659. -e '/.dockerenv'
  5660. or
  5661. 'pcHPDV7-HP' eq hostname()
  5662. )
  5663. {
  5664. skip( 'Tests avoided on CUILLERE/pcHPDV7-HP/macosx.polarhome.com/docker cannot do ipv6', 2 ) ;
  5665. }
  5666. $socket = IO::Socket::INET6->new(
  5667. PeerAddr => 'ks6ipv6.lamiral.info',
  5668. PeerPort => 143,
  5669. ) ;
  5670. ok( $imap = connect_socket( $socket ), 'connect_socket: ks6ipv6.lamiral.info port 143 IO::Socket::INET6' ) ;
  5671. #$imap->Debug( 1 ) ;
  5672. # myprint( $imap->capability( ) ) ;
  5673. if ( $imap ) {
  5674. $imap->logout( ) ;
  5675. }
  5676. $IO::Socket::SSL::DEBUG = 4 ;
  5677. $socket = IO::Socket::SSL->new(
  5678. PeerHost => 'ks6ipv6.lamiral.info',
  5679. PeerPort => 993,
  5680. SSL_verify_mode => SSL_VERIFY_NONE,
  5681. SSL_cipher_list => 'DEFAULT:!DH',
  5682. ) ;
  5683. # myprint( $socket ) ;
  5684. ok( $imap = connect_socket( $socket ), 'connect_socket: ks6ipv6.lamiral.info port 993 IO::Socket::SSL' ) ;
  5685. #$imap->Debug( 1 ) ;
  5686. # myprint( $imap->capability( ) ) ;
  5687. # $socket->close( ) ;
  5688. if ( $imap ) {
  5689. $socket->close( ) ;
  5690. }
  5691. #$socket->close(SSL_no_shutdown => 1) ;
  5692. #$imap->logout( ) ;
  5693. #myprint( "\n" ) ;
  5694. #$imap->logout( ) ;
  5695. }
  5696. note( 'Leaving tests_connect_socket()' ) ;
  5697. return ;
  5698. }
  5699. sub connect_socket
  5700. {
  5701. my( $socket ) = @ARG ;
  5702. if ( ! defined $socket ) { return ; }
  5703. my $host = $socket->peerhost( ) ;
  5704. my $port = $socket->peerport( ) ;
  5705. #print "socket->peerhost: ", $socket->peerhost( ), "\n" ;
  5706. #print "socket->peerport: ", $socket->peerport( ), "\n" ;
  5707. my $imap = Mail::IMAPClient->new( ) ;
  5708. $imap->Socket( $socket ) ;
  5709. my $banner = $imap->Results()->[0] ;
  5710. #myprint( "banner: $banner" ) ;
  5711. return $imap ;
  5712. }
  5713. sub tests_probe_imapssl
  5714. {
  5715. note( 'Entering tests_probe_imapssl()' ) ;
  5716. is( undef, probe_imapssl( ), 'probe_imapssl: no args => undef' ) ;
  5717. is( undef, probe_imapssl( 'unknown' ), 'probe_imapssl: unknown => undef' ) ;
  5718. note( "hostname is: ", hostname() ) ;
  5719. SKIP: {
  5720. if (
  5721. 'CUILLERE' eq hostname()
  5722. or
  5723. skip_macosx()
  5724. or
  5725. -e '/.dockerenv'
  5726. or
  5727. 'pcHPDV7-HP' eq hostname()
  5728. )
  5729. {
  5730. skip( 'Tests avoided on CUILLERE or pcHPDV7-HP or Mac or docker: cannot do ipv6', 0 ) ;
  5731. }
  5732. # fed up with this one
  5733. #like( probe_imapssl( 'ks6ipv6.lamiral.info' ), qr/^\* OK/, 'probe_imapssl: ks6ipv6.lamiral.info matches "* OK"' ) ;
  5734. } ;
  5735. # It sounds stupid but it avoids failures on the next test about $imap->connect
  5736. ok( resolv( 'imap.gmail.com' ), 'resolv: imap.gmail.com => something' ) ;
  5737. like( probe_imapssl( 'imap.gmail.com' ), qr/^\* OK/, 'probe_imapssl: imap.gmail.com matches "* OK"' ) ;
  5738. like( probe_imapssl( 'test1.lamiral.info' ), qr/^\* OK/, 'probe_imapssl: test1.lamiral.info matches "* OK"' ) ;
  5739. note( 'Leaving tests_probe_imapssl()' ) ;
  5740. return ;
  5741. }
  5742. sub probe_imapssl
  5743. {
  5744. my $host = shift ;
  5745. if ( ! $host ) { return ; }
  5746. $sync->{ debug } and $IO::Socket::SSL::DEBUG = 4 ;
  5747. my $socket = IO::Socket::SSL->new(
  5748. PeerHost => $host,
  5749. PeerPort => $IMAP_SSL_PORT,
  5750. SSL_verifycn_scheme => 'imap',
  5751. SSL_verify_mode => $SSL_VERIFY_POLICY,
  5752. SSL_cipher_list => 'DEFAULT:!DH',
  5753. ) ;
  5754. if ( ! $socket ) { return ; }
  5755. $sync->{ debug } and print "socket: $socket\n" ;
  5756. my $banner ;
  5757. $socket->sysread( $banner, 65_536 ) ;
  5758. $sync->{ debug } and print "banner: $banner" ;
  5759. $socket->close( ) ;
  5760. return $banner ;
  5761. }
  5762. sub connect_imap
  5763. {
  5764. my( $host, $port, $ssl, $tls, $acc ) = @_ ;
  5765. my $imap = Mail::IMAPClient->new( ) ;
  5766. if ( $ssl ) { set_ssl( $imap, $acc ) }
  5767. $imap->Server( $host ) ;
  5768. $imap->Port( $port ) ;
  5769. $imap->Debug( $acc->{ debugimap } ) ;
  5770. $imap->Timeout( $acc->{ timeout } ) ;
  5771. my $side = lc $acc->{ Side } ;
  5772. myprint( "$acc->{ Side }: connecting on $side [$host] port [$port]\n" ) ;
  5773. if ( ! $imap->connect( ) )
  5774. {
  5775. $sync->{nb_errors}++ ;
  5776. exit_clean( $sync, $EXIT_CONNECTION_FAILURE,
  5777. "$acc->{ Side }: Can not open imap connection on [$host]: ",
  5778. $imap->LastError,
  5779. " $OS_ERROR\n"
  5780. ) ;
  5781. }
  5782. myprint( "$acc->{ Side } IP address: ", $imap->Socket->peerhost(), "\n" ) ;
  5783. my $banner = $imap->Results()->[0] ;
  5784. myprint( "$acc->{ Side } banner: $banner" ) ;
  5785. myprint( "$acc->{ Side } capability: ", join(q{ }, @{ $imap->capability() || [] }), "\n" ) ;
  5786. if ( $tls ) {
  5787. set_tls( $imap, $acc ) ;
  5788. if ( ! $imap->starttls( ) )
  5789. {
  5790. $sync->{nb_errors}++ ;
  5791. exit_clean( $sync, $EXIT_TLS_FAILURE,
  5792. "$acc->{ Side }: Can not go to tls encryption on $side [$host]:",
  5793. $imap->LastError, "\n"
  5794. ) ;
  5795. }
  5796. myprint( "$acc->{ Side }: Socket successfully converted to SSL\n" ) ;
  5797. }
  5798. return( $imap ) ;
  5799. }
  5800. sub tests_login_imap
  5801. {
  5802. note( 'Entering tests_login_imap()' ) ;
  5803. is( undef, login_imap( ), 'login_imap: no args => undef' ) ;
  5804. SKIP: {
  5805. if ( skip_macosx_binary( ) )
  5806. {
  5807. skip( 'Tests avoided only on binary on host polarhome macosx, no clue "ssl3_get_server_certificate:certificate verify failed"', 11 ) ;
  5808. }
  5809. else{
  5810. my $myimap ;
  5811. my $acc = {} ;
  5812. $acc->{ Side } = 'HostK' ;
  5813. $acc->{ authmech } = 'LOGIN' ;
  5814. #$IO::Socket::SSL::DEBUG = 4 ;
  5815. # Each month (trimester?):
  5816. # echo | openssl s_client -crlf -connect test1.lamiral.info:993
  5817. # ...
  5818. # certificate has expired
  5819. # Fix:
  5820. # ssh root@test1.lamiral.info 'apt update && apt upgrade && /etc/init.d/dovecot restart'
  5821. ok(
  5822. $myimap = login_imap( 'test1.lamiral.info', 993, 'test1', 'secret1',
  5823. 1, undef,
  5824. 1, 100, $acc, {},
  5825. ), 'login_imap: test1.lamiral.info test1 ssl' ) ;
  5826. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'login_imap: test1.lamiral.info test1 ssl IsAuthenticated' ) ;
  5827. ok(
  5828. $myimap = login_imap( 'test1.lamiral.info', 143, 'test1', 'secret1',
  5829. 0, undef,
  5830. 1, 100, $acc, {},
  5831. ), 'login_imap: test1.lamiral.info test1 tls' ) ;
  5832. ok( $myimap && $myimap->IsAuthenticated( ), 'login_imap: test1.lamiral.info test1 tls IsAuthenticated' ) ;
  5833. #$IO::Socket::SSL::DEBUG = 4 ;
  5834. $acc->{sslargs} = { SSL_version => 'SSLv2' } ;
  5835. # SSLv2 not supported
  5836. is(
  5837. undef, $myimap = login_imap( 'test1.lamiral.info', 143, 'test1', 'secret1',
  5838. 0, undef,
  5839. 1, 100, $acc, {},
  5840. ), 'login_imap: test1.lamiral.info test1 tls SSLv2 not supported' ) ;
  5841. #SSL_verify_mode => 1
  5842. #SSL_version => 'TLSv1_1'
  5843. # I have left ? exit_clean to be replaced by errors_incr( $mysync, 'error message' )
  5844. # 1 in login_imap()
  5845. my $mysync = {} ;
  5846. $acc = {} ;
  5847. $acc->{ Side } = 'Host2' ;
  5848. $acc->{ authmech } = 'LOGIN' ;
  5849. is(
  5850. undef, login_imap( 'noresol.lamiral.info', 143, 'test1', 'secret1',
  5851. 0, undef,
  5852. 1, 100, $acc, $mysync,
  5853. ), 'login_imap: noresol.lamiral.info undef' ) ;
  5854. is( 'ERR_CONNECTION_FAILURE_HOST2', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host2 noresol.lamiral.info => ERR_CONNECTION_FAILURE_HOST2' ) ;
  5855. # authentication failure for user2
  5856. $mysync = {} ;
  5857. is(
  5858. undef, login_imap( 'test1.lamiral.info', 143, 'test1', 'Ce crétin',
  5859. 0, undef,
  5860. 1, 100, $acc, $mysync,
  5861. ), 'login_imap: user2 bad passord => undef' ) ;
  5862. is( 'ERR_AUTHENTICATION_FAILURE_USER2', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host2 bad password => ERR_AUTHENTICATION_FAILURE_USER2' ) ;
  5863. # authentication failure for user1
  5864. $mysync = {} ;
  5865. $acc = {} ;
  5866. $acc->{ Side } = 'Host1' ;
  5867. $acc->{ authmech } = 'LOGIN' ;
  5868. is(
  5869. undef, login_imap( 'test1.lamiral.info', 143, 'test1', 'Ce crétin',
  5870. 0, undef,
  5871. 1, 100, $acc, $mysync,
  5872. ), 'login_imap: user1 bad passord => undef' ) ;
  5873. is( 'ERR_AUTHENTICATION_FAILURE_USER1', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host1 bad password => ERR_AUTHENTICATION_FAILURE_USER1' ) ;
  5874. }
  5875. }
  5876. note( 'Leaving tests_login_imap()' ) ;
  5877. return ;
  5878. }
  5879. sub oauthgenerateaccess
  5880. {
  5881. if ( "petite" eq hostname() )
  5882. {
  5883. myprint( "oauthgenerateaccess\n" ) ;
  5884. my @output = backtick( 'cd oauth2 && pwd && ./generate_gmail_token imapsync.gl0@gmail.com' ) ;
  5885. myprint( @output ) ;
  5886. }
  5887. return ;
  5888. }
  5889. sub tests_login_imap_oauth
  5890. {
  5891. note( 'Entering tests_login_imap_oauth()' ) ;
  5892. oauthgenerateaccess() ;
  5893. SKIP: {
  5894. if ( skip_macosx_binary( ) )
  5895. {
  5896. skip( 'Tests avoided only on binary on host polarhome macosx, no clue "ssl3_get_server_certificate:certificate verify failed"', 6 ) ;
  5897. }
  5898. else
  5899. {
  5900. my $mysync ;
  5901. my $acc ;
  5902. # oauthdirect authentication failure for user2
  5903. $mysync = {} ;
  5904. $acc = {} ;
  5905. $acc->{ oauthdirect } = 'caca2' ;
  5906. $acc->{ debugimap } = 1 ;
  5907. $mysync->{ showpasswords } = 1 ;
  5908. $acc->{ Side } = 'Host2' ;
  5909. $acc->{ authmech } = 'QQQ' ;
  5910. is(
  5911. undef, login_imap( 'imap.gmail.com', 993, 'test1', 'Ce crétin',
  5912. 1, undef,
  5913. 1, 100, $acc, $mysync,
  5914. ), 'login_imap: user2 bad oauthdirect => undef' ) ;
  5915. is( 'ERR_AUTHENTICATION_FAILURE_USER2', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host2 bad oauthdirect => ERR_AUTHENTICATION_FAILURE_USER2' ) ;
  5916. # oauthdirect authentication failure for user1
  5917. $mysync = {} ;
  5918. $acc = {} ;
  5919. $acc->{ Side } = 'Host1' ;
  5920. $acc->{ oauthdirect } = 'caca1' ;
  5921. $acc->{ debugimap } = 1 ;
  5922. $mysync->{ showpasswords } = 1 ;
  5923. $acc->{ authmech } = 'QQQ' ;
  5924. is(
  5925. undef, login_imap( 'imap.gmail.com', 993, 'test1', 'Ce crétin',
  5926. 1, undef,
  5927. 1, 100, $acc, $mysync,
  5928. ), 'login_imap: user1 bad oauthdirect => undef' ) ;
  5929. is( 'ERR_AUTHENTICATION_FAILURE_USER1', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host1 bad oauthdirect => ERR_AUTHENTICATION_FAILURE_USER1' ) ;
  5930. # oauthdirect authentication failure for user1
  5931. $mysync = {} ;
  5932. $acc = {} ;
  5933. $acc->{ Side } = 'Host1' ;
  5934. $acc->{ oauthdirect } = '' ;
  5935. $acc->{ debugimap } = 1 ;
  5936. $mysync->{ showpasswords } = 1 ;
  5937. $acc->{ authmech } = 'QQQ' ;
  5938. is(
  5939. undef, login_imap( 'imap.gmail.com', 993, 'test1', 'Ce crétin',
  5940. 1, undef,
  5941. 1, 100, $acc, $mysync,
  5942. ), 'login_imap: user1 bad oauthdirect => undef' ) ;
  5943. is( 'ERR_AUTHENTICATION_FAILURE_USER1', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host1 no oauthdirect value => ERR_AUTHENTICATION_FAILURE_USER1' ) ;
  5944. }
  5945. }
  5946. # oauthdirect authentication success for user1
  5947. SKIP: {
  5948. if ( ! -r 'oauth2/D_oauth2_oauthdirect_imapsync.gl0@gmail.com.txt' )
  5949. {
  5950. skip( 'oauthdirect: no oauthdirect file', 2 ) ;
  5951. }
  5952. my $myimap ;
  5953. my $mysync = {} ;
  5954. my $acc = {} ;
  5955. $acc->{ Side } = 'Host1' ;
  5956. $acc->{ oauthdirect } = 'oauth2/D_oauth2_oauthdirect_imapsync.gl0@gmail.com.txt' ;
  5957. $acc->{ debugimap } = 1 ;
  5958. $mysync->{ showpasswords } = 1 ;
  5959. $acc->{ authmech } = 'QQQ' ;
  5960. isa_ok(
  5961. $myimap = login_imap( 'imap.gmail.com', 993, 'user_useless', 'password_useless',
  5962. 1, undef,
  5963. 1, 100, $acc, $mysync,
  5964. ), 'Mail::IMAPClient', 'login_imap: user1 good oauthdirect => Mail::IMAPClient' ) ;
  5965. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'login_imap: gmail oauth2 IsAuthenticated' ) ;
  5966. }
  5967. # oauthaccesstoken authentication success for user1
  5968. SKIP: {
  5969. if ( ! -r 'oauth2/D_oauth2_access_token_imapsync.gl0@gmail.com.txt' )
  5970. {
  5971. skip( 'oauthaccesstoken: no access_token file', 2 ) ;
  5972. }
  5973. my $myimap ;
  5974. my $mysync = {} ;
  5975. my $acc = {} ;
  5976. $acc->{ Side } = 'Host1' ;
  5977. $acc->{ oauthaccesstoken } = 'oauth2/D_oauth2_access_token_imapsync.gl0@gmail.com.txt' ;
  5978. $acc->{ debugimap } = 1 ;
  5979. $mysync->{ showpasswords } = 1 ;
  5980. $acc->{ authmech } = 'QQQ' ;
  5981. isa_ok(
  5982. $myimap = login_imap( 'imap.gmail.com', 993, 'imapsync.gl0@gmail.com', 'password_useless',
  5983. 1, undef,
  5984. 1, 100, $acc, $mysync,
  5985. ), 'Mail::IMAPClient', 'login_imap: user1 good oauthaccesstoken => Mail::IMAPClient' ) ;
  5986. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'login_imap: gmail oauth2 oauthaccesstoken IsAuthenticated' ) ;
  5987. }
  5988. note( 'Leaving tests_login_imap_oauth()' ) ;
  5989. return ;
  5990. }
  5991. sub login_imap
  5992. {
  5993. my @allargs = @_ ;
  5994. my(
  5995. $host, $port, $user, $password,
  5996. $ssl, $tls,
  5997. $uid, $split, $acc, $mysync ) = @allargs ;
  5998. if ( ! all_defined( $host, $port, $user, $acc->{ Side } ) )
  5999. {
  6000. return ;
  6001. }
  6002. my $side = lc $acc->{ Side } ;
  6003. myprint( "$acc->{ Side }: connecting and login on $side [$host] port [$port] with user [$user]\n" ) ;
  6004. my $imap = init_imap( @allargs ) ;
  6005. if ( ! $imap->connect() )
  6006. {
  6007. my $error = "$acc->{ Side } failure: can not open imap connection on $side [$host] with user [$user]: "
  6008. . $imap->LastError . " $OS_ERROR\n" ;
  6009. errors_incr( $mysync, $error ) ;
  6010. return ;
  6011. }
  6012. myprint( "$acc->{ Side } IP address: ", $imap->Socket->peerhost(), "\n" ) ;
  6013. my $banner = $imap->Results()->[0] ;
  6014. myprint( "$acc->{ Side } banner: $banner" ) ;
  6015. myprint( "$acc->{ Side } capability before authentication: ", join(q{ }, @{ $imap->capability() || [] }), "\n" ) ;
  6016. if ( (! $ssl) and (! defined $tls ) and $imap->has_capability( 'STARTTLS' ) ) {
  6017. myprint( "$acc->{ Side }: going to ssl because STARTTLS is in CAPABILITY. Use --notls1 or --notls2 to avoid that behavior\n" ) ;
  6018. $tls = 1 ;
  6019. }
  6020. #myprint( Data::Dumper->Dump( [ @allargs ] ) ) ;
  6021. if ( $tls ) {
  6022. set_tls( $imap, $acc ) ;
  6023. if ( ! $imap->starttls( ) )
  6024. {
  6025. my $error = "$acc->{ Side } failure: Can not go to tls encryption on $side [$host]: "
  6026. . $imap->LastError . "\n" ;
  6027. errors_incr( $mysync, $error ) ;
  6028. return ;
  6029. }
  6030. myprint( "$acc->{ Side }: Socket successfully converted to SSL\n" ) ;
  6031. }
  6032. if ( $acc->{ authmech } eq 'PREAUTH' ) {
  6033. if ( $imap->IsAuthenticated( ) ) {
  6034. $imap->Socket ;
  6035. myprintf("%s: Assuming PREAUTH for %s\n", $acc->{ Side }, $imap->Server ) ;
  6036. }else{
  6037. $mysync->{nb_errors}++ ;
  6038. exit_clean(
  6039. $mysync, $EXIT_AUTHENTICATION_FAILURE,
  6040. "$acc->{ Side } failure: error login on $side [$host] with user [$user] auth [PREAUTH]\n"
  6041. ) ;
  6042. }
  6043. }
  6044. if ( authenticate_imap( $imap, @allargs ) )
  6045. {
  6046. myprint( "$acc->{ Side }: success login on [$host] with user [$user] auth [$acc->{ authmech }] or [LOGIN]\n" ) ;
  6047. return( $imap ) ;
  6048. }
  6049. else
  6050. {
  6051. # The errors are already printed
  6052. myprint( "$acc->{ Side }: failed login on [$host] with user [$user] auth [$acc->{ authmech }]\n" ) ;
  6053. return ;
  6054. }
  6055. }
  6056. sub init_imap
  6057. {
  6058. my(
  6059. $host, $port, $user, $password,
  6060. $ssl, $tls,
  6061. $uid, $split, $acc, $mysync ) = @_ ;
  6062. my ( $imap ) ;
  6063. $imap = Mail::IMAPClient->new() ;
  6064. if ( $mysync->{ tee } )
  6065. {
  6066. # Well, it does not change anything, does it?
  6067. # It does when suppressing the hack with *STDERR
  6068. $imap->Debug_fh( $mysync->{ tee } ) ;
  6069. }
  6070. if ( $ssl ) { set_ssl( $imap, $acc ) }
  6071. if ( $tls ) { } # can not do set_tls() here because connect() will directly do a STARTTLS
  6072. $imap->Clear( 1 ) ;
  6073. $imap->Server( $host ) ;
  6074. $imap->Port( $port ) ;
  6075. $imap->Fast_io( $acc->{ fastio } ) ;
  6076. $imap->Buffer( $buffersize || $DEFAULT_BUFFER_SIZE ) ;
  6077. $imap->Uid( $uid ) ;
  6078. $imap->Peek( 1 ) ;
  6079. $imap->Debug( $acc->{ debugimap } ) ;
  6080. if ( $mysync->{ showpasswords } ) {
  6081. $imap->Showcredentials( 1 ) ;
  6082. }
  6083. defined $acc->{ timeout } and $imap->Timeout( $acc->{ timeout } ) ;
  6084. if ( defined $acc->{ reconnectretry } )
  6085. {
  6086. $imap->Reconnectretry( $acc->{ reconnectretry } ) ;
  6087. }
  6088. $imap->{IMAPSYNC_RECONNECT_COUNT} = 0 ;
  6089. $imap->Ignoresizeerrors( $allowsizemismatch ) ;
  6090. $split and $imap->Maxcommandlength( $SPLIT_FACTOR * $split ) ;
  6091. return( $imap ) ;
  6092. }
  6093. sub authenticate_imap
  6094. {
  6095. my( $imap,
  6096. $host, $port, $user, $password,
  6097. $ssl, $tls,
  6098. $uid, $split, $acc, $mysync ) = @_ ;
  6099. check_capability( $imap, $acc->{ authmech }, $acc->{ Side } ) ;
  6100. $imap->User( $user ) ;
  6101. if ( defined $acc->{ domain } )
  6102. {
  6103. $imap->Domain( $acc->{ domain } ) ;
  6104. $mysync->{ debug } and myprint( "Domain: $acc->{ domain }\n" ) ;
  6105. }
  6106. $imap->Authuser( $acc->{ authuser } ) ;
  6107. $imap->Password( $password ) ;
  6108. if ( 'X-MASTERAUTH' eq $acc->{ authmech } )
  6109. {
  6110. xmasterauth( $imap ) ;
  6111. return 1 ;
  6112. }
  6113. if ( defined $acc->{ oauthdirect } )
  6114. {
  6115. $acc->{ authmech } = 'XOAUTH2 direct' ;
  6116. return( oauthdirect( $mysync, $acc, $imap, $host, $user ) ) ;
  6117. }
  6118. if ( defined $acc->{ oauthaccesstoken } )
  6119. {
  6120. $acc->{ authmech } = 'XOAUTH2 accesstoken' ;
  6121. return( oauthaccesstoken( $mysync, $acc, $imap, $host, $user ) ) ;
  6122. }
  6123. if ( $acc->{ proxyauth } ) {
  6124. $imap->Authmechanism(q{}) ;
  6125. $imap->User( $acc->{ authuser } ) ;
  6126. } else {
  6127. $imap->Authmechanism( $acc->{ authmech } ) unless ( $acc->{ authmech } eq 'LOGIN' or $acc->{ authmech } eq 'PREAUTH' ) ;
  6128. }
  6129. $imap->Authcallback(\&xoauth2) if ( 'XOAUTH2' eq $acc->{ authmech } ) ;
  6130. $imap->Authcallback(\&plainauth) if ( ( 'PLAIN' eq $acc->{ authmech } ) or ( 'EXTERNAL' eq $acc->{ authmech } ) ) ;
  6131. unless ( $acc->{ authmech } eq 'PREAUTH' or $imap->login( ) ) {
  6132. my $info = "$acc->{ Side } failure: Error login on [$host] with user [$user] auth" ;
  6133. my $einfo = imap_last_error( $imap ) ;
  6134. my $error = "$info [$acc->{ authmech }]: $einfo\n" ;
  6135. if ( ( $acc->{ authmech } eq 'LOGIN' ) or $imap->IsUnconnected( ) or $acc->{ authuser } ) {
  6136. $acc->{ authuser } ||= "" ;
  6137. myprint( "$acc->{ Side } info: authmech [$acc->{ authmech }] user [$user] authuser [$acc->{ authuser }] IsUnconnected [", $imap->IsUnconnected( ), "]\n" ) ;
  6138. errors_incr( $mysync, $error ) ;
  6139. return ;
  6140. }else{
  6141. errors_incr( $mysync, $error ) ;
  6142. }
  6143. # It is not secure to try plain text LOGIN when another authmech failed
  6144. # but I do it anyway. This behavior is optional as option --notrylogin will skip it.
  6145. if ( $mysync->{ trylogin } )
  6146. {
  6147. myprint( "$acc->{ Side } info: trying LOGIN Auth mechanism on [$host] with user [$user]. Use option --notrylogin to avoid this second chance to login via LOGIN auth\n" ) ;
  6148. $imap->Authmechanism(q{}) ;
  6149. if ( ! $imap->login( ) )
  6150. {
  6151. failure_login( $mysync, $acc, 'LOGIN', $imap, $host, $user ) ;
  6152. return ;
  6153. }
  6154. else
  6155. {
  6156. myprint( "$acc->{ Side }: success login on [$host] with user [$user] auth [LOGIN] after [$acc->{ authmech }] failure\n" ) ;
  6157. }
  6158. }
  6159. else
  6160. {
  6161. myprint( "$acc->{ Side } info: not trying LOGIN Auth mechanism on [$host] with user [$user]. Use option --trylogin to have this second chance to login via LOGIN auth\n" ) ;
  6162. return ;
  6163. }
  6164. }
  6165. if ( $acc->{ proxyauth } ) {
  6166. if ( ! $imap->proxyauth( $user ) ) {
  6167. failure_proxyauth( $mysync, $acc, $acc->{ authmech }, $imap, $host, $user ) ;
  6168. return ;
  6169. }
  6170. }
  6171. return 1;
  6172. }
  6173. sub failure_login
  6174. {
  6175. my( $mysync, $acc, $authmech, $imap, $host, $user ) = @ARG ;
  6176. my $info = "$acc->{ Side } failure: Error login on [$host] with user [$user] auth" ;
  6177. my $einfo = imap_last_error( $imap ) ;
  6178. my $error = "$info [$authmech]: $einfo\n" ;
  6179. errors_incr( $mysync, $error ) ;
  6180. return ;
  6181. }
  6182. # failure_login and failure_proxyauth function are similar but
  6183. # variable $error so no factoring
  6184. sub failure_proxyauth
  6185. {
  6186. my( $mysync, $acc, $authmech, $imap, $host, $user ) = @ARG ;
  6187. my $info = "$acc->{ Side } failure: Error login on [$host] with user [$user] auth" ;
  6188. my $einfo = imap_last_error( $imap ) ;
  6189. my $error = "$info [$authmech] using proxy-login as [$acc->{ authuser }]: $einfo\n" ;
  6190. errors_incr( $mysync, $error ) ;
  6191. return ;
  6192. }
  6193. sub oauthdirect
  6194. {
  6195. my( $mysync, $acc, $imap, $host, $user ) = @_ ;
  6196. my $oauthdirect_str ;
  6197. if ( -f -r $acc->{ oauthdirect } )
  6198. {
  6199. $oauthdirect_str = firstline( $acc->{ oauthdirect } ) ;
  6200. }
  6201. else
  6202. {
  6203. $oauthdirect_str = $acc->{ oauthdirect } || 'Please define oauthdirect value' ;
  6204. }
  6205. if ( $imap->authenticate('XOAUTH2', sub { return $oauthdirect_str } ) )
  6206. {
  6207. return 1 ;
  6208. }
  6209. else
  6210. {
  6211. failure_login( $mysync, $acc, $acc->{ authmech }, $imap, $host, $user ) ;
  6212. return ;
  6213. }
  6214. return ;
  6215. }
  6216. sub oauthaccesstoken
  6217. {
  6218. my( $mysync, $acc, $imap, $host, $user ) = @_ ;
  6219. my $oauthaccesstoken_str ;
  6220. if ( -f -r $acc->{ oauthaccesstoken } )
  6221. {
  6222. $oauthaccesstoken_str = firstline( $acc->{ oauthaccesstoken } ) ;
  6223. }
  6224. else
  6225. {
  6226. $oauthaccesstoken_str = $acc->{ oauthaccesstoken } || 'Please define oauthaccesstoken value' ;
  6227. }
  6228. my $oauth_string = "user=" . $user . "\x01auth=Bearer ". $oauthaccesstoken_str . "\x01\x01" ;
  6229. #myprint "oauth_string: $oauth_string\n" ;
  6230. my $oauth_string_base64 = encode_base64( $oauth_string , '' ) ;
  6231. #myprint "oauth_string_base64: $oauth_string_base64\n" ;
  6232. my $oauthdirect_str = $oauth_string_base64 ;
  6233. if ( $imap->authenticate('XOAUTH2', sub { return $oauthdirect_str } ) )
  6234. {
  6235. return 1 ;
  6236. }
  6237. else
  6238. {
  6239. failure_login( $mysync, $acc, $acc->{ authmech }, $imap, $host, $user ) ;
  6240. return ;
  6241. }
  6242. return ;
  6243. }
  6244. sub check_capability
  6245. {
  6246. my( $imap, $authmech, $Side ) = @_ ;
  6247. if ( $imap->has_capability( "AUTH=$authmech" )
  6248. or $imap->has_capability( $authmech ) )
  6249. {
  6250. myprintf("%s: %s says it has CAPABILITY for AUTHENTICATE %s\n",
  6251. $Side, $imap->Server, $authmech) ;
  6252. return ;
  6253. }
  6254. if ( $authmech eq 'LOGIN' )
  6255. {
  6256. # Well, the warning is so common and useless that I prefer to remove it
  6257. # No more "... says it has NO CAPABILITY for AUTHENTICATE LOGIN"
  6258. return ;
  6259. }
  6260. myprintf( "%s: %s says it has NO CAPABILITY for AUTHENTICATE %s\n",
  6261. $Side, $imap->Server, $authmech ) ;
  6262. if ( $authmech eq 'PLAIN' )
  6263. {
  6264. myprint( "$Side: frequently PLAIN is only supported with SSL, try --ssl or --tls options\n" ) ;
  6265. }
  6266. return ;
  6267. }
  6268. sub set_ssl
  6269. {
  6270. my ( $imap, $acc ) = @_ ;
  6271. # SSL_version can be
  6272. # SSLv3 SSLv2 SSLv23 SSLv23:!SSLv2 (last one is the default in IO-Socket-SSL-1.953)
  6273. #
  6274. my $sslargs_hash = $acc->{sslargs} ;
  6275. my $sslargs_default = {
  6276. SSL_verify_mode => $SSL_VERIFY_POLICY,
  6277. SSL_verifycn_scheme => 'imap',
  6278. SSL_cipher_list => 'DEFAULT:!DH',
  6279. } ;
  6280. # initiate with default values
  6281. my %sslargs_mix = %{ $sslargs_default } ;
  6282. # now override with passed values
  6283. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  6284. # remove keys with undef values
  6285. foreach my $key ( keys %sslargs_mix ) {
  6286. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  6287. }
  6288. # back to an ARRAY
  6289. my @sslargs_mix = %sslargs_mix ;
  6290. #myprint( Data::Dumper->Dump( [ $sslargs_hash, $sslargs_default, \%sslargs_mix, \@sslargs_mix ] ) ) ;
  6291. $imap->Ssl( \@sslargs_mix ) ;
  6292. return ;
  6293. }
  6294. sub set_tls
  6295. {
  6296. my ( $imap, $acc ) = @_ ;
  6297. my $sslargs_hash = $acc->{sslargs} ;
  6298. my $sslargs_default = {
  6299. SSL_verify_mode => $SSL_VERIFY_POLICY,
  6300. SSL_cipher_list => 'DEFAULT:!DH',
  6301. } ;
  6302. #myprint( Data::Dumper->Dump( [ $acc, $sslargs_hash, $sslargs_default ] ) ) ;
  6303. # initiate with default values
  6304. my %sslargs_mix = %{ $sslargs_default } ;
  6305. # now override with passed values
  6306. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  6307. # remove keys with undef values
  6308. foreach my $key ( keys %sslargs_mix ) {
  6309. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  6310. }
  6311. # back to an ARRAY
  6312. my @sslargs_mix = %sslargs_mix ;
  6313. $imap->Starttls( \@sslargs_mix ) ;
  6314. return ;
  6315. }
  6316. sub plainauth
  6317. {
  6318. my $code = shift;
  6319. my $imap = shift;
  6320. my $string = mysprintf("%s\x00%s\x00%s", $imap->User,
  6321. $imap->Authuser, $imap->Password);
  6322. return encode_base64("$string", q{});
  6323. }
  6324. # Copy from https://github.com/imapsync/imapsync/pull/25/files
  6325. # Changes "use" pragmas to "require".
  6326. # The openssl system call shall be replaced by pure Perl and
  6327. # https://metacpan.org/pod/Crypt::OpenSSL::PKCS12
  6328. # Now the Joaquin Lopez code:
  6329. #
  6330. # Used this as an example: https://gist.github.com/gsainio/6322375
  6331. #
  6332. # And this as a reference: https://developers.google.com/accounts/docs/OAuth2ServiceAccount
  6333. # (note there is an http/rest tab, where the real info is hidden away... went on a witch hunt
  6334. # until I noticed that...)
  6335. #
  6336. # This is targeted at gmail to maintain compatibility after google's oauth1 service is deactivated
  6337. # on May 5th, 2015: https://developers.google.com/gmail/oauth_protocol
  6338. # If there are other oauth2 implementations out there, this would need to be modified to be
  6339. # compatible
  6340. #
  6341. # This is a good guide on setting up the google api/apps side of the equation:
  6342. # http://www.limilabs.com/blog/oauth2-gmail-imap-service-account
  6343. #
  6344. # 2016/05/27: Updated to support oauth/key data in the .json files Google now defaults to
  6345. # when creating gmail service accounts. They're easier to work with since they neither
  6346. # requiring decrypting nor specifying the oauth2 client id separately.
  6347. #
  6348. # If the password arg ends in .json, it will assume this new json method, otherwise it
  6349. # will fallback to the "oauth client id;.p12" format it was previously using.
  6350. sub xoauth2
  6351. {
  6352. require JSON::WebToken ;
  6353. require LWP::UserAgent ;
  6354. require HTML::Entities ;
  6355. require JSON ;
  6356. require JSON::WebToken::Crypt::RSA ;
  6357. require Crypt::OpenSSL::RSA ;
  6358. require Encode::Byte ;
  6359. require IO::Socket::SSL ;
  6360. my $code = shift;
  6361. my $imap = shift;
  6362. my ($iss,$key);
  6363. if( $imap->Password =~ /^(.*\.json)$/x )
  6364. {
  6365. my $json = JSON->new( ) ;
  6366. my $filename = $1;
  6367. $sync->{ debug } and myprint( "XOAUTH2 json file: $filename\n" ) ;
  6368. my $FILE ;
  6369. if ( ! open( $FILE, '<', $filename ) )
  6370. {
  6371. $sync->{nb_errors}++ ;
  6372. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6373. "error [$filename]: $OS_ERROR\n"
  6374. ) ;
  6375. }
  6376. my $jsonfile = $json->decode( join q{}, <$FILE> ) ;
  6377. close $FILE ;
  6378. $iss = $jsonfile->{client_id};
  6379. $key = $jsonfile->{private_key};
  6380. $sync->{ debug } and myprint( "Service account: $iss\n");
  6381. $sync->{ debug } and myprint( "Private key:\n$key\n");
  6382. }
  6383. else
  6384. {
  6385. # Get iss (service account address), keyfile name, and keypassword if necessary
  6386. ( $iss, my $keyfile, my $keypass ) = $imap->Password =~ /([\-\d\w\@\.]+);([a-zA-Z0-9 \_\-\.\/]+);?(.*)?/x ;
  6387. # Assume key password is google default if not provided
  6388. $keypass = 'notasecret' if not $keypass;
  6389. $sync->{ debug } and myprint( "Service account: $iss\nKey file: $keyfile\nKey password: $keypass\n");
  6390. # Get private key from p12 file (would be better in perl...)
  6391. $key = `openssl pkcs12 -in "$keyfile" -nodes -nocerts -passin pass:$keypass -nomacver`;
  6392. $sync->{ debug } and myprint( "Private key:\n$key\n");
  6393. }
  6394. # Create jwt of oauth2 request
  6395. my $time = time ;
  6396. my $jwt = JSON::WebToken->encode( {
  6397. 'iss' => $iss, # service account
  6398. 'scope' => 'https://mail.google.com/',
  6399. 'aud' => 'https://www.googleapis.com/oauth2/v3/token',
  6400. 'exp' => $time + $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12,
  6401. 'iat' => $time,
  6402. 'prn' => $imap->User # user to auth as
  6403. },
  6404. $key, 'RS256', {'typ' => 'JWT'} ); # Crypt::OpenSSL::RSA needed here.
  6405. # Post oauth2 request
  6406. my $ua = LWP::UserAgent->new( ) ;
  6407. $ua->env_proxy( ) ;
  6408. my $response = $ua->post('https://www.googleapis.com/oauth2/v3/token',
  6409. { grant_type => HTML::Entities::encode_entities('urn:ietf:params:oauth:grant-type:jwt-bearer'),
  6410. assertion => $jwt } ) ;
  6411. unless( $response->is_success( ) ) {
  6412. $sync->{nb_errors}++ ;
  6413. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6414. $response->code, "\n", $response->content, "\n"
  6415. ) ;
  6416. }else{
  6417. $sync->{ debug } and myprint( $response->content ) ;
  6418. }
  6419. # access_token in response is what we need
  6420. my $data = JSON::decode_json( $response->content ) ;
  6421. # format as oauth2 auth data
  6422. my $xoauth2_string = encode_base64( 'user=' . $imap->User . "\1auth=Bearer " . $data->{access_token} . "\1\1", q{} ) ;
  6423. $sync->{ debug } and myprint( "XOAUTH2 String: $xoauth2_string\n");
  6424. return($xoauth2_string);
  6425. }
  6426. sub xmasterauth
  6427. {
  6428. # This is Kerio auth admin
  6429. # This code comes from
  6430. # https://github.com/imapsync/imapsync/pull/53/files
  6431. my $imap = shift ;
  6432. my $user = $imap->User( ) ;
  6433. my $password = $imap->Password( ) ;
  6434. my $authmech = 'X-MASTERAUTH' ;
  6435. my @challenge = $imap->tag_and_run( $authmech, "+" ) ;
  6436. if ( not defined $challenge[0] )
  6437. {
  6438. $sync->{nb_errors}++ ;
  6439. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6440. "Failure authenticate with $authmech: ",
  6441. $imap->LastError, "\n"
  6442. ) ;
  6443. return ; # hahaha!
  6444. }
  6445. $sync->{ debug } and myprint( "X-MASTERAUTH challenge: [@challenge]\n" ) ;
  6446. $challenge[1] =~ s/^\+ |^\s+|\s+$//g ;
  6447. if ( ! $imap->_imap_command( { addcrlf => 1, addtag => 0, tag => $imap->Count }, md5_hex( $challenge[1] . $password ) ) )
  6448. {
  6449. $sync->{nb_errors}++ ;
  6450. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6451. "Failure authenticate with $authmech: ",
  6452. $imap->LastError, "\n"
  6453. ) ;
  6454. }
  6455. if ( ! $imap->tag_and_run( 'X-SETUSER ' . $user ) )
  6456. {
  6457. $sync->{nb_errors}++ ;
  6458. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6459. "Failure authenticate with $authmech: ",
  6460. "X-SETUSER ", $imap->LastError, "\n"
  6461. ) ;
  6462. }
  6463. $imap->State( Mail::IMAPClient::Authenticated ) ;
  6464. # I comment this state because "Selected" state is usually done by SELECT or EXAMINE imap commands
  6465. # $imap->State( Mail::IMAPClient::Selected ) ;
  6466. return ;
  6467. }
  6468. sub banner_imapsync
  6469. {
  6470. my $mysync = shift @ARG ;
  6471. my @argv = @ARG ;
  6472. my $banner_imapsync = join q{},
  6473. q{$RCSfile: imapsync,v $ },
  6474. q{$Revision: 2.148 $ },
  6475. q{$Date: 2021/07/22 14:21:09 $ },
  6476. "\n",
  6477. "Command line used, run by $EXECUTABLE_NAME:\n",
  6478. "$PROGRAM_NAME ", command_line_nopassword( $mysync, @argv ), "\n" ;
  6479. return( $banner_imapsync ) ;
  6480. }
  6481. sub tests_do_valid_directory
  6482. {
  6483. note( 'Entering tests_do_valid_directory()' ) ;
  6484. is( 1, do_valid_directory( '.'), 'do_valid_directory: . good' ) ;
  6485. is( 1, do_valid_directory( './W/tmp/tests/valid/sub'), 'do_valid_directory: ./W/tmp/tests/valid/sub good' ) ;
  6486. Readonly my $NB_UNIX_tests_do_valid_directory_non_root => 2 ;
  6487. diag( "OSNAME=$OSNAME EFFECTIVE_USER_ID=$EFFECTIVE_USER_ID" ) ;
  6488. SKIP: {
  6489. skip( 'Tests only for non roor user', $NB_UNIX_tests_do_valid_directory_non_root ) if ( '0' eq $EFFECTIVE_USER_ID ) ;
  6490. diag( 'The "Error / is not writable" is on purpose' ) ;
  6491. ok( 0 == do_valid_directory( '/'), 'do_valid_directory: / bad' ) ;
  6492. diag( 'The "Error permission denied" on /noway is on purpose' ) ;
  6493. ok( 0 == do_valid_directory( '/noway'), 'do_valid_directory: /noway bad' ) ;
  6494. }
  6495. note( 'Leaving tests_do_valid_directory()' ) ;
  6496. return ;
  6497. }
  6498. sub do_valid_directory
  6499. {
  6500. my $dir = shift @ARG ;
  6501. # all good => return ok.
  6502. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  6503. # exist but bad
  6504. if ( -e $dir and not -d _ ) {
  6505. myprint( "Error: $dir exists but is not a directory\n" ) ;
  6506. return( 0 ) ;
  6507. }
  6508. if ( -e $dir and not -w _ ) {
  6509. my $sb = stat $dir ;
  6510. myprintf( "Error: directory %s is not writable for user %s, permissions are %04o and owner is %s ( uid %s )\n",
  6511. $dir, getpwuid_any_os( $EFFECTIVE_USER_ID ), ($sb->mode & oct($PERMISSION_FILTER) ), getpwuid_any_os( $sb->uid ), $sb->uid( ) ) ;
  6512. return( 0 ) ;
  6513. }
  6514. # Trying to create it
  6515. myprint( "Creating directory $dir (current directory is " . getcwd( ) . ")\n" ) ;
  6516. if ( ! eval { mkpath( $dir ) } ) {
  6517. myprint( "$EVAL_ERROR" ) if ( $EVAL_ERROR ) ;
  6518. }
  6519. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  6520. return( 0 ) ;
  6521. }
  6522. sub tests_match_a_pid_number
  6523. {
  6524. note( 'Entering tests_match_a_pid_number()' ) ;
  6525. is( undef, match_a_pid_number( ), 'match_a_pid_number: no args => undef' ) ;
  6526. is( undef, match_a_pid_number( q{} ), 'match_a_pid_number: "" => undef' ) ;
  6527. is( undef, match_a_pid_number( 'lalala' ), 'match_a_pid_number: lalala => undef' ) ;
  6528. is( 1, match_a_pid_number( 1 ), 'match_a_pid_number: 1 => 1' ) ;
  6529. is( 1, match_a_pid_number( 123 ), 'match_a_pid_number: 123 => 1' ) ;
  6530. is( 1, match_a_pid_number( -123 ), 'match_a_pid_number: -123 => 1' ) ;
  6531. is( 1, match_a_pid_number( '123' ), 'match_a_pid_number: "123" => 1' ) ;
  6532. is( 1, match_a_pid_number( '-123' ), 'match_a_pid_number: "-123" => 1' ) ;
  6533. is( undef, match_a_pid_number( 'a123' ), 'match_a_pid_number: a123 => undef' ) ;
  6534. is( undef, match_a_pid_number( '-a123' ), 'match_a_pid_number: -a123 => undef' ) ;
  6535. is( 1, match_a_pid_number( 99999 ), 'match_a_pid_number: 99999 => 1' ) ;
  6536. is( 1, match_a_pid_number( -99999 ), 'match_a_pid_number: -99999 => 1' ) ;
  6537. is( undef, match_a_pid_number( 0 ), 'match_a_pid_number: 0 => undef' ) ;
  6538. is( 1, match_a_pid_number( 100000 ), 'match_a_pid_number: 100000 => 1' ) ;
  6539. is( 1, match_a_pid_number( 123456 ), 'match_a_pid_number: 123456 => 1' ) ;
  6540. is( undef, match_a_pid_number( '-0' ), 'match_a_pid_number: "-0" => undef' ) ;
  6541. is( 1, match_a_pid_number( -100000 ), 'match_a_pid_number: -100000 => 1' ) ;
  6542. is( 1, match_a_pid_number( -123456 ), 'match_a_pid_number: -123456 => 1' ) ;
  6543. is( 1, match_a_pid_number( 2**22 ), 'match_a_pid_number: 2**22 => 1' ) ;
  6544. is( undef, match_a_pid_number( 2**22 + 1 ), 'match_a_pid_number: 2**22 + 1 => undef' ) ;
  6545. is( undef, match_a_pid_number( 4194304 + 1 ), 'match_a_pid_number: 2**22 + 1 = 4194305 => undef' ) ;
  6546. note( 'Leaving tests_match_a_pid_number()' ) ;
  6547. return ;
  6548. }
  6549. sub match_a_pid_number
  6550. {
  6551. my $pid = shift @ARG ;
  6552. if ( ! defined $pid ) { return ; }
  6553. #print "$pid\n" ;
  6554. if ( ! match( $pid, '^-?\d+$' ) ) { return ; }
  6555. #print "$pid\n" ;
  6556. # can be negative on Windows
  6557. #if ( 0 > $pid ) { return ; }
  6558. #if ( 65535 < $pid ) { return ; }
  6559. if ( 2**22 < abs( $pid ) ) { return ; }
  6560. if ( 0 == abs( $pid ) ) { return ; }
  6561. return 1 ;
  6562. }
  6563. sub tests_remove_pidfile_not_running
  6564. {
  6565. note( 'Entering tests_remove_pidfile_not_running()' ) ;
  6566. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'remove_pidfile_not_running: mkpath W/tmp/tests/' ) ;
  6567. is( undef, remove_pidfile_not_running( ), 'remove_pidfile_not_running: no args => undef' ) ;
  6568. is( undef, remove_pidfile_not_running( './W' ), 'remove_pidfile_not_running: a dir => undef' ) ;
  6569. is( undef, remove_pidfile_not_running( 'noexists' ), 'remove_pidfile_not_running: noexists => undef' ) ;
  6570. is( 1, touch( 'W/tmp/tests/empty.pid' ), 'remove_pidfile_not_running: prepa empty W/tmp/tests/empty.pid' ) ;
  6571. is( undef, remove_pidfile_not_running( 'W/tmp/tests/empty.pid' ), 'remove_pidfile_not_running: W/tmp/tests/empty.pid => undef' ) ;
  6572. is( 'lalala', string_to_file( 'lalala', 'W/tmp/tests/lalala.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/lalala.pid' ) ;
  6573. is( undef, remove_pidfile_not_running( 'W/tmp/tests/lalala.pid' ), 'remove_pidfile_not_running: W/tmp/tests/lalala.pid => undef' ) ;
  6574. is( '55555', string_to_file( '55555', 'W/tmp/tests/notrunning.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/notrunning.pid' ) ;
  6575. is( 1, remove_pidfile_not_running( 'W/tmp/tests/notrunning.pid' ), 'remove_pidfile_not_running: W/tmp/tests/notrunning.pid => 1' ) ;
  6576. is( $PROCESS_ID, string_to_file( $PROCESS_ID, 'W/tmp/tests/running.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/running.pid' ) ;
  6577. is( undef, remove_pidfile_not_running( 'W/tmp/tests/running.pid' ), 'remove_pidfile_not_running: W/tmp/tests/running.pid => undef' ) ;
  6578. note( 'Leaving tests_remove_pidfile_not_running()' ) ;
  6579. return ;
  6580. }
  6581. sub remove_pidfile_not_running
  6582. {
  6583. #
  6584. my $pid_filename = shift @ARG ;
  6585. #myprint( "In remove_pidfile_not_running $pid_filename\n" ) ;
  6586. if ( ! $pid_filename ) { myprint( "No variable pid_filename\n" ) ; return } ;
  6587. if ( ! -e $pid_filename )
  6588. {
  6589. myprint( "File $pid_filename does not exist\n" ) ;
  6590. return ;
  6591. }
  6592. #myprint( "Still In remove_pidfile_not_running $pid_filename\n" ) ;
  6593. if ( ! -f $pid_filename ) { myprint( "File $pid_filename is not a file\n" ) ; return } ;
  6594. my $pid = firstline( $pid_filename ) ;
  6595. if ( ! match_a_pid_number( $pid ) ) { myprint( "In remove_pidfile_not_running: pid $pid in $pid_filename is not a pid number\n" ) ; return } ;
  6596. # can't kill myself => do nothing
  6597. if ( ! kill 'ZERO', $PROCESS_ID ) { myprint( "Can not kill ZERO myself $PROCESS_ID\n" ) ; return } ;
  6598. # can't kill ZERO the pid => it is gone or own by another user => remove pidfile
  6599. if ( ! kill 'ZERO', $pid ) {
  6600. myprint( "Removing old $pid_filename since its PID $pid is not running anymore (oo-killed?)\n" ) ;
  6601. if ( unlink $pid_filename ) {
  6602. myprint( "Removed old $pid_filename\n" ) ;
  6603. return 1 ;
  6604. }else{
  6605. myprint( "Could not remove old $pid_filename because $!\n" ) ;
  6606. return ;
  6607. }
  6608. }
  6609. myprint( "Another imapsync process $pid is running as says pidfile $pid_filename\n" ) ;
  6610. return ;
  6611. }
  6612. sub tests_tail
  6613. {
  6614. note( 'Entering tests_tail()' ) ;
  6615. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'tail: mkpath W/tmp/tests/' ) ;
  6616. ok( ( ! -e 'W/tmp/tests/tail.pid' || unlink 'W/tmp/tests/tail.pid' ), 'tail: unlink W/tmp/tests/tail.pid' ) ;
  6617. ok( ( ! -e 'W/tmp/tests/tail.txt' || unlink 'W/tmp/tests/tail.txt' ), 'tail: unlink W/tmp/tests/tail.txt' ) ;
  6618. is( undef, tail( ), 'tail: no args => undef' ) ;
  6619. my $mysync ;
  6620. is( undef, tail( $mysync ), 'tail: no pidfile => undef' ) ;
  6621. $mysync->{pidfile} = 'W/tmp/tests/tail.pid' ;
  6622. is( undef, tail( $mysync ), 'tail: no pidfilelocking => undef' ) ;
  6623. $mysync->{pidfilelocking} = 1 ;
  6624. is( undef, tail( $mysync ), 'tail: pidfile no exists => undef' ) ;
  6625. my $pidandlog = "33333\nW/tmp/tests/tail.txt\n" ;
  6626. is( $pidandlog, string_to_file( $pidandlog, $mysync->{pidfile} ), 'tail: put pid 33333 and tail.txt in pidfile' ) ;
  6627. is( undef, tail( $mysync ), 'tail: logfile to tail no exists => undef' ) ;
  6628. my $tailcontent = "L1\nL2\nL3\nL4\nL5\n" ;
  6629. is( $tailcontent, string_to_file( $tailcontent, 'W/tmp/tests/tail.txt' ),
  6630. 'tail: put L1\nL2\nL3\nL4\nL5\n in W/tmp/tests/tail.txt' ) ;
  6631. is( undef, tail( $mysync ), 'tail: fake pid in pidfile + tail off => 1' ) ;
  6632. $mysync->{ tail } = 1 ;
  6633. is( 1, tail( $mysync ), 'tail: fake pid in pidfile + tail on=> 1' ) ;
  6634. # put my own pid, won't do tail
  6635. $pidandlog = "$PROCESS_ID\nW/tmp/tests/tail.txt\n" ;
  6636. is( $pidandlog, string_to_file( $pidandlog, $mysync->{pidfile} ), 'tail: put my own PID in pidfile' ) ;
  6637. is( undef, tail( $mysync ), 'tail: my own pid in pidfile => undef' ) ;
  6638. note( 'Leaving tests_tail()' ) ;
  6639. return ;
  6640. }
  6641. sub tail
  6642. {
  6643. # return undef on failures
  6644. # return 1 on success
  6645. my $mysync = shift ;
  6646. # no tail when aborting!
  6647. if ( $mysync->{ abort } ) { return ; }
  6648. my $pidfile = $mysync->{pidfile} ;
  6649. my $lock = $mysync->{pidfilelocking} ;
  6650. my $tail = $mysync->{tail} ;
  6651. if ( ! $pidfile ) { return ; }
  6652. if ( ! $lock ) { return ; }
  6653. if ( ! $tail ) { return ; }
  6654. if ( ! -e $pidfile ) { return ; }
  6655. my $pidtotail = firstline( $pidfile ) ;
  6656. if ( ! $pidtotail ) { return ; }
  6657. # It should not happen but who knows...
  6658. if ( $pidtotail eq $PROCESS_ID ) { return ; }
  6659. my $filetotail = secondline( $pidfile ) ;
  6660. if ( ! $filetotail ) { return ; }
  6661. if ( ! -r $filetotail )
  6662. {
  6663. #myprint( "Error: can not read $filetotail\n" ) ;
  6664. return ;
  6665. }
  6666. myprint( "Doing a tail -f on $filetotail for processus pid $pidtotail until it is finished.\n" ) ;
  6667. my $file = File::Tail->new(
  6668. name => $filetotail,
  6669. nowait => 1,
  6670. interval => 1,
  6671. tail => 1,
  6672. adjustafter => 2
  6673. );
  6674. my $moretimes = 200 ;
  6675. # print one line at least
  6676. my $line = $file->read ;
  6677. myprint( $line ) ;
  6678. while ( isrunning( $pidtotail, \$moretimes ) and defined( $line = $file->read ) )
  6679. {
  6680. myprint( $line );
  6681. sleep( 0.02 ) ;
  6682. }
  6683. return 1 ;
  6684. }
  6685. sub isrunning
  6686. {
  6687. my $pidtocheck = shift ;
  6688. my $moretimes_ref = shift ;
  6689. if ( kill 'ZERO', $pidtocheck )
  6690. {
  6691. #myprint( "$pidtocheck running\n" ) ;
  6692. return 1 ;
  6693. }
  6694. elsif ( $$moretimes_ref >= 0 )
  6695. {
  6696. # continue to consider it running
  6697. $$moretimes_ref-- ;
  6698. return 1 ;
  6699. }
  6700. else
  6701. {
  6702. myprint( "Tailed processus $pidtocheck ended\n" ) ;
  6703. return ;
  6704. }
  6705. }
  6706. sub tests_write_pidfile
  6707. {
  6708. note( 'Entering tests_write_pidfile()' ) ;
  6709. my $mysync ;
  6710. is( 1, write_pidfile( ), 'write_pidfile: no args => 1' ) ;
  6711. # no pidfile => ok
  6712. $mysync->{pidfile} = q{} ;
  6713. is( 1, write_pidfile( $mysync ), 'write_pidfile: no pidfile => undef' ) ;
  6714. # The pidfile path is bad => failure
  6715. $mysync->{pidfile} = '/no/no/no.pid' ;
  6716. is( undef, write_pidfile( $mysync ), 'write_pidfile: no permission for /no/no/no.pid, no lock => undef' ) ;
  6717. $mysync->{pidfilelocking} = 1 ;
  6718. is( undef, write_pidfile( $mysync ), 'write_pidfile: no permission for /no/no/no.pid + lock => undef' ) ;
  6719. $mysync->{pidfile} = 'W/tmp/tests/test.pid' ;
  6720. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'write_pidfile: mkpath W/tmp/tests/' ) ;
  6721. is( 1, touch( $mysync->{pidfile} ), 'write_pidfile: lock prepa' ) ;
  6722. $mysync->{pidfilelocking} = 0 ;
  6723. is( 1, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + no lock => 1' ) ;
  6724. is( $PROCESS_ID, firstline( 'W/tmp/tests/test.pid' ), "write_pidfile: W/tmp/tests/test.pid contains $PROCESS_ID" ) ;
  6725. is( q{}, secondline( 'W/tmp/tests/test.pid' ), "write_pidfile: W/tmp/tests/test.pid contains no second line" ) ;
  6726. $mysync->{pidfilelocking} = 1 ;
  6727. is( undef, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + lock => undef' ) ;
  6728. $mysync->{pidfilelocking} = 0 ;
  6729. $mysync->{ logfile } = 'rrrr.txt' ;
  6730. is( 1, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + no lock + logfile => 1' ) ;
  6731. is( $PROCESS_ID, firstline( 'W/tmp/tests/test.pid' ), "write_pidfile: + no lock + logfile W/tmp/tests/test.pid contains $PROCESS_ID" ) ;
  6732. is( q{rrrr.txt}, secondline( 'W/tmp/tests/test.pid' ), "write_pidfile: + no lock + logfile W/tmp/tests/test.pid contains rrrr.txt" ) ;
  6733. note( 'Leaving tests_write_pidfile()' ) ;
  6734. return ;
  6735. }
  6736. sub write_pidfile
  6737. {
  6738. # returns undef if something is considered fatal
  6739. # returns 1 otherwise
  6740. #myprint( "In write_pidfile\n" ) ;
  6741. if ( ! @ARG ) { return 1 ; }
  6742. my $mysync = shift @ARG ;
  6743. # Do not write the pid file if the current process goal is to abort the process designed by the pid file
  6744. if ( $mysync->{ abort } ) { return 1 ; }
  6745. #
  6746. my $pid_filename = $mysync->{ pidfile } ;
  6747. my $lock = $mysync->{ pidfilelocking } ;
  6748. if ( ! $pid_filename )
  6749. {
  6750. myprint( "PID file is unset ( to set it, use --pidfile filepath ; to avoid it use --pidfile \"\" )\n" ) ;
  6751. return( 1 ) ;
  6752. }
  6753. myprint( "PID file is $pid_filename ( to change it, use --pidfile filepath ; to avoid it use --pidfile \"\" )\n" ) ;
  6754. if ( -e $pid_filename and $lock ) {
  6755. myprint( "$pid_filename already exists, another imapsync may be curently running. Aborting imapsync.\n" ) ;
  6756. return ;
  6757. }
  6758. if ( -e $pid_filename ) {
  6759. myprint( "$pid_filename already exists, overwriting it ( use --pidfilelocking to avoid concurrent runs )\n" ) ;
  6760. }
  6761. my $pid_string = "$PROCESS_ID\n" ;
  6762. my $pid_message = "Writing my PID $PROCESS_ID in $pid_filename\n" ;
  6763. if ( $mysync->{ logfile } )
  6764. {
  6765. $pid_string .= "$mysync->{ logfile }\n" ;
  6766. $pid_message .= "Writing also my logfile name in $pid_filename : $mysync->{ logfile }\n" ;
  6767. }
  6768. if ( open my $FILE_HANDLE, '>', $pid_filename ) {
  6769. myprint( $pid_message ) ;
  6770. print $FILE_HANDLE $pid_string ;
  6771. close $FILE_HANDLE ;
  6772. return( 1 ) ;
  6773. }
  6774. else
  6775. {
  6776. myprint( "Could not open $pid_filename for writing. Check permissions or disk space: $OS_ERROR\n" ) ;
  6777. return ;
  6778. }
  6779. }
  6780. sub fix_Inbox_INBOX_mapping
  6781. {
  6782. my( $h1_all, $h2_all ) = @_ ;
  6783. my $regex = q{} ;
  6784. SWITCH: {
  6785. if ( exists $h1_all->{INBOX} and exists $h2_all->{INBOX} ) { $regex = q{} ; last SWITCH ; } ;
  6786. if ( exists $h1_all->{Inbox} and exists $h2_all->{Inbox} ) { $regex = q{} ; last SWITCH ; } ;
  6787. if ( exists $h1_all->{INBOX} and exists $h2_all->{Inbox} ) { $regex = q{s/^INBOX$/Inbox/x} ; last SWITCH ; } ;
  6788. if ( exists $h1_all->{Inbox} and exists $h2_all->{INBOX} ) { $regex = q{s/^Inbox$/INBOX/x} ; last SWITCH ; } ;
  6789. } ;
  6790. return( $regex ) ;
  6791. }
  6792. sub tests_fix_Inbox_INBOX_mapping
  6793. {
  6794. note( 'Entering tests_fix_Inbox_INBOX_mapping()' ) ;
  6795. my( $h1_all, $h2_all ) ;
  6796. $h1_all = { 'INBOX' => q{} } ;
  6797. $h2_all = { 'INBOX' => q{} } ;
  6798. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX INBOX' ) ;
  6799. $h1_all = { 'Inbox' => q{} } ;
  6800. $h2_all = { 'Inbox' => q{} } ;
  6801. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox Inbox' ) ;
  6802. $h1_all = { 'INBOX' => q{} } ;
  6803. $h2_all = { 'Inbox' => q{} } ;
  6804. ok( q{s/^INBOX$/Inbox/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX Inbox' ) ;
  6805. $h1_all = { 'Inbox' => q{} } ;
  6806. $h2_all = { 'INBOX' => q{} } ;
  6807. ok( q{s/^Inbox$/INBOX/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox INBOX' ) ;
  6808. $h1_all = { 'INBOX' => q{} } ;
  6809. $h2_all = { 'rrrrr' => q{} } ;
  6810. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX rrrrrr' ) ;
  6811. $h1_all = { 'rrrrr' => q{} } ;
  6812. $h2_all = { 'Inbox' => q{} } ;
  6813. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: rrrrr Inbox' ) ;
  6814. note( 'Leaving tests_fix_Inbox_INBOX_mapping()' ) ;
  6815. return ;
  6816. }
  6817. sub jux_utf8_list
  6818. {
  6819. my @s_inp = @_ ;
  6820. my $s_out = q{} ;
  6821. foreach my $s ( @s_inp ) {
  6822. $s_out .= jux_utf8( $s ) . "\n" ;
  6823. }
  6824. return( $s_out ) ;
  6825. }
  6826. sub tests_jux_utf8_list
  6827. {
  6828. note( 'Entering tests_jux_utf8_list()' ) ;
  6829. use utf8 ;
  6830. is( q{}, jux_utf8_list( ), 'jux_utf8_list: void' ) ;
  6831. is( "[]\n", jux_utf8_list( q{} ), 'jux_utf8_list: empty string' ) ;
  6832. is( "[INBOX]\n", jux_utf8_list( 'INBOX' ), 'jux_utf8_list: INBOX' ) ;
  6833. is( "[&ANY-] = [Ö]\n", jux_utf8_list( '&ANY-' ), 'jux_utf8_list: [&ANY-] = [Ö]' ) ;
  6834. note( 'Leaving tests_jux_utf8_list()' ) ;
  6835. return( 0 ) ;
  6836. }
  6837. # editing utf8 can be tricky without an utf8 editor
  6838. sub tests_jux_utf8_old
  6839. {
  6840. note( 'Entering tests_jux_utf8_old()' ) ;
  6841. no utf8 ;
  6842. is( '[]', jux_utf8_old( q{} ), 'jux_utf8_old: void => []' ) ;
  6843. is( '[INBOX]', jux_utf8_old( 'INBOX'), 'jux_utf8_old: INBOX => [INBOX]' ) ;
  6844. is( '[&ZTZO9nux-] = [æ”¶ä»¶ç®±]', jux_utf8_old( '&ZTZO9nux-'), 'jux_utf8_old: => [&ZTZO9nux-] = [æ”¶ä»¶ç®±]' ) ;
  6845. is( '[&ANY-] = [Ö]', jux_utf8_old( '&ANY-'), 'jux_utf8_old: &ANY- => [&ANY-] = [Ö]' ) ;
  6846. # +BD8EQAQ1BDQEOwQ+BDM- SHOULD stay as is!
  6847. is( '[+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]', jux_utf8_old( '+BD8EQAQ1BDQEOwQ+BDM-' ), 'jux_utf8_old: => [+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]' ) ;
  6848. is( '[&BB8EQAQ+BDUEOgRC-] = [Проект]', jux_utf8_old( '&BB8EQAQ+BDUEOgRC-' ), 'jux_utf8_old: => [&BB8EQAQ+BDUEOgRC-] = [Проект]' ) ;
  6849. note( 'Leaving tests_jux_utf8_old()' ) ;
  6850. return ;
  6851. }
  6852. sub jux_utf8_old
  6853. {
  6854. # juxtapose utf8 at the right if different
  6855. my ( $s_utf7 ) = shift ;
  6856. my ( $s_utf8 ) = imap_utf7_decode_old( $s_utf7 ) ;
  6857. if ( $s_utf7 eq $s_utf8 ) {
  6858. #myprint( "[$s_utf7]\n" ) ;
  6859. return( "[$s_utf7]" ) ;
  6860. }else{
  6861. #myprint( "[$s_utf7] = [$s_utf8]\n" ) ;
  6862. return( "[$s_utf7] = [$s_utf8]" ) ;
  6863. }
  6864. }
  6865. # Copied from http://cpansearch.perl.org/src/FABPOT/Unicode-IMAPUtf7-2.01/lib/Unicode/IMAPUtf7.pm
  6866. # and then fixed with
  6867. # https://rt.cpan.org/Public/Bug/Display.html?id=11172
  6868. sub imap_utf7_decode_old
  6869. {
  6870. my ( $s ) = shift ;
  6871. # Algorithm
  6872. # On remplace , par / dans les BASE 64 (, entre & et -)
  6873. # On remplace les &, non suivi d'un - par +
  6874. # On remplace les &- par &
  6875. $s =~ s/&([^,&\-]*),([^,\-&]*)\-/&$1\/$2\-/xg ;
  6876. $s =~ s/&(?!\-)/\+/xg ;
  6877. $s =~ s/&\-/&/xg ;
  6878. return( Unicode::String::utf7( $s )->utf8 ) ;
  6879. }
  6880. sub tests_jux_utf8
  6881. {
  6882. note( 'Entering tests_jux_utf8()' ) ;
  6883. #no utf8 ;
  6884. use utf8 ;
  6885. #binmode STDOUT, ":encoding(UTF-8)" ;
  6886. binmode STDERR, ":encoding(UTF-8)" ;
  6887. # This test is because the binary can fail on it, a PAR.pm issue.
  6888. # The failure was with the underlying Encode::IMAPUTF7 module line 66 release 1.05
  6889. # Was solved by including Encode in imapsync and using "pp -x".
  6890. ok( find_encoding( "UTF-16BE"), 'jux_utf8: Encode::find_encoding: UTF-16BE' ) ;
  6891. #
  6892. is( '[]', jux_utf8( q{} ), 'jux_utf8: void => []' ) ;
  6893. is( '[INBOX]', jux_utf8( 'INBOX'), 'jux_utf8: INBOX => [INBOX]' ) ;
  6894. is( '[&ANY-] = [Ö]', jux_utf8( '&ANY-'), 'jux_utf8: &ANY- => [&ANY-] = [Ö]' ) ;
  6895. # +BD8EQAQ1BDQEOwQ+BDM- must stay as is
  6896. is( '[+BD8EQAQ1BDQEOwQ+BDM-]', jux_utf8( '+BD8EQAQ1BDQEOwQ+BDM-' ), 'jux_utf8: => [+BD8EQAQ1BDQEOwQ+BDM-] = [+BD8EQAQ1BDQEOwQ+BDM-]' ) ;
  6897. is( '[&BB8EQAQ+BDUEOgRC-] = [Проект]', jux_utf8( '&BB8EQAQ+BDUEOgRC-' ), 'jux_utf8: => [&BB8EQAQ+BDUEOgRC-] = [Проект]' ) ;
  6898. is( '[R&AOk-ponses 1200+1201+1202] = [Réponses 1200+1201+1202]', jux_utf8( q{R&AOk-ponses 1200+1201+1202} ), 'jux_utf8: [R&AOk-ponses 1200+1201+1202] = [Réponses 1200+1201+1202]' ) ;
  6899. my $str = Encode::IMAPUTF7::encode("IMAP-UTF-7", 'Réponses 1200+1201+1202' ) ;
  6900. is( '[R&AOk-ponses 1200+1201+1202] = [Réponses 1200+1201+1202]', jux_utf8( $str ), "jux_utf8: [$str] = [Réponses 1200+1201+1202]" ) ;
  6901. is( '[INBOX.&AOkA4ADnAPk-&-*] = [INBOX.éà çù&*]', jux_utf8( 'INBOX.&AOkA4ADnAPk-&-*' ), "jux_utf8: [INBOX.&AOkA4ADnAPk-&-*] = [INBOX.éà çù&*]" ) ;
  6902. is( '[&ZTZO9nux-] = [æ”¶ä»¶ç®±]', jux_utf8( '&ZTZO9nux-'), 'jux_utf8: => [&ZTZO9nux-] = [æ”¶ä»¶ç®±]' ) ;
  6903. #
  6904. #
  6905. is( '[!Old Emails]', jux_utf8( '!Old Emails'), 'jux_utf8: !Old Emails => [!Old Emails]' ) ;
  6906. is( '[2006 Budget & Fcst]', jux_utf8( '2006 Budget & Fcst'), 'jux_utf8: 2006 Budget & Fcst => [2006 Budget & Fcst]' ) ;
  6907. note( 'Leaving tests_jux_utf8()' ) ;
  6908. return ;
  6909. }
  6910. sub jux_utf8
  6911. {
  6912. #use utf8 ;
  6913. # juxtapose utf8 at the right if different
  6914. my ( $s_utf7 ) = shift ;
  6915. my ( $s_utf8 ) = imap_utf7_decode( $s_utf7 ) ;
  6916. if ( $s_utf7 eq $s_utf8 ) {
  6917. #myprint( "[$s_utf7]\n" ) ;
  6918. return( "[$s_utf7]" ) ;
  6919. }else{
  6920. #myprint( "[$s_utf7] = [$s_utf8]\n" ) ;
  6921. return( "[$s_utf7] = [$s_utf8]" ) ;
  6922. }
  6923. }
  6924. sub imap_utf7_decode
  6925. {
  6926. #use utf8 ;
  6927. my ( $s ) = shift ;
  6928. return( Encode::IMAPUTF7::decode("IMAP-UTF-7", $s ) ) ;
  6929. }
  6930. sub imap_utf7_encode
  6931. {
  6932. #use utf8 ;
  6933. my ( $s ) = shift ;
  6934. return( Encode::IMAPUTF7::encode("IMAP-UTF-7", $s ) ) ;
  6935. }
  6936. sub imap_utf7_encode_old
  6937. {
  6938. my ( $s ) = @_ ;
  6939. $s = Unicode::String::utf8( $s )->utf7 ;
  6940. $s =~ s/\+([^\/&\-]*)\/([^\/\-&]*)\-/\+$1,$2\-/xg ;
  6941. $s =~ s/&/&\-/xg ;
  6942. $s =~ s/\+([^+\-]+)?\-/&$1\-/xg ;
  6943. return( $s ) ;
  6944. }
  6945. sub select_folder
  6946. {
  6947. my ( $mysync, $imap, $folder, $hostside ) = @_ ;
  6948. if ( ! $imap->select( $folder ) ) {
  6949. my $error = join q{},
  6950. "$hostside folder $folder: Could not select: ",
  6951. $imap->LastError, "\n" ;
  6952. errors_incr( $mysync, $error ) ;
  6953. return( 0 ) ;
  6954. }else{
  6955. # ok select succeeded
  6956. return( 1 ) ;
  6957. }
  6958. }
  6959. sub examine_folder
  6960. {
  6961. my ( $mysync, $imap, $folder, $hostside ) = @_ ;
  6962. if ( ! $imap->examine( $folder ) ) {
  6963. my $error = join q{},
  6964. "$hostside folder $folder: Could not examine: ",
  6965. $imap->LastError, "\n" ;
  6966. errors_incr( $mysync, $error ) ;
  6967. return( 0 ) ;
  6968. }else{
  6969. # ok select succeeded
  6970. return( 1 ) ;
  6971. }
  6972. }
  6973. sub count_from_select
  6974. {
  6975. my @lines = @ARG ;
  6976. my $count ;
  6977. foreach my $line ( @lines ) {
  6978. #myprint( "line = [$line]\n" ) ;
  6979. if ( $line =~ m/^\*\s+(\d+)\s+EXISTS/x ) {
  6980. $count = $1 ;
  6981. return( $count ) ;
  6982. }
  6983. }
  6984. return( undef ) ;
  6985. }
  6986. sub create_folder_old
  6987. {
  6988. my $mysync = shift @ARG ;
  6989. my( $imap, $h2_fold, $h1_fold ) = @ARG ;
  6990. myprint( "Creating (old way) folder [$h2_fold] on host2\n" ) ;
  6991. if ( ( 'INBOX' eq uc $h2_fold )
  6992. and ( $imap->exists( $h2_fold ) ) ) {
  6993. myprint( "Folder [$h2_fold] already exists\n" ) ;
  6994. return( 1 ) ;
  6995. }
  6996. if ( ! $mysync->{dry} ){
  6997. if ( ! $imap->create( $h2_fold ) ) {
  6998. my $error = join q{},
  6999. "Could not create folder [$h2_fold] from [$h1_fold]: ",
  7000. $imap->LastError( ), "\n" ;
  7001. errors_incr( $mysync, $error ) ;
  7002. # success if folder exists ("already exists" error)
  7003. return( 1 ) if $imap->exists( $h2_fold ) ;
  7004. # failure since create failed
  7005. return( 0 ) ;
  7006. }else{
  7007. #create succeeded
  7008. myprint( "Created ( the old way ) folder [$h2_fold] on host2\n" ) ;
  7009. return( 1 ) ;
  7010. }
  7011. }else{
  7012. # dry mode, no folder so many imap will fail, assuming failure
  7013. myprint( "Created ( the old way ) folder [$h2_fold] on host2 $mysync->{dry_message}\n" ) ;
  7014. return( 0 ) ;
  7015. }
  7016. }
  7017. sub create_folder
  7018. {
  7019. my $mysync = shift @ARG ;
  7020. my( $myimap2 , $h2_fold , $h1_fold ) = @ARG ;
  7021. my( @parts , $parent ) ;
  7022. if ( $myimap2->IsUnconnected( ) ) {
  7023. myprint( "Host2: Unconnected state\n" ) ;
  7024. return( 0 ) ;
  7025. }
  7026. if ( $create_folder_old ) {
  7027. return( create_folder_old( $mysync, $myimap2 , $h2_fold , $h1_fold ) ) ;
  7028. }
  7029. myprint( "Creating folder [$h2_fold] on host2\n" ) ;
  7030. if ( ( 'INBOX' eq uc $h2_fold )
  7031. and ( $myimap2->exists( $h2_fold ) ) ) {
  7032. myprint( "Folder [$h2_fold] already exists\n" ) ;
  7033. return( 1 ) ;
  7034. }
  7035. if ( $mixfolders and $myimap2->exists( $h2_fold ) ) {
  7036. myprint( "Folder [$h2_fold] already exists (--nomixfolders is not set)\n" ) ;
  7037. return( 1 ) ;
  7038. }
  7039. if ( ( not $mixfolders ) and ( $myimap2->exists( $h2_fold ) ) ) {
  7040. myprint( "Folder [$h2_fold] already exists and --nomixfolders is set\n" ) ;
  7041. return( 0 ) ;
  7042. }
  7043. @parts = split /\Q$mysync->{ h2_sep }\E/x, $h2_fold ;
  7044. pop @parts ;
  7045. $parent = join $mysync->{ h2_sep }, @parts ;
  7046. $parent =~ s/^\s+|\s+$//xg ;
  7047. if ( ( $parent ne q{} ) and ( ! $myimap2->exists( $parent ) ) ) {
  7048. create_folder( $mysync, $myimap2 , $parent , $h1_fold ) ;
  7049. }
  7050. if ( ! $mysync->{dry} ) {
  7051. if ( ! $myimap2->create( $h2_fold ) ) {
  7052. my $error = join q{},
  7053. "Could not create folder [$h2_fold] from [$h1_fold]: " ,
  7054. $myimap2->LastError( ), "\n" ;
  7055. errors_incr( $mysync, $error ) ;
  7056. # success if folder exists ("already exists" error)
  7057. return( 1 ) if $myimap2->exists( $h2_fold ) ;
  7058. # failure since create failed
  7059. return( 0 ) ;
  7060. }else{
  7061. #create succeeded
  7062. myprint( "Created folder [$h2_fold] on host2\n" ) ;
  7063. return( 1 ) ;
  7064. }
  7065. }else{
  7066. # dry mode, no folder so many imap will fail, assuming failure
  7067. myprint( "Created folder [$h2_fold] on host2 $mysync->{dry_message}\n" ) ;
  7068. if ( ! $mysync->{ justfolders } ) {
  7069. myprint( "Since --dry mode is on and folder [$h2_fold] on host2 does not exist yet, syncing messages will not be simulated.\n"
  7070. . "To simulate message syncing, use --justfolders without --dry to first create the missing folders then rerun the --dry sync.\n" ) ;
  7071. # The messages that could be transferred are counted and the number is given at the end.
  7072. }
  7073. return( 0 ) ;
  7074. }
  7075. }
  7076. sub tests_folder_routines
  7077. {
  7078. note( 'Entering tests_folder_routines()' ) ;
  7079. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 1' );
  7080. ok( add_to_requested_folders('folder_foo'), 'add_to_requested_folders folder_foo' );
  7081. ok( is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 2' );
  7082. ok( !is_requested_folder('folder_NO_EXIST'), 'is_requested_folder folder_NO_EXIST' );
  7083. is_deeply( [ 'folder_foo' ], [ remove_from_requested_folders( 'folder_foo' ) ], 'removed folder_foo => folder_foo' ) ;
  7084. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 3' );
  7085. my @f ;
  7086. ok( @f = add_to_requested_folders('folder_bar', 'folder_toto'), "add result: @f" );
  7087. ok( is_requested_folder('folder_bar'), 'is_requested_folder 4' );
  7088. ok( is_requested_folder('folder_toto'), 'is_requested_folder 5' );
  7089. ok( remove_from_requested_folders('folder_toto'), 'remove_from_requested_folders: ' );
  7090. ok( !is_requested_folder('folder_toto'), 'is_requested_folder 6' );
  7091. is_deeply( [ 'folder_bar' ], [ remove_from_requested_folders('folder_bar') ], 'remove_from_requested_folders: empty' ) ;
  7092. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [] ), 'sort_requested_folders: all empty' ) ;
  7093. ok( add_to_requested_folders( 'A_99', 'M_55', 'Z_11' ), 'add_to_requested_folders M_55 Z_11' );
  7094. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'A_99', 'M_55', 'Z_11' ] ), 'sort_requested_folders: middle' ) ;
  7095. @folderfirst = ( 'Z_11' ) ;
  7096. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'A_99', 'M_55' ] ), 'sort_requested_folders: first+middle' ) ;
  7097. is_deeply( [ 'Z_11', 'A_99', 'M_55' ], [ sort_requested_folders( ) ], 'sort_requested_folders: first+middle is_deeply' ) ;
  7098. @folderlast = ( 'A_99' ) ;
  7099. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_55', 'A_99' ] ), 'sort_requested_folders: first+middle+last 1' ) ;
  7100. ok( add_to_requested_folders('M_55', 'M_44',), 'add_to_requested_folders M_55 M_44' ) ;
  7101. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_44', 'M_55', 'A_99'] ), 'sort_requested_folders: first+middle+last 2' ) ;
  7102. ok( add_to_requested_folders('A_88', 'Z_22',), 'add_to_requested_folders A_88 Z_22' ) ;
  7103. @folderfirst = qw( Z_22 Z_11 ) ;
  7104. @folderlast = qw( A_99 A_88 ) ;
  7105. 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' ) ;
  7106. undef @folderfirst ;
  7107. undef @folderlast ;
  7108. note( 'Leaving tests_folder_routines()' ) ;
  7109. return ;
  7110. }
  7111. sub sort_requested_folders
  7112. {
  7113. my @requested_folders_sorted = () ;
  7114. $sync->{ debug } and myprint "folderfirst: @folderfirst\n" ;
  7115. my @folderfirst_requested = remove_from_requested_folders( @folderfirst ) ;
  7116. #myprint "folderfirst_requested: @folderfirst_requested\n" ;
  7117. my @folderlast_requested = remove_from_requested_folders( @folderlast ) ;
  7118. my @middle = sort keys %requested_folder ;
  7119. @requested_folders_sorted = ( @folderfirst_requested, @middle, @folderlast_requested ) ;
  7120. $sync->{ debug } and myprint "requested_folders_sorted: @requested_folders_sorted\n" ;
  7121. add_to_requested_folders( @requested_folders_sorted ) ;
  7122. return( @requested_folders_sorted ) ;
  7123. }
  7124. sub is_requested_folder
  7125. {
  7126. my ( $folder ) = @_;
  7127. return( defined $requested_folder{ $folder } ) ;
  7128. }
  7129. sub add_to_requested_folders
  7130. {
  7131. my @wanted_folders = @_ ;
  7132. foreach my $folder ( @wanted_folders ) {
  7133. ++$requested_folder{ $folder } ;
  7134. }
  7135. return( keys %requested_folder ) ;
  7136. }
  7137. sub tests_remove_from_requested_folders
  7138. {
  7139. note( 'Entering tests_remove_from_requested_folders()' ) ;
  7140. is( undef, undef, 'remove_from_requested_folders: undef is undef' ) ;
  7141. is_deeply( [], [ remove_from_requested_folders( ) ], 'remove_from_requested_folders: no args' ) ;
  7142. %requested_folder = (
  7143. 'F1' => 1,
  7144. ) ;
  7145. is_deeply( [], [ remove_from_requested_folders( ) ], 'remove_from_requested_folders: remove nothing among F1 => nothing' ) ;
  7146. is_deeply( [], [ remove_from_requested_folders( 'Fno' ) ], 'remove_from_requested_folders: remove Fno among F1 => nothing' ) ;
  7147. is_deeply( [ 'F1' ], [ remove_from_requested_folders( 'F1' ) ], 'remove_from_requested_folders: remove F1 among F1 => F1' ) ;
  7148. is_deeply( { }, { %requested_folder }, 'remove_from_requested_folders: remove F1 among F1 => %requested_folder emptied' ) ;
  7149. %requested_folder = (
  7150. 'F1' => 1,
  7151. 'F2' => 1,
  7152. ) ;
  7153. is_deeply( [], [ remove_from_requested_folders( ) ], 'remove_from_requested_folders: remove nothing among F1 F2 => nothing' ) ;
  7154. is_deeply( [], [ remove_from_requested_folders( 'Fno' ) ], 'remove_from_requested_folders: remove Fno among F1 F2 => nothing' ) ;
  7155. is_deeply( [ 'F1' ], [ remove_from_requested_folders( 'F1' ) ], 'remove_from_requested_folders: remove F1 among F1 F2 => F1' ) ;
  7156. is_deeply( { 'F2' => 1 }, { %requested_folder }, 'remove_from_requested_folders: remove F1 among F1 F2 => %requested_folder F2' ) ;
  7157. is_deeply( [], [ remove_from_requested_folders( 'F1' ) ], 'remove_from_requested_folders: remove F1 among F2 => nothing' ) ;
  7158. is_deeply( [ 'F2' ], [ remove_from_requested_folders( 'F1', 'F2' ) ], 'remove_from_requested_folders: remove F1 F2 among F2 => F2' ) ;
  7159. is_deeply( {}, { %requested_folder }, 'remove_from_requested_folders: remove F1 among F1 F2 => %requested_folder F2' ) ;
  7160. %requested_folder = (
  7161. 'F1' => 1,
  7162. 'F2' => 1,
  7163. 'F3' => 1,
  7164. ) ;
  7165. is_deeply( [ 'F1', 'F2' ], [ remove_from_requested_folders( 'F1', 'F2' ) ], 'remove_from_requested_folders: remove F1 F2 among F1 F2 F3 => F1 F2' ) ;
  7166. is_deeply( { 'F3' => 1 }, { %requested_folder }, 'remove_from_requested_folders: remove F1 F2 among F1 F2 F3 => %requested_folder F3' ) ;
  7167. undef %requested_folder ;
  7168. note( 'Leaving tests_remove_from_requested_folders()' ) ;
  7169. return ;
  7170. }
  7171. sub remove_from_requested_folders
  7172. {
  7173. my @unwanted_folders = @_ ;
  7174. my @removed_folders = () ;
  7175. foreach my $folder ( @unwanted_folders ) {
  7176. if ( exists $requested_folder{ $folder } )
  7177. {
  7178. delete $requested_folder{ $folder } ;
  7179. push @removed_folders, $folder ;
  7180. }
  7181. }
  7182. return( @removed_folders ) ;
  7183. }
  7184. sub compare_lists
  7185. {
  7186. my ($list_1_ref, $list_2_ref) = @_;
  7187. return($MINUS_ONE) if ((not defined $list_1_ref) and defined $list_2_ref);
  7188. return(0) if ((not defined $list_1_ref) and not defined $list_2_ref); # end if no list
  7189. return(1) if (not defined $list_2_ref); # end if only one list
  7190. if (not ref $list_1_ref ) {$list_1_ref = [$list_1_ref]};
  7191. if (not ref $list_2_ref ) {$list_2_ref = [$list_2_ref]};
  7192. my $last_used_indice = $MINUS_ONE;
  7193. ELEMENT:
  7194. foreach my $indice ( 0 .. $#{ $list_1_ref } ) {
  7195. $last_used_indice = $indice ;
  7196. # End of list_2
  7197. return 1 if ($indice > $#{ $list_2_ref } ) ;
  7198. my $element_list_1 = $list_1_ref->[$indice] ;
  7199. my $element_list_2 = $list_2_ref->[$indice] ;
  7200. my $balance = $element_list_1 cmp $element_list_2 ;
  7201. next ELEMENT if ($balance == 0) ;
  7202. return $balance ;
  7203. }
  7204. # each element equal until last indice of list_1
  7205. return $MINUS_ONE if ($last_used_indice < $#{ $list_2_ref } ) ;
  7206. # same size, each element equal
  7207. return 0 ;
  7208. }
  7209. sub tests_compare_lists
  7210. {
  7211. note( 'Entering tests_compare_lists()' ) ;
  7212. my $empty_list_ref = [];
  7213. ok( 0 == compare_lists() , 'compare_lists, no args');
  7214. ok( 0 == compare_lists(undef) , 'compare_lists, undef = nothing');
  7215. ok( 0 == compare_lists(undef, undef) , 'compare_lists, undef = undef');
  7216. ok($MINUS_ONE == compare_lists(undef , []) , 'compare_lists, undef < []');
  7217. ok($MINUS_ONE == compare_lists(undef , [1]) , 'compare_lists, undef < [1]');
  7218. ok($MINUS_ONE == compare_lists(undef , [0]) , 'compare_lists, undef < [0]');
  7219. ok(+1 == compare_lists([]) , 'compare_lists, [] > nothing');
  7220. ok(+1 == compare_lists([], undef) , 'compare_lists, [] > undef');
  7221. ok( 0 == compare_lists([] , []) , 'compare_lists, [] = []');
  7222. ok($MINUS_ONE == compare_lists([] , [1]) , 'compare_lists, [] < [1]');
  7223. ok(+1 == compare_lists([1] , []) , 'compare_lists, [1] > []');
  7224. ok( 0 == compare_lists( [1], 1 ) , 'compare_lists, [1] = 1 ') ;
  7225. ok( 0 == compare_lists( 1 , [1] ) , 'compare_lists, 1 = [1]') ;
  7226. ok( 0 == compare_lists( 1 , 1 ) , 'compare_lists, 1 = 1 ') ;
  7227. ok( $MINUS_ONE == compare_lists( 0 , 1 ) , 'compare_lists, 0 < 1 ') ;
  7228. ok( $MINUS_ONE == compare_lists( $MINUS_ONE , 0 ) , 'compare_lists, -1 < 0 ') ;
  7229. ok( $MINUS_ONE == compare_lists( 1 , 2 ) , 'compare_lists, 1 < 2 ') ;
  7230. ok( +1 == compare_lists( 2 , 1 ) , 'compare_lists, 2 > 1 ') ;
  7231. ok( 0 == compare_lists([1,2], [1,2]) , 'compare_lists, [1,2] = [1,2]' ) ;
  7232. ok($MINUS_ONE == compare_lists([1], [1,2]) , 'compare_lists, [1] < [1,2]' ) ;
  7233. ok(+1 == compare_lists([2], [1,2]) , 'compare_lists, [2] > [1,2]' ) ;
  7234. ok($MINUS_ONE == compare_lists([1], [1,1]) , 'compare_lists, [1] < [1,1]' ) ;
  7235. ok(+1 == compare_lists([1, 1], [1]) , 'compare_lists, [1, 1] > [1]' ) ;
  7236. ok( 0 == compare_lists([1 .. $NUMBER_20_000] , [1 .. $NUMBER_20_000])
  7237. , 'compare_lists, [1..20_000] = [1..20_000]' ) ;
  7238. ok($MINUS_ONE == compare_lists([1], [2]) , 'compare_lists, [1] < [2]') ;
  7239. ok( 0 == compare_lists([2], [2]) , 'compare_lists, [0] = [2]') ;
  7240. ok(+1 == compare_lists([2], [1]) , 'compare_lists, [2] > [1]') ;
  7241. ok($MINUS_ONE == compare_lists(['a'], ['b']) , 'compare_lists, ["a"] < ["b"]') ;
  7242. ok( 0 == compare_lists(['a'], ['a']) , 'compare_lists, ["a"] = ["a"]') ;
  7243. ok( 0 == compare_lists(['ab'], ['ab']) , 'compare_lists, ["ab"] = ["ab"]') ;
  7244. ok(+1 == compare_lists(['b'], ['a']) , 'compare_lists, ["b"] > ["a"]') ;
  7245. ok($MINUS_ONE == compare_lists(['a'], ['aa']) , 'compare_lists, ["a"] < ["aa"]') ;
  7246. ok($MINUS_ONE == compare_lists(['a'], ['a', 'a']), 'compare_lists, ["a"] < ["a", "a"]') ;
  7247. ok( 0 == compare_lists([split q{ }, 'a b' ], ['a', 'b']), 'compare_lists, split') ;
  7248. ok( 0 == compare_lists([sort split q{ }, 'b a' ], ['a', 'b']), 'compare_lists, sort split') ;
  7249. note( 'Leaving tests_compare_lists()' ) ;
  7250. return ;
  7251. }
  7252. sub guess_prefix
  7253. {
  7254. my @foldernames = @_ ;
  7255. my $prefix_guessed = q{} ;
  7256. foreach my $folder ( @foldernames ) {
  7257. next if ( $folder =~ m{^INBOX$}xi ) ; # no guessing from INBOX
  7258. if ( $folder !~ m{^INBOX}xi ) {
  7259. $prefix_guessed = q{} ; # prefix empty guessed
  7260. last ;
  7261. }
  7262. if ( $folder =~ m{^(INBOX(?:\.|\/))}xi ) {
  7263. $prefix_guessed = $1 ; # prefix Inbox/ or INBOX. guessed
  7264. }
  7265. }
  7266. return( $prefix_guessed ) ;
  7267. }
  7268. sub tests_guess_prefix
  7269. {
  7270. note( 'Entering tests_guess_prefix()' ) ;
  7271. is( guess_prefix( ), q{}, 'guess_prefix: no args => empty string' ) ;
  7272. is( q{} , guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  7273. is( q{} , guess_prefix( 'Inbox' ), 'guess_prefix: Inbox alone' ) ;
  7274. is( q{} , guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  7275. is( 'INBOX/' , guess_prefix( 'INBOX', 'INBOX/Junk' ), 'guess_prefix: INBOX INBOX/Junk' ) ;
  7276. is( 'INBOX.' , guess_prefix( 'INBOX', 'INBOX.Junk' ), 'guess_prefix: INBOX INBOX.Junk' ) ;
  7277. is( 'Inbox/' , guess_prefix( 'Inbox', 'Inbox/Junk' ), 'guess_prefix: Inbox Inbox/Junk' ) ;
  7278. is( 'Inbox.' , guess_prefix( 'Inbox', 'Inbox.Junk' ), 'guess_prefix: Inbox Inbox.Junk' ) ;
  7279. is( 'INBOX/' , guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr' ) ;
  7280. is( q{} , guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr', 'zzz' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr zzz' ) ;
  7281. is( q{} , guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  7282. is( q{} , guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  7283. note( 'Leaving tests_guess_prefix()' ) ;
  7284. return ;
  7285. }
  7286. sub get_prefix
  7287. {
  7288. my( $imap, $prefix_in, $prefix_opt, $Side, $folders_ref ) = @_ ;
  7289. my( $prefix_out, $prefix_guessed ) ;
  7290. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: Getting prefix\n" ) ;
  7291. $prefix_guessed = guess_prefix( @{ $folders_ref } ) ;
  7292. myprint( "$Side: guessing prefix from folder listing: [$prefix_guessed]\n" ) ;
  7293. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: Calling namespace capability\n" ) ;
  7294. if ( $imap->has_capability( 'namespace' ) ) {
  7295. my $r_namespace = $imap->namespace( ) ;
  7296. $prefix_out = $r_namespace->[0][0][0] ;
  7297. myprint( "$Side: prefix given by NAMESPACE: [$prefix_out]\n" ) ;
  7298. if ( defined $prefix_in ) {
  7299. myprint( "$Side: but using [$prefix_in] given by $prefix_opt\n" ) ;
  7300. $prefix_out = $prefix_in ;
  7301. return( $prefix_out ) ;
  7302. }else{
  7303. # all good
  7304. return( $prefix_out ) ;
  7305. }
  7306. }
  7307. else{
  7308. if ( defined $prefix_in ) {
  7309. myprint( "$Side: using [$prefix_in] given by $prefix_opt\n" ) ;
  7310. $prefix_out = $prefix_in ;
  7311. return( $prefix_out ) ;
  7312. }else{
  7313. myprint(
  7314. "$Side: No NAMESPACE capability so using guessed prefix [$prefix_guessed]\n",
  7315. help_to_guess_prefix( $imap, $prefix_opt ) ) ;
  7316. return( $prefix_guessed ) ;
  7317. }
  7318. }
  7319. return ;
  7320. }
  7321. sub guess_separator
  7322. {
  7323. my @foldernames = @_ ;
  7324. #return( undef ) unless ( @foldernames ) ;
  7325. my $sep_guessed ;
  7326. my %counter ;
  7327. foreach my $folder ( @foldernames ) {
  7328. $counter{'/'}++ while ( $folder =~ m{/}xg ) ; # count /
  7329. $counter{'.'}++ while ( $folder =~ m{\.}xg ) ; # count .
  7330. $counter{'\\\\'}++ while ( $folder =~ m{(\\){2}}xg ) ; # count \\
  7331. $counter{'\\'}++ while ( $folder =~ m{[^\\](\\){1}(?=[^\\])}xg ) ; # count \
  7332. }
  7333. my @race_sorted = sort { $counter{ $b } <=> $counter{ $a } } keys %counter ;
  7334. $sync->{ debug } and myprint( "@foldernames\n@race_sorted\n", %counter, "\n" ) ;
  7335. $sep_guessed = shift @race_sorted || $LAST_RESSORT_SEPARATOR ; # / when nothing found.
  7336. return( $sep_guessed ) ;
  7337. }
  7338. sub tests_guess_separator
  7339. {
  7340. note( 'Entering tests_guess_separator()' ) ;
  7341. ok( '/' eq guess_separator( ), 'guess_separator: no args' ) ;
  7342. ok( '/' eq guess_separator( 'abcd' ), 'guess_separator: abcd' ) ;
  7343. ok( '/' eq guess_separator( 'a/b/c.d' ), 'guess_separator: a/b/c.d' ) ;
  7344. ok( '.' eq guess_separator( 'a.b/c.d' ), 'guess_separator: a.b/c.d' ) ;
  7345. ok( '\\\\' eq guess_separator( 'a\\\\b\\\\c.c\\\\d/e/f' ), 'guess_separator: a\\\\b\\\\c.c\\\\d/e/f' ) ;
  7346. ok( '\\' eq guess_separator( 'a\\b\\c.c\\d/e/f' ), 'guess_separator: a\\b\\c.c\\d/e/f' ) ;
  7347. ok( '\\' eq guess_separator( 'a\\b' ), 'guess_separator: a\\b' ) ;
  7348. ok( '\\' eq guess_separator( 'a\\b\\c' ), 'guess_separator: a\\b\\c' ) ;
  7349. note( 'Leaving tests_guess_separator()' ) ;
  7350. return ;
  7351. }
  7352. sub get_separator
  7353. {
  7354. my( $imap, $sep_in, $sep_opt, $Side, $folders_ref ) = @_ ;
  7355. my( $sep_out, $sep_guessed ) ;
  7356. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: Getting separator\n" ) ;
  7357. $sep_guessed = guess_separator( @{ $folders_ref } ) ;
  7358. myprint( "$Side: guessing separator from folder listing: [$sep_guessed]\n" ) ;
  7359. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: calling namespace capability\n" ) ;
  7360. if ( $imap->has_capability( 'namespace' ) )
  7361. {
  7362. $sep_out = $imap->separator( ) ;
  7363. if ( defined $sep_out ) {
  7364. myprint( "$Side: separator given by NAMESPACE: [$sep_out]\n" ) ;
  7365. if ( defined $sep_in ) {
  7366. myprint( "$Side: but using [$sep_in] given by $sep_opt\n" ) ;
  7367. $sep_out = $sep_in ;
  7368. return( $sep_out ) ;
  7369. }else{
  7370. return( $sep_out ) ;
  7371. }
  7372. }else{
  7373. if ( defined $sep_in ) {
  7374. myprint( "$Side: NAMESPACE request failed but using [$sep_in] given by $sep_opt\n" ) ;
  7375. $sep_out = $sep_in ;
  7376. return( $sep_out ) ;
  7377. }else{
  7378. myprint(
  7379. "$Side: NAMESPACE request failed so using guessed separator [$sep_guessed]\n",
  7380. help_to_guess_sep( $imap, $sep_opt ) ) ;
  7381. return( $sep_guessed ) ;
  7382. }
  7383. }
  7384. }
  7385. else
  7386. {
  7387. if ( defined $sep_in ) {
  7388. myprint( "$Side: No NAMESPACE capability but using [$sep_in] given by $sep_opt\n" ) ;
  7389. $sep_out = $sep_in ;
  7390. return( $sep_out ) ;
  7391. }else{
  7392. myprint(
  7393. "$Side: No NAMESPACE capability, so using guessed separator [$sep_guessed]\n",
  7394. help_to_guess_sep( $imap, $sep_opt ) ) ;
  7395. return( $sep_guessed ) ;
  7396. }
  7397. }
  7398. return ;
  7399. }
  7400. sub help_to_guess_sep
  7401. {
  7402. my( $imap, $sep_opt ) = @_ ;
  7403. my $help_to_guess_sep = "You can set the separator character with the $sep_opt option,\n"
  7404. . "the complete listing of folders may help you to find it\n"
  7405. . folders_list_to_help( $imap ) ;
  7406. return( $help_to_guess_sep ) ;
  7407. }
  7408. sub help_to_guess_prefix
  7409. {
  7410. my( $imap, $prefix_opt ) = @_ ;
  7411. my $help_to_guess_prefix = "You can set the prefix namespace with the $prefix_opt option,\n"
  7412. . "the folowing listing of folders may help you to find it:\n"
  7413. . folders_list_to_help( $imap ) ;
  7414. return( $help_to_guess_prefix ) ;
  7415. }
  7416. sub folders_list_to_help
  7417. {
  7418. my( $imap ) = shift ;
  7419. my @folders = $imap->folders ;
  7420. my $listing = join q{}, map { "[$_]\n" } @folders ;
  7421. return( $listing ) ;
  7422. }
  7423. # Globals are $sync @h1_folders_all @h2_folders_all $prefix1 $prefix2
  7424. sub private_folders_separators_and_prefixes
  7425. {
  7426. # what are the private folders separators and prefixes for each server ?
  7427. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "Getting separators\n" ) ;
  7428. $sync->{ h1_sep } = get_separator( $sync->{imap1}, $sync->{ sep1 }, '--sep1', 'Host1', \@h1_folders_all ) ;
  7429. $sync->{ h2_sep } = get_separator( $sync->{imap2}, $sync->{ sep2 }, '--sep2', 'Host2', \@h2_folders_all ) ;
  7430. $sync->{ h1_prefix } = get_prefix( $sync->{imap1}, $prefix1, '--prefix1', 'Host1', \@h1_folders_all ) ;
  7431. $sync->{ h2_prefix } = get_prefix( $sync->{imap2}, $prefix2, '--prefix2', 'Host2', \@h2_folders_all ) ;
  7432. myprint( "Host1: separator and prefix: [$sync->{ h1_sep }][$sync->{ h1_prefix }]\n" ) ;
  7433. myprint( "Host2: separator and prefix: [$sync->{ h2_sep }][$sync->{ h2_prefix }]\n" ) ;
  7434. return ;
  7435. }
  7436. sub subfolder1
  7437. {
  7438. my $mysync = shift ;
  7439. my $subfolder1 = sanitize_subfolder( $mysync->{ subfolder1 } ) ;
  7440. if ( $subfolder1 )
  7441. {
  7442. # turns off automap
  7443. myprint( "Turning off automapping folders because of --subfolder1\n" ) ;
  7444. $mysync->{ automap } = undef ;
  7445. myprint( "Sanitizing subfolder1: [$mysync->{ subfolder1 }] => [$subfolder1]\n" ) ;
  7446. $mysync->{ subfolder1 } = $subfolder1 ;
  7447. if ( ! add_subfolder1_to_folderrec( $mysync ) )
  7448. {
  7449. $mysync->{nb_errors}++ ;
  7450. exit_clean( $mysync, $EXIT_SUBFOLDER1_NO_EXISTS, "subfolder1 $subfolder1 does not exist\n" ) ;
  7451. }
  7452. }
  7453. else
  7454. {
  7455. $mysync->{ subfolder1 } = undef ;
  7456. }
  7457. return ;
  7458. }
  7459. sub subfolder2
  7460. {
  7461. my $mysync = shift ;
  7462. my $subfolder2 = sanitize_subfolder( $mysync->{ subfolder2 } ) ;
  7463. if ( $subfolder2 )
  7464. {
  7465. # turns off automap
  7466. myprint( "Turning off automapping folders because of --subfolder2\n" ) ;
  7467. $mysync->{ automap } = undef ;
  7468. myprint( "Sanitizing subfolder2: [$mysync->{ subfolder2 }] => [$subfolder2]\n" ) ;
  7469. $mysync->{ subfolder2 } = $subfolder2 ;
  7470. set_regextrans2_for_subfolder2( $mysync ) ;
  7471. }
  7472. else
  7473. {
  7474. $mysync->{ subfolder2 } = undef ;
  7475. }
  7476. return ;
  7477. }
  7478. sub tests_sanitize_subfolder
  7479. {
  7480. note( 'Entering tests_sanitize_subfolder()' ) ;
  7481. is( undef, sanitize_subfolder( ), 'sanitize_subfolder: no args => undef' ) ;
  7482. is( undef, sanitize_subfolder( q{} ), 'sanitize_subfolder: empty => undef' ) ;
  7483. is( undef, sanitize_subfolder( ' ' ), 'sanitize_subfolder: blank => undef' ) ;
  7484. is( undef, sanitize_subfolder( ' ' ), 'sanitize_subfolder: blanks => undef' ) ;
  7485. is( 'abcd', sanitize_subfolder( 'abcd' ), 'sanitize_subfolder: abcd => abcd' ) ;
  7486. is( 'ab cd', sanitize_subfolder( ' ab cd ' ), 'sanitize_subfolder: " ab cd " => "ab cd"' ) ;
  7487. is( 'abcd', sanitize_subfolder( q{a&~b#\\c[]=d;} ), 'sanitize_subfolder: "a&~b#\\c[]=d;" => "abcd"' ) ;
  7488. is( 'aA.b-_ 8c/dD', sanitize_subfolder( 'aA.b-_ 8c/dD' ), 'sanitize_subfolder: aA.b-_ 8c/dD => aA.b-_ 8c/dD' ) ;
  7489. note( 'Leaving tests_sanitize_subfolder()' ) ;
  7490. return ;
  7491. }
  7492. sub sanitize_subfolder
  7493. {
  7494. my $subfolder = shift ;
  7495. if ( ! $subfolder )
  7496. {
  7497. return ;
  7498. }
  7499. # Remove edging blanks
  7500. $subfolder =~ s,^ +| +$,,g ;
  7501. # Keep only abcd...ABCD...0123... and -_./
  7502. $subfolder =~ tr,-_a-zA-Z0-9./ ,,cd ;
  7503. # A blank subfolder is not a subfolder
  7504. if ( ! $subfolder )
  7505. {
  7506. return ;
  7507. }
  7508. else
  7509. {
  7510. return $subfolder ;
  7511. }
  7512. }
  7513. sub tests_sanitize_host
  7514. {
  7515. note( 'Entering tests_sanitize_host()' ) ;
  7516. is( undef, sanitize_host( ), 'sanitize_host: no args => undef' ) ;
  7517. is( '', sanitize_host( '' ), 'sanitize_host: empty => empty' ) ;
  7518. is( 'imap.example.org', sanitize_host( 'imap.example.org' ), 'sanitize_host: imap.example.org => imap.example.org' ) ;
  7519. is( 'imap.example.org', sanitize_host( ' imap.example.org' ), 'sanitize_host: imap.example.org 1 => imap.example.org' ) ;
  7520. is( 'imap.example.org', sanitize_host( 'imap.example.org ' ), 'sanitize_host: imap.example.org 2 => imap.example.org' ) ;
  7521. is( 'imap.example.org', sanitize_host( 'imap.exam ple.org' ), 'sanitize_host: imap.example.org 3 => imap.example.org' ) ;
  7522. is( 'imap.example.org', sanitize_host( ' imap.exam ple.org ' ), 'sanitize_host: imap.example.org 4 => imap.example.org' ) ;
  7523. is( 'imap.example.org', sanitize_host( 'imap.exa/mple.org/' ), 'sanitize_host: imap.example.org/ => imap.example.org' ) ;
  7524. note( 'Leaving tests_sanitize_host()' ) ;
  7525. return ;
  7526. }
  7527. sub sanitize_host
  7528. {
  7529. my $host = shift ;
  7530. if ( ! defined $host ) { return ; }
  7531. $host =~ tr{ /}{}d ;
  7532. return $host ;
  7533. }
  7534. sub tests_add_subfolder1_to_folderrec
  7535. {
  7536. note( 'Entering tests_add_subfolder1_to_folderrec()' ) ;
  7537. is( undef, add_subfolder1_to_folderrec( ), 'add_subfolder1_to_folderrec: undef => undef' ) ;
  7538. is_deeply( [], [ add_subfolder1_to_folderrec( ) ], 'add_subfolder1_to_folderrec: no args => empty array' ) ;
  7539. @folderrec = () ;
  7540. my $mysync = {} ;
  7541. is_deeply( [ ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: empty => empty array' ) ;
  7542. is_deeply( [ ], [ @folderrec ], 'add_subfolder1_to_folderrec: empty => empty folderrec' ) ;
  7543. $mysync->{ subfolder1 } = 'SUBI' ;
  7544. $h1_folders_all{ 'SUBI' } = 1 ;
  7545. $mysync->{ h1_prefix } = 'INBOX/' ;
  7546. is_deeply( [ 'SUBI' ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: SUBI => SUBI' ) ;
  7547. is_deeply( [ 'SUBI' ], [ @folderrec ], 'add_subfolder1_to_folderrec: SUBI => folderrec SUBI ' ) ;
  7548. @folderrec = () ;
  7549. $mysync->{ subfolder1 } = 'SUBO' ;
  7550. is_deeply( [ ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: SUBO no exists => empty array' ) ;
  7551. is_deeply( [ ], [ @folderrec ], 'add_subfolder1_to_folderrec: SUBO no exists => empty folderrec' ) ;
  7552. $h1_folders_all{ 'INBOX/SUBO' } = 1 ;
  7553. is_deeply( [ 'INBOX/SUBO' ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: SUBO + INBOX/SUBO exists => INBOX/SUBO' ) ;
  7554. is_deeply( [ 'INBOX/SUBO' ], [ @folderrec ], 'add_subfolder1_to_folderrec: SUBO + INBOX/SUBO exists => INBOX/SUBO folderrec' ) ;
  7555. note( 'Leaving tests_add_subfolder1_to_folderrec()' ) ;
  7556. return ;
  7557. }
  7558. sub add_subfolder1_to_folderrec
  7559. {
  7560. my $mysync = shift ;
  7561. if ( ! $mysync || ! $mysync->{ subfolder1 } )
  7562. {
  7563. return ;
  7564. }
  7565. my $subfolder1 = $mysync->{ subfolder1 } ;
  7566. my $subfolder1_extended = $mysync->{ h1_prefix } . $subfolder1 ;
  7567. if ( exists $h1_folders_all{ $subfolder1 } )
  7568. {
  7569. myprint( qq{Acting like --folderrec "$subfolder1"\n} ) ;
  7570. push @folderrec, $subfolder1 ;
  7571. }
  7572. elsif ( exists $h1_folders_all{ $subfolder1_extended } )
  7573. {
  7574. myprint( qq{Acting like --folderrec "$subfolder1_extended"\n} ) ;
  7575. push @folderrec, $subfolder1_extended ;
  7576. }
  7577. else
  7578. {
  7579. myprint( qq{Nor folder "$subfolder1" nor "$subfolder1_extended" exists on host1\n} ) ;
  7580. }
  7581. return @folderrec ;
  7582. }
  7583. sub set_regextrans2_for_subfolder2
  7584. {
  7585. my $mysync = shift ;
  7586. unshift @{ $mysync->{ regextrans2 } },
  7587. q(s,^$mysync->{ h2_prefix }(.*),$mysync->{ h2_prefix }$mysync->{ subfolder2 }$mysync->{ h2_sep }$1,),
  7588. q(s,^INBOX$,$mysync->{ h2_prefix }$mysync->{ subfolder2 }$mysync->{ h2_sep }INBOX,),
  7589. q(s,^($mysync->{ h2_prefix }){2},$mysync->{ h2_prefix },);
  7590. #myprint( "@{ $mysync->{ regextrans2 } }\n" ) ;
  7591. return ;
  7592. }
  7593. # Looks like no globals here
  7594. sub tests_imap2_folder_name
  7595. {
  7596. note( 'Entering tests_imap2_folder_name()' ) ;
  7597. my $mysync = {} ;
  7598. $mysync->{ h1_prefix } = q{} ;
  7599. $mysync->{ h2_prefix } = q{} ;
  7600. $mysync->{ h1_sep } = '/';
  7601. $mysync->{ h2_sep } = '.';
  7602. $mysync->{ debug } and myprint( <<"EOS"
  7603. prefix1: [$mysync->{ h1_prefix }]
  7604. prefix2: [$mysync->{ h2_prefix }]
  7605. sep1: [$sync->{ h1_sep }]
  7606. sep2: [$sync->{ h2_sep }]
  7607. EOS
  7608. ) ;
  7609. $mysync->{ fixslash2 } = 0 ;
  7610. is( q{INBOX}, imap2_folder_name( $mysync, q{} ), 'imap2_folder_name: empty string' ) ;
  7611. is( 'blabla', imap2_folder_name( $mysync, 'blabla' ), 'imap2_folder_name: blabla' ) ;
  7612. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam' ), 'imap2_folder_name: spam/spam' ) ;
  7613. is( 'spam/spam', imap2_folder_name( $mysync, 'spam.spam' ), 'imap2_folder_name: spam.spam') ;
  7614. is( 'spam.spam/spam', imap2_folder_name( $mysync, 'spam/spam.spam' ), 'imap2_folder_name: spam/spam.spam' ) ;
  7615. is( 's pam.spam/sp am', imap2_folder_name( $mysync, 's pam/spam.sp am' ), 'imap2_folder_name: s pam/spam.sp am' ) ;
  7616. $mysync->{f1f2h}{ 'auto' } = 'moto' ;
  7617. is( 'moto', imap2_folder_name( $mysync, 'auto' ), 'imap2_folder_name: auto' ) ;
  7618. $mysync->{f1f2h}{ 'auto/auto' } = 'moto x 2' ;
  7619. is( 'moto x 2', imap2_folder_name( $mysync, 'auto/auto' ), 'imap2_folder_name: auto/auto' ) ;
  7620. @{ $mysync->{ regextrans2 } } = ( 's,/,X,g' ) ;
  7621. is( q{INBOX}, imap2_folder_name( $mysync, q{} ), 'imap2_folder_name: empty string [s,/,X,g]' ) ;
  7622. is( 'blabla', imap2_folder_name( $mysync, 'blabla' ), 'imap2_folder_name: blabla [s,/,X,g]' ) ;
  7623. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam'), 'imap2_folder_name: spam/spam [s,/,X,g]');
  7624. is('spamXspam', imap2_folder_name( $mysync, 'spam.spam'), 'imap2_folder_name: spam.spam [s,/,X,g]');
  7625. is('spam.spamXspam', imap2_folder_name( $mysync, 'spam/spam.spam'), 'imap2_folder_name: spam/spam.spam [s,/,X,g]');
  7626. @{ $mysync->{ regextrans2 } } = ( 's, ,_,g' ) ;
  7627. is('blabla', imap2_folder_name( $mysync, 'blabla'), 'imap2_folder_name: blabla [s, ,_,g]');
  7628. is('bla_bla', imap2_folder_name( $mysync, 'bla bla'), 'imap2_folder_name: blabla [s, ,_,g]');
  7629. @{ $mysync->{ regextrans2 } } = ( q{s,(.*),\U$1,} ) ;
  7630. is( 'BLABLA', imap2_folder_name( $mysync, 'blabla' ), q{imap2_folder_name: blabla [s,\U(.*)\E,$1,]} ) ;
  7631. $mysync->{ fixslash2 } = 1 ;
  7632. @{ $mysync->{ regextrans2 } } = ( ) ;
  7633. is(q{INBOX}, imap2_folder_name( $mysync, q{}), 'imap2_folder_name: empty string');
  7634. is('blabla', imap2_folder_name( $mysync, 'blabla'), 'imap2_folder_name: blabla');
  7635. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  7636. is('spam_spam', imap2_folder_name( $mysync, 'spam.spam'), 'imap2_folder_name: spam.spam -> spam_spam');
  7637. is('spam.spam_spam', imap2_folder_name( $mysync, 'spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam_spam');
  7638. is('s pam.spam_spa m', imap2_folder_name( $mysync, 's pam/spam.spa m'), 'imap2_folder_name: s pam/spam.spa m -> s pam.spam_spa m');
  7639. $mysync->{ h1_sep } = '.';
  7640. $mysync->{ h2_sep } = '/';
  7641. is( q{INBOX}, imap2_folder_name( $mysync, q{}), 'imap2_folder_name: empty string');
  7642. is('blabla', imap2_folder_name( $mysync, 'blabla'), 'imap2_folder_name: blabla');
  7643. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  7644. is('spam/spam', imap2_folder_name( $mysync, 'spam.spam'), 'imap2_folder_name: spam.spam -> spam/spam');
  7645. is('spam.spam/spam', imap2_folder_name( $mysync, 'spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam');
  7646. $mysync->{ fixslash2 } = 0 ;
  7647. $mysync->{ h1_prefix } = q{ };
  7648. is( 'spam.spam/spam', imap2_folder_name( $mysync, 'spam/spam.spam' ), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam' ) ;
  7649. is( 'spam.spam/spam', imap2_folder_name( $mysync, ' spam/spam.spam' ), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam' ) ;
  7650. $mysync->{ h1_sep } = '.' ;
  7651. $mysync->{ h2_sep } = '/' ;
  7652. $mysync->{ h1_prefix } = 'INBOX.' ;
  7653. $mysync->{ h2_prefix } = q{} ;
  7654. @{ $mysync->{ regextrans2 } } = ( q{s,(.*),\U$1,} ) ;
  7655. is( 'BLABLA', imap2_folder_name( $mysync, 'blabla' ), 'imap2_folder_name: blabla' ) ;
  7656. is( 'TEST/TEST/TEST/TEST', imap2_folder_name( $mysync, 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  7657. @{ $mysync->{ regextrans2 } } = ( q{s,(.*),\L$1,} ) ;
  7658. is( 'test/test/test/test', imap2_folder_name( $mysync, 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  7659. # INBOX
  7660. $mysync = {} ;
  7661. $mysync->{ h1_prefix } = q{Pf1.} ;
  7662. $mysync->{ h2_prefix } = q{Pf2/} ;
  7663. $mysync->{ h1_sep } = '.';
  7664. $mysync->{ h2_sep } = '/';
  7665. #
  7666. #$mysync->{ debug } = 1 ;
  7667. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'F1.F2.F3' ), 'imap2_folder_name: F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  7668. is( 'Pf2/F1/INBOX', imap2_folder_name( $mysync, 'F1.INBOX' ), 'imap2_folder_name: F1.INBOX -> Pf2/F1/INBOX' ) ;
  7669. is( 'INBOX', imap2_folder_name( $mysync, 'INBOX' ), 'imap2_folder_name: INBOX -> INBOX' ) ;
  7670. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'Pf1.F1.F2.F3' ), 'imap2_folder_name: Pf1.F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  7671. is( 'Pf2/F1/INBOX', imap2_folder_name( $mysync, 'Pf1.F1.INBOX' ), 'imap2_folder_name: Pf1.F1.INBOX -> Pf2/F1/INBOX' ) ;
  7672. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.INBOX' ), 'imap2_folder_name: Pf1.INBOX -> INBOX' ) ; # not Pf2/INBOX: Yes I can!
  7673. # subfolder2
  7674. $mysync = {} ;
  7675. $mysync->{ h1_prefix } = q{} ;
  7676. $mysync->{ h2_prefix } = q{} ;
  7677. $mysync->{ h1_sep } = '/';
  7678. $mysync->{ h2_sep } = '.';
  7679. set_regextrans2_for_subfolder2( $mysync ) ;
  7680. $mysync->{ subfolder2 } = 'S1.S2' ;
  7681. is( 'S1.S2.F1.F2.F3', imap2_folder_name( $mysync, 'F1/F2/F3' ), 'imap2_folder_name: F1/F2/F3 -> S1.S2.F1.F2.F3' ) ;
  7682. is( 'S1.S2.INBOX', imap2_folder_name( $mysync, 'INBOX' ), 'imap2_folder_name: F1/F2/F3 -> S1.S2.INBOX' ) ;
  7683. $mysync = {} ;
  7684. $mysync->{ h1_prefix } = q{Pf1/} ;
  7685. $mysync->{ h2_prefix } = q{Pf2.} ;
  7686. $mysync->{ h1_sep } = '/';
  7687. $mysync->{ h2_sep } = '.';
  7688. #$mysync->{ debug } = 1 ;
  7689. set_regextrans2_for_subfolder2( $mysync ) ;
  7690. $mysync->{ subfolder2 } = 'Pf2.S1.S2' ;
  7691. is( 'Pf2.S1.S2.F1.F2.F3', imap2_folder_name( $mysync, 'F1/F2/F3' ), 'imap2_folder_name: F1/F2/F3 -> Pf2.S1.S2.F1.F2.F3' ) ;
  7692. is( 'Pf2.S1.S2.INBOX', imap2_folder_name( $mysync, 'INBOX' ), 'imap2_folder_name: INBOX -> Pf2.S1.S2.INBOX' ) ;
  7693. is( 'Pf2.S1.S2.F1.F2.F3', imap2_folder_name( $mysync, 'Pf1/F1/F2/F3' ), 'imap2_folder_name: F1/F2/F3 -> Pf2.S1.S2.F1.F2.F3' ) ;
  7694. is( 'Pf2.S1.S2.INBOX', imap2_folder_name( $mysync, 'Pf1/INBOX' ), 'imap2_folder_name: INBOX -> Pf2.S1.S2.INBOX' ) ;
  7695. # subfolder1
  7696. # scenario as the reverse of the previous tests, separators point of vue
  7697. $mysync = {} ;
  7698. $mysync->{ h1_prefix } = q{Pf1.} ;
  7699. $mysync->{ h2_prefix } = q{Pf2/} ;
  7700. $mysync->{ h1_sep } = '.';
  7701. $mysync->{ h2_sep } = '/';
  7702. #$mysync->{ debug } = 1 ;
  7703. $mysync->{ subfolder1 } = 'S1.S2' ;
  7704. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'S1.S2.F1.F2.F3' ), 'imap2_folder_name: S1.S2.F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  7705. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'Pf1.S1.S2.F1.F2.F3' ), 'imap2_folder_name: Pf1.S1.S2.F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  7706. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.INBOX' ), 'imap2_folder_name: S1.S2.INBOX -> INBOX' ) ;
  7707. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2' ), 'imap2_folder_name: S1.S2 -> INBOX' ) ;
  7708. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.' ), 'imap2_folder_name: S1.S2. -> INBOX' ) ;
  7709. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.INBOX' ), 'imap2_folder_name: Pf1.S1.S2.INBOX -> INBOX' ) ;
  7710. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2' ), 'imap2_folder_name: Pf1.S1.S2 -> INBOX' ) ;
  7711. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.' ), 'imap2_folder_name: Pf1.S1.S2. -> INBOX' ) ;
  7712. $mysync->{ subfolder1 } = 'S1.S2.' ;
  7713. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'S1.S2.F1.F2.F3' ), 'imap2_folder_name: S1.S2.F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  7714. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'Pf1.S1.S2.F1.F2.F3' ), 'imap2_folder_name: Pf1.S1.S2.F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  7715. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.INBOX' ), 'imap2_folder_name: S1.S2.INBOX -> INBOX' ) ;
  7716. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2' ), 'imap2_folder_name: S1.S2 -> INBOX' ) ;
  7717. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.' ), 'imap2_folder_name: S1.S2. -> INBOX' ) ;
  7718. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.INBOX' ), 'imap2_folder_name: Pf1.S1.S2.INBOX -> INBOX' ) ;
  7719. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2' ), 'imap2_folder_name: Pf1.S1.S2 -> INBOX' ) ;
  7720. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.' ), 'imap2_folder_name: Pf1.S1.S2. -> INBOX' ) ;
  7721. # subfolder1
  7722. # scenario as Gmail
  7723. $mysync = {} ;
  7724. $mysync->{ h1_prefix } = q{} ;
  7725. $mysync->{ h2_prefix } = q{} ;
  7726. $mysync->{ h1_sep } = '/';
  7727. $mysync->{ h2_sep } = '/';
  7728. #$mysync->{ debug } = 1 ;
  7729. $mysync->{ subfolder1 } = 'S1/S2' ;
  7730. is( 'F1/F2/F3', imap2_folder_name( $mysync, 'S1/S2/F1/F2/F3' ), 'imap2_folder_name: S1/S2/F1/F2/F3 -> F1/F2/F3' ) ;
  7731. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/INBOX' ), 'imap2_folder_name: S1/S2/INBOX -> INBOX' ) ;
  7732. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2' ), 'imap2_folder_name: S1/S2 -> INBOX' ) ;
  7733. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/' ), 'imap2_folder_name: S1/S2/ -> INBOX' ) ;
  7734. $mysync->{ subfolder1 } = 'S1/S2/' ;
  7735. is( 'F1/F2/F3', imap2_folder_name( $mysync, 'S1/S2/F1/F2/F3' ), 'imap2_folder_name: S1/S2/F1/F2/F3 -> F1/F2/F3' ) ;
  7736. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/INBOX' ), 'imap2_folder_name: S1/S2/INBOX -> INBOX' ) ;
  7737. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2' ), 'imap2_folder_name: S1/S2 -> INBOX' ) ;
  7738. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/' ), 'imap2_folder_name: S1/S2/ -> INBOX' ) ;
  7739. note( 'Leaving tests_imap2_folder_name()' ) ;
  7740. return ;
  7741. }
  7742. # Global variables to remove:
  7743. # None?
  7744. sub imap2_folder_name
  7745. {
  7746. my $mysync = shift ;
  7747. my ( $h1_fold ) = shift ;
  7748. my ( $h2_fold ) ;
  7749. if ( $mysync->{f1f2h}{ $h1_fold } ) {
  7750. $h2_fold = $mysync->{f1f2h}{ $h1_fold } ;
  7751. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "f1f2 [$h1_fold] -> [$h2_fold]\n" ) ;
  7752. return( $h2_fold ) ;
  7753. }
  7754. if ( $mysync->{f1f2auto}{ $h1_fold } ) {
  7755. $h2_fold = $mysync->{f1f2auto}{ $h1_fold } ;
  7756. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "automap [$h1_fold] -> [$h2_fold]\n" ) ;
  7757. return( $h2_fold ) ;
  7758. }
  7759. if ( $mysync->{ subfolder1 } )
  7760. {
  7761. my $esc_h1_sep = "\\" . $mysync->{ h1_sep } ;
  7762. # case where subfolder1 has the sep1 at the end, then remove it
  7763. my $part_to_removed = remove_last_char_if_is( $mysync->{ subfolder1 }, $mysync->{ h1_sep } ) ;
  7764. # remove the subfolder1 part and the sep1 if present after
  7765. $h1_fold =~ s{$part_to_removed($esc_h1_sep)?}{} ;
  7766. #myprint( "h1_fold=$h1_fold\n" ) ;
  7767. }
  7768. if ( ( q{} eq $h1_fold ) or ( $mysync->{ h1_prefix } eq $h1_fold ) )
  7769. {
  7770. $h1_fold = 'INBOX' ;
  7771. }
  7772. $h2_fold = prefix_seperator_invertion( $mysync, $h1_fold ) ;
  7773. $h2_fold = regextrans2( $mysync, $h2_fold ) ;
  7774. return( $h2_fold ) ;
  7775. }
  7776. sub tests_remove_last_char_if_is
  7777. {
  7778. note( 'Entering tests_remove_last_char_if_is()' ) ;
  7779. is( undef, remove_last_char_if_is( ), 'remove_last_char_if_is: no args => undef' ) ;
  7780. is( q{}, remove_last_char_if_is( q{} ), 'remove_last_char_if_is: empty => empty' ) ;
  7781. is( q{}, remove_last_char_if_is( q{}, 'Z' ), 'remove_last_char_if_is: empty Z => empty' ) ;
  7782. is( q{}, remove_last_char_if_is( 'Z', 'Z' ), 'remove_last_char_if_is: Z Z => empty' ) ;
  7783. is( 'abc', remove_last_char_if_is( 'abcZ', 'Z' ), 'remove_last_char_if_is: abcZ Z => abc' ) ;
  7784. is( 'abcY', remove_last_char_if_is( 'abcY', 'Z' ), 'remove_last_char_if_is: abcY Z => abcY' ) ;
  7785. note( 'Leaving tests_remove_last_char_if_is()' ) ;
  7786. return ;
  7787. }
  7788. sub remove_last_char_if_is
  7789. {
  7790. my $string = shift ;
  7791. my $char = shift ;
  7792. if ( ! defined $string )
  7793. {
  7794. return ;
  7795. }
  7796. if ( ! defined $char )
  7797. {
  7798. return $string ;
  7799. }
  7800. my $last_char = substr $string, -1 ;
  7801. if ( $char eq $last_char )
  7802. {
  7803. chop $string ;
  7804. return $string ;
  7805. }
  7806. else
  7807. {
  7808. return $string ;
  7809. }
  7810. }
  7811. sub tests_prefix_seperator_invertion
  7812. {
  7813. note( 'Entering tests_prefix_seperator_invertion()' ) ;
  7814. is( undef, prefix_seperator_invertion( ), 'prefix_seperator_invertion: no args => undef' ) ;
  7815. is( q{}, prefix_seperator_invertion( undef, q{} ), 'prefix_seperator_invertion: empty string => empty string' ) ;
  7816. is( 'lalala', prefix_seperator_invertion( undef, 'lalala' ), 'prefix_seperator_invertion: lalala => lalala' ) ;
  7817. is( 'lal/ala', prefix_seperator_invertion( undef, 'lal/ala' ), 'prefix_seperator_invertion: lal/ala => lal/ala' ) ;
  7818. is( 'lal.ala', prefix_seperator_invertion( undef, 'lal.ala' ), 'prefix_seperator_invertion: lal.ala => lal.ala' ) ;
  7819. is( '////', prefix_seperator_invertion( undef, '////' ), 'prefix_seperator_invertion: //// => ////' ) ;
  7820. is( '.....', prefix_seperator_invertion( undef, '.....' ), 'prefix_seperator_invertion: ..... => .....' ) ;
  7821. my $mysync = {
  7822. h1_prefix => q{},
  7823. h2_prefix => q{},
  7824. h1_sep => '/',
  7825. h2_sep => '/',
  7826. } ;
  7827. is( q{}, prefix_seperator_invertion( $mysync, q{} ), 'prefix_seperator_invertion: $mysync empty string => empty string' ) ;
  7828. is( 'lalala', prefix_seperator_invertion( $mysync, 'lalala' ), 'prefix_seperator_invertion: $mysync lalala => lalala' ) ;
  7829. is( 'lal/ala', prefix_seperator_invertion( $mysync, 'lal/ala' ), 'prefix_seperator_invertion: $mysync lal/ala => lal/ala' ) ;
  7830. is( 'lal.ala', prefix_seperator_invertion( $mysync, 'lal.ala' ), 'prefix_seperator_invertion: $mysync lal.ala => lal.ala' ) ;
  7831. is( '////', prefix_seperator_invertion( $mysync, '////' ), 'prefix_seperator_invertion: $mysync //// => ////' ) ;
  7832. is( '.....', prefix_seperator_invertion( $mysync, '.....' ), 'prefix_seperator_invertion: $mysync ..... => .....' ) ;
  7833. $mysync = {
  7834. h1_prefix => 'PPP',
  7835. h2_prefix => 'QQQ',
  7836. h1_sep => 's',
  7837. h2_sep => 't',
  7838. } ;
  7839. is( q{QQQ}, prefix_seperator_invertion( $mysync, q{} ), 'prefix_seperator_invertion: PPPQQQst empty string => QQQ' ) ;
  7840. is( 'QQQlalala', prefix_seperator_invertion( $mysync, 'lalala' ), 'prefix_seperator_invertion: PPPQQQst lalala => QQQlalala' ) ;
  7841. is( 'QQQlal/ala', prefix_seperator_invertion( $mysync, 'lal/ala' ), 'prefix_seperator_invertion: PPPQQQst lal/ala => QQQlal/ala' ) ;
  7842. is( 'QQQlal.ala', prefix_seperator_invertion( $mysync, 'lal.ala' ), 'prefix_seperator_invertion: PPPQQQst lal.ala => QQQlal.ala' ) ;
  7843. is( 'QQQ////', prefix_seperator_invertion( $mysync, '////' ), 'prefix_seperator_invertion: PPPQQQst //// => QQQ////' ) ;
  7844. is( 'QQQ.....', prefix_seperator_invertion( $mysync, '.....' ), 'prefix_seperator_invertion: PPPQQQst ..... => QQQ.....' ) ;
  7845. is( 'QQQPlalala', prefix_seperator_invertion( $mysync, 'PPPPlalala' ), 'prefix_seperator_invertion: PPPQQQst PPPPlalala => QQQPlalala' ) ;
  7846. is( 'QQQ', prefix_seperator_invertion( $mysync, 'PPP' ), 'prefix_seperator_invertion: PPPQQQst PPP => QQQ' ) ;
  7847. is( 'QQQttt', prefix_seperator_invertion( $mysync, 'sss' ), 'prefix_seperator_invertion: PPPQQQst sss => QQQttt' ) ;
  7848. is( 'QQQt', prefix_seperator_invertion( $mysync, 's' ), 'prefix_seperator_invertion: PPPQQQst s => QQQt' ) ;
  7849. is( 'QQQtAAAtBBB', prefix_seperator_invertion( $mysync, 'PPPsAAAsBBB' ), 'prefix_seperator_invertion: PPPQQQst PPPsAAAsBBB => QQQtAAAtBBB' ) ;
  7850. note( 'Leaving tests_prefix_seperator_invertion()' ) ;
  7851. return ;
  7852. }
  7853. # Global variables to remove:
  7854. sub prefix_seperator_invertion
  7855. {
  7856. my $mysync = shift ;
  7857. my $h1_fold = shift ;
  7858. my $h2_fold ;
  7859. if ( not defined $h1_fold ) { return ; }
  7860. my $my_h1_prefix = $mysync->{ h1_prefix } || q{} ;
  7861. my $my_h2_prefix = $mysync->{ h2_prefix } || q{} ;
  7862. my $my_h1_sep = $mysync->{ h1_sep } || '/' ;
  7863. my $my_h2_sep = $mysync->{ h2_sep } || '/' ;
  7864. # first we remove the prefix
  7865. $h1_fold =~ s/^\Q$my_h1_prefix\E//x ;
  7866. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "removed host1 prefix: [$h1_fold]\n" ) ;
  7867. $h2_fold = separator_invert( $mysync, $h1_fold, $my_h1_sep, $my_h2_sep ) ;
  7868. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "inverted separators: [$h2_fold]\n" ) ;
  7869. # Adding the prefix supplied by namespace or the --prefix2 option
  7870. # except for INBOX or Inbox
  7871. if ( $h2_fold !~ m/^INBOX$/xi )
  7872. {
  7873. $h2_fold = $my_h2_prefix . $h2_fold ;
  7874. }
  7875. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "added host2 prefix: [$h2_fold]\n" ) ;
  7876. return( $h2_fold ) ;
  7877. }
  7878. sub tests_separator_invert
  7879. {
  7880. note( 'Entering tests_separator_invert()' ) ;
  7881. my $mysync = {} ;
  7882. $mysync->{ fixslash2 } = 0 ;
  7883. ok( not( defined separator_invert( ) ), 'separator_invert: no args' ) ;
  7884. ok( not( defined separator_invert( q{} ) ), 'separator_invert: not enough args' ) ;
  7885. ok( not( defined separator_invert( q{}, q{} ) ), 'separator_invert: not enough args' ) ;
  7886. ok( q{} eq separator_invert( $mysync, q{}, q{}, q{} ), 'separator_invert: 3 empty strings' ) ;
  7887. ok( 'lalala' eq separator_invert( $mysync, 'lalala', q{}, q{} ), 'separator_invert: empty separator' ) ;
  7888. ok( 'lalala' eq separator_invert( $mysync, 'lalala', '/', '/' ), 'separator_invert: same separator /' ) ;
  7889. ok( 'lal/ala' eq separator_invert( $mysync, 'lal/ala', '/', '/' ), 'separator_invert: same separator / 2' ) ;
  7890. ok( 'lal.ala' eq separator_invert( $mysync, 'lal/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  7891. ok( 'lal/ala' eq separator_invert( $mysync, 'lal.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  7892. ok( 'la.l/ala' eq separator_invert( $mysync, 'la/l.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  7893. ok( 'l/al.ala' eq separator_invert( $mysync, 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  7894. $mysync->{ fixslash2 } = 1 ;
  7895. ok( 'l_al.ala' eq separator_invert( $mysync, 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  7896. note( 'Leaving tests_separator_invert()' ) ;
  7897. return ;
  7898. }
  7899. # Global variables to remove:
  7900. #
  7901. sub separator_invert
  7902. {
  7903. my( $mysync, $h1_fold, $h1_separator, $h2_separator ) = @_ ;
  7904. return( undef ) if ( not all_defined( $mysync, $h1_fold, $h1_separator, $h2_separator ) ) ;
  7905. # The separator we hope we'll never encounter: 00000000 == 0x00
  7906. my $o_sep = "\000" ;
  7907. my $h2_fold = $h1_fold ;
  7908. $h2_fold =~ s,\Q$h2_separator,$o_sep,xg ;
  7909. $h2_fold =~ s,\Q$h1_separator,$h2_separator,xg ;
  7910. $h2_fold =~ s,\Q$o_sep,$h1_separator,xg ;
  7911. $h2_fold =~ s,/,_,xg if( $mysync->{ fixslash2 } and '/' ne $h2_separator and '/' eq $h1_separator ) ;
  7912. return( $h2_fold ) ;
  7913. }
  7914. sub regextrans2
  7915. {
  7916. my( $mysync, $h2_fold ) = @_ ;
  7917. # Transforming the folder name by the --regextrans2 option(s)
  7918. foreach my $regextrans2 ( @{ $mysync->{ regextrans2 } } ) {
  7919. my $h2_fold_before = $h2_fold ;
  7920. my $ret = eval "\$h2_fold =~ $regextrans2 ; 1 " ;
  7921. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "[$h2_fold_before] -> [$h2_fold] using regextrans2 [$regextrans2]\n" ) ;
  7922. if ( not ( defined $ret ) or $EVAL_ERROR ) {
  7923. $mysync->{nb_errors}++ ;
  7924. exit_clean( $mysync, $EX_USAGE,
  7925. "error: eval regextrans2 '$regextrans2': $EVAL_ERROR\n"
  7926. ) ;
  7927. }
  7928. }
  7929. return( $h2_fold ) ;
  7930. }
  7931. sub tests_decompose_regex
  7932. {
  7933. note( 'Entering tests_decompose_regex()' ) ;
  7934. ok( 1, 'decompose_regex 1' ) ;
  7935. ok( 0 == compare_lists( [ q{}, q{} ], [ decompose_regex( q{} ) ] ), 'decompose_regex empty string' ) ;
  7936. ok( 0 == compare_lists( [ '.*', 'lala' ], [ decompose_regex( 's/.*/lala/' ) ] ), 'decompose_regex s/.*/lala/' ) ;
  7937. note( 'Leaving tests_decompose_regex()' ) ;
  7938. return ;
  7939. }
  7940. sub decompose_regex
  7941. {
  7942. my $regex = shift ;
  7943. my( $left_part, $right_part ) ;
  7944. ( $left_part, $right_part ) = $regex =~ m{^s/((?:[^/]|\\/)+)/((?:[^/]|\\/)+)/}x;
  7945. return( q{}, q{} ) if not $left_part ;
  7946. return( $left_part, $right_part ) ;
  7947. }
  7948. sub tests_timenext
  7949. {
  7950. note( 'Entering tests_timenext()' ) ;
  7951. is( undef, timenext( ), 'timenext: no args => undef' ) ;
  7952. my $mysync ;
  7953. is( undef, timenext( $mysync ), 'timenext: undef => undef' ) ;
  7954. $mysync = {} ;
  7955. ok( time - timenext( $mysync ) <= 1e-02, 'timenext: defined first time => ~ time' ) ;
  7956. ok( timenext( $mysync ) <= 1e-02, 'timenext: second time => less than 1e-02' ) ;
  7957. ok( timenext( $mysync ) <= 1e-02, 'timenext: third time => less than 1e-02' ) ;
  7958. note( 'Leaving tests_timenext()' ) ;
  7959. return ;
  7960. }
  7961. sub timenext
  7962. {
  7963. my $mysync = shift ;
  7964. if ( ! defined $mysync )
  7965. {
  7966. return ;
  7967. }
  7968. my ( $timenow, $timediff ) ;
  7969. $mysync->{ timebefore } ||= 0; # epoch...
  7970. $timenow = time ;
  7971. $timediff = $timenow - $mysync->{ timebefore } ;
  7972. $mysync->{ timebefore } = $timenow ;
  7973. # myprint( "timenext: $timediff\n" ) ;
  7974. return( $timediff ) ;
  7975. }
  7976. sub tests_timesince
  7977. {
  7978. note( 'Entering tests_timesince()' ) ;
  7979. ok( timesince( time - 1 ) - 1 <= 1e-02, 'timesince: time - 1 => <= 1 + 1e-02' ) ;
  7980. ok( timesince( time ) <= 1e-02, 'timesince: time => <= 1e-02' ) ;
  7981. ok( timesince( ) - time <= 1e-02, 'timesince: no args => <= time + 1e-02' ) ;
  7982. note( 'Leaving tests_timesince()' ) ;
  7983. return ;
  7984. }
  7985. sub timesince
  7986. {
  7987. my $timeinit = shift || 0 ;
  7988. my ( $timenow, $timediff ) ;
  7989. $timenow = time ;
  7990. $timediff = $timenow - $timeinit ;
  7991. # Often used in a division so no 0 but a nano seconde.
  7992. return( max( $timediff, min( 1e-09, $timediff ) ) ) ;
  7993. }
  7994. sub tests_regexflags
  7995. {
  7996. note( 'Entering tests_regexflags()' ) ;
  7997. my $mysync = {} ;
  7998. ok( q{} eq regexflags( $mysync, q{} ), 'regexflags, null string q{}' ) ;
  7999. ok( q{\Seen NonJunk $Spam} eq regexflags( $mysync, q{\Seen NonJunk $Spam} ), q{regexflags, nothing to do} ) ;
  8000. @{ $mysync->{ regexflag } } = ('I am BAD' ) ;
  8001. ok( not ( defined regexflags( $mysync, q{} ) ), 'regexflags, bad regex' ) ;
  8002. @{ $mysync->{ regexflag } } = ( 's/NonJunk//g' ) ;
  8003. ok( q{\Seen $Spam} eq regexflags( $mysync, q{\Seen NonJunk $Spam} ), q{regexflags, remove NonJunk: 's/NonJunk//g'} ) ;
  8004. @{ $mysync->{ regexflag } } = ( q{s/\$Spam//g} ) ;
  8005. ok( q{\Seen NonJunk } eq regexflags( $mysync, q{\Seen NonJunk $Spam} ), q{regexflags, remove $Spam: 's/\$Spam//g'} ) ;
  8006. @{ $mysync->{ regexflag } } = ( 's/\\\\Seen//g' ) ;
  8007. ok( q{ NonJunk $Spam} eq regexflags( $mysync, q{\Seen NonJunk $Spam} ), q{regexflags, remove \Seen: 's/\\\\\\\\Seen//g'} ) ;
  8008. @{ $mysync->{ regexflag } } = ( 's/(\s|^)[^\\\\]\w+//g' ) ;
  8009. ok( q{\Seen \Middle \End} eq regexflags( $mysync, q{\Seen NonJunk \Middle $Spam \End} ), q{regexflags: only \word among \Seen NonJunk \Middle $Spam \End} ) ;
  8010. ok( q{ \Seen \Middle \End1} eq regexflags( $mysync, q{Begin \Seen NonJunk \Middle $Spam \End1 End} ),
  8011. q{regexflags: only \word among Begin \Seen NonJunk \Middle $Spam \End1 End} ) ;
  8012. @{ $mysync->{ regexflag } } = ( q{s/.*?(Keep1|Keep2|Keep3)/$1 /g} ) ;
  8013. ok( 'Keep1 Keep2 ReB' eq regexflags( $mysync, 'ReA Keep1 REM Keep2 ReB' ), 'Keep only regex' ) ;
  8014. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM REM Keep1 Keep2' ), 'Keep only regex' ) ;
  8015. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 REM REM Keep2' ), 'Keep only regex' ) ;
  8016. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM Keep1 REM REM Keep2' ), 'Keep only regex' ) ;
  8017. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 Keep2' ), 'Keep only regex' ) ;
  8018. ok( 'Keep1 ' eq regexflags( $mysync, 'REM Keep1' ), 'Keep only regex' ) ;
  8019. @{ $mysync->{ regexflag } } = ( q{s/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g} ) ;
  8020. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 Keep2 ReB' ), 'Keep only regex' ) ;
  8021. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 Keep2 REM REM REM' ), 'Keep only regex' ) ;
  8022. ok( 'Keep2 ' eq regexflags( $mysync, 'Keep2 REM REM REM' ), 'Keep only regex' ) ;
  8023. @{ $mysync->{ regexflag } } = ( q{s/.*?(Keep1|Keep2|Keep3)/$1 /g},
  8024. 's/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g' ) ;
  8025. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM Keep1 REM Keep2 REM' ), 'Keep only regex' ) ;
  8026. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 REM Keep2 REM' ), 'Keep only regex' ) ;
  8027. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM Keep1 Keep2 REM' ), 'Keep only regex' ) ;
  8028. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM Keep1 REM Keep2' ), 'Keep only regex' ) ;
  8029. ok( 'Keep1 Keep2 Keep3 ' eq regexflags( $mysync, 'REM Keep1 REM Keep2 REM REM Keep3 REM' ), 'Keep only regex' ) ;
  8030. ok( 'Keep1 ' eq regexflags( $mysync, 'REM REM Keep1 REM REM REM ' ), 'Keep only regex' ) ;
  8031. ok( 'Keep1 Keep3 ' eq regexflags( $mysync, 'RE1 Keep1 RE2 Keep3 RE3 RE4 RE5 ' ), 'Keep only regex' ) ;
  8032. @{ $mysync->{ regexflag } } = ( 's/(.*)/$1 jrdH8u/' ) ;
  8033. ok('REM REM REM REM REM jrdH8u' eq regexflags( $mysync, 'REM REM REM REM REM' ), q{Add jrdH8u 's/(.*)/\$1 jrdH8u/'} ) ;
  8034. @{ $mysync->{ regexflag } } = ('s/jrdH8u *//' );
  8035. ok('REM REM REM REM REM ' eq regexflags( $mysync, 'REM REM REM REM REM jrdH8u' ), q{Remove jrdH8u s/jrdH8u *//} ) ;
  8036. @{ $mysync->{ regexflag } } = (
  8037. 's/.*?(?:(\\\\(?:Answered|Flagged|Deleted|Seen|Draft)\s?)|$)/defined($1)?$1:q()/eg'
  8038. );
  8039. ok( '\\Deleted \\Answered '
  8040. eq regexflags( $mysync, 'Blabla \$Junk \\Deleted machin \\Answered truc' ),
  8041. 'Keep only regex: Exchange case (Phil)' ) ;
  8042. ok( q{} eq regexflags( $mysync, q{} ), 'Keep only regex: Exchange case, null string (Phil)' ) ;
  8043. ok( q{}
  8044. eq regexflags( $mysync, 'Blabla $Junk machin truc' ),
  8045. 'Keep only regex: Exchange case, no accepted flags (Phil)' ) ;
  8046. ok('\\Deleted \\Answered \\Draft \\Flagged '
  8047. eq regexflags( $mysync, '\\Deleted \\Answered \\Draft \\Flagged ' ),
  8048. 'Keep only regex: Exchange case (Phil)' ) ;
  8049. @{ $mysync->{ regexflag } } = ( 's/\\\\Flagged//g' ) ;
  8050. is('\Deleted \Answered \Draft ',
  8051. regexflags( $mysync, '\\Deleted \\Answered \\Draft \\Flagged ' ),
  8052. 'regexflags: remove \Flagged 1' ) ;
  8053. is('\\Deleted \\Answered \\Draft',
  8054. regexflags( $mysync, '\\Deleted \\Flagged \\Answered \\Draft' ),
  8055. 'regexflags: remove \Flagged 2' ) ;
  8056. # I didn't understand why it gives \F
  8057. # https://perldoc.perl.org/perlrebackslash.html
  8058. # \F Foldcase till \E. Not in [].
  8059. # https://perldoc.perl.org/functions/fc.html
  8060. # \F Not available in old Perl so I comment the test
  8061. # @{ $mysync->{ regexflag } } = ( 's/\\Flagged/X/g' ) ;
  8062. #is('\Deleted FX \Answered \FX \Draft \FX',
  8063. #regexflags( '\Deleted Flagged \Answered \Flagged \Draft \Flagged' ),
  8064. # 'regexflags: remove \Flagged 3 mistery...' ) ;
  8065. $mysync->{ regexflag } = [ ] ;
  8066. $mysync->{ filterbuggyflags } = 1 ;
  8067. filterbuggyflags( $mysync ) ;
  8068. is( '\Deleted \Answered \Draft \Flagged',
  8069. regexflags( $mysync, '\\Deleted \\Answered \\RECEIPTCHECKED \\Draft \\Indexed \\Flagged' ),
  8070. 'regexflags: remove famous /X 1' ) ;
  8071. is( '\\Deleted \\Flagged \\Answered \\Draft',
  8072. regexflags( $mysync, '\\Deleted \\RECEIPTCHECKED \\Flagged \\Answered \\Indexed \\Draft' ),
  8073. 'regexflags: remove famous /X 2' ) ;
  8074. is( '\ ', '\\ ', 'regexflags: \ is \\ ' ) ;
  8075. is( '\\ ', '\\ ', 'regexflags: \\ is \\ ' ) ;
  8076. is( '\\ \ ', '\ \\ ', 'regexflags: \\ \ is \ \\ ' ) ;
  8077. note( 'Leaving tests_regexflags()' ) ;
  8078. return ;
  8079. }
  8080. sub regexflags
  8081. {
  8082. my $mysync = shift ;
  8083. my $flags = shift ;
  8084. foreach my $regexflag ( @{ $mysync->{ regexflag } } )
  8085. {
  8086. my $flags_orig = $flags ;
  8087. $debugflags and myprint( "eval \$flags =~ $regexflag\n" ) ;
  8088. my $ret = eval "\$flags =~ $regexflag ; 1 " ;
  8089. $debugflags and myprint( "regexflag $regexflag [$flags_orig] -> [$flags]\n" ) ;
  8090. if( not ( defined $ret ) or $EVAL_ERROR ) {
  8091. myprint( "Error: eval regexflag '$regexflag': $EVAL_ERROR\n" ) ;
  8092. return( undef ) ;
  8093. }
  8094. }
  8095. return( $flags ) ;
  8096. }
  8097. sub filterbuggyflags
  8098. {
  8099. my $mysync = shift ;
  8100. if ( $mysync->{ filterbuggyflags } )
  8101. {
  8102. unshift @{ $mysync->{ regexflag } }, buggyflagsregex( ) ;
  8103. }
  8104. return ;
  8105. }
  8106. sub tests_remove_doublequotes_if_any
  8107. {
  8108. note( 'Entering tests_remove_doublequotes_if_any()' ) ;
  8109. # the number of tests is stupid here
  8110. is( undef, remove_doublequotes_if_any( ), 'remove_doublequotes_if_any: no args => undef' ) ;
  8111. is( q{}, remove_doublequotes_if_any( q{} ), 'remove_doublequotes_if_any: empty string => empty string' ) ;
  8112. is( q{}, remove_doublequotes_if_any( q{""} ), 'remove_doublequotes_if_any: double-quotes => empty string' ) ;
  8113. is( q{}, remove_doublequotes_if_any( q{"""} ), 'remove_doublequotes_if_any: double-quotes => empty string' ) ;
  8114. is( q{}, remove_doublequotes_if_any( q{"""} ), 'remove_doublequotes_if_any: double-quotes => empty string' ) ;
  8115. is( q{toto}, remove_doublequotes_if_any( q{"toto"} ), 'remove_doublequotes_if_any: "toto" => toto' ) ;
  8116. is( q{toto}, remove_doublequotes_if_any( q{toto} ), 'remove_doublequotes_if_any: toto => toto' ) ;
  8117. is( q{toto}, remove_doublequotes_if_any( q{to"to} ), 'remove_doublequotes_if_any: to"to => toto' ) ;
  8118. is( q{toto}, remove_doublequotes_if_any( q{toto"} ), 'remove_doublequotes_if_any: toto" => toto' ) ;
  8119. is( q{toto}, remove_doublequotes_if_any( q{"toto} ), 'remove_doublequotes_if_any: "toto => toto' ) ;
  8120. is( q{toto}, remove_doublequotes_if_any( q{"to"to} ), 'remove_doublequotes_if_any: "to"to => toto' ) ;
  8121. is( q{toto}, remove_doublequotes_if_any( q{to"to"} ), 'remove_doublequotes_if_any: to"to" => toto' ) ;
  8122. is( q{toto}, remove_doublequotes_if_any( q{to\"to} ), 'remove_doublequotes_if_any: to\"to => toto' ) ;
  8123. is( q{toto}, remove_doublequotes_if_any( q{toto\"} ), 'remove_doublequotes_if_any: toto\" => toto' ) ;
  8124. is( q{toto}, remove_doublequotes_if_any( q{\"toto} ), 'remove_doublequotes_if_any: \"toto => toto' ) ;
  8125. is( q{toto}, remove_doublequotes_if_any( q{\"to\"to} ), 'remove_doublequotes_if_any: \"to\"to => toto' ) ;
  8126. is( q{toto}, remove_doublequotes_if_any( q{to\"to\"} ), 'remove_doublequotes_if_any: to\"to" => toto' ) ;
  8127. note( 'Leaving tests_remove_doublequotes_if_any()' ) ;
  8128. return ;
  8129. }
  8130. sub remove_doublequotes_if_any
  8131. {
  8132. my $string = shift ;
  8133. if ( ! defined $string ) { return ; }
  8134. $string =~ s/\\\"//g ;
  8135. $string =~ tr/"//d ;
  8136. return $string ;
  8137. }
  8138. # No globals here
  8139. sub acls_sync
  8140. {
  8141. # https://tools.ietf.org/html/rfc4314
  8142. # Standard Rights:
  8143. # https://tools.ietf.org/html/rfc4314#section-2.1
  8144. my( $mysync, $h1_fold, $h2_fold ) = @_ ;
  8145. if ( $mysync->{ syncacls } ) {
  8146. my $h1_hash = $mysync->{imap1}->getacl($h1_fold)
  8147. or myprint( "Host1: Could not getacl for $h1_fold: $EVAL_ERROR\n" ) ;
  8148. my $h2_hash = $mysync->{imap2}->getacl($h2_fold)
  8149. or myprint( "Host2: Could not getacl for $h2_fold: $EVAL_ERROR\n" ) ;
  8150. my %users = map { ($_, 1) } ( keys %{ $h1_hash} , keys %{ $h2_hash } ) ;
  8151. foreach my $user (sort keys %users ) {
  8152. my $h1_acl = remove_doublequotes_if_any( $h1_hash->{$user} ) || '' ;
  8153. my $h2_acl = remove_doublequotes_if_any( $h2_hash->{$user} ) || '' ;
  8154. myprint( "Host1: user $user has acl [$h1_acl] on host1\n" ) ;
  8155. myprint( "Host2: user $user has acl [$h2_acl] on host2\n" ) ;
  8156. # removes surrounding double-quotes if any
  8157. my $user_no_quotes = remove_doublequotes_if_any( $user ) ;
  8158. if ( $h1_hash->{$user}
  8159. && $h2_hash->{$user}
  8160. && $h1_hash->{$user} eq $h2_hash->{$user} )
  8161. {
  8162. myprint( "Host2: user $user_no_quotes has already the same acl, no need to set it.\n" ) ;
  8163. next ;
  8164. }
  8165. myprint( "Host2: setting acl for folder $h2_fold user $user_no_quotes acl $h1_acl $mysync->{dry_message}\n" ) ;
  8166. unless ( $mysync->{dry} ) {
  8167. $mysync->{imap2}->setacl( $h2_fold, $user_no_quotes, $h1_acl )
  8168. or myprint( "Could not set acl for user $user_no_quotes on host2: $EVAL_ERROR\n" ) ;
  8169. }
  8170. }
  8171. }
  8172. return ;
  8173. }
  8174. sub tests_permanentflags
  8175. {
  8176. note( 'Entering tests_permanentflags()' ) ;
  8177. my $string;
  8178. ok(q{} eq permanentflags(' * OK [PERMANENTFLAGS (\* \Draft \Answered)] Limited'),
  8179. 'permanentflags \*');
  8180. ok('\Draft \Answered' eq permanentflags(' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited'),
  8181. 'permanentflags \Draft \Answered');
  8182. ok('\Draft \Answered'
  8183. eq permanentflags('Blabla',
  8184. ' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited',
  8185. 'Blabla'),
  8186. 'permanentflags \Draft \Answered'
  8187. );
  8188. ok(q{} eq permanentflags('Blabla'), 'permanentflags nothing');
  8189. note( 'Leaving tests_permanentflags()' ) ;
  8190. return ;
  8191. }
  8192. sub permanentflags
  8193. {
  8194. my @lines = @_ ;
  8195. foreach my $line (@lines) {
  8196. if ( $line =~ m{\[PERMANENTFLAGS\s\(([^)]+?)\)\]}x ) {
  8197. ( $debugflags or $sync->{ debug } ) and myprint( "permanentflags: $line" ) ;
  8198. my $permanentflags = $1 ;
  8199. if ( $permanentflags =~ m{\\\*}x )
  8200. {
  8201. $permanentflags = q{} ;
  8202. }
  8203. return( $permanentflags ) ;
  8204. } ;
  8205. }
  8206. return( q{} ) ;
  8207. }
  8208. sub tests_flags_filter
  8209. {
  8210. note( 'Entering tests_flags_filter()' ) ;
  8211. ok( '\Seen' eq flags_filter('\Seen', '\Draft \Seen \Answered'), 'flags_filter ' );
  8212. ok( q{} eq flags_filter('\Seen', '\Draft \Answered'), 'flags_filter ' );
  8213. ok( '\Seen' eq flags_filter('\Seen', '\Seen'), 'flags_filter ' );
  8214. ok( '\Seen' eq flags_filter('\Seen', ' \Seen '), 'flags_filter ' );
  8215. ok( '\Seen \Draft'
  8216. eq flags_filter('\Seen \Draft', '\Draft \Seen \Answered'), 'flags_filter ' );
  8217. ok( '\Seen \Draft'
  8218. eq flags_filter('\Seen \Draft', ' \Draft \Seen \Answered '), 'flags_filter ' );
  8219. note( 'Leaving tests_flags_filter()' ) ;
  8220. return ;
  8221. }
  8222. sub flags_filter
  8223. {
  8224. my( $flags, $allowed_flags ) = @_ ;
  8225. my @flags = split /\s+/x, $flags ;
  8226. my %allowed_flags = map { $_ => 1 } split q{ }, $allowed_flags ;
  8227. my @flags_out = map { exists $allowed_flags{$_} ? $_ : () } @flags ;
  8228. my $flags_out = join q{ }, @flags_out ;
  8229. return( $flags_out ) ;
  8230. }
  8231. sub tests_flagscase
  8232. {
  8233. note( 'Entering tests_flagscase()' ) ;
  8234. ok( '\Seen' eq flagscase( '\Seen' ), 'flagscase: \Seen -> \Seen' ) ;
  8235. ok( '\Seen' eq flagscase( '\SEEN' ), 'flagscase: \SEEN -> \Seen' ) ;
  8236. ok( '\Seen \Draft' eq flagscase( '\SEEN \DRAFT' ), 'flagscase: \SEEN \DRAFT -> \Seen \Draft' ) ;
  8237. ok( '\Draft \Seen' eq flagscase( '\DRAFT \SEEN' ), 'flagscase: \DRAFT \SEEN -> \Draft \Seen' ) ;
  8238. ok( '\Draft LALA \Seen' eq flagscase( '\DRAFT LALA \SEEN' ), 'flagscase: \DRAFT LALA \SEEN -> \Draft LALA \Seen' ) ;
  8239. ok( '\Draft lala \Seen' eq flagscase( '\DRAFT lala \SEEN' ), 'flagscase: \DRAFT lala \SEEN -> \Draft lala \Seen' ) ;
  8240. note( 'Leaving tests_flagscase()' ) ;
  8241. return ;
  8242. }
  8243. sub flagscase
  8244. {
  8245. my $flags = shift ;
  8246. my @flags = split /\s+/x, $flags ;
  8247. my %rfc_flags = map { $_ => 1 } split q{ }, '\Answered \Flagged \Deleted \Seen \Draft' ;
  8248. my @flags_out = map { exists $rfc_flags{ ucsecond( lc $_ ) } ? ucsecond( lc $_ ) : $_ } @flags ;
  8249. my $flags_out = join q{ }, @flags_out ;
  8250. return( $flags_out ) ;
  8251. }
  8252. sub tests_flags_for_host2
  8253. {
  8254. note( 'Entering tests_flags_for_host2()' ) ;
  8255. is( undef, flags_for_host2( ), 'flags_for_host2: no args => undef' ) ;
  8256. my $mysync ;
  8257. is( undef, flags_for_host2( $mysync ), 'flags_for_host2: undef => undef' ) ;
  8258. $mysync = { } ;
  8259. is( undef, flags_for_host2( $mysync ), 'flags_for_host2: nothing => undef' ) ;
  8260. is( q{}, flags_for_host2( $mysync, '' ), 'flags_for_host2: no flags => empty string' ) ;
  8261. is( q{}, flags_for_host2( $mysync, '\Recent' ), 'flags_for_host2: \Recent => empty string' ) ;
  8262. is( q{\Seen}, flags_for_host2( $mysync, '\Recent \Seen' ), 'flags_for_host2: \Recent \Seen => \Seen' ) ;
  8263. is( q{\Deleted \Seen}, flags_for_host2( $mysync, '\Deleted \Recent \Seen' ), 'flags_for_host2: \Deleted \Recent \Seen => \Deleted \Seen' ) ;
  8264. $mysync->{ flagscase } = 0 ;
  8265. is( q{\DELETED \Seen}, flags_for_host2( $mysync, '\DELETED \Seen' ), 'flags_for_host2: flagscase = 0 \DELETED \Seen => \DELETED \Seen' ) ;
  8266. $mysync->{ flagscase } = 1 ;
  8267. is( q{\Deleted \Seen}, flags_for_host2( $mysync, '\DELETED \Seen' ), 'flags_for_host2: flagscase = 1 \DELETED \Seen => \Deleted \Seen' ) ;
  8268. $mysync->{ filterflags } = 0 ;
  8269. is( q{\Seen \Blabla}, flags_for_host2( $mysync, '\Seen \Blabla', '\Seen \Junk' ), 'flags_for_host2: filterflags = 0 \Seen \Blabla among \Seen \Junk => \Seen \Blabla' ) ;
  8270. $mysync->{ filterflags } = 1 ;
  8271. is( q{\Seen}, flags_for_host2( $mysync, '\Seen \Blabla', '\Seen \Junk' ), 'flags_for_host2: filterflags = 1 \Seen \Blabla among \Seen \Junk => \Seen' ) ;
  8272. $mysync->{ filterflags } = 1 ;
  8273. is( q{\Seen \Blabla}, flags_for_host2( $mysync, '\Seen \Blabla', '' ), 'flags_for_host2: filterflags = 1 \Seen \Blabla among "" => \Seen \Blabla' ) ;
  8274. note( 'Leaving tests_flags_for_host2()' ) ;
  8275. return ;
  8276. }
  8277. sub flags_for_host2
  8278. {
  8279. my $mysync = shift ;
  8280. my $h1_flags = shift ;
  8281. my $permanentflags2 = shift ;
  8282. if ( ! all_defined( $mysync, $h1_flags ) ) { return ; } ;
  8283. # RFC 2060: This flag can not be altered by any client
  8284. $h1_flags =~ s@\\Recent\s?@@xgi ;
  8285. my $h1_flags_re ;
  8286. if ( $mysync->{ regexflag } and defined( $h1_flags_re = regexflags( $mysync, $h1_flags ) ) ) {
  8287. $h1_flags = $h1_flags_re ;
  8288. }
  8289. if ( $mysync->{ flagscase } )
  8290. {
  8291. $h1_flags = flagscase( $h1_flags ) ;
  8292. }
  8293. if ( $permanentflags2 and $mysync->{ filterflags } )
  8294. {
  8295. $h1_flags = flags_filter( $h1_flags, $permanentflags2 ) ;
  8296. }
  8297. return( $h1_flags ) ;
  8298. }
  8299. sub ucsecond
  8300. {
  8301. my $string = shift ;
  8302. my $output ;
  8303. return( $string ) if ( 1 >= length $string ) ;
  8304. $output = ( substr( $string, 0, 1) ) . ( uc substr $string, 1, 1 ) . ( substr $string, 2 ) ;
  8305. #myprint( "UUU $string -> $output\n" ) ;
  8306. return( $output ) ;
  8307. }
  8308. sub tests_ucsecond
  8309. {
  8310. note( 'Entering tests_ucsecond()' ) ;
  8311. ok( 'aBcde' eq ucsecond( 'abcde' ), 'ucsecond: abcde -> aBcde' ) ;
  8312. ok( 'ABCDE' eq ucsecond( 'ABCDE' ), 'ucsecond: ABCDE -> ABCDE' ) ;
  8313. ok( 'ABCDE' eq ucsecond( 'AbCDE' ), 'ucsecond: AbCDE -> ABCDE' ) ;
  8314. ok( 'ABCde' eq ucsecond( 'AbCde' ), 'ucsecond: AbCde -> ABCde' ) ;
  8315. ok( 'A' eq ucsecond( 'A' ), 'ucsecond: A -> A' ) ;
  8316. ok( 'AB' eq ucsecond( 'Ab' ), 'ucsecond: Ab -> AB' ) ;
  8317. ok( '\B' eq ucsecond( '\b' ), 'ucsecond: \b -> \B' ) ;
  8318. ok( '\Bcde' eq ucsecond( '\bcde' ), 'ucsecond: \bcde -> \Bcde' ) ;
  8319. note( 'Leaving tests_ucsecond()' ) ;
  8320. return ;
  8321. }
  8322. sub select_msgs
  8323. {
  8324. my ( $imap, $msgs_all_hash_ref, $search_cmd, $abletosearch, $folder ) = @_ ;
  8325. my ( @msgs ) ;
  8326. if ( $abletosearch ) {
  8327. @msgs = select_msgs_by_search( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  8328. }else{
  8329. @msgs = select_msgs_by_fetch( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  8330. }
  8331. return( @msgs ) ;
  8332. }
  8333. sub select_msgs_by_search
  8334. {
  8335. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  8336. my ( @msgs, @msgs_all ) ;
  8337. # Need to have the whole list in msgs_all_hash_ref
  8338. # without calling messages() several times.
  8339. # Need all messages list to avoid deleting useful cache part
  8340. # in case of --search or --minage or --maxage
  8341. if ( ( defined $msgs_all_hash_ref and $usecache )
  8342. or ( not defined $maxage and not defined $minage and not defined $search_cmd )
  8343. ) {
  8344. $debugdev and myprint( "Calling messages()\n" ) ;
  8345. @msgs_all = $imap->messages( ) ;
  8346. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  8347. if ( defined $msgs_all_hash_ref ) {
  8348. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  8349. }
  8350. # return all messages
  8351. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  8352. return( @msgs_all ) ;
  8353. }
  8354. }
  8355. if ( defined $search_cmd ) {
  8356. @msgs = $imap->search( $search_cmd ) ;
  8357. return( @msgs ) ;
  8358. }
  8359. # we are here only if $maxage or $minage is defined
  8360. @msgs = select_msgs_by_age( $imap ) ;
  8361. return( @msgs );
  8362. }
  8363. sub select_msgs_by_fetch
  8364. {
  8365. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  8366. my ( @msgs, @msgs_all, %fetch ) ;
  8367. # Need to have the whole list in msgs_all_hash_ref
  8368. # without calling messages() several times.
  8369. # Need all messages list to avoid deleting useful cache part
  8370. # in case of --search or --minage or --maxage
  8371. $debugdev and myprint( "Calling fetch_hash()\n" ) ;
  8372. my $fetch_hash_uids = $fetch_hash_set || "1:*" ;
  8373. %fetch = %{$imap->fetch_hash( $fetch_hash_uids, 'INTERNALDATE' ) } ;
  8374. @msgs_all = sort { $a <=> $b } keys %fetch ;
  8375. $debugdev and myprint( "Done fetch_hash()\n" ) ;
  8376. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  8377. if ( defined $msgs_all_hash_ref ) {
  8378. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  8379. }
  8380. # return all messages
  8381. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  8382. return( @msgs_all ) ;
  8383. }
  8384. if ( defined $search_cmd ) {
  8385. myprint( "Warning: strange to see --search with --noabletosearch, an error can happen\n" ) ;
  8386. @msgs = $imap->search( $search_cmd ) ;
  8387. return( @msgs ) ;
  8388. }
  8389. # we are here only if $maxage or $minage is defined
  8390. my( @max, @min, $maxage_epoch, $minage_epoch ) ;
  8391. if ( defined $maxage ) { $maxage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ; }
  8392. if ( defined $minage ) { $minage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ; }
  8393. foreach my $msg ( @msgs_all ) {
  8394. my $idate = $fetch{ $msg }->{'INTERNALDATE'} ;
  8395. #myprint( "$idate\n" ) ;
  8396. if ( defined $maxage and ( epoch( $idate ) >= $maxage_epoch ) ) {
  8397. push @max, $msg ;
  8398. }
  8399. if ( defined $minage and ( epoch( $idate ) <= $minage_epoch ) ) {
  8400. push @min, $msg ;
  8401. }
  8402. }
  8403. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  8404. return( @msgs ) ;
  8405. }
  8406. sub select_msgs_by_age
  8407. {
  8408. my( $imap ) = @_ ;
  8409. my( @max, @min, @msgs, @inter, @union ) ;
  8410. if ( defined $maxage ) {
  8411. @max = $imap->sentsince( $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ) ;
  8412. }
  8413. if ( defined $minage ) {
  8414. @min = $imap->sentbefore( $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ) ;
  8415. }
  8416. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  8417. return( @msgs ) ;
  8418. }
  8419. sub msgs_from_maxmin
  8420. {
  8421. my( $max_ref, $min_ref ) = @_ ;
  8422. my( @max, @min, @msgs, @inter, @union ) ;
  8423. @max = @{ $max_ref } ;
  8424. @min = @{ $min_ref } ;
  8425. SWITCH: {
  8426. if ( not ( defined $minage or defined $maxage ) )
  8427. {
  8428. return ;
  8429. }
  8430. unless( defined $minage ) { @msgs = @max ; last SWITCH } ;
  8431. unless( defined $maxage ) { @msgs = @min ; last SWITCH } ;
  8432. my ( %union, %inter ) ;
  8433. foreach my $m ( @min, @max ) { $union{ $m }++ && $inter{ $m }++ }
  8434. @inter = sort { $a <=> $b } keys %inter ;
  8435. @union = sort { $a <=> $b } keys %union ;
  8436. # normal case
  8437. if ( $minage <= $maxage ) { @msgs = @inter ; last SWITCH } ;
  8438. # just exclude messages between
  8439. if ( $minage > $maxage ) { @msgs = @union ; last SWITCH } ;
  8440. }
  8441. return( @msgs ) ;
  8442. }
  8443. sub tests_msgs_from_maxmin
  8444. {
  8445. note( 'Entering tests_msgs_from_maxmin()' ) ;
  8446. my @msgs ;
  8447. # no maxage nor minage
  8448. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8449. is_deeply( [ ], \@msgs , 'msgs_from_maxmin: no maxage nor minage => empty result' ) ;
  8450. # maxage alone
  8451. $maxage = $NUMBER_200 ;
  8452. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8453. is_deeply( [ '1', '2' ], \@msgs , 'msgs_from_maxmin: maxage++' ) ;
  8454. # maxage > minage -> intersection
  8455. $minage = $NUMBER_100 ;
  8456. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8457. is_deeply( [ '2' ], \@msgs , 'msgs_from_maxmin: -maxage++minage-' ) ;
  8458. # maxage < minage -> union
  8459. $minage = $NUMBER_300 ;
  8460. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8461. is_deeply( [ '1', '2', '3' ], \@msgs, 'msgs_from_maxmin: ++maxage-minage++' ) ;
  8462. # minage alone
  8463. $maxage = undef ;
  8464. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8465. is_deeply( [ '2', '3' ], \@msgs, 'msgs_from_maxmin: ++minage-' ) ;
  8466. note( 'Leaving tests_msgs_from_maxmin()' ) ;
  8467. return ;
  8468. }
  8469. sub tests_info_date_from_uid
  8470. {
  8471. note( 'Entering tests_info_date_from_uid()' ) ;
  8472. note( 'Leaving tests_info_date_from_uid()' ) ;
  8473. return ;
  8474. }
  8475. sub info_date_from_uid
  8476. {
  8477. #my $first_uid = $msgs_all[ 0 ] ;
  8478. #my $first_idate = $fetch{ $first_uid }->{'INTERNALDATE'} ;
  8479. #my $first_epoch = epoch( $first_idate ) ;
  8480. #my $first_days = ( $timestart_int - $first_epoch ) / $NB_SECONDS_IN_A_DAY ;
  8481. #myprint( "\nOldest msg has UID $first_uid INTERNALDATE $first_idate EPOCH $first_epoch DAYS AGO $first_days\n" ) ;
  8482. }
  8483. sub lastuid
  8484. {
  8485. my $imap = shift ;
  8486. my $folder = shift ;
  8487. my $lastuid_guess = shift ;
  8488. my $lastuid ;
  8489. # rfc3501: The only reliable way to identify recent messages is to
  8490. # look at message flags to see which have the \Recent flag
  8491. # set, or to do a SEARCH RECENT.
  8492. # SEARCH RECENT doesn't work this way on courrier.
  8493. my @recent_messages ;
  8494. # SEARCH RECENT for each transfer can be expensive with a big folder
  8495. # Call commented for now
  8496. #@recent_messages = $imap->recent( ) ;
  8497. #myprint( "Recent: @recent_messages\n" ) ;
  8498. my $max_recent ;
  8499. $max_recent = max( @recent_messages ) ;
  8500. if ( defined $max_recent and ($lastuid_guess <= $max_recent ) ) {
  8501. $lastuid = $max_recent ;
  8502. }else{
  8503. $lastuid = $lastuid_guess
  8504. }
  8505. return( $lastuid ) ;
  8506. }
  8507. sub size_filtered
  8508. {
  8509. my( $h1_size, $h1_msg, $h1_fold, $h2_fold ) = @_ ;
  8510. $h1_size = 0 if ( ! $h1_size ) ; # null if empty or undef
  8511. if ( defined $sync->{ maxsize } and $h1_size > $sync->{ maxsize } ) {
  8512. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size exceeds maxsize limit $sync->{ maxsize } bytes)\n" ) ;
  8513. $sync->{ total_bytes_skipped } += $h1_size;
  8514. $sync->{ nb_msg_skipped } += 1;
  8515. return( 1 ) ;
  8516. }
  8517. if ( defined $minsize and $h1_size <= $minsize ) {
  8518. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size smaller than minsize $minsize bytes)\n" ) ;
  8519. $sync->{ total_bytes_skipped } += $h1_size;
  8520. $sync->{ nb_msg_skipped } += 1;
  8521. return( 1 ) ;
  8522. }
  8523. return( 0 ) ;
  8524. }
  8525. sub message_exists
  8526. {
  8527. my( $imap, $msg ) = @_ ;
  8528. return( 1 ) if not $imap->Uid( ) ;
  8529. my $search_uid ;
  8530. ( $search_uid ) = $imap->search( "UID $msg" ) ;
  8531. #myprint( "$search ? $msg\n" ) ;
  8532. return( 1 ) if ( $search_uid eq $msg ) ;
  8533. return( 0 ) ;
  8534. }
  8535. # Globals
  8536. # $sync->{ total_bytes_skipped }
  8537. # $sync->{ nb_msg_skipped }
  8538. # $mysync->{ h1_nb_msg_processed }
  8539. sub stats_update_skip_message
  8540. {
  8541. my $mysync = shift ; # to be used
  8542. my $h1_size = shift ;
  8543. $mysync->{ total_bytes_skipped } += $h1_size ;
  8544. $mysync->{ nb_msg_skipped } += 1 ;
  8545. $mysync->{ h1_nb_msg_processed } +=1 ;
  8546. return ;
  8547. }
  8548. sub copy_message
  8549. {
  8550. # copy
  8551. my ( $mysync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) = @_ ;
  8552. ( $mysync->{ debug } or $mysync->{dry} )
  8553. and myprint( "msg $h1_fold/$h1_msg copying to $h2_fold $mysync->{dry_message} " . eta( $mysync ) . "\n" ) ;
  8554. if ( $mysync->{dry1} )
  8555. {
  8556. $mysync->{ h1_nb_msg_processed } +=1 ;
  8557. $nb_msg_skipped_dry_mode += 1 ;
  8558. return ;
  8559. }
  8560. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} || 0 ;
  8561. my $h1_flags = $h1_fir_ref->{$h1_msg}->{'FLAGS'} || q{} ;
  8562. my $h1_idate = $h1_fir_ref->{$h1_msg}->{'INTERNALDATE'} || q{} ;
  8563. if ( size_filtered( $h1_size, $h1_msg, $h1_fold, $h2_fold ) ) {
  8564. $mysync->{ h1_nb_msg_processed } +=1 ;
  8565. return ;
  8566. }
  8567. debugsleep( $mysync ) ;
  8568. myprint( "- msg $h1_fold/$h1_msg S[$h1_size] F[$h1_flags] I[$h1_idate] has RFC822.SIZE null!\n" ) if ( ! $h1_size ) ;
  8569. if ( $checkmessageexists and not message_exists( $mysync->{imap1}, $h1_msg ) ) {
  8570. stats_update_skip_message( $mysync, $h1_size ) ;
  8571. return ;
  8572. }
  8573. myprint( debugmemory( $mysync, " at C1" ) ) ;
  8574. my ( $string, $string_len ) ;
  8575. ( $string_len ) = message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, \$string ) ;
  8576. myprint( debugmemory( $mysync, " at C2" ) ) ;
  8577. # not defined or empty $string
  8578. if ( ( not $string ) or ( not $string_len ) ) {
  8579. myprint( "- msg $h1_fold/$h1_msg skipped.\n" ) ;
  8580. stats_update_skip_message( $mysync, $h1_size ) ;
  8581. return ;
  8582. }
  8583. # Lines too long (or not enough) => do no copy or fix
  8584. if ( ( defined $maxlinelength ) or ( defined $minmaxlinelength ) ) {
  8585. $string = linelengthstuff( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) ;
  8586. if ( not defined $string ) {
  8587. stats_update_skip_message( $mysync, $h1_size ) ;
  8588. return ;
  8589. }
  8590. }
  8591. my $h1_date = date_for_host2( $h1_msg, $h1_idate ) ;
  8592. ( $mysync->{ debug } or $debugflags ) and
  8593. myprint( "Host1: flags init msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  8594. $h1_flags = flags_for_host2( $mysync, $h1_flags, $permanentflags2 ) ;
  8595. ( $mysync->{ debug } or $debugflags ) and
  8596. myprint( "Host1: flags filt msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  8597. $h1_date = undef if ( $h1_date eq q{} ) ;
  8598. my $new_id = append_message_on_host2( $mysync, \$string, $h1_fold, $h1_msg, $string_len, $h2_fold, $h1_size, $h1_flags, $h1_date, $cache_dir ) ;
  8599. if ( $new_id and $syncflagsaftercopy ) {
  8600. sync_flags_after_copy( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $new_id, $permanentflags2 ) ;
  8601. }
  8602. myprint( debugmemory( $mysync, " at C3" ) ) ;
  8603. return $new_id ;
  8604. }
  8605. sub linelengthstuff
  8606. {
  8607. my( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) = @_ ;
  8608. my $maxlinelength_string = max_line_length( $string ) ;
  8609. $debugmaxlinelength and myprint( "msg $h1_fold/$h1_msg maxlinelength: $maxlinelength_string\n" ) ;
  8610. if ( ( defined $minmaxlinelength ) and ( $maxlinelength_string <= $minmaxlinelength ) ) {
  8611. my $subject = subject( $string ) ;
  8612. $debugdev and myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  8613. . "(Subject:[$subject]) (max line length under minmaxlinelength $minmaxlinelength bytes)\n" ) ;
  8614. return ;
  8615. }
  8616. if ( ( defined $maxlinelength ) and ( $maxlinelength_string > $maxlinelength ) ) {
  8617. my $subject = subject( $string ) ;
  8618. if ( $maxlinelengthcmd ) {
  8619. $string = pipemess( $string, $maxlinelengthcmd ) ;
  8620. # string undef means something was bad.
  8621. if ( not ( defined $string ) ) {
  8622. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] "
  8623. . "(Subject:[$subject]) could not be successfully transformed by --maxlinelengthcmd option\n" ) ;
  8624. return ;
  8625. }else{
  8626. return $string ;
  8627. }
  8628. }
  8629. myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  8630. . "(Subject:[$subject]) (line length exceeds maxlinelength $maxlinelength bytes)\n" ) ;
  8631. return ;
  8632. }
  8633. return $string ;
  8634. }
  8635. sub message_for_host2
  8636. {
  8637. # global variable list:
  8638. # @skipmess
  8639. # @regexmess
  8640. # @pipemess
  8641. # $debugcontent
  8642. # $debug
  8643. #
  8644. # API current
  8645. #
  8646. # at failure:
  8647. # * return nothing ( will then be undef or () )
  8648. # * $string_ref content is undef or empty
  8649. # at success:
  8650. # * return string length ($string_ref content length)
  8651. # * $string_ref content filled with message
  8652. # API future
  8653. #
  8654. #
  8655. my ( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) = @_ ;
  8656. # abort when missing a parameter
  8657. if ( ( ! $mysync ) or ( ! $h1_msg ) or ( ! $h1_fold ) or ( ! defined $h1_size )
  8658. or ( ! defined $h1_flags) or ( ! defined $h1_idate )
  8659. or ( ! $h1_fir_ref) or ( ! $string_ref ) )
  8660. {
  8661. return ;
  8662. }
  8663. myprint( debugmemory( $mysync, " at M1" ) ) ;
  8664. my $string_ok = $mysync->{imap1}->message_to_file( $string_ref, $h1_msg ) ;
  8665. myprint( debugmemory( $mysync, " at M2" ) ) ;
  8666. my $string_len = length_ref( $string_ref ) ;
  8667. unless ( defined $string_ok and $string_len ) {
  8668. # undef or 0 length
  8669. my $error = join q{},
  8670. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] could not be fetched: ",
  8671. $mysync->{imap1}->LastError || q{}, "\n" ;
  8672. errors_incr( $mysync, $error ) ;
  8673. $mysync->{ h1_nb_msg_processed } +=1 ;
  8674. return ;
  8675. }
  8676. if ( @skipmess ) {
  8677. my $match = skipmess( ${ $string_ref } ) ;
  8678. # string undef means the eval regex was bad.
  8679. if ( not ( defined $match ) ) {
  8680. myprint(
  8681. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  8682. . " could not be skipped by --skipmess option, bad regex\n" ) ;
  8683. return ;
  8684. }
  8685. if ( $match ) {
  8686. my $subject = subject( ${ $string_ref } ) ;
  8687. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  8688. . " (Subject:[$subject]) skipped by --skipmess\n" ) ;
  8689. return ;
  8690. }
  8691. }
  8692. if ( @regexmess ) {
  8693. ${ $string_ref } = regexmess( ${ $string_ref } ) ;
  8694. # string undef means the eval regex was bad.
  8695. if ( not ( defined ${ $string_ref } ) ) {
  8696. myprint(
  8697. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  8698. . " could not be transformed by --regexmess\n" ) ;
  8699. return ;
  8700. }
  8701. }
  8702. if ( @pipemess ) {
  8703. ${ $string_ref } = pipemess( ${ $string_ref }, @pipemess ) ;
  8704. # string undef means something was bad.
  8705. if ( not ( defined ${ $string_ref } ) ) {
  8706. myprint(
  8707. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  8708. . " could not be successfully transformed by --pipemess option\n" ) ;
  8709. return ;
  8710. }
  8711. }
  8712. if ( $mysync->{addheader} and defined $h1_fir_ref->{$h1_msg}->{'NO_HEADER'} ) {
  8713. my $header = add_header( $h1_msg ) ;
  8714. $mysync->{ debug } and myprint( "msg $h1_fold/$h1_msg adding custom header [$header]\n" ) ;
  8715. ${ $string_ref } = $header . "\r\n" . ${ $string_ref } ;
  8716. }
  8717. if ( ( defined $mysync->{ truncmess } ) and is_integer( $mysync->{ truncmess } ) )
  8718. {
  8719. ${ $string_ref } = truncmess( ${ $string_ref }, $mysync->{ truncmess } ) ;
  8720. }
  8721. $string_len = length_ref( $string_ref ) ;
  8722. $debugcontent and myprint(
  8723. q{=} x $STD_CHAR_PER_LINE, "\n",
  8724. "F message content begin next line ($string_len characters long)\n",
  8725. ${ $string_ref },
  8726. "\nF message content ended on previous line\n", q{=} x $STD_CHAR_PER_LINE, "\n" ) ;
  8727. myprint( debugmemory( $mysync, " at M3" ) ) ;
  8728. return $string_len ;
  8729. }
  8730. sub tests_truncmess
  8731. {
  8732. note( 'Entering tests_truncmess()' ) ;
  8733. is( undef, truncmess( ), 'truncmess: no args => undef' ) ;
  8734. is( 'abc', truncmess( 'abc' ), 'truncmess: abc => abc' ) ;
  8735. is( 'ab', truncmess( 'abc', 2 ), 'truncmess: abc 2 => ab' ) ;
  8736. is( 'abc', truncmess( 'abc', 3 ), 'truncmess: abc 3 => abc' ) ;
  8737. is( 'abc', truncmess( 'abc', 4 ), 'truncmess: abc 4 => abc' ) ;
  8738. is( '12345', truncmess( "123456789\n", 5 ), 'truncmess: "123456789\n", 5 => 12345' ) ;
  8739. is( "123456789\n" x 5000, truncmess( "123456789\n" x 100000, 50000 ), 'truncmess: "123456789\n" x 100000, 50000 => "123456789\n" x 5000' ) ;
  8740. note( 'Leaving tests_truncmess()' ) ;
  8741. return ;
  8742. }
  8743. sub truncmess
  8744. {
  8745. my $string = shift ;
  8746. my $length = shift ;
  8747. if ( not defined $string ) { return ; }
  8748. if ( not defined $length ) { return $string ; }
  8749. $string = substr $string, 0, $length ;
  8750. return $string ;
  8751. }
  8752. sub tests_message_for_host2
  8753. {
  8754. note( 'Entering tests_message_for_host2()' ) ;
  8755. my ( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) ;
  8756. is( undef, message_for_host2( ), q{message_for_host2: no args} ) ;
  8757. 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} ) ;
  8758. require_ok( "Test::MockObject" ) ;
  8759. my $imapT = Test::MockObject->new( ) ;
  8760. $mysync->{imap1} = $imapT ;
  8761. my $string ;
  8762. $h1_msg = 1 ;
  8763. $h1_fold = 'FoldFoo';
  8764. $h1_size = 9 ;
  8765. $h1_flags = q{} ;
  8766. $h1_idate = '10-Jul-2015 09:00:00 +0200' ;
  8767. $h1_fir_ref = {} ;
  8768. $string_ref = \$string ;
  8769. $imapT->mock( 'message_to_file',
  8770. sub {
  8771. my ( $imap, $mystring_ref, $msg ) = @_ ;
  8772. ${$mystring_ref} = 'blablabla' ;
  8773. return length ${$mystring_ref} ;
  8774. }
  8775. ) ;
  8776. is( 9, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  8777. q{message_for_host2: msg 1 == "blablabla", length} ) ;
  8778. is( 'blablabla', $string, q{message_for_host2: msg 1 == "blablabla", value} ) ;
  8779. # so far so good
  8780. # now the --pipemess stuff
  8781. SKIP: {
  8782. Readonly my $NB_WIN_tests_message_for_host2 => 0 ;
  8783. skip( 'Not on MSWin32', $NB_WIN_tests_message_for_host2 ) if ('MSWin32' ne $OSNAME) ;
  8784. # Windows
  8785. # "type" command does not accept redirection of STDIN with <
  8786. # "sort" does
  8787. } ;
  8788. SKIP: {
  8789. Readonly my $NB_UNX_tests_message_for_host2 => 6 ;
  8790. skip( 'Not on Unix', $NB_UNX_tests_message_for_host2 ) if ('MSWin32' eq $OSNAME) ;
  8791. # Unix
  8792. # no change by cat
  8793. @pipemess = ( 'cat' ) ;
  8794. is( 9, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  8795. q{message_for_host2: --pipemess 'cat', length} ) ;
  8796. is( 'blablabla', $string, q{message_for_host2: --pipemess 'cat', value} ) ;
  8797. # failure by false
  8798. @pipemess = ( 'false' ) ;
  8799. is( undef, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  8800. q{message_for_host2: --pipemess 'false', length} ) ;
  8801. is( undef, $string, q{message_for_host2: --pipemess 'false', value} ) ;
  8802. # failure by true since no output
  8803. @pipemess = ( 'true' ) ;
  8804. is( undef, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  8805. q{message_for_host2: --pipemess 'true', length} ) ;
  8806. is( undef, $string, q{message_for_host2: --pipemess 'true', value} ) ;
  8807. }
  8808. note( 'Leaving tests_message_for_host2()' ) ;
  8809. return ;
  8810. }
  8811. sub tests_labels_remove_subfolder1
  8812. {
  8813. note( 'Entering tests_labels_remove_subfolder1()' ) ;
  8814. is( undef, labels_remove_subfolder1( ), 'labels_remove_subfolder1: no parameters => undef' ) ;
  8815. is( 'Blabla', labels_remove_subfolder1( 'Blabla' ), 'labels_remove_subfolder1: one parameter Blabla => Blabla' ) ;
  8816. is( 'Blan blue', labels_remove_subfolder1( 'Blan blue' ), 'labels_remove_subfolder1: one parameter Blan blue => Blan blue' ) ;
  8817. is( '\Bla "Blan blan" Blabla', labels_remove_subfolder1( '\Bla "Blan blan" Blabla' ),
  8818. 'labels_remove_subfolder1: one parameter \Bla "Blan blan" Blabla => \Bla "Blan blan" Blabla' ) ;
  8819. is( 'Bla', labels_remove_subfolder1( 'Subf/Bla', 'Subf' ), 'labels_remove_subfolder1: Subf/Bla Subf => "Bla"' ) ;
  8820. is( '"\\\\Bla"', labels_remove_subfolder1( '"\\\\Bla"', 'Subf' ), 'labels_remove_subfolder1: "\\\\Bla" Subf => "\\\\Bla"' ) ;
  8821. is( 'Bla Kii', labels_remove_subfolder1( 'Subf/Bla Subf/Kii', 'Subf' ),
  8822. 'labels_remove_subfolder1: Subf/Bla Subf/Kii, Subf => "Bla" "Kii"' ) ;
  8823. is( '"\\\\Bla" Kii', labels_remove_subfolder1( '"\\\\Bla" Subf/Kii', 'Subf' ),
  8824. 'labels_remove_subfolder1: "\\\\Bla" Subf/Kii Subf => "\\\\Bla" Kii' ) ;
  8825. is( '"Blan blan"', labels_remove_subfolder1( '"Subf/Blan blan"', 'Subf' ),
  8826. 'labels_remove_subfolder1: "Subf/Blan blan" Subf => "Blan blan"' ) ;
  8827. is( '"\\\\Loo" "Blan blan" Kii', labels_remove_subfolder1( '"\\\\Loo" "Subf/Blan blan" Subf/Kii', 'Subf' ),
  8828. 'labels_remove_subfolder1: "\\\\Loo" "Subf/Blan blan" Subf/Kii + Subf => "\\\\Loo" "Blan blan" Kii' ) ;
  8829. is( '"\\\\Inbox"', labels_remove_subfolder1( 'Subf/INBOX', 'Subf' ),
  8830. 'labels_remove_subfolder1: Subf/INBOX + Subf => "\\\\Inbox"' ) ;
  8831. is( '"\\\\Loo" "Blan blan" Kii "\\\\Inbox"', labels_remove_subfolder1( '"\\\\Loo" "Subf/Blan blan" Subf/Kii Subf/INBOX', 'Subf' ),
  8832. 'labels_remove_subfolder1: "\\\\Loo" "Subf/Blan blan" Subf/Kii Subf/INBOX + Subf => "\\\\Loo" "Blan blan" Kii "\\\\Inbox"' ) ;
  8833. note( 'Leaving tests_labels_remove_subfolder1()' ) ;
  8834. return ;
  8835. }
  8836. sub labels_remove_subfolder1
  8837. {
  8838. my $labels = shift ;
  8839. my $subfolder1 = shift ;
  8840. if ( not defined $labels ) { return ; }
  8841. if ( not defined $subfolder1 ) { return $labels ; }
  8842. my @labels = quotewords('\s+', 1, $labels ) ;
  8843. #myprint( "@labels\n" ) ;
  8844. my @labels_subfolder2 ;
  8845. foreach my $label ( @labels )
  8846. {
  8847. if ( $label =~ m{zzzzzzzzzz} )
  8848. {
  8849. # \Seen \Deleted ... stay the same
  8850. push @labels_subfolder2, $label ;
  8851. }
  8852. else
  8853. {
  8854. # Remove surrounding quotes if any, to add them again in case of space
  8855. $label = join( q{}, quotewords('\s+', 0, $label ) ) ;
  8856. $label =~ s{$subfolder1/?}{} ;
  8857. if ( 'INBOX' eq $label )
  8858. {
  8859. push @labels_subfolder2, q{"\\\\Inbox"} ;
  8860. }
  8861. elsif ( $label =~ m{\\} )
  8862. {
  8863. push @labels_subfolder2, qq{"\\$label"} ;
  8864. }
  8865. elsif ( $label =~ m{ } )
  8866. {
  8867. push @labels_subfolder2, qq{"$label"} ;
  8868. }
  8869. else
  8870. {
  8871. push @labels_subfolder2, $label ;
  8872. }
  8873. }
  8874. }
  8875. my $labels_subfolder2 = join( ' ', sort uniq( @labels_subfolder2 ) ) ;
  8876. return $labels_subfolder2 ;
  8877. }
  8878. sub tests_labels_remove_special
  8879. {
  8880. note( 'Entering tests_labels_remove_special()' ) ;
  8881. is( undef, labels_remove_special( ), 'labels_remove_special: no parameters => undef' ) ;
  8882. is( q{}, labels_remove_special( q{} ), 'labels_remove_special: empty string => empty string' ) ;
  8883. is( q{}, labels_remove_special( '"\\\\Inbox"' ), 'labels_remove_special:"\\\\Inbox" => empty string' ) ;
  8884. is( q{}, labels_remove_special( '"\\\\Inbox" "\\\\Starred"' ), 'labels_remove_special:"\\\\Inbox" "\\\\Starred" => empty string' ) ;
  8885. is( 'Bar Foo', labels_remove_special( 'Foo Bar' ), 'labels_remove_special:Foo Bar => Bar Foo' ) ;
  8886. is( 'Bar Foo', labels_remove_special( 'Foo Bar "\\\\Inbox"' ), 'labels_remove_special:Foo Bar "\\\\Inbox" => Bar Foo' ) ;
  8887. note( 'Leaving tests_labels_remove_special()' ) ;
  8888. return ;
  8889. }
  8890. sub labels_remove_special
  8891. {
  8892. my $labels = shift ;
  8893. if ( not defined $labels ) { return ; }
  8894. my @labels = quotewords('\s+', 1, $labels ) ;
  8895. myprint( "labels before remove_non_folded: @labels\n" ) ;
  8896. my @labels_remove_special ;
  8897. foreach my $label ( @labels )
  8898. {
  8899. if ( $label =~ m{^\"\\\\} )
  8900. {
  8901. # not kept
  8902. }
  8903. else
  8904. {
  8905. push @labels_remove_special, $label ;
  8906. }
  8907. }
  8908. my $labels_remove_special = join( ' ', sort @labels_remove_special ) ;
  8909. return $labels_remove_special ;
  8910. }
  8911. sub tests_labels_add_subfolder2
  8912. {
  8913. note( 'Entering tests_labels_add_subfolder2()' ) ;
  8914. is( undef, labels_add_subfolder2( ), 'labels_add_subfolder2: no parameters => undef' ) ;
  8915. is( 'Blabla', labels_add_subfolder2( 'Blabla' ), 'labels_add_subfolder2: one parameter Blabla => Blabla' ) ;
  8916. is( 'Blan blue', labels_add_subfolder2( 'Blan blue' ), 'labels_add_subfolder2: one parameter Blan blue => Blan blue' ) ;
  8917. is( '\Bla "Blan blan" Blabla', labels_add_subfolder2( '\Bla "Blan blan" Blabla' ),
  8918. 'labels_add_subfolder2: one parameter \Bla "Blan blan" Blabla => \Bla "Blan blan" Blabla' ) ;
  8919. is( 'Subf/Bla', labels_add_subfolder2( 'Bla', 'Subf' ), 'labels_add_subfolder2: Bla Subf => "Subf/Bla"' ) ;
  8920. is( 'Subf/\Bla', labels_add_subfolder2( '\\\\Bla', 'Subf' ), 'labels_add_subfolder2: \Bla Subf => \Bla' ) ;
  8921. is( 'Subf/Bla Subf/Kii', labels_add_subfolder2( 'Bla Kii', 'Subf' ),
  8922. 'labels_add_subfolder2: Bla Kii Subf => "Subf/Bla" "Subf/Kii"' ) ;
  8923. is( 'Subf/Kii Subf/\Bla', labels_add_subfolder2( '\\\\Bla Kii', 'Subf' ),
  8924. 'labels_add_subfolder2: \Bla Kii Subf => \Bla Subf/Kii' ) ;
  8925. is( '"Subf/Blan blan"', labels_add_subfolder2( '"Blan blan"', 'Subf' ),
  8926. 'labels_add_subfolder2: "Blan blan" Subf => "Subf/Blan blan"' ) ;
  8927. is( '"Subf/Blan blan" Subf/Kii Subf/\Loo', labels_add_subfolder2( '\\\\Loo "Blan blan" Kii', 'Subf' ),
  8928. 'labels_add_subfolder2: \Loo "Blan blan" Kii + Subf => "Subf/Blan blan" Subf/Kii Subf/\Loo' ) ;
  8929. # "\\Inbox" is special, add to subfolder INBOX also because Gmail will but ...
  8930. is( '"Subf/\\\\Inbox" Subf/INBOX', labels_add_subfolder2( '"\\\\Inbox"', 'Subf' ),
  8931. 'labels_add_subfolder2: "\\\\Inbox" Subf => "Subf/\\\\Inbox" Subf/INBOX' ) ;
  8932. # but not with INBOX folder
  8933. is( '"Subf/\\\\Inbox"', labels_add_subfolder2( '"\\\\Inbox"', 'Subf', 'INBOX' ),
  8934. 'labels_add_subfolder2: "\\\\Inbox" Subf INBOX => "Subf/\\\\Inbox"' ) ;
  8935. # two times => one time
  8936. is( '"Subf/\\\\Inbox" Subf/INBOX', labels_add_subfolder2( '"\\\\Inbox" "\\\\Inbox"', 'Subf' ),
  8937. 'labels_add_subfolder2: "\\\\Inbox" "\\\\Inbox" Subf => "Subf/\\\\Inbox"' ) ;
  8938. is( '"Subf/\\\\Starred"', labels_add_subfolder2( '"\\\\Starred"', 'Subf' ),
  8939. 'labels_add_subfolder2: "\\\\Starred" Subf => "Subf/\\\\Starred"' ) ;
  8940. note( 'Leaving tests_labels_add_subfolder2()' ) ;
  8941. return ;
  8942. }
  8943. sub labels_add_subfolder2
  8944. {
  8945. my $labels = shift ;
  8946. my $subfolder2 = shift ;
  8947. my $h1_folder = shift || q{} ;
  8948. if ( not defined $labels ) { return ; }
  8949. if ( not defined $subfolder2 ) { return $labels ; }
  8950. # Isn't it messy?
  8951. if ( 'INBOX' eq $h1_folder )
  8952. {
  8953. $labels .= ' "\\\\Inbox"' ;
  8954. }
  8955. my @labels = uniq( quotewords('\s+', 1, $labels ) ) ;
  8956. myprint( "labels before subfolder2: @labels\n" ) ;
  8957. my @labels_subfolder2 ;
  8958. foreach my $label ( @labels )
  8959. {
  8960. # Isn't it more messy?
  8961. if ( ( q{"\\\\Inbox"} eq $label ) and ( 'INBOX' ne $h1_folder ) )
  8962. {
  8963. if ( $subfolder2 =~ m{ } )
  8964. {
  8965. push @labels_subfolder2, qq{"$subfolder2/INBOX"} ;
  8966. }
  8967. else
  8968. {
  8969. push @labels_subfolder2, "$subfolder2/INBOX" ;
  8970. }
  8971. }
  8972. if ( $label =~ m{^\"\\\\} )
  8973. {
  8974. # \Seen \Deleted ... stay the same
  8975. #push @labels_subfolder2, $label ;
  8976. # Remove surrounding quotes if any, to add them again
  8977. $label = join( q{}, quotewords('\s+', 0, $label ) ) ;
  8978. push @labels_subfolder2, qq{"$subfolder2/\\$label"} ;
  8979. }
  8980. else
  8981. {
  8982. # Remove surrounding quotes if any, to add them again in case of space
  8983. $label = join( q{}, quotewords('\s+', 0, $label ) ) ;
  8984. if ( $label =~ m{ } )
  8985. {
  8986. push @labels_subfolder2, qq{"$subfolder2/$label"} ;
  8987. }
  8988. else
  8989. {
  8990. push @labels_subfolder2, "$subfolder2/$label" ;
  8991. }
  8992. }
  8993. }
  8994. my $labels_subfolder2 = join( ' ', sort @labels_subfolder2 ) ;
  8995. return $labels_subfolder2 ;
  8996. }
  8997. sub tests_labels
  8998. {
  8999. note( 'Entering tests_labels()' ) ;
  9000. is( undef, labels( ), 'labels: no parameters => undef' ) ;
  9001. is( undef, labels( undef ), 'labels: undef => undef' ) ;
  9002. require_ok( "Test::MockObject" ) ;
  9003. my $myimap = Test::MockObject->new( ) ;
  9004. $myimap->mock( 'fetch_hash',
  9005. sub {
  9006. return(
  9007. { '1' => {
  9008. 'X-GM-LABELS' => '\Seen Blabla'
  9009. }
  9010. }
  9011. ) ;
  9012. }
  9013. ) ;
  9014. $myimap->mock( 'Debug' , sub { } ) ;
  9015. $myimap->mock( 'Unescape', sub { return Mail::IMAPClient::Unescape( @_ ) } ) ; # real one
  9016. is( undef, labels( $myimap ), 'labels: one parameter => undef' ) ;
  9017. is( '\Seen Blabla', labels( $myimap, '1' ), 'labels: $mysync UID_1 => \Seen Blabla' ) ;
  9018. note( 'Leaving tests_labels()' ) ;
  9019. return ;
  9020. }
  9021. sub labels
  9022. {
  9023. my ( $myimap, $uid ) = @ARG ;
  9024. if ( not all_defined( $myimap, $uid ) ) {
  9025. return ;
  9026. }
  9027. my $hash = $myimap->fetch_hash( [ $uid ], 'X-GM-LABELS' ) ;
  9028. my $labels = $hash->{ $uid }->{ 'X-GM-LABELS' } ;
  9029. #$labels = $myimap->Unescape( $labels ) ;
  9030. return $labels ;
  9031. }
  9032. sub tests_synclabels
  9033. {
  9034. note( 'Entering tests_synclabels()' ) ;
  9035. is( undef, synclabels( ), 'synclabels: no parameters => undef' ) ;
  9036. is( undef, synclabels( undef ), 'synclabels: undef => undef' ) ;
  9037. my $mysync ;
  9038. is( undef, synclabels( $mysync ), 'synclabels: var undef => undef' ) ;
  9039. require_ok( "Test::MockObject" ) ;
  9040. $mysync = {} ;
  9041. my $myimap1 = Test::MockObject->new( ) ;
  9042. $myimap1->mock( 'fetch_hash',
  9043. sub {
  9044. return(
  9045. { '1' => {
  9046. 'X-GM-LABELS' => '\Seen Blabla'
  9047. }
  9048. }
  9049. ) ;
  9050. }
  9051. ) ;
  9052. $myimap1->mock( 'Debug', sub { } ) ;
  9053. $myimap1->mock( 'Unescape', sub { return Mail::IMAPClient::Unescape( @_ ) } ) ; # real one
  9054. my $myimap2 = Test::MockObject->new( ) ;
  9055. $myimap2->mock( 'store',
  9056. sub {
  9057. return 1 ;
  9058. }
  9059. ) ;
  9060. $mysync->{imap1} = $myimap1 ;
  9061. $mysync->{imap2} = $myimap2 ;
  9062. is( undef, synclabels( $mysync ), 'synclabels: fresh $mysync => undef' ) ;
  9063. is( undef, synclabels( $mysync, '1' ), 'synclabels: $mysync UID_1 alone => undef' ) ;
  9064. is( 1, synclabels( $mysync, '1', '2' ), 'synclabels: $mysync UID_1 UID_2 => 1' ) ;
  9065. note( 'Leaving tests_synclabels()' ) ;
  9066. return ;
  9067. }
  9068. sub synclabels
  9069. {
  9070. my( $mysync, $uid1, $uid2 ) = @ARG ;
  9071. if ( not all_defined( $mysync, $uid1, $uid2 ) ) {
  9072. return ;
  9073. }
  9074. my $myimap1 = $mysync->{ 'imap1' } || return ;
  9075. my $myimap2 = $mysync->{ 'imap2' } || return ;
  9076. $mysync->{debuglabels} and $myimap1->Debug( 1 ) ;
  9077. my $labels1 = labels( $myimap1, $uid1 ) ;
  9078. $mysync->{debuglabels} and $myimap1->Debug( 0 ) ;
  9079. $mysync->{debuglabels} and myprint( "Host1 labels: $labels1\n" ) ;
  9080. if ( $mysync->{ subfolder1 } and $labels1 )
  9081. {
  9082. $labels1 = labels_remove_subfolder1( $labels1, $mysync->{ subfolder1 } ) ;
  9083. $mysync->{debuglabels} and myprint( "Host1 labels with subfolder1: $labels1\n" ) ;
  9084. }
  9085. if ( $mysync->{ subfolder2 } and $labels1 )
  9086. {
  9087. $labels1 = labels_add_subfolder2( $labels1, $mysync->{ subfolder2 } ) ;
  9088. $mysync->{debuglabels} and myprint( "Host1 labels with subfolder2: $labels1\n" ) ;
  9089. }
  9090. my $store ;
  9091. if ( $labels1 and not $mysync->{ dry } )
  9092. {
  9093. $mysync->{ debuglabels } and $myimap2->Debug( 1 ) ;
  9094. $store = $myimap2->store( $uid2, "X-GM-LABELS ($labels1)" ) ;
  9095. $mysync->{ debuglabels } and $myimap2->Debug( 0 ) ;
  9096. }
  9097. return $store ;
  9098. }
  9099. sub tests_resynclabels
  9100. {
  9101. note( 'Entering tests_resynclabels()' ) ;
  9102. is( undef, resynclabels( ), 'resynclabels: no parameters => undef' ) ;
  9103. is( undef, resynclabels( undef ), 'resynclabels: undef => undef' ) ;
  9104. my $mysync ;
  9105. is( undef, resynclabels( $mysync ), 'resynclabels: var undef => undef' ) ;
  9106. my ( $h1_fir_ref, $h2_fir_ref ) ;
  9107. $mysync->{ debuglabels } = 1 ;
  9108. $h1_fir_ref->{ 11 }->{ 'X-GM-LABELS' } = '\Seen Baa Kii' ;
  9109. $h2_fir_ref->{ 22 }->{ 'X-GM-LABELS' } = '\Seen Baa Kii' ;
  9110. # labels are equal
  9111. is( 1, resynclabels( $mysync, 11, 22, $h1_fir_ref, $h2_fir_ref ),
  9112. 'resynclabels: $mysync UID_1 UID_2 labels are equal => 1' ) ;
  9113. # labels are different
  9114. $h2_fir_ref->{ 22 }->{ 'X-GM-LABELS' } = '\Seen Zuu' ;
  9115. require_ok( "Test::MockObject" ) ;
  9116. my $myimap2 = Test::MockObject->new( ) ;
  9117. $myimap2->mock( 'store',
  9118. sub {
  9119. return 1 ;
  9120. }
  9121. ) ;
  9122. $myimap2->mock( 'Debug', sub { } ) ;
  9123. $mysync->{imap2} = $myimap2 ;
  9124. is( 1, resynclabels( $mysync, 11, 22, $h1_fir_ref, $h2_fir_ref ),
  9125. 'resynclabels: $mysync UID_1 UID_2 labels are not equal => store => 1' ) ;
  9126. note( 'Leaving tests_resynclabels()' ) ;
  9127. return ;
  9128. }
  9129. sub resynclabels
  9130. {
  9131. my( $mysync, $uid1, $uid2, $h1_fir_ref, $h2_fir_ref, $h1_folder ) = @ARG ;
  9132. if ( not all_defined( $mysync, $uid1, $uid2, $h1_fir_ref, $h2_fir_ref ) ) {
  9133. return ;
  9134. }
  9135. my $labels1 = $h1_fir_ref->{ $uid1 }->{ 'X-GM-LABELS' } || q{} ;
  9136. my $labels2 = $h2_fir_ref->{ $uid2 }->{ 'X-GM-LABELS' } || q{} ;
  9137. if ( $mysync->{ subfolder1 } and $labels1 )
  9138. {
  9139. $labels1 = labels_remove_subfolder1( $labels1, $mysync->{ subfolder1 } ) ;
  9140. }
  9141. if ( $mysync->{ subfolder2 } and $labels1 )
  9142. {
  9143. $labels1 = labels_add_subfolder2( $labels1, $mysync->{ subfolder2 }, $h1_folder ) ;
  9144. $labels2 = labels_remove_special( $labels2 ) ;
  9145. }
  9146. $mysync->{ debuglabels } and myprint( "Host1 labels fixed: $labels1\n" ) ;
  9147. $mysync->{ debuglabels } and myprint( "Host2 labels : $labels2\n" ) ;
  9148. my $store ;
  9149. if ( $labels1 eq $labels2 )
  9150. {
  9151. # no sync needed
  9152. $mysync->{ debuglabels } and myprint( "Labels are already equal\n" ) ;
  9153. return 1 ;
  9154. }
  9155. elsif ( not $mysync->{ dry } )
  9156. {
  9157. # sync needed
  9158. $mysync->{debuglabels} and $mysync->{imap2}->Debug( 1 ) ;
  9159. $store = $mysync->{imap2}->store( $uid2, "X-GM-LABELS ($labels1)" ) ;
  9160. $mysync->{debuglabels} and $mysync->{imap2}->Debug( 0 ) ;
  9161. }
  9162. return $store ;
  9163. }
  9164. sub tests_uniq
  9165. {
  9166. note( 'Entering tests_uniq()' ) ;
  9167. is( 0, uniq( ), 'uniq: undef => 0' ) ;
  9168. is_deeply( [ 'one' ], [ uniq( 'one' ) ], 'uniq: one => one' ) ;
  9169. is_deeply( [ 'one' ], [ uniq( 'one', 'one' ) ], 'uniq: one one => one' ) ;
  9170. is_deeply( [ 'one', 'two' ], [ uniq( 'one', 'one', 'two', 'one', 'two' ) ], 'uniq: one one two one two => one two' ) ;
  9171. note( 'Leaving tests_uniq()' ) ;
  9172. return ;
  9173. }
  9174. sub uniq
  9175. {
  9176. my @list = @ARG ;
  9177. my %seen = ( ) ;
  9178. my @uniq = ( ) ;
  9179. foreach my $item ( @list ) {
  9180. if ( ! $seen{ $item } ) {
  9181. $seen{ $item } = 1 ;
  9182. push( @uniq, $item ) ;
  9183. }
  9184. }
  9185. return @uniq ;
  9186. }
  9187. sub length_ref
  9188. {
  9189. my $string_ref = shift ;
  9190. my $string_len = defined ${ $string_ref } ? length( ${ $string_ref } ) : q{} ; # length or empty string
  9191. return $string_len ;
  9192. }
  9193. sub tests_length_ref
  9194. {
  9195. note( 'Entering tests_length_ref()' ) ;
  9196. my $notdefined ;
  9197. is( q{}, length_ref( \$notdefined ), q{length_ref: value not defined} ) ;
  9198. my $notref ;
  9199. is( q{}, length_ref( $notref ), q{length_ref: param not a ref} ) ;
  9200. my $lala = 'lala' ;
  9201. is( 4, length_ref( \$lala ), q{length_ref: lala length == 4} ) ;
  9202. is( 4, length_ref( \'lili' ), q{length_ref: lili length == 4} ) ;
  9203. note( 'Leaving tests_length_ref()' ) ;
  9204. return ;
  9205. }
  9206. sub date_for_host2
  9207. {
  9208. my( $h1_msg, $h1_idate ) = @_ ;
  9209. my $h1_date = q{} ;
  9210. if ( $syncinternaldates ) {
  9211. $h1_date = $h1_idate ;
  9212. $sync->{ debug } and myprint( "internal date from host1: [$h1_date]\n" ) ;
  9213. $h1_date = good_date( $h1_date ) ;
  9214. $sync->{ debug } and myprint( "internal date from host1: [$h1_date] (fixed)\n" ) ;
  9215. }
  9216. if ( $idatefromheader ) {
  9217. $h1_date = $sync->{imap1}->get_header( $h1_msg, 'Date' ) ;
  9218. $sync->{ debug } and myprint( "header date from host1: [$h1_date]\n" ) ;
  9219. $h1_date = good_date( $h1_date ) ;
  9220. $sync->{ debug } and myprint( "header date from host1: [$h1_date] (fixed)\n" ) ;
  9221. }
  9222. return( $h1_date ) ;
  9223. }
  9224. sub subject
  9225. {
  9226. my $string = shift ;
  9227. my $subject = q{} ;
  9228. my $header = extract_header( $string ) ;
  9229. if( $header =~ m/^Subject:[ \t]*([^\n\r]*)\r?$/msx ) {
  9230. #myprint( "MMM[$1]\n" ) ;
  9231. $subject = $1 ;
  9232. }
  9233. return( $subject ) ;
  9234. }
  9235. sub tests_subject
  9236. {
  9237. note( 'Entering tests_subject()' ) ;
  9238. ok( q{} eq subject( q{} ), 'subject: null') ;
  9239. is( '', subject( 'Subject:' ), 'Subject:') ;
  9240. is( '', subject( "Subject:\r\n" ), 'Subject:\r\n') ;
  9241. ok( 'toto le hero' eq subject( 'Subject: toto le hero' ), 'Subject: toto le hero') ;
  9242. ok( 'toto le hero' eq subject( 'Subject:toto le hero' ), 'Subject:toto le hero') ;
  9243. ok( 'toto le hero' eq subject( "Subject:toto le hero\r\n" ), 'Subject: toto le hero\r\n') ;
  9244. my $MESS ;
  9245. $MESS = <<'EOF';
  9246. From: lalala
  9247. Subject: toto le hero
  9248. Date: zzzzzz
  9249. Boogie boogie
  9250. EOF
  9251. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 2') ;
  9252. $MESS = <<'EOF';
  9253. Subject: toto le hero
  9254. From: lalala
  9255. Date: zzzzzz
  9256. Boogie boogie
  9257. EOF
  9258. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 3') ;
  9259. $MESS = <<'EOF';
  9260. From: lalala
  9261. Subject: cuicui
  9262. Date: zzzzzz
  9263. Subject: toto le hero
  9264. EOF
  9265. ok( 'cuicui' eq subject( $MESS ), 'subject: cuicui') ;
  9266. $MESS = <<'EOF';
  9267. From: lalala
  9268. Date: zzzzzz
  9269. Subject: toto le hero
  9270. EOF
  9271. ok( q{} eq subject( $MESS ), 'subject: null but body could') ;
  9272. $MESS = <<'EOF';
  9273. From: lalala
  9274. Subject:
  9275. Date: zzzzzz
  9276. Subject: toto le hero
  9277. EOF
  9278. is( '', subject( $MESS ), 'Subject:') ;
  9279. note( 'Leaving tests_subject()' ) ;
  9280. return ;
  9281. }
  9282. # GlobVar
  9283. # $h2_uidguess
  9284. # ...
  9285. #
  9286. #
  9287. sub append_message_on_host2
  9288. {
  9289. my( $mysync, $string_ref, $h1_fold, $h1_msg, $string_len, $h2_fold, $h1_size, $h1_flags, $h1_date, $cache_dir ) = @_ ;
  9290. myprint( debugmemory( $mysync, " at A1" ) ) ;
  9291. my $new_id ;
  9292. if ( ! $mysync->{dry} ) {
  9293. $new_id = $mysync->{imap2}->append_string( $h2_fold, ${ $string_ref }, $h1_flags, $h1_date ) ;
  9294. myprint( debugmemory( $mysync, " at A2" ) ) ;
  9295. if ( ! defined $new_id ){
  9296. my $subject = subject( ${ $string_ref } ) ;
  9297. my $error_imap = $mysync->{imap2}->LastError || q{} ;
  9298. my $error = "- msg $h1_fold/$h1_msg {$string_len} could not append ( Subject:[$subject], Date:[$h1_date], Size:[$h1_size], Flags:[$h1_flags] ) to folder $h2_fold: $error_imap\n" ;
  9299. errors_incr( $mysync, $error ) ;
  9300. $mysync->{ h1_nb_msg_processed } +=1 ;
  9301. return ;
  9302. }
  9303. else{
  9304. # good
  9305. # $new_id is an id if the IMAP server has the
  9306. # UIDPLUS capability else just a ref
  9307. if ( $new_id !~ m{^\d+$}x ) {
  9308. $new_id = lastuid( $mysync->{imap2}, $h2_fold, $h2_uidguess ) ;
  9309. }
  9310. if ( $mysync->{ synclabels } ) { synclabels( $mysync, $h1_msg, $new_id ) }
  9311. $h2_uidguess += 1 ;
  9312. $mysync->{ total_bytes_transferred } += $string_len ;
  9313. $mysync->{ nb_msg_transferred } += 1 ;
  9314. $mysync->{ h1_nb_msg_processed } +=1 ;
  9315. $mysync->{ biggest_message_transferred } = max( $string_len, $mysync->{ biggest_message_transferred } ) ;
  9316. my $time_spent = timesince( $mysync->{begin_transfer_time} ) ;
  9317. my $rate = bytes_display_string( $mysync->{total_bytes_transferred} / $time_spent ) ;
  9318. my $eta = eta( $mysync ) ;
  9319. my $amount_transferred = bytes_display_string( $mysync->{total_bytes_transferred} ) ;
  9320. myprintf( "msg %s/%-19s copied to %s/%-10s %.2f msgs/s %s/s %s copied %s\n",
  9321. $h1_fold, "$h1_msg {$string_len}", $h2_fold, $new_id, $mysync->{nb_msg_transferred}/$time_spent, $rate,
  9322. $amount_transferred,
  9323. $eta );
  9324. sleep_if_needed( $mysync ) ;
  9325. if ( $usecache and $cacheaftercopy and $new_id =~ m{^\d+$}x ) {
  9326. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$new_id\n" ) ;
  9327. touch( "$cache_dir/${h1_msg}_$new_id" )
  9328. or croak( "Couldn't touch $cache_dir/${h1_msg}_$new_id" ) ;
  9329. }
  9330. if ( $mysync->{ delete1 } ) {
  9331. delete_message_on_host1( $mysync, $h1_fold, $mysync->{ expungeaftereach }, $h1_msg ) ;
  9332. }
  9333. #myprint( "PRESS ENTER" ) and my $a = <> ;
  9334. return( $new_id ) ;
  9335. }
  9336. }
  9337. else{
  9338. $nb_msg_skipped_dry_mode += 1 ;
  9339. $mysync->{ h1_nb_msg_processed } += 1 ;
  9340. }
  9341. return ;
  9342. }
  9343. sub tests_sleep_if_needed
  9344. {
  9345. note( 'Entering tests_sleep_if_needed()' ) ;
  9346. is( undef, sleep_if_needed( ), 'sleep_if_needed: no args => undef' ) ;
  9347. my $mysync ;
  9348. is( undef, sleep_if_needed( $mysync ), 'sleep_if_needed: arg undef => undef' ) ;
  9349. $mysync->{maxbytespersecond} = 1000 ;
  9350. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: maxbytespersecond only => no sleep => 0' ) ;
  9351. $mysync->{begin_transfer_time} = time ; # now
  9352. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: begin_transfer_time now => no sleep => 0' ) ;
  9353. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before
  9354. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 0 => no sleep => 0' ) ;
  9355. $mysync->{total_bytes_transferred} = 2200 ;
  9356. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before
  9357. is( '0.20', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 2200 since 2s => sleep 0.2s' ) ;
  9358. is( '0', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 2200 since 2+2 == 4s => no sleep' ) ;
  9359. $mysync->{maxsleep} = 0.1 ;
  9360. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before again
  9361. is( '0.10', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 4000 since 2s but maxsleep 0.1s => sleep 0.1s' ) ;
  9362. $mysync->{maxbytesafter} = 4000 ;
  9363. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before again
  9364. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: maxbytesafter == total_bytes_transferred => no sleep => 0' ) ;
  9365. note( 'Leaving tests_sleep_if_needed()' ) ;
  9366. return ;
  9367. }
  9368. sub sleep_if_needed
  9369. {
  9370. my( $mysync ) = shift ;
  9371. if ( ! $mysync ) {
  9372. return ;
  9373. }
  9374. # No need to go further if there is no limit set
  9375. if (
  9376. not (
  9377. $mysync->{maxmessagespersecond}
  9378. or $mysync->{maxbytespersecond}
  9379. )
  9380. ) {
  9381. return ;
  9382. }
  9383. $mysync->{maxsleep} = defined $mysync->{maxsleep} ? $mysync->{maxsleep} : $MAX_SLEEP ;
  9384. # Must be positive
  9385. $mysync->{maxsleep} = max( 0, $mysync->{maxsleep} ) ;
  9386. my $time_spent = timesince( $mysync->{begin_transfer_time} ) ;
  9387. my $sleep_max_messages = sleep_max_messages( $mysync->{nb_msg_transferred}, $time_spent, $mysync->{maxmessagespersecond} ) ;
  9388. my $maxbytesafter = $mysync->{maxbytesafter} || 0 ;
  9389. my $total_bytes_transferred = $mysync->{total_bytes_transferred} || 0 ;
  9390. my $total_bytes_to_consider = $total_bytes_transferred - $maxbytesafter ;
  9391. #myprint( "maxbytesafter:$maxbytesafter\n" ) ;
  9392. #myprint( "total_bytes_to_consider:$total_bytes_to_consider\n" ) ;
  9393. my $sleep_max_bytes = sleep_max_bytes( $total_bytes_to_consider, $time_spent, $mysync->{maxbytespersecond} ) ;
  9394. my $sleep_max = min( $mysync->{maxsleep}, max( $sleep_max_messages, $sleep_max_bytes ) ) ;
  9395. $sleep_max = mysprintf( "%.2f", $sleep_max ) ; # round with 2 decimals.
  9396. if ( $sleep_max > 0 ) {
  9397. myprint( "sleeping $sleep_max s\n" ) ;
  9398. sleep $sleep_max ;
  9399. # Slept
  9400. return $sleep_max ;
  9401. }
  9402. # No sleep
  9403. return 0 ;
  9404. }
  9405. sub sleep_max_messages
  9406. {
  9407. # how long we have to sleep to go under max_messages_per_second
  9408. my( $nb_msg_transferred, $time_spent, $maxmessagespersecond ) = @_ ;
  9409. if ( ( not defined $maxmessagespersecond ) or $maxmessagespersecond <= 0 ) { return( 0 ) } ;
  9410. my $sleep = ( $nb_msg_transferred / $maxmessagespersecond ) - $time_spent ;
  9411. # the sleep must be positive
  9412. return( max( 0, $sleep ) ) ;
  9413. }
  9414. sub tests_sleep_max_messages
  9415. {
  9416. note( 'Entering tests_sleep_max_messages()' ) ;
  9417. ok( 0 == sleep_max_messages( 4, 2, undef ), 'sleep_max_messages: maxmessagespersecond = undef') ;
  9418. ok( 0 == sleep_max_messages( 4, 2, 0 ), 'sleep_max_messages: maxmessagespersecond = 0') ;
  9419. ok( 0 == sleep_max_messages( 4, 2, $MINUS_ONE ), 'sleep_max_messages: maxmessagespersecond = -1') ;
  9420. ok( 0 == sleep_max_messages( 4, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max reached') ;
  9421. ok( 2 == sleep_max_messages( 8, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max over') ;
  9422. ok( 0 == sleep_max_messages( 2, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max not reached') ;
  9423. note( 'Leaving tests_sleep_max_messages()' ) ;
  9424. return ;
  9425. }
  9426. sub sleep_max_bytes
  9427. {
  9428. # how long we have to sleep to go under max_bytes_per_second
  9429. my( $total_bytes_to_consider, $time_spent, $maxbytespersecond ) = @_ ;
  9430. $total_bytes_to_consider ||= 0 ;
  9431. $time_spent ||= 0 ;
  9432. if ( ( not defined $maxbytespersecond ) or $maxbytespersecond <= 0 ) { return( 0 ) } ;
  9433. #myprint( "total_bytes_to_consider:$total_bytes_to_consider\n" ) ;
  9434. my $sleep = ( $total_bytes_to_consider / $maxbytespersecond ) - $time_spent ;
  9435. # the sleep must be positive
  9436. return( max( 0, $sleep ) ) ;
  9437. }
  9438. sub tests_sleep_max_bytes
  9439. {
  9440. note( 'Entering tests_sleep_max_bytes()' ) ;
  9441. ok( 0 == sleep_max_bytes( 4000, 2, undef ), 'sleep_max_bytes: maxbytespersecond == undef => sleep 0' ) ;
  9442. ok( 0 == sleep_max_bytes( 4000, 2, 0 ), 'sleep_max_bytes: maxbytespersecond = 0 => sleep 0') ;
  9443. ok( 0 == sleep_max_bytes( 4000, 2, $MINUS_ONE ), 'sleep_max_bytes: maxbytespersecond = -1 => sleep 0') ;
  9444. ok( 0 == sleep_max_bytes( 4000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max reached sharp => sleep 0') ;
  9445. ok( 2 == sleep_max_bytes( 8000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max over => sleep a little') ;
  9446. ok( 0 == sleep_max_bytes( -8000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max not reached => sleep 0') ;
  9447. ok( 0 == sleep_max_bytes( 2000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max not reached => sleep 0') ;
  9448. ok( 0 == sleep_max_bytes( -2000, 2, 1000 ), 'sleep_max_bytes: maxbytespersecond = 1k max not reached => sleep 0') ;
  9449. note( 'Leaving tests_sleep_max_bytes()' ) ;
  9450. return ;
  9451. }
  9452. sub delete_message_on_host1
  9453. {
  9454. my( $mysync, $h1_fold, $expunge, @h1_msg ) = @_ ;
  9455. if ( ! $mysync->{ delete1 } ) { return ; }
  9456. if ( ! @h1_msg ) { return ; }
  9457. delete_messages_on_any(
  9458. $mysync,
  9459. $mysync->{ acc1 },
  9460. $mysync->{ imap1 },
  9461. "Host1: $h1_fold",
  9462. $expunge,
  9463. $split1,
  9464. @h1_msg ) ;
  9465. return ;
  9466. }
  9467. sub tests_operators_and_exclam_precedence
  9468. {
  9469. note( 'Entering tests_operators_and_exclam_precedence()' ) ;
  9470. is( 1, ! 0, 'tests_operators_and_exclam_precedence: ! 0 => 1' ) ;
  9471. is( "", ! 1, 'tests_operators_and_exclam_precedence: ! 1 => ""' ) ;
  9472. is( 1, not( 0 ), 'tests_operators_and_exclam_precedence: not( 0 ) => 1' ) ;
  9473. is( "", not( 1 ), 'tests_operators_and_exclam_precedence: not( 1 ) => ""' ) ;
  9474. # I wrote those tests to avoid perlcrit "Mixed high and low-precedence booleans"
  9475. # and change sub delete_messages_on_any() but got 4 more warnings... So now commented.
  9476. #is( 0, ( ! 0 and 0 ), 'tests_operators_and_exclam_precedence: ! 0 and 0 ) => 0' ) ;
  9477. #is( 1, ( ! 0 and 1 ), 'tests_operators_and_exclam_precedence: ! 0 and 1 ) => 1' ) ;
  9478. #is( "", ( ! 1 and 0 ), 'tests_operators_and_exclam_precedence: ! 1 and 0 ) => ""' ) ;
  9479. #is( "", ( ! 1 and 1 ), 'tests_operators_and_exclam_precedence: ! 1 and 1 ) => ""' ) ;
  9480. is( 0, ( ! 0 && 0 ), 'tests_operators_and_exclam_precedence: ! 0 && 0 ) => 0' ) ;
  9481. is( 1, ( ! 0 && 1 ), 'tests_operators_and_exclam_precedence: ! 0 && 1 ) => 1' ) ;
  9482. is( "", ( ! 1 && 0 ), 'tests_operators_and_exclam_precedence: ! 1 && 0 ) => ""' ) ;
  9483. is( "", ( ! 1 && 1 ), 'tests_operators_and_exclam_precedence: ! 1 && 1 ) => ""' ) ;
  9484. is( 2, ( ! 0 && 2 ), 'tests_operators_and_exclam_precedence: ! 0 && 2 ) => 1' ) ;
  9485. note( 'Leaving tests_operators_and_exclam_precedence()' ) ;
  9486. return ;
  9487. }
  9488. sub delete_messages_on_any
  9489. {
  9490. # $acc is not used yet,
  9491. #
  9492. my( $mysync, $acc, $imap, $hostX_folder, $expunge, $split, @messages ) = @_ ;
  9493. my $expunge_message = q{} ;
  9494. my $dry_message = $mysync->{ dry_message } ;
  9495. $expunge_message = 'and expunged' if ( $expunge ) ;
  9496. # "Host1: msg "
  9497. # $imap->Debug( 1 ) ;
  9498. my @messages_to_mark_deleted = @messages ;
  9499. while ( my @messages_part = splice @messages_to_mark_deleted, 0, $split )
  9500. {
  9501. foreach my $message ( @messages_part )
  9502. {
  9503. myprint( "$hostX_folder/$message marking deleted $expunge_message $dry_message\n" ) ;
  9504. }
  9505. if ( ! $mysync->{dry} && @messages_part )
  9506. {
  9507. my $nb_deleted = $imap->delete_message( $imap->Range( @messages_part ) ) ;
  9508. if ( defined $nb_deleted )
  9509. {
  9510. # $nb_deleted is not accurate
  9511. $acc->{ nb_msg_deleted } += scalar @messages_part ;
  9512. }
  9513. else
  9514. {
  9515. my $error_imap = $imap->LastError || q{} ;
  9516. my $error = join( q{}, "$hostX_folder folder, could not delete ",
  9517. scalar @messages_part, ' messages: ', $error_imap, "\n" ) ;
  9518. errors_incr( $mysync, $error ) ;
  9519. }
  9520. }
  9521. }
  9522. if ( $expunge ) {
  9523. uidexpunge_or_expunge( $mysync, $imap, @messages ) ;
  9524. }
  9525. #$imap->Debug( 0 ) ;
  9526. return ;
  9527. }
  9528. sub tests_uidexpunge_or_expunge
  9529. {
  9530. note( 'Entering tests_uidexpunge_or_expunge()' ) ;
  9531. is( undef, uidexpunge_or_expunge( ), 'uidexpunge_or_expunge: no args => undef' ) ;
  9532. my $mysync ;
  9533. is( undef, uidexpunge_or_expunge( $mysync ), 'uidexpunge_or_expunge: undef args => undef' ) ;
  9534. $mysync = {} ;
  9535. is( undef, uidexpunge_or_expunge( $mysync ), 'uidexpunge_or_expunge: arg empty => undef' ) ;
  9536. my $imap ;
  9537. is( undef, uidexpunge_or_expunge( $mysync, $imap ), 'uidexpunge_or_expunge: undef Mail-IMAPClient instance => undef' ) ;
  9538. require_ok( "Test::MockObject" ) ;
  9539. $imap = Test::MockObject->new( ) ;
  9540. is( undef, uidexpunge_or_expunge( $mysync, $imap ), 'uidexpunge_or_expunge: no message (1) to uidexpunge => undef' ) ;
  9541. my @messages = ( ) ;
  9542. is( undef, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: no message (2) to uidexpunge => undef' ) ;
  9543. @messages = ( '2', '1' ) ;
  9544. $imap->mock( 'uidexpunge', sub { return ; } ) ;
  9545. $imap->mock( 'expunge', sub { return ; } ) ;
  9546. is( undef, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: uidexpunge failure => expunge failure => undef' ) ;
  9547. $imap->mock( 'expunge', sub { return 1 ; } ) ;
  9548. is( 1, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: uidexpunge failure => expunge ok => 1' ) ;
  9549. $imap->mock( 'uidexpunge', sub { return 1 ; } ) ;
  9550. is( 1, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: messages to uidexpunge ok => 1' ) ;
  9551. note( 'Leaving tests_uidexpunge_or_expunge()' ) ;
  9552. return ;
  9553. }
  9554. sub uidexpunge_or_expunge
  9555. {
  9556. my $mysync = shift ;
  9557. my $imap = shift ;
  9558. my @messages = @ARG ;
  9559. if ( ! $imap ) { return ; } ;
  9560. if ( ! @messages ) { return ; } ;
  9561. # Doing uidexpunge
  9562. my @uidexpunge_result = $imap->uidexpunge( @messages ) ;
  9563. if ( @uidexpunge_result ) {
  9564. return 1 ;
  9565. }
  9566. # Failure so doing expunge
  9567. my $expunge_result = $imap->expunge( ) ;
  9568. if ( $expunge_result ) {
  9569. return 1 ;
  9570. }
  9571. # bad trip
  9572. return ;
  9573. }
  9574. sub eta_print
  9575. {
  9576. my $mysync = shift ;
  9577. if ( my $eta = eta( $mysync ) )
  9578. {
  9579. myprint( "$eta\n" ) ;
  9580. }
  9581. return ;
  9582. }
  9583. sub tests_eta
  9584. {
  9585. note( 'Entering tests_eta()' ) ;
  9586. is( q{}, eta( ), 'eta: no args => ""' ) ;
  9587. is( q{}, eta( undef ), 'eta: undef => ""' ) ;
  9588. my $mysync = {} ;
  9589. # No foldersizes
  9590. is( q{}, eta( $mysync ), 'eta: No foldersizes => ""' ) ;
  9591. $mysync->{ foldersizes } = 1 ;
  9592. $mysync->{ begin_transfer_time } = time ; # Now
  9593. $mysync->{ h1_nb_msg_processed } = 0 ;
  9594. is( "ETA: " . localtimez( time ) . " 0 s 0/0 msgs left",
  9595. eta( $mysync ),
  9596. 'eta: no args => ETA: "Now" 0 s 0/0 msgs left' ) ;
  9597. $mysync->{ h1_nb_msg_processed } = 1 ;
  9598. $mysync->{ h1_nb_msg_start } = 2 ;
  9599. is( "ETA: " . localtimez( time ) . " 0 s 1/2 msgs left",
  9600. eta( $mysync ),
  9601. 'eta: 1, 1, 2 => ETA: "Now" 0 s 1/2 msgs left' ) ;
  9602. note( 'Leaving tests_eta()' ) ;
  9603. return ;
  9604. }
  9605. sub eta
  9606. {
  9607. my( $mysync ) = shift ;
  9608. if ( ! $mysync )
  9609. {
  9610. return q{} ;
  9611. }
  9612. return( q{} ) if not $mysync->{ foldersizes } ;
  9613. my $h1_nb_msg_start = $mysync->{ h1_nb_msg_start } ;
  9614. my $h1_nb_processed = $mysync->{ h1_nb_msg_processed } ;
  9615. my $nb_msg_transferred = ( $mysync->{dry} ) ? $mysync->{ h1_nb_msg_processed } : $mysync->{ nb_msg_transferred } ;
  9616. my $time_spent = timesince( $mysync->{ begin_transfer_time } ) ;
  9617. $h1_nb_processed ||= 0 ;
  9618. $h1_nb_msg_start ||= 0 ;
  9619. $time_spent ||= 0 ;
  9620. my $time_remaining = time_remaining( $time_spent, $h1_nb_processed, $h1_nb_msg_start, $nb_msg_transferred ) ;
  9621. $mysync->{ debug } and myprint( "time_spent: $time_spent time_remaining: $time_remaining\n" ) ;
  9622. my $nb_msg_remaining = $h1_nb_msg_start - $h1_nb_processed ;
  9623. my $eta_date = localtimez( time + $time_remaining ) ;
  9624. return( mysprintf( 'ETA: %s %1.0f s %s/%s msgs left',
  9625. $eta_date, $time_remaining, $nb_msg_remaining, $h1_nb_msg_start ) ) ;
  9626. }
  9627. sub time_remaining
  9628. {
  9629. my( $my_time_spent, $h1_nb_processed, $h1_nb_msg_start, $nb_transferred ) = @_ ;
  9630. $nb_transferred ||= 1 ; # At least one is done (no division by zero)
  9631. $h1_nb_processed ||= 0 ;
  9632. $h1_nb_msg_start ||= $h1_nb_processed ;
  9633. $my_time_spent ||= 0 ;
  9634. my $time_remaining = ( $my_time_spent / $nb_transferred ) * ( $h1_nb_msg_start - $h1_nb_processed ) ;
  9635. return( $time_remaining ) ;
  9636. }
  9637. sub tests_time_remaining
  9638. {
  9639. note( 'Entering tests_time_remaining()' ) ;
  9640. # time_spent, nb_processed, nb_to_do_total, nb_transferred
  9641. is( 0, time_remaining( ), 'time_remaining: no args -> 0' ) ;
  9642. is( 0, time_remaining( 0, 0, 0, 0 ), 'time_remaining: 0, 0, 0, 0 -> 0' ) ;
  9643. is( 1, time_remaining( 1, 1, 2, 1 ), 'time_remaining: 1, 1, 2, 1 -> 1' ) ;
  9644. is( 1, time_remaining( 9, 9, 10, 9 ), 'time_remaining: 9, 9, 10, 9 -> 1' ) ;
  9645. is( 9, time_remaining( 1, 1, 10, 1 ), 'time_remaining: 1, 1, 10, 1 -> 9' ) ;
  9646. is( 5, time_remaining( 5, 5, 10, 5 ), 'time_remaining: 5, 5, 10, 5 -> 5' ) ;
  9647. is( 25, time_remaining( 5, 5, 10, 0 ), 'time_remaining: 5, 5, 10, 0 -> ( 5 / 1 ) * ( 10 - 5) = 25' ) ;
  9648. is( 25, time_remaining( 5, 5, 10, 1 ), 'time_remaining: 5, 5, 10, 1 -> ( 5 / 1 ) * ( 10 - 5) = 25' ) ;
  9649. note( 'Leaving tests_time_remaining()' ) ;
  9650. return ;
  9651. }
  9652. sub cache_map
  9653. {
  9654. my ( $cache_files_ref, $h1_msgs_ref, $h2_msgs_ref ) = @_;
  9655. my ( %map1_2, %map2_1, %done2 ) ;
  9656. my $h1_msgs_hash_ref = { } ;
  9657. my $h2_msgs_hash_ref = { } ;
  9658. @{ $h1_msgs_hash_ref }{ @{ $h1_msgs_ref } } = ( ) ;
  9659. @{ $h2_msgs_hash_ref }{ @{ $h2_msgs_ref } } = ( ) ;
  9660. foreach my $file ( sort @{ $cache_files_ref } ) {
  9661. $debugcache and myprint( "C12: $file\n" ) ;
  9662. ( $uid1, $uid2 ) = match_a_cache_file( $file ) ;
  9663. if ( exists( $h1_msgs_hash_ref->{ defined $uid1 ? $uid1 : q{} } )
  9664. and exists( $h2_msgs_hash_ref->{ defined $uid2 ? $uid2 : q{} } ) ) {
  9665. # keep only the greatest uid2
  9666. # 130_2301 and
  9667. # 130_231 => keep only 130 -> 2301
  9668. # keep only the greatest uid1
  9669. # 1601_260 and
  9670. # 161_260 => keep only 1601 -> 260
  9671. my $max_uid2 = max( $uid2, $map1_2{ $uid1 } || $MINUS_ONE ) ;
  9672. if ( exists $done2{ $max_uid2 } ) {
  9673. if ( $done2{ $max_uid2 } < $uid1 ) {
  9674. $map1_2{ $uid1 } = $max_uid2 ;
  9675. delete $map1_2{ $done2{ $max_uid2 } } ;
  9676. $done2{ $max_uid2 } = $uid1 ;
  9677. }
  9678. }else{
  9679. $map1_2{ $uid1 } = $max_uid2 ;
  9680. $done2{ $max_uid2 } = $uid1 ;
  9681. }
  9682. };
  9683. }
  9684. %map2_1 = reverse %map1_2 ;
  9685. return( \%map1_2, \%map2_1) ;
  9686. }
  9687. sub tests_cache_map
  9688. {
  9689. note( 'Entering tests_cache_map()' ) ;
  9690. #$debugcache = 1 ;
  9691. my @cache_files = qw (
  9692. 100_200
  9693. 101_201
  9694. 120_220
  9695. 142_242
  9696. 143_243
  9697. 177_277
  9698. 177_278
  9699. 177_279
  9700. 155_255
  9701. 180_280
  9702. 181_280
  9703. 182_280
  9704. 130_231
  9705. 130_2301
  9706. 161_260
  9707. 1601_260
  9708. ) ;
  9709. my $msgs_1 = [120, 142, 143, 144, 161, 1601, 177, 182, 130 ];
  9710. my $msgs_2 = [ 242, 243, 260, 299, 377, 279, 255, 280, 231, 2301 ];
  9711. my( $c12, $c21 ) ;
  9712. ok( ( $c12, $c21 ) = cache_map( \@cache_files, $msgs_1, $msgs_2 ), 'cache_map: 02' );
  9713. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  9714. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  9715. ok( 0 == compare_lists( [ 130, 142, 143, 177, 182, 1601 ], $a1 ), 'cache_map: 03' );
  9716. ok( 0 == compare_lists( [ 242, 243, 260, 279, 280, 2301 ], $a2 ), 'cache_map: 04' );
  9717. ok( ! $c12->{161}, 'cache_map: ! 161 -> 260' );
  9718. ok( 260 == $c12->{1601}, 'cache_map: 1601 -> 260' );
  9719. ok( 2301 == $c12->{130}, 'cache_map: 130 -> 2301' );
  9720. #myprint( $c12->{1601}, "\n" ) ;
  9721. note( 'Leaving tests_cache_map()' ) ;
  9722. return ;
  9723. }
  9724. sub cache_dir_fix
  9725. {
  9726. my $cache_dir = shift ;
  9727. $cache_dir =~ s/([;<>\*\|`&\$!#\(\)\[\]\{\}:'"\\])/\\$1/xg ;
  9728. #myprint( "cache_dir_fix: $cache_dir\n" ) ;
  9729. return( $cache_dir ) ;
  9730. }
  9731. sub tests_cache_dir_fix
  9732. {
  9733. note( 'Entering tests_cache_dir_fix()' ) ;
  9734. ok( 'lalala' eq cache_dir_fix('lalala'), 'cache_dir_fix: lalala -> lalala' );
  9735. ok( 'ii\\\\ii' eq cache_dir_fix('ii\ii'), 'cache_dir_fix: ii\ii -> ii\\\\ii' );
  9736. ok( 'ii@ii' eq cache_dir_fix('ii@ii'), 'cache_dir_fix: ii@ii -> ii@ii' );
  9737. ok( 'ii@ii\\:ii' eq cache_dir_fix('ii@ii:ii'), 'cache_dir_fix: ii@ii:ii -> ii@ii\\:ii' );
  9738. ok( 'i\\\\i\\\\ii' eq cache_dir_fix('i\i\ii'), 'cache_dir_fix: i\i\ii -> i\\\\i\\\\ii' );
  9739. ok( 'i\\\\ii' eq cache_dir_fix('i\\ii'), 'cache_dir_fix: i\\ii -> i\\\\\\\\ii' );
  9740. ok( '\\\\ ' eq cache_dir_fix('\\ '), 'cache_dir_fix: \\ -> \\\\\ ' );
  9741. ok( '\\\\ ' eq cache_dir_fix('\ '), 'cache_dir_fix: \ -> \\\\\ ' );
  9742. ok( '\[bracket\]' eq cache_dir_fix('[bracket]'), 'cache_dir_fix: [bracket] -> \[bracket\]' );
  9743. note( 'Leaving tests_cache_dir_fix()' ) ;
  9744. return ;
  9745. }
  9746. sub cache_dir_fix_win
  9747. {
  9748. my $cache_dir = shift ;
  9749. $cache_dir =~ s/(\[|\])/[$1]/xg ;
  9750. #myprint( "cache_dir_fix_win: $cache_dir\n" ) ;
  9751. return( $cache_dir ) ;
  9752. }
  9753. sub tests_cache_dir_fix_win
  9754. {
  9755. note( 'Entering tests_cache_dir_fix_win()' ) ;
  9756. ok( 'lalala' eq cache_dir_fix_win('lalala'), 'cache_dir_fix_win: lalala -> lalala' );
  9757. ok( '[[]bracket[]]' eq cache_dir_fix_win('[bracket]'), 'cache_dir_fix_win: [bracket] -> [[]bracket[]]' );
  9758. note( 'Leaving tests_cache_dir_fix_win()' ) ;
  9759. return ;
  9760. }
  9761. sub get_cache
  9762. {
  9763. my ( $cache_dir, $h1_msgs_ref, $h2_msgs_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_;
  9764. $debugcache and myprint( "Entering get_cache\n" ) ;
  9765. -d $cache_dir or return( undef ); # exit if cache directory doesn't exist
  9766. $debugcache and myprint( "cache_dir : $cache_dir\n" ) ;
  9767. if ( 'MSWin32' ne $OSNAME ) {
  9768. $cache_dir = cache_dir_fix( $cache_dir ) ;
  9769. }else{
  9770. $cache_dir = cache_dir_fix_win( $cache_dir ) ;
  9771. }
  9772. $debugcache and myprint( "cache_dir_fix: $cache_dir\n" ) ;
  9773. my @cache_files = bsd_glob( "$cache_dir/*" ) ;
  9774. #$debugcache and myprint( "cache_files: [@cache_files]\n" ) ;
  9775. $debugcache and myprint( 'cache_files: ', scalar @cache_files , " files found\n" ) ;
  9776. my( $cache_1_2_ref, $cache_2_1_ref )
  9777. = cache_map( \@cache_files, $h1_msgs_ref, $h2_msgs_ref ) ;
  9778. clean_cache( \@cache_files, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  9779. $debugcache and myprint( "Exiting get_cache\n" ) ;
  9780. return( $cache_1_2_ref, $cache_2_1_ref ) ;
  9781. }
  9782. sub tests_get_cache
  9783. {
  9784. note( 'Entering tests_get_cache()' ) ;
  9785. ok( not( get_cache('/cache_no_exist') ), 'get_cache: /cache_no_exist' );
  9786. ok( ( not -d 'W/tmp/cache/F1/F2' or rmtree( 'W/tmp/cache/F1/F2' ) ), 'get_cache: rmtree W/tmp/cache/F1/F2' ) ;
  9787. ok( mkpath( 'W/tmp/cache/F1/F2' ), 'get_cache: mkpath W/tmp/cache/F1/F2' ) ;
  9788. my @test_files_cache = ( qw(
  9789. W/tmp/cache/F1/F2/100_200
  9790. W/tmp/cache/F1/F2/101_201
  9791. W/tmp/cache/F1/F2/120_220
  9792. W/tmp/cache/F1/F2/142_242
  9793. W/tmp/cache/F1/F2/143_243
  9794. W/tmp/cache/F1/F2/177_277
  9795. W/tmp/cache/F1/F2/177_377
  9796. W/tmp/cache/F1/F2/177_777
  9797. W/tmp/cache/F1/F2/155_255
  9798. ) ) ;
  9799. ok( touch( @test_files_cache ), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  9800. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  9801. # on live:
  9802. my $msgs_1 = [120, 142, 143, 144, 177 ];
  9803. my $msgs_2 = [ 242, 243, 299, 377, 777, 255 ];
  9804. my $msgs_all_1 = { 120 => 0, 142 => 0, 143 => 0, 144 => 0, 177 => 0 } ;
  9805. my $msgs_all_2 = { 242 => 0, 243 => 0, 299 => 0, 377 => 0, 777 => 0, 255 => 0 } ;
  9806. my( $c12, $c21 ) ;
  9807. ok( ( $c12, $c21 ) = get_cache( 'W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  9808. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  9809. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  9810. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: 03' );
  9811. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: 04' );
  9812. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  9813. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  9814. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file removed 100_200');
  9815. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file removed 101_201');
  9816. # test clean_cache executed
  9817. $maxage = 2 ;
  9818. ok( touch(@test_files_cache), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  9819. ok( ( $c12, $c21 ) = get_cache('W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  9820. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  9821. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  9822. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file NOT removed 100_200');
  9823. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file NOT removed 101_201');
  9824. # strange files
  9825. #$debugcache = 1 ;
  9826. $maxage = undef ;
  9827. ok( ( not -d 'W/tmp/cache/rr\uee' or rmtree( 'W/tmp/cache/rr\uee' )), 'get_cache: rmtree W/tmp/cache/rr\uee' ) ;
  9828. ok( mkpath( 'W/tmp/cache/rr\uee' ), 'get_cache: mkpath W/tmp/cache/rr\uee' ) ;
  9829. @test_files_cache = ( qw(
  9830. W/tmp/cache/rr\uee/100_200
  9831. W/tmp/cache/rr\uee/101_201
  9832. W/tmp/cache/rr\uee/120_220
  9833. W/tmp/cache/rr\uee/142_242
  9834. W/tmp/cache/rr\uee/143_243
  9835. W/tmp/cache/rr\uee/177_277
  9836. W/tmp/cache/rr\uee/177_377
  9837. W/tmp/cache/rr\uee/177_777
  9838. W/tmp/cache/rr\uee/155_255
  9839. ) ) ;
  9840. ok( touch(@test_files_cache), 'get_cache: touch strange W/tmp/cache/...' ) ;
  9841. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  9842. # on live:
  9843. $msgs_1 = [120, 142, 143, 144, 177 ] ;
  9844. $msgs_2 = [ 242, 243, 299, 377, 777, 255 ] ;
  9845. $msgs_all_1 = { 120 => q{}, 142 => q{}, 143 => q{}, 144 => q{}, 177 => q{} } ;
  9846. $msgs_all_2 = { 242 => q{}, 243 => q{}, 299 => q{}, 377 => q{}, 777 => q{}, 255 => q{} } ;
  9847. 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' );
  9848. $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  9849. $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  9850. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: strange path 03' );
  9851. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: strange path 04' );
  9852. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 142_242');
  9853. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 143_243');
  9854. ok( ! -f 'W/tmp/cache/rr\uee/100_200', 'get_cache: strange path file removed 100_200');
  9855. ok( ! -f 'W/tmp/cache/rr\uee/101_201', 'get_cache: strange path file removed 101_201');
  9856. note( 'Leaving tests_get_cache()' ) ;
  9857. return ;
  9858. }
  9859. sub match_a_cache_file
  9860. {
  9861. my $file = shift ;
  9862. my ( $cache_uid1, $cache_uid2 ) ;
  9863. return( ( undef, undef ) ) if ( ! $file ) ;
  9864. if ( $file =~ m{(?:^|/)(\d+)_(\d+)$}x ) {
  9865. $cache_uid1 = $1 ;
  9866. $cache_uid2 = $2 ;
  9867. }
  9868. return( $cache_uid1, $cache_uid2 ) ;
  9869. }
  9870. sub tests_match_a_cache_file
  9871. {
  9872. note( 'Entering tests_match_a_cache_file()' ) ;
  9873. my ( $tuid1, $tuid2 ) ;
  9874. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( ), 'match_a_cache_file: no arg' ) ;
  9875. ok( ! defined $tuid1 , 'match_a_cache_file: no arg 1' ) ;
  9876. ok( ! defined $tuid2 , 'match_a_cache_file: no arg 2' ) ;
  9877. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( q{} ), 'match_a_cache_file: empty arg' ) ;
  9878. ok( ! defined $tuid1 , 'match_a_cache_file: empty arg 1' ) ;
  9879. ok( ! defined $tuid2 , 'match_a_cache_file: empty arg 2' ) ;
  9880. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '000_000' ), 'match_a_cache_file: 000_000' ) ;
  9881. ok( '000' eq $tuid1, 'match_a_cache_file: 000_000 1' ) ;
  9882. ok( '000' eq $tuid2, 'match_a_cache_file: 000_000 2' ) ;
  9883. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '123_456' ), 'match_a_cache_file: 123_456' ) ;
  9884. ok( '123' eq $tuid1, 'match_a_cache_file: 123_456 1' ) ;
  9885. ok( '456' eq $tuid2, 'match_a_cache_file: 123_456 2' ) ;
  9886. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/tmp/truc/123_456' ), 'match_a_cache_file: /tmp/truc/123_456' ) ;
  9887. ok( '123' eq $tuid1, 'match_a_cache_file: /tmp/truc/123_456 1' ) ;
  9888. ok( '456' eq $tuid2, 'match_a_cache_file: /tmp/truc/123_456 2' ) ;
  9889. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/lala123_456' ), 'match_a_cache_file: NO /lala123_456' ) ;
  9890. ok( ! $tuid1, 'match_a_cache_file: /lala123_456 1' ) ;
  9891. ok( ! $tuid2, 'match_a_cache_file: /lala123_456 2' ) ;
  9892. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( 'la123_456' ), 'match_a_cache_file: NO la123_456' ) ;
  9893. ok( ! $tuid1, 'match_a_cache_file: la123_456 1' ) ;
  9894. ok( ! $tuid2, 'match_a_cache_file: la123_456 2' ) ;
  9895. note( 'Leaving tests_match_a_cache_file()' ) ;
  9896. return ;
  9897. }
  9898. sub clean_cache
  9899. {
  9900. my ( $cache_files_ref, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_ ;
  9901. $debugcache and myprint( "Entering clean_cache\n" ) ;
  9902. $debugcache and myprint( map { "$_ -> " . $cache_1_2_ref->{ $_ } . "\n" } keys %{ $cache_1_2_ref } ) ;
  9903. foreach my $file ( @{ $cache_files_ref } ) {
  9904. $debugcache and myprint( "$file\n" ) ;
  9905. my ( $cache_uid1, $cache_uid2 ) = match_a_cache_file( $file ) ;
  9906. $debugcache and myprint( "u1: $cache_uid1 u2: $cache_uid2 c12: ", $cache_1_2_ref->{ $cache_uid1 } || q{}, "\n") ;
  9907. # or ( ! exists( $cache_1_2_ref->{ $cache_uid1 } ) )
  9908. # or ( ! ( $cache_uid2 == $cache_1_2_ref->{ $cache_uid1 } ) )
  9909. if ( ( not defined $cache_uid1 )
  9910. or ( not defined $cache_uid2 )
  9911. or ( not exists $h1_msgs_all_hash_ref->{ $cache_uid1 } )
  9912. or ( not exists $h2_msgs_all_hash_ref->{ $cache_uid2 } )
  9913. ) {
  9914. $debugcache and myprint( "remove $file\n" ) ;
  9915. unlink $file or myprint( "$OS_ERROR" ) ;
  9916. }
  9917. }
  9918. $debugcache and myprint( "Exiting clean_cache\n" ) ;
  9919. return( 1 ) ;
  9920. }
  9921. sub tests_clean_cache
  9922. {
  9923. note( 'Entering tests_clean_cache()' ) ;
  9924. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache: rmtree W/tmp/cache/G1/G2' ) ;
  9925. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache: mkpath W/tmp/cache/G1/G2' ) ;
  9926. my @test_files_cache = ( qw(
  9927. W/tmp/cache/G1/G2/100_200
  9928. W/tmp/cache/G1/G2/101_201
  9929. W/tmp/cache/G1/G2/120_220
  9930. W/tmp/cache/G1/G2/142_242
  9931. W/tmp/cache/G1/G2/143_243
  9932. W/tmp/cache/G1/G2/177_277
  9933. W/tmp/cache/G1/G2/177_377
  9934. W/tmp/cache/G1/G2/177_777
  9935. W/tmp/cache/G1/G2/155_255
  9936. ) ) ;
  9937. ok( touch(@test_files_cache), 'clean_cache: touch W/tmp/cache/G1/G2/...' ) ;
  9938. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 before' );
  9939. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 before' );
  9940. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 before' );
  9941. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 before' );
  9942. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 before' );
  9943. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 before' );
  9944. my $cache = {
  9945. 142 => 242,
  9946. 177 => 777,
  9947. } ;
  9948. my $all_1 = {
  9949. 142 => q{},
  9950. 177 => q{},
  9951. } ;
  9952. my $all_2 = {
  9953. 200 => q{},
  9954. 242 => q{},
  9955. 777 => q{},
  9956. } ;
  9957. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache: ' ) ;
  9958. ok( ! -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 after' );
  9959. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 after' );
  9960. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 after' );
  9961. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 after' );
  9962. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 after' );
  9963. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 after' );
  9964. note( 'Leaving tests_clean_cache()' ) ;
  9965. return ;
  9966. }
  9967. sub tests_clean_cache_2
  9968. {
  9969. note( 'Entering tests_clean_cache_2()' ) ;
  9970. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache_2: rmtree W/tmp/cache/G1/G2' ) ;
  9971. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache_2: mkpath W/tmp/cache/G1/G2' ) ;
  9972. my @test_files_cache = ( qw(
  9973. W/tmp/cache/G1/G2/100_200
  9974. W/tmp/cache/G1/G2/101_201
  9975. W/tmp/cache/G1/G2/120_220
  9976. W/tmp/cache/G1/G2/142_242
  9977. W/tmp/cache/G1/G2/143_243
  9978. W/tmp/cache/G1/G2/177_277
  9979. W/tmp/cache/G1/G2/177_377
  9980. W/tmp/cache/G1/G2/177_777
  9981. W/tmp/cache/G1/G2/155_255
  9982. ) ) ;
  9983. ok( touch(@test_files_cache), 'clean_cache_2: touch W/tmp/cache/G1/G2/...' ) ;
  9984. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 before' );
  9985. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 before' );
  9986. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 before' );
  9987. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 before' );
  9988. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 before' );
  9989. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 before' );
  9990. my $cache = {
  9991. 142 => 242,
  9992. 177 => 777,
  9993. } ;
  9994. my $all_1 = {
  9995. $NUMBER_100 => q{},
  9996. 142 => q{},
  9997. 177 => q{},
  9998. } ;
  9999. my $all_2 = {
  10000. 200 => q{},
  10001. 242 => q{},
  10002. 777 => q{},
  10003. } ;
  10004. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache_2: ' ) ;
  10005. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 after' );
  10006. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 after' );
  10007. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 after' );
  10008. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 after' );
  10009. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 after' );
  10010. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 after' );
  10011. note( 'Leaving tests_clean_cache_2()' ) ;
  10012. return ;
  10013. }
  10014. sub tests_mkpath
  10015. {
  10016. note( 'Entering tests_mkpath()' ) ;
  10017. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' )), 'mkpath: mkpath W/tmp/tests/' ) ;
  10018. SKIP: {
  10019. skip( 'Tests only for Unix', 10 ) if ( 'MSWin32' eq $OSNAME ) ;
  10020. my $long_path_unix = '123456789/' x 30 ;
  10021. ok( ( -d "W/tmp/tests/long/$long_path_unix" or mkpath( "W/tmp/tests/long/$long_path_unix" ) ), 'mkpath: mkpath 300 char' ) ;
  10022. ok( -d "W/tmp/tests/long/$long_path_unix", 'mkpath: mkpath > 300 char verified' ) ;
  10023. ok( ( -d "W/tmp/tests/long/$long_path_unix" and rmtree( 'W/tmp/tests/long/' ) ), 'mkpath: rmtree 300 char' ) ;
  10024. ok( ! -d "W/tmp/tests/long/$long_path_unix", 'mkpath: rmtree 300 char verified' ) ;
  10025. ok( ( -d 'W/tmp/tests/trailing_dots...' or mkpath( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: mkpath trailing_dots...' ) ;
  10026. ok( -d 'W/tmp/tests/trailing_dots...', 'mkpath: mkpath trailing_dots... verified' ) ;
  10027. ok( ( -d 'W/tmp/tests/trailing_dots...' and rmtree( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: rmtree trailing_dots...' ) ;
  10028. ok( ! -d 'W/tmp/tests/trailing_dots...', 'mkpath: rmtree trailing_dots... verified' ) ;
  10029. eval { ok( 1 / 0, 'mkpath: divide by 0' ) ; } or ok( 1, 'mkpath: can not divide by 0' ) ;
  10030. ok( 1, 'mkpath: still alive' ) ;
  10031. } ;
  10032. SKIP: {
  10033. skip( 'Tests only for MSWin32', 13 ) if ( 'MSWin32' ne $OSNAME ) ;
  10034. my $long_path_2_prefix = ".\\imapsync_tests" || '\\\?\\E:\\TEMP\\imapsync_tests' ;
  10035. myprint( "long_path_2_prefix: $long_path_2_prefix\n" ) ;
  10036. my $long_path_100 = $long_path_2_prefix . '\\' . '123456789\\' x 10 . 'END' ;
  10037. my $long_path_300 = $long_path_2_prefix . '\\' . '123456789\\' x 30 . 'END' ;
  10038. #myprint( "$long_path_100\n" ) ;
  10039. ok( ( -d $long_path_2_prefix or mkpath( $long_path_2_prefix ) ), 'mkpath: -d mkpath small path' ) ;
  10040. ok( ( -d $long_path_2_prefix ), 'mkpath: -d mkpath small path done' ) ;
  10041. ok( ( -d $long_path_100 or mkpath( $long_path_100 ) ), 'mkpath: mkpath > 100 char' ) ;
  10042. ok( ( -d $long_path_100 ), 'mkpath: -d mkpath > 200 char done' ) ;
  10043. ok( ( -d $long_path_2_prefix and rmtree( $long_path_2_prefix ) ), 'mkpath: rmtree > 100 char' ) ;
  10044. ok( (! -d $long_path_2_prefix ), 'mkpath: ! -d rmtree done' ) ;
  10045. # Without the eval the following mkpath 300 just kill the whole process without a whisper
  10046. #myprint( "$long_path_300\n" ) ;
  10047. eval { ok( ( -d $long_path_300 or mkpath( $long_path_300 ) ), 'mkpath: create a path with 300 characters' ) ; }
  10048. or ok( 1, 'mkpath: can not create a path with 300 characters' ) ;
  10049. ok( ( ( ! -d $long_path_300 ) or -d $long_path_300 and rmtree( $long_path_300 ) ), 'mkpath: rmtree the 300 character path' ) ;
  10050. ok( 1, 'mkpath: still alive' ) ;
  10051. ok( ( -d 'W/tmp/tests/trailing_dots...' or mkpath( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: mkpath trailing_dots...' ) ;
  10052. ok( -d 'W/tmp/tests/trailing_dots...', 'mkpath: mkpath trailing_dots... verified' ) ;
  10053. ok( ( -d 'W/tmp/tests/trailing_dots...' and rmtree( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: rmtree trailing_dots...' ) ;
  10054. ok( ! -d 'W/tmp/tests/trailing_dots...', 'mkpath: rmtree trailing_dots... verified' ) ;
  10055. } ;
  10056. note( 'Leaving tests_mkpath()' ) ;
  10057. # Keep this because of the eval used by the caller (failed badly?)
  10058. return 1 ;
  10059. }
  10060. sub tests_touch
  10061. {
  10062. note( 'Entering tests_touch()' ) ;
  10063. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' )), 'touch: mkpath W/tmp/tests/' ) ;
  10064. ok( 1 == touch( 'W/tmp/tests/lala'), 'touch: W/tmp/tests/lala') ;
  10065. ok( 1 == touch( 'W/tmp/tests/\y'), 'touch: W/tmp/tests/\y') ;
  10066. ok( 0 == touch( '/no/no/no/aaa'), 'touch: not /aaa') ;
  10067. ok( 1 == touch( 'W/tmp/tests/lili', 'W/tmp/tests/lolo'), 'touch: 2 files') ;
  10068. ok( 0 == touch( 'W/tmp/tests/\y', '/no/no/aaa'), 'touch: 2 files, 1 fails' ) ;
  10069. note( 'Leaving tests_touch()' ) ;
  10070. return ;
  10071. }
  10072. sub touch
  10073. {
  10074. my @files = @_ ;
  10075. my $failures = 0 ;
  10076. foreach my $file ( @files ) {
  10077. my $fh = IO::File->new ;
  10078. if ( $fh->open(">> $file" ) ) {
  10079. $fh->close ;
  10080. }else{
  10081. myprint( "Could not open file $file in write/append mode\n" ) ;
  10082. $failures++ ;
  10083. }
  10084. }
  10085. return( ! $failures );
  10086. }
  10087. sub tests_tmpdir_has_colon_bug
  10088. {
  10089. note( 'Entering tests_tmpdir_has_colon_bug()' ) ;
  10090. ok( 0 == tmpdir_has_colon_bug( q{} ), 'tmpdir_has_colon_bug: ' ) ;
  10091. ok( 0 == tmpdir_has_colon_bug( '/tmp' ), 'tmpdir_has_colon_bug: /tmp' ) ;
  10092. ok( 1 == tmpdir_has_colon_bug( 'C:' ), 'tmpdir_has_colon_bug: C:' ) ;
  10093. ok( 1 == tmpdir_has_colon_bug( 'C:\temp' ), 'tmpdir_has_colon_bug: C:\temp' ) ;
  10094. note( 'Leaving tests_tmpdir_has_colon_bug()' ) ;
  10095. return ;
  10096. }
  10097. sub tmpdir_has_colon_bug
  10098. {
  10099. my $path = shift ;
  10100. my $path_filtered = filter_forbidden_characters( $path ) ;
  10101. if ( $path_filtered ne $path ) {
  10102. ( -d $path_filtered ) and myprint( "Path $path was previously mistakely changed to $path_filtered\n" ) ;
  10103. return( 1 ) ;
  10104. }
  10105. return( 0 ) ;
  10106. }
  10107. sub tmpdir_fix_colon_bug
  10108. {
  10109. my $mysync = shift ;
  10110. my $err = 0 ;
  10111. if ( not (-d $mysync->{ tmpdir } and -r _ and -w _) ) {
  10112. myprint( "tmpdir $mysync->{ tmpdir } is not valid\n" ) ;
  10113. return( 0 ) ;
  10114. }
  10115. my $cachedir_new = "$mysync->{ tmpdir }/imapsync_cache" ;
  10116. if ( not tmpdir_has_colon_bug( $cachedir_new ) ) { return( 0 ) } ;
  10117. # check if old cache directory already exists
  10118. my $cachedir_old = filter_forbidden_characters( $cachedir_new ) ;
  10119. if ( not ( -d $cachedir_old ) ) {
  10120. myprint( "Old cache directory $cachedir_new no exists, nothing to do\n" ) ;
  10121. return( 1 ) ;
  10122. }
  10123. # check if new cache directory already exists
  10124. if ( -d $cachedir_new ) {
  10125. myprint( "New fixed cache directory $cachedir_new already exists, not moving the old one $cachedir_old. Fix this manually.\n" ) ;
  10126. return( 0 ) ;
  10127. }else{
  10128. # move the old one to the new place
  10129. myprint( "Moving $cachedir_old to $cachedir_new Do not interrupt this task.\n" ) ;
  10130. File::Copy::Recursive::rmove( $cachedir_old, $cachedir_new )
  10131. or do {
  10132. myprint( "Could not move $cachedir_old to $cachedir_new\n" ) ;
  10133. $err++ ;
  10134. } ;
  10135. # check it succeeded
  10136. if ( -d $cachedir_new and -r _ and -w _ ) {
  10137. myprint( "New fixed cache directory $cachedir_new ok\n" ) ;
  10138. }else{
  10139. myprint( "New fixed cache directory $cachedir_new does not exist\n" ) ;
  10140. $err++ ;
  10141. }
  10142. if ( -d $cachedir_old ) {
  10143. myprint( "Old cache directory $cachedir_old still exists\n" ) ;
  10144. $err++ ;
  10145. }else{
  10146. myprint( "Old cache directory $cachedir_old successfully moved\n" ) ;
  10147. }
  10148. }
  10149. return( not $err ) ;
  10150. }
  10151. sub tests_cache_folder
  10152. {
  10153. note( 'Entering tests_cache_folder()' ) ;
  10154. ok( '/path/fold1/fold2' eq cache_folder( q{}, '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  10155. ok( '/pa_th/fold1/fold2' eq cache_folder( q{}, '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  10156. 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' ) ;
  10157. ok( 'D:/path/fold1/fold2' eq cache_folder( 'D:', '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  10158. ok( 'D:/pa_th/fold1/fold2' eq cache_folder( 'D:', '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  10159. 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' ) ;
  10160. ok( '//' eq cache_folder( q{}, q{}, q{}, q{}), 'cache_folder: -> //' ) ;
  10161. ok( '//_______' eq cache_folder( q{}, q{}, q{}, '*|?:"<>'), 'cache_folder: *|?:"<> -> //_______' ) ;
  10162. note( 'Leaving tests_cache_folder()' ) ;
  10163. return ;
  10164. }
  10165. sub cache_folder
  10166. {
  10167. my( $cache_base, $cache_dir, $h1_fold, $h2_fold ) = @_ ;
  10168. my $sep_1 = $sync->{ h1_sep } || '/';
  10169. my $sep_2 = $sync->{ h2_sep } || '/';
  10170. #myprint( "$cache_dir h1_fold $h1_fold sep1 $sep_1 h2_fold $h2_fold sep2 $sep_2\n" ) ;
  10171. $h1_fold = convert_sep_to_slash( $h1_fold, $sep_1 ) ;
  10172. $h2_fold = convert_sep_to_slash( $h2_fold, $sep_2 ) ;
  10173. my $cache_folder = "$cache_base" . filter_forbidden_characters( "$cache_dir/$h1_fold/$h2_fold" ) ;
  10174. #myprint( "cache_folder [$cache_folder]\n" ) ;
  10175. return( $cache_folder ) ;
  10176. }
  10177. sub tests_filter_forbidden_characters
  10178. {
  10179. note( 'Entering tests_filter_forbidden_characters()' ) ;
  10180. is( undef , filter_forbidden_characters( ), 'filter_forbidden_characters: no args -> undef' ) ;
  10181. is( 'a_b' , filter_forbidden_characters( 'a_b' ), 'filter_forbidden_characters: a_b -> a_b' ) ;
  10182. is( 'a_b' , filter_forbidden_characters( 'a*b' ), 'filter_forbidden_characters: a*b -> a_b' ) ;
  10183. is( 'a_b' , filter_forbidden_characters( 'a|b' ), 'filter_forbidden_characters: a|b -> a_b' ) ;
  10184. is( 'a_b' , filter_forbidden_characters( 'a?b' ), 'filter_forbidden_characters: a?b -> a_b' ) ;
  10185. is( 'a________b', filter_forbidden_characters( q{a*|?:"<>'b} ), q{filter_forbidden_characters: a*|?:"<>'b -> a________b} ) ;
  10186. is( 'a_b_' , filter_forbidden_characters( 'a b ' ), 'filter_forbidden_characters: "a b " -> "a_b_"' ) ;
  10187. is( 'a_b' , filter_forbidden_characters( "a\tb" ), 'filter_forbidden_characters: a\tb -> a_b' ) ;
  10188. is( "a_b" , filter_forbidden_characters( "a\rb" ), 'filter_forbidden_characters: a\rb -> a_b' ) ;
  10189. is( "a_b" , filter_forbidden_characters( "a\nb" ), 'filter_forbidden_characters: a\nb -> a_b' ) ;
  10190. is( "a_b" , filter_forbidden_characters( "a\\b" ), 'filter_forbidden_characters: a\b -> a_b' ) ;
  10191. is( 'a-b' , filter_forbidden_characters( 'a-b' ), 'filter_forbidden_characters: a-b -> a-b' ) ;
  10192. is( 'a__-__-__-__-__b' , filter_forbidden_characters( 'aé-è-à -ç-Öb' ), 'filter_forbidden_characters: aé-è-à -ç-Öb -> a__-__-__-__-__b' ) ;
  10193. is( 'abcdABCDwxyzWXYZ012789' , filter_forbidden_characters( 'abcdABCDwxyzWXYZ012789' ),
  10194. 'filter_forbidden_characters: abcdABCDwxyzWXYZ012789 -> abcdABCDwxyzWXYZ012789' ) ;
  10195. note( 'Leaving tests_filter_forbidden_characters()' ) ;
  10196. return ;
  10197. }
  10198. sub filter_forbidden_characters
  10199. {
  10200. my $string = shift ;
  10201. if ( ! defined $string ) { return ; }
  10202. $string =~ s{[\Q*|?:"<>' \E\t\r\n\\]}{_}xg ;
  10203. # replace all non-ascii and control characters by _
  10204. $string =~ s/[[:^ascii:][:cntrl:]]/_/xg ;
  10205. #myprint( "[$string]\n" ) ;
  10206. return( $string ) ;
  10207. }
  10208. sub tests_convert_sep_to_slash
  10209. {
  10210. note( 'Entering tests_convert_sep_to_slash()' ) ;
  10211. ok(q{} eq convert_sep_to_slash(q{}, '/'), 'convert_sep_to_slash: no folder');
  10212. ok('INBOX' eq convert_sep_to_slash('INBOX', '/'), 'convert_sep_to_slash: INBOX');
  10213. ok('INBOX/foo' eq convert_sep_to_slash('INBOX/foo', '/'), 'convert_sep_to_slash: INBOX/foo');
  10214. ok('INBOX/foo' eq convert_sep_to_slash('INBOX_foo', '_'), 'convert_sep_to_slash: INBOX_foo');
  10215. ok('INBOX/foo/zob' eq convert_sep_to_slash('INBOX_foo_zob', '_'), 'convert_sep_to_slash: INBOX_foo_zob');
  10216. ok('INBOX/foo' eq convert_sep_to_slash('INBOX.foo', '.'), 'convert_sep_to_slash: INBOX.foo');
  10217. ok('INBOX/foo/hi' eq convert_sep_to_slash('INBOX.foo.hi', '.'), 'convert_sep_to_slash: INBOX.foo.hi');
  10218. note( 'Leaving tests_convert_sep_to_slash()' ) ;
  10219. return ;
  10220. }
  10221. sub convert_sep_to_slash
  10222. {
  10223. my ( $folder, $sep ) = @_ ;
  10224. $folder =~ s{\Q$sep\E}{/}xg ;
  10225. return( $folder ) ;
  10226. }
  10227. sub tests_regexmess
  10228. {
  10229. note( 'Entering tests_regexmess()' ) ;
  10230. ok( 'blabla' eq regexmess( 'blabla' ), 'regexmess: no regexmess, nothing to do' ) ;
  10231. @regexmess = ( 'lalala' ) ;
  10232. ok( not( defined regexmess( 'popopo' ) ), 'regexmess: bad regex lalala' ) ;
  10233. @regexmess = ( 's/p/Z/g' ) ;
  10234. ok( 'ZoZoZo' eq regexmess( 'popopo' ), 'regexmess: s/p/Z/g' ) ;
  10235. @regexmess = ( 's{c}{C}gxms' ) ;
  10236. ok("H1: abC\nH2: Cde\n\nBody abC"
  10237. eq regexmess( "H1: abc\nH2: cde\n\nBody abc"),
  10238. 'regexmess: c->C');
  10239. @regexmess = ( 's{\AFrom\ }{From:}gxms' ) ;
  10240. ok( q{}
  10241. eq regexmess(q{}),
  10242. 'regexmess: From mbox 1 add colon blank');
  10243. ok( 'From:<tartanpion@machin.truc>'
  10244. eq regexmess('From <tartanpion@machin.truc>'),
  10245. 'regexmess: From mbox 2 add colo');
  10246. ok( "\n" . 'From <tartanpion@machin.truc>'
  10247. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  10248. 'regexmess: From mbox 3 add colo') ;
  10249. ok( "From: zzz\n" . 'From <tartanpion@machin.truc>'
  10250. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  10251. 'regexmess: From mbox 4 add colo') ;
  10252. @regexmess = ( 's{\AFrom\ [^\n]*(\n)?}{}gxms' ) ;
  10253. ok( q{}
  10254. eq regexmess(q{}),
  10255. 'regexmess: From mbox 1 remove, blank');
  10256. ok( q{}
  10257. eq regexmess('From <tartanpion@machin.truc>'),
  10258. 'regexmess: From mbox 2 remove');
  10259. ok( "\n" . 'From <tartanpion@machin.truc>'
  10260. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  10261. 'regexmess: From mbox 3 remove');
  10262. #myprint( "[", regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'), "]" ) ;
  10263. ok( q{} . 'From <tartanpion@machin.truc>'
  10264. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  10265. 'regexmess: From mbox 4 remove');
  10266. is(
  10267. <<'EOM'
  10268. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10269. From:<tartanpion@machin.truc>
  10270. Hello,
  10271. Bye.
  10272. EOM
  10273. , regexmess(
  10274. <<'EOM'
  10275. From zzz
  10276. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10277. From:<tartanpion@machin.truc>
  10278. Hello,
  10279. Bye.
  10280. EOM
  10281. ), 'regexmess: From mbox 5 remove');
  10282. @regexmess = ( 's{\A((?:[^\n]+\n)+|)^Disposition-Notification-To:[^\n]*\n(\r?\n|.*\n\r?\n)}{$1$2}xms' ) ; # SUPER SUPER BEST!
  10283. ok(
  10284. <<'EOM'
  10285. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10286. From:<tartanpion@machin.truc>
  10287. Hello,
  10288. Bye.
  10289. EOM
  10290. eq regexmess(
  10291. <<'EOM'
  10292. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10293. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10294. From:<tartanpion@machin.truc>
  10295. Hello,
  10296. Bye.
  10297. EOM
  10298. ),
  10299. 'regexmess: 1 Delete header Disposition-Notification-To:');
  10300. ok(
  10301. <<'EOM'
  10302. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10303. From:<tartanpion@machin.truc>
  10304. Hello,
  10305. Bye.
  10306. EOM
  10307. eq regexmess(
  10308. <<'EOM'
  10309. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10310. From:<tartanpion@machin.truc>
  10311. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10312. Hello,
  10313. Bye.
  10314. EOM
  10315. ),
  10316. 'regexmess: 2 Delete header Disposition-Notification-To:');
  10317. ok(
  10318. <<'EOM'
  10319. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10320. From:<tartanpion@machin.truc>
  10321. Hello,
  10322. Bye.
  10323. EOM
  10324. eq regexmess(
  10325. <<'EOM'
  10326. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10327. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10328. From:<tartanpion@machin.truc>
  10329. Hello,
  10330. Bye.
  10331. EOM
  10332. ),
  10333. 'regexmess: 3 Delete header Disposition-Notification-To:');
  10334. ok(
  10335. <<'EOM'
  10336. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10337. From:<tartanpion@machin.truc>
  10338. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10339. Bye.
  10340. EOM
  10341. eq regexmess(
  10342. <<'EOM'
  10343. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10344. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10345. From:<tartanpion@machin.truc>
  10346. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10347. Bye.
  10348. EOM
  10349. ),
  10350. 'regexmess: 4 Delete header Disposition-Notification-To:');
  10351. ok(
  10352. <<'EOM'
  10353. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10354. From:<tartanpion@machin.truc>
  10355. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10356. Bye.
  10357. EOM
  10358. eq regexmess(
  10359. <<'EOM'
  10360. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10361. From:<tartanpion@machin.truc>
  10362. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10363. Bye.
  10364. EOM
  10365. ),
  10366. 'regexmess: 5 Delete header Disposition-Notification-To:');
  10367. ok(
  10368. <<'EOM'
  10369. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10370. From:<tartanpion@machin.truc>
  10371. Hello,
  10372. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10373. Bye.
  10374. EOM
  10375. eq regexmess(
  10376. <<'EOM'
  10377. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10378. From:<tartanpion@machin.truc>
  10379. Hello,
  10380. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10381. Bye.
  10382. EOM
  10383. ),
  10384. 'regexmess: 6 Delete header Disposition-Notification-To:');
  10385. ok(
  10386. <<'EOM'
  10387. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10388. From:<tartanpion@machin.truc>
  10389. Hello,
  10390. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10391. Bye.
  10392. EOM
  10393. eq regexmess(
  10394. <<'EOM'
  10395. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10396. From:<tartanpion@machin.truc>
  10397. Hello,
  10398. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10399. Bye.
  10400. EOM
  10401. ),
  10402. 'regexmess: 7 Delete header Disposition-Notification-To:');
  10403. ok(
  10404. <<'EOM'
  10405. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10406. From:<tartanpion@machin.truc>
  10407. Hello,
  10408. Bye.
  10409. EOM
  10410. eq regexmess(
  10411. <<'EOM'
  10412. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10413. From:<tartanpion@machin.truc>
  10414. Hello,
  10415. Bye.
  10416. EOM
  10417. ),
  10418. 'regexmess: 8 Delete header Disposition-Notification-To:');
  10419. ok(
  10420. <<'EOM'
  10421. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10422. From:<tartanpion@machin.truc>
  10423. Hello,
  10424. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10425. Bye.
  10426. EOM
  10427. eq regexmess(
  10428. <<'EOM'
  10429. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10430. From:<tartanpion@machin.truc>
  10431. Hello,
  10432. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10433. Bye.
  10434. EOM
  10435. ),
  10436. 'regexmess: 9 Delete header Disposition-Notification-To:');
  10437. ok(
  10438. <<'EOM'
  10439. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10440. From:<tartanpion@machin.truc>
  10441. Hello,
  10442. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10443. Bye.
  10444. EOM
  10445. eq regexmess(
  10446. <<'EOM'
  10447. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10448. From:<tartanpion@machin.truc>
  10449. Hello,
  10450. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10451. Bye.
  10452. EOM
  10453. ),
  10454. 'regexmess: 10 Delete header Disposition-Notification-To:');
  10455. ok(
  10456. <<'EOM'
  10457. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10458. From:<tartanpion@machin.truc>
  10459. Hello,
  10460. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10461. Bye.
  10462. EOM
  10463. eq regexmess(
  10464. <<'EOM'
  10465. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10466. From:<tartanpion@machin.truc>
  10467. Hello,
  10468. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10469. Bye.
  10470. EOM
  10471. ),
  10472. 'regexmess: 11 Delete header Disposition-Notification-To:');
  10473. ok(
  10474. <<'EOM'
  10475. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10476. From:<tartanpion@machin.truc>
  10477. Hello,
  10478. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10479. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10480. Bye.
  10481. EOM
  10482. eq regexmess(
  10483. <<'EOM'
  10484. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10485. From:<tartanpion@machin.truc>
  10486. Hello,
  10487. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10488. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10489. Bye.
  10490. EOM
  10491. ),
  10492. 'regexmess: 12 Delete header Disposition-Notification-To:');
  10493. @regexmess = ( 's{\A(.*?(?! ^$))^Disposition-Notification-To:(.*?)$}{$1X-Disposition-Notification-To:$2}igxms' ) ; # BAD!
  10494. @regexmess = ( 's{\A((?:[^\n]+\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims' ) ;
  10495. ok(
  10496. <<'EOM'
  10497. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10498. From:<tartanpion@machin.truc>
  10499. Hello,
  10500. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10501. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10502. Bye.
  10503. EOM
  10504. eq regexmess(
  10505. <<'EOM'
  10506. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10507. From:<tartanpion@machin.truc>
  10508. Hello,
  10509. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10510. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10511. Bye.
  10512. EOM
  10513. ),
  10514. 'regexmess: 13 Delete header Disposition-Notification-To:');
  10515. ok(
  10516. <<'EOM'
  10517. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10518. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10519. From:<tartanpion@machin.truc>
  10520. Hello,
  10521. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10522. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10523. Bye.
  10524. EOM
  10525. eq regexmess(
  10526. <<'EOM'
  10527. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10528. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10529. From:<tartanpion@machin.truc>
  10530. Hello,
  10531. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10532. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10533. Bye.
  10534. EOM
  10535. ),
  10536. 'regexmess: 14 Delete header Disposition-Notification-To:');
  10537. ok(
  10538. <<'EOM'
  10539. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10540. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10541. From:<tartanpion@machin.truc>
  10542. Hello,
  10543. Bye.
  10544. EOM
  10545. eq regexmess(
  10546. <<'EOM'
  10547. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10548. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10549. From:<tartanpion@machin.truc>
  10550. Hello,
  10551. Bye.
  10552. EOM
  10553. ),
  10554. 'regexmess: 15 Delete header Disposition-Notification-To:');
  10555. ok(
  10556. <<'EOM'
  10557. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10558. From:<tartanpion@machin.truc>
  10559. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10560. Hello,
  10561. Bye.
  10562. EOM
  10563. eq regexmess(
  10564. <<'EOM'
  10565. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10566. From:<tartanpion@machin.truc>
  10567. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10568. Hello,
  10569. Bye.
  10570. EOM
  10571. ),
  10572. 'regexmess: 16 Delete header Disposition-Notification-To:');
  10573. ok(
  10574. <<'EOM'
  10575. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10576. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10577. From:<tartanpion@machin.truc>
  10578. Hello,
  10579. Bye.
  10580. EOM
  10581. eq regexmess(
  10582. <<'EOM'
  10583. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10584. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10585. From:<tartanpion@machin.truc>
  10586. Hello,
  10587. Bye.
  10588. EOM
  10589. ),
  10590. 'regexmess: 17 Delete header Disposition-Notification-To:');
  10591. @regexmess = ( 's/.{11}\K.*//gs' ) ;
  10592. is( "0123456789\n", regexmess( "0123456789\n" x 100 ), 'regexmess: truncate whole message after 11 characters' ) ;
  10593. is( "0123456789\n", regexmess( "0123456789\n" x 100_000 ), 'regexmess: truncate whole message after 11 characters ~ 1MB' ) ;
  10594. @regexmess = ( 's/.{10000}\K.*//gs' ) ;
  10595. is( "123456789\n" x 1000, regexmess( "123456789\n" x 100_000 ), 'regexmess: truncate whole message after 10000 characters ~ 1MB' ) ;
  10596. @regexmess = ( 's/^(X-Ham-Report.*?\n)^X-/X-/sm' ) ;
  10597. is(
  10598. <<'EOM'
  10599. X-Spam-Score: -1
  10600. X-Spam-Bar: /
  10601. X-Spam-Flag: NO
  10602. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10603. From:<tartanpion@machin.truc>
  10604. Hello,
  10605. Bye.
  10606. EOM
  10607. ,
  10608. regexmess(
  10609. <<'EOM'
  10610. X-Spam-Score: -1
  10611. X-Spam-Bar: /
  10612. X-Ham-Report: =?utf-8?Q?Spam_detection_software=2C_running?=
  10613. =?utf-8?Q?_on_the_system_=22ohp-ag006.int200?=
  10614. _has_NOT_identified_thi?=
  10615. =?utf-8?Q?s_incoming_email_as_spam.__The_o?=
  10616. _message_has_been_attac?=
  10617. =?utf-8?Q?hed_to_this_so_you_can_view_it_o?=
  10618. ___________________________?=
  10619. =?utf-8?Q?__author's_domain
  10620. X-Spam-Flag: NO
  10621. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10622. From:<tartanpion@machin.truc>
  10623. Hello,
  10624. Bye.
  10625. EOM
  10626. ),
  10627. 'regexmess: Delete header X-Ham-Report:');
  10628. # regex to play with Date: from the FAQ
  10629. #@regexmess = 's{\A(.*?(?! ^$))^Date:(.*?)$}{$1Date:$2\nX-Date:$2}gxms'
  10630. # Change 8bit characters in whole email to X characters
  10631. @regexmess = ( 's{[\x80-\xff]}{X}gxms' ) ;
  10632. is( 'X-8bit: kaka 1 XX kiki', regexmess('X-8bit: kaka 1 ¤ kiki'), 'regexmess: 1 Change 8bit characters in whole email to X characters');
  10633. # Same change but using tr
  10634. @regexmess = ( 'tr [\x80-\xff] [X]' ) ;
  10635. is( 'X-8bit: kaka 1 XXXX kiki', regexmess('X-8bit: kaka 1 ¤£ kiki'), 'regexmess: 2 Change 8bit characters in whole email to X characters, using tr');
  10636. # Add a final \r\n if missing
  10637. @regexmess = ( 's{(?<![\n])\z}{\r\n}gxms' ) ;
  10638. is( "\r\n", regexmess(""), 'regexmess: 1. Add a final \r\n if missing. Missing' ) ;
  10639. is( "abc\r\n", regexmess("abc"), 'regexmess: 2. Add a final \r\n if missing. Missing' ) ;
  10640. is( "abc\ndef\r\n", regexmess("abc\ndef"), 'regexmess: 3. Add a final \r\n if missing. Missing' ) ;
  10641. is( "abc\r\ndef\r\n", regexmess("abc\r\ndef"), 'regexmess: 3. Add a final \r\n if missing. Missing' ) ;
  10642. is( "\r\n", regexmess("\r\n"), 'regexmess: 3. Add a final \r\n if missing. Not missing' ) ;
  10643. is( "abc\n", regexmess("abc\n"), 'regexmess: 4. Add a final \r\n if missing. Not missing' ) ;
  10644. is( "abc\r\n", regexmess("abc\r\n"), 'regexmess: 4. Add a final \r\n if missing. Not missing' ) ;
  10645. is( "abc\ndef\n", regexmess("abc\ndef\n"), 'regexmess: 4. Add a final \r\n if missing. Not missing' ) ;
  10646. is( "abc\r\ndef\r\n", regexmess("abc\r\ndef\r\n"), 'regexmess: 4. Add a final \r\n if missing. Not missing' ) ;
  10647. # Remove the fucking buggy X-Spam-Report: a bad header on several lines that can even begin without a space!
  10648. @regexmess = ( 's{X-Spam-Report:.*?\n(^[^\n]+:|^\r?\n)}{$1}xms' ) ;
  10649. # Damien regexes:
  10650. #@regexmess = ( 's{X-Spam-Report:.*?\n(^[a-zA-Z0-9\-]+:)}{$1}xms' ) ;
  10651. #@regexmess = ( 's{X-Spam-Report:.*?\n(^[a-zA-Z0-9\-]+:|^\r?\n)}{$1}xms' ) ;
  10652. is(
  10653. <<'EOM'
  10654. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10655. From:<tartanpion@machin.truc>
  10656. LaSuite: super
  10657. Hello,
  10658. Bye.
  10659. EOM
  10660. , regexmess(
  10661. <<'EOM'
  10662. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10663. From:<tartanpion@machin.truc>
  10664. X-Spam-Report: caca
  10665. caca
  10666. caca
  10667. caca
  10668. LaSuite: super
  10669. Hello,
  10670. Bye.
  10671. EOM
  10672. ), 'regexmess: 1 remove buggy X-Spam-Report: across several lines, not the final header');
  10673. is(
  10674. <<'EOM'
  10675. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10676. From:<tartanpion@machin.truc>
  10677. LaSuite: super
  10678. LaSuite2: super 2
  10679. Hello,
  10680. Bye.
  10681. EOM
  10682. , regexmess(
  10683. <<'EOM'
  10684. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10685. From:<tartanpion@machin.truc>
  10686. X-Spam-Report: caca
  10687. caca
  10688. caca
  10689. caca
  10690. LaSuite: super
  10691. LaSuite2: super 2
  10692. Hello,
  10693. Bye.
  10694. EOM
  10695. ), 'regexmess: 2 remove buggy X-Spam-Report: across several lines, not the final header');
  10696. is(
  10697. <<'EOM'
  10698. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10699. From:<tartanpion@machin.truc>
  10700. LaSuite: super
  10701. LaSuite2: super 2
  10702. Hello,
  10703. Bye.
  10704. EOM
  10705. , regexmess(
  10706. <<'EOM'
  10707. X-Spam-Report: caca
  10708. caca
  10709. caca
  10710. caca
  10711. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10712. From:<tartanpion@machin.truc>
  10713. LaSuite: super
  10714. LaSuite2: super 2
  10715. Hello,
  10716. Bye.
  10717. EOM
  10718. ), 'regexmess: 3 remove buggy X-Spam-Report: across several lines, first header');
  10719. is(
  10720. <<'EOM'
  10721. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10722. From:<tartanpion@machin.truc>
  10723. Hello,
  10724. Bye.
  10725. EOM
  10726. , regexmess(
  10727. <<'EOM'
  10728. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10729. From:<tartanpion@machin.truc>
  10730. X-Spam-Report: caca
  10731. caca
  10732. caca
  10733. caca
  10734. Hello,
  10735. Bye.
  10736. EOM
  10737. ), 'regexmess: 4 remove buggy X-Spam-Report: across several lines, final header');
  10738. is(
  10739. <<'EOM'
  10740. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10741. From:<tartanpion@machin.truc>
  10742. Hello,
  10743. Bye.
  10744. EOM
  10745. , regexmess(
  10746. <<'EOM'
  10747. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10748. From:<tartanpion@machin.truc>
  10749. Hello,
  10750. Bye.
  10751. EOM
  10752. ), 'regexmess: 5 remove buggy X-Spam-Report: not there at all');
  10753. is(
  10754. <<"EOM"
  10755. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  10756. From:<tartanpion>\r
  10757. LaSuite: super\r
  10758. LaSuite2: super 2\r
  10759. \r
  10760. Hello,\r
  10761. Bye.\r
  10762. EOM
  10763. , regexmess(
  10764. <<"EOM"
  10765. X-Spam-Report: caca\r
  10766. caca\r
  10767. caca\r
  10768. caca\r
  10769. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  10770. From:<tartanpion>\r
  10771. LaSuite: super\r
  10772. LaSuite2: super 2\r
  10773. \r
  10774. Hello,\r
  10775. Bye.\r
  10776. EOM
  10777. ), 'regexmess: 6 remove buggy X-Spam-Report: across several lines, first header, with \r');
  10778. is(
  10779. <<"EOM"
  10780. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  10781. From:<tartanpion>\r
  10782. LaSuite: super\r
  10783. LaSuite2: super 2\r
  10784. \r
  10785. Hello,\r
  10786. Bye.\r
  10787. EOM
  10788. , regexmess(
  10789. <<"EOM"
  10790. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  10791. From:<tartanpion>\r
  10792. X-Spam-Report: caca\r
  10793. caca\r
  10794. caca\r
  10795. caca\r
  10796. LaSuite: super\r
  10797. LaSuite2: super 2\r
  10798. \r
  10799. Hello,\r
  10800. Bye.\r
  10801. EOM
  10802. ), 'regexmess: 7 remove buggy X-Spam-Report: across several lines, middle header, with \r');
  10803. is(
  10804. <<"EOM"
  10805. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  10806. From:<tartanpion>\r
  10807. \r
  10808. Hello,\r
  10809. Bye.\r
  10810. EOM
  10811. , regexmess(
  10812. <<"EOM"
  10813. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  10814. From:<tartanpion>\r
  10815. X-Spam-Report: caca\r
  10816. caca\r
  10817. caca\r
  10818. caca\r
  10819. \r
  10820. Hello,\r
  10821. Bye.\r
  10822. EOM
  10823. ), 'regexmess: 8 remove buggy X-Spam-Report: across several lines, final header, with \r');
  10824. undef @regexmess ;
  10825. note( 'Leaving tests_regexmess()' ) ;
  10826. return ;
  10827. }
  10828. sub regexmess
  10829. {
  10830. my ( $string ) = @_ ;
  10831. foreach my $regexmess ( @regexmess ) {
  10832. $sync->{ debug } and myprint( "eval \$string =~ $regexmess\n" ) ;
  10833. my $ret = eval "\$string =~ $regexmess ; 1" ;
  10834. #myprint( "eval [$ret]\n" ) ;
  10835. if ( ( not $ret ) or $EVAL_ERROR ) {
  10836. myprint( "Error: eval regexmess '$regexmess': $EVAL_ERROR" ) ;
  10837. return( undef ) ;
  10838. }
  10839. }
  10840. $sync->{ debug } and myprint( "$string\n" ) ;
  10841. return( $string ) ;
  10842. }
  10843. sub tests_skipmess
  10844. {
  10845. note( 'Entering tests_skipmess()' ) ;
  10846. ok( not( defined skipmess( 'blabla' ) ), 'skipmess, no skipmess, no skip' ) ;
  10847. @skipmess = ('[') ;
  10848. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex [' ) ;
  10849. @skipmess = ('lalala') ;
  10850. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex lalala' ) ;
  10851. @skipmess = ('/popopo/') ;
  10852. ok( 1 == skipmess( 'popopo' ), 'skipmess, popopo match regex /popopo/' ) ;
  10853. @skipmess = ('/popopo/') ;
  10854. ok( 0 == skipmess( 'rrrrrr' ), 'skipmess, rrrrrr does not match regex /popopo/' ) ;
  10855. @skipmess = ('m{^$}') ;
  10856. ok( 1 == skipmess( q{} ), 'skipmess: empty string yes' ) ;
  10857. ok( 0 == skipmess( 'Hi!' ), 'skipmess: empty string no' ) ;
  10858. @skipmess = ('m{i}') ;
  10859. ok( 1 == skipmess( 'Hi!' ), 'skipmess: i string yes' ) ;
  10860. ok( 0 == skipmess( 'Bye!' ), 'skipmess: i string no' ) ;
  10861. @skipmess = ('m{[\x80-\xff]}') ;
  10862. ok( 0 == skipmess( 'Hi!' ), 'skipmess: i 8bit no' ) ;
  10863. ok( 1 == skipmess( "\xff" ), 'skipmess: \xff 8bit yes' ) ;
  10864. @skipmess = ('m{A}', 'm{B}') ;
  10865. ok( 0 == skipmess( 'Hi!' ), 'skipmess: A or B no' ) ;
  10866. ok( 0 == skipmess( 'lala' ), 'skipmess: A or B no' ) ;
  10867. ok( 0 == skipmess( "\xff" ), 'skipmess: A or B no' ) ;
  10868. ok( 1 == skipmess( 'AB' ), 'skipmess: A or B yes' ) ;
  10869. ok( 1 == skipmess( 'BA' ), 'skipmess: A or B yes' ) ;
  10870. ok( 1 == skipmess( 'AA' ), 'skipmess: A or B yes' ) ;
  10871. ok( 1 == skipmess( 'Ok Bye' ), 'skipmess: A or B yes' ) ;
  10872. @skipmess = ( 'm#\A((?:[^\n]+\n)+|)^Content-Type: Message/Partial;[^\n]*\n(?:\n|.*\n\n)#ism' ) ; # SUPER BEST!
  10873. ok( 1 == skipmess(
  10874. <<'EOM'
  10875. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10876. Content-Type: Message/Partial; blabla
  10877. From:<tartanpion@machin.truc>
  10878. Hello!
  10879. Bye.
  10880. EOM
  10881. ),
  10882. 'skipmess: 1 match Content-Type: Message/Partial' ) ;
  10883. ok( 0 == skipmess(
  10884. <<'EOM'
  10885. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10886. From:<tartanpion@machin.truc>
  10887. Hello!
  10888. Bye.
  10889. EOM
  10890. ),
  10891. 'skipmess: 2 not match Content-Type: Message/Partial' ) ;
  10892. ok( 1 == skipmess(
  10893. <<'EOM'
  10894. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10895. From:<tartanpion@machin.truc>
  10896. Content-Type: Message/Partial; blabla
  10897. Hello!
  10898. Bye.
  10899. EOM
  10900. ),
  10901. 'skipmess: 3 match Content-Type: Message/Partial' ) ;
  10902. ok( 0 == skipmess(
  10903. <<'EOM'
  10904. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10905. From:<tartanpion@machin.truc>
  10906. Hello!
  10907. Content-Type: Message/Partial; blabla
  10908. Bye.
  10909. EOM
  10910. ),
  10911. 'skipmess: 4 not match Content-Type: Message/Partial' ) ;
  10912. ok( 0 == skipmess(
  10913. <<'EOM'
  10914. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10915. From:<tartanpion@machin.truc>
  10916. Hello!
  10917. Content-Type: Message/Partial; blabla
  10918. Bye.
  10919. EOM
  10920. ),
  10921. 'skipmess: 5 not match Content-Type: Message/Partial' ) ;
  10922. ok( 1 == skipmess(
  10923. <<'EOM'
  10924. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10925. Content-Type: Message/Partial; blabla
  10926. From:<tartanpion@machin.truc>
  10927. Hello!
  10928. Content-Type: Message/Partial; blabla
  10929. Bye.
  10930. EOM
  10931. ),
  10932. 'skipmess: 6 match Content-Type: Message/Partial' ) ;
  10933. ok( 1 == skipmess(
  10934. <<'EOM'
  10935. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10936. Content-Type: Message/Partial;
  10937. From:<tartanpion@machin.truc>
  10938. Hello!
  10939. Bye.
  10940. EOM
  10941. ),
  10942. 'skipmess: 7 match Content-Type: Message/Partial' ) ;
  10943. ok( 1 == skipmess(
  10944. <<'EOM'
  10945. Date: Wed, 2 Jul 2014 02:26:40 +0000
  10946. MIME-Version: 1.0
  10947. Content-Type: message/partial;
  10948. id="TAN_U_P<1404267997.00007489ed17>";
  10949. number=3;
  10950. total=3
  10951. 6HQ6Hh3CdXj77qEGixerQ6zHx0OnQ/Cf5On4W0Y6vtU2crABZQtD46Hx1EOh8dDz4+OnTr1G
  10952. Hello!
  10953. Bye.
  10954. EOM
  10955. ),
  10956. 'skipmess: 8 match Content-Type: Message/Partial' ) ;
  10957. ok( 1 == skipmess(
  10958. <<'EOM'
  10959. Return-Path: <gilles@lamiral.info>
  10960. Received: by lamiral.info (Postfix, from userid 1000)
  10961. id 21EB12443BF; Mon, 2 Mar 2015 15:38:35 +0100 (CET)
  10962. Subject: test: aethaecohngiexao
  10963. To: <tata@petite.lamiral.info>
  10964. X-Mailer: mail (GNU Mailutils 2.2)
  10965. Message-Id: <20150302143835.21EB12443BF@lamiral.info>
  10966. Content-Type: message/partial;
  10967. id="TAN_U_P<1404267997.00007489ed17>";
  10968. number=3;
  10969. total=3
  10970. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  10971. From: gilles@lamiral.info (Gilles LAMIRAL)
  10972. test: aethaecohngiexao
  10973. EOM
  10974. ),
  10975. 'skipmess: 9 match Content-Type: Message/Partial' ) ;
  10976. ok( 1 == skipmess(
  10977. <<'EOM'
  10978. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  10979. From: gilles@lamiral.info (Gilles LAMIRAL)
  10980. Content-Type: message/partial;
  10981. id="TAN_U_P<1404267997.00007489ed17>";
  10982. number=3;
  10983. total=3
  10984. test: aethaecohngiexao
  10985. EOM
  10986. . "lalala\n" x 3_000_000
  10987. ),
  10988. 'skipmess: 10 match Content-Type: Message/Partial' ) ;
  10989. ok( 0 == skipmess(
  10990. <<'EOM'
  10991. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  10992. From: gilles@lamiral.info (Gilles LAMIRAL)
  10993. test: aethaecohngiexao
  10994. EOM
  10995. . "lalala\n" x 3_000_000
  10996. ),
  10997. 'skipmess: 11 match Content-Type: Message/Partial' ) ;
  10998. ok( 0 == skipmess(
  10999. <<"EOM"
  11000. From: fff\r
  11001. To: fff\r
  11002. Subject: Testing imapsync --skipmess\r
  11003. Date: Mon, 22 Aug 2011 08:40:20 +0800\r
  11004. Mime-Version: 1.0\r
  11005. Content-Type: text/plain; charset=iso-8859-1\r
  11006. Content-Transfer-Encoding: 7bit\r
  11007. \r
  11008. EOM
  11009. . qq{!#"d%&'()*+,-./0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg\r\n } x 32_730
  11010. ),
  11011. 'skipmess: 12 not match Content-Type: Message/Partial' ) ;
  11012. # Complex regular subexpression recursion limit (32766) exceeded with more lines
  11013. # exit;
  11014. undef @skipmess ;
  11015. note( 'Leaving tests_skipmess()' ) ;
  11016. return ;
  11017. }
  11018. sub tests_skipmess_neg
  11019. {
  11020. note( 'Entering tests_skipmess_neg()' ) ;
  11021. @skipmess = ('m{i}') ;
  11022. ok( 1 == skipmess( 'Hi!' ), 'skipmess: i string yes' ) ;
  11023. ok( 0 == skipmess( 'Ho!' ), 'skipmess: i string no' ) ;
  11024. @skipmess = ('m{\A(?!.*i)}') ;
  11025. ok( 0 == skipmess( 'Hi!' ), 'skipmess: not i string no' ) ;
  11026. ok( 1 == skipmess( 'Ho!' ), 'skipmess: not i string yes' ) ;
  11027. @skipmess = ('m{\A(?!.*^From:[^\n]*tartanpion\@machin\.truc)}xms') ;
  11028. ok( 0 == skipmess(
  11029. <<'EOM'
  11030. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11031. From: <tartanpion@machin.truc>
  11032. Bye.
  11033. EOM
  11034. ),
  11035. 'skipmess: 1 not From tartanpion@machin.truc' ) ;
  11036. ok( 1 == skipmess(
  11037. <<'EOM'
  11038. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11039. From: <kikiki@machin.truc>
  11040. Bye.
  11041. EOM
  11042. ),
  11043. 'skipmess: 2 not From tartanpion@machin.truc' ) ;
  11044. ok( 0 == skipmess(
  11045. <<'EOM'
  11046. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11047. From: <tartanpion@machin.truc>
  11048. From: <tartanpion@machin.truc>
  11049. Bye.
  11050. EOM
  11051. ),
  11052. 'skipmess: 3 not From tartanpion@machin.truc' ) ;
  11053. ok( 1 == skipmess(
  11054. <<'EOM'
  11055. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11056. From: <kikiki@machin.truc>
  11057. From: <tartanpion@machin.truc>
  11058. Bye.
  11059. EOM
  11060. ),
  11061. 'skipmess: 4 not From tartanpion@machin.truc' ) ;
  11062. undef @skipmess ;
  11063. note( 'Leaving tests_skipmess_neg()' ) ;
  11064. return ;
  11065. }
  11066. sub skipmess
  11067. {
  11068. my ( $string ) = @_ ;
  11069. my $match ;
  11070. #myprint( "$string\n" ) ;
  11071. foreach my $skipmess ( @skipmess ) {
  11072. $sync->{ debug } and myprint( "eval \$match = \$string =~ $skipmess\n" ) ;
  11073. my $ret = eval "\$match = \$string =~ $skipmess ; 1" ;
  11074. #myprint( "eval [$ret]\n" ) ;
  11075. $sync->{ debug } and myprint( "match [$match]\n" ) ;
  11076. if ( ( not $ret ) or $EVAL_ERROR ) {
  11077. myprint( "Error: eval skipmess '$skipmess': $EVAL_ERROR" ) ;
  11078. return( undef ) ;
  11079. }
  11080. return( $match ) if ( $match ) ;
  11081. }
  11082. return( $match ) ;
  11083. }
  11084. sub tests_bytes_display_string
  11085. {
  11086. note( 'Entering tests_bytes_display_string()' ) ;
  11087. is( 'NA', bytes_display_string( ), 'bytes_display_string: no args => NA' ) ;
  11088. is( 'NA', bytes_display_string( undef ), 'bytes_display_string: undef => NA' ) ;
  11089. is( 'NA', bytes_display_string( 'blabla' ), 'bytes_display_string: blabla => NA' ) ;
  11090. is( '0.000 KiB', bytes_display_string( 0 ), 'bytes_display_string: 0' ) ;
  11091. is( '0.001 KiB', bytes_display_string( 1 ), 'bytes_display_string: 1' ) ;
  11092. is( '0.010 KiB', bytes_display_string( 10 ), 'bytes_display_string: 10' ) ;
  11093. is( '1.000 MiB', bytes_display_string( 1_048_575 ), 'bytes_display_string: 1_048_575' ) ;
  11094. is( '1.000 MiB', bytes_display_string( 1_048_576 ), 'bytes_display_string: 1_048_576' ) ;
  11095. is( '1.000 GiB', bytes_display_string( 1_073_741_823 ), 'bytes_display_string: 1_073_741_823 ' ) ;
  11096. is( '1.000 GiB', bytes_display_string( 1_073_741_824 ), 'bytes_display_string: 1_073_741_824 ' ) ;
  11097. is( '1.000 TiB', bytes_display_string( 1_099_511_627_775 ), 'bytes_display_string: 1_099_511_627_775' ) ;
  11098. is( '1.000 TiB', bytes_display_string( 1_099_511_627_776 ), 'bytes_display_string: 1_099_511_627_776' ) ;
  11099. is( '1.000 PiB', bytes_display_string( 1_125_899_906_842_623 ), 'bytes_display_string: 1_125_899_906_842_623' ) ;
  11100. is( '1.000 PiB', bytes_display_string( 1_125_899_906_842_624 ), 'bytes_display_string: 1_125_899_906_842_624' ) ;
  11101. is( '1024.000 PiB', bytes_display_string( 1_152_921_504_606_846_975 ), 'bytes_display_string: 1_152_921_504_606_846_975' ) ;
  11102. is( '1024.000 PiB', bytes_display_string( 1_152_921_504_606_846_976 ), 'bytes_display_string: 1_152_921_504_606_846_976' ) ;
  11103. is( '1048576.000 PiB', bytes_display_string( 1_180_591_620_717_411_303_424 ), 'bytes_display_string: 1_180_591_620_717_411_303_424' ) ;
  11104. #myprint( bytes_display_string( 1_180_591_620_717_411_303_424 ), "\n" ) ;
  11105. note( 'Leaving tests_bytes_display_string()' ) ;
  11106. return ;
  11107. }
  11108. sub bytes_display_string
  11109. {
  11110. my ( $bytes ) = @_ ;
  11111. my $readable_value = q{} ;
  11112. if ( ! defined( $bytes ) ) {
  11113. return( 'NA' ) ;
  11114. }
  11115. if ( not match_number( $bytes ) ) {
  11116. return( 'NA' ) ;
  11117. }
  11118. SWITCH: {
  11119. if ( abs( $bytes ) < ( 1000 * $KIBI ) ) {
  11120. $readable_value = mysprintf( '%.3f KiB', $bytes / $KIBI) ;
  11121. last SWITCH ;
  11122. }
  11123. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI ) ) {
  11124. $readable_value = mysprintf( '%.3f MiB', $bytes / ($KIBI * $KIBI) ) ;
  11125. last SWITCH ;
  11126. }
  11127. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI) ) {
  11128. $readable_value = mysprintf( '%.3f GiB', $bytes / ($KIBI * $KIBI * $KIBI) ) ;
  11129. last SWITCH ;
  11130. }
  11131. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI * $KIBI) ) {
  11132. $readable_value = mysprintf( '%.3f TiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI) ) ;
  11133. last SWITCH ;
  11134. } else {
  11135. $readable_value = mysprintf( '%.3f PiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI * $KIBI) ) ;
  11136. }
  11137. # if you have exabytes (EiB) of email to transfer, you have too much email!
  11138. }
  11139. #myprint( "$bytes = $readable_value\n" ) ;
  11140. return( $readable_value ) ;
  11141. }
  11142. sub tests_useheader_suggestion
  11143. {
  11144. note( 'Entering tests_useheader_suggestion()' ) ;
  11145. is( undef, useheader_suggestion( ), 'useheader_suggestion: no args => undef' ) ;
  11146. my $mysync = {} ;
  11147. $mysync->{ h1_nb_msg_noheader } = 0 ;
  11148. is( q{}, useheader_suggestion( $mysync ), 'useheader_suggestion: h1_nb_msg_noheader count null => no suggestion' ) ;
  11149. $mysync->{ h1_nb_msg_noheader } = 2 ;
  11150. is( q{in order to sync those 2 unidentified messages, add option --addheader}, useheader_suggestion( $mysync ),
  11151. 'useheader_suggestion: h1_nb_msg_noheader count 2 => suggestion of --addheader' ) ;
  11152. note( 'Leaving tests_useheader_suggestion()' ) ;
  11153. return ;
  11154. }
  11155. sub useheader_suggestion
  11156. {
  11157. my $mysync = shift ;
  11158. if ( ! defined $mysync->{ h1_nb_msg_noheader } )
  11159. {
  11160. return ;
  11161. }
  11162. elsif ( 1 <= $mysync->{ h1_nb_msg_noheader } )
  11163. {
  11164. return qq{in order to sync those $mysync->{ h1_nb_msg_noheader } unidentified messages, add option --addheader} ;
  11165. }
  11166. else
  11167. {
  11168. return q{} ;
  11169. }
  11170. return ;
  11171. }
  11172. sub do_and_print_stats
  11173. {
  11174. my $mysync = shift ;
  11175. if ( ! $mysync->{can_do_stats} ) {
  11176. return ;
  11177. }
  11178. my $timeend = time ;
  11179. my $timediff = $timeend - $mysync->{timestart} ;
  11180. my $timeend_str = localtimez( $timeend ) ;
  11181. my $cpu_time = cpu_time( $mysync ) ;
  11182. my $cpu_percent = cpu_percent( $mysync, $cpu_time, $timediff ) ;
  11183. my $cpu_percent_global = cpu_percent_global( $mysync, $cpu_percent ) ;
  11184. my $memory_consumption_at_end = memory_consumption( ) || 0 ;
  11185. my $memory_consumption_at_start = $mysync->{ memory_consumption_at_start } || 0 ;
  11186. my $memory_ratio = ( $mysync->{ biggest_message_transferred } ) ?
  11187. mysprintf( '%.1f', $memory_consumption_at_end / $mysync->{ biggest_message_transferred } ) : 'NA' ;
  11188. # my $useheader_suggestion = useheader_suggestion( $mysync ) ;
  11189. myprint( "++++ Statistics\n" ) ;
  11190. myprint( "Transfer started on : $mysync->{ timestart_str }\n" ) ;
  11191. myprint( "Transfer ended on : $timeend_str\n" ) ;
  11192. myprintf( "Transfer time : %.1f sec\n", $timediff ) ;
  11193. myprint( "Folders synced : $h1_folders_wanted_ct/$h1_folders_wanted_nb synced\n" ) ;
  11194. myprint( "Messages transferred : $mysync->{ nb_msg_transferred } " ) ;
  11195. myprint( "(could be $nb_msg_skipped_dry_mode without dry mode)" ) if ( $mysync->{dry} ) ;
  11196. myprint( "\n" ) ;
  11197. myprint( "Messages skipped : $mysync->{ nb_msg_skipped }\n" ) ;
  11198. myprint( "Messages found duplicate on host1 : $mysync->{ acc1 }->{ nb_msg_duplicate }\n" ) ;
  11199. myprint( "Messages found duplicate on host2 : $mysync->{ acc2 }->{ nb_msg_duplicate }\n" ) ;
  11200. myprint( "Messages found crossduplicate on host2 : $mysync->{ h2_nb_msg_crossdup }\n" ) ;
  11201. myprint( "Messages void (noheader) on host1 : $mysync->{ h1_nb_msg_noheader } ", useheader_suggestion( $mysync ), "\n" ) ;
  11202. myprint( "Messages void (noheader) on host2 : $h2_nb_msg_noheader\n" ) ;
  11203. nb_messages_in_1_not_in_2( $mysync ) ;
  11204. nb_messages_in_2_not_in_1( $mysync ) ;
  11205. myprintf( "Messages found in host1 not in host2 : %s messages\n", $mysync->{ nb_messages_in_1_not_in_2 } ) ;
  11206. myprintf( "Messages found in host2 not in host1 : %s messages\n", $mysync->{ nb_messages_in_2_not_in_1 } ) ;
  11207. myprint( "Messages deleted on host1 : $mysync->{ acc1 }->{ nb_msg_deleted }\n" ) ;
  11208. myprint( "Messages deleted on host2 : $mysync->{ acc2 }->{ nb_msg_deleted }\n" ) ;
  11209. myprintf( "Total bytes transferred : %s (%s)\n",
  11210. $mysync->{total_bytes_transferred},
  11211. bytes_display_string( $mysync->{total_bytes_transferred} ) ) ;
  11212. myprintf( "Total bytes skipped : %s (%s)\n",
  11213. $mysync->{ total_bytes_skipped },
  11214. bytes_display_string( $mysync->{ total_bytes_skipped } ) ) ;
  11215. $timediff ||= 1 ; # No division per 0
  11216. myprintf("Message rate : %.1f messages/s\n", $mysync->{nb_msg_transferred} / $timediff ) ;
  11217. myprintf("Average bandwidth rate : %.1f KiB/s\n", $mysync->{total_bytes_transferred} / $KIBI / $timediff ) ;
  11218. myprint( "Reconnections to host1 : $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT}\n" ) ;
  11219. myprint( "Reconnections to host2 : $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT}\n" ) ;
  11220. myprintf("Memory consumption at the end : %.1f MiB (started with %.1f MiB)\n",
  11221. $memory_consumption_at_end / $KIBI / $KIBI,
  11222. $memory_consumption_at_start / $KIBI / $KIBI ) ;
  11223. myprint( "Load end is : " . ( join( q{ }, loadavg( ) ) || 'unknown' ), " on $mysync->{cpu_number} cores\n" ) ;
  11224. myprint( "CPU time and %cpu : $cpu_time sec $cpu_percent %cpu $cpu_percent_global %allcpus\n" ) ;
  11225. myprintf("Biggest message transferred : %s bytes (%s)\n",
  11226. $mysync->{ biggest_message_transferred },
  11227. bytes_display_string( $mysync->{ biggest_message_transferred } ) ) ;
  11228. myprint( "Memory/biggest message ratio : $memory_ratio\n" ) ;
  11229. if ( $mysync->{ foldersizesatend } and $mysync->{ foldersizes } ) {
  11230. my $nb_msg_start_diff = diff_or_NA( $mysync->{ h2_nb_msg_start }, $mysync->{ h1_nb_msg_start } ) ;
  11231. my $bytes_start_diff = diff_or_NA( $mysync->{ h2_bytes_start }, $mysync->{ h1_bytes_start } ) ;
  11232. myprintf("Start difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_start_diff,
  11233. $bytes_start_diff,
  11234. bytes_display_string( $bytes_start_diff ) ) ;
  11235. my $nb_msg_end_diff = diff_or_NA( $h2_nb_msg_end, $h1_nb_msg_end ) ;
  11236. my $bytes_end_diff = diff_or_NA( $h2_bytes_end, $h1_bytes_end ) ;
  11237. myprintf("Final difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_end_diff,
  11238. $bytes_end_diff,
  11239. bytes_display_string( $bytes_end_diff ) ) ;
  11240. }
  11241. comment_on_final_diff_in_1_not_in_2( $mysync ) ;
  11242. comment_on_final_diff_in_2_not_in_1( $mysync ) ;
  11243. myprint( "Detected $mysync->{nb_errors} errors\n\n" ) ;
  11244. myprint( $warn_release, "\n" ) ;
  11245. myprint( homepage( ), "\n" ) ;
  11246. return ;
  11247. }
  11248. sub diff_or_NA
  11249. {
  11250. my( $n1, $n2 ) = @ARG ;
  11251. if ( not defined $n1 or not defined $n2 ) {
  11252. return 'NA' ;
  11253. }
  11254. if ( not match_number( $n1 )
  11255. or not match_number( $n2 ) ) {
  11256. return 'NA' ;
  11257. }
  11258. return( $n1 - $n2 ) ;
  11259. }
  11260. sub match_number
  11261. {
  11262. my $n = shift @ARG ;
  11263. if ( not defined $n ) {
  11264. return 0 ;
  11265. }
  11266. if ( $n =~ /[0-9]+\.?[0-9]?/x ) {
  11267. return 1 ;
  11268. }
  11269. else {
  11270. return 0 ;
  11271. }
  11272. }
  11273. sub tests_match_number
  11274. {
  11275. note( 'Entering tests_match_number()' ) ;
  11276. is( 0, match_number( ), 'match_number: no parameters => 0' ) ;
  11277. is( 0, match_number( undef ), 'match_number: undef => 0' ) ;
  11278. is( 0, match_number( 'blabla' ), 'match_number: blabla => 0' ) ;
  11279. is( 1, match_number( 0 ), 'match_number: 0 => 1' ) ;
  11280. is( 1, match_number( 1 ), 'match_number: 1 => 1' ) ;
  11281. is( 1, match_number( 1.0 ), 'match_number: 1.0 => 1' ) ;
  11282. is( 1, match_number( 0.0 ), 'match_number: 0.0 => 1' ) ;
  11283. note( 'Leaving tests_match_number()' ) ;
  11284. return ;
  11285. }
  11286. sub tests_diff_or_NA
  11287. {
  11288. note( 'Entering tests_diff_or_NA()' ) ;
  11289. is( 'NA', diff_or_NA( ), 'diff_or_NA: no parameters => NA' ) ;
  11290. is( 'NA', diff_or_NA( undef ), 'diff_or_NA: undef => NA' ) ;
  11291. is( 'NA', diff_or_NA( undef, undef ), 'diff_or_NA: undef undef => NA' ) ;
  11292. is( 'NA', diff_or_NA( undef, 1 ), 'diff_or_NA: undef 1 => NA' ) ;
  11293. is( 'NA', diff_or_NA( 1, undef ), 'diff_or_NA: 1 undef => NA' ) ;
  11294. is( 'NA', diff_or_NA( 'blabla', 1 ), 'diff_or_NA: blabla 1 => NA' ) ;
  11295. is( 'NA', diff_or_NA( 1, 'blabla' ), 'diff_or_NA: 1 blabla => NA' ) ;
  11296. is( 0, diff_or_NA( 1, 1 ), 'diff_or_NA: 1 1 => 0' ) ;
  11297. is( 1, diff_or_NA( 1, 0 ), 'diff_or_NA: 1 0 => 1' ) ;
  11298. is( -1, diff_or_NA( 0, 1 ), 'diff_or_NA: 0 1 => -1' ) ;
  11299. is( 0, diff_or_NA( 1.0, 1 ), 'diff_or_NA: 1.0 1 => 0' ) ;
  11300. is( 1, diff_or_NA( 1.0, 0 ), 'diff_or_NA: 1.0 0 => 1' ) ;
  11301. is( -1, diff_or_NA( 0, 1.0 ), 'diff_or_NA: 0 1.0 => -1' ) ;
  11302. note( 'Leaving tests_diff_or_NA()' ) ;
  11303. return ;
  11304. }
  11305. sub homepage
  11306. {
  11307. return( 'Homepage: https://imapsync.lamiral.info/' ) ;
  11308. }
  11309. sub load_modules
  11310. {
  11311. if ( $sync->{ssl1}
  11312. or $sync->{ssl2}
  11313. or $sync->{tls1}
  11314. or $sync->{tls2}) {
  11315. if ( $sync->{inet4} ) {
  11316. IO::Socket::SSL->import( 'inet4' ) ;
  11317. }
  11318. if ( $sync->{inet6} ) {
  11319. IO::Socket::SSL->import( 'inet6' ) ;
  11320. }
  11321. }
  11322. return ;
  11323. }
  11324. # Globals: $skipsize $wholeheaderifneeded
  11325. sub parse_header_msg
  11326. {
  11327. my ( $mysync, $imap, $m_uid, $s_heads, $s_fir, $side, $s_hash ) = @_ ;
  11328. my $head = $s_heads->{$m_uid} ;
  11329. my $headnum = scalar keys %{ $head } ;
  11330. $mysync->{ debug } and myprint( "$side: uid $m_uid number of headers, pass one: ", $headnum, "\n" ) ;
  11331. if ( ( ! $headnum ) and ( $wholeheaderifneeded ) ){
  11332. $mysync->{ debug } and myprint( "$side: uid $m_uid no header by parse_headers so taking whole header with BODY.PEEK[HEADER]\n" ) ;
  11333. $imap->fetch($m_uid, 'BODY.PEEK[HEADER]' ) ;
  11334. my $whole_header = $imap->_transaction_literals ;
  11335. #myprint( $whole_header ) ;
  11336. $head = decompose_header( $whole_header ) ;
  11337. $headnum = scalar keys %{ $head } ;
  11338. $mysync->{ debug } and myprint( "$side: uid $m_uid number of headers, pass two: ", $headnum, "\n" ) ;
  11339. }
  11340. #myprint( Data::Dumper->Dump( [ $head, \%useheader ] ) ) ;
  11341. my $headstr = header_construct( $mysync, $head, $side, $m_uid ) ;
  11342. if ( ( ! $headstr ) and ( $mysync->{addheader} ) and ( $side eq 'Host1' ) ) {
  11343. my $header = add_header( $m_uid ) ;
  11344. $mysync->{ debug } and myprint( "$side: uid $m_uid no header found so adding our own [$header]\n" ) ;
  11345. $headstr .= uc $header ;
  11346. $s_fir->{$m_uid}->{NO_HEADER} = 1;
  11347. }
  11348. return if ( ! $headstr ) ;
  11349. my $size = $s_fir->{$m_uid}->{'RFC822.SIZE'} ;
  11350. my $flags = $s_fir->{$m_uid}->{'FLAGS'} ;
  11351. my $idate = $s_fir->{$m_uid}->{'INTERNALDATE'} ;
  11352. $size = length $headstr unless ( $size ) ;
  11353. my $m_md5 = md5_base64( $headstr ) ;
  11354. my $key ;
  11355. if ( $skipsize ) {
  11356. $key = "$m_md5";
  11357. }
  11358. else {
  11359. $key = "$m_md5:$size";
  11360. }
  11361. if ( exists $s_hash->{"$key"} )
  11362. {
  11363. # 0 return code is used to identify duplicate message hash
  11364. my $dup_ref = $s_hash->{"$key"}->{'U'} ;
  11365. my $num = scalar( @{ $dup_ref } ) ;
  11366. push( @{ $dup_ref }, $m_uid ) ;
  11367. my $keydup = "$key#$num" ;
  11368. $mysync->{ debug } and myprint( "$side: uid $m_uid sig $keydup size $size idate $idate dup @{ $dup_ref }\n" ) ;
  11369. if ( $mysync->{ syncduplicates } )
  11370. {
  11371. $s_hash->{"$keydup"}{'5'} = $m_md5 ;
  11372. $s_hash->{"$keydup"}{'s'} = $size ;
  11373. $s_hash->{"$keydup"}{'D'} = $idate ;
  11374. $s_hash->{"$keydup"}{'F'} = $flags ;
  11375. $s_hash->{"$keydup"}{'m'} = $m_uid ;
  11376. }
  11377. return 0 ;
  11378. }
  11379. else
  11380. {
  11381. $s_hash->{"$key"}{'5'} = $m_md5 ;
  11382. $s_hash->{"$key"}{'s'} = $size ;
  11383. $s_hash->{"$key"}{'D'} = $idate ;
  11384. $s_hash->{"$key"}{'F'} = $flags ;
  11385. $s_hash->{"$key"}{'m'} = $m_uid ;
  11386. $s_hash->{"$key"}{'U'} = [ $m_uid ] ; # ? or [ ] ?
  11387. $mysync->{ debug } and myprint( "$side: uid $m_uid sig $key size $size idate $idate\n" ) ;
  11388. return( 1 ) ;
  11389. }
  11390. # we should not be here
  11391. return ;
  11392. }
  11393. sub tests_header_construct
  11394. {
  11395. note( 'Entering tests_header_construct()' ) ;
  11396. is( undef, header_construct( ), 'header_construct: no args => undef' ) ;
  11397. my $mysync = {} ;
  11398. my $head = {
  11399. 'key1' => [ 'val1_key1' ]
  11400. } ;
  11401. is( undef, header_construct( $mysync, $head, 'Host1', '1' ), 'header_construct: key1 val1_key1 no useheader => undef' ) ;
  11402. $mysync->{useheader}->{ 'KEY1' } = 1 ;
  11403. is( 'KEY1: VAL1_KEY1', header_construct( $mysync, $head, 'Host1', '1' ), 'header_construct: key1 val1_key1 => KEY1: VAL1_KEY1' ) ;
  11404. $head = {
  11405. 'key1' => [ 'val1_key1', 'val3_key1', 'val2_key1' ]
  11406. } ;
  11407. is( 'KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1', header_construct( $mysync, $head, 'Host1', '1' ),
  11408. 'header_construct: key1 val1_key1 val3_key1 val2_key1 => KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1' ) ;
  11409. $head = {
  11410. 'key1' => [ 'val1_key1', 'val3_key1', ' val2_key1' ]
  11411. } ;
  11412. is( 'KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1', header_construct( $mysync, $head, 'Host1', '1' ),
  11413. 'header_construct: key1 val1_key1 val3_key1 val2_key1 => KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1' ) ;
  11414. $mysync->{useheader}->{ 'ALL' } = 1 ;
  11415. is( 'KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1', header_construct( $mysync, $head, 'Host1', '1' ),
  11416. 'header_construct: key1 val1_key1 val3_key1 val2_key1 useheader ALL => KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1' ) ;
  11417. $mysync->{skipheader} = 'key1' ;
  11418. is( undef, header_construct( $mysync, $head, 'Host1', '1' ),
  11419. 'header_construct: key1 val1_key1 val3_key1 val2_key1 useheader ALL => undef' ) ;
  11420. $head = {
  11421. 'key1' => [ 'val1_key1', 'val3_key1', ' val2_key1' ],
  11422. 'key2' => [ 'val1_key2', 'val3_key2', ' val2_key2' ]
  11423. } ;
  11424. is( 'KEY2: VAL1_KEY2KEY2: VAL2_KEY2KEY2: VAL3_KEY2', header_construct( $mysync, $head, 'Host1', '1' ),
  11425. 'header_construct: ... useheader ALL skipheader key1 => KEY2: VAL1_KEY2KEY2: VAL2_KEY2KEY2: VAL3_KEY2' ) ;
  11426. note( 'Leaving tests_header_construct()' ) ;
  11427. return ;
  11428. }
  11429. # No global in header_construct
  11430. sub header_construct
  11431. {
  11432. my( $mysync, $head, $side, $m_uid ) = @_ ;
  11433. my @headstr ;
  11434. foreach my $h ( sort keys %{ $head } ) {
  11435. next if ( not ( exists $mysync->{useheader}->{ uc $h } )
  11436. and ( not exists $mysync->{useheader}->{ 'ALL' } )
  11437. ) ;
  11438. foreach my $val ( @{$head->{$h}} ) {
  11439. my $H = header_line_normalize( $h, $val ) ;
  11440. # show stuff in debug mode
  11441. $mysync->{ debug } and myprint( "$side uid $m_uid header [$H]", "\n" ) ;
  11442. if ( $mysync->{skipheader} and $H =~ m/$mysync->{skipheader}/xi) {
  11443. $mysync->{ debug } and myprint( "$side uid $m_uid skipping header [$H]\n" ) ;
  11444. next ;
  11445. }
  11446. push @headstr, $H ;
  11447. }
  11448. }
  11449. my $headstr = join( '', sort @headstr ) || undef ;
  11450. return( $headstr ) ;
  11451. }
  11452. sub header_line_normalize
  11453. {
  11454. my( $header_key, $header_val ) = @_ ;
  11455. # no 8-bit data in headers !
  11456. $header_val =~ s/[\x80-\xff]/X/xog;
  11457. # change tabulations to space (Gmail bug on with "Received:" on multilines)
  11458. $header_val =~ s/\t/\ /xgo ;
  11459. # remove the first blanks ( dbmail bug? )
  11460. $header_val =~ s/^\s*//xo;
  11461. # remove the last blanks ( Gmail bug )
  11462. $header_val =~ s/\s*$//xo;
  11463. # remove successive blanks ( Mailenable does it )
  11464. $header_val =~ s/\s+/ /xgo;
  11465. # remove Message-Id value domain part ( Mailenable changes it )
  11466. if ( ( $messageidnodomain ) and ( 'MESSAGE-ID' eq uc $header_key ) ) { $header_val =~ s/^([^@]+).*$/$1/xo ; }
  11467. # and uppercase header line
  11468. # (dbmail and dovecot)
  11469. my $header_line = uc "$header_key: $header_val" ;
  11470. return( $header_line ) ;
  11471. }
  11472. sub tests_header_line_normalize
  11473. {
  11474. note( 'Entering tests_header_line_normalize()' ) ;
  11475. ok( ': ' eq header_line_normalize( q{}, q{} ), 'header_line_normalize: empty args' ) ;
  11476. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', 'vvv' ), 'header_line_normalize: hhh vvv ' ) ;
  11477. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', ' vvv' ), 'header_line_normalize: remove first blancs' ) ;
  11478. ok( 'HHH: AA BB CCC D' eq header_line_normalize( 'hhh', 'aa bb ccc d' ), 'header_line_normalize: remove succesive blanks' ) ;
  11479. ok( 'HHH: AA BB CCC' eq header_line_normalize( 'hhh', 'aa bb ccc ' ), 'header_line_normalize: remove last blanks' ) ;
  11480. ok( 'HHH: VVV XX YY' eq header_line_normalize( 'hhh', "vvv\t\txx\tyy" ), 'header_line_normalize: tabs' ) ;
  11481. ok( 'HHH: XABX' eq header_line_normalize( 'hhh', "\x80AB\xff" ), 'header_line_normalize: 8bit' ) ;
  11482. note( 'Leaving tests_header_line_normalize()' ) ;
  11483. return ;
  11484. }
  11485. sub tests_firstline
  11486. {
  11487. note( 'Entering tests_firstline()' ) ;
  11488. is( q{}, firstline( 'W/tmp/tests/noexist.txt' ), 'firstline: getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  11489. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'firstline: mkpath W/tmp/tests/' ) ;
  11490. is( "blabla\n" , string_to_file( "blabla\n", 'W/tmp/tests/firstline.txt' ), 'firstline: put blabla in W/tmp/tests/firstline.txt' ) ;
  11491. is( 'blabla' , firstline( 'W/tmp/tests/firstline.txt' ), 'firstline: get blabla from W/tmp/tests/firstline.txt' ) ;
  11492. is( q{} , string_to_file( q{}, 'W/tmp/tests/firstline2.txt' ), 'firstline: put empty string in W/tmp/tests/firstline2.txt' ) ;
  11493. is( q{} , firstline( 'W/tmp/tests/firstline2.txt' ), 'firstline: get empty string from W/tmp/tests/firstline2.txt' ) ;
  11494. is( "\n" , string_to_file( "\n", 'W/tmp/tests/firstline3.txt' ), 'firstline: put CR in W/tmp/tests/firstline3.txt' ) ;
  11495. is( q{} , firstline( 'W/tmp/tests/firstline3.txt' ), 'firstline: get empty string from W/tmp/tests/firstline3.txt' ) ;
  11496. is( "blabla\nTiti\n" , string_to_file( "blabla\nTiti\n", 'W/tmp/tests/firstline4.txt' ), 'firstline: put blabla\nTiti\n in W/tmp/tests/firstline4.txt' ) ;
  11497. is( 'blabla' , firstline( 'W/tmp/tests/firstline4.txt' ), 'firstline: get blabla from W/tmp/tests/firstline4.txt' ) ;
  11498. note( 'Leaving tests_firstline()' ) ;
  11499. return ;
  11500. }
  11501. sub firstline
  11502. {
  11503. # extract the first line of a file (without \n)
  11504. # return empty string if error or empty string
  11505. my $file = shift ;
  11506. my $line ;
  11507. $line = nthline( $file, 1 ) ;
  11508. return $line ;
  11509. }
  11510. sub tests_secondline
  11511. {
  11512. note( 'Entering tests_secondline()' ) ;
  11513. is( q{}, secondline( 'W/tmp/tests/noexist.txt' ), 'secondline: getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  11514. is( q{}, secondline( 'W/tmp/tests/noexist.txt', 2 ), 'secondline: 2nd getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  11515. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'secondline: mkpath W/tmp/tests/' ) ;
  11516. is( "L1\nL2\nL3\nL4\n" , string_to_file( "L1\nL2\nL3\nL4\n", 'W/tmp/tests/secondline.txt' ), 'secondline: put L1\nL2\nL3\nL4\n in W/tmp/tests/secondline.txt' ) ;
  11517. is( 'L2' , secondline( 'W/tmp/tests/secondline.txt' ), 'secondline: get L2 from W/tmp/tests/secondline.txt' ) ;
  11518. note( 'Leaving tests_secondline()' ) ;
  11519. return ;
  11520. }
  11521. sub secondline
  11522. {
  11523. # extract the second line of a file (without \n)
  11524. # return empty string if error or empty string
  11525. my $file = shift ;
  11526. my $line ;
  11527. $line = nthline( $file, 2 ) ;
  11528. return $line ;
  11529. }
  11530. sub tests_nthline
  11531. {
  11532. note( 'Entering tests_nthline()' ) ;
  11533. is( q{}, nthline( 'W/tmp/tests/noexist.txt' ), 'nthline: getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  11534. is( q{}, nthline( 'W/tmp/tests/noexist.txt', 2 ), 'nthline: 2nd getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  11535. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'nthline: mkpath W/tmp/tests/' ) ;
  11536. is( "L1\nL2\nL3\nL4\n" , string_to_file( "L1\nL2\nL3\nL4\n", 'W/tmp/tests/nthline.txt' ), 'nthline: put L1\nL2\nL3\nL4\n in W/tmp/tests/nthline.txt' ) ;
  11537. is( 'L3' , nthline( 'W/tmp/tests/nthline.txt', 3 ), 'nthline: get L3 from W/tmp/tests/nthline.txt' ) ;
  11538. note( 'Leaving tests_nthline()' ) ;
  11539. return ;
  11540. }
  11541. sub nthline
  11542. {
  11543. # extract the nth line of a file (without \n)
  11544. # return empty string if error or empty string
  11545. my $file = shift ;
  11546. my $num = shift ;
  11547. if ( ! all_defined( $file, $num ) ) { return q{} ; }
  11548. my $line ;
  11549. $line = ( file_to_array( $file ) )[$num - 1] ;
  11550. if ( ! defined $line )
  11551. {
  11552. return q{} ;
  11553. }
  11554. else
  11555. {
  11556. chomp $line ;
  11557. return $line ;
  11558. }
  11559. }
  11560. sub tests_file_to_array
  11561. {
  11562. note( 'Entering tests_file_to_array()' ) ;
  11563. is( undef, file_to_array( ), 'file_to_array: no args => undef' ) ;
  11564. is( undef, file_to_array( '/noexist' ), 'file_to_array: /noexist => undef' ) ;
  11565. is( undef, file_to_array( '/' ), 'file_to_array: reading a directory => undef' ) ;
  11566. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'file_to_array: mkpath W/tmp/tests/' ) ;
  11567. is( "L1\nL2\nL3\nL4\n" , string_to_file( "L1\nL2\nL3\nL4\n", 'W/tmp/tests/file_to_array.txt' ), 'file_to_array: put L1\nL2\nL3\nL4\n in W/tmp/tests/file_to_array.txt' ) ;
  11568. is_deeply( [ "L1\n", "L2\n", "L3\n", "L4\n" ] , [ file_to_array( 'W/tmp/tests/file_to_array.txt' ) ], 'file_to_array: get back L1\n L2\n L3\n L4\n from W/tmp/tests/file_to_array.txt' ) ;
  11569. note( 'Leaving tests_file_to_array()' ) ;
  11570. return ;
  11571. }
  11572. sub file_to_array
  11573. {
  11574. my( $file ) = shift ;
  11575. if ( ! $file ) { return ; }
  11576. if ( ! -e $file ) { return ; }
  11577. if ( ! -f $file ) { return ; }
  11578. if ( ! -r $file ) { return ; }
  11579. my @string ;
  11580. if ( open my $FILE, '<', $file )
  11581. {
  11582. @string = <$FILE> ;
  11583. close $FILE ;
  11584. return( @string ) ;
  11585. }
  11586. else
  11587. {
  11588. myprint( "Error reading file $file : $OS_ERROR\n" ) ;
  11589. return ;
  11590. }
  11591. }
  11592. sub tests_file_to_string
  11593. {
  11594. note( 'Entering tests_file_to_string()' ) ;
  11595. is( undef, file_to_string( ), 'file_to_string: no args => undef' ) ;
  11596. is( undef, file_to_string( '/noexist' ), 'file_to_string: /noexist => undef' ) ;
  11597. is( undef, file_to_string( '/' ), 'file_to_string: reading a directory => undef' ) ;
  11598. ok( file_to_string( $PROGRAM_NAME ), 'file_to_string: reading myself' ) ;
  11599. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'file_to_string: mkpath W/tmp/tests/' ) ;
  11600. is( 'lilili', string_to_file( 'lilili', 'W/tmp/tests/canbewritten' ), 'file_to_string: string_to_file filling W/tmp/tests/canbewritten with lilili' ) ;
  11601. is( 'lilili', file_to_string( 'W/tmp/tests/canbewritten' ), 'file_to_string: reading W/tmp/tests/canbewritten is lilili' ) ;
  11602. is( q{}, string_to_file( q{}, 'W/tmp/tests/empty' ), 'file_to_string: string_to_file filling W/tmp/tests/empty with empty string' ) ;
  11603. is( q{}, file_to_string( 'W/tmp/tests/empty' ), 'file_to_string: reading W/tmp/tests/empty is empty' ) ;
  11604. note( 'Leaving tests_file_to_string()' ) ;
  11605. return ;
  11606. }
  11607. sub file_to_string
  11608. {
  11609. my $file = shift ;
  11610. if ( ! $file ) { return ; }
  11611. if ( ! -e $file ) { return ; }
  11612. if ( ! -f $file ) { return ; }
  11613. if ( ! -r $file ) { return ; }
  11614. return( join q{}, file_to_array( $file ) ) ;
  11615. }
  11616. sub tests_string_to_file
  11617. {
  11618. note( 'Entering tests_string_to_file()' ) ;
  11619. is( undef, string_to_file( ), 'string_to_file: no args => undef' ) ;
  11620. is( undef, string_to_file( 'lalala' ), 'string_to_file: one arg => undef' ) ;
  11621. is( undef, string_to_file( 'lalala', '.' ), 'string_to_file: writing a directory => undef' ) ;
  11622. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'string_to_file: mkpath W/tmp/tests/' ) ;
  11623. is( 'lalala', string_to_file( 'lalala', 'W/tmp/tests/canbewritten' ), 'string_to_file: W/tmp/tests/canbewritten with lalala' ) ;
  11624. is( q{}, string_to_file( q{}, 'W/tmp/tests/empty' ), 'string_to_file: W/tmp/tests/empty with empty string' ) ;
  11625. SKIP: {
  11626. Readonly my $NB_UNX_tests_string_to_file => 1 ;
  11627. skip( 'Not on Unix non-root', $NB_UNX_tests_string_to_file ) if ('MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) ;
  11628. is( undef, string_to_file( 'lalala', '/cantouch' ), 'string_to_file: /cantouch denied => undef' ) ;
  11629. }
  11630. note( 'Leaving tests_string_to_file()' ) ;
  11631. return ;
  11632. }
  11633. sub string_to_file
  11634. {
  11635. my( $string, $file ) = @_ ;
  11636. if( ! defined $string ) { return ; }
  11637. if( ! defined $file ) { return ; }
  11638. if ( ! -e $file && ! -w dirname( $file ) ) {
  11639. myprint( "string_to_file: directory of $file is not writable\n" ) ;
  11640. return ;
  11641. }
  11642. if ( ! sysopen( FILE, $file, O_WRONLY|O_TRUNC|O_CREAT, 0600) ) {
  11643. myprint( "string_to_file: failure writing to $file with error: $OS_ERROR\n" ) ;
  11644. return ;
  11645. }
  11646. print FILE $string ;
  11647. close FILE ;
  11648. return $string ;
  11649. }
  11650. 0 and <<'MULTILINE_COMMENT' ;
  11651. This is a multiline comment.
  11652. Based on David Carter discussion, to do:
  11653. * Call parameters stay the same.
  11654. * Now always "return( $string, $error )". Descriptions below.
  11655. OK * Still capture STDOUT via "1> $output_tmpfile" to finish in $string and "return( $string, $error )"
  11656. OK * Now also capture STDERR via "2> $error_tmpfile" to finish in $error and "return( $string, $error )"
  11657. OK * in case of CHILD_ERROR, return( undef, $error )
  11658. and print $error, with folder/UID/maybeSubject context,
  11659. on console and at the end with the final error listing. Count this as a sync error.
  11660. * in case of good command, take final $string as is, unless void. In case $error with value then print it.
  11661. * in case of good command and final $string empty, consider it like CHILD_ERROR =>
  11662. return( undef, $error ) and print $error, with folder/UID/maybeSubject context,
  11663. on console and at the end with the final error listing. Count this as a sync error.
  11664. MULTILINE_COMMENT
  11665. # End of multiline comment.
  11666. sub pipemess
  11667. {
  11668. my ( $string, @commands ) = @_ ;
  11669. my $error = q{} ;
  11670. foreach my $command ( @commands ) {
  11671. my $input_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.inp.txt" ;
  11672. my $output_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.out.txt" ;
  11673. my $error_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.err.txt" ;
  11674. string_to_file( $string, $input_tmpfile ) ;
  11675. ` $command < $input_tmpfile 1> $output_tmpfile 2> $error_tmpfile ` ;
  11676. my $is_command_ko = $CHILD_ERROR ;
  11677. my $error_cmd = file_to_string( $error_tmpfile ) ;
  11678. chomp( $error_cmd ) ;
  11679. $string = file_to_string( $output_tmpfile ) ;
  11680. my $string_len = length( $string ) ;
  11681. unlink $input_tmpfile, $output_tmpfile, $error_tmpfile ;
  11682. if ( $is_command_ko or ( ! $string_len ) ) {
  11683. my $cmd_exit_value = $CHILD_ERROR >> 8 ;
  11684. my $cmd_end_signal = $CHILD_ERROR & 127 ;
  11685. my $signal_log = ( $cmd_end_signal ) ? " signal $cmd_end_signal and" : q{} ;
  11686. 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} ;
  11687. myprint( $error_log ) ;
  11688. if ( wantarray ) {
  11689. return @{ [ undef, $error_log ] }
  11690. }else{
  11691. return ;
  11692. }
  11693. }
  11694. if ( $error_cmd ) {
  11695. $error .= qq{STDERR of --pipemess "$command": $error_cmd\n} ;
  11696. myprint( qq{STDERR of --pipemess "$command": $error_cmd\n} ) ;
  11697. }
  11698. }
  11699. #myprint( "[$string]\n" ) ;
  11700. if ( wantarray ) {
  11701. return ( $string, $error ) ;
  11702. }else{
  11703. return $string ;
  11704. }
  11705. }
  11706. sub tests_pipemess
  11707. {
  11708. note( 'Entering tests_pipemess()' ) ;
  11709. SKIP: {
  11710. Readonly my $NB_WIN_tests_pipemess => 3 ;
  11711. skip( 'Not on MSWin32', $NB_WIN_tests_pipemess ) if ('MSWin32' ne $OSNAME) ;
  11712. # Windows
  11713. # "type" command does not accept redirection of STDIN with <
  11714. # "sort" does
  11715. ok( "nochange\n" eq pipemess( 'nochange', 'sort' ), 'pipemess: nearly no change by sort' ) ;
  11716. ok( "nochange2\n" eq pipemess( 'nochange2', qw( sort sort ) ), 'pipemess: nearly no change by sort,sort' ) ;
  11717. # command not found
  11718. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  11719. ok( ! defined( pipemess( q{}, 'cacaprout' ) ), 'pipemess: command not found' ) ;
  11720. } ;
  11721. my ( $stringT, $errorT ) ;
  11722. SKIP: {
  11723. Readonly my $NB_UNX_tests_pipemess => 25 ;
  11724. skip( 'Not on Unix', $NB_UNX_tests_pipemess ) if ('MSWin32' eq $OSNAME) ;
  11725. # Unix
  11726. ok( 'nochange' eq pipemess( 'nochange', 'cat' ), 'pipemess: no change by cat' ) ;
  11727. ok( 'nochange2' eq pipemess( 'nochange2', 'cat', 'cat' ), 'pipemess: no change by cat,cat' ) ;
  11728. ok( " 1\tnumberize\n" eq pipemess( "numberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  11729. ok( " 1\tnumberize\n 2\tnumberize\n" eq pipemess( "numberize\nnumberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  11730. ok( "A\nB\nC\n" eq pipemess( "A\nC\nB\n", 'sort' ), 'pipemess: sort' ) ;
  11731. # command not found
  11732. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  11733. is( undef, pipemess( q{}, 'cacaprout' ), 'pipemess: command not found' ) ;
  11734. # success with true but no output at all
  11735. is( undef, pipemess( q{blabla}, 'true' ), 'pipemess: true but no output' ) ;
  11736. # failure with false and no output at all
  11737. is( undef, pipemess( q{blabla}, 'false' ), 'pipemess: false and no output' ) ;
  11738. # Failure since pipemess is not a real pipe, so first cat wait for standard input
  11739. is( q{blabla}, pipemess( q{blabla}, '( cat|cat ) ' ), 'pipemess: ok by ( cat|cat )' ) ;
  11740. ( $stringT, $errorT ) = pipemess( 'nochange', 'cat' ) ;
  11741. is( $stringT, 'nochange', 'pipemess: list context, no change by cat, string' ) ;
  11742. is( $errorT, q{}, 'pipemess: list context, no change by cat, no error' ) ;
  11743. ( $stringT, $errorT ) = pipemess( 'dontcare', 'true' ) ;
  11744. is( $stringT, undef, 'pipemess: list context, true but no output, string' ) ;
  11745. 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' ) ;
  11746. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false' ) ;
  11747. is( $stringT, undef, 'pipemess: list context, false and no output, string' ) ;
  11748. like( $errorT, qr{\QFailure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""\E}xm,
  11749. 'pipemess: list context, false and no output, error' ) ;
  11750. ( $stringT, $errorT ) = pipemess( 'dontcare', '/bin/echo -n blablabla' ) ;
  11751. is( $stringT, q{blablabla}, 'pipemess: list context, "echo -n blablabla", string' ) ;
  11752. is( $errorT, q{}, 'pipemess: list context, "echo blablabla", error' ) ;
  11753. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  11754. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla", string' ) ;
  11755. like( $errorT, qr{blablabla"}xm, 'pipemess: list context, "no output STDERR blablabla", error' ) ;
  11756. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )', 'false' ) ;
  11757. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla then false", string' ) ;
  11758. like( $errorT, qr{blablabla"}xm, 'pipemess: list context, "no output STDERR blablabla then false", error' ) ;
  11759. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  11760. is( $stringT, undef, 'pipemess: list context, "false then STDERR blablabla", string' ) ;
  11761. like( $errorT, qr{\QFailure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""\E}xm,
  11762. 'pipemess: list context, "false then STDERR blablabla", error' ) ;
  11763. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo rrrrr ; echo -n error_blablabla 3>&1 1>&2 2>&3 )' ) ;
  11764. like( $stringT, qr{rrrrr}xm, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", string' ) ;
  11765. like( $errorT, qr{STDERR.*error_blablabla}xm, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", error' ) ;
  11766. }
  11767. ( $stringT, $errorT ) = pipemess( 'dontcare', 'cacaprout' ) ;
  11768. is( $stringT, undef, 'pipemess: list context, cacaprout not found, string' ) ;
  11769. like( $errorT, qr{\QFailure: --pipemess command "cacaprout" ended with "0" characters exit value\E}xm,
  11770. 'pipemess: list context, cacaprout not found, error' ) ;
  11771. note( 'Leaving tests_pipemess()' ) ;
  11772. return ;
  11773. }
  11774. sub tests_is_a_release_number
  11775. {
  11776. note( 'Entering tests_is_a_release_number()' ) ;
  11777. is( undef, is_a_release_number( ), 'is_a_release_number: no args => undef' ) ;
  11778. ok( is_a_release_number( $RELEASE_NUMBER_EXAMPLE_1 ), 'is_a_release_number 1.351' ) ;
  11779. ok( is_a_release_number( $RELEASE_NUMBER_EXAMPLE_2 ), 'is_a_release_number 42.4242' ) ;
  11780. ok( is_a_release_number( imapsync_version( $sync ) ), 'is_a_release_number imapsync_version( )' ) ;
  11781. ok( ! is_a_release_number( 'blabla' ), '! is_a_release_number blabla' ) ;
  11782. note( 'Leaving tests_is_a_release_number()' ) ;
  11783. return ;
  11784. }
  11785. sub is_a_release_number
  11786. {
  11787. my $number = shift ;
  11788. if ( ! defined $number ) { return ; }
  11789. return( $number =~ m{^\d+\.\d+$}xo ) ;
  11790. }
  11791. sub imapsync_version_public
  11792. {
  11793. my $local_version = imapsync_version( $sync ) ;
  11794. my $imapsync_basename = imapsync_basename( ) ;
  11795. my $context = imapsync_context( ) ;
  11796. my $agent_info = "$OSNAME system, perl "
  11797. . mysprintf( '%vd', $PERL_VERSION)
  11798. . ", Mail::IMAPClient $Mail::IMAPClient::VERSION"
  11799. . " $imapsync_basename"
  11800. . " $context" ;
  11801. my $sock = IO::Socket::INET->new(
  11802. PeerAddr => 'imapsync.lamiral.info',
  11803. PeerPort => 80,
  11804. Proto => 'tcp',
  11805. ) ;
  11806. return( 'unknown' ) if not $sock ;
  11807. print $sock
  11808. "GET /prj/imapsync/VERSION HTTP/1.0\r\n",
  11809. "User-Agent: imapsync/$local_version ($agent_info)\r\n",
  11810. "Host: ks.lamiral.info\r\n\r\n" ;
  11811. my @line = <$sock> ;
  11812. close $sock ;
  11813. my $last_release = $line[$LAST] ;
  11814. chomp $last_release ;
  11815. return( $last_release ) ;
  11816. }
  11817. sub not_long_imapsync_version_public
  11818. {
  11819. #myprint( "Entering not_long_imapsync_version_public\n" ) ;
  11820. my $fake = shift ;
  11821. if ( $fake ) { return $fake }
  11822. my $val ;
  11823. # Doesn't work with gethostbyname (see perlipc)
  11824. #local $SIG{ALRM} = sub { die "alarm\n" } ;
  11825. if ('MSWin32' eq $OSNAME) {
  11826. local $SIG{ALRM} = sub { die "alarm\n" } ;
  11827. }else{
  11828. POSIX::sigaction(SIGALRM,
  11829. POSIX::SigAction->new(sub { croak 'alarm' } ) )
  11830. or myprint( "Error setting SIGALRM handler: $OS_ERROR\n" ) ;
  11831. }
  11832. my $ret = eval {
  11833. alarm 3 ;
  11834. {
  11835. $val = imapsync_version_public( ) ;
  11836. #sleep 4 ;
  11837. #myprint( "End of imapsync_version_public\n" ) ;
  11838. }
  11839. alarm 0 ;
  11840. 1 ;
  11841. } ;
  11842. #myprint( "eval [$ret]\n" ) ;
  11843. if ( ( not $ret ) or $EVAL_ERROR ) {
  11844. #myprint( "$EVAL_ERROR" ) ;
  11845. if ($EVAL_ERROR =~ /alarm/) {
  11846. # timed out
  11847. return('timeout') ;
  11848. }else{
  11849. alarm 0 ;
  11850. return( 'unknown' ) ; # propagate unexpected errors
  11851. }
  11852. }else {
  11853. # Good!
  11854. return( $val ) ;
  11855. }
  11856. }
  11857. sub tests_not_long_imapsync_version_public
  11858. {
  11859. note( 'Entering tests_not_long_imapsync_version_public()' ) ;
  11860. is( 1, is_a_release_number( not_long_imapsync_version_public( ) ),
  11861. 'not_long_imapsync_version_public: public release is a number' ) ;
  11862. note( 'Leaving tests_not_long_imapsync_version_public()' ) ;
  11863. return ;
  11864. }
  11865. sub check_last_release
  11866. {
  11867. my $fake = shift ;
  11868. my $public_release = not_long_imapsync_version_public( $fake ) ;
  11869. $sync->{ debug } and myprint( "check_last_release: [$public_release]\n" ) ;
  11870. my $inline_help_when_on = '( Use --noreleasecheck to avoid this release check. )' ;
  11871. if ( $public_release eq 'unknown' ) {
  11872. return( 'Imapsync public release is unknown.' . $inline_help_when_on ) ;
  11873. }
  11874. if ( $public_release eq 'timeout' ) {
  11875. return( 'Imapsync public release is unknown (timeout).' . $inline_help_when_on ) ;
  11876. }
  11877. if ( ! is_a_release_number( $public_release ) ) {
  11878. return( "Imapsync public release is unknown ($public_release)." . $inline_help_when_on ) ;
  11879. }
  11880. my $imapsync_here = imapsync_version( $sync ) ;
  11881. if ( $public_release > $imapsync_here ) {
  11882. return( 'This imapsync is not up to date. ' . "( local $imapsync_here < official $public_release )" . $inline_help_when_on ) ;
  11883. }else{
  11884. return( 'This imapsync is up to date. ' . "( local $imapsync_here >= official $public_release )" . $inline_help_when_on ) ;
  11885. }
  11886. return( 'really unknown' ) ; # Should never arrive here
  11887. }
  11888. sub tests_check_last_release
  11889. {
  11890. note( 'Entering tests_check_last_release()' ) ;
  11891. diag( check_last_release( 1.1 ) ) ;
  11892. # \Q \E here to avoid putting \ before each space
  11893. like( check_last_release( 1.1 ), qr/\Qis up to date\E/mxs, 'check_last_release: up to date' ) ;
  11894. like( check_last_release( 1.1 ), qr/1\.1/mxs, 'check_last_release: up to date, include number' ) ;
  11895. diag( check_last_release( 999.999 ) ) ;
  11896. like( check_last_release( 999.999 ), qr/\Qnot up to date\E/mxs, 'check_last_release: not up to date' ) ;
  11897. like( check_last_release( 999.999 ), qr/999\.999/mxs, 'check_last_release: not up to date, include number' ) ;
  11898. like( check_last_release( 'unknown' ), qr/\QImapsync public release is unknown\E/mxs, 'check_last_release: unknown' ) ;
  11899. like( check_last_release( 'timeout' ), qr/\QImapsync public release is unknown (timeout)\E/mxs, 'check_last_release: timeout' ) ;
  11900. like( check_last_release( 'lalala' ), qr/\QImapsync public release is unknown (lalala)\E/mxs, 'check_last_release: lalala' ) ;
  11901. diag( check_last_release( ) ) ;
  11902. note( 'Leaving tests_check_last_release()' ) ;
  11903. return ;
  11904. }
  11905. sub tests_imapsync_context
  11906. {
  11907. note( 'Entering tests_imapsync_context()' ) ;
  11908. like( imapsync_context( ), qr/^CGI|^Docker|^DockerCGI|^Standard/, 'imapsync_context: CGI or Docker or DockerCGI or Standard' ) ;
  11909. note( 'Leaving tests_imapsync_context()' ) ;
  11910. return ;
  11911. }
  11912. sub imapsync_context
  11913. {
  11914. my $mysync = shift ;
  11915. my $context = q{} ;
  11916. if ( under_docker_context( $mysync ) && under_cgi_context( $mysync ) )
  11917. {
  11918. $context = 'DockerCGI' ;
  11919. }
  11920. elsif ( under_docker_context( $mysync ) )
  11921. {
  11922. $context = 'Docker' ;
  11923. }
  11924. elsif ( under_cgi_context( $mysync ) )
  11925. {
  11926. $context = 'CGI' ;
  11927. }
  11928. else
  11929. {
  11930. $context = 'Standard' ;
  11931. }
  11932. return $context ;
  11933. }
  11934. sub imapsync_version
  11935. {
  11936. my $mysync = shift ;
  11937. my $rcs = $mysync->{rcs} ;
  11938. my $version ;
  11939. $version = version_from_rcs( $rcs ) ;
  11940. return( $version ) ;
  11941. }
  11942. sub tests_version_from_rcs
  11943. {
  11944. note( 'Entering tests_version_from_rcs()' ) ;
  11945. is( undef, version_from_rcs( ), 'version_from_rcs: no args => undef' ) ;
  11946. 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' ) ;
  11947. is( 'UNKNOWN', version_from_rcs( 1.831 ), 'version_from_rcs: 1.831 => UNKNOWN' ) ;
  11948. note( 'Leaving tests_version_from_rcs()' ) ;
  11949. return ;
  11950. }
  11951. sub version_from_rcs
  11952. {
  11953. my $rcs = shift ;
  11954. if ( ! $rcs ) { return ; }
  11955. my $version = 'UNKNOWN' ;
  11956. if ( $rcs =~ m{,v\s+(\d+\.\d+)}mxso ) {
  11957. $version = $1
  11958. }
  11959. return( $version ) ;
  11960. }
  11961. sub tests_imapsync_basename
  11962. {
  11963. note( 'Entering tests_imapsync_basename()' ) ;
  11964. ok( imapsync_basename() =~ m/imapsync/, 'imapsync_basename: match imapsync');
  11965. ok( 'blabla' ne imapsync_basename(), 'imapsync_basename: do not equal blabla');
  11966. note( 'Leaving tests_imapsync_basename()' ) ;
  11967. return ;
  11968. }
  11969. sub imapsync_basename
  11970. {
  11971. return basename( $PROGRAM_NAME ) ;
  11972. }
  11973. sub localhost_info
  11974. {
  11975. my $mysync = shift ;
  11976. my( $infos ) = join( q{},
  11977. "Here is imapsync ", imapsync_version( $mysync ),
  11978. " on host " . hostname(),
  11979. ", a $OSNAME system with ",
  11980. ram_memory_info( ),
  11981. "\n",
  11982. 'with Perl ',
  11983. mysprintf( '%vd ', $PERL_VERSION),
  11984. "and Mail::IMAPClient $Mail::IMAPClient::VERSION",
  11985. ) ;
  11986. return( $infos ) ;
  11987. }
  11988. sub tests_cpu_number
  11989. {
  11990. note( 'Entering tests_cpu_number()' ) ;
  11991. is( 1, is_integer( cpu_number( ) ), "cpu_number: is_integer" ) ;
  11992. ok( 1 <= cpu_number( ), "cpu_number: 1 or more" ) ;
  11993. is( 1, cpu_number( 1 ), "cpu_number: 1 => 1" ) ;
  11994. is( 1, cpu_number( $MINUS_ONE ), "cpu_number: -1 => 1" ) ;
  11995. is( 1, cpu_number( 'lalala' ), "cpu_number: lalala => 1" ) ;
  11996. is( $NUMBER_42, cpu_number( $NUMBER_42 ), "cpu_number: $NUMBER_42 => $NUMBER_42" ) ;
  11997. note( "cpu_number = " . cpu_number( ) . "\n" ) ;
  11998. note( "hostname = " . hostname( ) . "\n" ) ;
  11999. SKIP: {
  12000. if ( ! ( 'i005' eq hostname() ) )
  12001. {
  12002. skip( 'cpu_number on host != i005 (FreeBSD)', 1 ) ;
  12003. }
  12004. is( 4, cpu_number( ), "cpu_number: on i005 (FreeBSD) => 4" ) ;
  12005. } ;
  12006. SKIP: {
  12007. if ( ! ( 'petite' eq hostname() ) )
  12008. {
  12009. skip( 'cpu_number on host != petite (Linux)', 1 ) ;
  12010. }
  12011. is( 2, cpu_number( ), "cpu_number: on petite (Linux) => 2" ) ;
  12012. } ;
  12013. SKIP: {
  12014. if ( ! ( skip_macosx( ) ) )
  12015. {
  12016. skip( 'cpu_number on host != polarhome macosx (Darwin MacOS X 10.7.5 Lion)', 1 ) ;
  12017. }
  12018. is( 2, cpu_number( ), "cpu_number: on polarhome macosx (Darwin MacOS X 10.7.5 Lion) => 2" ) ;
  12019. } ;
  12020. SKIP: {
  12021. if ( ! ( 'pcHPDV7-HP' eq hostname() ) )
  12022. {
  12023. skip( 'cpu_number on host != pcHPDV7-HP (Windows 7, 64bits)', 1 ) ;
  12024. }
  12025. is( 2, cpu_number( ), "cpu_number: on pcHPDV7-HP (Windows 7, 64bits) => 2" ) ;
  12026. } ;
  12027. SKIP: {
  12028. if ( ! ( 'CUILLERE' eq hostname() ) )
  12029. {
  12030. skip( 'cpu_number on host != CUILLERE (Windows XP, 32bits)', 1 ) ;
  12031. }
  12032. is( 1, cpu_number( ), "cpu_number: on CUILLERE (Windows XP, 32bits) => 1" ) ;
  12033. } ;
  12034. note( 'Leaving tests_cpu_number()' ) ;
  12035. return ;
  12036. }
  12037. sub cpu_number {
  12038. my $cpu_number_forced = shift ;
  12039. # Well, here 1 is better than 0 or undef
  12040. my $cpu_number = 1 ; # Default value, erased if better found
  12041. my @cpuinfo ;
  12042. if ( $ENV{"NUMBER_OF_PROCESSORS"} )
  12043. {
  12044. # might be under a Windows system
  12045. $cpu_number = $ENV{"NUMBER_OF_PROCESSORS"} ;
  12046. #myprint( "Number of processors found by env var NUMBER_OF_PROCESSORS: $cpu_number\n" ) ;
  12047. }
  12048. if ( 'darwin' eq $OSNAME )
  12049. {
  12050. $cpu_number = backtick( "sysctl -n hw.ncpu" ) ;
  12051. chomp( $cpu_number ) ;
  12052. #myprint( "Number of processors found by cmd 'sysctl -n hw.ncpu': $cpu_number\n" ) ;
  12053. }
  12054. if ( 'freebsd' eq $OSNAME )
  12055. {
  12056. $cpu_number = backtick( "sysctl -n kern.smp.cpus" ) ;
  12057. chomp( $cpu_number ) ;
  12058. #myprint( "Number of processors found by cmd 'sysctl -n kern.smp.cpus': $cpu_number\n" ) ;
  12059. }
  12060. if ( 'linux' eq $OSNAME && -e '/proc/cpuinfo' )
  12061. {
  12062. @cpuinfo = file_to_array( '/proc/cpuinfo' ) ;
  12063. $cpu_number = grep { /^processor/mxs } @cpuinfo ;
  12064. #myprint( "Number of processors found via /proc/cpuinfo: $cpu_number\n" ) ;
  12065. }
  12066. if ( defined $cpu_number_forced )
  12067. {
  12068. $cpu_number = $cpu_number_forced ;
  12069. }
  12070. return( integer_or_1( $cpu_number ) ) ;
  12071. }
  12072. sub tests_integer_or_1
  12073. {
  12074. note( 'Entering tests_integer_or_1()' ) ;
  12075. is( 1, integer_or_1( ), 'integer_or_1: no args => 1' ) ;
  12076. is( 1, integer_or_1( undef ), 'integer_or_1: undef => 1' ) ;
  12077. is( $NUMBER_10, integer_or_1( $NUMBER_10 ), 'integer_or_1: 10 => 10' ) ;
  12078. is( 1, integer_or_1( q{} ), 'integer_or_1: empty string => 1' ) ;
  12079. is( 1, integer_or_1( 'lalala' ), 'integer_or_1: lalala => 1' ) ;
  12080. note( 'Leaving tests_integer_or_1()' ) ;
  12081. return ;
  12082. }
  12083. sub integer_or_1
  12084. {
  12085. my $number = shift ;
  12086. if ( is_integer( $number ) ) {
  12087. return $number ;
  12088. }
  12089. # else
  12090. return 1 ;
  12091. }
  12092. sub tests_is_integer
  12093. {
  12094. note( 'Entering tests_is_integer()' ) ;
  12095. is( undef, is_integer( ), 'is_integer: no args => undef ' ) ;
  12096. ok( is_integer( 1 ), 'is_integer: 1 => yes ') ;
  12097. ok( is_integer( $NUMBER_42 ), 'is_integer: 42 => yes ') ;
  12098. ok( is_integer( "$NUMBER_42" ), 'is_integer: "$NUMBER_42" => yes ') ;
  12099. ok( is_integer( '42' ), 'is_integer: "42" => yes ') ;
  12100. ok( is_integer( $NUMBER_104_857_600 ), 'is_integer: 104_857_600 => yes') ;
  12101. ok( is_integer( "$NUMBER_104_857_600" ), 'is_integer: "$NUMBER_104_857_600" => yes') ;
  12102. ok( is_integer( '104857600' ), 'is_integer: 104857600 => yes') ;
  12103. ok( ! is_integer( 'blabla' ), 'is_integer: blabla => no' ) ;
  12104. ok( ! is_integer( q{} ), 'is_integer: empty string => no' ) ;
  12105. note( 'Leaving tests_is_integer()' ) ;
  12106. return ;
  12107. }
  12108. sub is_integer
  12109. {
  12110. my $number = shift ;
  12111. if ( ! defined $number ) { return ; }
  12112. return( $number =~ m{^\d+$}xo ) ;
  12113. }
  12114. sub tests_loadavg
  12115. {
  12116. note( 'Entering tests_loadavg()' ) ;
  12117. SKIP: {
  12118. skip( 'Tests for darwin', 2 ) if ('darwin' ne $OSNAME) ;
  12119. is( undef, loadavg( '/noexist' ), 'loadavg: /noexist => undef' ) ;
  12120. is_deeply( [ '0.11', '0.22', '0.33' ],
  12121. [ loadavg( 'W/t/loadavg.out' ) ],
  12122. 'loadavg W/t/loadavg.out => 0.11 0.22 0.33' ) ;
  12123. } ;
  12124. SKIP: {
  12125. skip( 'Tests for linux', 3 ) if ('linux' ne $OSNAME) ;
  12126. is( undef, loadavg( '/noexist' ), 'loadavg: /noexist => undef' ) ;
  12127. ok( loadavg( ), 'loadavg: no args' ) ;
  12128. is_deeply( [ '0.39', '0.30', '0.37', '1/602' ],
  12129. [ loadavg( '0.39 0.30 0.37 1/602 6073' ) ],
  12130. 'loadavg 0.39 0.30 0.37 1/602 6073 => [0.39, 0.30, 0.37, 1/602]' ) ;
  12131. } ;
  12132. SKIP: {
  12133. skip( 'Tests for Windows', 1 ) if ('MSWin32' ne $OSNAME) ;
  12134. is_deeply( [ 0 ],
  12135. [ loadavg( ) ],
  12136. 'loadavg on MSWin32 => 0' ) ;
  12137. } ;
  12138. note( 'Leaving tests_loadavg()' ) ;
  12139. return ;
  12140. }
  12141. sub loadavg
  12142. {
  12143. if ( 'linux' eq $OSNAME ) {
  12144. return ( loadavg_linux( @ARG ) ) ;
  12145. }
  12146. if ( 'freebsd' eq $OSNAME ) {
  12147. return ( loadavg_freebsd( @ARG ) ) ;
  12148. }
  12149. if ( 'darwin' eq $OSNAME ) {
  12150. return ( loadavg_darwin( @ARG ) ) ;
  12151. }
  12152. if ( 'MSWin32' eq $OSNAME ) {
  12153. return ( loadavg_windows( @ARG ) ) ;
  12154. }
  12155. return( 'unknown' ) ;
  12156. }
  12157. sub loadavg_linux
  12158. {
  12159. my $line = shift ;
  12160. if ( ! $line ) {
  12161. $line = firstline( '/proc/loadavg' ) or return ;
  12162. }
  12163. my ( $avg_1_min, $avg_5_min, $avg_15_min, $current_runs ) = split /\s/mxs, $line ;
  12164. if ( all_defined( $avg_1_min, $avg_5_min, $avg_15_min ) ) {
  12165. $sync->{ debug } and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min $current_runs\n" ) ;
  12166. return ( $avg_1_min, $avg_5_min, $avg_15_min, $current_runs ) ;
  12167. }
  12168. return ;
  12169. }
  12170. sub loadavg_freebsd
  12171. {
  12172. my $file = shift ;
  12173. # Example of output of command "sysctl vm.loadavg":
  12174. # vm.loadavg: { 0.15 0.08 0.08 }
  12175. my $loadavg ;
  12176. if ( ! defined $file ) {
  12177. eval {
  12178. $loadavg = `/sbin/sysctl vm.loadavg` ;
  12179. #myprint( "LOADAVG FREEBSD: $loadavg\n" ) ;
  12180. } ;
  12181. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  12182. }else{
  12183. $loadavg = firstline( $file ) or return ;
  12184. }
  12185. my ( $avg_1_min, $avg_5_min, $avg_15_min )
  12186. = $loadavg =~ /vm\.loadavg\s*[:=]\s*\{?\s*(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)/mxs ;
  12187. $sync->{ debug } and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min\n" ) ;
  12188. return ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  12189. }
  12190. sub loadavg_darwin
  12191. {
  12192. my $file = shift ;
  12193. # Example of output of command "sysctl vm.loadavg":
  12194. # vm.loadavg: { 0.15 0.08 0.08 }
  12195. my $loadavg ;
  12196. if ( ! defined $file ) {
  12197. eval {
  12198. $loadavg = `/usr/sbin/sysctl vm.loadavg` ;
  12199. #myprint( "LOADAVG DARWIN: $loadavg\n" ) ;
  12200. } ;
  12201. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  12202. }else{
  12203. $loadavg = firstline( $file ) or return ;
  12204. }
  12205. my ( $avg_1_min, $avg_5_min, $avg_15_min )
  12206. = $loadavg =~ /vm\.loadavg\s*[:=]\s*\{?\s*(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)/mxs ;
  12207. $sync->{ debug } and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min\n" ) ;
  12208. return ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  12209. }
  12210. sub loadavg_windows
  12211. {
  12212. my $file = shift ;
  12213. # Example of output of command "wmic cpu get loadpercentage":
  12214. # LoadPercentage
  12215. # 12
  12216. my $loadavg ;
  12217. if ( ! defined $file ) {
  12218. eval {
  12219. #$loadavg = `CMD wmic cpu get loadpercentage` ;
  12220. $loadavg = "LoadPercentage\n0\n" ;
  12221. #myprint( "LOADAVG WIN: $loadavg\n" ) ;
  12222. } ;
  12223. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  12224. }else{
  12225. $loadavg = file_to_string( $file ) or return ;
  12226. #myprint( "$loadavg" ) ;
  12227. }
  12228. $loadavg =~ /LoadPercentage\n(\d+)/xms ;
  12229. my $num = $1 ;
  12230. $num /= 100 ;
  12231. $sync->{ debug } and myprint( "System load: $num\n" ) ;
  12232. return ( $num ) ;
  12233. }
  12234. sub tests_load_and_delay
  12235. {
  12236. note( 'Entering tests_load_and_delay()' ) ;
  12237. is( undef, load_and_delay( ), 'load_and_delay: no args => undef ' ) ;
  12238. is( undef, load_and_delay( 1 ), 'load_and_delay: not 4 args => undef ' ) ;
  12239. is( undef, load_and_delay( 0, 1, 1, 1 ), 'load_and_delay: division per 0 => undef ' ) ;
  12240. # ( $cpu_num, $avg_1_min, $avg_5_min, $avg_15_min )
  12241. is( 0, load_and_delay( 1, 1, 1, 1 ), 'load_and_delay: one core, loads are all 1 => ok ' ) ;
  12242. is( 0, load_and_delay( 1, 1, 1, 1, 'lalala' ), 'load_and_delay: five arguments is ok' ) ;
  12243. is( 0, load_and_delay( 2, 2, 2, 2 ), 'load_and_delay: two core, loads are all 2 => ok ' ) ;
  12244. is( 0, load_and_delay( 2, 2, 4, 5 ), 'load_and_delay: two core, load1m is 2 => ok ' ) ;
  12245. is( 0, load_and_delay( 1, 0, 0, 0 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=0 => 0 ' ) ;
  12246. is( 0, load_and_delay( 1, 0, 0, 2 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=2 => 0 ' ) ;
  12247. is( 0, load_and_delay( 1, 0, 2, 0 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=0 => 0 ' ) ;
  12248. is( 0, load_and_delay( 1, 0, 2, 2 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=2 => 0 ' ) ;
  12249. is( 0, load_and_delay( 1, 0, 3, 3 ), 'load_and_delay: one core, load1m=0 load5m=3 load15m=3 => 0 ' ) ;
  12250. is( 0, load_and_delay( 1, 0, 4, 4 ), 'load_and_delay: one core, load1m=0 load5m=3 load15m=3 => 0 ' ) ;
  12251. is( 0, load_and_delay( 1, 2, 0, 0 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=0 => 0 ' ) ;
  12252. is( 0, load_and_delay( 1, 2, 0, 2 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=2 => 0 ' ) ;
  12253. is( 0, load_and_delay( 1, 2, 2, 0 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=0 => 0 ' ) ;
  12254. is( 0, load_and_delay( 1, 2, 2, 2 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=2 => 0 ' ) ;
  12255. is( 0, load_and_delay( 1, 2.9, 2.9, 2.9 ), 'load_and_delay: one core, load1m=2.9 load5m=2.9 load15m=2.9 => 0 ' ) ;
  12256. is( 0, load_and_delay( 1, 3, 0, 0 ), 'load_and_delay: one core, load1m=3 load5m=0 load15m=0 => 0 ' ) ;
  12257. is( 0, load_and_delay( 1, 3, 2.9, 2.9 ), 'load_and_delay: one core, load1m=3 load5m=2.9 load15m=2.9 => 0 ' ) ;
  12258. is( 0, load_and_delay( 1, 3, 3, 2.9 ), 'load_and_delay: one core, load1m=3 load5m=3 load15m=2.9 => 0 ' ) ;
  12259. is( 0, load_and_delay( 1, 3, 3, 3 ), 'load_and_delay: one core, load1m=3 load5m=3 load15m=3 => 0 ' ) ;
  12260. is( 1, load_and_delay( 1, 6, 0, 0 ), 'load_and_delay: one core, load1m=3 load5m=0 load15m=0 => 1 ' ) ;
  12261. is( 1, load_and_delay( 1, 6, 5.9, 5.9 ), 'load_and_delay: one core, load1m=3 load5m=2.9 load15m=2.9 => 1 ' ) ;
  12262. is( 5, load_and_delay( 1, 6, 6, 5.9 ), 'load_and_delay: one core, load1m=3 load5m=3 load15m=2.9 => 5 ' ) ;
  12263. is( 15, load_and_delay( 1, 6, 6, 6 ), 'load_and_delay: one core, load1m=3 load5m=3 load15m=3 => 15 ' ) ;
  12264. note( 'Leaving tests_load_and_delay()' ) ;
  12265. return ;
  12266. }
  12267. sub load_and_delay
  12268. {
  12269. # Basically return 0 if load is not heavy, ie <= 1 per processor
  12270. # Not enough arguments
  12271. if ( 4 > scalar @ARG ) { return ; }
  12272. my ( $cpu_num, $avg_1_min, $avg_5_min, $avg_15_min ) = @ARG ;
  12273. if ( 0 == $cpu_num ) { return ; }
  12274. # Let divide by number of cores
  12275. ( $avg_1_min, $avg_5_min, $avg_15_min ) = map { $_ / $cpu_num } ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  12276. # One of avg ok => ok, for now it is a OR
  12277. if ( $avg_1_min < 6 ) { return 0 ; }
  12278. if ( $avg_5_min < 6 ) { return 1 ; } # Retry in 1 minute
  12279. if ( $avg_15_min < 6 ) { return 5 ; } # Retry in 5 minutes
  12280. return 15 ; # Retry in 15 minutes
  12281. }
  12282. sub tests_cpu_time
  12283. {
  12284. note( 'Entering tests_cpu_time()' ) ;
  12285. ok( is_number( cpu_time( ) ), 'cpu_time: no args => a number' ) ;
  12286. my $mysync = { } ;
  12287. $mysync->{ debug } = 1 ;
  12288. ok( is_number( cpu_time( $mysync ) ), 'cpu_time: {} => a number' ) ;
  12289. note( 'Leaving tests_cpu_time()' ) ;
  12290. return ;
  12291. }
  12292. sub cpu_time
  12293. {
  12294. my $mysync = shift ;
  12295. my @cpu_times = times ;
  12296. if ( ! @cpu_times ) { return ; }
  12297. my $cpu_time = 0 ;
  12298. # last element is the sum of all elements
  12299. $cpu_time = ( map { $cpu_time += $_ } @cpu_times )[ -1 ] ;
  12300. $mysync->{ debug } and myprint( join(' + ', @cpu_times), " = $cpu_time\n" ) ;
  12301. return $cpu_time ;
  12302. }
  12303. sub tests_cpu_percent
  12304. {
  12305. note( 'Entering tests_cpu_percent()' ) ;
  12306. is( '0.0', cpu_percent( ), 'cpu_percent: no args => 0.0' ) ;
  12307. my $mysync = { } ;
  12308. $mysync->{ debug } = 1 ;
  12309. is( '0.0', cpu_percent( $mysync ), 'cpu_percent: {} => 0.0' ) ;
  12310. is( '0.0', cpu_percent( $mysync, 0 ), 'cpu_percent: {} 0 => 0.0' ) ;
  12311. is( '300.0', cpu_percent( $mysync, 3 ), 'cpu_percent: {} 3 => 300.0' ) ;
  12312. is( '30.0', cpu_percent( $mysync, 3, 10 ), 'cpu_percent: {} 3 10 => 30.0' ) ;
  12313. is( '0.0', cpu_percent( $mysync, 0, 10 ), 'cpu_percent: {} 0 10 => 0.0' ) ;
  12314. note( 'Leaving tests_cpu_percent()' ) ;
  12315. return ;
  12316. }
  12317. sub cpu_percent
  12318. {
  12319. my $mysync = shift ;
  12320. my $cpu_time = shift || 0 ;
  12321. my $timediff = shift || 1 ; # no division by 0
  12322. if ( $cpu_time > $timediff )
  12323. {
  12324. myprint( "Strange: cpu_time $cpu_time > timediff $timediff\n" ) ;
  12325. }
  12326. my $cpu_percent = 0 ;
  12327. $cpu_percent = mysprintf( '%.1f', 100 * $cpu_time / $timediff ) ;
  12328. $mysync->{ debug } and myprint( "cpu_percent: $cpu_percent \n" ) ;
  12329. return $cpu_percent ;
  12330. }
  12331. sub tests_cpu_percent_global
  12332. {
  12333. note( 'Entering tests_cpu_percent_global()' ) ;
  12334. is( '0.0', cpu_percent_global( ), 'cpu_percent_global: no args => 0' ) ;
  12335. my $mysync = { } ;
  12336. $mysync->{ debug } = 1 ;
  12337. is( '0.0', cpu_percent_global( $mysync ), 'cpu_percent_global: {} => 0' ) ;
  12338. is( '0.0', cpu_percent_global( $mysync, 0 ), 'cpu_percent_global: {} 0 => 0' ) ;
  12339. SKIP: {
  12340. if ( ! ( 'i005' eq hostname() ) )
  12341. {
  12342. skip( 'cpu_percent_global on host != i005', 1 ) ;
  12343. }
  12344. is( '25.0', cpu_percent_global( $mysync, 100 ), 'cpu_percent_global: {} 100 => 25 on host i005' ) ;
  12345. } ;
  12346. SKIP: {
  12347. if ( ! ( 'petite' eq hostname() ) )
  12348. {
  12349. skip( 'cpu_percent_global on host != petite', 1 ) ;
  12350. }
  12351. is( '50.0', cpu_percent_global( $mysync, 100 ), 'cpu_percent_global: {} 100 => 50 on host petite' ) ;
  12352. } ;
  12353. note( 'Leaving tests_cpu_percent_global()' ) ;
  12354. return ;
  12355. }
  12356. sub cpu_percent_global
  12357. {
  12358. my $mysync = shift ;
  12359. my $cpu_percent = shift || 0 ;
  12360. my $cpu_number = cpu_number( ) ;
  12361. my $cpu_percent_global ;
  12362. $cpu_percent_global = mysprintf( '%.1f', $cpu_percent / $cpu_number ) ;
  12363. $mysync->{ debug } and myprint( "cpu_percent_global: $cpu_percent_global \n" ) ;
  12364. return( $cpu_percent_global ) ;
  12365. }
  12366. sub ram_memory_info
  12367. {
  12368. # In GigaBytes so division by 1024 * 1024 * 1024
  12369. #
  12370. return(
  12371. sprintf( "%.1f/%.1f free GiB of RAM",
  12372. Sys::MemInfo::get("freemem") / ( $KIBI ** 3 ),
  12373. Sys::MemInfo::get("totalmem") / ( $KIBI ** 3 ),
  12374. )
  12375. ) ;
  12376. }
  12377. sub tests_memory_stress
  12378. {
  12379. note( 'Entering tests_memory_stress()' ) ;
  12380. is( undef, memory_stress( ), 'memory_stress: => undef' ) ;
  12381. note( 'Leaving tests_memory_stress()' ) ;
  12382. return ;
  12383. }
  12384. sub memory_stress
  12385. {
  12386. my $total_ram_in_MB = Sys::MemInfo::get("totalmem") / ( $KIBI * $KIBI ) ;
  12387. my $i = 1 ;
  12388. myprintf("Stress memory consumption before: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  12389. while ( $i < $total_ram_in_MB / 1.7 ) { $a .= "A" x 1000_000; $i++ } ;
  12390. myprintf("Stress memory consumption after: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  12391. return ;
  12392. }
  12393. sub tests_memory_consumption
  12394. {
  12395. note( 'Entering tests_memory_consumption()' ) ;
  12396. like( memory_consumption( ), qr{\d+}xms,'memory_consumption no args') ;
  12397. like( memory_consumption( 1 ), qr{\d+}xms,'memory_consumption 1') ;
  12398. like( memory_consumption( $PROCESS_ID ), qr{\d+}xms,"memory_consumption_of_pids $PROCESS_ID") ;
  12399. like( memory_consumption_ratio(), qr{\d+}xms, 'memory_consumption_ratio' ) ;
  12400. like( memory_consumption_ratio(1), qr{\d+}xms, 'memory_consumption_ratio 1' ) ;
  12401. like( memory_consumption_ratio(10), qr{\d+}xms, 'memory_consumption_ratio 10' ) ;
  12402. like( memory_consumption(), qr{\d+}xms, "memory_consumption\n" ) ;
  12403. note( 'Leaving tests_memory_consumption()' ) ;
  12404. return ;
  12405. }
  12406. sub memory_consumption
  12407. {
  12408. # memory consumed by imapsync until now in bytes
  12409. return( ( memory_consumption_of_pids( ) )[0] );
  12410. }
  12411. sub debugmemory
  12412. {
  12413. my $mysync = shift ;
  12414. if ( ! $mysync->{debugmemory} ) { return q{} ; }
  12415. my $precision = shift ;
  12416. return( mysprintf( "Memory consumption$precision: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ) ;
  12417. }
  12418. sub memory_consumption_of_pids
  12419. {
  12420. my @pid = @_;
  12421. @pid = ( @pid ) ? @pid : ( $PROCESS_ID ) ;
  12422. $sync->{ debug } and myprint( "memory_consumption_of_pids PIDs: @pid\n" ) ;
  12423. my @val ;
  12424. if ( ( 'MSWin32' eq $OSNAME ) or ( 'cygwin' eq $OSNAME ) ) {
  12425. @val = memory_consumption_of_pids_win32( @pid ) ;
  12426. }else{
  12427. # Unix
  12428. my @ps = qx{ ps -o vsz -p @pid } ;
  12429. #myprint( "ps: @ps" ) ;
  12430. # Use IPC::Open3 from perlcrit -3
  12431. # But it stalls on Darwin, I don't understand why!
  12432. #my @ps = backtick( "ps -o vsz -p @pid" ) ;
  12433. #myprint( "ps: @ps" ) ;
  12434. shift @ps; # First line is column name "VSZ"
  12435. chomp @ps;
  12436. # convert to octets
  12437. @val = map { $_ * $KIBI } @ps ;
  12438. }
  12439. $sync->{ debug } and myprint( "@val\n" ) ;
  12440. return( @val ) ;
  12441. }
  12442. sub memory_consumption_of_pids_win32
  12443. {
  12444. # Windows
  12445. my @PID = @_;
  12446. my %PID;
  12447. # hash of pids as key values
  12448. map { $PID{$_}++ } @PID;
  12449. # Does not work but should work reading the tasklist documentation
  12450. #@ps = qx{ tasklist /FI "PID eq @PID" };
  12451. my @ps = qx{ tasklist /NH /FO CSV } ;
  12452. #my @ps = backtick( 'tasklist /NH /FO CSV' ) ;
  12453. #myprint( "-" x $STD_CHAR_PER_LINE, "\n", @ps, "-" x $STD_CHAR_PER_LINE, "\n" ) ;
  12454. my @val;
  12455. foreach my $line (@ps) {
  12456. my($name, $pid, $mem) = (split ',', $line )[0,1,4];
  12457. next if (! $pid);
  12458. #myprint( "[$name][$pid][$mem]" ) ;
  12459. if ($PID{remove_qq($pid)}) {
  12460. #myprint( "MATCH !\n" ) ;
  12461. chomp $mem ;
  12462. $mem = remove_qq($mem);
  12463. $mem = remove_Ko($mem);
  12464. $mem = remove_not_num($mem);
  12465. #myprint( "[$mem]\n" ) ;
  12466. push @val, $mem * $KIBI;
  12467. }
  12468. }
  12469. return(@val);
  12470. }
  12471. sub tests_backtick
  12472. {
  12473. note( 'Entering tests_backtick()' ) ;
  12474. is( undef, backtick( ), 'backtick: no args' ) ;
  12475. is( undef, backtick( q{} ), 'backtick: empty command' ) ;
  12476. SKIP: {
  12477. skip( 'test for MSWin32', 5 ) if ('MSWin32' ne $OSNAME) ;
  12478. my @output ;
  12479. @output = backtick( 'echo Hello World!' ) ;
  12480. # Add \r on Windows.
  12481. ok( "Hello World!\r\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  12482. $sync->{ debug } and myprint( "[@output]" ) ;
  12483. @output = backtick( 'echo Hello & echo World!' ) ;
  12484. ok( "Hello \r\n" eq $output[0], 'backtick: echo Hello & echo World! line 1' ) ;
  12485. ok( "World!\r\n" eq $output[1], 'backtick: echo Hello & echo World! line 2' ) ;
  12486. $sync->{ debug } and myprint( "[@output][$output[0]][$output[1]]" ) ;
  12487. # Scalar context
  12488. ok( "Hello World!\r\n" eq backtick( 'echo Hello World!' ),
  12489. 'backtick: echo Hello World! scalar' ) ;
  12490. ok( "Hello \r\nWorld!\r\n" eq backtick( 'echo Hello & echo World!' ),
  12491. 'backtick: echo Hello & echo World! scalar 2 lines' ) ;
  12492. } ;
  12493. SKIP: {
  12494. skip( 'test for Unix', 7 ) if ('MSWin32' eq $OSNAME) ;
  12495. is( undef, backtick( 'aaaarrrg' ), 'backtick: aaaarrrg command not found' ) ;
  12496. # Array context
  12497. my @output ;
  12498. @output = backtick( 'echo Hello World!' ) ;
  12499. ok( "Hello World!\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  12500. $sync->{ debug } and myprint( "[@output]" ) ;
  12501. @output = backtick( "echo Hello\necho World!" ) ;
  12502. ok( "Hello\n" eq $output[0], 'backtick: echo Hello; echo World! line 1' ) ;
  12503. ok( "World!\n" eq $output[1], 'backtick: echo Hello; echo World! line 2' ) ;
  12504. $sync->{ debug } and myprint( "[@output]" ) ;
  12505. # Scalar context
  12506. ok( "Hello World!\n" eq backtick( 'echo Hello World!' ),
  12507. 'backtick: echo Hello World! scalar' ) ;
  12508. ok( "Hello\nWorld!\n" eq backtick( "echo Hello\necho World!" ),
  12509. 'backtick: echo Hello; echo World! scalar 2 lines' ) ;
  12510. # Return error positive value, that's ok
  12511. is( undef, backtick( 'false' ), 'backtick: false returns no output' ) ;
  12512. my $mem = backtick( "ps -o vsz -p $PROCESS_ID" ) ;
  12513. $sync->{ debug } and myprint( "MEM=$mem\n" ) ;
  12514. }
  12515. note( 'Leaving tests_backtick()' ) ;
  12516. return ;
  12517. }
  12518. sub backtick
  12519. {
  12520. my $command = shift ;
  12521. if ( ! $command ) { return ; }
  12522. my ( $writer, $reader, $err ) ;
  12523. my @output ;
  12524. my $pid ;
  12525. my $eval = eval {
  12526. $pid = IPC::Open3::open3( $writer, $reader, $err, $command ) ;
  12527. } ;
  12528. if ( $EVAL_ERROR ) {
  12529. myprint( $EVAL_ERROR ) ;
  12530. return ;
  12531. }
  12532. if ( ! $eval ) { return ; }
  12533. if ( ! $pid ) { return ; }
  12534. waitpid( $pid, 0 ) ;
  12535. @output = <$reader>; # Output here
  12536. #
  12537. #my @errors = <$err>; #Errors here, instead of the console
  12538. if ( not @output ) { return ; }
  12539. #myprint( @output ) ;
  12540. if ( $output[0] =~ /\Qopen3: exec of $command failed\E/mxs ) { return ; }
  12541. if ( wantarray ) {
  12542. return( @output ) ;
  12543. } else {
  12544. return( join( q{}, @output) ) ;
  12545. }
  12546. }
  12547. sub tests_check_binary_embed_all_dyn_libs
  12548. {
  12549. note( 'Entering tests_check_binary_embed_all_dyn_libs()' ) ;
  12550. is( 1, check_binary_embed_all_dyn_libs( ), 'check_binary_embed_all_dyn_libs: no args => 1' ) ;
  12551. note( 'Leaving tests_check_binary_embed_all_dyn_libs()' ) ;
  12552. return ;
  12553. }
  12554. sub check_binary_embed_all_dyn_libs
  12555. {
  12556. my @search_dyn_lib_locale = search_dyn_lib_locale( ) ;
  12557. if ( @search_dyn_lib_locale )
  12558. {
  12559. myprint( "Found myself $PROGRAM_NAME pid $PROCESS_ID using locale dynamic libraries that seems out of myself:\n" ) ;
  12560. myprint( @search_dyn_lib_locale ) ;
  12561. if ( $PROGRAM_NAME =~ m{imapsync_bin_Darwin} )
  12562. {
  12563. return 0 ;
  12564. }
  12565. elsif ( $PROGRAM_NAME =~ m{imapsync.*\.exe} )
  12566. {
  12567. return 0 ;
  12568. }
  12569. else
  12570. {
  12571. # is always ok for non binary
  12572. return 1 ;
  12573. }
  12574. }
  12575. else
  12576. {
  12577. # Found only embedded dynamic lib
  12578. myprint( "Found only embedded dynamic lib. Good!\n" ) ;
  12579. return 1 ;
  12580. }
  12581. }
  12582. sub search_dyn_lib_locale
  12583. {
  12584. if ( 'darwin' eq $OSNAME )
  12585. {
  12586. return search_dyn_lib_locale_darwin( ) ;
  12587. }
  12588. if ( 'linux' eq $OSNAME )
  12589. {
  12590. return search_dyn_lib_locale_linux( ) ;
  12591. }
  12592. if ( 'MSWin32' eq $OSNAME )
  12593. {
  12594. return search_dyn_lib_locale_MSWin32( ) ;
  12595. }
  12596. }
  12597. sub search_dyn_lib_locale_darwin
  12598. {
  12599. my $command = qq{ lsof -p $PROCESS_ID | grep ' REG ' | grep .dylib | grep -v '/par-' } ;
  12600. myprint( "Search non embeded dynamic libs with the command: $command\n" ) ;
  12601. return backtick( $command ) ;
  12602. }
  12603. sub search_dyn_lib_locale_linux
  12604. {
  12605. my $command = qq{ lsof -p $PROCESS_ID | grep ' REG ' | grep -v '/tmp/par-' | grep '\.so' } ;
  12606. myprint( "Search non embeded dynamic libs with the command: $command\n" ) ;
  12607. return backtick( $command ) ;
  12608. }
  12609. sub search_dyn_lib_locale_MSWin32
  12610. {
  12611. my $command = qq{ Listdlls.exe $PROCESS_ID|findstr Strawberry } ;
  12612. # $command = qq{ Listdlls.exe $PROCESS_ID|findstr Strawberry } ;
  12613. myprint( "Search non embeded dynamic libs with the command: $command\n" ) ;
  12614. return qx( $command ) ;
  12615. }
  12616. sub remove_not_num
  12617. {
  12618. my $string = shift ;
  12619. $string =~ tr/0-9//cd ;
  12620. #myprint( "tr [$string]\n" ) ;
  12621. return( $string ) ;
  12622. }
  12623. sub tests_remove_not_num
  12624. {
  12625. note( 'Entering tests_remove_not_num()' ) ;
  12626. ok( '123' eq remove_not_num( 123 ), 'remove_not_num( 123 )' ) ;
  12627. ok( '123' eq remove_not_num( '123' ), q{remove_not_num( '123' )} ) ;
  12628. ok( '123' eq remove_not_num( '12 3' ), q{remove_not_num( '12 3' )} ) ;
  12629. ok( '123' eq remove_not_num( 'a 12 3 Ko' ), q{remove_not_num( 'a 12 3 Ko' )} ) ;
  12630. note( 'Leaving tests_remove_not_num()' ) ;
  12631. return ;
  12632. }
  12633. sub remove_Ko
  12634. {
  12635. my $string = shift;
  12636. if ($string =~ /^(.*)\sKo$/xo) {
  12637. return($1);
  12638. }else{
  12639. return($string);
  12640. }
  12641. }
  12642. sub remove_qq
  12643. {
  12644. my $string = shift;
  12645. if ($string =~ /^"(.*)"$/xo) {
  12646. return($1);
  12647. }else{
  12648. return($string);
  12649. }
  12650. }
  12651. sub memory_consumption_ratio
  12652. {
  12653. my ($base) = @_;
  12654. $base ||= 1;
  12655. my $consu = memory_consumption();
  12656. return($consu / $base);
  12657. }
  12658. sub date_from_rcs
  12659. {
  12660. my $d = shift ;
  12661. 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 ) ;
  12662. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  12663. # Handles the following format
  12664. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  12665. #myprint( "$d\n" ) ;
  12666. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  12667. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  12668. $month = $num2mon{$month} ;
  12669. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  12670. #myprint( "$d\n" ) ;
  12671. }
  12672. return( $d ) ;
  12673. }
  12674. sub tests_date_from_rcs
  12675. {
  12676. note( 'Entering tests_date_from_rcs()' ) ;
  12677. ok('19-Sep-2015 16:11:07 +0000'
  12678. eq date_from_rcs('Date: 2015/09/19 16:11:07 '), 'date_from_rcs from RCS date' ) ;
  12679. note( 'Leaving tests_date_from_rcs()' ) ;
  12680. return ;
  12681. }
  12682. sub good_date
  12683. {
  12684. # two incoming formats:
  12685. # header Tue, 24 Aug 2010 16:00:00 +0200
  12686. # internal 24-Aug-2010 16:00:00 +0200
  12687. # outgoing format: internal date format
  12688. # 24-Aug-2010 16:00:00 +0200
  12689. my $d = shift ;
  12690. return(q{}) if not defined $d;
  12691. SWITCH: {
  12692. if ( $d =~ m{(\d?)(\d-...-\d{4})(\s\d{2}:\d{2}:\d{2})(\s(?:\+|-)\d{4})?}xo ) {
  12693. #myprint( "internal: [$1][$2][$3][$4]\n" ) ;
  12694. my ($day_1, $date_rest, $hour, $zone) = ($1,$2,$3,$4) ;
  12695. $day_1 = '0' if ($day_1 eq q{}) ;
  12696. $zone = ' +0000' if not defined $zone ;
  12697. $d = $day_1 . $date_rest . $hour . $zone ;
  12698. last SWITCH ;
  12699. }
  12700. 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 ) {
  12701. # Handles any combination of following formats
  12702. # Tue, 24 Aug 2010 16:00:00 +0200 -- Standard
  12703. # 24 Aug 2010 16:00:00 +0200 -- Missing Day of Week
  12704. # Tue, 24 Aug 97 16:00:00 +0200 -- Two digit year
  12705. # Tue, 24 Aug 1997 16.00.00 +0200 -- Periods instead of colons
  12706. # Tue, 24 Aug 1997 16:00:00 +0200 -- Extra whitespace between year and hour
  12707. # Tue, 24 Aug 1997 6:5:2 +0200 -- Single digit hour, min, or second
  12708. # Tue, 24, Aug 1997 16:00:00 +0200 -- Extra comma
  12709. #myprint( "header: [$1][$2][$3][$4][$5][$6][$7][$8]\n" ) ;
  12710. my ($day, $month, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7,$8);
  12711. $year = '19' . $year if length($year) == 2 && $year =~ m/^[789]/xo;
  12712. $year = '20' . $year if length($year) == 2;
  12713. $month = substr $month, 0, 3 if length($month) > 4;
  12714. $day = mysprintf( '%02d', $day);
  12715. $hour = mysprintf( '%02d', $hour);
  12716. $min = mysprintf( '%02d', $min);
  12717. $sec = '00' if not defined $sec ;
  12718. $sec = mysprintf( '%02d', $sec ) ;
  12719. $zone = '+0000' if not defined $zone ;
  12720. $d = "$day-$month-$year $hour:$min:$sec $zone" ;
  12721. last SWITCH ;
  12722. }
  12723. 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 ) {
  12724. # Handles any combination of following formats
  12725. # Sun Aug 20 11:55:09 2006
  12726. # Wed Jan 24 11:58:38 MST 2007
  12727. # Wed Jan 2 08:40:57 2008
  12728. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  12729. my ($month, $day, $hour, $min, $sec, $year) = ($1,$2,$3,$4,$5,$6);
  12730. $day = mysprintf( '%02d', $day ) ;
  12731. $hour = mysprintf( '%02d', $hour ) ;
  12732. $min = mysprintf( '%02d', $min ) ;
  12733. $sec = mysprintf( '%02d', $sec ) ;
  12734. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  12735. last SWITCH ;
  12736. }
  12737. 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 ) ;
  12738. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  12739. # Handles the following format
  12740. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  12741. #myprint( "$d\n" ) ;
  12742. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  12743. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  12744. $month = $num2mon{$month} ;
  12745. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  12746. #myprint( "$d\n" ) ;
  12747. last SWITCH ;
  12748. }
  12749. if ($d =~ m{(\d{2})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  12750. # Handles the following format
  12751. # 02/06/09 22:18:08 -- Generated by AVTECH TemPageR devices
  12752. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  12753. my ($month, $day, $year, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6);
  12754. $year = '20' . $year;
  12755. $month = $num2mon{$month};
  12756. $d = "$day-$month-$year $hour:$min:$sec +0000";
  12757. last SWITCH ;
  12758. }
  12759. 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 ) {
  12760. # Handles the following format
  12761. # Saturday, December 14, 2002 05:00 PM - KBtoys.com order confirmations
  12762. my ($month, $day, $year, $hour, $min, $apm) = ($1,$2,$3,$4,$5,$6);
  12763. $hour += 12 if $apm eq 'PM' ;
  12764. $day = mysprintf( '%02d', $day ) ;
  12765. $d = "$day-$month-$year $hour:$min:00 +0000" ;
  12766. last SWITCH ;
  12767. }
  12768. if ($d =~ m{(\w{3})\s(\d{1,2})\s(\d{4})\s(\d{2}):(\d{2}):(\d{2})\s((?:\+|-)\d{4})}xo ) {
  12769. # Handles the following format
  12770. # Saturday, December 14, 2002 05:00 PM - jr.com order confirmations
  12771. my ($month, $day, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7);
  12772. $day = mysprintf( '%02d', $day ) ;
  12773. $d = "$day-$month-$year $hour:$min:$sec $zone";
  12774. last SWITCH ;
  12775. }
  12776. if ($d =~ m{(\d{1,2})-(\w{3})-(\d{4})}xo ) {
  12777. # Handles the following format
  12778. # 21-Jun-2001 - register.com domain transfer email circa 2001
  12779. my ($day, $month, $year) = ($1,$2,$3);
  12780. $day = mysprintf( '%02d', $day);
  12781. $d = "$day-$month-$year 11:11:11 +0000";
  12782. last SWITCH ;
  12783. }
  12784. # unknown or unmatch => return same string
  12785. return($d);
  12786. }
  12787. $d = qq("$d") ;
  12788. return( $d ) ;
  12789. }
  12790. sub tests_good_date
  12791. {
  12792. note( 'Entering tests_good_date()' ) ;
  12793. ok(q{} eq good_date(), 'good_date no arg');
  12794. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('24-Aug-2010 16:00:00 +0200'), 'good_date internal 2digit zone');
  12795. ok('"24-Aug-2010 16:00:00 +0000"' eq good_date('24-Aug-2010 16:00:00'), 'good_date internal 2digit no zone');
  12796. ok('"01-Sep-2010 16:00:00 +0200"' eq good_date( '1-Sep-2010 16:00:00 +0200'), 'good_date internal SP 1digit');
  12797. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('Tue, 24 Aug 2010 16:00:00 +0200'), 'good_date header 2digit zone');
  12798. ok('"01-Sep-2010 16:00:00 +0000"' eq good_date('Wed, 1 Sep 2010 16:00:00'), 'good_date header SP 1digit zone');
  12799. 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');
  12800. 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');
  12801. ok('"06-Feb-2009 22:18:08 +0000"' eq good_date('02/06/09 22:18:08'), 'good_date header TemPageR');
  12802. 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');
  12803. 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');
  12804. 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');
  12805. 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');
  12806. ok('"24-Aug-2067 16:00:00 +0200"' eq good_date('Tue, 24 Aug 67 16:00:00 +0200'), 'good_date header 2digit year');
  12807. ok('"24-Aug-1977 16:00:00 +0200"' eq good_date('Tue, 24 Aug 77 16:00:00 +0200'), 'good_date header 2digit year');
  12808. ok('"24-Aug-1987 16:00:00 +0200"' eq good_date('Tue, 24 Aug 87 16:00:00 +0200'), 'good_date header 2digit year');
  12809. ok('"24-Aug-1997 16:00:00 +0200"' eq good_date('Tue, 24 Aug 97 16:00:00 +0200'), 'good_date header 2digit year');
  12810. ok('"24-Aug-2004 16:00:00 +0200"' eq good_date('Tue, 24 Aug 04 16:00:00 +0200'), 'good_date header 2digit year');
  12811. 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');
  12812. 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');
  12813. 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');
  12814. ok('"24-Aug-1997 05:06:02 +0200"' eq good_date('Tue, 24, Aug 1997 05:06:02 +0200'), 'good_date header extra commas');
  12815. ok('"01-Oct-2003 12:45:24 +0000"' eq good_date('Wednesday, 01 October 2003 12:45:24 CDT'), 'good_date header no abbrev');
  12816. ok('"11-Jan-2005 17:58:27 -0500"' eq good_date('Tue, 11 Jan 2005 17:58:27 -0500'), 'good_date extra white space');
  12817. ok('"18-Dec-2002 15:07:00 +0000"' eq good_date('Wednesday, December 18, 2002 03:07 PM'), 'good_date kbtoys.com orders');
  12818. ok('"16-Dec-2004 02:01:49 -0500"' eq good_date('Dec 16 2004 02:01:49 -0500'), 'good_date jr.com orders');
  12819. ok('"21-Jun-2001 11:11:11 +0000"' eq good_date('21-Jun-2001'), 'good_date register.com domain transfer');
  12820. 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)');
  12821. ok('"19-Sep-2015 16:11:07 +0000"' eq good_date('Date: 2015/09/19 16:11:07 '), 'good_date from RCS date' ) ;
  12822. note( 'Leaving tests_good_date()' ) ;
  12823. return ;
  12824. }
  12825. sub tests_list_keys_in_2_not_in_1
  12826. {
  12827. note( 'Entering tests_list_keys_in_2_not_in_1()' ) ;
  12828. my @list;
  12829. ok( ! list_keys_in_2_not_in_1( {}, {}), 'list_keys_in_2_not_in_1: {} {}');
  12830. ok( 0 == compare_lists( [], [ list_keys_in_2_not_in_1( {}, {} ) ] ), 'list_keys_in_2_not_in_1: {} {}');
  12831. 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}');
  12832. 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}');
  12833. 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}');
  12834. 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}');
  12835. 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}');
  12836. note( 'Leaving tests_list_keys_in_2_not_in_1()' ) ;
  12837. return ;
  12838. }
  12839. sub list_keys_in_2_not_in_1
  12840. {
  12841. my $hash_1_ref = shift;
  12842. my $hash_2_ref = shift;
  12843. my @list;
  12844. foreach my $key ( sort keys %{ $hash_2_ref } ) {
  12845. #$sync->{ debug } and print "$key\n" ;
  12846. if ( exists $hash_1_ref->{$key} )
  12847. {
  12848. next ;
  12849. }
  12850. #$sync->{ debug } and print "list_keys_in_2_not_in_1: $key\n" ;
  12851. push @list, $key ;
  12852. }
  12853. #$sync->{ debug } and print "@list\n" ;
  12854. return( @list ) ;
  12855. }
  12856. sub list_folders_in_2_not_in_1
  12857. {
  12858. my ( @h2_folders_not_in_h1, %h2_folders_not_in_h1 ) ;
  12859. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h1_folders_all, \%h2_folders_all ) ;
  12860. map { $h2_folders_not_in_h1{$_} = 1} @h2_folders_not_in_h1 ;
  12861. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h2_folders_from_1_all, \%h2_folders_not_in_h1 ) ;
  12862. #$sync->{ debug } and print "h2_folders_not_in_h1: @h2_folders_not_in_h1\n" ;
  12863. return( reverse @h2_folders_not_in_h1 ) ;
  12864. }
  12865. sub tests_nb_messages_in_2_not_in_1
  12866. {
  12867. note( 'Entering tests_stats_across_folders()' ) ;
  12868. is( undef, nb_messages_in_2_not_in_1( ), 'nb_messages_in_2_not_in_1: no args => undef' ) ;
  12869. my $mysync->{ h1_folders_of_md5 }->{ 'some_id_01' }->{ 'some_folder_01' } = 1 ;
  12870. is( 0, nb_messages_in_2_not_in_1( $mysync ), 'nb_messages_in_2_not_in_1: no messages in 2 => 0' ) ;
  12871. $mysync->{ h1_folders_of_md5 }->{ 'some_id_in_1_and_2' }->{ 'some_folder_01' } = 2 ;
  12872. $mysync->{ h2_folders_of_md5 }->{ 'some_id_in_1_and_2' }->{ 'some_folder_02' } = 4 ;
  12873. is( 0, nb_messages_in_2_not_in_1( $mysync ), 'nb_messages_in_2_not_in_1: a common message => 0' ) ;
  12874. $mysync->{ h2_folders_of_md5 }->{ 'some_id_in_2_not_in_1' }->{ 'some_folder_02' } = 1 ;
  12875. is( 1, nb_messages_in_2_not_in_1( $mysync ), 'nb_messages_in_2_not_in_1: one message in_2_not_in_1 => 1' ) ;
  12876. $mysync->{ h2_folders_of_md5 }->{ 'some_other_id_in_2_not_in_1' }->{ 'some_folder_02' } = 3 ;
  12877. is( 2, nb_messages_in_2_not_in_1( $mysync ), 'nb_messages_in_2_not_in_1: two messages in_2_not_in_1 => 2' ) ;
  12878. note( 'Leaving tests_stats_across_folders()' ) ;
  12879. return ;
  12880. }
  12881. sub nb_messages_in_2_not_in_1
  12882. {
  12883. my $mysync = shift ;
  12884. if ( not defined $mysync ) { return ; }
  12885. $mysync->{ nb_messages_in_2_not_in_1 } = scalar(
  12886. list_keys_in_2_not_in_1(
  12887. $mysync->{ h1_folders_of_md5 },
  12888. $mysync->{ h2_folders_of_md5 } ) ) ;
  12889. return $mysync->{ nb_messages_in_2_not_in_1 } ;
  12890. }
  12891. sub nb_messages_in_1_not_in_2
  12892. {
  12893. my $mysync = shift ;
  12894. if ( not defined $mysync ) { return ; }
  12895. $mysync->{ nb_messages_in_1_not_in_2 } = scalar(
  12896. list_keys_in_2_not_in_1(
  12897. $mysync->{ h2_folders_of_md5 },
  12898. $mysync->{ h1_folders_of_md5 } ) ) ;
  12899. return $mysync->{ nb_messages_in_1_not_in_2 } ;
  12900. }
  12901. sub comment_on_final_diff_in_1_not_in_2
  12902. {
  12903. my $mysync = shift ;
  12904. if ( not defined $mysync
  12905. or $mysync->{ justfolders }
  12906. or $mysync->{ useuid }
  12907. )
  12908. {
  12909. return ;
  12910. }
  12911. my $nb_identified_h1_messages = scalar( keys %{ $mysync->{ h1_folders_of_md5 } } ) ;
  12912. my $nb_identified_h2_messages = scalar( keys %{ $mysync->{ h2_folders_of_md5 } } ) ;
  12913. $mysync->{ debug } and myprint( "nb_keys h1_folders_of_md5 $nb_identified_h1_messages\n" ) ;
  12914. $mysync->{ debug } and myprint( "nb_keys h2_folders_of_md5 $nb_identified_h2_messages\n" ) ;
  12915. if ( 0 == $nb_identified_h1_messages ) { return ; }
  12916. # Calculate if not yet done
  12917. if ( not defined $mysync->{ nb_messages_in_1_not_in_2 } )
  12918. {
  12919. nb_messages_in_1_not_in_2( $mysync ) ;
  12920. }
  12921. if ( 0 == $mysync->{ nb_messages_in_1_not_in_2 } )
  12922. {
  12923. myprint( "The sync looks good, all ",
  12924. $nb_identified_h1_messages,
  12925. " identified messages in host1 are on host2.\n" ) ;
  12926. }
  12927. else
  12928. {
  12929. myprint( "The sync is not finished, there are ",
  12930. $mysync->{ nb_messages_in_1_not_in_2 },
  12931. " among ",
  12932. $nb_identified_h1_messages,
  12933. " identified messages in host1 that are not on host2.\n" ) ;
  12934. }
  12935. if ( 1 <= $mysync->{ h1_nb_msg_noheader } )
  12936. {
  12937. myprint( "There are ",
  12938. $mysync->{ h1_nb_msg_noheader },
  12939. " unidentified messages (usually Sent or Draft messages).",
  12940. " To sync them add option --addheader\n" ) ;
  12941. }
  12942. else
  12943. {
  12944. myprint( "There is no unidentified message on host1.\n" ) ;
  12945. }
  12946. return ;
  12947. }
  12948. sub comment_on_final_diff_in_2_not_in_1
  12949. {
  12950. my $mysync = shift ;
  12951. if ( not defined $mysync
  12952. or $mysync->{ justfolders }
  12953. or $mysync->{ useuid }
  12954. )
  12955. {
  12956. return ;
  12957. }
  12958. my $nb_identified_h2_messages = scalar( keys %{ $mysync->{ h2_folders_of_md5 } } ) ;
  12959. # Calculate if not done yet
  12960. if ( not defined $mysync->{ nb_messages_in_2_not_in_1 } )
  12961. {
  12962. nb_messages_in_2_not_in_1( $mysync ) ;
  12963. }
  12964. if ( 0 == $mysync->{ nb_messages_in_2_not_in_1 } )
  12965. {
  12966. myprint( "The sync is strict, all ",
  12967. $nb_identified_h2_messages,
  12968. " identified messages in host2 are on host1.\n" ) ;
  12969. }
  12970. else
  12971. {
  12972. myprint( "The sync is not strict, there are ",
  12973. $mysync->{ nb_messages_in_2_not_in_1 },
  12974. " among ",
  12975. $nb_identified_h2_messages,
  12976. " identified messages in host2 that are not on host1.",
  12977. " Use --delete2 and sync again to delete them and have a strict sync.\n"
  12978. ) ;
  12979. }
  12980. return ;
  12981. }
  12982. sub tests_match
  12983. {
  12984. note( 'Entering tests_match()' ) ;
  12985. # undef serie
  12986. is( undef, match( ), 'match: no args => undef' ) ;
  12987. is( undef, match( 'lalala' ), 'match: one args => undef' ) ;
  12988. # This one gives 0 under a binary made by pp
  12989. # but 1 under "normal" Perl interpreter. So a PAR bug?
  12990. #is( 1, match( q{}, q{} ), 'match: q{} =~ q{} => 1' ) ;
  12991. is( 'lalala', match( 'lalala', 'lalala' ), 'match: lalala =~ lalala => lalala' ) ;
  12992. is( 'lalala', match( 'lalala', '^lalala' ), 'match: lalala =~ ^lalala => lalala' ) ;
  12993. is( 'lalala', match( 'lalala', 'lalala$' ), 'match: lalala =~ lalala$ => lalala' ) ;
  12994. is( 'lalala', match( 'lalala', '^lalala$' ), 'match: lalala =~ ^lalala$ => lalala' ) ;
  12995. is( '_lalala_', match( '_lalala_', 'lalala' ), 'match: _lalala_ =~ lalala => _lalala_' ) ;
  12996. is( 'lalala', match( 'lalala', '.*' ), 'match: lalala =~ .* => lalala' ) ;
  12997. is( 'lalala', match( 'lalala', '.' ), 'match: lalala =~ . => lalala' ) ;
  12998. is( '/lalala/', match( '/lalala/', '/lalala/' ), 'match: /lalala/ =~ /lalala/ => /lalala/' ) ;
  12999. is( 0, match( 'foo', 's/foo/bar/g' ), 'match: foo =~ s/foo/bar/g => 0' ) ;
  13000. is( 's/foo/bar/g', match( 's/foo/bar/g', 's/foo/bar/g' ), 'match: s/foo/bar/g =~ s/foo/bar/g => s/foo/bar/g' ) ;
  13001. is( 0, match( 'lalala', 'ooo' ), 'match: lalala =~ ooo => 0' ) ;
  13002. is( 0, match( 'lalala', 'lal_ala' ), 'match: lalala =~ lal_ala => 0' ) ;
  13003. is( 0, match( 'lalala', '\.' ), 'match: lalala =~ \. => 0' ) ;
  13004. is( 0, match( 'lalalaX', '^lalala$' ), 'match: lalalaX =~ ^lalala$ => 0' ) ;
  13005. is( 0, match( 'lalala', '/lalala/' ), 'match: lalala =~ /lalala/ => 0' ) ;
  13006. is( 'LALALA', match( 'LALALA', '(?i:lalala)' ), 'match: LALALA =~ (?i:lalala) => 1' ) ;
  13007. is( undef, match( 'LALALA', '(?{`ls /`})' ), 'match: LALALA =~ (?{`ls /`}) => undef' ) ;
  13008. is( undef, match( 'LALALA', '(?{print "CACA"})' ), 'match: LALALA =~ (?{print "CACA"}) => undef' ) ;
  13009. is( undef, match( 'CACA', '(??{print "CACA"})' ), 'match: CACA =~ (??{print "CACA"}) => undef' ) ;
  13010. note( 'Leaving tests_match()' ) ;
  13011. return ;
  13012. }
  13013. sub match
  13014. {
  13015. my( $var, $regex ) = @ARG ;
  13016. # undef cases
  13017. if ( ( ! defined $var ) or ( ! defined $regex ) ) { return ; }
  13018. # normal cases
  13019. if ( eval { $var =~ qr{$regex} } ) {
  13020. return $var ;
  13021. }elsif ( $EVAL_ERROR ) {
  13022. myprint( "Fatal regex $regex\n" ) ;
  13023. return ;
  13024. } else {
  13025. return 0 ;
  13026. }
  13027. return ;
  13028. }
  13029. sub tests_notmatch
  13030. {
  13031. note( 'Entering tests_notmatch()' ) ;
  13032. # undef serie
  13033. is( undef, notmatch( ), 'notmatch: no args => undef' ) ;
  13034. is( undef, notmatch( 'lalala' ), 'notmatch: one args => undef' ) ;
  13035. is( 1, notmatch( 'lalala', '/lalala/' ), 'notmatch: lalala !~ /lalala/ => 1' ) ;
  13036. is( 0, notmatch( '/lalala/', '/lalala/' ), 'notmatch: /lalala/ !~ /lalala/ => 0' ) ;
  13037. is( 1, notmatch( 'lalala', '/ooo/' ), 'notmatch: lalala !~ /ooo/ => 1' ) ;
  13038. # This one gives 1 under a binary made by pp
  13039. # but 0 under "normal" Perl interpreter. So a PAR bug, same in tests_match .
  13040. #is( 0, notmatch( q{}, q{} ), 'notmatch: q{} !~ q{} => 0' ) ;
  13041. is( 0, notmatch( 'lalala', 'lalala' ), 'notmatch: lalala !~ lalala => 0' ) ;
  13042. is( 0, notmatch( 'lalala', '^lalala' ), 'notmatch: lalala !~ ^lalala => 0' ) ;
  13043. is( 0, notmatch( 'lalala', 'lalala$' ), 'notmatch: lalala !~ lalala$ => 0' ) ;
  13044. is( 0, notmatch( 'lalala', '^lalala$' ), 'notmatch: lalala !~ ^lalala$ => 0' ) ;
  13045. is( 0, notmatch( '_lalala_', 'lalala' ), 'notmatch: _lalala_ !~ lalala => 0' ) ;
  13046. is( 0, notmatch( 'lalala', '.*' ), 'notmatch: lalala !~ .* => 0' ) ;
  13047. is( 0, notmatch( 'lalala', '.' ), 'notmatch: lalala !~ . => 0' ) ;
  13048. is( 1, notmatch( 'lalala', 'ooo' ), 'notmatch: does not match regex => 1' ) ;
  13049. is( 1, notmatch( 'lalala', 'lal_ala' ), 'notmatch: does not match regex => 1' ) ;
  13050. is( 1, notmatch( 'lalala', '\.' ), 'notmatch: matches regex => 0' ) ;
  13051. is( 1, notmatch( 'lalalaX', '^lalala$' ), 'notmatch: does not match regex => 1' ) ;
  13052. note( 'Leaving tests_notmatch()' ) ;
  13053. return ;
  13054. }
  13055. sub notmatch
  13056. {
  13057. my( $var, $regex ) = @ARG ;
  13058. # undef cases
  13059. if ( ( ! defined $var ) or ( ! defined $regex ) ) { return ; }
  13060. # normal cases
  13061. if ( eval { $var !~ $regex } ) {
  13062. return 1 ;
  13063. }elsif ( $EVAL_ERROR ) {
  13064. myprint( "Fatal regex $regex\n" ) ;
  13065. return ;
  13066. }else{
  13067. return 0 ;
  13068. }
  13069. return ;
  13070. }
  13071. sub delete_folders_in_2_not_in_1
  13072. {
  13073. foreach my $folder ( @h2_folders_not_in_1 ) {
  13074. if ( defined $delete2foldersonly and eval "\$folder !~ $delete2foldersonly" ) {
  13075. myprint( "Not deleting $folder because of --delete2foldersonly $delete2foldersonly\n" ) ;
  13076. next ;
  13077. }
  13078. if ( defined $delete2foldersbutnot and eval "\$folder =~ $delete2foldersbutnot" ) {
  13079. myprint( "Not deleting $folder because of --delete2foldersbutnot $delete2foldersbutnot\n" ) ;
  13080. next ;
  13081. }
  13082. my $res = $sync->{dry} ; # always success in dry mode!
  13083. $sync->{imap2}->unsubscribe( $folder ) if ( ! $sync->{dry} ) ;
  13084. $res = $sync->{imap2}->delete( $folder ) if ( ! $sync->{dry} ) ;
  13085. if ( $res ) {
  13086. myprint( "Deleted $folder", "$sync->{dry_message}", "\n" ) ;
  13087. }else{
  13088. myprint( "Deleting $folder failed", "\n" ) ;
  13089. }
  13090. }
  13091. return ;
  13092. }
  13093. sub delete_folder
  13094. {
  13095. my ( $mysync, $imap, $folder, $Side ) = @_ ;
  13096. if ( ! $mysync ) { return ; }
  13097. if ( ! $imap ) { return ; }
  13098. if ( ! $folder ) { return ; }
  13099. $Side ||= 'HostX' ;
  13100. my $res = $mysync->{dry} ; # always success in dry mode!
  13101. if ( ! $mysync->{dry} ) {
  13102. $imap->unsubscribe( $folder ) ;
  13103. $res = $imap->delete( $folder ) ;
  13104. }
  13105. if ( $res ) {
  13106. myprint( "$Side deleted $folder", $mysync->{dry_message}, "\n" ) ;
  13107. return 1 ;
  13108. }else{
  13109. myprint( "$Side deleting $folder failed", "\n" ) ;
  13110. return ;
  13111. }
  13112. }
  13113. sub delete1emptyfolders
  13114. {
  13115. my $mysync = shift ;
  13116. if ( ! $mysync ) { return ; } # abort if no parameter
  13117. if ( ! $mysync->{delete1emptyfolders} ) { return ; } # abort if --delete1emptyfolders off
  13118. my $imap = $mysync->{imap1} ;
  13119. if ( ! $imap ) { return ; } # abort if no imap
  13120. if ( $imap->IsUnconnected( ) ) { return ; } # abort if disconnected
  13121. my %folders_kept ;
  13122. myprint( qq{Host1 deleting empty folders\n} ) ;
  13123. foreach my $folder ( reverse sort @{ $mysync->{h1_folders_wanted} } ) {
  13124. my $parenthood = $imap->is_parent( $folder ) ;
  13125. if ( defined $parenthood and $parenthood ) {
  13126. myprint( "Host1: folder $folder has subfolders\n" ) ;
  13127. $folders_kept{ $folder }++ ;
  13128. next ;
  13129. }
  13130. my $nb_messages_select = examine_folder_and_count( $mysync, $imap, $folder, 'Host1' ) ;
  13131. if ( ! defined $nb_messages_select ) { next ; } # Select failed => Neither continue nor keep this folder }
  13132. my $nb_messages_search = scalar( @{ $imap->messages( ) } ) ;
  13133. if ( 0 != $nb_messages_select and 0 != $nb_messages_search ) {
  13134. myprint( "Host1: folder $folder has messages: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  13135. $folders_kept{ $folder }++ ;
  13136. next ;
  13137. }
  13138. if ( 0 != $nb_messages_select + $nb_messages_search ) {
  13139. myprint( "Host1: folder $folder odd messages count: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  13140. $folders_kept{ $folder }++ ;
  13141. next ;
  13142. }
  13143. # Here we must have 0 messages by messages() aka "SEARCH ALL" and also "EXAMINE"
  13144. if ( uc $folder eq 'INBOX' ) {
  13145. myprint( "Host1: Not deleting $folder\n" ) ;
  13146. $folders_kept{ $folder }++ ;
  13147. next ;
  13148. }
  13149. myprint( "Host1: deleting empty folder $folder\n" ) ;
  13150. # can not delete a SELECTed or EXAMINEd folder so closing it
  13151. # could changed be SELECT INBOX
  13152. $imap->close( ) ; # close after examine does not expunge; anyway expunging an empty folder...
  13153. if ( delete_folder( $mysync, $imap, $folder, 'Host1' ) ) {
  13154. next ; # Deleted, good!
  13155. }else{
  13156. $folders_kept{ $folder }++ ;
  13157. next ; # Not deleted, bad!
  13158. }
  13159. }
  13160. remove_deleted_folders_from_wanted_list( $mysync, %folders_kept ) ;
  13161. myprint( qq{Host1 ended deleting empty folders\n} ) ;
  13162. return ;
  13163. }
  13164. sub remove_deleted_folders_from_wanted_list
  13165. {
  13166. my ( $mysync, %folders_kept ) = @ARG ;
  13167. my @h1_folders_wanted_init = @{ $mysync->{h1_folders_wanted} } ;
  13168. my @h1_folders_wanted_last ;
  13169. foreach my $folder ( @h1_folders_wanted_init ) {
  13170. if ( $folders_kept{ $folder } ) {
  13171. push @h1_folders_wanted_last, $folder ;
  13172. }
  13173. }
  13174. @{ $mysync->{h1_folders_wanted} } = @h1_folders_wanted_last ;
  13175. return ;
  13176. }
  13177. sub examine_folder_and_count
  13178. {
  13179. my ( $mysync, $imap, $folder, $Side ) = @_ ;
  13180. $Side ||= 'HostX' ;
  13181. if ( ! examine_folder( $mysync, $imap, $folder, $Side ) ) {
  13182. return ;
  13183. }
  13184. my $nb_messages_select = count_from_select( $imap->History ) ;
  13185. return $nb_messages_select ;
  13186. }
  13187. sub tests_delete1emptyfolders
  13188. {
  13189. note( 'Entering tests_delete1emptyfolders()' ) ;
  13190. is( undef, delete1emptyfolders( ), q{delete1emptyfolders: undef} ) ;
  13191. my $syncT ;
  13192. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef 2} ) ;
  13193. my $imapT ;
  13194. $syncT->{imap1} = $imapT ;
  13195. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef imap} ) ;
  13196. require_ok( "Test::MockObject" ) ;
  13197. $imapT = Test::MockObject->new( ) ;
  13198. $syncT->{imap1} = $imapT ;
  13199. $imapT->set_true( 'IsUnconnected' ) ;
  13200. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: Unconnected imap} ) ;
  13201. # Now connected tests
  13202. $imapT->set_false( 'IsUnconnected' ) ;
  13203. $imapT->mock( 'LastError', sub { q{LastError mocked} } ) ;
  13204. $syncT->{delete1emptyfolders} = 0 ;
  13205. tests_delete1emptyfolders_unit(
  13206. $syncT,
  13207. [ qw{ INBOX DELME1 DELME2 } ],
  13208. [ qw{ INBOX DELME1 DELME2 } ],
  13209. q{tests_delete1emptyfolders: --delete1emptyfolders OFF}
  13210. ) ;
  13211. # All are parents => no deletion at all
  13212. $imapT->set_true( 'is_parent' ) ;
  13213. $syncT->{delete1emptyfolders} = 1 ;
  13214. tests_delete1emptyfolders_unit(
  13215. $syncT,
  13216. [ qw{ INBOX DELME1 DELME2 } ],
  13217. [ qw{ INBOX DELME1 DELME2 } ],
  13218. q{tests_delete1emptyfolders: --delete1emptyfolders ON}
  13219. ) ;
  13220. # No parents but examine false for all => skip all
  13221. $imapT->set_false( 'is_parent', 'examine' ) ;
  13222. tests_delete1emptyfolders_unit(
  13223. $syncT,
  13224. [ qw{ INBOX DELME1 DELME2 } ],
  13225. [ ],
  13226. q{tests_delete1emptyfolders: EXAMINE fails}
  13227. ) ;
  13228. # examine ok for all but History bad => skip all
  13229. $imapT->set_true( 'examine' ) ;
  13230. $imapT->mock( 'History', sub { ( q{History badly mocked} ) } ) ;
  13231. tests_delete1emptyfolders_unit(
  13232. $syncT,
  13233. [ qw{ INBOX DELME1 DELME2 } ],
  13234. [ ],
  13235. q{tests_delete1emptyfolders: examine ok but History badly mocked so count messages fails}
  13236. ) ;
  13237. # History good but some messages EXISTS == messages() => no deletion
  13238. $imapT->mock( 'History', sub { ( q{* 2 EXISTS} ) } ) ;
  13239. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  13240. tests_delete1emptyfolders_unit(
  13241. $syncT,
  13242. [ qw{ INBOX DELME1 DELME2 } ],
  13243. [ qw{ INBOX DELME1 DELME2 } ],
  13244. q{tests_delete1emptyfolders: History EXAMINE ok, several messages}
  13245. ) ;
  13246. # 0 EXISTS but != messages() => no deletion
  13247. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  13248. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  13249. tests_delete1emptyfolders_unit(
  13250. $syncT,
  13251. [ qw{ INBOX DELME1 DELME2 } ],
  13252. [ qw{ INBOX DELME1 DELME2 } ],
  13253. q{tests_delete1emptyfolders: 0 EXISTS but 2 by messages()}
  13254. ) ;
  13255. # 1 EXISTS but != 0 == messages() => no deletion
  13256. $imapT->mock( 'History', sub { ( q{* 1 EXISTS} ) } ) ;
  13257. $imapT->mock( 'messages', sub { [ ] } ) ;
  13258. tests_delete1emptyfolders_unit(
  13259. $syncT,
  13260. [ qw{ INBOX DELME1 DELME2 } ],
  13261. [ qw{ INBOX DELME1 DELME2 } ],
  13262. q{tests_delete1emptyfolders: 1 EXISTS but 0 by messages()}
  13263. ) ;
  13264. # 0 EXISTS and 0 == messages() => deletion except INBOX
  13265. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  13266. $imapT->mock( 'messages', sub { [ ] } ) ;
  13267. $imapT->set_true( qw{ delete close unsubscribe } ) ;
  13268. $syncT->{dry_message} = q{ (not really since in a mocked test)} ;
  13269. tests_delete1emptyfolders_unit(
  13270. $syncT,
  13271. [ qw{ INBOX DELME1 DELME2 } ],
  13272. [ qw{ INBOX } ],
  13273. q{tests_delete1emptyfolders: 0 EXISTS 0 by messages() delete folders, keep INBOX}
  13274. ) ;
  13275. note( 'Leaving tests_delete1emptyfolders()' ) ;
  13276. return ;
  13277. }
  13278. sub tests_delete1emptyfolders_unit
  13279. {
  13280. note( 'Entering tests_delete1emptyfolders_unit()' ) ;
  13281. my $syncT = shift ;
  13282. my $folders1wanted_init_ref = shift ;
  13283. my $folders1wanted_after_ref = shift ;
  13284. my $comment = shift || q{delete1emptyfolders:} ;
  13285. my @folders1wanted_init = @{ $folders1wanted_init_ref } ;
  13286. my @folders1wanted_after = @{ $folders1wanted_after_ref } ;
  13287. @{ $syncT->{h1_folders_wanted} } = @folders1wanted_init ;
  13288. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_init, qq{$comment, init check} ) ;
  13289. delete1emptyfolders( $syncT ) ;
  13290. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_after, qq{$comment, after check} ) ;
  13291. note( 'Leaving tests_delete1emptyfolders_unit()' ) ;
  13292. return ;
  13293. }
  13294. sub extract_header
  13295. {
  13296. my $string = shift ;
  13297. my ( $header ) = split /\n\n/x, $string ;
  13298. if ( ! $header ) { return( q{} ) ; }
  13299. #myprint( "[$header]\n" ) ;
  13300. return( $header ) ;
  13301. }
  13302. sub tests_extract_header
  13303. {
  13304. note( 'Entering tests_extract_header()' ) ;
  13305. my $h = <<'EOM';
  13306. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  13307. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  13308. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  13309. EOM
  13310. chomp $h ;
  13311. ok( $h eq extract_header(
  13312. <<'EOM'
  13313. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  13314. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  13315. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  13316. body
  13317. lalala
  13318. EOM
  13319. ), 'extract_header: 1') ;
  13320. note( 'Leaving tests_extract_header()' ) ;
  13321. return ;
  13322. }
  13323. sub decompose_header{
  13324. my $string = shift ;
  13325. # a hash, for a keyword header KEY value are list of strings [VAL1, VAL1_other, etc]
  13326. # Think of multiple "Received:" header lines.
  13327. my $header = { } ;
  13328. my ($key, $val ) ;
  13329. my @line = split /\n|\r\n/x, $string ;
  13330. foreach my $line ( @line ) {
  13331. #myprint( "DDD $line\n" ) ;
  13332. # End of header
  13333. last if ( $line =~ m{^$}xo ) ;
  13334. # Key: value
  13335. if ( $line =~ m/(^[^:]+):\s(.*)/xo ) {
  13336. $key = $1 ;
  13337. $val = $2 ;
  13338. $debugdev and myprint( "DDD KV [$key] [$val]\n" ) ;
  13339. push @{ $header->{ $key } }, $val ;
  13340. # blanc and value => value from previous line continues
  13341. }elsif( $line =~ m/^(\s+)(.*)/xo ) {
  13342. $val = $2 ;
  13343. $debugdev and myprint( "DDD V [$val]\n" ) ;
  13344. @{ $header->{ $key } }[ $LAST ] .= " $val" if $key ;
  13345. # dirty line?
  13346. }else{
  13347. next ;
  13348. }
  13349. }
  13350. #myprint( Data::Dumper->Dump( [ $header ] ) ) ;
  13351. return( $header ) ;
  13352. }
  13353. sub tests_decompose_header{
  13354. note( 'Entering tests_decompose_header()' ) ;
  13355. my $header_dec ;
  13356. $header_dec = decompose_header(
  13357. <<'EOH'
  13358. KEY_1: VAL_1
  13359. KEY_2: VAL_2
  13360. VAL_2_+
  13361. VAL_2_++
  13362. KEY_3: VAL_3
  13363. KEY_1: VAL_1_other
  13364. KEY_4: VAL_4
  13365. VAL_4_+
  13366. KEY_5 BLANC: VAL_5
  13367. KEY_6_BAD_BODY: VAL_6
  13368. EOH
  13369. ) ;
  13370. ok( 'VAL_3'
  13371. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: VAL_3' ) ;
  13372. ok( 'VAL_1'
  13373. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: VAL_1' ) ;
  13374. ok( 'VAL_1_other'
  13375. eq $header_dec->{ 'KEY_1' }[1], 'decompose_header: VAL_1_other' ) ;
  13376. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  13377. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: VAL_2 VAL_2_+ VAL_2_++' ) ;
  13378. ok( 'VAL_4 VAL_4_+'
  13379. eq $header_dec->{ 'KEY_4' }[0], 'decompose_header: VAL_4 VAL_4_+' ) ;
  13380. ok( ' VAL_5'
  13381. eq $header_dec->{ 'KEY_5 BLANC' }[0], 'decompose_header: KEY_5 BLANC' ) ;
  13382. ok( not( defined $header_dec->{ 'KEY_6_BAD_BODY' }[0] ), 'decompose_header: KEY_6_BAD_BODY' ) ;
  13383. $header_dec = decompose_header(
  13384. <<'EOH'
  13385. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  13386. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  13387. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  13388. EOH
  13389. ) ;
  13390. ok( '<20100428101817.A66CB162474E@plume.est.belle>'
  13391. eq $header_dec->{ 'Message-Id' }[0], 'decompose_header: 1' ) ;
  13392. $header_dec = decompose_header(
  13393. <<'EOH'
  13394. Return-Path: <gilles@louloutte.dyndns.org>
  13395. Received: by plume.est.belle (Postfix, from userid 1000)
  13396. id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)
  13397. Subject: test:eekahceishukohpe
  13398. EOH
  13399. ) ;
  13400. ok(
  13401. 'by plume.est.belle (Postfix, from userid 1000) id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)'
  13402. eq $header_dec->{ 'Received' }[0], 'decompose_header: 2' ) ;
  13403. $header_dec = decompose_header(
  13404. <<'EOH'
  13405. Received: from plume (localhost [127.0.0.1])
  13406. by plume.est.belle (Postfix) with ESMTP id C6EB73F6C9
  13407. for <gilles@localhost>; Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  13408. Received: from plume [192.168.68.7]
  13409. by plume with POP3 (fetchmail-6.3.6)
  13410. for <gilles@localhost> (single-drop); Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  13411. EOH
  13412. ) ;
  13413. ok(
  13414. '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)'
  13415. eq $header_dec->{ 'Received' }[0], 'decompose_header: 3' ) ;
  13416. ok(
  13417. '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)'
  13418. eq $header_dec->{ 'Received' }[1], 'decompose_header: 3' ) ;
  13419. # Bad header beginning with a blank character
  13420. $header_dec = decompose_header(
  13421. <<'EOH'
  13422. KEY_1: VAL_1
  13423. KEY_2: VAL_2
  13424. VAL_2_+
  13425. VAL_2_++
  13426. KEY_3: VAL_3
  13427. KEY_1: VAL_1_other
  13428. EOH
  13429. ) ;
  13430. ok( 'VAL_3'
  13431. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: Bad header VAL_3' ) ;
  13432. ok( 'VAL_1_other'
  13433. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: Bad header VAL_1_other' ) ;
  13434. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  13435. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: Bad header VAL_2 VAL_2_+ VAL_2_++' ) ;
  13436. note( 'Leaving tests_decompose_header()' ) ;
  13437. return ;
  13438. }
  13439. sub tests_epoch
  13440. {
  13441. note( 'Entering tests_epoch()' ) ;
  13442. ok( '1282658400' eq epoch( '24-Aug-2010 16:00:00 +0200' ), 'epoch 24-Aug-2010 16:00:00 +0200 -> 1282658400' ) ;
  13443. ok( '1282658400' eq epoch( '24-Aug-2010 14:00:00 +0000' ), 'epoch 24-Aug-2010 14:00:00 +0000 -> 1282658400' ) ;
  13444. ok( '1282658400' eq epoch( '24-Aug-2010 12:00:00 -0200' ), 'epoch 24-Aug-2010 12:00:00 -0200 -> 1282658400' ) ;
  13445. ok( '1282658400' eq epoch( '24-Aug-2010 16:01:00 +0201' ), 'epoch 24-Aug-2010 16:01:00 +0201 -> 1282658400' ) ;
  13446. ok( '1282658400' eq epoch( '24-Aug-2010 14:01:00 +0001' ), 'epoch 24-Aug-2010 14:01:00 +0001 -> 1282658400' ) ;
  13447. ok( '1280671200' eq epoch( '1-Aug-2010 16:00:00 +0200' ), 'epoch 1-Aug-2010 16:00:00 +0200 -> 1280671200' ) ;
  13448. ok( '1280671200' eq epoch( '1-Aug-2010 14:00:00 +0000' ), 'epoch 1-Aug-2010 14:00:00 +0000 -> 1280671200' ) ;
  13449. ok( '1280671200' eq epoch( '1-Aug-2010 12:00:00 -0200' ), 'epoch 1-Aug-2010 12:00:00 -0200 -> 1280671200' ) ;
  13450. ok( '1280671200' eq epoch( '1-Aug-2010 16:01:00 +0201' ), 'epoch 1-Aug-2010 16:01:00 +0201 -> 1280671200' ) ;
  13451. ok( '1280671200' eq epoch( '1-Aug-2010 14:01:00 +0001' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  13452. is( '1280671200', epoch( '1-Aug-2010 14:01:00 +0001' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  13453. is( '946684800', epoch( '00-Jan-0000 00:00:00 +0000' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  13454. note( 'Leaving tests_epoch()' ) ;
  13455. return ;
  13456. }
  13457. sub epoch
  13458. {
  13459. # incoming format:
  13460. # internal date 24-Aug-2010 16:00:00 +0200
  13461. # outgoing format: epoch
  13462. my $d = shift ;
  13463. return(q{}) if not defined $d;
  13464. my ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m ) ;
  13465. my $time ;
  13466. 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 ) {
  13467. #myprint( "internal: [$1][$2][$3][$4][$5][$6][$7][$8][$9]\n" ) ;
  13468. ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )
  13469. = ( $1, $2, $3, $4, $5, $6, $7, $8, $9 ) ;
  13470. #myprint( "( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )\n" ) ;
  13471. $sign = +1 if ( '+' eq $sign ) ;
  13472. $sign = $MINUS_ONE if ( '-' eq $sign ) ;
  13473. if ( 0 == $mday ) {
  13474. myprint( "buggy day in $d. Fixed to 01\n" ) ;
  13475. $mday = '01' ;
  13476. }
  13477. $time = timegm( $sec, $min, $hour, $mday, $month_abrev{$month}, $year )
  13478. - $sign * ( 3600 * $zone_h + 60 * $zone_m ) ;
  13479. #myprint( "$time ", scalar localtime($time), "\n");
  13480. }
  13481. return( $time ) ;
  13482. }
  13483. sub tests_add_header
  13484. {
  13485. note( 'Entering tests_add_header()' ) ;
  13486. ok( 'Message-Id: <mistake@imapsync>' eq add_header(), 'add_header no arg' ) ;
  13487. ok( 'Message-Id: <123456789@imapsync>' eq add_header( '123456789' ), 'add_header 123456789' ) ;
  13488. note( 'Leaving tests_add_header()' ) ;
  13489. return ;
  13490. }
  13491. sub add_header
  13492. {
  13493. my $header_uid = shift || 'mistake' ;
  13494. my $header_Message_Id = 'Message-Id: <' . $header_uid . '@imapsync>' ;
  13495. return( $header_Message_Id ) ;
  13496. }
  13497. sub tests_max_line_length
  13498. {
  13499. note( 'Entering tests_max_line_length()' ) ;
  13500. ok( 0 == max_line_length( q{} ), 'max_line_length: 0 == null string' ) ;
  13501. ok( 1 == max_line_length( "\n" ), 'max_line_length: 1 == \n' ) ;
  13502. ok( 1 == max_line_length( "\n\n" ), 'max_line_length: 1 == \n\n' ) ;
  13503. ok( 1 == max_line_length( "\n" x 500 ), 'max_line_length: 1 == 500 \n' ) ;
  13504. ok( 1 == max_line_length( 'a' ), 'max_line_length: 1 == a' ) ;
  13505. ok( 2 == max_line_length( "a\na" ), 'max_line_length: 2 == a\na' ) ;
  13506. ok( 2 == max_line_length( "a\na\n" ), 'max_line_length: 2 == a\na\n' ) ;
  13507. ok( 3 == max_line_length( "a\nab\n" ), 'max_line_length: 3 == a\nab\n' ) ;
  13508. ok( 3 == max_line_length( "a\nab\n" x 1_000 ), 'max_line_length: 3 == 1_000 a\nab\n' ) ;
  13509. ok( 3 == max_line_length( "a\nab\nabc" ), 'max_line_length: 3 == a\nab\nabc' ) ;
  13510. ok( 4 == max_line_length( "a\nab\nabc\n" ), 'max_line_length: 4 == a\nab\nabc\n' ) ;
  13511. ok( 5 == max_line_length( "a\nabcd\nabc\n" ), 'max_line_length: 5 == a\nabcd\nabc\n' ) ;
  13512. 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' ) ;
  13513. note( 'Leaving tests_max_line_length()' ) ;
  13514. return ;
  13515. }
  13516. sub max_line_length
  13517. {
  13518. my $string = shift ;
  13519. my $max = 0 ;
  13520. while ( $string =~ m/([^\n]*\n?)/msxg ) {
  13521. $max = max( $max, length $1 ) ;
  13522. }
  13523. return( $max ) ;
  13524. }
  13525. sub tests_setlogfile
  13526. {
  13527. note( 'Entering tests_setlogfile()' ) ;
  13528. my $mysync = {} ;
  13529. $mysync->{logdir} = 'vallogdir' ;
  13530. $mysync->{logfile} = 'vallogfile.txt' ;
  13531. is( 'vallogdir/vallogfile.txt', setlogfile( $mysync ),
  13532. 'setlogfile: logdir vallogdir, logfile vallogfile.txt, vallogdir/vallogfile.txt' ) ;
  13533. SKIP: {
  13534. skip( 'Too hard to have a well known timezone on Windows', 9 ) if ( 'MSWin32' eq $OSNAME ) ;
  13535. local $ENV{TZ} = 'GMT' ;
  13536. $mysync = {
  13537. timestart => 2,
  13538. } ;
  13539. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000__.txt", setlogfile( $mysync ),
  13540. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000__.txt" ) ;
  13541. $mysync = {
  13542. timestart => 2,
  13543. user1 => 'user1',
  13544. user2 => 'user2',
  13545. abort => 1,
  13546. } ;
  13547. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_abort.txt", setlogfile( $mysync ),
  13548. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_abort.txt" ) ;
  13549. $mysync = {
  13550. timestart => 2,
  13551. user1 => 'user1',
  13552. user2 => 'user2',
  13553. remote => 'zzz',
  13554. } ;
  13555. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote.txt", setlogfile( $mysync ),
  13556. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote.txt" ) ;
  13557. $mysync = {
  13558. timestart => 2,
  13559. user1 => 'user1',
  13560. user2 => 'user2',
  13561. remote => 'zzz',
  13562. abort => 1,
  13563. } ;
  13564. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote_abort.txt", setlogfile( $mysync ),
  13565. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote_abort.txt" ) ;
  13566. $mysync = {
  13567. timestart => 2,
  13568. user1 => 'user1',
  13569. user2 => 'user2',
  13570. } ;
  13571. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt", setlogfile( $mysync ),
  13572. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt" ) ;
  13573. $mysync->{logdir} = undef ;
  13574. $mysync->{logfile} = undef ;
  13575. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt", setlogfile( $mysync ),
  13576. "setlogfile: logdir undef, $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt" ) ;
  13577. $mysync->{logdir} = q{} ;
  13578. $mysync->{logfile} = undef ;
  13579. is( '1970_01_01_00_00_02_000_user1_user2.txt', setlogfile( $mysync ),
  13580. 'setlogfile: logdir empty, 1970_01_01_00_00_02_000_user1_user2.txt' ) ;
  13581. $mysync->{logdir} = 'vallogdir' ;
  13582. $mysync->{logfile} = undef ;
  13583. is( 'vallogdir/1970_01_01_00_00_02_000_user1_user2.txt', setlogfile( $mysync ),
  13584. 'setlogfile: logdir vallogdir, vallogdir/1970_01_01_00_00_02_000_user1_user2.txt' ) ;
  13585. $mysync = {
  13586. user1 => 'us/er1a*|?:"<>b',
  13587. user2 => 'u/ser2a*|?:"<>b',
  13588. } ;
  13589. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_00_000_us_er1a_______b_u_ser2a_______b.txt", setlogfile( $mysync ),
  13590. "setlogfile: logdir undef, $DEFAULT_LOGDIR/1970_01_01_00_00_00_000_us_er1a_______b_u_ser2a_______b.txt" ) ;
  13591. } ;
  13592. note( 'Leaving tests_setlogfile()' ) ;
  13593. return ;
  13594. }
  13595. sub setlogfile
  13596. {
  13597. my( $mysync ) = shift ;
  13598. # When aborting another process the log file name finishes with "_abort.txt"
  13599. my $abort_suffix = ( $mysync->{ abort } ) ? '_abort' : q{} ;
  13600. # When acting as a proxy the log file name finishes with "_remote.txt"
  13601. # proxy mode is not done in imapsync, it is done by proximapsync
  13602. my $remote_suffix = ( $mysync->{ remote } ) ? '_remote' : q{} ;
  13603. my $suffix = (
  13604. filter_forbidden_characters( slash_to_underscore( $mysync->{ user1 } ) ) || q{} )
  13605. . '_'
  13606. . ( filter_forbidden_characters( slash_to_underscore( $mysync->{ user2 } ) ) || q{} )
  13607. . $remote_suffix . $abort_suffix ;
  13608. $mysync->{ logdir } = defined $mysync->{ logdir } ? $mysync->{ logdir } : $DEFAULT_LOGDIR ;
  13609. $mysync->{ logfile } = defined $mysync->{ logfile }
  13610. ? "$mysync->{ logdir }/$mysync->{ logfile }"
  13611. : logfile( $mysync->{ timestart }, $suffix, $mysync->{ logdir } ) ;
  13612. return( $mysync->{ logfile } ) ;
  13613. }
  13614. sub tests_logfile
  13615. {
  13616. note( 'Entering tests_logfile()' ) ;
  13617. SKIP: {
  13618. # Too hard to have a well known timezone on Windows
  13619. skip( 'Too hard to have a well known timezone on Windows', 10 ) if ( 'MSWin32' eq $OSNAME ) ;
  13620. local $ENV{TZ} = 'GMT' ;
  13621. {
  13622. POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  13623. is( '1970_01_01_00_00_00_000.txt', logfile( ), 'logfile: no args => 1970_01_01_00_00_00.txt' ) ;
  13624. is( '1970_01_01_00_00_00_000.txt', logfile( 0 ), 'logfile: 0 => 1970_01_01_00_00_00.txt' ) ;
  13625. is( '1970_01_01_00_01_01_000.txt', logfile( 61 ), 'logfile: 0 => 1970_01_01_00_01_01.txt' ) ;
  13626. is( '1970_01_01_00_01_01_234.txt', logfile( 61.234 ), 'logfile: 0 => 1970_01_01_00_01_01.txt' ) ;
  13627. 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' ) ;
  13628. 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' ) ;
  13629. 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' ) ;
  13630. 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' ) ;
  13631. is( '2010_08_24_14_01_01_234_poup.txt', logfile( 1_282_658_461.2347, 'poup' ),
  13632. 'logfile: 1_282_658_461.2347 poup => 2010_08_24_14_01_01_234_poup.txt' ) ;
  13633. is( 'dirdir/2010_08_24_14_01_01_234_poup.txt', logfile( 1_282_658_461.2347, 'poup', 'dirdir' ),
  13634. 'logfile: 1_282_658_461.2347 poup dirdir => dirdir/2010_08_24_14_01_01_234_poup.txt' ) ;
  13635. }
  13636. POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  13637. } ;
  13638. note( 'Leaving tests_logfile()' ) ;
  13639. return ;
  13640. }
  13641. sub logfile
  13642. {
  13643. my ( $time, $suffix, $dir ) = @_ ;
  13644. $time ||= 0 ;
  13645. $suffix ||= q{} ;
  13646. $suffix =~ tr/ //ds ;
  13647. my $sep_suffix = ( $suffix ) ? '_' : q{} ;
  13648. $dir ||= q{} ;
  13649. my $sep_dir = ( $dir ) ? '/' : q{} ;
  13650. my $date_str = POSIX::strftime( '%Y_%m_%d_%H_%M_%S', localtime $time ) ;
  13651. # Because of ab tests or web accesses, more than one sync withing one second is possible
  13652. # so we add also milliseconds
  13653. $date_str .= sprintf "_%03d", ($time - int( $time ) ) * 1000 ; # without rounding
  13654. my $logfile = "${dir}${sep_dir}${date_str}${sep_suffix}${suffix}.txt" ;
  13655. return( $logfile ) ;
  13656. }
  13657. sub tests_localtimez
  13658. {
  13659. note( 'Entering tests_localtimez()' ) ;
  13660. SKIP: {
  13661. # Too hard to have a well known timezone on Windows
  13662. skip( 'Too hard to have a well known timezone on Windows', 1 ) if ( 'MSWin32' eq $OSNAME ) ;
  13663. local $ENV{TZ} = 'GMT' ;
  13664. like( localtimez( 0 ), qr'1970-01-01 00:00:00 \+0000 (GMT|UTC)', 'localtimez: 0 => match 1970-01-01 00:00:00 +0000 GMT' ) ;
  13665. }
  13666. is( localtimez( ), localtimez( time ), 'localtimez: undef => equals currrent' ) ;
  13667. note( 'Leaving tests_localtimez()' ) ;
  13668. return ;
  13669. }
  13670. sub localtimez
  13671. {
  13672. my $time = shift ;
  13673. $time = defined( $time ) ? $time : time ;
  13674. my $datetimestr = POSIX::strftime( '%A %e %B %Y-%m-%d %H:%M:%S %z %Z', localtime( $time ) ) ;
  13675. #myprint( "$datetimestr\n" ) ;
  13676. return $datetimestr ;
  13677. }
  13678. sub tests_slash_to_underscore
  13679. {
  13680. note( 'Entering tests_slash_to_underscore()' ) ;
  13681. is( undef, slash_to_underscore( ), 'slash_to_underscore: no parameters => undef' ) ;
  13682. is( '_', slash_to_underscore( '/' ), 'slash_to_underscore: / => _' ) ;
  13683. is( '_abc_def_', slash_to_underscore( '/abc/def/' ), 'slash_to_underscore: /abc/def/ => _abc_def_' ) ;
  13684. note( 'Leaving tests_slash_to_underscore()' ) ;
  13685. return ;
  13686. }
  13687. sub slash_to_underscore
  13688. {
  13689. my $string = shift ;
  13690. if ( ! defined $string ) { return ; }
  13691. $string =~ tr{/}{_} ;
  13692. return( $string ) ;
  13693. }
  13694. sub tests_million_folders_baby_2
  13695. {
  13696. note( 'Entering tests_million_folders_baby_2()' ) ;
  13697. my %long ;
  13698. @long{ 1 .. 900_000 } = (1) x 900_000 ;
  13699. #myprint( %long, "\n" ) ;
  13700. my $pasglop = 0 ;
  13701. foreach my $elem ( 1 .. 900_000 ) {
  13702. #$debug and myprint( "$elem " ) ;
  13703. if ( not exists $long{ $elem } ) {
  13704. $pasglop++ ;
  13705. }
  13706. }
  13707. ok( 0 == $pasglop, 'tests_million_folders_baby_2: search among 900_000' ) ;
  13708. # myprint( "$pasglop\n" ) ;
  13709. note( 'Leaving tests_million_folders_baby_2()' ) ;
  13710. return ;
  13711. }
  13712. sub tests_always_fail
  13713. {
  13714. note( 'Entering tests_always_fail()' ) ;
  13715. is( 0, 1, 'always_fail: 0 is 1' ) ;
  13716. note( 'Leaving tests_always_fail()' ) ;
  13717. return ;
  13718. }
  13719. sub tests_logfileprepa
  13720. {
  13721. note( 'Entering tests_logfileprepa()' ) ;
  13722. is( undef, logfileprepa( ), 'logfileprepa: no args => undef' ) ;
  13723. my $logfile = 'W/tmp/tests/tests_logfileprepa.txt' ;
  13724. is( 1, logfileprepa( $logfile ), 'logfileprepa: W/tmp/tests/tests_logfileprepa.txt => 1' ) ;
  13725. note( 'Leaving tests_logfileprepa()' ) ;
  13726. return ;
  13727. }
  13728. sub logfileprepa
  13729. {
  13730. my $logfile = shift ;
  13731. if ( ! defined( $logfile ) )
  13732. {
  13733. return ;
  13734. }else
  13735. {
  13736. #myprint( "[$logfile]\n" ) ;
  13737. my $dirname = dirname( $logfile ) ;
  13738. do_valid_directory( $dirname ) || return( 0 ) ;
  13739. return( 1 ) ;
  13740. }
  13741. }
  13742. sub tests_teelaunch
  13743. {
  13744. note( 'Entering tests_teelaunch()' ) ;
  13745. is( undef, teelaunch( ), 'teelaunch: no args => undef' ) ;
  13746. my $mysync = {} ;
  13747. is( undef, teelaunch( $mysync ), 'teelaunch: arg empty {} => undef' ) ;
  13748. $mysync->{logfile} = q{} ;
  13749. is( undef, teelaunch( $mysync ), 'teelaunch: logfile empty string => undef' ) ;
  13750. # First time, learning IO::Tee intrasics
  13751. $mysync->{logfile} = 'W/tmp/tests/tests_teelaunch.txt' ;
  13752. isa_ok( my $tee = teelaunch( $mysync ), 'IO::Tee' , 'teelaunch: logfile W/tmp/tests/tests_teelaunch.txt' ) ;
  13753. is( 1, print( $tee "Hi!\n" ), 'teelaunch: write Hi!') ;
  13754. is( "Hi!\n", file_to_string( 'W/tmp/tests/tests_teelaunch.txt' ), 'teelaunch: reading W/tmp/tests/tests_teelaunch.txt is Hi!\n' ) ;
  13755. is( 1, print( $tee "Hoo\n" ), 'teelaunch: write Hoo') ;
  13756. is( "Hi!\nHoo\n", file_to_string( 'W/tmp/tests/tests_teelaunch.txt' ), 'teelaunch: reading W/tmp/tests/tests_teelaunch.txt is Hi!\nHoo\n' ) ;
  13757. # closing so tee won't be happy
  13758. close $mysync->{logfile_handle} ;
  13759. is( undef, print( $tee "Argh1\n" ), 'teelaunch: write Argh1') ;
  13760. is( undef, print( $tee "Argh2\n" ), 'teelaunch: write Argh2') ;
  13761. # write not done
  13762. is( "Hi!\nHoo\n", file_to_string( 'W/tmp/tests/tests_teelaunch.txt' ), 'teelaunch: reading W/tmp/tests/tests_teelaunch.txt is still Hi!\nHoo\n' ) ;
  13763. print join( ' ', $tee->handles ), "\n";
  13764. is( 2, scalar $tee->handles, 'teelaunch: 2 handles') ;
  13765. shift @{*{$tee}};
  13766. print join(' ', $tee->handles), "\n" ;
  13767. is( 1, scalar $tee->handles, 'teelaunch: 1 handle') ;
  13768. is( 1, print( $tee "Argh3\n" ), 'teelaunch: write Argh3 yeah') ;
  13769. shift @{*{$tee}};
  13770. # will not print anything now
  13771. is( 0, scalar $tee->handles, 'teelaunch: 0 handle') ;
  13772. is( 1, print( $tee "Argh 4\n" ), 'teelaunch: write Argh4 no') ;
  13773. # Second time, lesson learnt IO::Tee
  13774. $mysync->{logfile} = 'W/tmp/tests/tests_teelaunch2.txt' ;
  13775. isa_ok( $tee = teelaunch( $mysync ), 'IO::Tee' , 'teelaunch: logfile W/tmp/tests/tests_teelaunch2.txt' ) ;
  13776. is( 1, print( $tee "Hi!\n" ), 'teelaunch: write Hi!') ;
  13777. is( "Hi!\n", file_to_string( 'W/tmp/tests/tests_teelaunch2.txt' ), 'teelaunch: reading W/tmp/tests/tests_teelaunch2.txt is Hi!\n' ) ;
  13778. is( 1, print( $tee "Hoo\n" ), 'teelaunch: write Hoo') ;
  13779. is( "Hi!\nHoo\n", file_to_string( 'W/tmp/tests/tests_teelaunch2.txt' ), 'teelaunch: reading W/tmp/tests/tests_teelaunch2.txt is Hi!\nHoo\n' ) ;
  13780. is( 1, teefinish( $mysync ), 'teefinish: return 1') ;
  13781. is( 1, print( $tee "Argh1\n" ), 'teelaunch: write Argh1') ;
  13782. is( 1, print( $tee "Argh2\n" ), 'teelaunch: write Argh2') ;
  13783. is( "Hi!\nHoo\n", file_to_string( 'W/tmp/tests/tests_teelaunch2.txt' ), 'teelaunch: reading W/tmp/tests/tests_teelaunch2.txt is still Hi!\nHoo\n' ) ;
  13784. is( 1, teefinish( $mysync ), 'teefinish: still return 1') ;
  13785. note( 'Leaving tests_teelaunch()' ) ;
  13786. return ;
  13787. }
  13788. sub teelaunch
  13789. {
  13790. my $mysync = shift ;
  13791. if ( ! defined( $mysync ) )
  13792. {
  13793. return ;
  13794. }
  13795. my $logfile = $mysync->{logfile} ;
  13796. if ( ! $logfile )
  13797. {
  13798. return ;
  13799. }
  13800. logfileprepa( $logfile ) || croak "Error no valid directory to write log file $logfile : $OS_ERROR" ;
  13801. # This is a log file opened during the whole sync
  13802. ## no critic (InputOutput::RequireBriefOpen)
  13803. open my $logfile_handle, '>', $logfile
  13804. or croak( "Can not open $logfile for write: $OS_ERROR" ) ;
  13805. binmode $logfile_handle, ":encoding(UTF-8)" ;
  13806. my $tee = IO::Tee->new( $logfile_handle, \*STDOUT ) ;
  13807. $tee->autoflush( 1 ) ;
  13808. $mysync->{logfile_handle} = $logfile_handle ;
  13809. $mysync->{tee} = $tee ;
  13810. return $tee ;
  13811. }
  13812. sub teefinish
  13813. {
  13814. my $mysync = shift ;
  13815. if ( ! defined( $mysync ) ) { return ; }
  13816. my $tee = $mysync->{tee} ;
  13817. if ( ! defined( $tee ) ) { return ; }
  13818. if ( 2 == scalar $tee->handles )
  13819. {
  13820. shift @{*{$tee}};
  13821. }
  13822. else
  13823. {
  13824. # nothing
  13825. }
  13826. return scalar $tee->handles ;
  13827. }
  13828. sub getpwuid_any_os
  13829. {
  13830. my $uid = shift ;
  13831. return( scalar getlogin ) if ( 'MSWin32' eq $OSNAME ) ; # Windows system
  13832. return( scalar getpwuid $uid ) ; # Unix system
  13833. }
  13834. sub abortifneeded
  13835. {
  13836. my $mysync = shift ;
  13837. if ( -e $mysync->{ abortfile } )
  13838. {
  13839. myprint( "Asked to terminate by file $mysync->{ abortfile }\n" ) ;
  13840. do_and_print_stats( $mysync ) ;
  13841. myprint( "You should resynchronize those accounts by running a sync again,\n",
  13842. "since some messages and entire folders might still be missing on host2.\n"
  13843. ) ;
  13844. exit_clean( $mysync, $EXIT_BY_FILE ) ;
  13845. return ;
  13846. }
  13847. else
  13848. {
  13849. return ;
  13850. }
  13851. }
  13852. sub simulong
  13853. {
  13854. my $mysync = shift ;
  13855. my $max_seconds = $mysync->{ simulong } ;
  13856. if ( ! $max_seconds ) { return ; }
  13857. my $division = 5 ;
  13858. my $last_count = int( $division * $max_seconds ) ;
  13859. $mysync->{ debug } and myprint "last_count $last_count = int( division $division * max_seconds $max_seconds)\n" ;
  13860. foreach my $i ( 1 .. ( $last_count ) ) {
  13861. myprint( "Are you still here ETA: " . ( $last_count - $i ) . "/$last_count msgs left\n" ) ;
  13862. #this one is for testing huge page behavior
  13863. #myprint( "Are you still here ETA: " . ($last_count - $i) . "/$last_count msgs left\n" . ( "Ah" x 40 . "\n") x 4000 ) ;
  13864. sleep( 1 / $division ) ;
  13865. abortifneeded( $mysync ) ;
  13866. }
  13867. return ;
  13868. }
  13869. sub printenv
  13870. {
  13871. myprint( "Environment variables listing:\n",
  13872. ( map { "$_ => $ENV{$_}\n" } sort keys %ENV),
  13873. "Environment variables listing end\n" ) ;
  13874. return ;
  13875. }
  13876. sub unittestssuite
  13877. {
  13878. my $mysync = shift ;
  13879. if ( ! ( $mysync->{ tests } or $mysync->{ testsdebug } or $mysync->{ testsunit } ) ) {
  13880. return ;
  13881. }
  13882. my $test_builder = Test::More->builder ;
  13883. tests( $mysync ) ;
  13884. testsdebug( $mysync ) ;
  13885. testunitsession( $mysync ) ;
  13886. my @summary = $test_builder->summary() ;
  13887. my @details = $test_builder->details() ;
  13888. my $nb_tests_run = scalar( @summary ) ;
  13889. my $nb_tests_expected = $test_builder->expected_tests() ;
  13890. my $nb_tests_failed = count_0s( @summary ) ;
  13891. my $tests_failed = report_failures( @details ) ;
  13892. if ( $nb_tests_failed or ( $nb_tests_run != $nb_tests_expected ) ) {
  13893. #$test_builder->reset( ) ;
  13894. myprint( "Summary of tests: failed $nb_tests_failed tests, run $nb_tests_run tests, expected to run $nb_tests_expected tests.\n",
  13895. "List of failed tests:\n", $tests_failed ) ;
  13896. return $EXIT_TESTS_FAILED ;
  13897. }
  13898. cleanup_mess_from_tests( ) ;
  13899. return 0 ;
  13900. }
  13901. sub cleanup_mess_from_tests
  13902. {
  13903. undef @pipemess ;
  13904. return ;
  13905. }
  13906. sub after_get_options
  13907. {
  13908. my $mysync = shift ;
  13909. my $numopt = shift ;
  13910. # exit with --help option or no option at all
  13911. $mysync->{ debug } and myprint( "numopt:$numopt\n" ) ;
  13912. if ( $help or not $numopt ) {
  13913. myprint( usage( $mysync ) ) ;
  13914. exit ;
  13915. }
  13916. return ;
  13917. }
  13918. sub tests_remove_edging_blanks
  13919. {
  13920. note( 'Entering tests_remove_edging_blanks()' ) ;
  13921. is( undef, remove_edging_blanks( ), 'remove_edging_blanks: no args => undef' ) ;
  13922. is( 'abcd', remove_edging_blanks( 'abcd' ), 'remove_edging_blanks: abcd => abcd' ) ;
  13923. is( 'ab cd', remove_edging_blanks( ' ab cd ' ), 'remove_edging_blanks: " ab cd " => "ab cd"' ) ;
  13924. note( 'Leaving tests_remove_edging_blanks()' ) ;
  13925. return ;
  13926. }
  13927. sub remove_edging_blanks
  13928. {
  13929. my $string = shift ;
  13930. if ( ! defined $string )
  13931. {
  13932. return ;
  13933. }
  13934. $string =~ s,^ +| +$,,g ;
  13935. return $string ;
  13936. }
  13937. sub tests_sanitize
  13938. {
  13939. note( 'Entering tests_remove_edging_blanks()' ) ;
  13940. is( undef, sanitize( ), 'sanitize: no args => undef' ) ;
  13941. my $mysync = {} ;
  13942. $mysync->{ host1 } = ' example.com ' ;
  13943. $mysync->{ user1 } = ' to to ' ;
  13944. $mysync->{ password1 } = ' sex is good! ' ;
  13945. is( undef, sanitize( $mysync ), 'sanitize: => undef' ) ;
  13946. is( 'example.com', $mysync->{ host1 }, 'sanitize: host1 " example.com " => "example.com"' ) ;
  13947. is( 'to to', $mysync->{ user1 }, 'sanitize: user1 " to to " => "to to"' ) ;
  13948. is( 'sex is good!', $mysync->{ password1 }, 'sanitize: password1 " sex is good! " => "sex is good!"' ) ;
  13949. note( 'Leaving tests_remove_edging_blanks()' ) ;
  13950. return ;
  13951. }
  13952. sub sanitize
  13953. {
  13954. my $mysync = shift ;
  13955. if ( ! defined $mysync )
  13956. {
  13957. return ;
  13958. }
  13959. foreach my $parameter ( qw( host1 host2 user1 user2 password1 password2 ) )
  13960. {
  13961. $mysync->{ $parameter } = remove_edging_blanks( $mysync->{ $parameter } ) ;
  13962. }
  13963. return ;
  13964. }
  13965. sub easyany
  13966. {
  13967. my $mysync = shift ;
  13968. # Gmail
  13969. if ( $mysync->{gmail1} and $mysync->{gmail2} ) {
  13970. $mysync->{ debug } and myprint( "gmail1 gmail2\n") ;
  13971. gmail12( $mysync ) ;
  13972. return ;
  13973. }
  13974. if ( $mysync->{gmail1} ) {
  13975. $mysync->{ debug } and myprint( "gmail1\n" ) ;
  13976. gmail1( $mysync ) ;
  13977. }
  13978. if ( $mysync->{gmail2} ) {
  13979. $mysync->{ debug } and myprint( "gmail2\n" ) ;
  13980. gmail2( $mysync ) ;
  13981. }
  13982. # Office 365
  13983. if ( $mysync->{office1} ) {
  13984. office1( $mysync ) ;
  13985. }
  13986. if ( $mysync->{office2} ) {
  13987. office2( $mysync ) ;
  13988. }
  13989. # Exchange
  13990. if ( $mysync->{exchange1} ) {
  13991. exchange1( $mysync ) ;
  13992. }
  13993. if ( $mysync->{exchange2} ) {
  13994. exchange2( $mysync ) ;
  13995. }
  13996. # Domino
  13997. if ( $mysync->{domino1} ) {
  13998. domino1( $mysync ) ;
  13999. }
  14000. if ( $mysync->{domino2} ) {
  14001. domino2( $mysync ) ;
  14002. }
  14003. return ;
  14004. }
  14005. # From and for https://imapsync.lamiral.info/FAQ.d/FAQ.Gmail.txt
  14006. sub gmail12
  14007. {
  14008. my $mysync = shift ;
  14009. # Gmail at host1 and host2
  14010. $mysync->{host1} ||= 'imap.gmail.com' ;
  14011. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  14012. $mysync->{host2} ||= 'imap.gmail.com' ;
  14013. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  14014. $mysync->{maxbytespersecond} ||= 20_000 ; # should be less than 10_000 when computed from Gmail documentation
  14015. $mysync->{maxbytesafter} ||= 1_000_000_000 ; # In fact it is documented as half: 500_000_000
  14016. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  14017. $mysync->{maxsleep} = ( defined $mysync->{maxsleep} ) ? $mysync->{maxsleep} : $MAX_SLEEP ; ;
  14018. $skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 0 ;
  14019. $mysync->{ synclabels } = ( defined $mysync->{ synclabels } ) ? $mysync->{ synclabels } : 1 ;
  14020. $mysync->{ resynclabels } = ( defined $mysync->{ resynclabels } ) ? $mysync->{ resynclabels } : 1 ;
  14021. push @exclude, '\[Gmail\]$' ;
  14022. push @folderlast, '[Gmail]/All Mail' ;
  14023. return ;
  14024. }
  14025. sub gmail1
  14026. {
  14027. my $mysync = shift ;
  14028. # Gmail at host2
  14029. $mysync->{host1} ||= 'imap.gmail.com' ;
  14030. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  14031. $mysync->{maxbytespersecond} ||= 40_000 ; # should be 30_000 computed from by Gmail documentation
  14032. $mysync->{maxbytesafter} ||= 3_000_000_000 ; #
  14033. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  14034. $mysync->{maxsleep} = ( defined $mysync->{maxsleep} ) ? $mysync->{maxsleep} : $MAX_SLEEP ; ;
  14035. $skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 1 ;
  14036. push @useheader, 'X-Gmail-Received', 'Message-Id' ;
  14037. push @{ $mysync->{ regextrans2 } }, 's,\[Gmail\].,,' ;
  14038. push @folderlast, '[Gmail]/All Mail' ;
  14039. return ;
  14040. }
  14041. sub gmail2
  14042. {
  14043. my $mysync = shift ;
  14044. # Gmail at host2
  14045. $mysync->{ host2 } ||= 'imap.gmail.com' ;
  14046. $mysync->{ ssl2 } = ( defined $mysync->{ ssl2 } ) ? $mysync->{ ssl2 } : 1 ;
  14047. $mysync->{ maxbytespersecond } ||= 20_000 ; # should be less than 10_000 computed from by Gmail documentation
  14048. $mysync->{ maxbytesafter } ||= 1_000_000_000 ; # In fact it is documented as half: 500_000_000
  14049. $mysync->{ automap } = ( defined $mysync->{ automap } ) ? $mysync->{ automap } : 1 ;
  14050. #$skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 1 ;
  14051. $mysync->{ expunge1 } = ( defined $mysync->{ expunge1 } ) ? $mysync->{ expunge1 } : 1 ;
  14052. $mysync->{ addheader } = ( defined $mysync->{ addheader } ) ? $mysync->{ addheader } : 1 ;
  14053. $mysync->{ maxsleep } = ( defined $mysync->{ maxsleep } ) ? $mysync->{ maxsleep } : $MAX_SLEEP ; ;
  14054. #$mysync->{ maxsize } = ( defined $mysync->{ maxsize } ) ? $mysync->{ maxsize } : $GMAIL_MAXSIZE ;
  14055. if ( ! $mysync->{ noexclude } ) {
  14056. push @exclude, '\[Gmail\]$' ;
  14057. }
  14058. push @useheader, 'Message-Id' ;
  14059. push @{ $mysync->{ regextrans2 } }, 's,\[Gmail\].,,' ;
  14060. # push @{ $mysync->{ regextrans2 } }, 's/[ ]+/_/g' ; # is now replaced
  14061. # by the two more specific following regexes,
  14062. # they remove just the beginning and trailing blanks, not all.
  14063. push @{ $mysync->{ regextrans2 } }, 's,^ +| +$,,g' ;
  14064. push @{ $mysync->{ regextrans2 } }, 's,/ +| +/,/,g' ;
  14065. #
  14066. push @{ $mysync->{ regextrans2 } }, q{s/['\\^"]/_/g} ; # Verified this
  14067. push @folderlast, '[Gmail]/All Mail' ;
  14068. return ;
  14069. }
  14070. # From https://imapsync.lamiral.info/FAQ.d/FAQ.Exchange.txt
  14071. sub office1
  14072. {
  14073. # Office 365 at host1
  14074. my $mysync = shift ;
  14075. output( $mysync, q{Option --office1 is like: --host1 outlook.office365.com --ssl1 --exclude "^Files$"} . "\n" ) ;
  14076. output( $mysync, "Option --office1 (cont) : unless overrided with --host1 otherhost --nossl1 --noexclude\n" ) ;
  14077. $mysync->{host1} ||= 'outlook.office365.com' ;
  14078. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  14079. if ( ! $mysync->{noexclude} ) {
  14080. push @exclude, '^Files$' ;
  14081. }
  14082. return ;
  14083. }
  14084. sub office2
  14085. {
  14086. # Office 365 at host2
  14087. my $mysync = shift ;
  14088. output( $mysync, qq{Option --office2 is like: --host2 outlook.office365.com --ssl2 --maxsize 45_000_000 --maxmessagespersecond 4\n} ) ;
  14089. output( $mysync, qq{Option --office2 (cont) : --disarmreadreceipts --regexmess "wrap 10500" --f1f2 "Files=Files_renamed_by_imapsync"\n} ) ;
  14090. output( $mysync, qq{Option --office2 (cont) : unless overrided with --host2 otherhost --nossl2 ... --nodisarmreadreceipts --noregexmess\n} ) ;
  14091. output( $mysync, qq{Option --office2 (cont) : and --nof1f2 to avoid Files folder renamed to Files_renamed_by_imapsync\n} ) ;
  14092. $mysync->{host2} ||= 'outlook.office365.com' ;
  14093. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  14094. $mysync->{ maxsize } ||= 45_000_000 ;
  14095. $mysync->{maxmessagespersecond} ||= 4 ;
  14096. #push @{ $mysync->{ regexflag } }, 's/\\\\Flagged//g' ; # No problem without! tested 2018_09_10
  14097. $disarmreadreceipts = ( defined $disarmreadreceipts ) ? $disarmreadreceipts : 1 ;
  14098. # I dislike double negation but here is one
  14099. if ( ! $mysync->{noregexmess} )
  14100. {
  14101. push @regexmess, 's,(.{10239}),$1\r\n,g' ;
  14102. }
  14103. # and another...
  14104. if ( ! $mysync->{nof1f2} )
  14105. {
  14106. push @{ $mysync->{f1f2} }, 'Files=Files_renamed_by_imapsync' ;
  14107. }
  14108. return ;
  14109. }
  14110. sub exchange1
  14111. {
  14112. # Exchange 2010/2013 at host1
  14113. my $mysync = shift ;
  14114. output( $mysync, "Option --exchange1 does nothing (except printing this line...)\n" ) ;
  14115. # Well nothing to do so far
  14116. return ;
  14117. }
  14118. sub exchange2
  14119. {
  14120. # Exchange 2010/2013 at host2
  14121. my $mysync = shift ;
  14122. output( $mysync, "Option --exchange2 is like: --maxsize 10_000_000 --maxmessagespersecond 4 --disarmreadreceipts\n" ) ;
  14123. output( $mysync, "Option --exchange2 (cont) : --regexflag del Flagged --regexmess wrap 10500\n" ) ;
  14124. output( $mysync, "Option --exchange2 (cont) : unless overrided with --maxsize xxx --nodisarmreadreceipts --noregexflag --noregexmess\n" ) ;
  14125. $mysync->{ maxsize } ||= 10_000_000 ;
  14126. $mysync->{maxmessagespersecond} ||= 4 ;
  14127. $disarmreadreceipts = ( defined $disarmreadreceipts ) ? $disarmreadreceipts : 1 ;
  14128. # I dislike double negation but here are two
  14129. if ( ! $mysync->{noregexflag} ) {
  14130. push @{ $mysync->{ regexflag } }, 's/\\\\Flagged//g' ;
  14131. }
  14132. if ( ! $mysync->{noregexmess} ) {
  14133. push @regexmess, 's,(.{10239}),$1\r\n,g' ;
  14134. }
  14135. return ;
  14136. }
  14137. sub domino1
  14138. {
  14139. # Domino at host1
  14140. my $mysync = shift ;
  14141. $mysync->{ sep1 } = q{\\} ;
  14142. $prefix1 = q{} ;
  14143. $messageidnodomain = ( defined $messageidnodomain ) ? $messageidnodomain : 1 ;
  14144. return ;
  14145. }
  14146. sub domino2
  14147. {
  14148. # Domino at host1
  14149. my $mysync = shift ;
  14150. $mysync->{ sep2 } = q{\\} ;
  14151. $prefix2 = q{} ;
  14152. $messageidnodomain = ( defined $messageidnodomain ) ? $messageidnodomain : 1 ;
  14153. push @{ $mysync->{ regextrans2 } }, 's,^Inbox\\\\(.*),$1,i' ;
  14154. return ;
  14155. }
  14156. sub tests_resolv
  14157. {
  14158. note( 'Entering tests_resolv()' ) ;
  14159. # is( , resolv( ), 'resolv: => ' ) ;
  14160. is( undef, resolv( ), 'resolv: no args => undef' ) ;
  14161. is( undef, resolv( q{} ), 'resolv: empty string => undef' ) ;
  14162. is( undef, resolv( 'hostnotexist' ), 'resolv: hostnotexist => undef' ) ;
  14163. is( '127.0.0.1', resolv( '127.0.0.1' ), 'resolv: 127.0.0.1 => 127.0.0.1' ) ;
  14164. is( '127.0.0.1', resolv( 'localhost' ), 'resolv: localhost => 127.0.0.1' ) ;
  14165. is( '2001:41d0:2:84e0::1', resolv( 'imapsync.lamiral.info' ), 'resolv: imapsync.lamiral.info => 2001:41d0:2:84e0::1' ) ;
  14166. # ip6-localhost ( in /etc/hosts )
  14167. is( '::1', resolv( 'ip6-localhost' ), 'resolv: ip6-localhost => ::1' ) ;
  14168. is( '::1', resolv( '::1' ), 'resolv: ::1 => ::1' ) ;
  14169. # ks2ipv6 now has CNAME ks6ipv6
  14170. is( '2001:41d0:8:d8b6::1', resolv( '2001:41d0:8:d8b6::1' ), 'resolv: 2001:41d0:8:d8b6::1 => 2001:41d0:8:d8b6::1' ) ;
  14171. is( '2001:41d0:8:9951::1', resolv( 'ks6ipv6.lamiral.info' ), 'resolv: ks6ipv6.lamiral.info => 2001:41d0:8:9951::1' ) ;
  14172. # ks6
  14173. is( '2001:41d0:8:9951::1', resolv( '2001:41d0:8:9951::1' ), 'resolv: 2001:41d0:8:9951::1 => 2001:41d0:8:9951::1' ) ;
  14174. is( '2001:41d0:8:9951::1', resolv( 'ks6ipv6.lamiral.info' ), 'resolv: ks6ipv6.lamiral.info => 2001:41d0:8:9951::1' ) ;
  14175. # ks3
  14176. is( '2001:41d0:8:bebd::1', resolv( '2001:41d0:8:bebd::1' ), 'resolv: 2001:41d0:8:bebd::1 => 2001:41d0:8:bebd::1' ) ;
  14177. is( '2001:41d0:8:bebd::1', resolv( 'ks3ipv6.lamiral.info' ), 'resolv: ks3ipv6.lamiral.info => 2001:41d0:8:bebd::1' ) ;
  14178. note( 'Leaving tests_resolv()' ) ;
  14179. return ;
  14180. }
  14181. sub resolv
  14182. {
  14183. my $host = shift @ARG ;
  14184. if ( ! $host ) { return ; }
  14185. my $addr ;
  14186. if ( defined &Socket::getaddrinfo ) {
  14187. $addr = resolv_with_getaddrinfo( $host ) ;
  14188. return( $addr ) ;
  14189. }
  14190. my $iaddr = inet_aton( $host ) ;
  14191. if ( ! $iaddr ) { return ; }
  14192. $addr = inet_ntoa( $iaddr ) ;
  14193. return $addr ;
  14194. }
  14195. sub resolv_with_getaddrinfo
  14196. {
  14197. my $host = shift @ARG ;
  14198. $sync->{ debug } and myprint( "Entering resolv_with_getaddrinfo( $host )\n" ) ;
  14199. if ( ! $host ) { return ; }
  14200. my ( $err_getaddrinfo, @res ) = Socket::getaddrinfo( $host, "", { socktype => Socket::SOCK_RAW } ) ;
  14201. if ( $err_getaddrinfo ) {
  14202. myprint( "Cannot getaddrinfo of $host: $err_getaddrinfo\n" ) ;
  14203. return ;
  14204. }
  14205. my @addr ;
  14206. while( my $ai = shift @res ) {
  14207. my ( $err_getnameinfo, $ipaddr ) = Socket::getnameinfo( $ai->{addr}, Socket::NI_NUMERICHOST(), Socket::NIx_NOSERV() ) ;
  14208. if ( $err_getnameinfo ) {
  14209. myprint( "Cannot getnameinfo of $host: $err_getnameinfo\n" ) ;
  14210. return ;
  14211. }else{
  14212. $sync->{ debug } and myprint( "$host => $ipaddr\n" ) ;
  14213. push @addr, $ipaddr ;
  14214. my $reverse ;
  14215. ( $err_getnameinfo, $reverse ) = Socket::getnameinfo( $ai->{addr}, 0, Socket::NIx_NOSERV() ) ;
  14216. $sync->{ debug } and myprint( "$host => $ipaddr => $reverse\n" ) ;
  14217. }
  14218. $sync->{ debug } and myprint( "$host => $ipaddr\n" ) ;
  14219. }
  14220. $sync->{ debug } and myprint( "Leaving resolv_with_getaddrinfo( $host => $addr[0])\n" ) ;
  14221. return $addr[0] ;
  14222. }
  14223. sub tests_resolvrev
  14224. {
  14225. note( 'Entering tests_resolvrev()' ) ;
  14226. # is( , resolvrev( ), 'resolvrev: => ' ) ;
  14227. is( undef, resolvrev( ), 'resolvrev: no args => undef' ) ;
  14228. is( undef, resolvrev( q{} ), 'resolvrev: empty string => undef' ) ;
  14229. is( undef, resolvrev( 'hostnotexist' ), 'resolvrev: hostnotexist => undef' ) ;
  14230. is( 'localhost', resolvrev( '127.0.0.1' ), 'resolvrev: 127.0.0.1 => localhost' ) ;
  14231. is( 'localhost', resolvrev( 'localhost' ), 'resolvrev: localhost => localhost' ) ;
  14232. is( 'ks.lamiral.info', resolvrev( 'imapsync.lamiral.info' ), 'resolvrev: imapsync.lamiral.info => ks.lamiral.info' ) ;
  14233. # ip6-localhost ( in /etc/hosts )
  14234. is( 'ip6-localhost', resolvrev( 'ip6-localhost' ), 'resolvrev: ip6-localhost => ip6-localhost' ) ;
  14235. is( 'ip6-localhost', resolvrev( '::1' ), 'resolvrev: ::1 => ip6-localhost' ) ;
  14236. # ks2
  14237. is( 'ks6ipv6.lamiral.info', resolvrev( '2001:41d0:8:d8b6::1' ), 'resolvrev: 2001:41d0:8:d8b6::1 => ks6ipv6.lamiral.info' ) ;
  14238. is( 'ks6ipv6.lamiral.info', resolvrev( 'ks6ipv6.lamiral.info' ), 'resolvrev: ks6ipv6.lamiral.info => ks6ipv6.lamiral.info' ) ;
  14239. # ks3
  14240. is( 'ks3ipv6.lamiral.info', resolvrev( '2001:41d0:8:bebd::1' ), 'resolvrev: 2001:41d0:8:bebd::1 => ks3ipv6.lamiral.info' ) ;
  14241. is( 'ks3ipv6.lamiral.info', resolvrev( 'ks3ipv6.lamiral.info' ), 'resolvrev: ks3ipv6.lamiral.info => ks3ipv6.lamiral.info' ) ;
  14242. note( 'Leaving tests_resolvrev()' ) ;
  14243. return ;
  14244. }
  14245. sub resolvrev
  14246. {
  14247. my $host = shift @ARG ;
  14248. if ( ! $host ) { return ; }
  14249. if ( defined &Socket::getaddrinfo ) {
  14250. my $name = resolvrev_with_getaddrinfo( $host ) ;
  14251. return( $name ) ;
  14252. }
  14253. return ;
  14254. }
  14255. sub resolvrev_with_getaddrinfo
  14256. {
  14257. my $host = shift @ARG ;
  14258. if ( ! $host ) { return ; }
  14259. my ( $err, @res ) = Socket::getaddrinfo( $host, "", { socktype => Socket::SOCK_RAW } ) ;
  14260. if ( $err ) {
  14261. myprint( "Cannot getaddrinfo of $host: $err\n" ) ;
  14262. return ;
  14263. }
  14264. my @name ;
  14265. while( my $ai = shift @res ) {
  14266. my ( $err, $reverse ) = Socket::getnameinfo( $ai->{addr}, 0, Socket::NIx_NOSERV() ) ;
  14267. if ( $err ) {
  14268. myprint( "Cannot getnameinfo of $host: $err\n" ) ;
  14269. return ;
  14270. }
  14271. $sync->{ debug } and myprint( "$host => $reverse\n" ) ;
  14272. push @name, $reverse ;
  14273. }
  14274. return $name[0] ;
  14275. }
  14276. sub tests_imapsping
  14277. {
  14278. note( 'Entering tests_imapsping()' ) ;
  14279. is( undef, imapsping( ), 'imapsping: no args => undef' ) ;
  14280. is( undef, imapsping( 'hostnotexist' ), 'imapsping: hostnotexist => undef' ) ;
  14281. is( 1, imapsping( 'imapsync.lamiral.info' ), 'imapsping: imapsync.lamiral.info => 1' ) ;
  14282. is( 1, imapsping( 'ks6ipv6.lamiral.info' ), 'imapsping: ks6ipv6.lamiral.info => 1' ) ;
  14283. note( 'Leaving tests_imapsping()' ) ;
  14284. return ;
  14285. }
  14286. sub imapsping
  14287. {
  14288. my $host = shift ;
  14289. return tcpping( $host, $IMAP_SSL_PORT ) ;
  14290. }
  14291. sub tests_tcpping
  14292. {
  14293. note( 'Entering tests_tcpping()' ) ;
  14294. is( undef, tcpping( ), 'tcpping: no args => undef' ) ;
  14295. is( undef, tcpping( 'hostnotexist' ), 'tcpping: one arg => undef' ) ;
  14296. is( undef, tcpping( undef, 888 ), 'tcpping: arg undef, port => undef' ) ;
  14297. is( undef, tcpping( 'hostnotexist', 993 ), 'tcpping: hostnotexist 993 => undef' ) ;
  14298. is( undef, tcpping( 'hostnotexist', 888 ), 'tcpping: hostnotexist 888 => undef' ) ;
  14299. is( 1, tcpping( 'imapsync.lamiral.info', 993 ), 'tcpping: imapsync.lamiral.info 993 => 1' ) ;
  14300. is( 0, tcpping( 'imapsync.lamiral.info', 888 ), 'tcpping: imapsync.lamiral.info 888 => 0' ) ;
  14301. is( 1, tcpping( '5.135.158.182', 993 ), 'tcpping: 5.135.158.182 993 => 1' ) ;
  14302. is( 0, tcpping( '5.135.158.182', 888 ), 'tcpping: 5.135.158.182 888 => 0' ) ;
  14303. # Net::Ping supports ipv6 only after release 1.50
  14304. # http://cpansearch.perl.org/src/RURBAN/Net-Ping-2.59/Changes
  14305. # Anyway I plan to avoid Net-Ping for that too long standing feature
  14306. # Net-Ping is integrated in Perl itself, who knows ipv6 for a long time
  14307. is( 1, tcpping( '2001:41d0:8:d8b6::1', 993 ), 'tcpping: 2001:41d0:8:d8b6::1 993 => 1' ) ;
  14308. is( 0, tcpping( '2001:41d0:8:d8b6::1', 888 ), 'tcpping: 2001:41d0:8:d8b6::1 888 => 0' ) ;
  14309. note( 'Leaving tests_tcpping()' ) ;
  14310. return ;
  14311. }
  14312. sub tcpping
  14313. {
  14314. if ( 2 != scalar( @ARG ) ) {
  14315. return ;
  14316. }
  14317. my ( $host, $port ) = @ARG ;
  14318. if ( ! $host ) { return ; }
  14319. if ( ! $port ) { return ; }
  14320. my $mytimeout = $TCP_PING_TIMEOUT ;
  14321. require Net::Ping ;
  14322. #my $p = Net::Ping->new( 'tcp' ) ;
  14323. my $p = Net::Ping->new( ) ;
  14324. $p->{port_num} = $port ;
  14325. $p->service_check( 1 ) ;
  14326. $p->hires( 1 ) ;
  14327. my ($ping_ok, $rtt, $ip ) = $p->ping( $host, $mytimeout ) ;
  14328. if ( ! defined $ping_ok ) { return ; }
  14329. my $rtt_approx = sprintf( "%.3f", $rtt ) ;
  14330. $sync->{ debug } and myprint( "Host $host timeout $mytimeout port $port ok $ping_ok ip $ip acked in $rtt_approx s\n" ) ;
  14331. $p->close( ) ;
  14332. if( $ping_ok ) {
  14333. return 1 ;
  14334. }else{
  14335. return 0 ;
  14336. }
  14337. }
  14338. sub tests_sslcheck
  14339. {
  14340. note( 'Entering tests_sslcheck()' ) ;
  14341. my $mysync ;
  14342. is( undef, sslcheck( $mysync ), 'sslcheck: no sslcheck => undef' ) ;
  14343. $mysync = {
  14344. sslcheck => 1,
  14345. } ;
  14346. is( 0, sslcheck( $mysync ), 'sslcheck: no host => 0' ) ;
  14347. $mysync = {
  14348. sslcheck => 1,
  14349. host1 => 'test1.lamiral.info',
  14350. tls1 => 1,
  14351. } ;
  14352. is( 0, sslcheck( $mysync ), 'sslcheck: tls1 => 0' ) ;
  14353. $mysync = {
  14354. sslcheck => 1,
  14355. host1 => 'test1.lamiral.info',
  14356. } ;
  14357. is( 1, sslcheck( $mysync ), 'sslcheck: test1.lamiral.info => 1' ) ;
  14358. is( 1, $mysync->{ssl1}, 'sslcheck: test1.lamiral.info => ssl1 1' ) ;
  14359. $mysync->{sslcheck} = 0 ;
  14360. is( undef, sslcheck( $mysync ), 'sslcheck: sslcheck off => undef' ) ;
  14361. $mysync = {
  14362. sslcheck => 1,
  14363. host1 => 'test1.lamiral.info',
  14364. host2 => 'test2.lamiral.info',
  14365. } ;
  14366. is( 2, sslcheck( $mysync ), 'sslcheck: test1.lamiral.info + test2.lamiral.info => 2' ) ;
  14367. $mysync = {
  14368. sslcheck => 1,
  14369. host1 => 'test1.lamiral.info',
  14370. host2 => 'test2.lamiral.info',
  14371. tls1 => 1,
  14372. } ;
  14373. is( 1, sslcheck( $mysync ), 'sslcheck: test1.lamiral.info + test2.lamiral.info + tls1 => 1' ) ;
  14374. note( 'Leaving tests_sslcheck()' ) ;
  14375. return ;
  14376. }
  14377. sub sslcheck
  14378. {
  14379. my $mysync = shift ;
  14380. if ( ! $mysync->{sslcheck} ) {
  14381. return ;
  14382. }
  14383. my $nb_on = 0 ;
  14384. $mysync->{ debug } and myprint( "sslcheck\n" ) ;
  14385. if (
  14386. ( ! defined $mysync->{port1} )
  14387. and
  14388. ( ! defined $mysync->{tls1} )
  14389. and
  14390. ( ! defined $mysync->{ssl1} )
  14391. and
  14392. ( defined $mysync->{host1} )
  14393. ) {
  14394. myprint( "Host1: probing ssl on port $IMAP_SSL_PORT ( use --nosslcheck to avoid this ssl probe ) \n" ) ;
  14395. if ( probe_imapssl( $mysync->{host1} ) ) {
  14396. $mysync->{ssl1} = 1 ;
  14397. 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" ) ;
  14398. $nb_on++ ;
  14399. }else{
  14400. myprint( "Host1: sslcheck did not detected open ssl port $IMAP_SSL_PORT. Will use standard $IMAP_PORT port.\n" ) ;
  14401. }
  14402. }
  14403. if (
  14404. ( ! defined $mysync->{port2} )
  14405. and
  14406. ( ! defined $mysync->{tls2} )
  14407. and
  14408. ( ! defined $mysync->{ssl2} )
  14409. and
  14410. ( defined $mysync->{host2} )
  14411. ) {
  14412. myprint( "Host2: probing ssl on port $IMAP_SSL_PORT ( use --nosslcheck to avoid this ssl probe ) \n" ) ;
  14413. if ( probe_imapssl( $mysync->{host2} ) ) {
  14414. $mysync->{ssl2} = 1 ;
  14415. 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" ) ;
  14416. $nb_on++ ;
  14417. }else{
  14418. myprint( "Host2: sslcheck did not detected open ssl port $IMAP_SSL_PORT. Will use standard $IMAP_PORT port.\n" ) ;
  14419. }
  14420. }
  14421. return $nb_on ;
  14422. }
  14423. sub testslive_init
  14424. {
  14425. my $mysync = shift ;
  14426. $mysync->{host1} ||= 'test1.lamiral.info' ;
  14427. $mysync->{user1} ||= 'test1' ;
  14428. $mysync->{password1} ||= 'secret1' ;
  14429. $mysync->{host2} ||= 'test2.lamiral.info' ;
  14430. $mysync->{user2} ||= 'test2' ;
  14431. $mysync->{password2} ||= 'secret2' ;
  14432. return ;
  14433. }
  14434. sub testslive6_init
  14435. {
  14436. my $mysync = shift ;
  14437. $mysync->{host1} ||= 'ks6ipv6.lamiral.info' ;
  14438. $mysync->{user1} ||= 'test1' ;
  14439. $mysync->{password1} ||= 'secret1' ;
  14440. $mysync->{host2} ||= 'ks6ipv6.lamiral.info' ;
  14441. $mysync->{user2} ||= 'test2' ;
  14442. $mysync->{password2} ||= 'secret2' ;
  14443. return ;
  14444. }
  14445. sub tests_backslash_caret
  14446. {
  14447. note( 'Entering tests_backslash_caret()' ) ;
  14448. is( "lalala", backslash_caret( "lalala" ), 'backslash_caret: lalala => lalala' ) ;
  14449. is( "lalala\n", backslash_caret( "lalala\n" ), 'backslash_caret: lalala => lalala 2nd' ) ;
  14450. is( '^', backslash_caret( '\\' ), 'backslash_caret: \\ => ^' ) ;
  14451. is( "^\n", backslash_caret( "\\\n" ), 'backslash_caret: \\ => ^' ) ;
  14452. is( "\\lalala", backslash_caret( "\\lalala" ), 'backslash_caret: \\lalala => \\lalala' ) ;
  14453. is( "\\lal\\ala", backslash_caret( "\\lal\\ala" ), 'backslash_caret: \\lal\\ala => \\lal\\ala' ) ;
  14454. is( "\\lalala\n", backslash_caret( "\\lalala\n" ), 'backslash_caret: \\lalala => \\lalala 2nd' ) ;
  14455. is( "lalala^\n", backslash_caret( "lalala\\\n" ), 'backslash_caret: lalala\\\n => lalala^\n' ) ;
  14456. is( "lalala^\nlalala^\n", backslash_caret( "lalala\\\nlalala\\\n" ), 'backslash_caret: lalala\\\nlalala\\\n => lalala^\nlalala^\n' ) ;
  14457. is( "lal\\ala^\nlalala^\n", backslash_caret( "lal\\ala\\\nlalala\\\n" ), 'backslash_caret: lal\\ala\\\nlalala\\\n => lal\\ala^\nlalala^\n' ) ;
  14458. note( 'Leaving tests_backslash_caret()' ) ;
  14459. return ;
  14460. }
  14461. sub backslash_caret
  14462. {
  14463. my $string = shift ;
  14464. $string =~ s{\\ $ }{^}gxms ;
  14465. return $string ;
  14466. }
  14467. sub tests_split_around_equal
  14468. {
  14469. note( 'Entering tests_split_around_equal()' ) ;
  14470. is( undef, split_around_equal( ), 'split_around_equal: no args => undef' ) ;
  14471. is_deeply( { toto => 'titi' }, { split_around_equal( 'toto=titi' ) }, 'split_around_equal: toto=titi => toto => titi' ) ;
  14472. is_deeply( { A => 'B', C => 'D' }, { split_around_equal( 'A=B=C=D' ) }, 'split_around_equal: toto=titi => toto => titi' ) ;
  14473. is_deeply( { A => 'B', C => 'D' }, { split_around_equal( 'A=B', 'C=D' ) }, 'split_around_equal: A=B C=D => A => B, C=>D' ) ;
  14474. note( 'Leaving tests_split_around_equal()' ) ;
  14475. return ;
  14476. }
  14477. sub split_around_equal
  14478. {
  14479. if ( ! @ARG ) { return ; } ;
  14480. return map { split /=/mxs, $_ } @ARG ;
  14481. }
  14482. sub tests_sig_install
  14483. {
  14484. note( 'Entering tests_sig_install()' ) ;
  14485. my $mysync ;
  14486. is( undef, sig_install( ), 'sig_install: no args => undef' ) ;
  14487. is( undef, sig_install( $mysync ), 'sig_install: arg undef => undef' ) ;
  14488. $mysync = { } ;
  14489. is( undef, sig_install( $mysync ), 'sig_install: empty hash => undef' ) ;
  14490. SKIP: {
  14491. Readonly my $SKIP_15 => 15 ;
  14492. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests only for Unix', $SKIP_15 ) ; }
  14493. # Default to ignore USR1 USR2 in case future install fails
  14494. local $SIG{ USR1 } = local $SIG{ USR2 } = sub { } ;
  14495. kill( 'USR1', $PROCESS_ID ) ;
  14496. $mysync->{ debugsig } = 1 ;
  14497. # Assign USR1 to call sub tototo
  14498. # Surely a better value than undef should be returned when doing real signal stuff
  14499. is( undef, sig_install( $mysync, 'tototo', 'USR1' ), 'sig_install: USR1 tototo' ) ;
  14500. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 1' ) ;
  14501. is( 1, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 1' ) ;
  14502. #return ;
  14503. # Assign USR2 to call sub tototo
  14504. is( undef, sig_install( $mysync, 'tototo', 'USR2' ), 'sig_install: USR2 tototo' ) ;
  14505. is( 1, kill( 'USR2', $PROCESS_ID ), 'sig_install: kill USR2 myself 1' ) ;
  14506. is( 2, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 2' ) ;
  14507. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 2' ) ;
  14508. is( 3, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 3' ) ;
  14509. local $SIG{ USR1 } = local $SIG{ USR2 } = sub { } ;
  14510. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 3' ) ;
  14511. is( 3, $mysync->{ tototo_calls }, 'sig_install: tototo call still nb 3' ) ;
  14512. # Assign USR1 + USR2 to call sub tototo
  14513. is( undef, sig_install( $mysync, 'tototo', 'USR1', 'USR2' ), 'sig_install: USR1 USR2 tototo' ) ;
  14514. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 4' ) ;
  14515. is( 4, $mysync->{ tototo_calls }, 'sig_install: tototo call now nb 4' ) ;
  14516. is( 1, kill( 'USR2', $PROCESS_ID ), 'sig_install: kill USR1 myself 2' ) ;
  14517. is( 5, $mysync->{ tototo_calls }, 'sig_install: tototo call now nb 5' ) ;
  14518. }
  14519. note( 'Leaving tests_sig_install()' ) ;
  14520. return ;
  14521. }
  14522. #
  14523. sub sig_install
  14524. {
  14525. my $mysync = shift ;
  14526. if ( ! $mysync ) { return ; }
  14527. my $mysubname = shift ;
  14528. if ( ! $mysubname ) { return ; }
  14529. if ( ! @ARG ) { return ; }
  14530. my @signals = @ARG ;
  14531. my $mysub = \&$mysubname ;
  14532. #$mysync->{ debugsig } = 1 ;
  14533. $mysync->{ debugsig } and myprint( "In sig_install with sub $mysubname and signal @ARG\n" ) ;
  14534. my $subsignal = sub {
  14535. my $signame = shift ;
  14536. $mysync->{ debugsig } and myprint( "In subsignal with $signame and $mysubname\n" ) ;
  14537. &$mysub( $mysync, $signame ) ;
  14538. } ;
  14539. foreach my $signal ( @signals ) {
  14540. $mysync->{ debugsig } and myprint( "Installing signal $signal to call sub $mysubname\n") ;
  14541. output( $mysync, "kill -$signal $PROCESS_ID # special behavior: call to sub $mysubname\n" ) ;
  14542. ## no critic (RequireLocalizedPunctuationVars)
  14543. $SIG{ $signal } = $subsignal ;
  14544. }
  14545. return ;
  14546. }
  14547. sub tototo
  14548. {
  14549. my $mysync = shift ;
  14550. myprint("In tototo with @ARG\n" ) ;
  14551. $mysync->{ tototo_calls } += 1 ;
  14552. return ;
  14553. }
  14554. sub mygetppid
  14555. {
  14556. if ( 'MSWin32' eq $OSNAME ) {
  14557. return( 'unknown under MSWin32 (too complicated)' ) ;
  14558. } else {
  14559. # Unix
  14560. return( getppid( ) ) ;
  14561. }
  14562. }
  14563. sub tests_toggle_sleep
  14564. {
  14565. note( 'Entering tests_toggle_sleep()' ) ;
  14566. is( undef, toggle_sleep( ), 'toggle_sleep: no args => undef' ) ;
  14567. my $mysync ;
  14568. is( undef, toggle_sleep( $mysync ), 'toggle_sleep: undef => undef' ) ;
  14569. $mysync = { } ;
  14570. is( undef, toggle_sleep( $mysync ), 'toggle_sleep: no maxsleep => undef' ) ;
  14571. $mysync->{maxsleep} = 3 ;
  14572. is( 0, toggle_sleep( $mysync ), 'toggle_sleep: 3 => 0' ) ;
  14573. is( $MAX_SLEEP, toggle_sleep( $mysync ), "toggle_sleep: 0 => $MAX_SLEEP" ) ;
  14574. is( 0, toggle_sleep( $mysync ), "toggle_sleep: $MAX_SLEEP => 0" ) ;
  14575. is( $MAX_SLEEP, toggle_sleep( $mysync ), "toggle_sleep: 0 => $MAX_SLEEP" ) ;
  14576. is( 0, toggle_sleep( $mysync ), "toggle_sleep: $MAX_SLEEP => 0" ) ;
  14577. SKIP: {
  14578. Readonly my $SKIP_9 => 9 ;
  14579. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests only for Unix', $SKIP_9 ) ; }
  14580. # Default to ignore USR1 USR2 in case future install fails
  14581. local $SIG{ USR1 } = sub { } ;
  14582. kill( 'USR1', $PROCESS_ID ) ;
  14583. $mysync->{ debugsig } = 1 ;
  14584. # Assign USR1 to call sub toggle_sleep
  14585. is( undef, sig_install( $mysync, \&toggle_sleep, 'USR1' ), 'toggle_sleep: install USR1 toggle_sleep' ) ;
  14586. $mysync->{maxsleep} = 4 ;
  14587. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself' ) ;
  14588. is( 0, $mysync->{ maxsleep }, 'toggle_sleep: toggle_sleep called => sleeps are 0s' ) ;
  14589. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself again' ) ;
  14590. is( $MAX_SLEEP, $mysync->{ maxsleep }, "toggle_sleep: toggle_sleep called => sleeps are ${MAX_SLEEP}s" ) ;
  14591. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself' ) ;
  14592. is( 0, $mysync->{ maxsleep }, 'toggle_sleep: toggle_sleep called => sleeps are 0s' ) ;
  14593. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself again' ) ;
  14594. is( $MAX_SLEEP, $mysync->{ maxsleep }, "toggle_sleep: toggle_sleep called => sleeps are ${MAX_SLEEP}s" ) ;
  14595. }
  14596. note( 'Leaving tests_toggle_sleep()' ) ;
  14597. return ;
  14598. }
  14599. sub toggle_sleep
  14600. {
  14601. my $mysync = shift ;
  14602. myprint("In toggle_sleep with @ARG\n" ) ;
  14603. if ( !defined( $mysync ) ) { return ; }
  14604. if ( !defined( $mysync->{maxsleep} ) ) { return ; }
  14605. $mysync->{ maxsleep } = max( 0, $MAX_SLEEP - $mysync->{maxsleep} ) ;
  14606. myprint("Resetting maxsleep to ", $mysync->{maxsleep}, "s\n" ) ;
  14607. return $mysync->{maxsleep} ;
  14608. }
  14609. sub mypod2usage
  14610. {
  14611. my $fh_pod2usage = shift ;
  14612. pod2usage(
  14613. -exitval => 'NOEXIT',
  14614. -noperldoc => 1,
  14615. -verbose => 99,
  14616. -sections => [ qw(NAME VERSION USAGE OPTIONS) ],
  14617. -indent => 1,
  14618. -loose => 1,
  14619. -output => $fh_pod2usage,
  14620. ) ;
  14621. return ;
  14622. }
  14623. sub usage
  14624. {
  14625. my $mysync = shift ;
  14626. if ( ! defined $mysync ) { return ; }
  14627. my $usage = q{} ;
  14628. my $usage_from_pod ;
  14629. my $usage_footer = usage_footer( $mysync ) ;
  14630. # pod2usage writes on a filehandle only and I want a variable
  14631. open my $fh_pod2usage, ">", \$usage_from_pod
  14632. or do { warn $OS_ERROR ; return ; } ;
  14633. mypod2usage( $fh_pod2usage ) ;
  14634. close $fh_pod2usage ;
  14635. if ( 'MSWin32' eq $OSNAME ) {
  14636. $usage_from_pod = backslash_caret( $usage_from_pod ) ;
  14637. }
  14638. $usage = join( q{}, $usage_from_pod, $usage_footer ) ;
  14639. return( $usage ) ;
  14640. }
  14641. sub tests_usage
  14642. {
  14643. note( 'Entering tests_usage()' ) ;
  14644. my $usage ;
  14645. like( $usage = usage( $sync ), qr/Name:/, 'usage: contains Name:' ) ;
  14646. myprint( $usage ) ;
  14647. like( $usage, qr/Version:/, 'usage: contains Version:' ) ;
  14648. like( $usage, qr/Usage:/, 'usage: contains Usage:' ) ;
  14649. like( $usage, qr/imapsync/, 'usage: contains imapsync' ) ;
  14650. is( undef, usage( ), 'usage: no args => undef' ) ;
  14651. note( 'Leaving tests_usage()' ) ;
  14652. return ;
  14653. }
  14654. sub usage_footer
  14655. {
  14656. my $mysync = shift ;
  14657. my $footer = q{} ;
  14658. my $localhost_info = localhost_info( $mysync ) ;
  14659. my $rcs = $mysync->{rcs} ;
  14660. my $homepage = homepage( ) ;
  14661. my $imapsync_release = $STR_use_releasecheck ;
  14662. if ( $mysync->{releasecheck} ) {
  14663. $imapsync_release = check_last_release( ) ;
  14664. }
  14665. $footer = qq{$localhost_info
  14666. $rcs
  14667. $imapsync_release
  14668. $homepage
  14669. } ;
  14670. return( $footer ) ;
  14671. }
  14672. sub usage_complete
  14673. {
  14674. # Unused, I guess this function could be deleted
  14675. my $usage = <<'EOF' ;
  14676. --skipheader reg : Don't take into account header keyword
  14677. matching reg ex: --skipheader 'X.*'
  14678. --skipsize : Don't take message size into account to compare
  14679. messages on both sides. On by default.
  14680. Use --no-skipsize for using size comparaison.
  14681. --allowsizemismatch : allow RFC822.SIZE != fetched msg size
  14682. consider also --skipsize to avoid duplicate messages
  14683. when running syncs more than one time per mailbox
  14684. --reconnectretry1 int : reconnect to host1 if connection is lost up to
  14685. int times per imap command (default is 3)
  14686. --reconnectretry2 int : same as --reconnectretry1 but for host2
  14687. --split1 int : split the requests in several parts on host1.
  14688. int is the number of messages handled per request.
  14689. default is like --split1 100.
  14690. --split2 int : same thing on host2.
  14691. --nofixInboxINBOX : Don't fix Inbox INBOX mapping.
  14692. EOF
  14693. return( $usage ) ;
  14694. }
  14695. sub setvalfromcgikey
  14696. {
  14697. my ( $mysync, $mycgi, $key, $val ) = @ARG ;
  14698. my $badthings = 0 ;
  14699. my ( $name, $type, $struct ) ;
  14700. if ( $key !~ m/^([\w\d\|]+)([=:][isf])?([\+!\@\%])?$/mxs )
  14701. {
  14702. $badthings++ ;
  14703. next ; # Unknown item
  14704. }
  14705. else
  14706. {
  14707. $name = [ split '|', $1, 1 ]->[0] ; # option name ab|cd|ef => keep only ab
  14708. $type = $2 ; # = or : followed by i or s or f
  14709. $struct = $3 ; # + or ! or @ or %
  14710. }
  14711. if ( ( $struct || q{} ) eq '+' )
  14712. {
  14713. ${$val} = $mycgi->param( $name ) ; # "Incremental" integer
  14714. }
  14715. elsif ( $type )
  14716. {
  14717. my @values = $mycgi->multi_param( $name ) ;
  14718. #myprint( "type[$type]values[@values]\$struct[", $struct || q{}, "]val[$val]ref(val)[", ref($val), "]\n" ) ;
  14719. if ( ( $struct || q{} ) eq '%' or ref( $val ) eq 'HASH' )
  14720. {
  14721. setvalfromhash( $val, $type, @values ) ;
  14722. }
  14723. else
  14724. {
  14725. setvalfromlist( $mysync, $val, $name, $type, $struct, @values ) ;
  14726. }
  14727. }
  14728. else
  14729. {
  14730. setvalfromcheckbox( $mysync, $mycgi, $key, $name, $val ) ;
  14731. }
  14732. return $badthings ;
  14733. }
  14734. sub setvalfromlist
  14735. {
  14736. my ( $mysync, $val, $name, $type, $struct, @values ) = @ARG ;
  14737. if ( $type =~ m/i$/mxs )
  14738. {
  14739. @values = map { q{} ne $_ ? int $_ : undef } @values ;
  14740. }
  14741. elsif ( $type =~ m/f$/mxs )
  14742. {
  14743. @values = map { 0 + $_ } @values ;
  14744. }
  14745. if ( ( $struct || q{} ) eq '@' )
  14746. {
  14747. @{ ${$val} } = @values ;
  14748. my @option = map { +( "--$name", "$_" ) } @values ;
  14749. push @{ $mysync->{ cmdcgi } }, @option ;
  14750. }
  14751. elsif ( ref( $val ) eq 'ARRAY' )
  14752. {
  14753. @{$val} = @values ;
  14754. }
  14755. elsif ( my $value = $values[0] )
  14756. {
  14757. ${$val} = $value ;
  14758. push @{ $mysync->{ cmdcgi } }, "--$name", $value ;
  14759. }
  14760. else
  14761. {
  14762. }
  14763. return ;
  14764. }
  14765. sub setvalfromhash
  14766. {
  14767. my ( $val, $type, @values ) = @ARG ;
  14768. my %values = map { split /=/mxs, $_ } @values ;
  14769. if ( $type =~ m/i$/mxs )
  14770. {
  14771. foreach my $k ( keys %values )
  14772. {
  14773. $values{$k} = int $values{$k} ;
  14774. }
  14775. }
  14776. elsif ( $type =~ m/f$/mxs )
  14777. {
  14778. foreach my $k ( keys %values ) {
  14779. $values{$k} = 0 + $values{$k};
  14780. }
  14781. }
  14782. if ( 'REF' eq ref $val )
  14783. {
  14784. %{ ${$val} } = %values ;
  14785. }
  14786. else
  14787. {
  14788. %{$val} = %values ;
  14789. }
  14790. return ;
  14791. }
  14792. sub setvalfromcheckbox
  14793. {
  14794. my ( $mysync, $mycgi, $key, $name, $val ) = @ARG ;
  14795. # Checkbox
  14796. # --noname is set by name=0 or name=
  14797. my $value = $mycgi->param( $name ) ;
  14798. if ( defined $value )
  14799. {
  14800. ${$val} = $value ;
  14801. if ( $value )
  14802. {
  14803. push @{ $mysync->{ cmdcgi } }, "--$name" ;
  14804. }
  14805. else
  14806. {
  14807. push @{ $mysync->{ cmdcgi } }, "--no$name" ;
  14808. }
  14809. }
  14810. else
  14811. {
  14812. ${$val} = undef ;
  14813. }
  14814. return ;
  14815. }
  14816. sub myGetOptions
  14817. {
  14818. # Started as a copy of Luke Ross Getopt::Long::CGI
  14819. # https://metacpan.org/release/Getopt-Long-CGI
  14820. # So this sub function is under the same license as Getopt-Long-CGI Luke Ross wants it,
  14821. # which was Perl 5.6 or later licenses at the date of the copy.
  14822. # It also applies for the sub functions called from this one.
  14823. my $mysync = shift @ARG ;
  14824. my $arguments_ref = shift @ARG ;
  14825. my %options = @ARG ;
  14826. my $mycgi = $mysync->{cgi} ;
  14827. if ( not under_cgi_context() ) {
  14828. # Not CGI - pass upstream for normal command line handling
  14829. return Getopt::Long::GetOptionsFromArray( $arguments_ref, %options ) ;
  14830. }
  14831. # We must be in CGI context now
  14832. if ( ! defined( $mycgi ) ) { return ; }
  14833. my $badthings = 0 ;
  14834. foreach my $key ( sort keys %options ) {
  14835. my $val = $options{$key} ;
  14836. $badthings += setvalfromcgikey( $mysync, $mycgi, $key, $val ) ;
  14837. }
  14838. if ( $badthings ) {
  14839. return ; # undef or ()
  14840. }
  14841. else {
  14842. return ( 1 ) ;
  14843. }
  14844. }
  14845. sub tests_get_options_cgi_context
  14846. {
  14847. note( 'Entering tests_get_options_cgi_context()' ) ;
  14848. # Temporary, have to think harder about testing CGI context in command line --tests
  14849. # API:
  14850. # * input arguments: two ways, command line or CGI
  14851. # * the program arguments
  14852. # * QUERY_STRING env variable
  14853. # * return
  14854. # * QUERY_STRING length
  14855. # CGI context
  14856. local $ENV{SERVER_SOFTWARE} = 'Votre serviteur' ;
  14857. # Real full test
  14858. # = 'host1=test1.lamiral.info&user1=test1&password1=secret1&host2=test2.lamiral.info&user2=test2&password2=secret2&debugenv=on'
  14859. my $mysync ;
  14860. is( undef, get_options( $mysync ), 'get_options cgi context: no CGI module => undef' ) ;
  14861. # skip all next tests if the CGI module is not available
  14862. SKIP: {
  14863. if ( ! eval { require CGI ; } ) {
  14864. skip( "CGI Perl module is not installed", 19 ) ;
  14865. }
  14866. CGI->import( qw( -no_debug -utf8 ) ) ;
  14867. is( undef, get_options( $mysync ), 'get_options cgi context: no CGI param => undef' ) ;
  14868. # Testing boolean
  14869. $mysync->{cgi} = CGI->new( 'version=on&debugenv=on' ) ;
  14870. local $ENV{'QUERY_STRING'} = 'version=on&debugenv=on' ;
  14871. is( 22, get_options( $mysync ), 'get_options cgi context: QUERY_STRING => 22' ) ;
  14872. is( 'on', $mysync->{ version }, 'get_options cgi context: --version => on' ) ;
  14873. # debugenv is not allowed in cgi context
  14874. is( undef, $mysync->{debugenv}, 'get_options cgi context: $mysync->{debugenv} => undef' ) ;
  14875. # QUERY_STRING in this test is only for return value of get_options
  14876. # Have to think harder, GET/POST context, is this return value a good thing?
  14877. local $ENV{'QUERY_STRING'} = 'host1=test1.lamiral.info&user1=test1' ;
  14878. $mysync->{cgi} = CGI->new( 'host1=test1.lamiral.info&user1=test1' ) ;
  14879. is( 36, get_options( $mysync, ), 'get_options cgi context: QUERY_STRING => 36' ) ;
  14880. is( 'test1', $mysync->{user1}, 'get_options cgi context: $mysync->{user1} => test1' ) ;
  14881. #local $ENV{'QUERY_STRING'} = undef ;
  14882. # Testing s@ as ref
  14883. $mysync->{cgi} = CGI->new( 'folder=fd1' ) ;
  14884. get_options( $mysync ) ;
  14885. is_deeply( [ 'fd1' ], $mysync->{ folder }, 'get_options cgi context: $mysync->{ folder } => fd1' ) ;
  14886. $mysync->{cgi} = CGI->new( 'folder=fd1&folder=fd2' ) ;
  14887. get_options( $mysync ) ;
  14888. is_deeply( [ 'fd1', 'fd2' ], $mysync->{ folder }, 'get_options cgi context: $mysync->{ folder } => fd1, fd2' ) ;
  14889. # Testing %
  14890. $mysync->{cgi} = CGI->new( 'f1f2h=s1=d1&f1f2h=s2=d2&f1f2h=s3=d3' ) ;
  14891. get_options( $mysync ) ;
  14892. is_deeply( { 's1' => 'd1', 's2' => 'd2', 's3' => 'd3' },
  14893. $mysync->{f1f2h}, 'get_options cgi context: f1f2h => s1=d1 s2=d2 s3=d3' ) ;
  14894. # Testing boolean ! with --noxxx, doesnot work
  14895. $mysync->{cgi} = CGI->new( 'nodry=on' ) ;
  14896. get_options( $mysync ) ;
  14897. is( undef, $mysync->{dry}, 'get_options cgi context: --nodry => $mysync->{dry} => undef' ) ;
  14898. $mysync->{cgi} = CGI->new( 'host1=example.com' ) ;
  14899. get_options( $mysync ) ;
  14900. is( 'example.com', $mysync->{host1}, 'get_options cgi context: --host1=example.com => $mysync->{host1} => example.com' ) ;
  14901. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  14902. $mysync->{cgi} = CGI->new( 'simulong=' ) ;
  14903. get_options( $mysync ) ;
  14904. is( undef, $mysync->{simulong}, 'get_options cgi context: --simulong= => $mysync->{simulong} => undef' ) ;
  14905. $mysync->{cgi} = CGI->new( 'simulong' ) ;
  14906. get_options( $mysync ) ;
  14907. is( undef, $mysync->{simulong}, 'get_options cgi context: --simulong => $mysync->{simulong} => undef' ) ;
  14908. $mysync->{cgi} = CGI->new( 'simulong=4' ) ;
  14909. get_options( $mysync ) ;
  14910. is( 4, $mysync->{simulong}, 'get_options cgi context: --simulong=4 => $mysync->{simulong} => 4' ) ;
  14911. is( undef, $mysync->{ folder }, 'get_options cgi context: --simulong=4 => $mysync->{ folder } => undef' ) ;
  14912. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  14913. $mysync ={} ;
  14914. $mysync->{cgi} = CGI->new( 'testslive=on' ) ;
  14915. get_options( $mysync ) ;
  14916. is( 'on', $mysync->{ testslive }, 'get_options cgi context: --testslive=on => testslive => on' ) ;
  14917. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  14918. $mysync ={} ;
  14919. $mysync->{cgi} = CGI->new( 'log=0' ) ;
  14920. get_options( $mysync ) ;
  14921. is( 0, $mysync->{ log }, 'get_options cgi context: --log=0 => log => 0' ) ;
  14922. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  14923. # What is this fucked up indentation?
  14924. }
  14925. note( 'Leaving tests_get_options_cgi_context()' ) ;
  14926. return ;
  14927. }
  14928. sub get_options_cgi
  14929. {
  14930. # In CGI context arguments are not in @ARGV but in QUERY_STRING variable (with GET).
  14931. my $mysync = shift @ARG ;
  14932. $mysync->{cgi} || return ;
  14933. my @arguments = @ARG ;
  14934. # final 0 is used to print usage when no option is given
  14935. my $numopt = length $ENV{'QUERY_STRING'} || 1 ;
  14936. $mysync->{f1f2h} = {} ;
  14937. my $opt_ret = myGetOptions(
  14938. $mysync,
  14939. \@arguments,
  14940. 'abort' => \$mysync->{ abort },
  14941. 'abortbyfile' => \$mysync->{ abortbyfile },
  14942. 'host1=s' => \$mysync->{ host1 },
  14943. 'host2=s' => \$mysync->{ host2 },
  14944. 'user1=s' => \$mysync->{ user1 },
  14945. 'user2=s' => \$mysync->{ user2 },
  14946. 'password1=s' => \$mysync->{ password1 },
  14947. 'password2=s' => \$mysync->{ password2 },
  14948. 'dry!' => \$mysync->{ dry },
  14949. 'dry1!' => \$mysync->{ dry1 },
  14950. 'version' => \$mysync->{ version },
  14951. 'ssl1!' => \$mysync->{ ssl1 },
  14952. 'ssl2!' => \$mysync->{ ssl2 },
  14953. 'tls1!' => \$mysync->{ tls1 },
  14954. 'tls2!' => \$mysync->{ tls2 },
  14955. 'justbanner!' => \$mysync->{ justbanner },
  14956. 'justlogin!' => \$mysync->{ justlogin },
  14957. 'justconnect!' => \$mysync->{ justconnect },
  14958. 'addheader!' => \$mysync->{ addheader },
  14959. 'automap!' => \$mysync->{ automap },
  14960. 'justautomap!' => \$mysync->{ justautomap },
  14961. 'gmail1' => \$mysync->{ gmail1 },
  14962. 'gmail2' => \$mysync->{ gmail2 },
  14963. 'office1' => \$mysync->{ office1 },
  14964. 'office2' => \$mysync->{ office2 },
  14965. 'exchange1' => \$mysync->{ exchange1 },
  14966. 'exchange2' => \$mysync->{ exchange2 },
  14967. 'domino1' => \$mysync->{ domino1 },
  14968. 'domino2' => \$mysync->{ domino2 },
  14969. 'f1f2=s@' => \$mysync->{ f1f2 },
  14970. 'f1f2h=s%' => \$mysync->{ f1f2h },
  14971. 'folder=s@' => \$mysync->{ folder },
  14972. 'testslive!' => \$mysync->{ testslive },
  14973. 'testslive6!' => \$mysync->{ testslive6 },
  14974. 'releasecheck!' => \$mysync->{ releasecheck },
  14975. 'simulong=f' => \$mysync->{ simulong },
  14976. 'debugsleep=f' => \$mysync->{ debugsleep },
  14977. 'subfolder1=s' => \$mysync->{ subfolder1 },
  14978. 'subfolder2=s' => \$mysync->{ subfolder2 },
  14979. 'justfolders!' => \$mysync->{ justfolders },
  14980. 'justfoldersizes!' => \$mysync->{ justfoldersizes },
  14981. 'delete1!' => \$mysync->{ delete1 },
  14982. 'delete2!' => \$mysync->{ delete2 },
  14983. 'delete2duplicates!' => \$mysync->{ delete2duplicates },
  14984. 'tail!' => \$mysync->{ tail },
  14985. 'tmphash=s' => \$mysync->{ tmphash },
  14986. 'exitwhenover=i' => \$mysync->{ exitwhenover },
  14987. 'syncduplicates!' => \$mysync->{ syncduplicates },
  14988. 'log!' => \$mysync->{ log },
  14989. 'loglogfile!' => \$mysync->{ loglogfile },
  14990. # f1f2h=s% could be removed but
  14991. # tests_get_options_cgi() should be split before
  14992. # with a sub tests_myGetOptions()
  14993. ) ;
  14994. $mysync->{ debug } and output( $mysync, "get options: [$opt_ret][$numopt]\n" ) ;
  14995. if ( ! $opt_ret ) {
  14996. return ;
  14997. }
  14998. return $numopt ;
  14999. }
  15000. sub get_options_cmd
  15001. {
  15002. my $mysync = shift @ARG ;
  15003. my @arguments = @ARG ;
  15004. my $mycgi = $mysync->{cgi} ;
  15005. # final 0 is used to print usage when no option is given on command line
  15006. my $numopt = scalar @arguments || 0 ;
  15007. my $argv = join "\x00", @arguments ;
  15008. if ( $argv =~ m/-delete\x002/x ) {
  15009. output( $mysync, "May be you mean --delete2 instead of --delete 2\n" ) ;
  15010. return ;
  15011. }
  15012. $mysync->{f1f2h} = {} ;
  15013. my $opt_ret = myGetOptions(
  15014. $mysync,
  15015. \@arguments,
  15016. 'debug!' => \$mysync->{ debug },
  15017. 'debuglist!' => \$debuglist,
  15018. 'debugcontent!' => \$debugcontent,
  15019. 'debugsleep=f' => \$mysync->{debugsleep},
  15020. 'debugflags!' => \$debugflags,
  15021. 'debugimap!' => \$mysync->{ debugimap },
  15022. 'debugimap1!' => \$mysync->{ acc1 }->{ debugimap },
  15023. 'debugimap2!' => \$mysync->{ acc2 }->{ debugimap },
  15024. 'debugdev!' => \$debugdev,
  15025. 'debugmemory!' => \$mysync->{debugmemory},
  15026. 'debugfolders!' => \$mysync->{debugfolders},
  15027. 'debugssl=i' => \$mysync->{debugssl},
  15028. 'debugcgi!' => \$debugcgi,
  15029. 'debugenv!' => \$mysync->{debugenv},
  15030. 'debugsig!' => \$mysync->{debugsig},
  15031. 'debuglabels!' => \$mysync->{debuglabels},
  15032. 'simulong=f' => \$mysync->{simulong},
  15033. 'abort' => \$mysync->{abort},
  15034. 'abortbyfile' => \$mysync->{abortbyfile},
  15035. 'host1=s' => \$mysync->{ host1 },
  15036. 'host2=s' => \$mysync->{ host2 },
  15037. 'port1=i' => \$mysync->{port1},
  15038. 'port2=i' => \$mysync->{port2},
  15039. 'inet4|ipv4' => \$mysync->{inet4},
  15040. 'inet6|ipv6' => \$mysync->{inet6},
  15041. 'user1=s' => \$mysync->{ user1 },
  15042. 'user2=s' => \$mysync->{ user2 },
  15043. 'gmail1' => \$mysync->{gmail1},
  15044. 'gmail2' => \$mysync->{gmail2},
  15045. 'office1' => \$mysync->{office1},
  15046. 'office2' => \$mysync->{office2},
  15047. 'exchange1' => \$mysync->{exchange1},
  15048. 'exchange2' => \$mysync->{exchange2},
  15049. 'domino1' => \$mysync->{domino1},
  15050. 'domino2' => \$mysync->{domino2},
  15051. 'domain1=s' => \$mysync->{ acc1 }->{ domain },
  15052. 'domain2=s' => \$mysync->{ acc2 }->{ domain },
  15053. 'password1=s' => \$mysync->{password1},
  15054. 'password2=s' => \$mysync->{password2},
  15055. 'passfile1=s' => \$mysync->{ passfile1 },
  15056. 'passfile2=s' => \$mysync->{ passfile2 },
  15057. 'authmd5!' => \$authmd5,
  15058. 'authmd51!' => \$authmd51,
  15059. 'authmd52!' => \$authmd52,
  15060. 'trylogin!' => \$mysync->{ trylogin },
  15061. 'oauthdirect1=s' => \$mysync->{ acc1 }->{ oauthdirect },
  15062. 'oauthdirect2=s' => \$mysync->{ acc2 }->{ oauthdirect },
  15063. 'oauthaccesstoken1=s' => \$mysync->{ acc1 }->{ oauthaccesstoken },
  15064. 'oauthaccesstoken2=s' => \$mysync->{ acc2 }->{ oauthaccesstoken },
  15065. 'sep1=s' => \$mysync->{ sep1 },
  15066. 'sep2=s' => \$mysync->{ sep2 },
  15067. 'sanitize!' => \$mysync->{ sanitize },
  15068. 'folder=s@' => \$mysync->{ folder },
  15069. 'folderrec=s' => \@folderrec,
  15070. 'include=s' => \@include,
  15071. 'exclude=s' => \@exclude,
  15072. 'noexclude' => \$mysync->{noexclude},
  15073. 'folderfirst=s' => \@folderfirst,
  15074. 'folderlast=s' => \@folderlast,
  15075. 'prefix1=s' => \$prefix1,
  15076. 'prefix2=s' => \$prefix2,
  15077. 'subfolder1=s' => \$mysync->{ subfolder1 },
  15078. 'subfolder2=s' => \$mysync->{ subfolder2 },
  15079. 'fixslash2!' => \$mysync->{ fixslash2 },
  15080. 'fixInboxINBOX!' => \$fixInboxINBOX,
  15081. 'regextrans2=s@' => \$mysync->{ regextrans2 },
  15082. 'mixfolders!' => \$mixfolders,
  15083. 'skipemptyfolders!' => \$mysync->{ skipemptyfolders },
  15084. 'regexmess=s' => \@regexmess,
  15085. 'noregexmess' => \$mysync->{noregexmess},
  15086. 'skipmess=s' => \@skipmess,
  15087. 'pipemess=s' => \@pipemess,
  15088. 'pipemesscheck!' => \$pipemesscheck,
  15089. 'disarmreadreceipts!' => \$disarmreadreceipts,
  15090. 'regexflag=s@' => \$mysync->{ regexflag },
  15091. 'noregexflag' => \$mysync->{ noregexflag },
  15092. 'filterflags!' => \$mysync->{ filterflags },
  15093. 'filterbuggyflags!' => \$mysync->{ filterbuggyflags },
  15094. 'flagscase!' => \$mysync->{ flagscase },
  15095. 'syncflagsaftercopy!' => \$syncflagsaftercopy,
  15096. 'resyncflags!' => \$mysync->{ resyncflags },
  15097. 'synclabels!' => \$mysync->{ synclabels },
  15098. 'resynclabels!' => \$mysync->{ resynclabels },
  15099. 'delete|delete1!' => \$mysync->{ delete1 },
  15100. 'delete2!' => \$mysync->{ delete2 },
  15101. 'delete2duplicates!' => \$mysync->{ delete2duplicates },
  15102. 'delete2folders!' => \$delete2folders,
  15103. 'delete2foldersonly=s' => \$delete2foldersonly,
  15104. 'delete2foldersbutnot=s' => \$delete2foldersbutnot,
  15105. 'syncinternaldates!' => \$syncinternaldates,
  15106. 'idatefromheader!' => \$idatefromheader,
  15107. 'syncacls!' => \$mysync->{ syncacls },
  15108. 'maxsize=i' => \$mysync->{ maxsize },
  15109. 'appendlimit=i' => \$mysync->{ appendlimit },
  15110. 'truncmess=i' => \$mysync->{ truncmess },
  15111. 'minsize=i' => \$minsize,
  15112. 'maxage=f' => \$maxage,
  15113. 'minage=f' => \$minage,
  15114. 'search=s' => \$search,
  15115. 'search1=s' => \$mysync->{ search1 },
  15116. 'search2=s' => \$mysync->{ search2 },
  15117. 'foldersizes!' => \$mysync->{ foldersizes },
  15118. 'foldersizesatend!' => \$mysync->{ foldersizesatend },
  15119. 'dry!' => \$mysync->{dry},
  15120. 'dry1!' => \$mysync->{dry1},
  15121. 'expunge1|expunge!' => \$mysync->{ expunge1 },
  15122. 'expunge2!' => \$mysync->{ expunge2 },
  15123. 'uidexpunge2!' => \$mysync->{ uidexpunge2 },
  15124. 'subscribed' => \$subscribed,
  15125. 'subscribe!' => \$subscribe,
  15126. 'subscribeall|subscribe_all!' => \$subscribeall,
  15127. 'justbanner!' => \$mysync->{ justbanner },
  15128. 'justfolders!'=> \$mysync->{ justfolders },
  15129. 'justfoldersizes!' => \$mysync->{ justfoldersizes },
  15130. 'fast!' => \$fast,
  15131. 'version' => \$mysync->{version},
  15132. 'help' => \$help,
  15133. 'timeout=f' => \$mysync->{timeout},
  15134. 'timeout1=f' => \$mysync->{ acc1 }->{timeout},
  15135. 'timeout2=f' => \$mysync->{ acc2 }->{timeout},
  15136. 'skipheader=s' => \$mysync->{ skipheader },
  15137. 'useheader=s' => \@useheader,
  15138. 'wholeheaderifneeded!' => \$wholeheaderifneeded,
  15139. 'messageidnodomain!' => \$messageidnodomain,
  15140. 'skipsize!' => \$skipsize,
  15141. 'allowsizemismatch!' => \$allowsizemismatch,
  15142. 'fastio1!' => \$mysync->{ acc1 }->{ fastio },
  15143. 'fastio2!' => \$mysync->{ acc2 }->{ fastio },
  15144. 'sslcheck!' => \$mysync->{sslcheck},
  15145. 'ssl1!' => \$mysync->{ssl1},
  15146. 'ssl2!' => \$mysync->{ssl2},
  15147. 'ssl1_ssl_version=s' => \$mysync->{ acc1 }->{sslargs}->{SSL_version},
  15148. 'ssl2_ssl_version=s' => \$mysync->{ acc2 }->{sslargs}->{SSL_version},
  15149. 'sslargs1=s%' => \$mysync->{ acc1 }->{sslargs},
  15150. 'sslargs2=s%' => \$mysync->{ acc2 }->{sslargs},
  15151. 'tls1!' => \$mysync->{tls1},
  15152. 'tls2!' => \$mysync->{tls2},
  15153. 'uid1!' => \$uid1,
  15154. 'uid2!' => \$uid2,
  15155. 'authmech1=s' => \$mysync->{ acc1 }->{ authmech },
  15156. 'authmech2=s' => \$mysync->{ acc2 }->{ authmech },
  15157. 'authuser1=s' => \$mysync->{ acc1 }->{ authuser },
  15158. 'authuser2=s' => \$mysync->{ acc2 }->{ authuser },
  15159. 'proxyauth1' => \$mysync->{ acc1 }->{ proxyauth },
  15160. 'proxyauth2' => \$mysync->{ acc2 }->{ proxyauth },
  15161. 'split1=i' => \$split1,
  15162. 'split2=i' => \$split2,
  15163. 'buffersize=i' => \$buffersize,
  15164. 'reconnectretry1=i' => \$mysync->{ acc1 }->{ reconnectretry },
  15165. 'reconnectretry2=i' => \$mysync->{ acc2 }->{ reconnectretry },
  15166. 'tests!' => \$mysync->{ tests },
  15167. 'testsdebug|tests_debug!' => \$mysync->{ testsdebug },
  15168. 'testsunit=s@' => \$mysync->{testsunit},
  15169. 'testslive!' => \$mysync->{testslive},
  15170. 'testslive6!' => \$mysync->{testslive6},
  15171. 'justlogin!' => \$mysync->{justlogin},
  15172. 'justconnect!' => \$mysync->{justconnect},
  15173. 'tmpdir=s' => \$mysync->{ tmpdir },
  15174. 'pidfile=s' => \$mysync->{pidfile},
  15175. 'pidfilelocking!' => \$mysync->{pidfilelocking},
  15176. 'sigexit=s@' => \$mysync->{ sigexit },
  15177. 'sigreconnect=s@' => \$mysync->{ sigreconnect },
  15178. 'sigignore=s@' => \$mysync->{ sigignore },
  15179. 'releasecheck!' => \$mysync->{releasecheck},
  15180. 'modulesversion|modules_version!' => \$modulesversion,
  15181. 'usecache!' => \$usecache,
  15182. 'cacheaftercopy!' => \$cacheaftercopy,
  15183. 'debugcache!' => \$debugcache,
  15184. 'useuid!' => \$useuid,
  15185. 'addheader!' => \$mysync->{addheader},
  15186. 'exitwhenover=i' => \$mysync->{ exitwhenover },
  15187. 'checkselectable!' => \$mysync->{ checkselectable },
  15188. 'checkfoldersexist!' => \$mysync->{ checkfoldersexist },
  15189. 'checkmessageexists!' => \$checkmessageexists,
  15190. 'expungeaftereach!' => \$mysync->{ expungeaftereach },
  15191. 'abletosearch!' => \$mysync->{abletosearch},
  15192. 'abletosearch1!' => \$mysync->{abletosearch1},
  15193. 'abletosearch2!' => \$mysync->{abletosearch2},
  15194. 'showpasswords!' => \$mysync->{showpasswords},
  15195. 'maxlinelength=i' => \$maxlinelength,
  15196. 'maxlinelengthcmd=s' => \$maxlinelengthcmd,
  15197. 'minmaxlinelength=i' => \$minmaxlinelength,
  15198. 'debugmaxlinelength!' => \$debugmaxlinelength,
  15199. 'fixcolonbug!' => \$fixcolonbug,
  15200. 'create_folder_old!' => \$create_folder_old,
  15201. 'maxmessagespersecond=f' => \$mysync->{maxmessagespersecond},
  15202. 'maxbytespersecond=i' => \$mysync->{maxbytespersecond},
  15203. 'maxbytesafter=i' => \$mysync->{maxbytesafter},
  15204. 'maxsleep=f' => \$mysync->{maxsleep},
  15205. 'skipcrossduplicates!' => \$skipcrossduplicates,
  15206. 'debugcrossduplicates!' => \$debugcrossduplicates,
  15207. 'log!' => \$mysync->{log},
  15208. 'tail!' => \$mysync->{tail},
  15209. 'logfile=s' => \$mysync->{logfile},
  15210. 'logdir=s' => \$mysync->{logdir},
  15211. 'errorsmax=i' => \$mysync->{errorsmax},
  15212. 'errorsdump!' => \$mysync->{errorsdump},
  15213. 'fetch_hash_set=s' => \$fetch_hash_set,
  15214. 'automap!' => \$mysync->{automap},
  15215. 'justautomap!' => \$mysync->{justautomap},
  15216. 'id!' => \$mysync->{id},
  15217. 'f1f2=s@' => \$mysync->{f1f2},
  15218. 'nof1f2' => \$mysync->{nof1f2},
  15219. 'f1f2h=s%' => \$mysync->{f1f2h},
  15220. 'justfolderlists!' => \$mysync->{justfolderlists},
  15221. 'delete1emptyfolders' => \$mysync->{delete1emptyfolders},
  15222. 'checknoabletosearch!' => \$mysync->{checknoabletosearch},
  15223. 'syncduplicates!' => \$mysync->{ syncduplicates },
  15224. 'dockercontext!' => \$mysync->{ dockercontext },
  15225. ) ;
  15226. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  15227. $mysync->{ debug } and output( $mysync, "get options: [$opt_ret][$numopt]\n" ) ;
  15228. my $numopt_after = scalar @arguments ;
  15229. #myprint( "get options: [$opt_ret][$numopt][$numopt_after]\n" ) ;
  15230. # The $arguments[0] test is just because parallel adds "" when it is
  15231. # used with {=7=} in sync_parallel_unix.sh
  15232. if ( $numopt_after and $arguments[0] ) {
  15233. myprint(
  15234. "Found ", scalar( @arguments ), " extra arguments : [@arguments]\n",
  15235. "It usually means a quoting issue in the command line ",
  15236. "or some misspelling options.\n",
  15237. ) ;
  15238. return ;
  15239. }
  15240. if ( ! $opt_ret ) {
  15241. return ;
  15242. }
  15243. return $numopt ;
  15244. }
  15245. sub tests_get_options
  15246. {
  15247. note( 'Entering tests_get_options()' ) ;
  15248. # CAVEAT: still setting global variables, be careful
  15249. # with tests, the context increases! $debug stays on for example.
  15250. # API:
  15251. # * input arguments: two ways, command line or CGI
  15252. # * the program arguments
  15253. # * QUERY_STRING env variable
  15254. # * return
  15255. # * undef if bad things happened like
  15256. # * options not known
  15257. # * --delete 2 input
  15258. # * number of arguments or QUERY_STRING length
  15259. my $mysync = { } ;
  15260. is( undef, get_options( $mysync, qw( --noexist ) ), 'get_options: --noexist => undef' ) ;
  15261. is( undef, $mysync->{ noexist }, 'get_options: --noexist => undef' ) ;
  15262. $mysync = { } ;
  15263. is( undef, get_options( $mysync, qw( --lalala --noexist --version ) ), 'get_options: --lalala --noexist --version => undef' ) ;
  15264. is( 1, $mysync->{ version }, 'get_options: --version => 1' ) ;
  15265. is( undef, $mysync->{ noexist }, 'get_options: --noexist => undef' ) ;
  15266. $mysync = { } ;
  15267. is( 1, get_options( $mysync, qw( --delete2 ) ), 'get_options: --delete2 => 1' ) ;
  15268. is( 1, $mysync->{ delete2 }, 'get_options: --delete2 => var delete2 = 1' ) ;
  15269. $mysync = { } ;
  15270. is( undef, get_options( $mysync, qw( --delete 2 ) ), 'get_options: --delete 2 => var undef' ) ;
  15271. is( undef, $mysync->{ delete1 }, 'get_options: --delete 2 => var still undef ; good!' ) ;
  15272. $mysync = { } ;
  15273. is( undef, get_options( $mysync, "--delete 2" ), 'get_options: --delete 2 => undef' ) ;
  15274. is( 1, get_options( $mysync, "--version" ), 'get_options: --version => 1' ) ;
  15275. is( 1, get_options( $mysync, "--help" ), 'get_options: --help => 1' ) ;
  15276. is( undef, get_options( $mysync, qw( --noexist --version ) ), 'get_options: --debug --noexist --version => undef' ) ;
  15277. is( 1, get_options( $mysync, qw( --version ) ), 'get_options: --version => 1' ) ;
  15278. is( undef, get_options( $mysync, qw( extra ) ), 'get_options: extra => undef' ) ;
  15279. is( undef, get_options( $mysync, qw( extra1 --version extra2 ) ), 'get_options: extra1 --version extra2 => undef' ) ;
  15280. $mysync = { } ;
  15281. is( 2, get_options( $mysync, qw( --host1 HOST_01) ), 'get_options: --host1 HOST_01 => 1' ) ;
  15282. is( 'HOST_01', $mysync->{ host1 }, 'get_options: --host1 HOST_01 => HOST_01' ) ;
  15283. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  15284. note( 'Leaving tests_get_options()' ) ;
  15285. return ;
  15286. }
  15287. sub get_options
  15288. {
  15289. my $mysync = shift @ARG ;
  15290. my @arguments = @ARG ;
  15291. #myprint( "1 mysync: ", Data::Dumper->Dump( [ $mysync ] ) ) ;
  15292. my $ret ;
  15293. if ( under_cgi_context( ) ) {
  15294. # CGI context
  15295. $ret = get_options_cgi( $mysync, @arguments ) ;
  15296. }else{
  15297. # Command line context ;
  15298. $ret = get_options_cmd( $mysync, @arguments ) ;
  15299. } ;
  15300. #myprint( "2 mysync: ", Data::Dumper->Dump( [ $mysync ] ) ) ;
  15301. foreach my $key ( sort keys %{ $mysync } ) {
  15302. if ( ! defined $mysync->{$key} ) {
  15303. delete $mysync->{$key} ;
  15304. next ;
  15305. }
  15306. if ( 'ARRAY' eq ref( $mysync->{$key} )
  15307. and 0 == scalar( @{ $mysync->{$key} } ) ) {
  15308. delete $mysync->{$key} ;
  15309. }
  15310. }
  15311. return $ret ;
  15312. }
  15313. sub condition_to_leave_after_tests
  15314. {
  15315. my $mysync = shift ;
  15316. if ( $mysync->{ testslive } or $mysync->{ testslive6 } )
  15317. {
  15318. return 0 ;
  15319. }
  15320. if ( $mysync->{ tests }
  15321. or $mysync->{ testsdebug }
  15322. or $mysync->{ testsunit }
  15323. )
  15324. {
  15325. return 1 ;
  15326. }
  15327. }
  15328. sub testunitsession
  15329. {
  15330. my $mysync = shift ;
  15331. if ( ! $mysync ) { return ; }
  15332. if ( ! $mysync->{ testsunit } ) { return ; }
  15333. my @functions = @{ $mysync->{ testsunit } } ;
  15334. if ( ! @functions ) { return ; }
  15335. SKIP: {
  15336. if ( ! @functions ) { skip 'No test in normal run' ; }
  15337. testsunit( @functions ) ;
  15338. done_testing( ) ;
  15339. }
  15340. return ;
  15341. }
  15342. sub tests_count_0s
  15343. {
  15344. note( 'Entering tests_count_zeros()' ) ;
  15345. is( 0, count_0s( ), 'count_0s: no parameters => 0' ) ;
  15346. is( 1, count_0s( 0 ), 'count_0s: 0 => 1' ) ;
  15347. is( 0, count_0s( 1 ), 'count_0s: 1 => 0' ) ;
  15348. is( 1, count_0s( 1, 0, 1 ), 'count_0s: 1, 0, 1 => 1' ) ;
  15349. is( 2, count_0s( 1, 0, 1, 0 ), 'count_0s: 1, 0, 1, 0 => 2' ) ;
  15350. note( 'Leaving tests_count_zeros()' ) ;
  15351. return ;
  15352. }
  15353. sub count_0s
  15354. {
  15355. my @array = @ARG ;
  15356. if ( ! @array ) { return 0 ; }
  15357. my $nb_zeros = 0 ;
  15358. map { $_ == 0 and $nb_zeros += 1 } @array ;
  15359. return $nb_zeros ;
  15360. }
  15361. sub tests_report_failures
  15362. {
  15363. note( 'Entering tests_report_failures()' ) ;
  15364. is( undef, report_failures( ), 'report_failures: no parameters => undef' ) ;
  15365. is( "nb 1 - first\n", report_failures( ({'ok' => 0, name => 'first'}) ), 'report_failures: "first" failed => nb 1 - first' ) ;
  15366. is( q{}, report_failures( ( {'ok' => 1, name => 'first'} ) ), 'report_failures: "first" success =>' ) ;
  15367. is( "nb 2 - second\n", report_failures( ( {'ok' => 1, name => 'second'}, {'ok' => 0, name => 'second'} ) ), 'report_failures: "second" failed => nb 2 - second' ) ;
  15368. 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' ) ;
  15369. note( 'Leaving tests_report_failures()' ) ;
  15370. return ;
  15371. }
  15372. sub report_failures
  15373. {
  15374. my @details = @ARG ;
  15375. if ( ! @details ) { return ; }
  15376. my $counter = 1 ;
  15377. my $report = q{} ;
  15378. foreach my $details ( @details ) {
  15379. if ( ! $details->{ 'ok' } ) {
  15380. my $name = $details->{ 'name' } || 'NONAME' ;
  15381. $report .= "nb $counter - $name\n" ;
  15382. }
  15383. $counter += 1 ;
  15384. }
  15385. return $report ;
  15386. }
  15387. sub tests_true
  15388. {
  15389. note( 'Entering tests_true()' ) ;
  15390. is( 1, 1, 'true: 1 is 1' ) ;
  15391. note( 'Leaving tests_true()' ) ;
  15392. return ;
  15393. }
  15394. sub tests_testsunit
  15395. {
  15396. note( 'Entering tests_testunit()' ) ;
  15397. is( undef, testsunit( ), 'testsunit: no parameters => undef' ) ;
  15398. is( undef, testsunit( undef ), 'testsunit: an undef parameter => undef' ) ;
  15399. is( undef, testsunit( q{} ), 'testsunit: an empty parameter => undef' ) ;
  15400. is( undef, testsunit( 'idonotexist' ), 'testsunit: a do not exist function as parameter => undef' ) ;
  15401. is( undef, testsunit( 'tests_true' ), 'testsunit: tests_true => undef' ) ;
  15402. note( 'Leaving tests_testunit()' ) ;
  15403. return ;
  15404. }
  15405. sub testsunit
  15406. {
  15407. my @functions = @ARG ;
  15408. if ( ! @functions ) { #
  15409. myprint( "testsunit warning: no argument given\n" ) ;
  15410. return ;
  15411. }
  15412. foreach my $function ( @functions ) {
  15413. if ( ! $function ) {
  15414. myprint( "testsunit warning: argument is empty\n" ) ;
  15415. next ;
  15416. }
  15417. if ( ! exists &$function ) {
  15418. myprint( "testsunit warning: function $function does not exist\n" ) ;
  15419. next ;
  15420. }
  15421. if ( ! defined &$function ) {
  15422. myprint( "testsunit warning: function $function is not defined\n" ) ;
  15423. next ;
  15424. }
  15425. my $function_ref = \&{ $function } ;
  15426. &$function_ref() ;
  15427. }
  15428. return ;
  15429. }
  15430. sub testsdebug
  15431. {
  15432. # Now a little obsolete since there is
  15433. # imapsync ... --testsunit "anyfunction"
  15434. my $mysync = shift ;
  15435. if ( ! $mysync->{ testsdebug } ) { return ; }
  15436. SKIP: {
  15437. if ( ! $mysync->{ testsdebug } ) {
  15438. skip 'No test in normal run' ;
  15439. }
  15440. note( 'Entering testsdebug()' ) ;
  15441. #ok( ( ( not -d 'W/tmp/tests' ) or rmtree( 'W/tmp/tests/' ) ), 'testsdebug: rmtree W/tmp/tests' ) ;
  15442. #tests_check_binary_embed_all_dyn_libs( ) ;
  15443. #tests_killpid_by_parent( ) ;
  15444. #tests_killpid_by_brother( ) ;
  15445. #tests_kill_zero( ) ;
  15446. #tests_connect_socket( ) ;
  15447. #tests_probe_imapssl( ) ;
  15448. tests_cpu_number( ) ;
  15449. tests_mailimapclient_connect( ) ;
  15450. #tests_always_fail( ) ;
  15451. note( 'Leaving testsdebug()' ) ;
  15452. done_testing( ) ;
  15453. }
  15454. return ;
  15455. }
  15456. sub tests
  15457. {
  15458. my $mysync = shift ;
  15459. if ( ! $mysync->{ tests } ) { return ; }
  15460. SKIP: {
  15461. skip 'No test in normal run' if ( ! $mysync->{ tests } ) ;
  15462. note( 'Entering tests()' ) ;
  15463. tests_folder_routines( ) ;
  15464. tests_compare_lists( ) ;
  15465. tests_regexmess( ) ;
  15466. tests_skipmess( ) ;
  15467. tests_regexflags( );
  15468. tests_ucsecond( ) ;
  15469. tests_permanentflags();
  15470. tests_flags_filter( ) ;
  15471. tests_separator_invert( ) ;
  15472. tests_imap2_folder_name( ) ;
  15473. tests_command_line_nopassword( ) ;
  15474. tests_good_date( ) ;
  15475. tests_max( ) ;
  15476. tests_remove_not_num();
  15477. tests_memory_consumption( ) ;
  15478. tests_is_a_release_number();
  15479. tests_imapsync_basename();
  15480. tests_list_keys_in_2_not_in_1();
  15481. tests_convert_sep_to_slash( ) ;
  15482. tests_match_a_cache_file( ) ;
  15483. tests_cache_map( ) ;
  15484. tests_get_cache( ) ;
  15485. tests_clean_cache( ) ;
  15486. tests_clean_cache_2( ) ;
  15487. tests_touch( ) ;
  15488. tests_flagscase( ) ;
  15489. tests_mkpath( ) ;
  15490. tests_extract_header( ) ;
  15491. tests_decompose_header( ) ;
  15492. tests_epoch( ) ;
  15493. tests_add_header( ) ;
  15494. tests_cache_dir_fix( ) ;
  15495. tests_cache_dir_fix_win( ) ;
  15496. tests_filter_forbidden_characters( ) ;
  15497. tests_cache_folder( ) ;
  15498. tests_time_remaining( ) ;
  15499. tests_decompose_regex( ) ;
  15500. tests_backtick( ) ;
  15501. tests_bytes_display_string( ) ;
  15502. tests_header_line_normalize( ) ;
  15503. tests_fix_Inbox_INBOX_mapping( ) ;
  15504. tests_max_line_length( ) ;
  15505. tests_subject( ) ;
  15506. tests_msgs_from_maxmin( ) ;
  15507. tests_tmpdir_has_colon_bug( ) ;
  15508. tests_sleep_max_messages( ) ;
  15509. tests_sleep_max_bytes( ) ;
  15510. tests_logfile( ) ;
  15511. tests_setlogfile( ) ;
  15512. tests_jux_utf8_old( ) ;
  15513. tests_jux_utf8( ) ;
  15514. tests_pipemess( ) ;
  15515. tests_jux_utf8_list( ) ;
  15516. tests_guess_prefix( ) ;
  15517. tests_guess_separator( ) ;
  15518. tests_format_for_imap_arg( ) ;
  15519. tests_imapsync_id( ) ;
  15520. tests_date_from_rcs( ) ;
  15521. tests_quota_extract_storage_limit_in_bytes( ) ;
  15522. tests_quota_extract_storage_current_in_bytes( ) ;
  15523. tests_guess_special( ) ;
  15524. tests_do_valid_directory( ) ;
  15525. tests_delete1emptyfolders( ) ;
  15526. tests_message_for_host2( ) ;
  15527. tests_length_ref( ) ;
  15528. tests_firstline( ) ;
  15529. tests_diff_or_NA( ) ;
  15530. tests_match_number( ) ;
  15531. tests_all_defined( ) ;
  15532. tests_special_from_folders_hash( ) ;
  15533. tests_notmatch( ) ;
  15534. tests_match( ) ;
  15535. tests_get_options( ) ;
  15536. tests_get_options_cgi_context( ) ;
  15537. tests_rand32( ) ;
  15538. tests_hashsynclocal( ) ;
  15539. tests_hashsync( ) ;
  15540. tests_output( ) ;
  15541. tests_output_reset_with( ) ;
  15542. tests_output_start( ) ;
  15543. tests_check_last_release( ) ;
  15544. tests_loadavg( ) ;
  15545. tests_cpu_number( ) ;
  15546. tests_load_and_delay( ) ;
  15547. #tests_imapsping( ) ;
  15548. #tests_tcpping( ) ;
  15549. tests_sslcheck( ) ;
  15550. tests_not_long_imapsync_version_public( ) ;
  15551. tests_reconnect_if_needed( ) ;
  15552. tests_reconnect_12_if_needed( ) ;
  15553. tests_sleep_if_needed( ) ;
  15554. tests_string_to_file( ) ;
  15555. tests_file_to_string( ) ;
  15556. tests_under_cgi_context( ) ;
  15557. tests_umask( ) ;
  15558. tests_umask_str( ) ;
  15559. tests_set_umask( ) ;
  15560. tests_createhashfileifneeded( ) ;
  15561. tests_slash_to_underscore( ) ;
  15562. tests_testsunit( ) ;
  15563. tests_count_0s( ) ;
  15564. tests_report_failures( ) ;
  15565. tests_min( ) ;
  15566. #tests_connect_socket( ) ;
  15567. #tests_resolvrev( ) ;
  15568. tests_usage( ) ;
  15569. tests_version_from_rcs( ) ;
  15570. tests_backslash_caret( ) ;
  15571. #tests_mailimapclient_connect_bug( ) ; # it fails with Mail-IMAPClient <= 3.39
  15572. tests_write_pidfile( ) ;
  15573. tests_remove_pidfile_not_running( ) ;
  15574. tests_match_a_pid_number( ) ;
  15575. tests_prefix_seperator_invertion( ) ;
  15576. tests_is_integer( ) ;
  15577. tests_integer_or_1( ) ;
  15578. tests_is_number( ) ;
  15579. tests_sig_install( ) ;
  15580. tests_template( ) ;
  15581. tests_split_around_equal( ) ;
  15582. tests_toggle_sleep( ) ;
  15583. tests_labels( ) ;
  15584. tests_synclabels( ) ;
  15585. tests_uidexpunge_or_expunge( ) ;
  15586. tests_appendlimit_from_capability( ) ;
  15587. tests_maxsize_setting( ) ;
  15588. tests_mock_capability( ) ;
  15589. tests_appendlimit( ) ;
  15590. tests_capability_of( ) ;
  15591. tests_search_in_array( ) ;
  15592. tests_operators_and_exclam_precedence( ) ;
  15593. tests_teelaunch( ) ;
  15594. tests_logfileprepa( ) ;
  15595. tests_useheader_suggestion( ) ;
  15596. tests_nb_messages_in_2_not_in_1( ) ;
  15597. tests_labels_add_subfolder2( ) ;
  15598. tests_labels_remove_subfolder1( ) ;
  15599. tests_resynclabels( ) ;
  15600. tests_labels_remove_special( ) ;
  15601. tests_uniq( ) ;
  15602. tests_remove_from_requested_folders( ) ;
  15603. tests_errors_log( ) ;
  15604. tests_add_subfolder1_to_folderrec( ) ;
  15605. tests_sanitize_subfolder( ) ;
  15606. tests_remove_edging_blanks( ) ;
  15607. tests_sanitize( ) ;
  15608. tests_remove_last_char_if_is( ) ;
  15609. tests_check_binary_embed_all_dyn_libs( ) ;
  15610. tests_nthline( ) ;
  15611. tests_secondline( ) ;
  15612. tests_tail( ) ;
  15613. tests_truncmess( ) ;
  15614. tests_eta( ) ;
  15615. tests_timesince( ) ;
  15616. tests_timenext( ) ;
  15617. tests_foldersize( ) ;
  15618. tests_imapsync_context( ) ;
  15619. tests_abort( ) ;
  15620. tests_probe_imapssl( ) ;
  15621. tests_mailimapclient_connect( ) ;
  15622. tests_checknoabletosearch( ) ;
  15623. tests_errorsdump( ) ;
  15624. tests_errorsanalyse( ) ;
  15625. tests_most_common_error( ) ;
  15626. tests_errorclassify( ) ;
  15627. tests_error_type( ) ;
  15628. tests_sanitize_host( ) ;
  15629. tests_hmac_sha1_hex( ) ;
  15630. tests_total_bytes_max_reached( ) ;
  15631. tests_header_construct( ) ;
  15632. tests_remove_doublequotes_if_any( ) ;
  15633. tests_login_imap( ) ;
  15634. tests_login_imap_oauth( ) ;
  15635. tests_skipmess_neg( ) ;
  15636. tests_localtimez( ) ;
  15637. tests_file_to_array( ) ;
  15638. tests_cpu_time( ) ;
  15639. tests_cpu_percent( ) ;
  15640. tests_cpu_percent_global( ) ;
  15641. tests_flags_for_host2( ) ;
  15642. tests_under_docker_context( ) ;
  15643. #tests_resolv( ) ;
  15644. # Those three are for later use, when webserver will be inside imapsync
  15645. # or will be deleted them if I abandon the project.
  15646. #tests_killpid_by_parent( ) ;
  15647. #tests_killpid_by_brother( ) ;
  15648. #tests_kill_zero( ) ;
  15649. #tests_always_fail( ) ;
  15650. done_testing( 1742 ) ;
  15651. note( 'Leaving tests()' ) ;
  15652. }
  15653. return ;
  15654. }
  15655. sub tests_template
  15656. {
  15657. note( 'Entering tests_template()' ) ;
  15658. is( undef, template( ), 'template: no args => undef' ) ;
  15659. my $mysync = { } ;
  15660. is( undef, template( $mysync ), 'template: undef => undef' ) ;
  15661. is_deeply( {}, {}, 'template: a hash is a hash' ) ;
  15662. is_deeply( [], [], 'template: an array is an array' ) ;
  15663. note( 'Leaving tests_template()' ) ;
  15664. return ;
  15665. }
  15666. sub template
  15667. {
  15668. my $mysync = shift @ARG ;
  15669. return ;
  15670. }