imapsync 756 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537
  1. #!/usr/bin/env perl
  2. # $Id: imapsync,v 2.178 2022/01/12 21:28:37 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.178 $
  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. =head2 OPTIONS/authentication
  160. --authmech1 str : Auth mechanism to use with host1:
  161. PLAIN, LOGIN, CRAM-MD5 etc. Use UPPERCASE.
  162. --authmech2 str : Auth mechanism to use with host2. See --authmech1
  163. --authuser1 str : User to auth with on host1 (admin user).
  164. Avoid using --authmech1 SOMETHING with --authuser1.
  165. --authuser2 str : User to auth with on host2 (admin user).
  166. --proxyauth1 : Use proxyauth on host1. Requires --authuser1.
  167. Required by Sun/iPlanet/Netscape IMAP servers to
  168. be able to use an administrative user.
  169. --proxyauth2 : Use proxyauth on host2. Requires --authuser2.
  170. --authmd51 : Use MD5 authentication for host1.
  171. --authmd52 : Use MD5 authentication for host2.
  172. --domain1 str : Domain on host1 (NTLM authentication).
  173. --domain2 str : Domain on host2 (NTLM authentication).
  174. --oauthaccesstoken1 str : The access token to authenticate with OAUTH2.
  175. It will be combined with the --user1 value to form the
  176. string to pass with XOAUTH2 authentication.
  177. The password given by --password1 or --passfile1
  178. is ignored.
  179. Instead of the access token itself, the value can be a
  180. file containing the access token on the first line.
  181. If the value is a file, imapsync reads its first line
  182. and take this line as the access token. The advantage
  183. of the file is that if the access token changes then
  184. imapsync can read it again when it needs to reconnect
  185. during a run.
  186. --oauthaccesstoken2 str : same thing as --oauthaccesstoken1
  187. --oauthdirect1 str : The direct string to pass with XOAUTH2 authentication.
  188. The password given by --password1 or --passfile1 and
  189. the user given by --user1 are ignored.
  190. --oauthdirect2 str : same thing as oauthdirect1
  191. =head2 OPTIONS/folders
  192. --folder str : Sync this folder.
  193. --folder str : and this one, etc.
  194. --folderrec str : Sync this folder recursively.
  195. --folderrec str : and this one, etc.
  196. --folderfirst str : Sync this folder first. Ex. --folderfirst "INBOX"
  197. --folderfirst str : then this one, etc.
  198. --folderlast str : Sync this folder last. --folderlast "[Gmail]/All Mail"
  199. --folderlast str : then this one, etc.
  200. --nomixfolders : Do not merge folders when host1 is case-sensitive
  201. while host2 is not (like Exchange). Only the first
  202. similar folder is synced (example: with folders
  203. "Sent", "SENT" and "sent"
  204. on host1 only "Sent" will be synced to host2).
  205. --skipemptyfolders : Empty host1 folders are not created on host2.
  206. --include reg : Sync folders matching this regular expression
  207. --include reg : or this one, etc.
  208. If both --include --exclude options are used, then
  209. include is done before.
  210. --exclude reg : Skips folders matching this regular expression
  211. Several folders to avoid:
  212. --exclude 'fold1|fold2|f3' skips fold1, fold2 and f3.
  213. --exclude reg : or this one, etc.
  214. --automap : guesses folders mapping, for folders well known as
  215. "Sent", "Junk", "Drafts", "All", "Archive", "Flagged".
  216. --f1f2 str1=str2 : Force folder str1 to be synced to str2,
  217. --f1f2 overrides --automap and --regextrans2.
  218. Use several --f1f2 options to map several folders.
  219. Option --f1f2 is a one to one only folder mapping,
  220. str1 and str2 have to be full path folder names.
  221. --subfolder2 str : Syncs the whole host1 folders hierarchy under the
  222. host2 folder named str.
  223. It does it internally by adding three
  224. --regextrans2 options before all others.
  225. Add --debug to see what's really going on.
  226. --subfolder1 str : Syncs the host1 folders hierarchy which is under folder
  227. str to the root hierarchy of host2.
  228. It's the couterpart of a sync done by --subfolder2
  229. when doing it in the reverse order.
  230. Backup/Restore scenario:
  231. Use --subfolder2 str for a backup to the folder str
  232. on host2. Then use --subfolder1 str for restoring
  233. from the folder str, after inverting
  234. host1/host2 user1/user2 values.
  235. --subscribed : Transfers subscribed folders.
  236. --subscribe : Subscribe to the folders transferred on the
  237. host2 that are subscribed on host1. On by default.
  238. --subscribeall : Subscribe to the folders transferred on the
  239. host2 even if they are not subscribed on host1.
  240. --prefix1 str : Remove prefix str to all destination folders,
  241. usually "INBOX." or "INBOX/" or an empty string "".
  242. imapsync guesses the prefix if host1 imap server
  243. does not have NAMESPACE capability. So this option
  244. should not be used most of the time.
  245. --prefix2 str : Add prefix to all host2 folders. See --prefix1
  246. --sep1 str : Host1 separator. This option should not be used
  247. most of the time.
  248. Imapsync gets the separator from the server itself,
  249. by using NAMESPACE, or it tries to guess it
  250. from the folders listing (it counts
  251. characters / . \\ \ in folder names and choose the
  252. more frequent, or finally / if nothing is found.
  253. --sep2 str : Host2 separator. See --sep1
  254. --regextrans2 reg : Apply the whole regex to each destination folders.
  255. --regextrans2 reg : and this one. etc.
  256. When you play with the --regextrans2 option, first
  257. add also the safe options --dry --justfolders
  258. Then, when happy, remove --dry for a run, then
  259. remove --justfolders for the next ones.
  260. Have in mind that --regextrans2 is applied after
  261. the automatic prefix and separator inversion.
  262. For examples see:
  263. https://imapsync.lamiral.info/FAQ.d/FAQ.Folders_Mapping.txt
  264. =head2 OPTIONS/folders sizes
  265. --nofoldersizes : Do not calculate the size of each folder at the
  266. beginning of the sync. Default is to calculate them.
  267. --nofoldersizesatend: Do not calculate the size of each folder at the
  268. end of the sync. Default is to calculate them.
  269. --justfoldersizes : Exit after having printed the initial folder sizes.
  270. =head2 OPTIONS/tmp
  271. --tmpdir str : Where to store temporary files and subdirectories.
  272. Will be created if it doesn't exist.
  273. Default is system specific, Unix is /tmp but
  274. /tmp is often too small and deleted at reboot.
  275. --tmpdir /var/tmp should be better.
  276. --pidfile str : The file where imapsync pid is written,
  277. it can be dirname/filename complete path.
  278. The default name is imapsync.pid in tmpdir.
  279. --pidfilelocking : Abort if pidfile already exists. Useful to avoid
  280. concurrent transfers on the same mailbox.
  281. =head2 OPTIONS/log
  282. --nolog : Turn off logging on file
  283. --logfile str : Change the default log filename (can be dirname/filename).
  284. --logdir str : Change the default log directory. Default is LOG_imapsync/
  285. The default logfile name is for example
  286. LOG_imapsync/2019_12_22_23_57_59_532_user1_user2.txt
  287. where:
  288. 2019_12_22_23_57_59_532 is nearly the date of the start
  289. YYYY_MM_DD_HH_MM_SS_mmm
  290. year_month_day_hour_minute_seconde_millisecond
  291. and user1 user2 are the --user1 --user2 values.
  292. =head2 OPTIONS/messages
  293. --skipmess reg : Skips messages matching the regex.
  294. Example: 'm/[\x80-\xff]/' # to avoid 8bits messages.
  295. --skipmess is applied before --regexmess
  296. --skipmess reg : or this one, etc.
  297. --skipcrossduplicates : Avoid copying messages that are already copied
  298. in another folder, good from Gmail to XYZ when
  299. XYZ is not also Gmail.
  300. Activated with --gmail1 unless --noskipcrossduplicates
  301. --debugcrossduplicates : Prints which messages (UIDs) are skipped with
  302. --skipcrossduplicates and in what other folders
  303. they are.
  304. --pipemess cmd : Apply this cmd command to each message content
  305. before the copy.
  306. --pipemess cmd : and this one, etc.
  307. With several --pipemess, the output of each cmd
  308. command (STDOUT) is given to the input (STDIN)
  309. of the next command.
  310. For example,
  311. --pipemess cmd1 --pipemess cmd2 --pipemess cmd3
  312. is like a Unix pipe:
  313. "cat message | cmd1 | cmd2 | cmd3"
  314. --disarmreadreceipts : Disarms read receipts (host2 Exchange issue)
  315. --regexmess reg : Apply the whole regex to each message before transfer.
  316. Example: 's/\000/ /g' # to replace null characters
  317. by spaces.
  318. --regexmess reg : and this one, etc.
  319. --truncmess int : truncates messages when their size exceed the int
  320. value, specified in bytes. Good to sync too big
  321. messages or to "suppress" attachments.
  322. Have in mind that this way, messages become
  323. uncoherent somehow.
  324. =head2 OPTIONS/labels
  325. Gmail present labels as folders in imap. Imapsync can accelerate the sync
  326. by syncing X-GM-LABELS, it will avoid to transfer messages when they are
  327. already on host2 in another folder.
  328. --synclabels : Syncs also Gmail labels when a message is copied to host2.
  329. Activated by default with --gmail1 --gmail2 unless
  330. --nosynclabels is added.
  331. --resynclabels : Resyncs Gmail labels when a message is already on host2.
  332. Activated by default with --gmail1 --gmail2 unless
  333. --noresynclabels is added.
  334. For Gmail syncs, see also:
  335. https://imapsync.lamiral.info/FAQ.d/FAQ.Gmail.txt
  336. =head2 OPTIONS/flags
  337. If you encounter flag problems see also:
  338. https://imapsync.lamiral.info/FAQ.d/FAQ.Flags.txt
  339. --regexflag reg : Apply the whole regex to each flags list.
  340. Example: 's/"Junk"//g' # to remove "Junk" flag.
  341. --regexflag reg : then this one, etc.
  342. --resyncflags : Resync flags for already transferred messages.
  343. On by default.
  344. --noresyncflags : Do not resync flags for already transferred messages.
  345. May be useful when a user has already started to play
  346. with its host2 account.
  347. --filterbuggyflags : Filter flags known to be buggy and generators of errors
  348. "BAD Invalid system flag" or "NO APPEND Invalid flag list".
  349. =head2 OPTIONS/deletions
  350. --delete1 : Deletes messages on host1 server after a successful
  351. transfer. Option --delete1 has the following behavior:
  352. it marks messages as deleted with the IMAP flag
  353. \Deleted, then messages are really deleted with an
  354. EXPUNGE IMAP command. If expunging after each message
  355. slows down too much the sync then use
  356. --noexpungeaftereach to speed up, expunging will then be
  357. done only twice per folder, one at the beginning and
  358. one at the end of a folder sync.
  359. --expunge1 : Expunge messages on host1 just before syncing a folder.
  360. Expunge is done per folder.
  361. Expunge aims is to really delete messages marked deleted.
  362. An expunge is also done after each message copied
  363. if option --delete1 is set (unless --noexpungeaftereach).
  364. --noexpunge1 : Do not expunge messages on host1.
  365. --delete1emptyfolders : Deletes empty folders on host1, INBOX excepted.
  366. Useful with --delete1 since what remains on host1
  367. is only what failed to be synced.
  368. --delete2 : Delete messages in the host2 account that are not in
  369. the host1 account. Useful for backup or pre-sync.
  370. --delete2 implies --uidexpunge2
  371. --delete2duplicates : Deletes messages in host2 that are duplicates in host2.
  372. Works only without --useuid since duplicates are
  373. detected with an header part of each message.
  374. NB: --delete2duplicates is far less violent than --delete2
  375. since it removes only duplicates.
  376. --delete2folders : Delete folders in host2 that are not in host1.
  377. For safety, first try it like this, it is safe:
  378. --delete2folders --dry --justfolders --nofoldersizes
  379. and see what folders will be deleted.
  380. --delete2foldersonly reg : Delete only folders matching the regex reg.
  381. Example: --delete2foldersonly "/^Junk$|^INBOX.Junk$/"
  382. This option activates --delete2folders
  383. --delete2foldersbutnot reg : Do not delete folders matching the regex rex.
  384. Example: --delete2foldersbutnot "/Tasks$|Contacts$|Foo$/"
  385. This option activates --delete2folders
  386. --noexpunge2 : Do not expunge messages on host2.
  387. --nouidexpunge2 : Do not uidexpunge messages on the host2 account
  388. that are not on the host1 account.
  389. =head2 OPTIONS/dates
  390. If you encounter problems with dates, see also:
  391. https://imapsync.lamiral.info/FAQ.d/FAQ.Dates.txt
  392. --syncinternaldates : Sets the internal dates on host2 as the same as host1.
  393. Turned on by default. Internal date is the date
  394. a message arrived on a host (Unix mtime usually).
  395. --idatefromheader : Sets the internal dates on host2 as same as the
  396. ones in "Date:" headers.
  397. =head2 OPTIONS/message selection
  398. --maxsize int : Skip messages larger (or equal) than int bytes
  399. --minsize int : Skip messages smaller (or equal) than int bytes
  400. --maxage int : Skip messages older than int days.
  401. final stats (skipped) don't count older messages
  402. see also --minage
  403. --minage int : Skip messages newer than int days.
  404. final stats (skipped) don't count newer messages
  405. You can do (+ zone are the messages selected):
  406. past|----maxage+++++++++++++++>now
  407. past|+++++++++++++++minage---->now
  408. past|----maxage+++++minage---->now (intersection)
  409. past|++++minage-----maxage++++>now (union)
  410. --search str : Selects only messages returned by this IMAP SEARCH
  411. command. Applied on both sides.
  412. For a complete set of what can be search see
  413. https://imapsync.lamiral.info/FAQ.d/FAQ.Messages_Selection.txt
  414. --search1 str : Same as --search but for selecting host1 messages only.
  415. --search2 str : Same as --search but for selecting host2 messages only.
  416. So --search CRIT equals --search1 CRIT --search2 CRIT
  417. --noabletosearch : Makes --minage and --maxage options use the internal
  418. dates given by a FETCH imap command instead of the
  419. "Date:" header. Internal date is the arrival date
  420. in the mailbox.
  421. --noabletosearch equals --noabletosearch1 --noabletosearch2
  422. --noabletosearch1 : Like --noabletosearch but for host1 only.
  423. --noabletosearch2 : Like --noabletosearch but for host2 only.
  424. --maxlinelength int : skip messages with a line length longer than int bytes.
  425. RFC 2822 says it must be no more than 1000 bytes but
  426. real life servers and email clients do more.
  427. --useheader str : Use this header to compare messages on both sides.
  428. Example: "Message-Id" or "Received" or "Date".
  429. --useheader str and this one, etc.
  430. --syncduplicates : Sync also duplicates. Off by default.
  431. --usecache : Use cache to speed up next syncs. Off by default.
  432. --nousecache : Do not use cache. Caveat: --useuid --nousecache creates
  433. duplicates on multiple runs.
  434. --useuid : Use UIDs instead of headers as a criterion to recognize
  435. messages. Option --usecache is then implied unless
  436. --nousecache is used.
  437. =head2 OPTIONS/miscellaneous
  438. --syncacls : Synchronizes acls (Access Control Lists).
  439. Acls in IMAP are not standardized, be careful
  440. since one acl code on one side may signify something
  441. else on the other one.
  442. --nosyncacls : Does not synchronize acls. This is the default.
  443. --addheader : When a message has no headers to be identified,
  444. --addheader adds a "Message-Id" header,
  445. like "Message-Id: 12345@imapsync", where 12345
  446. is the imap UID of the message on the host1 folder.
  447. Useful to sync folders "Sent" or "Draft".
  448. =head2 OPTIONS/debugging
  449. --debug : Debug mode.
  450. --debugfolders : Debug mode for the folders part only.
  451. --debugcontent : Debug content of the messages transferred. Huge output.
  452. --debugflags : Debug mode for flags.
  453. --debugimap1 : IMAP debug mode for host1. Very verbose.
  454. --debugimap2 : IMAP debug mode for host2. Very verbose.
  455. --debugimap : IMAP debug mode for host1 and host2. Twice very verbose.
  456. --debugmemory : Debug mode showing memory consumption after each copy.
  457. --errorsmax int : Exit when int number of errors is reached. Default is 50.
  458. --tests : Run local non-regression tests. Exit code 0 means all ok.
  459. --testslive : Run a live test with test1.lamiral.info imap server.
  460. Useful to check the basics. Needs internet connection.
  461. --testslive6 : Run a live test with ks6ipv6.lamiral.info imap server.
  462. Useful to check the ipv6 connectivity. Needs internet.
  463. =head2 OPTIONS/specific
  464. --gmail1 : sets --host1 to Gmail and other options. See FAQ.Gmail.txt
  465. --gmail2 : sets --host2 to Gmail and other options. See FAQ.Gmail.txt
  466. --office1 : sets --host1 to Office365 and other options. See FAQ.Office365.txt
  467. --office2 : sets --host2 to Office365 and other options. See FAQ.Office365.txt
  468. --exchange1 : sets options for Exchange. See FAQ.Exchange.txt
  469. --exchange2 : sets options for Exchange. See FAQ.Exchange.txt
  470. --domino1 : sets options for Domino. See FAQ.Domino.txt
  471. --domino2 : sets options for Domino. See FAQ.Domino.txt
  472. =head2 OPTIONS/behavior
  473. --timeout1 flo : Connection timeout in seconds for host1.
  474. Default is 120 and 0 means no timeout at all.
  475. --timeout2 flo : Connection timeout in seconds for host2.
  476. Default is 120 and 0 means no timeout at all.
  477. Caveat, under CGI context, you may encounter a timeout
  478. from the webserver, killing imapsync and the imap connexions.
  479. See the document INSTALL.OnlineUI.txt and search
  480. for "Timeout" for how to deal with this issue.
  481. --keepalive1 : https://metacpan.org/pod/Mail::IMAPClient#Keepalive
  482. Some firewalls and network gears like to timeout connections
  483. prematurely if the connection sits idle.
  484. This option enables SO_KEEPALIVE on the host1 socket.
  485. --keepalive1 is on by default since imapsync release 2.169
  486. Use --nokeepalive1 to disable it.
  487. --keepalive2 : Same as --keepalive2 but for host2.
  488. Use --nokeepalive2 to disable it.
  489. --maxmessagespersecond flo : limits the average number of messages
  490. transferred per second.
  491. --maxbytespersecond int : limits the average transfer rate per second.
  492. --maxbytesafter int : starts --maxbytespersecond limitation only after
  493. --maxbytesafter amount of data transferred.
  494. --maxsleep flo : do not sleep more than int seconds.
  495. On by default, 2 seconds max, like --maxsleep 2
  496. --abort : terminates a previous call still running.
  497. It uses the pidfile to know what process to abort.
  498. --exitwhenover int : Stop syncing and exits when int total bytes
  499. transferred is reached.
  500. --version : Print only the software version.
  501. --noreleasecheck : Do not check for any new imapsync release.
  502. --releasecheck : Check for new imapsync release.
  503. it's an http request to
  504. http://imapsync.lamiral.info/prj/imapsync/VERSION
  505. --noid : Do not send/receive IMAP "ID" command to imap servers.
  506. --justconnect : Just connect to both servers and print useful
  507. information. Need only --host1 and --host2 options.
  508. Obsolete since "imapsync --host1 imaphost" alone
  509. implies --justconnect
  510. --justlogin : Just login to both host1 and host2 with users
  511. credentials, then exit.
  512. --justfolders : Do only things about folders (ignore messages).
  513. --help : print this help.
  514. Example: to synchronize imap account "test1" on "test1.lamiral.info"
  515. to imap account "test2" on "test2.lamiral.info"
  516. with test1 password "secret1"
  517. and test2 password "secret2"
  518. imapsync \
  519. --host1 test1.lamiral.info --user1 test1 --password1 secret1 \
  520. --host2 test2.lamiral.info --user2 test2 --password2 secret2
  521. =cut
  522. # comment
  523. =pod
  524. =head1 SECURITY
  525. You can use --passfile1 instead of --password1 to mention the
  526. password since it is safer. With --password1 option, on Linux,
  527. any user on your host can see the password by using the 'ps auxwwww'
  528. command. Using a variable (like IMAPSYNC_PASSWORD1) is also
  529. dangerous because of the 'ps auxwwwwe' command. So, saving
  530. the password in a well protected file (600 or rw-------) is
  531. the best solution.
  532. Imapsync activates ssl or tls encryption by default, if possible.
  533. What detailed behavior is under this "if possible"?
  534. Imapsync activates ssl if the well known port imaps port (993) is open
  535. on the imap servers. If the imaps port is closed then it open a
  536. normal (clear) connection on port 143 but it looks for TLS support
  537. in the CAPABILITY list of the servers. If TLS is supported
  538. then imapsync goes to encryption with STARTTLS.
  539. If the automatic ssl and the tls detections fail then imapsync will
  540. not protect against sniffing activities on the network, especially
  541. for passwords.
  542. If you want to force ssl or tls just use --ssl1 --ssl2 or --tls1 --tls2
  543. See also the document FAQ.Security.txt in the FAQ.d/ directory
  544. or at https://imapsync.lamiral.info/FAQ.d/FAQ.Security.txt
  545. =head1 EXIT STATUS
  546. Imapsync will exit with a 0 status (return code) if everything went good.
  547. Otherwise, it exits with a non-zero status. That's classical Unix behavior.
  548. Here is the list of the exit code values (an integer between 0 and 255).
  549. In Bourne Shells, this exit code value can be retrieved within the variable
  550. value "$?" if you read it just after the imapsync call.
  551. The names reflect their meaning:
  552. =for comment
  553. egrep '^Readonly my.*\$EX' imapsync | egrep -o 'EX.*' | sed 's_^_ _'
  554. EX_OK => 0 ; #/* successful termination */
  555. EX_USAGE => 64 ; #/* command line usage error */
  556. EX_NOINPUT => 66 ; #/* cannot open input */
  557. EX_UNAVAILABLE => 69 ; #/* service unavailable */
  558. EX_SOFTWARE => 70 ; #/* internal software error */
  559. EXIT_CATCH_ALL => 1 ; # Any other error
  560. EXIT_BY_SIGNAL => 6 ; # Should be 128+n where n is the sig_num
  561. EXIT_BY_FILE => 7 ;
  562. EXIT_PID_FILE_ERROR => 8 ;
  563. EXIT_CONNECTION_FAILURE => 10 ;
  564. EXIT_TLS_FAILURE => 12 ;
  565. EXIT_AUTHENTICATION_FAILURE => 16 ;
  566. EXIT_SUBFOLDER1_NO_EXISTS => 21 ;
  567. EXIT_WITH_ERRORS => 111 ;
  568. EXIT_WITH_ERRORS_MAX => 112 ;
  569. EXIT_OVERQUOTA => 113 ;
  570. EXIT_ERR_APPEND => 114 ;
  571. EXIT_ERR_FETCH => 115 ;
  572. EXIT_ERR_CREATE => 116 ;
  573. EXIT_ERR_SELECT => 117 ;
  574. EXIT_TRANSFER_EXCEEDED => 118 ;
  575. EXIT_ERR_APPEND_VIRUS => 119 ;
  576. EXIT_TESTS_FAILED => 254 ; # Like Test::More API
  577. EXIT_CONNECTION_FAILURE_HOST1 => 101 ;
  578. EXIT_CONNECTION_FAILURE_HOST2 => 102 ;
  579. EXIT_AUTHENTICATION_FAILURE_USER1 => 161 ;
  580. EXIT_AUTHENTICATION_FAILURE_USER2 => 162 ;
  581. =head1 LICENSE AND COPYRIGHT
  582. Imapsync is free, open, public but not always gratis software
  583. cover by the NOLIMIT Public License, now called NLPL.
  584. See the LICENSE file included in the distribution or just read this
  585. simple sentence as it IS the licence text:
  586. "No limits to do anything with this work and this license."
  587. In case it is not long enough, I repeat:
  588. "No limits to do anything with this work and this license."
  589. Look at https://imapsync.lamiral.info/LICENSE
  590. =head1 AUTHOR
  591. Gilles LAMIRAL <gilles@lamiral.info>
  592. Good feedback is always welcome.
  593. Bad feedback is very often welcome.
  594. Gilles LAMIRAL earns his living by writing, installing,
  595. configuring and sometimes teaching free, open and often gratis
  596. software. Imapsync used to be "always gratis" but now it is
  597. only "often gratis" because imapsync is sold by its author,
  598. your servitor, a good way to maintain and support free open public
  599. software tools over decades.
  600. =head1 BUGS AND LIMITATIONS
  601. See https://imapsync.lamiral.info/FAQ.d/FAQ.Reporting_Bugs.txt
  602. =head1 IMAP SERVERS supported
  603. See https://imapsync.lamiral.info/S/imapservers.shtml
  604. =head1 HUGE MIGRATION
  605. If you have many mailboxes to migrate think about a little
  606. shell program. Write a file called file.txt (for example)
  607. containing users and passwords.
  608. The separator used in this example is ';'
  609. The file.txt file contains:
  610. user001_1;password001_1;user001_2;password001_2
  611. user002_1;password002_1;user002_2;password002_2
  612. user003_1;password003_1;user003_2;password003_2
  613. user004_1;password004_1;user004_2;password004_2
  614. user005_1;password005_1;user005_2;password005_2
  615. ...
  616. On Unix the shell program can be:
  617. { while IFS=';' read u1 p1 u2 p2; do
  618. imapsync --host1 imap.side1.org --user1 "$u1" --password1 "$p1" \
  619. --host2 imap.side2.org --user2 "$u2" --password2 "$p2" ...
  620. done ; } < file.txt
  621. On Windows the batch program can be:
  622. FOR /F "tokens=1,2,3,4 delims=; eol=#" %%G IN (file.txt) DO imapsync ^
  623. --host1 imap.side1.org --user1 %%G --password1 %%H ^
  624. --host2 imap.side2.org --user2 %%I --password2 %%J ...
  625. The ... have to be replaced by nothing or any imapsync option.
  626. Welcome in shell or batch programming !
  627. You will find already written scripts at
  628. https://imapsync.lamiral.info/examples/
  629. =head1 INSTALL
  630. Imapsync works under any Unix with Perl.
  631. Imapsync works under most Windows (2000, XP, Vista, Seven, Eight, Ten
  632. and all Server releases 2000, 2003, 2008 and R2, 2012 and R2, 2016)
  633. as a standalone binary software called imapsync.exe,
  634. usually launched from a batch file in order to avoid always typing
  635. the options. There is also a 32bit binary called imapsync_32bit.exe
  636. Imapsync works under OS X as a standalone binary
  637. software called imapsync_bin_Darwin
  638. Purchase latest imapsync at
  639. https://imapsync.lamiral.info/
  640. You'll receive a link to a compressed tarball called imapsync-x.xx.tgz
  641. where x.xx is the version number. Untar the tarball where
  642. you want (on Unix):
  643. tar xzvf imapsync-x.xx.tgz
  644. Go into the directory imapsync-x.xx and read the INSTALL file.
  645. As mentioned at https://imapsync.lamiral.info/#install
  646. the INSTALL file can also be found at
  647. https://imapsync.lamiral.info/INSTALL.d/INSTALL.ANY.txt
  648. It is now split in several files for each system
  649. https://imapsync.lamiral.info/INSTALL.d/
  650. =head1 CONFIGURATION
  651. There is no specific configuration file for imapsync,
  652. everything is specified by the command line parameters
  653. and the default behavior.
  654. =head1 HACKING
  655. Feel free to hack imapsync as the NOLIMIT license permits it.
  656. =head1 SIMILAR SOFTWARE
  657. See also https://imapsync.lamiral.info/S/external.shtml
  658. for a better up to date list.
  659. List verified on Friday July 1, 2021.
  660. imapsync: https://github.com/imapsync/imapsync (this is an imapsync copy, sometimes delayed, with --noreleasecheck by default since release 1.592, 2014/05/22)
  661. 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
  662. imaputils: https://github.com/mtsatsenko/imaputils (very old imap_tools fork)
  663. Doveadm-Sync: https://wiki2.dovecot.org/Tools/Doveadm/Sync ( Dovecot sync tool )
  664. davmail: http://davmail.sourceforge.net/
  665. offlineimap: http://offlineimap.org/
  666. fdm: https://github.com/nicm/fdm
  667. mbsync: http://isync.sourceforge.net/
  668. mailsync: http://mailsync.sourceforge.net/
  669. mailutil: https://www.washington.edu/imap/ part of the UW IMAP toolkit. (well, seems abandoned now)
  670. imaprepl: https://bl0rg.net/software/ http://freecode.com/projects/imap-repl/
  671. imapcopy (Pascal): http://www.ardiehl.de/imapcopy/
  672. imapcopy (Java): https://code.google.com/archive/p/imapcopy/
  673. imapsize: http://www.broobles.com/imapsize/
  674. migrationtool: http://sourceforge.net/projects/migrationtool/
  675. imapmigrate: http://sourceforge.net/projects/cyrus-utils/
  676. larch: https://github.com/rgrove/larch (derived from wonko_imapsync, good at Gmail)
  677. wonko_imapsync: http://wonko.com/article/554 (superseded by larch)
  678. pop2imap: http://www.linux-france.org/prj/pop2imap/ (I wrote that too)
  679. exchange-away: http://exchange-away.sourceforge.net/
  680. SyncBackPro: http://www.2brightsparks.com/syncback/sbpro.html
  681. ImapSyncClient: https://github.com/ridaamirini/ImapSyncClient
  682. MailStore: https://www.mailstore.com/en/products/mailstore-home/
  683. mnIMAPSync: https://github.com/manusa/mnIMAPSync
  684. imap-upload: http://imap-upload.sourceforge.net/ (A tool for uploading a local mbox file to IMAP4 server)
  685. imapbackup: https://github.com/rcarmo/imapbackup (A Python script for incremental backups of IMAP mailboxes)
  686. BitRecover email-backup 99 USD, 299 USD https://www.bitrecover.com/email-backup/.
  687. ImportExportTools: https://addons.thunderbird.net/en-us/thunderbird/addon/importexporttools/ ImportExportTools for Mozilla Thunderbird by Paolo Kaosmos. ImportExportTools does not do IMAP.
  688. rximapmail: https://sourceforge.net/projects/rximapmail/
  689. CodeTwo: https://www.codetwo.com/ but CodeTwo does imap source to Office365 only.
  690. =head1 HISTORY
  691. I initially wrote imapsync in July 2001 because an enterprise,
  692. called BaSystemes, paid me to install a new imap server
  693. without losing huge old mailboxes located in a far
  694. away remote imap server, accessible by an
  695. often broken low-bandwidth ISDN link.
  696. I had to verify every mailbox was well transferred, all folders, all messages,
  697. without wasting bandwidth or creating duplicates upon resyncs. The imapsync
  698. design was made with the beautiful rsync command in mind.
  699. Imapsync started its life as a patch of the copy_folder.pl
  700. script. The script copy_folder.pl comes from the Mail-IMAPClient-2.1.3 perl
  701. module tarball source (more precisely in the examples/ directory of the
  702. Mail-IMAPClient tarball).
  703. So many changes happened since then that I wonder
  704. if it remains any lines of the original
  705. copy_folder.pl in imapsync source code.
  706. =cut
  707. # use pragmas
  708. #
  709. use strict ;
  710. use warnings ;
  711. use Carp ;
  712. use Cwd ;
  713. use Compress::Zlib ;
  714. use Data::Dumper ;
  715. use Digest::HMAC_SHA1 qw( hmac_sha1 hmac_sha1_hex ) ;
  716. use Digest::MD5 qw( md5 md5_hex md5_base64 ) ;
  717. use Encode ;
  718. use Encode::IMAPUTF7 ;
  719. use English qw( -no_match_vars ) ;
  720. use Errno qw(EAGAIN EPIPE ECONNRESET) ;
  721. use Fcntl ;
  722. use File::Basename ;
  723. use File::Copy::Recursive ;
  724. use File::Glob qw( :glob ) ;
  725. use File::Path qw( mkpath rmtree ) ;
  726. use File::Spec ;
  727. use File::stat ;
  728. use Getopt::Long ( ) ;
  729. use IO::File ;
  730. use IO::Socket qw( :crlf SOL_SOCKET SO_KEEPALIVE ) ;
  731. use IO::Socket::INET6 ;
  732. use IO::Socket::SSL ;
  733. use IO::Tee ;
  734. use IPC::Open3 'open3' ;
  735. #use locale ;
  736. use Mail::IMAPClient 3.30 ;
  737. use MIME::Base64 ;
  738. use Pod::Usage qw(pod2usage) ;
  739. use POSIX qw( uname SIGALRM :sys_wait_h ) ;
  740. use Sys::Hostname ;
  741. use Term::ReadKey ;
  742. use Test::More ;
  743. use Time::HiRes qw( time sleep ) ;
  744. use Time::Local ;
  745. use Unicode::String ;
  746. use Readonly ;
  747. use Sys::MemInfo ;
  748. use Regexp::Common ;
  749. use Text::ParseWords ; # for quotewords()
  750. use File::Tail ;
  751. local $OUTPUT_AUTOFLUSH = 1 ;
  752. # constants
  753. # Let us do like sysexits.h
  754. # /usr/include/sysexits.h
  755. # and https://www.tldp.org/LDP/abs/html/exitcodes.html
  756. # Should avoid 2 126 127 128..128+64=192 255
  757. # Should use 0 1 3..125 193..254
  758. Readonly my $EX_OK => 0 ; #/* successful termination */
  759. Readonly my $EX_USAGE => 64 ; #/* command line usage error */
  760. #Readonly my $EX_DATAERR => 65 ; #/* data format error */
  761. Readonly my $EX_NOINPUT => 66 ; #/* cannot open input */
  762. #Readonly my $EX_NOUSER => 67 ; #/* addressee unknown */
  763. #Readonly my $EX_NOHOST => 68 ; #/* host name unknown */
  764. Readonly my $EX_UNAVAILABLE => 69 ; #/* service unavailable */
  765. Readonly my $EX_SOFTWARE => 70 ; #/* internal software error */
  766. #Readonly my $EX_OSERR => 71 ; #/* system error (e.g., can't fork) */
  767. #Readonly my $EX_OSFILE => 72 ; #/* critical OS file missing */
  768. #Readonly my $EX_CANTCREAT => 73 ; #/* can't create (user) output file */
  769. #Readonly my $EX_IOERR => 74 ; #/* input/output error */
  770. #Readonly my $EX_TEMPFAIL => 75 ; #/* temp failure; user is invited to retry */
  771. #Readonly my $EX_PROTOCOL => 76 ; #/* remote error in protocol */
  772. #Readonly my $EX_NOPERM => 77 ; #/* permission denied */
  773. #Readonly my $EX_CONFIG => 78 ; #/* configuration error */
  774. # Mine
  775. Readonly my $EXIT_CATCH_ALL => 1 ; # Any other error
  776. Readonly my $EXIT_BY_SIGNAL => 6 ; # Should be 128+n where n is the sig_num
  777. Readonly my $EXIT_BY_FILE => 7 ;
  778. Readonly my $EXIT_PID_FILE_ERROR => 8 ;
  779. Readonly my $EXIT_CONNECTION_FAILURE => 10 ;
  780. Readonly my $EXIT_TLS_FAILURE => 12 ;
  781. Readonly my $EXIT_AUTHENTICATION_FAILURE => 16 ;
  782. Readonly my $EXIT_SUBFOLDER1_NO_EXISTS => 21 ;
  783. Readonly my $EXIT_WITH_ERRORS => 111 ;
  784. Readonly my $EXIT_WITH_ERRORS_MAX => 112 ;
  785. Readonly my $EXIT_OVERQUOTA => 113 ;
  786. Readonly my $EXIT_ERR_APPEND => 114 ;
  787. Readonly my $EXIT_ERR_FETCH => 115 ;
  788. Readonly my $EXIT_ERR_CREATE => 116 ;
  789. Readonly my $EXIT_ERR_SELECT => 117 ;
  790. Readonly my $EXIT_TRANSFER_EXCEEDED => 118 ;
  791. Readonly my $EXIT_ERR_APPEND_VIRUS => 119 ;
  792. Readonly my $EXIT_ERR_FLAGS => 120 ;
  793. Readonly my $EXIT_TESTS_FAILED => 254 ; # Like Test::More API
  794. Readonly my $EXIT_CONNECTION_FAILURE_HOST1 => 101 ;
  795. Readonly my $EXIT_CONNECTION_FAILURE_HOST2 => 102 ;
  796. Readonly my $EXIT_AUTHENTICATION_FAILURE_USER1 => 161 ;
  797. Readonly my $EXIT_AUTHENTICATION_FAILURE_USER2 => 162 ;
  798. Readonly my %EXIT_TXT => (
  799. $EX_OK => 'EX_OK: successful termination',
  800. $EX_USAGE => 'EX_USAGE: command line usage error',
  801. $EX_NOINPUT => 'EX_NOINPUT: cannot open input',
  802. $EX_UNAVAILABLE => 'EX_UNAVAILABLE: service unavailable',
  803. $EX_SOFTWARE => 'EX_SOFTWARE: internal software error',
  804. $EXIT_CATCH_ALL => 'EXIT_CATCH_ALL',
  805. $EXIT_BY_SIGNAL => 'EXIT_BY_SIGNAL',
  806. $EXIT_BY_FILE => 'EXIT_BY_FILE',
  807. $EXIT_PID_FILE_ERROR => 'EXIT_PID_FILE_ERROR' ,
  808. $EXIT_CONNECTION_FAILURE => 'EXIT_CONNECTION_FAILURE',
  809. $EXIT_TLS_FAILURE => 'EXIT_TLS_FAILURE',
  810. $EXIT_AUTHENTICATION_FAILURE => 'EXIT_AUTHENTICATION_FAILURE',
  811. $EXIT_SUBFOLDER1_NO_EXISTS => 'EXIT_SUBFOLDER1_NO_EXISTS',
  812. $EXIT_WITH_ERRORS => 'EXIT_WITH_ERRORS',
  813. $EXIT_WITH_ERRORS_MAX => 'EXIT_WITH_ERRORS_MAX',
  814. $EXIT_OVERQUOTA => 'EXIT_OVERQUOTA',
  815. $EXIT_ERR_APPEND => 'EXIT_ERR_APPEND',
  816. $EXIT_ERR_APPEND_VIRUS => 'EXIT_ERR_APPEND_VIRUS',
  817. $EXIT_ERR_FETCH => 'EXIT_ERR_FETCH',
  818. $EXIT_ERR_FLAGS => 'EXIT_ERR_FLAGS',
  819. $EXIT_ERR_CREATE => 'EXIT_ERR_CREATE',
  820. $EXIT_ERR_SELECT => 'EXIT_ERR_SELECT',
  821. $EXIT_TESTS_FAILED => 'EXIT_TESTS_FAILED',
  822. $EXIT_TRANSFER_EXCEEDED => 'EXIT_TRANSFER_EXCEEDED',
  823. $EXIT_CONNECTION_FAILURE_HOST1 => 'EXIT_CONNECTION_FAILURE_HOST1',
  824. $EXIT_CONNECTION_FAILURE_HOST2 => 'EXIT_CONNECTION_FAILURE_HOST2',
  825. $EXIT_AUTHENTICATION_FAILURE_USER1 => 'EXIT_AUTHENTICATION_FAILURE_USER1',
  826. $EXIT_AUTHENTICATION_FAILURE_USER2 => 'EXIT_AUTHENTICATION_FAILURE_USER2',
  827. ) ;
  828. Readonly my %EXIT_VALUE_OF_ERR_TYPE => (
  829. ERR_APPEND_SIZE => $EXIT_ERR_APPEND,
  830. ERR_OVERQUOTA => $EXIT_OVERQUOTA,
  831. ERR_APPEND => $EXIT_ERR_APPEND,
  832. ERR_APPEND_VIRUS => $EXIT_ERR_APPEND_VIRUS,
  833. ERR_CREATE => $EXIT_ERR_CREATE,
  834. ERR_SELECT => $EXIT_ERR_SELECT,
  835. ERR_Host1_FETCH => $EXIT_ERR_FETCH,
  836. ERR_FLAGS => $EXIT_ERR_FLAGS,
  837. ERR_UNCLASSIFIED => $EXIT_WITH_ERRORS,
  838. ERR_NOTHING_REPORTED => $EXIT_WITH_ERRORS,
  839. ERR_TRANSFER_EXCEEDED => $EXIT_TRANSFER_EXCEEDED,
  840. ERR_CONNECTION_FAILURE_HOST1 => $EXIT_CONNECTION_FAILURE_HOST1,
  841. ERR_CONNECTION_FAILURE_HOST2 => $EXIT_CONNECTION_FAILURE_HOST2,
  842. ERR_AUTHENTICATION_FAILURE_USER1 => $EXIT_AUTHENTICATION_FAILURE_USER1,
  843. ERR_AUTHENTICATION_FAILURE_USER2 => $EXIT_AUTHENTICATION_FAILURE_USER2,
  844. ERR_EXIT_TLS_FAILURE => $EXIT_TLS_FAILURE,
  845. ) ;
  846. Readonly my %COMMENT_OF_ERR_TYPE => (
  847. ERR_APPEND_SIZE => \&comment_err_append_size,
  848. ERR_OVERQUOTA => \&comment_err_overquota,
  849. ERR_APPEND => \&comment_err_blank,
  850. ERR_APPEND_VIRUS => \&comment_err_blank,
  851. ERR_CREATE => \&comment_err_blank,
  852. ERR_SELECT => \&comment_err_blank,
  853. ERR_Host1_FETCH => \&comment_err_blank,
  854. ERR_FLAGS => \&comment_err_flags,
  855. ERR_UNCLASSIFIED => \&comment_err_blank,
  856. ERR_NOTHING_REPORTED => \&comment_err_blank,
  857. ERR_TRANSFER_EXCEEDED => \&comment_err_transfer_exceeded,
  858. ERR_CONNECTION_FAILURE_HOST1 => \&comment_err_connection_failure_host1,
  859. ERR_CONNECTION_FAILURE_HOST2 => \&comment_err_connection_failure_host2,
  860. ERR_AUTHENTICATION_FAILURE_USER1 => \&comment_err_authentication_failure_host1,
  861. ERR_AUTHENTICATION_FAILURE_USER2 => \&comment_err_authentication_failure_host2,
  862. ERR_EXIT_TLS_FAILURE => \&comment_err_blank,
  863. ) ;
  864. sub comment_err_blank
  865. {
  866. return '' ;
  867. }
  868. sub comment_err_append_size
  869. {
  870. my $mysync = shift @ARG ;
  871. my $comment = "The destination server refuses too big messages. Use --truncmess option. Read https://imapsync.lamiral.info/FAQ.d/FAQ.Messages_Too_Big.txt" ;
  872. return $comment ;
  873. }
  874. sub comment_err_authentication_failure_host1
  875. {
  876. my $mysync = shift @ARG ;
  877. my $comment = "Check the credentials for $mysync->{ user1 }." ;
  878. return $comment ;
  879. }
  880. sub comment_err_authentication_failure_host2
  881. {
  882. my $mysync = shift @ARG ;
  883. my $comment = "Check the credentials for $mysync->{ user2 }." ;
  884. return $comment ;
  885. }
  886. sub comment_err_connection_failure_host1
  887. {
  888. my $mysync = shift @ARG ;
  889. my $comment = "Check that host1 $mysync->{ host1 } on port $mysync->{ port1 } is the right IMAP server to be contacted for your mailbox." ;
  890. return $comment ;
  891. }
  892. sub comment_err_connection_failure_host2
  893. {
  894. my $mysync = shift @ARG ;
  895. my $comment = "Check that host1 $mysync->{ host2 } on port $mysync->{ port2 } is the right IMAP server to be contacted for your mailbox." ;
  896. return $comment ;
  897. }
  898. sub comment_err_overquota
  899. {
  900. my $mysync = shift @ARG ;
  901. my $comment = 'The destination mailbox is 100% full, get free space on it and then resume the sync.' ;
  902. return $comment ;
  903. }
  904. sub comment_err_transfer_exceeded
  905. {
  906. my $mysync = shift @ARG ;
  907. my $size_limit_human = bytes_display_string_dec( $mysync->{ exitwhenover } ) ;
  908. my $comment = "The maximum transfer size for a single sync is reached ( over $size_limit_human ). Relaunch the sync to sync more." ;
  909. return $comment ;
  910. }
  911. sub comment_err_flags
  912. {
  913. my $mysync = shift @ARG ;
  914. my $comment = 'Many STORE errors with FLAGS. Retry with the option --noresyncflags' ;
  915. return $comment ;
  916. }
  917. Readonly my $DEFAULT_LOGDIR => 'LOG_imapsync' ;
  918. Readonly my $ERRORS_MAX => 50 ; # exit after 50 errors.
  919. Readonly my $ERRORS_MAX_CGI => 20 ; # exit after 20 errors in CGI context.
  920. Readonly my $INTERVAL_TO_EXIT => 2 ; # interval max to exit instead of reconnect
  921. Readonly my $SPLIT => 100 ; # By default, 100 at a time, not more.
  922. Readonly my $SPLIT_FACTOR => 10 ; # init_imap() calls Maxcommandlength( $SPLIT_FACTOR * $split )
  923. # which means default Maxcommandlength is 10*100 = 1000 characters ;
  924. Readonly my $IMAP_PORT => 143 ; # Well know port for IMAP
  925. Readonly my $IMAP_SSL_PORT => 993 ; # Well know port for IMAP over SSL
  926. Readonly my $LAST => -1 ;
  927. Readonly my $MINUS_ONE => -1 ;
  928. Readonly my $MINUS_TWO => -2 ;
  929. Readonly my $RELEASE_NUMBER_EXAMPLE_1 => '1.351' ;
  930. Readonly my $RELEASE_NUMBER_EXAMPLE_2 => 42.4242 ;
  931. Readonly my $TCP_PING_TIMEOUT => 5 ;
  932. Readonly my $DEFAULT_TIMEOUT => 120 ;
  933. Readonly my $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND => 3 ;
  934. Readonly my $DEFAULT_BUFFER_SIZE => 4096 ;
  935. Readonly my $MAX_SLEEP => 2 ; # 2 seconds max for limiting too long sleeps from --maxbytespersecond and --maxmessagespersecond
  936. Readonly my $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12 => 3600 ;
  937. Readonly my $PERMISSION_FILTER => 7777 ;
  938. Readonly my $KIBI => 1024 ;
  939. Readonly my $NUMBER_10 => 10 ;
  940. Readonly my $NUMBER_42 => 42 ;
  941. Readonly my $NUMBER_100 => 100 ;
  942. Readonly my $NUMBER_200 => 200 ;
  943. Readonly my $NUMBER_300 => 300 ;
  944. Readonly my $NUMBER_123456 => 123_456 ;
  945. Readonly my $NUMBER_654321 => 654_321 ;
  946. Readonly my $NUMBER_20_000 => 20_000 ;
  947. Readonly my $QUOTA_PERCENT_LIMIT => 90 ;
  948. Readonly my $NUMBER_104_857_600 => 104_857_600 ;
  949. Readonly my $SIZE_MAX_STR => 64 ;
  950. Readonly my $NB_SECONDS_IN_A_DAY => 86_400 ;
  951. Readonly my $STD_CHAR_PER_LINE => 80 ;
  952. Readonly my $TRUE => 1 ;
  953. Readonly my $FALSE => 0 ;
  954. Readonly my $LAST_RESSORT_SEPARATOR => q{/} ;
  955. Readonly my $CGI_TMPDIR_TOP => '/var/tmp/imapsync_cgi' ;
  956. Readonly my $CGI_HASHFILE => '/var/tmp/imapsync_hash' ;
  957. Readonly my $UMASK_PARANO => '0077' ;
  958. Readonly my $STR_use_releasecheck => q{Check if a new imapsync release is available by adding --releasecheck} ;
  959. Readonly my $GMAIL_MAXSIZE => 35_651_584 ;
  960. Readonly my $FORCE => 1 ;
  961. # if ( 'MSWin32' eq $OSNAME )
  962. # if ( 'darwin' eq $OSNAME )
  963. # if ( 'linux' eq $OSNAME )
  964. # global variables
  965. # Currently working to finish with only $sync, $acc1, $acc2
  966. # Not finished yet...
  967. my(
  968. $sync, $acc1, $acc2,
  969. $debugflags,
  970. $debuglist, $debugdev, $debugmaxlinelength, $debugcgi,
  971. @include, @exclude, @folderrec,
  972. @folderfirst, @folderlast,
  973. @h1_folders_all, %h1_folders_all,
  974. @h2_folders_all, %h2_folders_all,
  975. @h2_folders_from_1_wanted, %h2_folders_from_1_all,
  976. %requested_folder,
  977. $h1_folders_wanted_nb, $h1_folders_wanted_ct,
  978. @h2_folders_not_in_1,
  979. %h1_subscribed_folder, %h2_subscribed_folder,
  980. %h2_folders_from_1_wanted,
  981. %h2_folders_from_1_several,
  982. $prefix1, $prefix2,
  983. @regexmess, @skipmess, @pipemess, $pipemesscheck,
  984. $syncflagsaftercopy,
  985. $syncinternaldates,
  986. $idatefromheader,
  987. $minsize, $maxage, $minage,
  988. $search,
  989. @useheader, %useheader,
  990. $skipsize, $allowsizemismatch, $buffersize,
  991. $authmd5, $authmd51, $authmd52,
  992. $subscribed, $subscribe, $subscribeall,
  993. $help,
  994. $nb_msg_skipped_dry_mode,
  995. $h2_nb_msg_noheader,
  996. $h1_bytes_processed,
  997. $h1_nb_msg_end, $h1_bytes_end,
  998. $h2_nb_msg_end, $h2_bytes_end,
  999. $timestart_int,
  1000. $uid1, $uid2,
  1001. $split1, $split2,
  1002. $modulesversion,
  1003. $delete2folders, $delete2foldersonly, $delete2foldersbutnot,
  1004. $usecache, $debugcache, $cacheaftercopy,
  1005. $wholeheaderifneeded, %h1_msgs_copy_by_uid, $useuid, $h2_uidguess,
  1006. $checkmessageexists,
  1007. $messageidnodomain,
  1008. $fixInboxINBOX,
  1009. $maxlinelength, $maxlinelengthcmd,
  1010. $minmaxlinelength,
  1011. $fixcolonbug,
  1012. $create_folder_old,
  1013. $skipcrossduplicates, $debugcrossduplicates,
  1014. $disarmreadreceipts,
  1015. $mixfolders,
  1016. $fetch_hash_set,
  1017. $cgidir,
  1018. %month_abrev,
  1019. $SSL_VERIFY_POLICY,
  1020. ) ;
  1021. single_sync( $sync, $acc1, $acc2 );
  1022. sub single_sync
  1023. {
  1024. # main program
  1025. # global variables initialization
  1026. # I'm currently removing all global variables except $sync $acc1 $acc2
  1027. # passing each of them under
  1028. # $sync->{variable_name}
  1029. # or $acc1->{variable_name}
  1030. # or $acc1->{variable_name}
  1031. #
  1032. $acc1 = {} ;
  1033. $acc2 = {} ;
  1034. $sync->{ acc1 } = $acc1 ;
  1035. $sync->{ acc2 } = $acc2 ;
  1036. $acc1->{ Side } = 'Host1' ;
  1037. $acc2->{ Side } = 'Host2' ;
  1038. $acc1->{ N } = '1' ;
  1039. $acc2->{ N } = '2' ;
  1040. $sync->{timestart} = time ; # Is a float because of use Time::HiRres
  1041. $sync->{rcs} = q{$Id: imapsync,v 2.178 2022/01/12 21:28:37 gilles Exp gilles $} ;
  1042. $sync->{ memory_consumption_at_start } = memory_consumption( ) || 0 ;
  1043. my @loadavg = loadavg( ) ;
  1044. $sync->{ cpu_number } = cpu_number( ) ;
  1045. $sync->{ loaddelay } = load_and_delay( $sync->{ cpu_number }, @loadavg ) ;
  1046. $sync->{ loaddelay } = 0 ;
  1047. $sync->{ loadavg } = join( q{ }, $loadavg[ 0 ] )
  1048. . " on $sync->{cpu_number} cores and "
  1049. . ram_memory_info( ) ;
  1050. $sync->{ total_bytes_transferred } = 0 ;
  1051. $sync->{ total_bytes_skipped } = 0 ;
  1052. $sync->{ nb_msg_transferred } = 0 ;
  1053. $sync->{ nb_msg_skipped } = $nb_msg_skipped_dry_mode = 0 ;
  1054. $sync->{ acc1 }->{ nb_msg_deleted } = 0 ;
  1055. $sync->{ acc2 }->{ nb_msg_deleted } = 0 ;
  1056. $sync->{ acc1 }->{ nb_msg_duplicate } = 0 ;
  1057. $sync->{ acc2 }->{ nb_msg_duplicate } = 0 ;
  1058. $sync->{ h1_nb_msg_noheader } = 0 ;
  1059. $h2_nb_msg_noheader = 0 ;
  1060. $sync->{ h1_nb_msg_start } = 0 ;
  1061. $sync->{ h1_bytes_start } = 0 ;
  1062. $sync->{ h2_nb_msg_start } = 0 ;
  1063. $sync->{ h2_bytes_start } = 0 ;
  1064. $sync->{ h1_nb_msg_processed } = $h1_bytes_processed = 0 ;
  1065. $sync->{ h2_nb_msg_crossdup } = 0 ;
  1066. #$h1_nb_msg_end = $h1_bytes_end = 0 ;
  1067. #$h2_nb_msg_end = $h2_bytes_end = 0 ;
  1068. $sync->{ nb_errors } = 0;
  1069. $sync->{ biggest_message_transferred } = 0;
  1070. %month_abrev = (
  1071. Jan => '00',
  1072. Feb => '01',
  1073. Mar => '02',
  1074. Apr => '03',
  1075. May => '04',
  1076. Jun => '05',
  1077. Jul => '06',
  1078. Aug => '07',
  1079. Sep => '08',
  1080. Oct => '09',
  1081. Nov => '10',
  1082. Dec => '11',
  1083. );
  1084. # Just create a CGI object if under cgi context only.
  1085. # Needed for the get_options() call
  1086. cgibegin( $sync ) ;
  1087. # In cgi context, printing must start by the header so we delay other prints by using output() storage
  1088. my $options_good = get_options( $sync, @ARGV ) ;
  1089. # Is it the first myprint?
  1090. cgibuildheader( $sync ) ;
  1091. docker_context( $sync ) ;
  1092. print_output_if_needed( $sync ) ;
  1093. output_reset_with( $sync ) ;
  1094. # don't go on if options are not all known.
  1095. if ( ! defined $options_good ) { exit $EX_USAGE ; }
  1096. # If you want releasecheck not to be done by default (like the github maintainer),
  1097. # then just uncomment the first "$sync->{releasecheck} =" line, the line ending with "0 ;",
  1098. # the second line (ending with "1 ;") can then stay active or be commented,
  1099. # the result will be the same: no releasecheck by default (because 0 is then the defined value).
  1100. #$sync->{releasecheck} = defined $sync->{releasecheck} ? $sync->{releasecheck} : 0 ;
  1101. $sync->{releasecheck} = defined $sync->{releasecheck} ? $sync->{releasecheck} : 1 ;
  1102. # just the version
  1103. if ( $sync->{ version } ) {
  1104. myprint( imapsync_version( $sync ), "\n" ) ;
  1105. return 0 ;
  1106. }
  1107. #$sync->{debugenv} = 1 ;
  1108. $sync->{debugenv} and printenv( $sync ) ; # if option --debugenv
  1109. load_modules( ) ;
  1110. # after_get_options call usage and exit if --help or options were not well got
  1111. after_get_options( $sync, $options_good ) ;
  1112. #local $ENV{TZ} = 'GMT' if ( under_cgi_context( $sync ) and 'MSWin32' ne $OSNAME ) ;
  1113. #output( $sync, localtime(time) . " " . gmtime(time) . "\n" ) ;
  1114. # Under CGI environment, fix caveat emptor potential issues
  1115. cgisetcontext( $sync ) ;
  1116. get_options_extra( $sync ) ;
  1117. # --gmail --gmail --exchange --office etc.
  1118. easyany( $sync ) ;
  1119. $sync->{ sanitize } = defined $sync->{ sanitize } ? $sync->{ sanitize } : 1 ;
  1120. sanitize( $sync ) ;
  1121. $sync->{ tmpdir } ||= File::Spec->tmpdir( ) ;
  1122. # Unit tests
  1123. my $unittestssuite = unittestssuite( $sync ) ;
  1124. if ( condition_to_leave_after_tests( $sync ) )
  1125. {
  1126. return $unittestssuite ;
  1127. }
  1128. # init live varaiables
  1129. if ( $sync->{ testslive } )
  1130. {
  1131. testslive_init( $sync ) ;
  1132. }
  1133. if ( $sync->{ testslive6 } )
  1134. {
  1135. testslive6_init( $sync ) ;
  1136. }
  1137. define_pidfile( $sync ) ;
  1138. if ( $sync->{ abortbyfile } ) { $sync->{ abort } = 1 ; }
  1139. install_signals( $sync ) ;
  1140. $sync->{ log } = defined $sync->{ log } ? $sync->{ log } : 1 ;
  1141. $sync->{ errorsdump } = defined $sync->{ errorsdump } ? $sync->{ errorsdump } : 1 ;
  1142. $sync->{ errorsmax } = defined $sync->{ errorsmax } ? $sync->{ errorsmax } : $ERRORS_MAX ;
  1143. # log and output
  1144. binmode STDOUT, ":encoding(UTF-8)" ;
  1145. if ( $sync->{ log } ) {
  1146. setlogfile( $sync ) ;
  1147. teelaunch( $sync ) ;
  1148. # now $sync->{tee} is a filehandle to STDOUT and the logfile
  1149. }
  1150. #binmode STDERR, ":encoding(UTF-8)" ;
  1151. # STDERR goes to the same place: LOG and STDOUT (if logging is on)
  1152. # Useful only for --debugssl
  1153. $sync->{tee} and local *STDERR = *${$sync->{tee}}{IO} ;
  1154. $timestart_int = int( $sync->{timestart} ) ;
  1155. $sync->{timebefore} = $sync->{timestart} ;
  1156. $sync->{ timestart_str } = localtimez( $sync->{timestart} ) ;
  1157. # The prints in the log starts here
  1158. myprint( localhost_info( $sync ), "\n" ) ;
  1159. myprint( "Transfer started at $sync->{ timestart_str }\n" ) ;
  1160. myprint( "PID is $PROCESS_ID my PPID is ", mygetppid( ), "\n" ) ;
  1161. announcelogfile( $sync ) ;
  1162. myprint( "Load is " . ( join( q{ }, loadavg( ) ) || 'unknown' ), " on $sync->{cpu_number} cores\n" ) ;
  1163. #myprintf( "Memory consumption so far: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  1164. myprint( 'Current directory is ' . getcwd( ) . "\n" ) ;
  1165. myprint( 'Real user id is ' . getpwuid_any_os( $REAL_USER_ID ) . " (uid $REAL_USER_ID)\n" ) ;
  1166. myprint( 'Effective user id is ' . getpwuid_any_os( $EFFECTIVE_USER_ID ). " (euid $EFFECTIVE_USER_ID)\n" ) ;
  1167. $modulesversion = defined $modulesversion ? $modulesversion : 1 ;
  1168. $sync->{ warn_release } = ( $sync->{ releasecheck } ) ? check_last_release( ) : $STR_use_releasecheck ;
  1169. $wholeheaderifneeded = defined $wholeheaderifneeded ? $wholeheaderifneeded : 1;
  1170. # Activate --usecache if --useuid is set and there is no --nousecache
  1171. $usecache = 1 if ( $useuid and ( ! defined $usecache ) ) ;
  1172. $cacheaftercopy = 1 if ( $usecache and ( ! defined $cacheaftercopy ) ) ;
  1173. $sync->{ checkfoldersexist } = defined $sync->{ checkfoldersexist } ? $sync->{ checkfoldersexist } : 1 ;
  1174. $checkmessageexists = defined $checkmessageexists ? $checkmessageexists : 0 ;
  1175. $sync->{ expungeaftereach } = defined $sync->{ expungeaftereach } ? $sync->{ expungeaftereach } : 1 ;
  1176. # abletosearch is on by default
  1177. $sync->{abletosearch} = defined $sync->{abletosearch} ? $sync->{abletosearch} : 1 ;
  1178. $sync->{abletosearch1} = defined $sync->{abletosearch1} ? $sync->{abletosearch1} : $sync->{abletosearch} ;
  1179. $sync->{abletosearch2} = defined $sync->{abletosearch2} ? $sync->{abletosearch2} : $sync->{abletosearch} ;
  1180. $checkmessageexists = 0 if ( not $sync->{abletosearch1} ) ;
  1181. $sync->{ trylogin } = defined $sync->{ trylogin } ? $sync->{ trylogin } : 1 ;
  1182. $sync->{showpasswords} = defined $sync->{showpasswords} ? $sync->{showpasswords} : 0 ;
  1183. $sync->{ fixslash2 } = defined $sync->{ fixslash2 } ? $sync->{ fixslash2 } : 1 ;
  1184. $fixInboxINBOX = defined $fixInboxINBOX ? $fixInboxINBOX : 1 ;
  1185. $create_folder_old = defined $create_folder_old ? $create_folder_old : 0 ;
  1186. $mixfolders = defined $mixfolders ? $mixfolders : 1 ;
  1187. $sync->{automap} = defined $sync->{automap} ? $sync->{automap} : 0 ;
  1188. $sync->{ delete2duplicates } = 1 if ( $sync->{ delete2 } and ( ! defined $sync->{ delete2duplicates } ) ) ;
  1189. $sync->{maxmessagespersecond} = defined $sync->{maxmessagespersecond} ? $sync->{maxmessagespersecond} : 0 ;
  1190. $sync->{maxbytespersecond} = defined $sync->{maxbytespersecond} ? $sync->{maxbytespersecond} : 0 ;
  1191. $sync->{sslcheck} = defined $sync->{sslcheck} ? $sync->{sslcheck} : 1 ;
  1192. myprint( banner_imapsync( $sync, @ARGV ) ) ;
  1193. myprint( "Temp directory is $sync->{ tmpdir } ( to change it use --tmpdir dirpath )\n" ) ;
  1194. myprint( output( $sync ) ) ;
  1195. output_reset_with( $sync ) ;
  1196. do_valid_directory( $sync->{ tmpdir } ) || croak "Error creating tmpdir $sync->{ tmpdir } : $OS_ERROR" ;
  1197. remove_pidfile_not_running( $sync->{ pidfile } ) ;
  1198. # if another imapsync is running then tail -f its logfile and exit
  1199. # useful in cgi context
  1200. if ( $sync->{ tail } and tail( $sync ) )
  1201. {
  1202. exit_clean( $sync, $EX_OK, "Tail -f finished. Now finishing myself processus $PROCESS_ID\n" ) ;
  1203. exit $EX_OK ;
  1204. }
  1205. if ( ! write_pidfile( $sync ) ) {
  1206. 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" ) ;
  1207. exit $EXIT_PID_FILE_ERROR ;
  1208. }
  1209. # New place for abort
  1210. # abort before simulong in order to be able to abort a simulong sync
  1211. if ( $sync->{ abort } )
  1212. {
  1213. abort( $sync ) ;
  1214. # well, the abort job is done, because even when not succeeded
  1215. # in aborting another run, this run has to end without doing any
  1216. # thing else
  1217. exit $EX_OK ;
  1218. }
  1219. # simulong is just a loop printing some lines for xx seconds with option "--simulong xx".
  1220. simulong( $sync ) ;
  1221. # New place for cgiload 2019_03_03
  1222. # because I want to log it
  1223. # Can break here if load is too heavy
  1224. # Have in mind the CGI header has already a 503 Service Unavailable
  1225. cgiload( $sync ) ;
  1226. $fixcolonbug = defined $fixcolonbug ? $fixcolonbug : 1 ;
  1227. if ( $usecache and $fixcolonbug ) { tmpdir_fix_colon_bug( $sync ) } ;
  1228. $modulesversion and myprint( "Modules version list ( use --no-modulesversion to turn off printing this Perl modules list ):\n", modulesversion(), "\n" ) ;
  1229. check_lib_version( $sync ) or
  1230. croak "imapsync needs perl lib Mail::IMAPClient release 3.30 or superior.\n";
  1231. if ( $sync->{ justbanner } )
  1232. {
  1233. myprint( "Exiting because of --justbanner\n" ) ;
  1234. exit_clean( $sync, $EX_OK ) ;
  1235. }
  1236. # turn on RFC standard flags correction like \SEEN -> \Seen
  1237. $sync->{ flagscase } = defined $sync->{ flagscase } ? $sync->{ flagscase } : 1 ;
  1238. # Use PERMANENTFLAGS if available
  1239. $sync->{ filterflags } = defined $sync->{ filterflags } ? $sync->{ filterflags } : 1 ;
  1240. filterbuggyflags( $sync ) ;
  1241. # sync flags just after an APPEND, some servers ignore the flags given in the APPEND
  1242. # like MailEnable IMAP server.
  1243. # Off by default since it takes time.
  1244. $syncflagsaftercopy = defined $syncflagsaftercopy ? $syncflagsaftercopy : 0 ;
  1245. # update flags on host2 for already transferred messages
  1246. $sync->{resyncflags} = defined $sync->{resyncflags} ? $sync->{resyncflags} : 1 ;
  1247. if ( $sync->{resyncflags} ) {
  1248. myprint( "Info: will resync flags for already transferred messages. Use --noresyncflags to not resync flags.\n" ) ;
  1249. }else{
  1250. myprint( "Info: will not resync flags for already transferred messages. Use --resyncflags to resync flags.\n" ) ;
  1251. }
  1252. sslcheck( $sync ) ;
  1253. #print Data::Dumper->Dump( [ \$sync ] ) ;
  1254. $split1 ||= $SPLIT ;
  1255. $split2 ||= $SPLIT ;
  1256. #$sync->{host1} || missing_option( $sync, '--host1' ) ;
  1257. $sync->{host1} = sanitize_host( $sync->{host1} ) ;
  1258. $sync->{port1} ||= ( $sync->{ssl1} ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  1259. #$sync->{host2} || missing_option( $sync, '--host2' ) ;
  1260. $sync->{host2} = sanitize_host( $sync->{host2} ) ;
  1261. $sync->{port2} ||= ( $sync->{ssl2} ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  1262. $acc1->{ debugimap } = $acc2->{ debugimap } = 1 if ( $sync->{ debugimap } ) ;
  1263. # Set on debug mode if one of the imap dialogs are in debug.
  1264. # imap dialog without the debug mode is scary and useless.
  1265. $sync->{ debug } = 1 if ( $acc1->{ debugimap } or $acc2->{ debugimap } ) ;
  1266. # By default, don't take size to compare
  1267. $skipsize = (defined $skipsize) ? $skipsize : 1;
  1268. $uid1 = defined $uid1 ? $uid1 : 1;
  1269. $uid2 = defined $uid2 ? $uid2 : 1;
  1270. $subscribe = defined $subscribe ? $subscribe : 1;
  1271. # Allow size mismatch by default
  1272. $allowsizemismatch = defined $allowsizemismatch ? $allowsizemismatch : 1;
  1273. if ( defined $delete2foldersbutnot or defined $delete2foldersonly ) {
  1274. $delete2folders = 1 ;
  1275. }
  1276. my %SSL_VERIFY_STR ;
  1277. Readonly $SSL_VERIFY_POLICY => IO::Socket::SSL::SSL_VERIFY_NONE( ) ;
  1278. Readonly %SSL_VERIFY_STR => (
  1279. IO::Socket::SSL::SSL_VERIFY_NONE( ) => 'SSL_VERIFY_NONE, ie, do not check the certificate server.' ,
  1280. IO::Socket::SSL::SSL_VERIFY_PEER( ) => 'SSL_VERIFY_PEER, ie, check the certificate server' ,
  1281. ) ;
  1282. $IO::Socket::SSL::DEBUG = defined( $sync->{debugssl} ) ? $sync->{debugssl} : 1 ;
  1283. if ( $sync->{ssl1} or $sync->{ssl2} or $sync->{tls1} or $sync->{tls2}) {
  1284. 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" ) ;
  1285. }
  1286. if ( $sync->{ssl1} ) {
  1287. 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} ) ;
  1288. 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" ) ;
  1289. # $sync->{ acc1 }->{sslargs}->{SSL_verify_mode}
  1290. }
  1291. if ( $sync->{ssl2} ) {
  1292. 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} ) ;
  1293. 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" ) ;
  1294. }
  1295. # ID on by default since 1.832
  1296. $sync->{id} = defined $sync->{id} ? $sync->{id} : 1 ;
  1297. if ( $sync->{justconnect}
  1298. or not $sync->{user1}
  1299. or not $sync->{user2}
  1300. or not $sync->{host1}
  1301. or not $sync->{host2}
  1302. )
  1303. {
  1304. my $justconnect = justconnect( $sync ) ;
  1305. myprint( debugmemory( $sync, " after justconnect() call" ) ) ;
  1306. exit_clean( $sync, $EX_OK,
  1307. "Exiting after a justconnect on host(s): $justconnect\n"
  1308. ) ;
  1309. }
  1310. #$sync->{user1} || missing_option( $sync, '--user1' ) ;
  1311. #$sync->{user2} || missing_option( $sync, '--user2' ) ;
  1312. $syncinternaldates = defined $syncinternaldates ? $syncinternaldates : 1;
  1313. # Turn on expunge if there is not explicit option --noexpunge1 and option
  1314. # --delete1 is given.
  1315. # Done because --delete1 --noexpunge1 is very dangerous on the second run:
  1316. # the Deleted flag is then synced to all previously transferred messages.
  1317. # So --delete1 implies --expunge1 is a better usability default behavior.
  1318. if ( $sync->{ delete1 } ) {
  1319. if ( ! defined $sync->{ expunge1 } ) {
  1320. myprint( "Info: turning on --expunge1 because --delete1 --noexpunge1 is very dangerous on the second run.\n" ) ;
  1321. $sync->{ expunge1 } = 1 ;
  1322. }
  1323. myprint( "Info: if expunging after each message slows down too much the sync then use --noexpungeaftereach to speed up\n" ) ;
  1324. }
  1325. if ( $sync->{ uidexpunge2 } and not Mail::IMAPClient->can( 'uidexpunge' ) ) {
  1326. myprint( "Failure: uidexpunge not supported (IMAPClient release < 3.17), use nothing or --expunge2 instead\n" ) ;
  1327. $sync->{nb_errors}++ ;
  1328. exit_clean( $sync, $EX_SOFTWARE ) ;
  1329. }
  1330. if ( ( $sync->{ delete2 } or $sync->{ delete2duplicates } ) and not defined $sync->{ uidexpunge2 } ) {
  1331. if ( Mail::IMAPClient->can( 'uidexpunge' ) ) {
  1332. myprint( "Info: will act as --uidexpunge2\n" ) ;
  1333. $sync->{ uidexpunge2 } = 1 ;
  1334. }elsif ( not defined $sync->{ expunge2 } ) {
  1335. myprint( "Info: will act as --expunge2 (no uidexpunge support)\n" ) ;
  1336. $sync->{ expunge2 } = 1 ;
  1337. }
  1338. }
  1339. if ( $sync->{ delete1 } and $sync->{ delete2 } ) {
  1340. myprint( "Warning: using --delete1 and --delete2 together is almost always a bad idea. "
  1341. . "You should probably launch two runs, the first with --delete2 for a strict sync, "
  1342. . "then the second with --delete1 to remove messages from the source account. "
  1343. . "Exiting imapsync.\n" ) ;
  1344. $sync->{ nb_errors }++ ;
  1345. exit_clean( $sync, $EX_USAGE ) ;
  1346. }
  1347. if ( $idatefromheader ) {
  1348. myprint( 'Turned ON idatefromheader, ',
  1349. "will set the internal dates on host2 from the 'Date:' header line.\n" ) ;
  1350. $syncinternaldates = 0 ;
  1351. }
  1352. if ( $syncinternaldates ) {
  1353. myprint( 'Info: turned ON syncinternaldates, ',
  1354. "will set the internal dates (arrival dates) on host2 same as host1.\n" ) ;
  1355. }else{
  1356. myprint( "Info: turned OFF syncinternaldates\n" ) ;
  1357. }
  1358. if ( defined $authmd5 and $authmd5 ) {
  1359. $authmd51 = 1 ;
  1360. $authmd52 = 1 ;
  1361. }
  1362. if ( defined $authmd51 and $authmd51 ) {
  1363. $acc1->{ authmech } ||= 'CRAM-MD5' ;
  1364. }
  1365. else{
  1366. $acc1->{ authmech } ||= $acc1->{ authuser } ? 'PLAIN' : 'LOGIN' ;
  1367. }
  1368. if ( defined $authmd52 and $authmd52 ) {
  1369. $acc2->{ authmech } ||= 'CRAM-MD5';
  1370. }
  1371. else{
  1372. $acc2->{ authmech } ||= $acc2->{ authuser } ? 'PLAIN' : 'LOGIN';
  1373. }
  1374. $acc1->{ authmech } = uc $acc1->{ authmech } ;
  1375. $acc2->{ authmech } = uc $acc2->{ authmech } ;
  1376. if ( defined $acc1->{ proxyauth } && !$acc1->{ authuser } )
  1377. {
  1378. missing_option( $sync, 'With --proxyauth1, --authuser1' ) ;
  1379. }
  1380. if ( defined $acc2->{ proxyauth } && !$acc2->{ authuser } )
  1381. {
  1382. missing_option( $sync, 'With --proxyauth2, --authuser2' ) ;
  1383. }
  1384. myprint( "Host1: will try to use $acc1->{ authmech } authentication on host1\n") ;
  1385. myprint( "Host2: will try to use $acc2->{ authmech } authentication on host2\n") ;
  1386. $sync->{ timeout } = defined $sync->{ timeout } ?$sync->{ timeout } : $DEFAULT_TIMEOUT ;
  1387. $sync->{ acc1 }->{timeout} = defined $sync->{ acc1 }->{timeout} ? $sync->{ acc1 }->{timeout} : $sync->{ timeout } ;
  1388. myprint( "Host1: imap connection timeout is $sync->{ acc1 }->{timeout} seconds\n") ;
  1389. $sync->{ acc2 }->{timeout} = defined $sync->{ acc2 }->{timeout} ? $sync->{ acc2 }->{timeout} : $sync->{ timeout } ;
  1390. myprint( "Host2: imap connection timeout is $sync->{ acc2 }->{timeout} seconds\n" ) ;
  1391. keepalive1( $sync ) ;
  1392. keepalive2( $sync ) ;
  1393. if ( under_cgi_context( $sync ) )
  1394. {
  1395. myprint( "Under CGI context, a timeout can occur from the webserver, see https://imapsync.lamiral.info/INSTALL.d/INSTALL.OnlineUI.txt\n" ) ;
  1396. }
  1397. $sync->{ syncacls } = defined $sync->{ syncacls } ? $sync->{ syncacls } : 0 ;
  1398. # No folders sizes at the beginning if --justfolders, unless really wanted.
  1399. if (
  1400. $sync->{ justfolders }
  1401. and not defined $sync->{ foldersizes }
  1402. and not $sync->{ justfoldersizes } )
  1403. {
  1404. $sync->{ foldersizes } = 0 ;
  1405. $sync->{ foldersizesatend } = 1 ;
  1406. }
  1407. $sync->{ foldersizes } = ( defined $sync->{ foldersizes } ) ? $sync->{ foldersizes } : 1 ;
  1408. $sync->{ foldersizesatend } = ( defined $sync->{ foldersizesatend } ) ? $sync->{ foldersizesatend } : $sync->{ foldersizes } ;
  1409. #$sync->{ checknoabletosearch } = ( defined $sync->{ checknoabletosearch } ) ? $sync->{ checknoabletosearch } : 1 ;
  1410. set_checknoabletosearch( $sync ) ;
  1411. $acc1->{ fastio } = defined $acc1->{ fastio } ? $acc1->{ fastio } : 0 ;
  1412. $acc2->{ fastio } = defined $acc2->{ fastio } ? $acc2->{ fastio } : 0 ;
  1413. $acc1->{ reconnectretry } = defined $acc1->{ reconnectretry } ? $acc1->{ reconnectretry } : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  1414. $acc2->{ reconnectretry } = defined $acc2->{ reconnectretry } ? $acc2->{ reconnectretry } : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  1415. # IMAP compression on by default
  1416. #$acc1->{ compress } = defined $acc1->{ compress } ? $acc1->{ compress } : 0 ;
  1417. #$acc2->{ compress } = defined $acc2->{ compress } ? $acc2->{ compress } : 0 ;
  1418. if ( ! @useheader ) { @useheader = qw( Message-Id Received ) ; }
  1419. # Make a hash %useheader of each --useheader 'key' in uppercase
  1420. for ( @useheader ) { $sync->{useheader}->{ uc $_ } = undef } ;
  1421. #myprint( Data::Dumper->Dump( [ \%useheader ] ) ) ;
  1422. #exit ;
  1423. myprint( "Host1: IMAP server [$sync->{host1}] port [$sync->{port1}] user [$sync->{user1}]\n" ) ;
  1424. myprint( "Host2: IMAP server [$sync->{host2}] port [$sync->{port2}] user [$sync->{user2}]\n" ) ;
  1425. get_password1( $sync ) ;
  1426. get_password2( $sync ) ;
  1427. # --dry1 make imapsync not fetching messages from host1, it is on when --dry is on.
  1428. # Use --dry --nodry1 to make imapsync fetching messages from host1,
  1429. # It is useful when debugging transformation options like --pipemess or --regexmess
  1430. $sync->{dry1} = defined $sync->{dry1} ? $sync->{dry1} : $sync->{dry} ;
  1431. $sync->{dry_message} = q{} ;
  1432. if( $sync->{dry} ) {
  1433. $sync->{dry_message} = "\t(not really since --dry mode)" ;
  1434. }
  1435. $sync->{ search1 } ||= $search if ( $search ) ;
  1436. $sync->{ search2 } ||= $search if ( $search ) ;
  1437. if ( $disarmreadreceipts )
  1438. {
  1439. push @regexmess, q{s{\A((?:[^\n]+\r\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims} ;
  1440. }
  1441. $pipemesscheck = ( defined $pipemesscheck ) ? $pipemesscheck : 1 ;
  1442. if ( @pipemess and $pipemesscheck ) {
  1443. myprint( 'Checking each --pipemess command, '
  1444. . join( q{, }, @pipemess )
  1445. . ", with an space string. ( Can avoid this check with --nopipemesscheck )\n" ) ;
  1446. my $string = pipemess( q{ }, @pipemess ) ;
  1447. # string undef means something was bad.
  1448. if ( not ( defined $string ) ) {
  1449. $sync->{nb_errors}++ ;
  1450. exit_clean( $sync, $EX_USAGE,
  1451. "Error: one of --pipemess command is bad, check it\n"
  1452. ) ;
  1453. }
  1454. myprint( "Ok with each --pipemess @pipemess\n" ) ;
  1455. }
  1456. if ( $maxlinelengthcmd ) {
  1457. myprint( "Checking --maxlinelengthcmd command,
  1458. $maxlinelengthcmd, with an space string.\n"
  1459. ) ;
  1460. my $string = pipemess( q{ }, $maxlinelengthcmd ) ;
  1461. # string undef means something was bad.
  1462. if ( not ( defined $string ) ) {
  1463. $sync->{nb_errors}++ ;
  1464. exit_clean( $sync, $EX_USAGE,
  1465. "Error: --maxlinelengthcmd command is bad, check it\n"
  1466. ) ;
  1467. }
  1468. myprint( "Ok with --maxlinelengthcmd $maxlinelengthcmd\n" ) ;
  1469. }
  1470. if ( @regexmess ) {
  1471. my $string = regexmess( q{ } ) ;
  1472. myprint( "Checking each --regexmess command with an space string.\n" ) ;
  1473. # string undef means one of the eval regex was bad.
  1474. if ( not ( defined $string ) ) {
  1475. #errors_incr( $sync, 'Warning: one of --regexmess option may be bad, check them' ) ;
  1476. exit_clean( $sync, $EX_USAGE,
  1477. "Error: one of --regexmess option is bad, check it\n"
  1478. ) ;
  1479. }
  1480. myprint( "Ok with each --regexmess\n" ) ;
  1481. }
  1482. if ( @skipmess ) {
  1483. myprint( "Checking each --skipmess command with an space string.\n" ) ;
  1484. my $match = skipmess( q{ } ) ;
  1485. # match undef means one of the eval regex was bad.
  1486. if ( not ( defined $match ) ) {
  1487. $sync->{nb_errors}++ ;
  1488. exit_clean( $sync, $EX_USAGE,
  1489. "Error: one of --skipmess option is bad, check it\n"
  1490. ) ;
  1491. }
  1492. myprint( "Ok with each --skipmess\n" ) ;
  1493. }
  1494. if ( $sync->{ regexflag } ) {
  1495. myprint( "Checking each --regexflag command with an space string.\n" ) ;
  1496. my $string = regexflags( $sync, q{ } ) ;
  1497. # string undef means one of the eval regex was bad.
  1498. if ( not ( defined $string ) ) {
  1499. $sync->{nb_errors}++ ;
  1500. exit_clean( $sync, $EX_USAGE,
  1501. "Error: one of --regexflag option is bad, check it\n"
  1502. ) ;
  1503. }
  1504. myprint( "Ok with each --regexflag\n" ) ;
  1505. }
  1506. $sync->{imap1} = login_imap( $sync->{host1}, $sync->{port1}, $sync->{user1}, $sync->{password1},
  1507. $sync->{ssl1}, $sync->{tls1},
  1508. $uid1, $split1, $sync->{ acc1 }, $sync ) ;
  1509. $sync->{imap2} = login_imap( $sync->{host2}, $sync->{port2}, $sync->{user2}, $sync->{password2},
  1510. $sync->{ssl2}, $sync->{tls2},
  1511. $uid2, $split2, $sync->{ acc2 }, $sync ) ;
  1512. $sync->{ debug } and $sync->{imap1} and myprint( 'Host1 Buffer I/O: ', $sync->{imap1}->Buffer(), "\n" ) ;
  1513. $sync->{ debug } and $sync->{imap2} and myprint( 'Host2 Buffer I/O: ', $sync->{imap2}->Buffer(), "\n" ) ;
  1514. if ( ! $sync->{imap1} || ! $sync->{imap2} )
  1515. {
  1516. exit_most_errors( $sync ) ;
  1517. }
  1518. myprint( "Host1: state Authenticated\n" ) ;
  1519. myprint( "Host2: state Authenticated\n" ) ;
  1520. myprint( 'Host1 capability once authenticated: ', join(q{ }, @{ $sync->{imap1}->capability() || [] }), "\n" ) ;
  1521. #myprint( Data::Dumper->Dump( [ $sync->{imap1} ] ) ) ;
  1522. #myprint( "imap4rev1: " . $sync->{imap1}->imap4rev1() . "\n" ) ;
  1523. myprint( 'Host2 capability once authenticated: ', join(q{ }, @{ $sync->{imap2}->capability() || [] }), "\n" ) ;
  1524. imap_id_stuff( $sync ) ;
  1525. #quota( $sync, $sync->{imap1}, 'h1' ) ; # quota on host1 is useless and pollute host2 output.
  1526. quota( $sync, $sync->{imap2}, 'h2' ) ;
  1527. maxsize_setting( $sync ) ;
  1528. acc_compress_imap( $acc1 ) ;
  1529. acc_compress_imap( $acc2 ) ;
  1530. if ( $sync->{ justlogin } ) {
  1531. $sync->{imap1}->logout( ) ;
  1532. $sync->{imap2}->logout( ) ;
  1533. exit_clean( $sync, $EX_OK, "Exiting because of --justlogin\n" ) ;
  1534. }
  1535. #
  1536. # Folder stuff
  1537. #
  1538. $h1_folders_wanted_nb = 0 ; # counter of folders to be done.
  1539. $h1_folders_wanted_ct = 0 ; # counter of folders done.
  1540. # All folders on host1 and host2
  1541. @h1_folders_all = sort $sync->{imap1}->folders( ) ;
  1542. @h2_folders_all = sort $sync->{imap2}->folders( ) ;
  1543. myprint( 'Host1: found ', scalar @h1_folders_all , " folders.\n" ) ;
  1544. myprint( 'Host2: found ', scalar @h2_folders_all , " folders.\n" ) ;
  1545. foreach my $f ( @h1_folders_all )
  1546. {
  1547. $h1_folders_all{ $f } = 1
  1548. }
  1549. foreach my $f ( @h2_folders_all )
  1550. {
  1551. $h2_folders_all{ $f } = 1 ;
  1552. $sync->{h2_folders_all_UPPER}{ uc $f } = 1 ;
  1553. }
  1554. $sync->{h1_folders_all} = \%h1_folders_all ;
  1555. $sync->{h2_folders_all} = \%h2_folders_all ;
  1556. private_folders_separators_and_prefixes( ) ;
  1557. # Make a hash of subscribed folders in both servers.
  1558. for ( $sync->{imap1}->subscribed( ) ) { $h1_subscribed_folder{ $_ } = 1 } ;
  1559. for ( $sync->{imap2}->subscribed( ) ) { $h2_subscribed_folder{ $_ } = 1 } ;
  1560. if ( defined $sync->{ subfolder1 } ) {
  1561. subfolder1( $sync ) ;
  1562. }
  1563. if ( defined $sync->{ subfolder2 } ) {
  1564. subfolder2( $sync ) ;
  1565. }
  1566. if ( $fixInboxINBOX and ( my $reg = fix_Inbox_INBOX_mapping( \%h1_folders_all, \%h2_folders_all ) ) ) {
  1567. push @{ $sync->{ regextrans2 } }, $reg ;
  1568. }
  1569. if ( ( $sync->{ folder } and scalar @{ $sync->{ folder } } )
  1570. or $subscribed
  1571. or scalar @folderrec )
  1572. {
  1573. # folders given by option --folder
  1574. if ( $sync->{ folder } and scalar @{ $sync->{ folder } } ) {
  1575. add_to_requested_folders( @{ $sync->{ folder } } ) ;
  1576. }
  1577. # option --subscribed
  1578. if ( $subscribed ) {
  1579. add_to_requested_folders( keys %h1_subscribed_folder ) ;
  1580. }
  1581. # option --folderrec
  1582. if ( scalar @folderrec ) {
  1583. foreach my $folderrec ( @folderrec ) {
  1584. add_to_requested_folders( $sync->{imap1}->folders( $folderrec ) ) ;
  1585. }
  1586. }
  1587. }
  1588. else
  1589. {
  1590. # no include, no folder/subscribed/folderrec options => all folders
  1591. if ( not scalar @include ) {
  1592. 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" ) ;
  1593. add_to_requested_folders( @h1_folders_all ) ;
  1594. }
  1595. }
  1596. # consider (optional) includes and excludes
  1597. if ( scalar @include ) {
  1598. foreach my $include ( @include ) {
  1599. # No, do not add /x after the regex, never.
  1600. # Users would kill you!
  1601. my @included_folders = grep { /$include/ } @h1_folders_all ;
  1602. add_to_requested_folders( @included_folders ) ;
  1603. myprint( "Including folders matching pattern $include\n" . jux_utf8_list( @included_folders ) . "\n" ) ;
  1604. }
  1605. }
  1606. if ( scalar @exclude ) {
  1607. foreach my $exclude ( @exclude ) {
  1608. my @requested_folder = sort keys %requested_folder ;
  1609. # No, do not add /x after the regex, never.
  1610. # Users would kill you!
  1611. my @excluded_folders = grep { /$exclude/ } @requested_folder ;
  1612. remove_from_requested_folders( @excluded_folders ) ;
  1613. myprint( "Excluding folders matching pattern $exclude\n" . jux_utf8_list( @excluded_folders ) . "\n" ) ;
  1614. }
  1615. }
  1616. # sort before is not very powerful
  1617. # it adds --folderfirst and --folderlast even if they don't exist on host1
  1618. #@h1_folders_wanted = sort_requested_folders( ) ;
  1619. $sync->{h1_folders_wanted} = [ sort_requested_folders( ) ] ;
  1620. # Remove no selectable folders
  1621. if ( $sync->{ checkfoldersexist } ) {
  1622. my @h1_folders_wanted_exist ;
  1623. myprint( "Host1: Checking wanted folders exist. Use --nocheckfoldersexist to avoid this check (shared of public namespace targeted).\n" ) ;
  1624. foreach my $folder ( @{ $sync->{h1_folders_wanted} } ) {
  1625. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "Checking $folder exists on host1\n" ) ;
  1626. if ( ! exists $h1_folders_all{ $folder } ) {
  1627. myprint( "Host1: warning! ignoring folder $folder because it is not in host1 whole folders list.\n" ) ;
  1628. next ;
  1629. }else{
  1630. push @h1_folders_wanted_exist, $folder ;
  1631. }
  1632. }
  1633. @{ $sync->{h1_folders_wanted} } = @h1_folders_wanted_exist ;
  1634. }else{
  1635. myprint( "Host1: Not checking that wanted folders exist. Remove --nocheckfoldersexist to get this check.\n" ) ;
  1636. }
  1637. setcheckselectable( $sync ) ;
  1638. checkselectable( $sync ) ;
  1639. # Bugfix OpenFind folders named like "kk \*123" are in fact "kk *123" (no \)
  1640. #foreach my $folder ( @{ $sync->{ h1_folders_wanted } } )
  1641. #{
  1642. # $folder =~ s{ \\\*}{ *}g ;
  1643. #}
  1644. # this hack is because LWP post does not pass well a hash in the $form parameter
  1645. # but it does pass well an array
  1646. %{ $sync->{f1f2h} } = split_around_equal( @{ $sync->{f1f2} } ) ;
  1647. automap( $sync ) ;
  1648. foreach my $h1_fold ( @{ $sync->{h1_folders_wanted} } ) {
  1649. my $h2_fold ;
  1650. $h2_fold = imap2_folder_name( $sync, $h1_fold ) ;
  1651. $h2_folders_from_1_wanted{ $h2_fold }++ ;
  1652. if ( 1 < $h2_folders_from_1_wanted{ $h2_fold } ) {
  1653. $h2_folders_from_1_several{ $h2_fold }++ ;
  1654. }
  1655. }
  1656. @h2_folders_from_1_wanted = sort keys %h2_folders_from_1_wanted;
  1657. foreach my $h1_fold ( @h1_folders_all ) {
  1658. my $h2_fold ;
  1659. $h2_fold = imap2_folder_name( $sync, $h1_fold ) ;
  1660. $h2_folders_from_1_all{ $h2_fold }++ ;
  1661. # Follows a fix to avoid deleting folder $sync->{ subfolder2 }
  1662. # because it usually does not exist on host1.
  1663. if ( $sync->{ subfolder2 } )
  1664. {
  1665. $h2_folders_from_1_all{ $sync->{ h2_prefix } . $sync->{ subfolder2 } }++ ;
  1666. $h2_folders_from_1_all{ $sync->{ subfolder2 } }++ ;
  1667. }
  1668. }
  1669. myprint( << 'END_LISTING' ) ;
  1670. ++++ Listing folders
  1671. All foldernames are presented between brackets like [X] where X is the foldername.
  1672. When a foldername contains non-ASCII characters it is presented in the form
  1673. [X] = [Y] where
  1674. X is the imap foldername you have to use in command line options and
  1675. Y is the utf8 output just printed for convenience, to recognize it.
  1676. END_LISTING
  1677. myprint(
  1678. "Host1: folders list (first the raw imap format then the [X] = [Y]):\n",
  1679. $sync->{imap1}->list( ),
  1680. "\n",
  1681. jux_utf8_list( @h1_folders_all ),
  1682. "\n",
  1683. "Host2: folders list (first the raw imap format then the [X] = [Y]):\n",
  1684. $sync->{imap2}->list( ),
  1685. "\n",
  1686. jux_utf8_list( @h2_folders_all ),
  1687. "\n",
  1688. q{}
  1689. ) ;
  1690. if ( $subscribed ) {
  1691. myprint(
  1692. 'Host1 subscribed folders list: ',
  1693. jux_utf8_list( sort keys %h1_subscribed_folder ), "\n",
  1694. ) ;
  1695. }
  1696. @h2_folders_not_in_1 = list_folders_in_2_not_in_1( ) ;
  1697. if ( @h2_folders_not_in_1 ) {
  1698. myprint( "Folders in host2 not in host1:\n",
  1699. jux_utf8_list( @h2_folders_not_in_1 ), "\n" ) ;
  1700. }
  1701. if ( keys %{ $sync->{f1f2auto} } ) {
  1702. myprint( "Folders mapping from --automap feature (use --f1f2 to override any mapping):\n" ) ;
  1703. foreach my $h1_fold ( keys %{ $sync->{f1f2auto} } ) {
  1704. my $h2_fold = $sync->{f1f2auto}{$h1_fold} ;
  1705. myprintf( "%-40s -> %-40s\n",
  1706. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1707. }
  1708. myprint( "\n" ) ;
  1709. }
  1710. if ( keys %{ $sync->{f1f2h} } ) {
  1711. myprint( "Folders mapping from --f1f2 options, it overrides --automap:\n" ) ;
  1712. foreach my $h1_fold ( keys %{ $sync->{f1f2h} } ) {
  1713. my $h2_fold = $sync->{f1f2h}{$h1_fold} ;
  1714. my $warn = q{} ;
  1715. if ( not exists $h1_folders_all{ $h1_fold } ) {
  1716. $warn = "BUT $h1_fold does NOT exist on host1!" ;
  1717. }
  1718. myprintf( "%-40s -> %-40s %s\n",
  1719. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ), $warn ) ;
  1720. }
  1721. myprint( "\n" ) ;
  1722. }
  1723. exit_clean( $sync, $EX_OK, "Exiting because of --justfolderlists\n" ) if ( $sync->{ justfolderlists } ) ;
  1724. exit_clean( $sync, $EX_OK, "Exiting because of --justautomap\n" ) if ( $sync->{ justautomap } ) ;
  1725. debugsleep( $sync ) ;
  1726. if ( $sync->{ skipemptyfolders } )
  1727. {
  1728. myprint( "Host1: will not syncing empty folders on host1. Use --noskipemptyfolders to create them anyway on host2\n") ;
  1729. }
  1730. if ( $sync->{ checknoabletosearch } )
  1731. {
  1732. myprint( "Checking SEARCH ALL works on both accounts. To avoid that check, use --nochecknoabletosearch\n" ) ;
  1733. my $check1 = checknoabletosearch( $sync, $sync->{ imap1 }, 'INBOX', 'Host1' ) ;
  1734. my $check2 = checknoabletosearch( $sync, $sync->{ imap2 }, 'INBOX', 'Host2' ) ;
  1735. if ( $check1 or $check2 )
  1736. {
  1737. myprint( "At least one account can not SEARCH ALL. So acting like --noabletosearch\n" ) ;
  1738. $sync->{abletosearch} = 0 ;
  1739. $sync->{abletosearch1} = 0 ;
  1740. $sync->{abletosearch2} = 0 ;
  1741. }
  1742. else
  1743. {
  1744. myprint( "Good! SEARCH ALL works on both accounts.\n" ) ;
  1745. }
  1746. }
  1747. if ( $sync->{ foldersizes } ) {
  1748. foldersizes_at_the_beggining( $sync ) ;
  1749. #foldersizes_at_the_beggining_old( $sync ) ;
  1750. }
  1751. if ( $sync->{ justfoldersizes } )
  1752. {
  1753. exit_clean( $sync, $EX_OK, "Exiting because of --justfoldersizes\n" ) ;
  1754. }
  1755. $sync->{can_do_stats} = 1 ;
  1756. if ( $sync->{ delete1emptyfolders } ) {
  1757. delete1emptyfolders( $sync ) ;
  1758. }
  1759. delete_folders_in_2_not_in_1( ) if $delete2folders ;
  1760. # folder loop
  1761. $h1_folders_wanted_nb = scalar @{ $sync->{h1_folders_wanted} } ;
  1762. myprint( "++++ Looping on each one of $h1_folders_wanted_nb folders to sync\n" ) ;
  1763. $sync->{begin_transfer_time} = time ;
  1764. my %uid_candidate_for_deletion ;
  1765. my %uid_candidate_no_deletion ;
  1766. $sync->{ h2_folders_of_md5 } = { } ;
  1767. FOLDER: foreach my $h1_fold ( @{ $sync->{h1_folders_wanted} } )
  1768. {
  1769. $sync->{ h1_current_folder } = $h1_fold ;
  1770. eta_print( $sync ) ;
  1771. abortifneeded( $sync ) ;
  1772. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1773. my $h2_fold = imap2_folder_name( $sync, $h1_fold ) ;
  1774. $sync->{ h2_current_folder } = $h2_fold ;
  1775. $h1_folders_wanted_ct++ ;
  1776. myprintf( "Folder %7s %-35s -> %-35s\n", "$h1_folders_wanted_ct/$h1_folders_wanted_nb",
  1777. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1778. myprint( debugmemory( $sync, " at folder loop" ) ) ;
  1779. # host1 can not be fetched read only, select is needed because of expunge.
  1780. select_folder( $sync, $sync->{imap1}, $h1_fold, 'Host1' ) or next FOLDER ;
  1781. debugsleep( $sync ) ;
  1782. my $h1_msgs_all_hash_ref ;
  1783. my @h1_msgs ;
  1784. my $h1_msgs_nb ;
  1785. my $h1_msgs_nb_from_select ;
  1786. $h1_msgs_nb_from_select = count_from_select( $sync->{imap1}->History ) ;
  1787. myprint( "Host1: folder [$h1_fold] has $h1_msgs_nb_from_select messages in total (mentioned by SELECT)\n" ) ;
  1788. if ( $sync->{ skipemptyfolders } and 0 == $h1_msgs_nb_from_select ) {
  1789. myprint( "Host1: skipping empty host1 folder [$h1_fold]\n" ) ;
  1790. next FOLDER ;
  1791. }
  1792. # Code added from https://github.com/imapsync/imapsync/issues/95
  1793. # Thanks jh1995
  1794. # Goal: do not create folder if --search or --max/minage return 0 message.
  1795. # even if there are messages by SELECT (no not real empty, empty for the user point of vue).
  1796. if ( $sync->{ skipemptyfolders } or $sync->{ dry } )
  1797. {
  1798. $h1_msgs_all_hash_ref = { } ;
  1799. @h1_msgs = select_msgs( $sync->{imap1}, $h1_msgs_all_hash_ref, $sync->{ search1 }, $sync->{abletosearch1}, $h1_fold ) ;
  1800. $h1_msgs_nb = scalar( @h1_msgs ) ;
  1801. if ( 0 == $h1_msgs_nb and $sync->{ skipemptyfolders } ) {
  1802. myprint( "Host1: skipping empty host1 folder [$h1_fold] (0 message found by SEARCH)\n" ) ;
  1803. next FOLDER ;
  1804. }
  1805. }
  1806. if ( ! exists $h2_folders_all{ $h2_fold } ) {
  1807. # In --dry mode I could count the messages to be transfered instead of 0
  1808. # Messages transferred : 0 (could be 0 without dry mode)
  1809. if ( ! create_folder( $sync, $sync->{imap2}, $h2_fold, $h1_fold ) )
  1810. {
  1811. if ( $sync->{ dry } )
  1812. {
  1813. $nb_msg_skipped_dry_mode += $h1_msgs_nb ;
  1814. }
  1815. next FOLDER ;
  1816. }
  1817. }
  1818. acls_sync( $sync, $h1_fold, $h2_fold ) ;
  1819. # Sometimes the folder on host2 is listed (it exists) but is
  1820. # not selectable but becomes selectable by a create (Gmail)
  1821. select_folder( $sync, $sync->{imap2}, $h2_fold, 'Host2' )
  1822. or ( create_folder( $sync, $sync->{imap2}, $h2_fold, $h1_fold )
  1823. and select_folder( $sync, $sync->{imap2}, $h2_fold, 'Host2' ) )
  1824. or next FOLDER ;
  1825. my @select_results = $sync->{imap2}->Results( ) ;
  1826. my $h2_fold_nb_messages = count_from_select( @select_results ) ;
  1827. myprint( "Host2: folder [$h2_fold] has $h2_fold_nb_messages messages in total (mentioned by SELECT)\n" ) ;
  1828. my $permanentflags2 = permanentflags( $sync, @select_results ) ;
  1829. myprint( "Host2: folder [$h2_fold] permanentflags: $permanentflags2\n" ) ;
  1830. if ( $sync->{ expunge1 } )
  1831. {
  1832. myprint( "Host1: Expunging $h1_fold $sync->{dry_message}\n" ) ;
  1833. if ( ! $sync->{dry} )
  1834. {
  1835. $sync->{imap1}->expunge( ) ;
  1836. }
  1837. }
  1838. if ( ( ( $subscribe and exists $h1_subscribed_folder{ $h1_fold } ) or $subscribeall )
  1839. and not exists $h2_subscribed_folder{ $h2_fold } )
  1840. {
  1841. myprint( "Host2: Subscribing to folder $h2_fold\n" ) ;
  1842. if ( ! $sync->{dry} ) { $sync->{imap2}->subscribe( $h2_fold ) } ;
  1843. }
  1844. next FOLDER if ( $sync->{ justfolders } ) ;
  1845. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1846. if ( ! defined $h1_msgs_nb )
  1847. {
  1848. $h1_msgs_all_hash_ref = { } ;
  1849. @h1_msgs = select_msgs( $sync->{imap1}, $h1_msgs_all_hash_ref, $sync->{ search1 }, $sync->{abletosearch1}, $h1_fold );
  1850. $h1_msgs_nb = scalar @h1_msgs ;
  1851. }else{
  1852. # select_msgs already done.
  1853. }
  1854. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1855. myprint( "Host1: folder [$h1_fold] considering $h1_msgs_nb messages\n" ) ;
  1856. ( $sync->{ debug } or $debuglist ) and myprint( "Host1: folder [$h1_fold] considering $h1_msgs_nb messages, LIST gives: @h1_msgs\n" ) ;
  1857. $sync->{ debug } and myprint( "Host1: selecting messages of folder [$h1_fold] took ", timenext( $sync ), " s\n" ) ;
  1858. my $h2_msgs_all_hash_ref = { } ;
  1859. my @h2_msgs = select_msgs( $sync->{imap2}, $h2_msgs_all_hash_ref, $sync->{ search2 }, $sync->{abletosearch2}, $h2_fold ) ;
  1860. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1861. my $h2_msgs_nb = scalar @h2_msgs ;
  1862. myprint( "Host2: folder [$h2_fold] considering $h2_msgs_nb messages\n" ) ;
  1863. ( $sync->{ debug } or $debuglist ) and myprint( "Host2: folder [$h2_fold] considering $h2_msgs_nb messages, LIST gives: @h2_msgs\n" ) ;
  1864. $sync->{ debug } and myprint( "Host2: selecting messages of folder [$h2_fold] took ", timenext( $sync ), " s\n" ) ;
  1865. my $cache_base = "$sync->{ tmpdir }/imapsync_cache/" ;
  1866. my $cache_dir = cache_folder( $cache_base,
  1867. "$sync->{host1}/$sync->{user1}/$sync->{host2}/$sync->{user2}", $h1_fold, $h2_fold ) ;
  1868. my ( $cache_1_2_ref, $cache_2_1_ref ) = ( {}, {} ) ;
  1869. my $h1_uidvalidity = $sync->{imap1}->uidvalidity( ) || q{} ;
  1870. my $h2_uidvalidity = $sync->{imap2}->uidvalidity( ) || q{} ;
  1871. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1872. if ( $usecache ) {
  1873. myprint( "Local cache directory: $cache_dir ( " . length( $cache_dir ) . " characters long )\n" ) ;
  1874. mkpath( "$cache_dir" ) ;
  1875. ( $cache_1_2_ref, $cache_2_1_ref )
  1876. = get_cache( $cache_dir, \@h1_msgs, \@h2_msgs, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  1877. myprint( 'CACHE h1 h2: ', scalar keys %{ $cache_1_2_ref } , " files\n" ) ;
  1878. $sync->{ debug } and myprint( '[',
  1879. map ( { "$_->$cache_1_2_ref->{$_} " } keys %{ $cache_1_2_ref } ), " ]\n" ) ;
  1880. }
  1881. my %h1_hash = ( ) ;
  1882. my %h2_hash = ( ) ;
  1883. my ( %h1_msgs, %h2_msgs ) ;
  1884. @h1_msgs{ @h1_msgs } = ( ) ;
  1885. @h2_msgs{ @h2_msgs } = ( ) ;
  1886. my @h1_msgs_in_cache = sort { $a <=> $b } keys %{ $cache_1_2_ref } ;
  1887. my @h2_msgs_in_cache = sort { $a <=> $b } keys %{ $cache_2_1_ref } ;
  1888. my ( %h1_msgs_not_in_cache, %h2_msgs_not_in_cache ) ;
  1889. %h1_msgs_not_in_cache = %h1_msgs ;
  1890. %h2_msgs_not_in_cache = %h2_msgs ;
  1891. delete @h1_msgs_not_in_cache{ @h1_msgs_in_cache } ;
  1892. delete @h2_msgs_not_in_cache{ @h2_msgs_in_cache } ;
  1893. my @h1_msgs_not_in_cache = sort { $a <=> $b } keys %h1_msgs_not_in_cache ;
  1894. #myprint( "h1_msgs_not_in_cache: [@h1_msgs_not_in_cache]\n" ) ;
  1895. my @h2_msgs_not_in_cache = sort { $a <=> $b } keys %h2_msgs_not_in_cache ;
  1896. my @h2_msgs_delete2_not_in_cache = () ;
  1897. %h1_msgs_copy_by_uid = ( ) ;
  1898. if ( $useuid ) {
  1899. # use uid so we have to avoid getting header
  1900. @h1_msgs_copy_by_uid{ @h1_msgs_not_in_cache } = ( ) ;
  1901. @h2_msgs_delete2_not_in_cache = @h2_msgs_not_in_cache if $usecache ;
  1902. @h1_msgs_not_in_cache = ( ) ;
  1903. @h2_msgs_not_in_cache = ( ) ;
  1904. #myprint( "delete2: @h2_msgs_delete2_not_in_cache\n" ) ;
  1905. }
  1906. $sync->{ debug } and myprint( "Host1: parsing headers of folder [$h1_fold]\n" ) ;
  1907. my ($h1_heads_ref, $h1_fir_ref) = ({}, {});
  1908. $h1_heads_ref = $sync->{imap1}->parse_headers([@h1_msgs_not_in_cache], @useheader) if (@h1_msgs_not_in_cache);
  1909. $sync->{ debug } and myprint( "Host1: parsing headers of folder [$h1_fold] took ", timenext( $sync ), " s\n" ) ;
  1910. @{ $h1_fir_ref }{@h1_msgs} = ( undef ) ;
  1911. $sync->{ debug } and myprint( "Host1: getting flags idate and sizes of folder [$h1_fold]\n" ) ;
  1912. my @h1_common_fetch_param = ( 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE' ) ;
  1913. if ( $sync->{ synclabels } or $sync->{ resynclabels } ) { push @h1_common_fetch_param, 'X-GM-LABELS' ; }
  1914. if ( $sync->{abletosearch1} )
  1915. {
  1916. $h1_fir_ref = $sync->{imap1}->fetch_hash( \@h1_msgs, @h1_common_fetch_param, $h1_fir_ref )
  1917. if ( @h1_msgs ) ;
  1918. }
  1919. else
  1920. {
  1921. my $fetch_hash_uids = $fetch_hash_set || "1:*" ;
  1922. $h1_fir_ref = $sync->{imap1}->fetch_hash( $fetch_hash_uids, @h1_common_fetch_param, $h1_fir_ref )
  1923. if ( @h1_msgs ) ;
  1924. }
  1925. $sync->{ debug } and myprint( "Host1: getting flags idate and sizes of folder [$h1_fold] took ", timenext( $sync ), " s\n" ) ;
  1926. if ( ! $h1_fir_ref )
  1927. {
  1928. my $error = join( q{}, "Host1: folder $h1_fold : Could not fetch_hash ",
  1929. scalar @h1_msgs, ' msgs: ', $sync->{imap1}->LastError || q{}, "\n" ) ;
  1930. errors_incr( $sync, $error ) ;
  1931. next FOLDER ;
  1932. }
  1933. my @h1_msgs_duplicate;
  1934. foreach my $m ( @h1_msgs_not_in_cache )
  1935. {
  1936. my $rc = parse_header_msg( $sync, $sync->{imap1}, $m, $h1_heads_ref, $h1_fir_ref, 'Host1', \%h1_hash ) ;
  1937. if ( ! defined $rc )
  1938. {
  1939. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1940. myprint( "Host1: $h1_fold/$m size $h1_size ignored (no wanted headers so we ignore this message. To solve this: use --addheader)\n" ) ;
  1941. $sync->{ total_bytes_skipped } += $h1_size ;
  1942. $sync->{ nb_msg_skipped } += 1 ;
  1943. $sync->{ h1_nb_msg_noheader } +=1 ;
  1944. $sync->{ h1_nb_msg_processed } +=1 ;
  1945. } elsif( 0 == $rc )
  1946. {
  1947. # duplicate
  1948. push @h1_msgs_duplicate, $m;
  1949. # duplicate, same id same size?
  1950. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1951. $sync->{ acc1 }->{ nb_msg_duplicate } += 1;
  1952. if ( ! $sync->{ syncduplicates } ) {
  1953. $sync->{ nb_msg_skipped } += 1 ;
  1954. $sync->{ h1_nb_msg_processed } +=1 ;
  1955. }
  1956. }
  1957. }
  1958. my $h1_msgs_duplicate_nb = scalar @h1_msgs_duplicate ;
  1959. myprint( "Host1: folder [$h1_fold] selected $h1_msgs_nb messages, duplicates $h1_msgs_duplicate_nb\n" ) ;
  1960. $sync->{ debug } and myprint( 'Host1: whole time parsing headers took ', timenext( $sync ), " s\n" ) ;
  1961. # Getting headers and metada can be so long that host2 might be disconnected here
  1962. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1963. $sync->{ debug } and myprint( "Host2: parsing headers of folder [$h2_fold]\n" ) ;
  1964. my ($h2_heads_ref, $h2_fir_ref) = ( {}, {} );
  1965. $h2_heads_ref = $sync->{imap2}->parse_headers([@h2_msgs_not_in_cache], @useheader) if (@h2_msgs_not_in_cache);
  1966. $sync->{ debug } and myprint( "Host2: parsing headers of folder [$h2_fold] took ", timenext( $sync ), " s\n" ) ;
  1967. $sync->{ debug } and myprint( "Host2: getting flags idate and sizes of folder [$h2_fold]\n" ) ;
  1968. @{ $h2_fir_ref }{@h2_msgs} = ( ); # fetch_hash can select by uid with last arg as ref
  1969. my @h2_common_fetch_param = ( 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE' ) ;
  1970. if ( $sync->{ synclabels } or $sync->{ resynclabels } ) { push @h2_common_fetch_param, 'X-GM-LABELS' ; }
  1971. if ( $sync->{abletosearch2} and scalar( @h2_msgs ) ) {
  1972. $h2_fir_ref = $sync->{imap2}->fetch_hash( \@h2_msgs, @h2_common_fetch_param, $h2_fir_ref) ;
  1973. }else{
  1974. my $fetch_hash_uids = $fetch_hash_set || "1:*" ;
  1975. $h2_fir_ref = $sync->{imap2}->fetch_hash( $fetch_hash_uids, @h2_common_fetch_param, $h2_fir_ref )
  1976. if ( @h2_msgs ) ;
  1977. }
  1978. $sync->{ debug } and myprint( "Host2: getting flags idate and sizes of folder [$h2_fold] took ", timenext( $sync ), " s\n" ) ;
  1979. my @h2_msgs_duplicate;
  1980. foreach my $m (@h2_msgs_not_in_cache) {
  1981. my $rc = parse_header_msg( $sync, $sync->{imap2}, $m, $h2_heads_ref, $h2_fir_ref, 'Host2', \%h2_hash ) ;
  1982. my $h2_size = $h2_fir_ref->{$m}->{'RFC822.SIZE'} || 0 ;
  1983. if (! defined $rc ) {
  1984. myprint( "Host2: $h2_fold/$m size $h2_size ignored (no wanted headers so we ignore this message)\n" ) ;
  1985. $h2_nb_msg_noheader += 1 ;
  1986. } elsif( 0 == $rc ) {
  1987. # duplicate
  1988. $sync->{ acc2 }->{ nb_msg_duplicate } += 1 ;
  1989. push @h2_msgs_duplicate, $m ;
  1990. }
  1991. }
  1992. # %h2_folders_of_md5
  1993. foreach my $md5 ( keys %h2_hash ) {
  1994. $sync->{ h2_folders_of_md5 }->{ $md5 }->{ $h2_fold } ++ ;
  1995. }
  1996. # %h1_folders_of_md5
  1997. foreach my $md5 ( keys %h1_hash ) {
  1998. $sync->{ h1_folders_of_md5 }->{ $md5 }->{ $h2_fold } ++ ;
  1999. }
  2000. my $h2_msgs_duplicate_nb = scalar @h2_msgs_duplicate ;
  2001. myprint( "Host2: folder [$h2_fold] selected $h2_msgs_nb messages, duplicates $h2_msgs_duplicate_nb\n" ) ;
  2002. $sync->{ debug } and myprint( 'Host2 whole time parsing headers took ', timenext( $sync ), " s\n" ) ;
  2003. $sync->{ debug } and myprint( "++++ Verifying [$h1_fold] -> [$h2_fold]\n" ) ;
  2004. # messages in host1 that are not in host2
  2005. my @h1_hash_keys_sorted_by_uid
  2006. = sort {$h1_hash{$a}{'m'} <=> $h1_hash{$b}{'m'}} keys %h1_hash;
  2007. #myprint( map { $h1_hash{$_}{'m'} . q{ }} @h1_hash_keys_sorted_by_uid ) ;
  2008. my @h2_hash_keys_sorted_by_uid
  2009. = sort {$h2_hash{$a}{'m'} <=> $h2_hash{$b}{'m'}} keys %h2_hash;
  2010. # Deletions on account2.
  2011. if( $sync->{ delete2duplicates } and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  2012. my @h2_expunge ;
  2013. foreach my $h2_msg ( @h2_msgs_duplicate ) {
  2014. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted [duplicate] on host2 $sync->{dry_message}\n" ) ;
  2015. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 } ;
  2016. if ( ! $sync->{ dry } ) {
  2017. $sync->{ imap2 }->delete_message( $h2_msg ) ;
  2018. $sync->{ acc2 }->{ nb_msg_deleted } += 1 ;
  2019. }
  2020. }
  2021. my $cnt = scalar @h2_expunge ;
  2022. if( @h2_expunge and not $sync->{ expunge2 } ) {
  2023. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  2024. $sync->{imap2}->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  2025. }
  2026. if ( $sync->{ expunge2 } ){
  2027. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  2028. $sync->{imap2}->expunge( ) if ! $sync->{dry} ;
  2029. }
  2030. }
  2031. if( $sync->{ delete2 } and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  2032. # No host1 folders f1a f1b ... going all to same f2 (via --regextrans2)
  2033. my @h2_expunge;
  2034. foreach my $m_id (@h2_hash_keys_sorted_by_uid) {
  2035. #myprint( "$m_id " ) ;
  2036. if ( ! exists $h1_hash{$m_id} ) {
  2037. my $h2_msg = $h2_hash{$m_id}{'m'};
  2038. my $h2_flags = $h2_hash{$m_id}{'F'} || q{};
  2039. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0;
  2040. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted on host2 [$m_id] $sync->{dry_message}\n" )
  2041. if ! $isdel;
  2042. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 };
  2043. if ( ! ( $sync->{ dry } or $isdel ) ) {
  2044. $sync->{ imap2 }->delete_message( $h2_msg );
  2045. $sync->{ acc2 }->{ nb_msg_deleted } += 1;
  2046. }
  2047. }
  2048. }
  2049. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  2050. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted [not in cache] on host2 $sync->{dry_message}\n" ) ;
  2051. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 };
  2052. if ( ! $sync->{dry} ) {
  2053. $sync->{ imap2 }->delete_message( $h2_msg );
  2054. $sync->{ acc2 }->{ nb_msg_deleted } += 1;
  2055. }
  2056. }
  2057. my $cnt = scalar @h2_expunge ;
  2058. if( @h2_expunge and not $sync->{ expunge2 } ) {
  2059. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  2060. $sync->{imap2}->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  2061. }
  2062. if ( $sync->{ expunge2 } ) {
  2063. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  2064. $sync->{imap2}->expunge( ) if ! $sync->{dry} ;
  2065. }
  2066. }
  2067. if( $sync->{ delete2 } and exists $h2_folders_from_1_several{ $h2_fold } ) {
  2068. myprint( "Host2: folder $h2_fold $h2_folders_from_1_several{ $h2_fold } folders left to sync there\n" ) ;
  2069. my @h2_expunge;
  2070. foreach my $m_id ( @h2_hash_keys_sorted_by_uid ) {
  2071. my $h2_msg = $h2_hash{ $m_id }{ 'm' } ;
  2072. if ( ! exists $h1_hash{ $m_id } ) {
  2073. my $h2_flags = $h2_hash{ $m_id }{ 'F' } || q{} ;
  2074. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0 ;
  2075. if ( ! $isdel ) {
  2076. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [$m_id]\n" ) ;
  2077. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  2078. }
  2079. }else{
  2080. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [$m_id]\n" ) ;
  2081. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  2082. }
  2083. }
  2084. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  2085. myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [not in cache]\n" ) ;
  2086. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  2087. }
  2088. foreach my $h2_msg ( @h2_msgs_in_cache ) {
  2089. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [in cache]\n" ) ;
  2090. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  2091. }
  2092. if ( 0 == $h2_folders_from_1_several{ $h2_fold } ) {
  2093. # last host1 folder going to $h2_fold
  2094. myprint( "Last host1 folder going to $h2_fold\n" ) ;
  2095. foreach my $h2_msg ( keys %{ $uid_candidate_for_deletion{ $h2_fold } } ) {
  2096. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion\n" ) ;
  2097. if ( exists $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg } ) {
  2098. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg canceled deletion\n" ) ;
  2099. }else{
  2100. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted $sync->{dry_message}\n" ) ;
  2101. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 } ;
  2102. if ( ! $sync->{ dry} ) {
  2103. $sync->{ imap2 }->delete_message( $h2_msg ) ;
  2104. $sync->{ acc2 }->{ nb_msg_deleted } += 1 ;
  2105. }
  2106. }
  2107. }
  2108. }
  2109. my $cnt = scalar @h2_expunge ;
  2110. if( @h2_expunge and not $sync->{ expunge2 } ) {
  2111. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  2112. $sync->{imap2}->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  2113. }
  2114. if ( $sync->{ expunge2 } ) {
  2115. myprint( "Host2: Expunging host2 folder $h2_fold $sync->{dry_message}\n" ) ;
  2116. $sync->{imap2}->expunge( ) if ! $sync->{dry} ;
  2117. }
  2118. $h2_folders_from_1_several{ $h2_fold }-- ;
  2119. }
  2120. my $h2_uidnext = $sync->{imap2}->uidnext( $h2_fold ) ;
  2121. $sync->{ debug } and myprint( "Host2: uidnext is $h2_uidnext\n" ) ;
  2122. $h2_uidguess = $h2_uidnext ;
  2123. # Getting host2 headers, metada and delete2 stuff can be so long that host1 might be disconnected here
  2124. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2125. my @h1_msgs_to_delete ;
  2126. MESS: foreach my $m_id (@h1_hash_keys_sorted_by_uid) {
  2127. abortifneeded( $sync ) ;
  2128. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2129. #myprint( "h1_nb_msg_processed: $sync->{ h1_nb_msg_processed }\n" ) ;
  2130. my $h1_size = $h1_hash{$m_id}{'s'};
  2131. my $h1_msg = $h1_hash{$m_id}{'m'};
  2132. my $h1_idate = $h1_hash{$m_id}{'D'};
  2133. #my $labels = labels( $sync->{imap1}, $h1_msg ) ;
  2134. #print "LABELS: $labels\n" ;
  2135. if ( ( not exists $h2_hash{ $m_id } )
  2136. and ( not ( exists $sync->{ h2_folders_of_md5 }->{ $m_id } )
  2137. or not $skipcrossduplicates ) )
  2138. {
  2139. # copy
  2140. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  2141. if ( $h2_msg and $sync->{ delete1 } and not $sync->{ expungeaftereach } ) {
  2142. # not expunged
  2143. push @h1_msgs_to_delete, $h1_msg ;
  2144. }
  2145. # A bug here with imapsync 1.920, fixed in 1.921
  2146. # Added $h2_msg in the condition. Errors of APPEND were not counted as missing messages on host2!
  2147. if ( $h2_msg and not $sync->{ dry } )
  2148. {
  2149. $sync->{ h2_folders_of_md5 }->{ $m_id }->{ $h2_fold } ++ ;
  2150. }
  2151. #
  2152. if( $sync->{ delete2 } and ( exists $h2_folders_from_1_several{ $h2_fold } ) and $h2_msg ) {
  2153. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  2154. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  2155. }
  2156. if ( total_bytes_max_reached( $sync ) ) {
  2157. # Still a bug when using --delete1 --noexpungeaftereach
  2158. # same thing below on all total_bytes_max_reached!
  2159. last FOLDER ;
  2160. }
  2161. next MESS;
  2162. }
  2163. else
  2164. {
  2165. # already on host2
  2166. if ( exists $h2_hash{ $m_id } )
  2167. {
  2168. my $h2_msg = $h2_hash{$m_id}{'m'} ;
  2169. $sync->{ debug } and myprint( "Host1: found that msg $h1_fold/$h1_msg equals Host2 $h2_fold/$h2_msg\n" ) ;
  2170. if ( $usecache )
  2171. {
  2172. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$h2_msg\n" ) ;
  2173. touch( "$cache_dir/${h1_msg}_$h2_msg" )
  2174. or croak( "Couldn't touch $cache_dir/${h1_msg}_$h2_msg" ) ;
  2175. }
  2176. }
  2177. elsif( exists $sync->{ h2_folders_of_md5 }->{ $m_id } )
  2178. {
  2179. my @folders_dup = keys %{ $sync->{ h2_folders_of_md5 }->{ $m_id } } ;
  2180. ( $sync->{ debug } or $debugcrossduplicates ) and myprint( "Host1: found that msg $h1_fold/$h1_msg is also in Host2 folders @folders_dup\n" ) ;
  2181. $sync->{ h2_nb_msg_crossdup } +=1 ;
  2182. }
  2183. $sync->{ total_bytes_skipped } += $h1_size ;
  2184. $sync->{ nb_msg_skipped } += 1 ;
  2185. $sync->{ h1_nb_msg_processed } +=1 ;
  2186. }
  2187. if ( exists $h2_hash{ $m_id } ) {
  2188. #$debug and myprint( "MESSAGE $m_id\n" ) ;
  2189. my $h2_msg = $h2_hash{$m_id}{'m'};
  2190. if ( $sync->{resyncflags} ) {
  2191. sync_flags_fir( $sync, $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  2192. }
  2193. # Good
  2194. my $h2_size = $h2_hash{$m_id}{'s'};
  2195. $sync->{ debug } and myprint(
  2196. "Host1: size msg $h1_fold/$h1_msg = $h1_size <> $h2_size = Host2 $h2_fold/$h2_msg\n" ) ;
  2197. if ( $sync->{ resynclabels } )
  2198. {
  2199. resynclabels( $sync, $h1_msg, $h2_msg, $h1_fir_ref, $h2_fir_ref, $h1_fold )
  2200. }
  2201. }
  2202. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2203. if ( $sync->{ delete1 } ) {
  2204. push @h1_msgs_to_delete, $h1_msg ;
  2205. }
  2206. }
  2207. # END MESS: loop
  2208. # @h1_msgs_in_cache are already synced too.
  2209. delete_message_on_host1( $sync, $h1_fold, $sync->{ expunge1 }, @h1_msgs_to_delete, @h1_msgs_in_cache ) ;
  2210. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2211. # MESS_IN_CACHE:
  2212. if ( ! $sync->{ delete1 } )
  2213. {
  2214. foreach my $h1_msg ( @h1_msgs_in_cache )
  2215. {
  2216. my $h2_msg = $cache_1_2_ref->{ $h1_msg } ;
  2217. $debugcache and myprint( "cache messages update flags $h1_msg->$h2_msg\n" ) ;
  2218. if ( $sync->{resyncflags} )
  2219. {
  2220. sync_flags_fir( $sync, $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  2221. }
  2222. my $h1_size = $h1_fir_ref->{ $h1_msg }->{ 'RFC822.SIZE' } || 0 ;
  2223. $sync->{ total_bytes_skipped } += $h1_size;
  2224. $sync->{ nb_msg_skipped } += 1;
  2225. $sync->{ h1_nb_msg_processed } +=1 ;
  2226. }
  2227. }
  2228. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2229. @h1_msgs_to_delete = ( ) ;
  2230. #myprint( "Messages by uid: ", map { "$_ " } keys %h1_msgs_copy_by_uid, "\n" ) ;
  2231. # MESS_BY_UID:
  2232. foreach my $h1_msg ( sort { $a <=> $b } keys %h1_msgs_copy_by_uid )
  2233. {
  2234. abortifneeded( $sync ) ;
  2235. $sync->{ debug } and myprint( "Copy by uid $h1_fold/$h1_msg\n" ) ;
  2236. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  2237. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  2238. if( $sync->{ delete2 } and exists $h2_folders_from_1_several{ $h2_fold } and $h2_msg ) {
  2239. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  2240. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  2241. }
  2242. last FOLDER if total_bytes_max_reached( $sync ) ;
  2243. }
  2244. if ( $sync->{ expunge1 } ){
  2245. myprint( "Host1: Expunging folder $h1_fold $sync->{dry_message}\n" ) ;
  2246. if ( ! $sync->{dry} ) { $sync->{imap1}->expunge( ) } ;
  2247. }
  2248. if ( $sync->{ expunge2 } ){
  2249. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  2250. if ( ! $sync->{dry} ) { $sync->{imap2}->expunge( ) } ;
  2251. }
  2252. $sync->{ debug } and myprint( 'Time: ', timenext( $sync ), " s\n" ) ;
  2253. }
  2254. eta_print( $sync ) ;
  2255. myprint( "++++ End looping on each folder\n" ) ;
  2256. if ( $sync->{ delete1 } and $sync->{ delete1emptyfolders } ) {
  2257. delete1emptyfolders( $sync ) ;
  2258. }
  2259. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( 'Time: ', timenext( $sync ), " s\n" ) ;
  2260. if ( $sync->{ foldersizesatend } ) {
  2261. myprint( << 'END_SIZE' ) ;
  2262. Folders sizes after the synchronization.
  2263. You can remove this foldersizes listing by using "--nofoldersizesatend"
  2264. END_SIZE
  2265. foldersizesatend( $sync ) ;
  2266. }
  2267. #$sync->{imap1}->State( 0 ); # Unconnected
  2268. if ( ! lost_connection( $sync, $sync->{imap1}, "for host1 [$sync->{host1}]" ) ) { $sync->{imap1}->logout( ) ; }
  2269. if ( ! lost_connection( $sync, $sync->{imap2}, "for host2 [$sync->{host2}]" ) ) { $sync->{imap2}->logout( ) ; }
  2270. do_and_print_stats( $sync ) ;
  2271. if ( $sync->{ nb_errors } )
  2272. {
  2273. myprint( errors_listing( $sync ) ) ;
  2274. }
  2275. if ( $sync->{ testslive } or $sync->{ testslive6 } )
  2276. {
  2277. tests_live_result( $sync->{ nb_errors } ) ;
  2278. }
  2279. if ( $sync->{ nb_errors } )
  2280. {
  2281. my $exit_value = exit_value( $sync, $sync->{ most_common_error } ) ;
  2282. exit_clean( $sync, $exit_value ) ;
  2283. }
  2284. else
  2285. {
  2286. exit_clean( $sync, $EX_OK ) ;
  2287. }
  2288. return ;
  2289. }
  2290. # END of sub single_sync
  2291. # subroutines
  2292. sub myprint
  2293. {
  2294. #print @ARG ;
  2295. print { $sync->{ tee } || \*STDOUT } @ARG ;
  2296. return ;
  2297. }
  2298. sub myprintf
  2299. {
  2300. printf { $sync->{ tee } || \*STDOUT } @ARG ;
  2301. return ;
  2302. }
  2303. sub mysprintf
  2304. {
  2305. my( $format, @list ) = @ARG ;
  2306. return sprintf $format, @list ;
  2307. }
  2308. sub output_start
  2309. {
  2310. my $mysync = shift @ARG ;
  2311. if ( not $mysync ) { return ; }
  2312. my @output = @ARG ;
  2313. $mysync->{ output } = join( q{}, @output ) . ( $mysync->{ output } || q{} ) ;
  2314. return $mysync->{ output } ;
  2315. }
  2316. sub tests_output_start
  2317. {
  2318. note( 'Entering tests_output_start()' ) ;
  2319. my $mysync = { } ;
  2320. is( undef, output_start( ), 'output_start: no args => undef' ) ;
  2321. is( q{}, output_start( $mysync ), 'output_start: one arg => ""' ) ;
  2322. is( 'rrrr', output_start( $mysync, 'rrrr' ), 'output_start: rrrr => rrrr' ) ;
  2323. is( 'aaaarrrr', output_start( $mysync, 'aaaa' ), 'output_start: aaaa => aaaarrrr' ) ;
  2324. is( "\naaaarrrr", output_start( $mysync, "\n" ), 'output_start: \n => \naaaarrrr' ) ;
  2325. is( "ABC\naaaarrrr", output_start( $mysync, 'A', 'B', 'C' ), 'output_start: A B C => ABC\naaaarrrr' ) ;
  2326. note( 'Leaving tests_output_start()' ) ;
  2327. return ;
  2328. }
  2329. sub tests_output
  2330. {
  2331. note( 'Entering tests_output()' ) ;
  2332. my $mysync = { } ;
  2333. is( undef, output( ), 'output: no args => undef' ) ;
  2334. is( q{}, output( $mysync ), 'output: one arg => ""' ) ;
  2335. is( 'rrrr', output( $mysync, 'rrrr' ), 'output: rrrr => rrrr' ) ;
  2336. is( 'rrrraaaa', output( $mysync, 'aaaa' ), 'output: aaaa => rrrraaaa' ) ;
  2337. is( "rrrraaaa\n", output( $mysync, "\n" ), 'output: \n => rrrraaaa\n' ) ;
  2338. is( "rrrraaaa\nABC", output( $mysync, 'A', 'B', 'C' ), 'output: A B C => rrrraaaaABC\n' ) ;
  2339. note( 'Leaving tests_output()' ) ;
  2340. return ;
  2341. }
  2342. sub output
  2343. {
  2344. my $mysync = shift @ARG ;
  2345. if ( not $mysync ) { return ; }
  2346. my @output = @ARG ;
  2347. $mysync->{ output } .= join( q{}, @output ) ;
  2348. return $mysync->{ output } ;
  2349. }
  2350. sub tests_output_reset_with
  2351. {
  2352. note( 'Entering tests_output_reset_with()' ) ;
  2353. my $mysync = { } ;
  2354. is( undef, output_reset_with( ), 'output_reset_with: no args => undef' ) ;
  2355. is( q{}, output_reset_with( $mysync ), 'output_reset_with: one arg => ""' ) ;
  2356. is( 'rrrr', output_reset_with( $mysync, 'rrrr' ), 'output_reset_with: rrrr => rrrr' ) ;
  2357. is( 'aaaa', output_reset_with( $mysync, 'aaaa' ), 'output_reset_with: aaaa => aaaa' ) ;
  2358. is( "\n", output_reset_with( $mysync, "\n" ), 'output_reset_with: \n => \n' ) ;
  2359. note( 'Leaving tests_output_reset_with()' ) ;
  2360. return ;
  2361. }
  2362. sub output_reset_with
  2363. {
  2364. my $mysync = shift @ARG ;
  2365. if ( not $mysync ) { return ; }
  2366. my @output = @ARG ;
  2367. $mysync->{ output } = join( q{}, @output ) ;
  2368. return $mysync->{ output } ;
  2369. }
  2370. sub tests_print_output_if_needed
  2371. {
  2372. note( 'Entering tests_print_output_if_needed()' ) ;
  2373. is( undef, print_output_if_needed( ), 'print_output_if_needed: no args => undef' ) ;
  2374. my $mysync = { } ;
  2375. is( q{}, print_output_if_needed( $mysync ), 'print_output_if_needed: undef => undef' ) ;
  2376. output( $mysync, "Hello\n" ) ;
  2377. is( "Hello\n", print_output_if_needed( $mysync ), 'print_output_if_needed: Hello => Hello' ) ;
  2378. $mysync->{ dockercontext } = 1 ;
  2379. is( "Hello\n", print_output_if_needed( $mysync ), 'print_output_if_needed: dockercontext + Hello => Hello' ) ;
  2380. $mysync->{ version } = 1 ;
  2381. is( q{}, print_output_if_needed( $mysync ), 'print_output_if_needed: dockercontext + Hello + --version => ""' ) ;
  2382. $mysync->{ dockercontext } = 0 ;
  2383. is( "Hello\n", print_output_if_needed( $mysync ), 'print_output_if_needed: Hello + --version => Hello' ) ;
  2384. note( 'Leaving tests_print_output_if_needed()' ) ;
  2385. return ;
  2386. }
  2387. sub print_output_if_needed
  2388. {
  2389. my $mysync = shift @ARG ;
  2390. if ( ! defined $mysync ) { return ; }
  2391. my $output = output( $mysync ) ;
  2392. if ( $mysync->{ version } && under_docker_context( $mysync ) )
  2393. {
  2394. return q{} ;
  2395. }
  2396. else
  2397. {
  2398. myprint( $output ) ;
  2399. return $output ;
  2400. }
  2401. }
  2402. sub define_pidfile
  2403. {
  2404. my $mysync = shift @ARG ;
  2405. $mysync->{ pidfilelocking } = defined $mysync->{ pidfilelocking } ? $mysync->{ pidfilelocking } : 0 ;
  2406. my $host1 = $mysync->{ host1 } || q{} ;
  2407. my $user1 = $mysync->{ user1 } || q{} ;
  2408. my $host2 = $mysync->{ host2 } || q{} ;
  2409. my $user2 = $mysync->{ user2 } || q{} ;
  2410. my $account1_filtered = filter_forbidden_characters( slash_to_underscore( $host1 . '_' . $user1 ) ) || q{} ;
  2411. my $account2_filtered = filter_forbidden_characters( slash_to_underscore( $host2 . '_' . $user2 ) ) || q{} ;
  2412. my $pidfile_basename ;
  2413. if ( $ENV{ 'NET_SERVER_SOFTWARE' } and ( $ENV{ 'NET_SERVER_SOFTWARE' } =~ /Net::Server::HTTP/ ) )
  2414. {
  2415. # under local webserver
  2416. $pidfile_basename = 'imapsync' . '_' . $account1_filtered . '_' . $account2_filtered . '.pid' ;
  2417. }
  2418. else
  2419. {
  2420. $pidfile_basename = 'imapsync.pid' ;
  2421. }
  2422. $mysync->{ pidfile } = defined $mysync->{ pidfile } ? $mysync-> { pidfile } : $mysync->{ tmpdir } . "/$pidfile_basename" ;
  2423. $mysync->{ abortfile } = abortfile( $mysync, $PROCESS_ID ) ;
  2424. return ;
  2425. }
  2426. sub abortfile
  2427. {
  2428. my $mysync = shift @ARG ;
  2429. my $pid = shift @ARG ;
  2430. my $abortfile ;
  2431. if ( $mysync->{ abort } )
  2432. {
  2433. $abortfile = $mysync->{ pidfile } . "abort$pid" ;
  2434. }
  2435. else
  2436. {
  2437. $abortfile = $mysync->{ pidfile } . "abort$PROCESS_ID" ;
  2438. }
  2439. return $abortfile ;
  2440. }
  2441. sub tests_kill_zero
  2442. {
  2443. note( 'Entering tests_kill_zero()' ) ;
  2444. SKIP: {
  2445. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests tests_kill_zero avoided on Windows', 8 ) ; }
  2446. is( 1, kill( 'ZERO', $PROCESS_ID ), "kill ZERO : myself $PROCESS_ID => 1" ) ;
  2447. is( 2, kill( 'ZERO', $PROCESS_ID, $PROCESS_ID ), "kill ZERO : myself $PROCESS_ID $PROCESS_ID => 2" ) ;
  2448. if ( (-e '/.dockerenv' ) or ( 0 == $EFFECTIVE_USER_ID) )
  2449. {
  2450. is( 1, kill( 'ZERO', 1 ), "kill ZERO : pid 1 => 1 (docker context or root)" ) ;
  2451. is( 2, kill( 'ZERO', $PROCESS_ID, 1 ), "kill ZERO : myself + pid 1, $PROCESS_ID 1 => 2 (docker context or root)" ) ;
  2452. }
  2453. else
  2454. {
  2455. is( 0, kill( 'ZERO', 1 ), "kill ZERO : pid 1 => 0 (non root)" ) ;
  2456. is( 1, kill( 'ZERO', $PROCESS_ID, 1 ), "kill ZERO : myself + pid 1, $PROCESS_ID 1 => 1 (one is non root)" ) ;
  2457. }
  2458. my $pid_1 = fork( ) ;
  2459. if ( $pid_1 )
  2460. {
  2461. # parent
  2462. }
  2463. else
  2464. {
  2465. # child
  2466. sleep 3 ;
  2467. exit ;
  2468. }
  2469. my $pid_2 ;
  2470. $pid_2 = fork( ) ;
  2471. if ( $pid_2 )
  2472. {
  2473. # I am the parent
  2474. ok( defined( $pid_2 ), "kill_zero: initial fork ok. I am the parent $PROCESS_ID" ) ;
  2475. ok( $pid_2 , "kill_zero: initial fork ok, child pid is $pid_2" ) ;
  2476. is( 3, kill( 'ZERO', $PROCESS_ID, $pid_2, $pid_1 ), "kill ZERO : myself $PROCESS_ID and child $pid_2 and brother $pid_1 => 3" ) ;
  2477. is( $pid_2, waitpid( $pid_2, 0 ), "kill_zero: child $pid_2 no more there => waitpid return $pid_2" ) ;
  2478. }
  2479. else
  2480. {
  2481. # I am the child
  2482. note( 'This one fails under Windows, kill ZERO returns 0 instead of 2' ) ;
  2483. is( 2, kill( 'ZERO', $PROCESS_ID, $pid_1 ), "kill ZERO : myself child $PROCESS_ID brother $pid_1 => 2" ) ;
  2484. myprint( "I am the child pid $PROCESS_ID, Exiting\n" ) ;
  2485. exit ;
  2486. }
  2487. wait( ) ;
  2488. # End of SKIP block
  2489. }
  2490. note( 'Leaving tests_kill_zero()' ) ;
  2491. return ;
  2492. }
  2493. sub tests_killpid_by_parent
  2494. {
  2495. note( 'Entering tests_killpid_by_parent()' ) ;
  2496. SKIP: {
  2497. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests tests_killpid_by_parent avoided on Windows', 7 ) ; }
  2498. is( undef, killpid( ), 'killpid: no args => undef' ) ;
  2499. note( "killpid: trying to kill myself pid $PROCESS_ID, hope I will not succeed" ) ;
  2500. is( undef, killpid( $PROCESS_ID ), 'killpid: myself => undef' ) ;
  2501. local $SIG{'QUIT'} = sub { myprint "GOT SIG QUIT! I am PID $PROCESS_ID. Exiting\n" ; exit ; } ;
  2502. my $pid ;
  2503. $pid = fork( ) ;
  2504. if ( $pid )
  2505. {
  2506. # I am the parent
  2507. ok( defined( $pid ), "killpid: initial fork ok. I am the parent $PROCESS_ID" ) ;
  2508. ok( $pid , "killpid: initial fork ok, child pid is $pid" ) ;
  2509. is( 2, kill( 'ZERO', $PROCESS_ID, $pid ), "kill ZERO : myself $PROCESS_ID and child $pid => 2" ) ;
  2510. is( 1, killpid( $pid ), "killpid: child $pid killed => 1" ) ;
  2511. is( -1, waitpid( $pid, 0 ), "killpid: child $pid no more there => waitpid return -1" ) ;
  2512. }
  2513. else
  2514. {
  2515. # I am the child
  2516. myprint( "I am the child pid $PROCESS_ID, sleeping 1 + 3 seconds then kill myself\n" ) ;
  2517. sleep 1 ;
  2518. myprint( "I am the child pid $PROCESS_ID, slept 1 second, should be killed by my parent now, PPID " . mygetppid( ) . "\n" ) ;
  2519. sleep 3 ;
  2520. # this test should not be run. If it happens => failure.
  2521. ok( 0 == 1, "killpid: child pid $PROCESS_ID not dead => failure" ) ;
  2522. myprint( "I am the child pid $PROCESS_ID, killing myself failure... Exiting\n" ) ;
  2523. exit ;
  2524. }
  2525. # End of SKIP block
  2526. }
  2527. note( 'Leaving tests_killpid_by_parent()' ) ;
  2528. return ;
  2529. }
  2530. sub tests_killpid_by_brother
  2531. {
  2532. note( 'Entering tests_killpid_by_brother()' ) ;
  2533. SKIP: {
  2534. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests tests_killpid_by_brother avoided on Windows', 2 ) ; }
  2535. local $SIG{'QUIT'} = sub { myprint "GOT SIG QUIT! I am PID $PROCESS_ID. Exiting\n" ; exit ; } ;
  2536. my $pid_parent = $PROCESS_ID ;
  2537. myprint( "I am the parent pid $pid_parent\n" ) ;
  2538. my $pid_1 = fork( ) ;
  2539. if ( $pid_1 )
  2540. {
  2541. # parent
  2542. }
  2543. else
  2544. {
  2545. # child
  2546. #while ( 1 ) { } ;
  2547. sleep 2 ;
  2548. sleep 2 ;
  2549. # this test should not be run. If it happens => failure.
  2550. # Well under Windows this always fails, shit!
  2551. ok( 0 == 1 or ( 'MSWin32' eq $OSNAME ) , "killpid: child pid $PROCESS_ID killing by brother but not dead => failure" ) ;
  2552. myprint( "I am the child pid $PROCESS_ID, killing by brother failed... Exiting\n" ) ;
  2553. exit ;
  2554. }
  2555. my $pid_2 ;
  2556. $pid_2 = fork( ) ;
  2557. if ( $pid_2 )
  2558. {
  2559. # parent
  2560. }
  2561. else
  2562. {
  2563. # I am the child
  2564. myprint( "I am the child pid $PROCESS_ID, my brother has pid $pid_1\n" ) ;
  2565. is( 1, killpid( $pid_1 ), "killpid: brother $pid_1 killed => 1" ) ;
  2566. sleep 2 ;
  2567. exit ;
  2568. }
  2569. #sleep 1 ;
  2570. is( $pid_1, waitpid( $pid_1, 0), "I am the parent $PROCESS_ID waitpid _1( $pid_1 )" ) ;
  2571. is( $pid_2, waitpid( $pid_2, 0 ), "I am the parent $PROCESS_ID waitpid _2( $pid_2 )" ) ;
  2572. # End of SKIP block
  2573. }
  2574. note( 'Leaving tests_killpid_by_brother()' ) ;
  2575. return ;
  2576. }
  2577. sub killpid
  2578. {
  2579. my $pidtokill = shift ;
  2580. if ( ! $pidtokill ) {
  2581. myprint( "No process to kill.\n" ) ;
  2582. return ;
  2583. }
  2584. if ( $PROCESS_ID == $pidtokill ) {
  2585. myprint( "I will not kill myself pid $PROCESS_ID via killpid. Sractch it!\n" ) ;
  2586. return ;
  2587. }
  2588. # First ask for suicide
  2589. if ( kill( 'ZERO', $pidtokill ) or ( 'MSWin32' eq $OSNAME ) ) {
  2590. myprint( "Sending signal QUIT to PID $pidtokill \n" ) ;
  2591. kill 'QUIT', $pidtokill ;
  2592. sleep 3 ;
  2593. waitpid( $pidtokill, WNOHANG) ;
  2594. }else{
  2595. myprint( "Can not send signal kill ZERO to PID $pidtokill.\n" ) ;
  2596. return ;
  2597. }
  2598. #while ( waitpid( $pidtokill, WNOHANG) > 0 ) { } ;
  2599. # Then murder
  2600. if ( kill( 'ZERO', $pidtokill ) or ( 'MSWin32' eq $OSNAME ) ) {
  2601. myprint( "Sending signal KILL to PID $pidtokill \n" ) ;
  2602. kill 'KILL', $pidtokill ;
  2603. sleep 1 ;
  2604. waitpid( $pidtokill, WNOHANG) ;
  2605. }else{
  2606. myprint( "Process PID $pidtokill ended.\n" ) ;
  2607. return 1;
  2608. }
  2609. # Well ...
  2610. if ( kill( 'ZERO', $pidtokill ) or ( 'xMSWin32' eq $OSNAME ) ) {
  2611. myprint( "Process PID $pidtokill seems still there. Can not do much.\n" ) ;
  2612. return ;
  2613. }else{
  2614. myprint( "Process PID $pidtokill ended.\n" ) ;
  2615. return 1;
  2616. }
  2617. return ;
  2618. }
  2619. sub tests_abort
  2620. {
  2621. note( 'Entering tests_abort()' ) ;
  2622. # Well, the abort behavior is tested by test.sh
  2623. is( undef, abort( ), 'abort: no args => undef' ) ;
  2624. note( 'Leaving tests_abort()' ) ;
  2625. return ;
  2626. }
  2627. sub abort
  2628. {
  2629. my $mysync = shift @ARG ;
  2630. myprint( "In abort\n" ) ;
  2631. if ( not $mysync ) { return ; }
  2632. if ( ! -r $mysync->{pidfile} ) {
  2633. myprint( "In abort: Can not read pidfile $mysync->{pidfile}\n" ) ;
  2634. return ;
  2635. }
  2636. my $pidtokill = firstline( $mysync->{pidfile} ) ;
  2637. if ( ! $pidtokill ) {
  2638. myprint( "In abort: No process to abort in $mysync->{pidfile}\n" ) ;
  2639. return ;
  2640. }
  2641. if ( ! match_a_pid_number( $pidtokill ) )
  2642. {
  2643. myprint( "In abort: pid $pidtokill in $mysync->{pidfile} is not a pid number\n" ) ;
  2644. return ;
  2645. }
  2646. if ( $mysync->{abortbyfile} )
  2647. {
  2648. abortbyfile( $mysync, $pidtokill ) ;
  2649. }
  2650. else
  2651. {
  2652. killpid( $pidtokill ) ;
  2653. }
  2654. return ;
  2655. }
  2656. sub abortbyfile
  2657. {
  2658. my $mysync = shift @ARG ;
  2659. my $pidtokill = shift @ARG ;
  2660. my $abortfile = abortfile( $mysync, $pidtokill ) ;
  2661. myprint( "touching $abortfile\n" ) ;
  2662. touch( $abortfile ) ;
  2663. return ;
  2664. }
  2665. sub tests_under_docker_context
  2666. {
  2667. note( 'Entering tests_under_docker_context()' ) ;
  2668. is( undef, under_docker_context( ), 'under_docker_context: no args => undef' ) ;
  2669. my $mysync = { } ;
  2670. $mysync->{ dockercontext } = 1 ;
  2671. is( 1, under_docker_context( $mysync ), 'under_docker_context: --dockercontext => 1' ) ;
  2672. $mysync->{ dockercontext } = 0 ;
  2673. is( 0, under_docker_context( $mysync ), 'under_docker_context: --nodockercontext => 0' ) ;
  2674. $mysync = { } ;
  2675. # Is not it a stupid test?
  2676. if ( under_docker_context( $mysync ) )
  2677. {
  2678. is( 1, under_docker_context( $mysync ), 'under_docker_context: docker context => 1' ) ;
  2679. }
  2680. else
  2681. {
  2682. is( 0, under_docker_context( $mysync ), 'under_docker_context: not docker context => 0' ) ;
  2683. }
  2684. note( 'Leaving tests_under_docker_context()' ) ;
  2685. return ;
  2686. }
  2687. sub under_docker_context
  2688. {
  2689. my $mysync = shift ;
  2690. if ( ! defined $mysync ) { return ; }
  2691. if ( defined $mysync->{ dockercontext } )
  2692. {
  2693. return( $mysync->{ dockercontext } ) ;
  2694. }
  2695. if ( -e '/.dockerenv' )
  2696. {
  2697. return 1 ;
  2698. }
  2699. else
  2700. {
  2701. return 0 ;
  2702. }
  2703. return ;
  2704. }
  2705. sub docker_context
  2706. {
  2707. my $mysync = shift ;
  2708. if ( ! under_docker_context( $mysync ) )
  2709. {
  2710. return ;
  2711. }
  2712. output( $mysync, "Docker context detected with the file /.dockerenv\n" ) ;
  2713. # No pidfile by default
  2714. $mysync->{ pidfile } = defined( $mysync->{ pidfile } ) ? $mysync->{ pidfile } : q{} ;
  2715. # No log by default
  2716. if ( defined( $mysync->{ log } ) )
  2717. {
  2718. 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" ) ;
  2719. }
  2720. else
  2721. {
  2722. output( $mysync, "No log by default in Docker context. Use --log to trigger logging to the logfile.\n" ) ;
  2723. $mysync->{ log } = 0 ;
  2724. }
  2725. # In case something is written relatively to .
  2726. my $tmp_dir = "/var/tmp/uid_$EFFECTIVE_USER_ID" ;
  2727. mkpath( $tmp_dir ) ; # silly? No. it is for imapsync --version being ok.
  2728. do_valid_directory( $tmp_dir ) ;
  2729. output( $mysync, "Changing current directory to $tmp_dir\n" ) ;
  2730. chdir $tmp_dir ;
  2731. return ;
  2732. }
  2733. sub cgibegin
  2734. {
  2735. my $mysync = shift ;
  2736. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2737. require CGI ;
  2738. CGI->import( qw( -no_debug -utf8 ) ) ;
  2739. require CGI::Carp ;
  2740. CGI::Carp->import( qw( fatalsToBrowser ) ) ;
  2741. $mysync->{cgi} = CGI->new( ) ;
  2742. return ;
  2743. }
  2744. sub tests_under_cgi_context
  2745. {
  2746. note( 'Entering tests_under_cgi_context()' ) ;
  2747. # $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  2748. do {
  2749. # Not in cgi context
  2750. delete local $ENV{SERVER_SOFTWARE} ;
  2751. is( undef, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE unset => not in cgi context' ) ;
  2752. } ;
  2753. do {
  2754. # In cgi context
  2755. local $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  2756. is( 1, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE set => in cgi context' ) ;
  2757. } ;
  2758. do {
  2759. # Not in cgi context
  2760. delete local $ENV{SERVER_SOFTWARE} ;
  2761. is( undef, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE unset => not in cgi context' ) ;
  2762. } ;
  2763. do {
  2764. # In cgi context
  2765. local $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  2766. is( 1, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE set => in cgi context' ) ;
  2767. } ;
  2768. note( 'Leaving tests_under_cgi_context()' ) ;
  2769. return ;
  2770. }
  2771. sub under_cgi_context
  2772. {
  2773. my $mysync = shift ;
  2774. # Under cgi context
  2775. if ( $ENV{SERVER_SOFTWARE} ) {
  2776. return 1 ;
  2777. }
  2778. # Not in cgi context
  2779. return ;
  2780. }
  2781. sub cgibuildheader
  2782. {
  2783. my $mysync = shift ;
  2784. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2785. my $imapsync_runs = $mysync->{cgi}->cookie( 'imapsync_runs' ) || 0 ;
  2786. my $cookie = $mysync->{cgi}->cookie(
  2787. -name => 'imapsync_runs',
  2788. -value => 1 + $imapsync_runs,
  2789. -expires => '+20y',
  2790. -path => '/cgi-bin/imapsync',
  2791. ) ;
  2792. my $httpheader ;
  2793. if ( $mysync->{ abort } ) {
  2794. $httpheader = $mysync->{cgi}->header(
  2795. -type => 'text/plain; charset=UTF-8',
  2796. -status => '200 OK to abort syncing IMAP boxes' . ". Here is " . hostname(),
  2797. ) ;
  2798. }elsif( $mysync->{ loaddelay } ) {
  2799. # https://tools.ietf.org/html/rfc2616#section-10.5.4
  2800. # 503 Service Unavailable
  2801. # The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
  2802. $httpheader = $mysync->{cgi}->header(
  2803. -type => 'text/plain; charset=UTF-8',
  2804. -status => '503 Service Unavailable' . ". Be back in $mysync->{ loaddelay } min. Load on " . hostname() . " is $mysync->{ loadavg }",
  2805. ) ;
  2806. }else{
  2807. $httpheader = $mysync->{cgi}->header(
  2808. -type => 'text/plain; charset=UTF-8',
  2809. -status => '200 OK to sync IMAP boxes' . ". Load on " . hostname() . " is $mysync->{ loadavg }",
  2810. -cookie => $cookie,
  2811. ) ;
  2812. }
  2813. output_start( $mysync, $httpheader ) ;
  2814. return ;
  2815. }
  2816. sub cgiload
  2817. {
  2818. # Exit on heavy load in CGI context
  2819. my $mysync = shift ;
  2820. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2821. if ( $mysync->{ abort } ) { return ; } # keep going to abort since some ressources will be free soon
  2822. if ( $mysync->{ loaddelay } )
  2823. {
  2824. $mysync->{nb_errors}++ ;
  2825. exit_clean( $mysync, $EX_UNAVAILABLE,
  2826. "Server is on heavy load. Be back in $mysync->{ loaddelay } min. Load is $mysync->{ loadavg }\n"
  2827. ) ;
  2828. }
  2829. return ;
  2830. }
  2831. sub tests_set_umask
  2832. {
  2833. note( 'Entering tests_set_umask()' ) ;
  2834. my $save_umask = umask ;
  2835. my $mysync = {} ;
  2836. if ( 'MSWin32' eq $OSNAME ) {
  2837. is( undef, set_umask( $mysync ), "set_umask: set failure to $UMASK_PARANO on MSWin32" ) ;
  2838. }else{
  2839. is( 1, set_umask( $mysync ), "set_umask: set to $UMASK_PARANO" ) ;
  2840. }
  2841. umask $save_umask ;
  2842. note( 'Leaving tests_set_umask()' ) ;
  2843. return ;
  2844. }
  2845. sub set_umask
  2846. {
  2847. my $mysync = shift ;
  2848. my $previous_umask = umask_str( ) ;
  2849. my $new_umask = umask_str( $UMASK_PARANO ) ;
  2850. output( $mysync, "Umask set with $new_umask (was $previous_umask)\n" ) ;
  2851. if ( $new_umask eq $UMASK_PARANO ) {
  2852. return 1 ;
  2853. }
  2854. return ;
  2855. }
  2856. sub tests_umask_str
  2857. {
  2858. note( 'Entering tests_umask_str()' ) ;
  2859. my $save_umask = umask ;
  2860. is( umask_str( ), umask_str( ), 'umask_str: no parameters => idopotent' ) ;
  2861. is( my $save_umask_str = umask_str( ), umask_str( ), 'umask_str: no parameters => idopotent + save' ) ;
  2862. is( '0000', umask_str( q{ } ), 'umask_str: q{ } => 0000' ) ;
  2863. is( '0000', umask_str( q{} ), 'umask_str: q{} => 0000' ) ;
  2864. is( '0000', umask_str( '0000' ), 'umask_str: 0000 => 0000' ) ;
  2865. is( '0000', umask_str( '0' ), 'umask_str: 0 => 0000' ) ;
  2866. is( '0200', umask_str( '0200' ), 'umask_str: 0200 => 0200' ) ;
  2867. is( '0400', umask_str( '0400' ), 'umask_str: 0400 => 0400' ) ;
  2868. is( '0600', umask_str( '0600' ), 'umask_str: 0600 => 0600' ) ;
  2869. SKIP: {
  2870. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests success only for Unix', 6 ) ; }
  2871. is( '0100', umask_str( '0100' ), 'umask_str: 0100 => 0100' ) ;
  2872. is( '0001', umask_str( '0001' ), 'umask_str: 0001 => 0001' ) ;
  2873. is( '0777', umask_str( '0777' ), 'umask_str: 0777 => 0777' ) ;
  2874. is( '0777', umask_str( '00777' ), 'umask_str: 00777 => 0777' ) ;
  2875. is( '0777', umask_str( ' 777 ' ), 'umask_str: 777 => 0777' ) ;
  2876. is( "$UMASK_PARANO", umask_str( $UMASK_PARANO ), "umask_str: UMASK_PARANO $UMASK_PARANO => $UMASK_PARANO" ) ;
  2877. }
  2878. is( $save_umask_str, umask_str( $save_umask_str ), 'umask_str: restore with str' ) ;
  2879. is( $save_umask, umask, 'umask_str: umask is restored, controlled by direct umask' ) ;
  2880. is( $save_umask, umask $save_umask, 'umask_str: umask is restored by direct umask' ) ;
  2881. is( $save_umask, umask, 'umask_str: umask initial controlled by direct umask' ) ;
  2882. note( 'Leaving tests_umask_str()' ) ;
  2883. return ;
  2884. }
  2885. sub umask_str
  2886. {
  2887. my $value = shift ;
  2888. if ( defined $value ) {
  2889. umask oct( $value ) ;
  2890. }
  2891. my $current = umask ;
  2892. return( sprintf( '%#04o', $current ) ) ;
  2893. }
  2894. sub tests_umask
  2895. {
  2896. note( 'Entering tests_umask()' ) ;
  2897. my $save_umask ;
  2898. is( umask, umask, 'umask: umask is umask' ) ;
  2899. is( $save_umask = umask, umask, "umask: umask is umask again + save it: $save_umask" ) ;
  2900. is( $save_umask, umask oct(0000), 'umask: umask 0000' ) ;
  2901. is( oct(0000), umask, 'umask: umask is now 0000' ) ;
  2902. is( oct(0000), umask oct(777), 'umask: umask 0777 call, previous 0000' ) ;
  2903. SKIP: {
  2904. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests success only for Unix', 2 ) ; }
  2905. is( oct(777), umask, 'umask: umask is now 0777' ) ;
  2906. is( oct(777), umask $save_umask, "umask: umask $save_umask restore inital value, previous 0777" ) ;
  2907. }
  2908. ok( defined umask $save_umask, "umask: umask $save_umask restore inital value, previous defined" ) ;
  2909. is( $save_umask, umask, 'umask: umask is umask restored' ) ;
  2910. note( 'Leaving tests_umask()' ) ;
  2911. return ;
  2912. }
  2913. sub buggyflagsregex
  2914. {
  2915. # From /X analyse
  2916. # cut -d: -f1 Error_112_all_syncs.txt | xargs egrep -oih 'Invalid system flag [^( ]+' | sort | uniq -c | sort -g
  2917. my @buggyflagsregex = ( 's/\\\\RECEIPTCHECKED|\\\\Indexed|\\\\X-EON-HAS-ATTACHMENT|\\\\UNSEEN|\\\\ATTACHED|\\\\X-HAS-ATTACH|\\\\FORWARDED|\\\\FORWARD|\\\\X-FORWARDED|\\\\\$FORWARDED|\\\\PRIORITY|\\\\READRCPT//g' ) ;
  2918. return( @buggyflagsregex ) ;
  2919. }
  2920. sub cgisetcontext
  2921. {
  2922. my $mysync = shift ;
  2923. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2924. output( $mysync, "Under cgi context\n" ) ;
  2925. set_umask( $mysync ) ;
  2926. # Remove all content in unsafe evaled options
  2927. @{ $mysync->{ regextrans2 } } = ( ) ;
  2928. @{ $mysync->{ regexflag } } = buggyflagsregex( ) ;
  2929. @regexmess = ( ) ;
  2930. @skipmess = ( ) ;
  2931. @pipemess = ( ) ;
  2932. $delete2foldersonly = undef ;
  2933. $delete2foldersbutnot = undef ;
  2934. $maxlinelengthcmd = undef ;
  2935. # Set safe default values (I hope...)
  2936. #$mysync->{pidfile} = 'imapsync.pid' ;
  2937. $mysync->{ pidfilelocking } = 1 ;
  2938. $mysync->{ errorsmax } = $ERRORS_MAX_CGI ;
  2939. $modulesversion = 0 ;
  2940. $mysync->{ releasecheck } = defined $mysync->{ releasecheck } ? $mysync->{ releasecheck } : 1 ;
  2941. $usecache = 0 ;
  2942. $mysync->{ showpasswords } = 0 ;
  2943. $mysync->{ acc1 }->{ debugimap } = 0 ;
  2944. $mysync->{ acc2 }->{ debugimap } = 0 ;
  2945. $mysync->{ acc1 }->{ reconnectretry } = $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  2946. $mysync->{ acc2 }->{ reconnectretry } = $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  2947. $pipemesscheck = 0 ;
  2948. $mysync->{ hashfile } = $CGI_HASHFILE ;
  2949. my $hashsynclocal = hashsynclocal( $mysync ) || die "Can not get hashsynclocal. Exiting\n" ;
  2950. if ( $ENV{ 'NET_SERVER_SOFTWARE' } and ( $ENV{ 'NET_SERVER_SOFTWARE' } =~ /Net::Server::HTTP/ ) )
  2951. {
  2952. # under local webserver
  2953. $cgidir = q{.} ;
  2954. }
  2955. else
  2956. {
  2957. $cgidir = $CGI_TMPDIR_TOP . '/' . $hashsynclocal ;
  2958. }
  2959. -d $cgidir or mkpath $cgidir or die "Can not create $cgidir: $OS_ERROR\n" ;
  2960. $mysync->{ tmpdir } = $cgidir ;
  2961. $mysync->{ logdir } = '' ;
  2962. chdir $cgidir or die "Can not cd to $cgidir: $OS_ERROR\n" ;
  2963. cgioutputenvcontext( $mysync ) ;
  2964. $mysync->{ debug } and output( $mysync, 'Current directory is ' . getcwd( ) . "\n" ) ;
  2965. $mysync->{ debug } and output( $mysync, 'Real user id is ' . getpwuid_any_os( $REAL_USER_ID ) . " (uid $REAL_USER_ID)\n" ) ;
  2966. $mysync->{ debug } and output( $mysync, 'Effective user id is ' . getpwuid_any_os( $EFFECTIVE_USER_ID ). " (euid $EFFECTIVE_USER_ID)\n" ) ;
  2967. $mysync->{ skipemptyfolders } = defined $mysync->{ skipemptyfolders } ? $mysync->{ skipemptyfolders } : 1 ;
  2968. # Out of memory with messages over 1 GB ?
  2969. $mysync->{ maxsize } = defined $mysync->{ maxsize } ? $mysync->{ maxsize } : 1_000_000_000 ;
  2970. # tail -f behaviour on by default
  2971. $mysync->{ tail } = defined $mysync->{ tail } ? $mysync->{ tail } : 1 ;
  2972. # not sure it's for good
  2973. @useheader = qw( Message-Id Received ) ;
  2974. # addheader on by default
  2975. $mysync->{ addheader } = defined $mysync->{ addheader } ? $mysync->{ addheader } : 1 ;
  2976. # sync duplicates by default in cgi context
  2977. $mysync->{ syncduplicates } = defined $mysync->{ syncduplicates } ? $mysync->{ syncduplicates } : 1 ;
  2978. # log the logfile name by default in cgi context
  2979. $mysync->{ loglogfile } = defined $mysync->{ loglogfile } ? $mysync->{ loglogfile } : 1 ;
  2980. return ;
  2981. }
  2982. sub cgioutputenvcontext
  2983. {
  2984. my $mysync = shift @ARG ;
  2985. for my $envvar ( qw( REMOTE_ADDR REMOTE_HOST HTTP_REFERER HTTP_USER_AGENT SERVER_SOFTWARE SERVER_PORT HTTP_COOKIE ) ) {
  2986. my $envval = $ENV{ $envvar } || q{} ;
  2987. if ( $envval ) { output( $mysync, "$envvar is $envval\n" ) } ;
  2988. }
  2989. return ;
  2990. }
  2991. sub announcelogfile
  2992. {
  2993. my $mysync = shift ;
  2994. if ( $mysync->{ log } )
  2995. {
  2996. myprint( "Log file is $mysync->{ logfile } ( to change it, use --logfile path ; or use --nolog to turn off logging )\n" ) ;
  2997. loglogfile( $mysync ) ;
  2998. }
  2999. else
  3000. {
  3001. myprint( "No log file because of option --nolog\n" ) ;
  3002. }
  3003. return ;
  3004. }
  3005. sub loglogfile
  3006. {
  3007. my $mysync = shift ;
  3008. if ( ! $mysync->{ loglogfile } ) { return ; }
  3009. if ( ! $mysync->{ log } ) { return ; }
  3010. my $cwd = getcwd( ) ;
  3011. my $absolutelogfilepath ;
  3012. # Fixme: add case when the logfile name is already absolute
  3013. $absolutelogfilepath = "$cwd/$mysync->{ logfile }" ;
  3014. my $loglogfilename = '../list_all_logs_auto.txt' ;
  3015. myprint( "Writing log file name $absolutelogfilepath to $loglogfilename\n" ) ;
  3016. if ( open( my $fh, '>>', $loglogfilename ) )
  3017. {
  3018. print $fh "$absolutelogfilepath\n" ;
  3019. close $fh ;
  3020. }
  3021. else
  3022. {
  3023. myprint( "Could not open loglogfile $loglogfilename $!\n" ) ;
  3024. }
  3025. return ;
  3026. }
  3027. sub checkselectable
  3028. {
  3029. my $mysync = shift ;
  3030. if ( $mysync->{ checkselectable } ) {
  3031. my @h1_folders_wanted_selectable ;
  3032. myprint( "Host1: Checking wanted folders are selectable. Use --nocheckselectable to avoid this check.\n" ) ;
  3033. foreach my $folder ( @{ $mysync->{ h1_folders_wanted } } )
  3034. {
  3035. ( $mysync->{ debug } or $mysync->{ debugfolders } ) and myprint( "Checking $folder is selectable on host1\n" ) ;
  3036. # It does an imap command LIST "" $folder and then search for no \Noselect
  3037. if ( ! $mysync->{ imap1 }->selectable( $folder ) )
  3038. {
  3039. myprint( "Host1: warning! ignoring folder $folder because it is not selectable\n" ) ;
  3040. }else
  3041. {
  3042. push @h1_folders_wanted_selectable, $folder ;
  3043. }
  3044. }
  3045. @{ $mysync->{ h1_folders_wanted } } = @h1_folders_wanted_selectable ;
  3046. ( $mysync->{ debug } or $mysync->{ debugfolders } )
  3047. and myprint( 'Host1: checking folders took ', timenext( $mysync ), " s\n" ) ;
  3048. }
  3049. else
  3050. {
  3051. myprint( "Host1: Not checking that wanted folders are selectable. Use --checkselectable to force this check.\n" ) ;
  3052. }
  3053. return ;
  3054. }
  3055. sub setcheckselectable
  3056. {
  3057. my $mysync = shift ;
  3058. my $h1_folders_wanted_nb = scalar @{ $mysync->{ h1_folders_wanted } } ;
  3059. # 152 because 98% of host1 accounts have less than 152 folders on /X service.
  3060. # command to get this value:
  3061. # datamash_file_op_index G_Host1_Nb_folders.txt perc:98 4 %16.1f
  3062. if ( ! defined $mysync->{ checkselectable } )
  3063. {
  3064. if ( 152 >= $h1_folders_wanted_nb )
  3065. {
  3066. $mysync->{ checkselectable } = 1 ;
  3067. }else{
  3068. myprint( "Host1: Not checking that $h1_folders_wanted_nb wanted folders are selectable. Use --checkselectable to force this check.\n" ) ;
  3069. $mysync->{ checkselectable } = 0 ;
  3070. }
  3071. }
  3072. return ;
  3073. }
  3074. sub debugsleep
  3075. {
  3076. my $mysync = shift @ARG ;
  3077. if ( defined $mysync->{debugsleep} ) {
  3078. myprint( "Info: sleeping $mysync->{debugsleep}s\n" ) ;
  3079. sleep $mysync->{debugsleep} ;
  3080. }
  3081. return ;
  3082. }
  3083. sub tests_foldersize
  3084. {
  3085. note( 'Entering tests_foldersize()' ) ;
  3086. is( undef, foldersize( ), 'foldersize: no args => undef' ) ;
  3087. #is_deeply( {}, {}, 'foldersize: a hash is a hash' ) ;
  3088. #is_deeply( [], [], 'foldersize: an array is an array' ) ;
  3089. note( 'Leaving tests_foldersize()' ) ;
  3090. return ;
  3091. }
  3092. # Globals:
  3093. # $fetch_hash_set
  3094. #
  3095. sub foldersize
  3096. {
  3097. # size of one folder
  3098. my ( $mysync, $side, $imap, $search_cmd, $abletosearch, $folder ) = @ARG ;
  3099. if ( ! all_defined( $mysync, $side, $imap, $folder ) )
  3100. {
  3101. return ;
  3102. }
  3103. # FTGate is RFC buggy with EXAMINE it does not act as SELECT
  3104. #if ( ! $imap->examine( $folder ) ) {
  3105. if ( ! $imap->select( $folder ) ) {
  3106. my $error = join q{},
  3107. "$side Folder $folder: Could not select: ",
  3108. $imap->LastError, "\n" ;
  3109. errors_incr( $mysync, $error ) ;
  3110. return ;
  3111. }
  3112. if ( $imap->IsUnconnected( ) )
  3113. {
  3114. return ;
  3115. }
  3116. my $hash_ref = { } ;
  3117. my @msgs = select_msgs( $imap, undef, $search_cmd, $abletosearch, $folder ) ;
  3118. my $nb_msgs = scalar @msgs ;
  3119. my $biggest_in_folder = 0 ;
  3120. @{ $hash_ref }{ @msgs } = ( undef ) if @msgs ;
  3121. my $stot = 0 ;
  3122. if ( $imap->IsUnconnected( ) )
  3123. {
  3124. return ;
  3125. }
  3126. if ( $nb_msgs > 0 and @msgs ) {
  3127. if ( $abletosearch ) {
  3128. if ( ! $imap->fetch_hash( \@msgs, 'RFC822.SIZE', $hash_ref) ) {
  3129. my $error = "$side failure with fetch_hash: $EVAL_ERROR\n" ;
  3130. errors_incr( $mysync, $error ) ;
  3131. return ;
  3132. }
  3133. }
  3134. else
  3135. {
  3136. my $fetch_hash_uids = $fetch_hash_set || "1:*" ;
  3137. if ( ! $imap->fetch_hash( $fetch_hash_uids, 'RFC822.SIZE', $hash_ref ) ) {
  3138. my $error = "$side failure with fetch_hash: $EVAL_ERROR\n" ;
  3139. errors_incr( $mysync, $error ) ;
  3140. return ;
  3141. }
  3142. }
  3143. for ( keys %{ $hash_ref } ) {
  3144. my $size = $hash_ref->{ $_ }->{ 'RFC822.SIZE' } ;
  3145. if ( defined $size )
  3146. {
  3147. $stot += $size ;
  3148. $biggest_in_folder = max( $biggest_in_folder, $size ) ;
  3149. }
  3150. }
  3151. }
  3152. return( $stot, $nb_msgs, $biggest_in_folder ) ;
  3153. }
  3154. # The old subroutine that performed just one side at a time.
  3155. # Still here for a while, until confident with sub foldersize_diff_compute()
  3156. sub foldersizes
  3157. {
  3158. my ( $mysync, $side, $imap, $search_cmd, $abletosearch, @folders ) = @_ ;
  3159. my $total_size = 0 ;
  3160. my $total_nb = 0 ;
  3161. my $biggest_in_all = 0 ;
  3162. my $nb_folders = scalar @folders ;
  3163. my $ct_folders = 0 ; # folder counter.
  3164. myprint( "++++ Calculating sizes of $nb_folders folders on $side\n" ) ;
  3165. foreach my $folder ( @folders ) {
  3166. my $stot = 0 ;
  3167. my $nb_msgs = 0 ;
  3168. my $biggest_in_folder = 0 ;
  3169. $ct_folders++ ;
  3170. myprintf( "$side folder %7s %-35s", "$ct_folders/$nb_folders", jux_utf8( $folder ) ) ;
  3171. if ( 'Host2' eq $side and not exists $mysync->{h2_folders_all_UPPER}{ uc $folder } ) {
  3172. myprint( " does not exist yet\n") ;
  3173. next ;
  3174. }
  3175. if ( 'Host1' eq $side and not exists $h1_folders_all{ $folder } ) {
  3176. myprint( " does not exist\n" ) ;
  3177. next ;
  3178. }
  3179. last if $imap->IsUnconnected( ) ;
  3180. ( $stot, $nb_msgs, $biggest_in_folder ) = foldersize( $mysync, $side, $imap, $search_cmd, $abletosearch, $folder ) ;
  3181. myprintf( ' Size: %9s', $stot ) ;
  3182. myprintf( ' Messages: %5s', $nb_msgs ) ;
  3183. myprintf( " Biggest: %9s\n", $biggest_in_folder ) ;
  3184. $total_size += $stot ;
  3185. $total_nb += $nb_msgs ;
  3186. $biggest_in_all = max( $biggest_in_all, $biggest_in_folder ) ;
  3187. }
  3188. myprintf( "%s Nb folders: %11s folders\n", $side, $nb_folders ) ;
  3189. myprintf( "%s Nb messages: %11s messages\n", $side, $total_nb ) ;
  3190. myprintf( "%s Total size: %11s bytes (%s)\n", $side, $total_size, bytes_display_string_bin( $total_size ) ) ;
  3191. myprintf( "%s Biggest message: %11s bytes (%s)\n", $side, $biggest_in_all, bytes_display_string_bin( $biggest_in_all ) ) ;
  3192. myprintf( "%s Time spent on sizing: %11.1f seconds\n", $side, timenext( $mysync ) ) ;
  3193. return( $total_nb, $total_size ) ;
  3194. }
  3195. sub foldersize_diff_present
  3196. {
  3197. my $mysync = shift ;
  3198. my $folder1 = shift ;
  3199. my $folder2 = shift ;
  3200. my $counter_str = shift ;
  3201. my $force = shift ;
  3202. my $values1_str ;
  3203. my $values2_str ;
  3204. if ( ! defined $mysync->{ folder1 }->{ $folder1 }->{ size } || $force )
  3205. {
  3206. foldersize_diff_compute( $mysync, $folder1, $folder2, $force ) ;
  3207. }
  3208. # again, but this time it means no availaible data.
  3209. if ( defined $mysync->{ folder1 }->{ $folder1 }->{ size } )
  3210. {
  3211. $values1_str = sprintf( "Size: %9s Messages: %5s Biggest: %9s\n",
  3212. $mysync->{ folder1 }->{ $folder1 }->{ size },
  3213. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs },
  3214. $mysync->{ folder1 }->{ $folder1 }->{ biggest },
  3215. ) ;
  3216. }
  3217. else
  3218. {
  3219. $values1_str = " does not exist\n" ;
  3220. }
  3221. if ( defined $mysync->{ folder2 }->{ $folder2 }->{ size } )
  3222. {
  3223. $values2_str = sprintf( "Size: %9s Messages: %5s Biggest: %9s\n",
  3224. $mysync->{ folder2 }->{ $folder2 }->{ size },
  3225. $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs },
  3226. $mysync->{ folder2 }->{ $folder2 }->{ biggest },
  3227. ) ;
  3228. }
  3229. else
  3230. {
  3231. $values2_str = " does not exist yet\n" ;
  3232. }
  3233. myprintf( "Host1 folder %7s %-35s %s",
  3234. "$counter_str",
  3235. jux_utf8( $folder1 ),
  3236. $values1_str
  3237. ) ;
  3238. myprintf( "Host2 folder %7s %-35s %s",
  3239. "$counter_str",
  3240. jux_utf8( $folder2 ),
  3241. $values2_str
  3242. ) ;
  3243. myprintf( "Host2-Host1 %7s %-35s %9s %5s %9s\n\n",
  3244. "",
  3245. "",
  3246. $mysync->{ folder1 }->{ $folder1 }->{ size_diff },
  3247. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs_diff },
  3248. $mysync->{ folder1 }->{ $folder1 }->{ biggest_diff },
  3249. ) ;
  3250. return ;
  3251. }
  3252. sub foldersize_diff_compute
  3253. {
  3254. my $mysync = shift ;
  3255. my $folder1 = shift ;
  3256. my $folder2 = shift ;
  3257. my $force = shift ;
  3258. my ( $size_1, $nb_msgs_1, $biggest_1 ) ;
  3259. # memoization
  3260. if (
  3261. exists $h1_folders_all{ $folder1 }
  3262. &&
  3263. (
  3264. ! defined $mysync->{ folder1 }->{ $folder1 }->{ size }
  3265. || $force
  3266. )
  3267. )
  3268. {
  3269. #myprint( "foldersize folder1 $h1_folders_all{ $folder1 }\n" ) ;
  3270. ( $size_1, $nb_msgs_1, $biggest_1 ) =
  3271. foldersize( $mysync,
  3272. 'Host1',
  3273. $mysync->{ imap1 },
  3274. $mysync->{ search1 },
  3275. $mysync->{ abletosearch1 },
  3276. $folder1
  3277. ) ;
  3278. $mysync->{ folder1 }->{ $folder1 }->{ size } = $size_1 ;
  3279. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs } = $nb_msgs_1 ;
  3280. $mysync->{ folder1 }->{ $folder1 }->{ biggest } = $biggest_1 ;
  3281. }
  3282. else
  3283. {
  3284. $size_1 = $mysync->{ folder1 }->{ $folder1 }->{ size } ;
  3285. $nb_msgs_1 = $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs } ;
  3286. $biggest_1 = $mysync->{ folder1 }->{ $folder1 }->{ biggest } ;
  3287. }
  3288. my ( $size_2, $nb_msgs_2, $biggest_2 ) ;
  3289. if (
  3290. exists $mysync->{ h2_folders_all_UPPER }{ uc $folder2 }
  3291. &&
  3292. (
  3293. ! defined $mysync->{ folder2 }->{ $folder2 }->{ size }
  3294. || $force
  3295. )
  3296. )
  3297. {
  3298. #myprint( "foldersize folder2\n" ) ;
  3299. ( $size_2, $nb_msgs_2, $biggest_2 ) =
  3300. foldersize( $mysync,
  3301. 'Host2',
  3302. $mysync->{ imap2 },
  3303. $mysync->{ search2 },
  3304. $mysync->{ abletosearch2 },
  3305. $folder2
  3306. ) ;
  3307. $mysync->{ folder2 }->{ $folder2 }->{ size } = $size_2 ;
  3308. $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs } = $nb_msgs_2 ;
  3309. $mysync->{ folder2 }->{ $folder2 }->{ biggest } = $biggest_2 ;
  3310. }
  3311. else
  3312. {
  3313. $size_2 = $mysync->{ folder2 }->{ $folder2 }->{ size } ;
  3314. $nb_msgs_2 = $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs } ;
  3315. $biggest_2 = $mysync->{ folder2 }->{ $folder2 }->{ biggest } ;
  3316. }
  3317. my $size_diff = diff( $size_2, $size_1 ) ;
  3318. my $nb_msgs_diff = diff( $nb_msgs_2, $nb_msgs_1 ) ;
  3319. my $biggest_diff = diff( $biggest_2, $biggest_1 ) ;
  3320. $mysync->{ folder1 }->{ $folder1 }->{ size_diff } = $size_diff ;
  3321. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs_diff } = $nb_msgs_diff ;
  3322. $mysync->{ folder1 }->{ $folder1 }->{ biggest_diff } = $biggest_diff ;
  3323. # It's redundant but easier to access later
  3324. $mysync->{ folder2 }->{ $folder2 }->{ size_diff } = $size_diff ;
  3325. $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs_diff } = $nb_msgs_diff ;
  3326. $mysync->{ folder2 }->{ $folder2 }->{ biggest_diff } = $biggest_diff ;
  3327. return ;
  3328. }
  3329. sub diff
  3330. {
  3331. my $x = shift ;
  3332. my $y = shift ;
  3333. $x ||= 0 ;
  3334. $y ||= 0 ;
  3335. return $x - $y ;
  3336. }
  3337. sub add
  3338. {
  3339. my $x = shift ;
  3340. my $y = shift ;
  3341. $x ||= 0 ;
  3342. $y ||= 0 ;
  3343. return $x + $y ;
  3344. }
  3345. sub tests_checknoabletosearch
  3346. {
  3347. note( 'Entering checknoabletosearch()' ) ;
  3348. is( undef, checknoabletosearch( ), 'checknoabletosearch: no args => undef' ) ;
  3349. note( 'Leaving checknoabletosearch()' ) ;
  3350. return ;
  3351. }
  3352. sub checknoabletosearch
  3353. {
  3354. # call example: checknoabletosearch( $sync, $sync->{ imap1 }, 'INBOX', 'Host1' ) ;
  3355. # output:
  3356. # * undef if something is not ok to decide
  3357. # * 1 if SEARCH ALL failed
  3358. my( $mysync, $imap, $folder, $HostX ) = @ARG ;
  3359. if ( ! all_defined( $mysync, $imap, $folder, $HostX ) )
  3360. {
  3361. return ;
  3362. }
  3363. myprint( "$HostX: checking if SEARCH ALL works on $folder\n" ) ;
  3364. if ( ! select_folder( $mysync, $imap, $folder, $HostX ) )
  3365. {
  3366. myprint( "$HostX: can not SELECT folder [$folder]\n" ) ;
  3367. return ;
  3368. }
  3369. my $count_from_select = count_from_select( $imap->History ) ;
  3370. myprint( "$HostX: folder [$folder] has $count_from_select messages mentioned by SELECT\n" ) ;
  3371. my $msgs_all = $imap->messages( ) ;
  3372. if ( ! $msgs_all )
  3373. {
  3374. myprint( "$HostX: can not SEARCH ALL folder [$folder]\n" ) ;
  3375. myprint( "$HostX: ", $imap->LastError(), "\n" ) ;
  3376. return 1 ;
  3377. }
  3378. my $count_from_search_all = scalar( @{ $msgs_all } ) ;
  3379. myprint( "$HostX: folder [$folder] has $count_from_search_all messages found by SEARCH ALL\n" ) ;
  3380. if ( $count_from_select == $count_from_search_all )
  3381. {
  3382. myprint( "$HostX: folder [$folder] has the same messages count ($count_from_select) by SELECT and SEARCH ALL\n" ) ;
  3383. }
  3384. else
  3385. {
  3386. myprint( "$HostX: Warning, folder [$folder] has not the same count by SELECT ($count_from_select) and SEARCH ALL ($count_from_search_all)\n" ) ;
  3387. return 1 ;
  3388. }
  3389. return ;
  3390. }
  3391. sub foldersizes_diff_list
  3392. {
  3393. my $mysync = shift ;
  3394. my $force = shift ;
  3395. my @folders = @{ $mysync->{h1_folders_wanted} } ;
  3396. my $nb_folders = scalar @folders ;
  3397. my $ct_folders = 0 ; # folder counter.
  3398. foreach my $folder1 ( @folders )
  3399. {
  3400. $ct_folders++ ;
  3401. my $counter_str = "$ct_folders/$nb_folders" ;
  3402. my $folder2 = imap2_folder_name( $mysync, $folder1 ) ;
  3403. foldersize_diff_present( $mysync, $folder1, $folder2, $counter_str, $force ) ;
  3404. }
  3405. return ;
  3406. }
  3407. sub foldersizes_total
  3408. {
  3409. my $mysync = shift ;
  3410. my @folders_1 = @{ $mysync->{h1_folders_wanted} } ;
  3411. my @folders_2 = @h2_folders_from_1_wanted ;
  3412. my $nb_folders_1 = scalar( @folders_1 ) ;
  3413. my $nb_folders_2 = scalar( @folders_2 ) ;
  3414. my ( $total_size_1, $total_nb_1, $biggest_in_all_1 ) = ( 0, 0, 0 ) ;
  3415. my ( $total_size_2, $total_nb_2, $biggest_in_all_2 ) = ( 0, 0, 0 ) ;
  3416. foreach my $folder1 ( @folders_1 )
  3417. {
  3418. $total_size_1 = add( $total_size_1, $mysync->{ folder1 }->{ $folder1 }->{ size } ) ;
  3419. $total_nb_1 = add( $total_nb_1, $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs } ) ;
  3420. $biggest_in_all_1 = max( $biggest_in_all_1 , $mysync->{ folder1 }->{ $folder1 }->{ biggest } ) ;
  3421. }
  3422. foreach my $folder2 ( @folders_2 )
  3423. {
  3424. $total_size_2 = add( $total_size_2, $mysync->{ folder2 }->{ $folder2 }->{ size } ) ;
  3425. $total_nb_2 = add( $total_nb_2, $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs } ) ;
  3426. $biggest_in_all_2 = max( $biggest_in_all_2 , $mysync->{ folder2 }->{ $folder2 }->{ biggest } ) ;
  3427. }
  3428. myprintf( "Host1 Nb folders: %11s folders\n", $nb_folders_1 ) ;
  3429. myprintf( "Host2 Nb folders: %11s folders\n", $nb_folders_2 ) ;
  3430. myprint( "\n" ) ;
  3431. myprintf( "Host1 Nb messages: %11s messages\n", $total_nb_1 ) ;
  3432. myprintf( "Host2 Nb messages: %11s messages\n", $total_nb_2 ) ;
  3433. myprint( "\n" ) ;
  3434. myprintf( "Host1 Total size: %11s bytes (%s)\n", $total_size_1, bytes_display_string_bin( $total_size_1 ) ) ;
  3435. myprintf( "Host2 Total size: %11s bytes (%s)\n", $total_size_2, bytes_display_string_bin( $total_size_2 ) ) ;
  3436. myprint( "\n" ) ;
  3437. myprintf( "Host1 Biggest message: %11s bytes (%s)\n", $biggest_in_all_1, bytes_display_string_bin( $biggest_in_all_1 ) ) ;
  3438. myprintf( "Host2 Biggest message: %11s bytes (%s)\n", $biggest_in_all_2, bytes_display_string_bin( $biggest_in_all_2 ) ) ;
  3439. myprint( "\n" ) ;
  3440. myprintf( "Time spent on sizing: %11.1f seconds\n", timenext( $mysync ) ) ;
  3441. my @total_1_2 = ( $total_nb_1, $total_size_1, $total_nb_2, $total_size_2 ) ;
  3442. return @total_1_2 ;
  3443. }
  3444. sub foldersizesatend_old
  3445. {
  3446. my $mysync = shift ;
  3447. timenext( $mysync ) ;
  3448. return if ( $mysync->{imap1}->IsUnconnected( ) ) ;
  3449. return if ( $mysync->{imap2}->IsUnconnected( ) ) ;
  3450. # Get all folders on host2 again since new were created
  3451. @h2_folders_all = sort $mysync->{imap2}->folders();
  3452. for ( @h2_folders_all ) {
  3453. $h2_folders_all{ $_ } = 1 ;
  3454. $mysync->{h2_folders_all_UPPER}{ uc $_ } = 1 ;
  3455. } ;
  3456. ( $h1_nb_msg_end, $h1_bytes_end ) = foldersizes( $mysync, 'Host1', $mysync->{imap1}, $mysync->{ search1 }, $mysync->{abletosearch1}, @{ $mysync->{h1_folders_wanted} } ) ;
  3457. ( $h2_nb_msg_end, $h2_bytes_end ) = foldersizes( $mysync, 'Host2', $mysync->{imap2}, $mysync->{ search2 }, $mysync->{abletosearch2}, @h2_folders_from_1_wanted ) ;
  3458. if ( not all_defined( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end ) ) {
  3459. my $error = "Failure getting foldersizes, final differences will not be calculated\n" ;
  3460. errors_incr( $mysync, $error ) ;
  3461. }
  3462. return ;
  3463. }
  3464. sub foldersizesatend
  3465. {
  3466. my $mysync = shift ;
  3467. timenext( $mysync ) ;
  3468. return if ( $mysync->{imap1}->IsUnconnected( ) ) ;
  3469. return if ( $mysync->{imap2}->IsUnconnected( ) ) ;
  3470. # Get all folders on host2 again since new were created
  3471. @h2_folders_all = sort $mysync->{imap2}->folders();
  3472. for ( @h2_folders_all ) {
  3473. $h2_folders_all{ $_ } = 1 ;
  3474. $mysync->{h2_folders_all_UPPER}{ uc $_ } = 1 ;
  3475. } ;
  3476. foldersizes_diff_list( $mysync, $FORCE ) ;
  3477. ( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end )
  3478. = foldersizes_total( $mysync ) ;
  3479. if ( not all_defined( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end ) ) {
  3480. my $error = "Failure getting foldersizes, final differences will not be calculated\n" ;
  3481. errors_incr( $mysync, $error ) ;
  3482. }
  3483. return ;
  3484. }
  3485. sub foldersizes_at_the_beggining
  3486. {
  3487. my $mysync = shift ;
  3488. myprint( << 'END_SIZE' ) ;
  3489. Folders sizes before the synchronization.
  3490. You can remove foldersizes listings by using "--nofoldersizes" and "--nofoldersizesatend"
  3491. but then you will also lose the ETA (Estimation Time of Arrival) given after each message copy.
  3492. END_SIZE
  3493. foldersizes_diff_list( $mysync ) ;
  3494. ( $mysync->{ h1_nb_msg_start }, $mysync->{ h1_bytes_start },
  3495. $mysync->{ h2_nb_msg_start }, $mysync->{ h2_bytes_start } )
  3496. = foldersizes_total( $mysync ) ;
  3497. if ( not all_defined(
  3498. $mysync->{ h1_nb_msg_start },
  3499. $mysync->{ h1_bytes_start },
  3500. $mysync->{ h2_nb_msg_start },
  3501. $mysync->{ h2_bytes_start } ) )
  3502. {
  3503. my $error = "Failure getting foldersizes, ETA and final diff will not be displayed\n" ;
  3504. errors_incr( $mysync, $error ) ;
  3505. $mysync->{ foldersizes } = 0 ;
  3506. $mysync->{ foldersizesatend } = 0 ;
  3507. return ;
  3508. }
  3509. my $h2_bytes_limit = $mysync->{ acc2 }->{quota_limit_bytes} || 0 ;
  3510. if ( $h2_bytes_limit and ( $h2_bytes_limit < $mysync->{ h1_bytes_start } ) )
  3511. {
  3512. my $quota_percent = mysprintf( '%.0f', $NUMBER_100 * $mysync->{ h1_bytes_start } / $h2_bytes_limit ) ;
  3513. my $error = "Host2: Quota limit will be exceeded! Over $quota_percent % ( $mysync->{ h1_bytes_start } bytes / $h2_bytes_limit bytes )\n" ;
  3514. errors_incr( $mysync, $error ) ;
  3515. }
  3516. return ;
  3517. }
  3518. # Globals:
  3519. # @h2_folders_from_1_wanted
  3520. sub foldersizes_at_the_beggining_old
  3521. {
  3522. my $mysync = shift ;
  3523. myprint( << 'END_SIZE' ) ;
  3524. Folders sizes before the synchronization.
  3525. You can remove foldersizes listings by using "--nofoldersizes" and "--nofoldersizesatend"
  3526. but then you will also lose the ETA (Estimation Time of Arrival) given after each message copy.
  3527. END_SIZE
  3528. ( $mysync->{ h1_nb_msg_start }, $mysync->{ h1_bytes_start } ) =
  3529. foldersizes( $mysync, 'Host1', $mysync->{imap1}, $mysync->{ search1 },
  3530. $mysync->{abletosearch1}, @{ $mysync->{h1_folders_wanted} } ) ;
  3531. ( $mysync->{ h2_nb_msg_start }, $mysync->{ h2_bytes_start } ) =
  3532. foldersizes( $mysync, 'Host2', $mysync->{imap2}, $mysync->{ search2 },
  3533. $mysync->{abletosearch2}, @h2_folders_from_1_wanted ) ;
  3534. if ( not all_defined( $mysync->{ h1_nb_msg_start },
  3535. $mysync->{ h1_bytes_start }, $mysync->{ h2_nb_msg_start }, $mysync->{ h2_bytes_start } ) )
  3536. {
  3537. my $error = "Failure getting foldersizes, ETA and final diff will not be displayed\n" ;
  3538. errors_incr( $mysync, $error ) ;
  3539. $mysync->{ foldersizes } = 0 ;
  3540. $mysync->{ foldersizesatend } = 0 ;
  3541. return ;
  3542. }
  3543. my $h2_bytes_limit = $mysync->{ acc2 }->{quota_limit_bytes} || 0 ;
  3544. if ( $h2_bytes_limit and ( $h2_bytes_limit < $mysync->{ h1_bytes_start } ) )
  3545. {
  3546. my $quota_percent = mysprintf( '%.0f', $NUMBER_100 * $mysync->{ h1_bytes_start } / $h2_bytes_limit ) ;
  3547. my $error = "Host2: Quota limit will be exceeded! Over $quota_percent % ( $mysync->{ h1_bytes_start } bytes / $h2_bytes_limit bytes )\n" ;
  3548. errors_incr( $mysync, $error ) ;
  3549. }
  3550. return ;
  3551. }
  3552. sub tests_total_bytes_max_reached
  3553. {
  3554. note( 'Entering tests_total_bytes_max_reached()' ) ;
  3555. is( undef, total_bytes_max_reached( ), 'total_bytes_max_reached: no args => undef' ) ;
  3556. my $mysync = {} ;
  3557. is( undef, total_bytes_max_reached( $mysync ), 'total_bytes_max_reached: no exitwhenover => undef' ) ;
  3558. $mysync->{ exitwhenover } = 300 ;
  3559. is( undef, total_bytes_max_reached( $mysync ), 'total_bytes_max_reached: exitwhenover 300 but no total_bytes_transferred => undef' ) ;
  3560. $mysync->{ total_bytes_transferred } = 200 ;
  3561. is( undef, total_bytes_max_reached( $mysync ), 'total_bytes_max_reached: exitwhenover 300 but total_bytes_transferred 200 => undef' ) ;
  3562. $mysync->{ total_bytes_transferred } = 400 ;
  3563. is( 1, total_bytes_max_reached( $mysync ), 'total_bytes_max_reached: exitwhenover 300 but total_bytes_transferred 400 => 1' ) ;
  3564. note( 'Leaving tests_total_bytes_max_reached()' ) ;
  3565. return ;
  3566. }
  3567. sub total_bytes_max_reached
  3568. {
  3569. my $mysync = shift ;
  3570. if ( ! defined $mysync ) { return ; }
  3571. if ( ! $mysync->{ exitwhenover } )
  3572. {
  3573. return ;
  3574. }
  3575. if ( ! $mysync->{ total_bytes_transferred } )
  3576. {
  3577. return ;
  3578. }
  3579. if ( $mysync->{ total_bytes_transferred } >= $mysync->{ exitwhenover } )
  3580. {
  3581. my $error = "Maximum bytes transferred reached, $mysync->{total_bytes_transferred} >= $mysync->{ exitwhenover }, ending sync\n" ;
  3582. errors_incr( $mysync, $error ) ;
  3583. return( 1 ) ;
  3584. }
  3585. return ;
  3586. }
  3587. sub tests_mock_capability
  3588. {
  3589. note( 'Entering tests_mock_capability()' ) ;
  3590. my $myimap ;
  3591. ok( $myimap = mock_capability( ),
  3592. 'mock_capability: (1) no args => a Test::MockObject'
  3593. ) ;
  3594. ok( $myimap->isa( 'Test::MockObject' ),
  3595. 'mock_capability: (2) no args => a Test::MockObject'
  3596. ) ;
  3597. is( undef, $myimap->capability( ),
  3598. 'mock_capability: (3) no args => capability undef'
  3599. ) ;
  3600. ok( mock_capability( $myimap ),
  3601. 'mock_capability: (1) one arg => MockObject'
  3602. ) ;
  3603. is( undef, $myimap->capability( ),
  3604. 'mock_capability: (2) one arg OO style => capability undef'
  3605. ) ;
  3606. ok( mock_capability( $myimap, $NUMBER_123456 ),
  3607. 'mock_capability: (1) two args 123456 => capability 123456'
  3608. ) ;
  3609. is( $NUMBER_123456, $myimap->capability( ),
  3610. 'mock_capability: (2) two args 123456 => capability 123456'
  3611. ) ;
  3612. ok( mock_capability( $myimap, 'ABCD' ),
  3613. 'mock_capability: (1) two args ABCD => capability ABCD'
  3614. ) ;
  3615. is( 'ABCD', $myimap->capability( ),
  3616. 'mock_capability: (2) two args ABCD => capability ABCD'
  3617. ) ;
  3618. ok( mock_capability( $myimap, [ 'ABCD' ] ),
  3619. 'mock_capability: (1) two args [ ABCD ] => capability [ ABCD ]'
  3620. ) ;
  3621. is_deeply( [ 'ABCD' ], $myimap->capability( ),
  3622. 'mock_capability: (2) two args [ ABCD ] => capability [ ABCD ]'
  3623. ) ;
  3624. ok( mock_capability( $myimap, [ 'ABC', 'DEF' ] ),
  3625. 'mock_capability: (1) two args [ ABC, DEF ] => capability [ ABC, DEF ]'
  3626. ) ;
  3627. is_deeply( [ 'ABC', 'DEF' ], $myimap->capability( ),
  3628. 'mock_capability: (2) two args [ ABC, DEF ] => capability capability [ ABC, DEF ]'
  3629. ) ;
  3630. ok( mock_capability( $myimap, 'ABC', 'DEF' ),
  3631. 'mock_capability: (1) two args ABC, DEF => capability [ ABC, DEF ]'
  3632. ) ;
  3633. is_deeply( [ 'ABC', 'DEF' ], [ $myimap->capability( ) ],
  3634. 'mock_capability: (2) two args ABC, DEF => capability capability [ ABC, DEF ]'
  3635. ) ;
  3636. ok( mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ),
  3637. 'mock_capability: (1) two args IMAP4rev1, APPENDLIMIT=123456 => capability [ IMAP4rev1, APPENDLIMIT=123456 ]'
  3638. ) ;
  3639. is_deeply( [ 'IMAP4rev1', 'APPENDLIMIT=123456' ], [ $myimap->capability( ) ],
  3640. 'mock_capability: (2) two args IMAP4rev1, APPENDLIMIT=123456 => capability capability [ IMAP4rev1, APPENDLIMIT=123456 ]'
  3641. ) ;
  3642. note( 'Leaving tests_mock_capability()' ) ;
  3643. return ;
  3644. }
  3645. sub sig_install_toggle_sleep
  3646. {
  3647. my $mysync = shift ;
  3648. if ( 'MSWin32' ne $OSNAME ) {
  3649. #myprint( "sig_install( $mysync, \&toggle_sleep, 'USR1' )\n" ) ;
  3650. sig_install( $mysync, 'toggle_sleep', 'USR1' ) ;
  3651. }
  3652. #myprint( "Leaving sig_install_toggle_sleep\n" ) ;
  3653. return ;
  3654. }
  3655. sub mock_capability
  3656. {
  3657. my $myimap = shift ;
  3658. my @has_capability_value = @ARG ;
  3659. my ( $has_capability_value ) = @has_capability_value ;
  3660. if ( ! $myimap )
  3661. {
  3662. require_ok( "Test::MockObject" ) ;
  3663. $myimap = Test::MockObject->new( ) ;
  3664. }
  3665. $myimap->mock(
  3666. 'capability',
  3667. sub { return wantarray ?
  3668. @has_capability_value
  3669. : $has_capability_value ;
  3670. }
  3671. ) ;
  3672. return $myimap ;
  3673. }
  3674. sub tests_capability_of
  3675. {
  3676. note( 'Entering tests_capability_of()' ) ;
  3677. is( undef, capability_of( ),
  3678. 'capability_of: no args => undef' ) ;
  3679. my $myimap ;
  3680. is( undef, capability_of( $myimap ),
  3681. 'capability_of: undef => undef' ) ;
  3682. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3683. is( undef, capability_of( $myimap, 'CACA' ),
  3684. 'capability_of: two args unknown capability => undef' ) ;
  3685. is( $NUMBER_123456, capability_of( $myimap, 'APPENDLIMIT' ),
  3686. 'capability_of: two args APPENDLIMIT 123456 => 123456 yeah!' ) ;
  3687. note( 'Leaving tests_capability_of()' ) ;
  3688. return ;
  3689. }
  3690. sub capability_of
  3691. {
  3692. my $imap = shift || return ;
  3693. my $capability_keyword = shift || return ;
  3694. my @capability = $imap->capability ;
  3695. if ( ! @capability ) { return ; }
  3696. my $capability_value = search_in_array( $capability_keyword, @capability ) ;
  3697. return $capability_value ;
  3698. }
  3699. sub tests_search_in_array
  3700. {
  3701. note( 'Entering tests_search_in_array()' ) ;
  3702. is( undef, search_in_array( 'KA' ),
  3703. 'search_in_array: no array => undef ' ) ;
  3704. is( 'VA', search_in_array( 'KA', ( 'KA=VA' ) ),
  3705. 'search_in_array: KA KA=VA => VA ' ) ;
  3706. is( 'VA', search_in_array( 'KA', ( 'KA=VA', 'KB=VB' ) ),
  3707. 'search_in_array: KA KA=VA KB=VB => VA ' ) ;
  3708. is( 'VB', search_in_array( 'KB', ( 'KA=VA', 'KB=VB' ) ),
  3709. 'search_in_array: KA=VA KB=VB => VB ' ) ;
  3710. note( 'Leaving tests_search_in_array()' ) ;
  3711. return ;
  3712. }
  3713. sub search_in_array
  3714. {
  3715. my ( $key, @array ) = @ARG ;
  3716. foreach my $item ( @array )
  3717. {
  3718. if ( $item =~ /([^=]+)=(.*)/ )
  3719. {
  3720. if ( $1 eq $key )
  3721. {
  3722. return $2 ;
  3723. }
  3724. }
  3725. }
  3726. return ;
  3727. }
  3728. sub tests_appendlimit_from_capability
  3729. {
  3730. note( 'Entering tests_appendlimit_from_capability()' ) ;
  3731. is( undef, appendlimit_from_capability( ),
  3732. 'appendlimit_from_capability: no args => undef'
  3733. ) ;
  3734. my $myimap ;
  3735. is( undef, appendlimit_from_capability( $myimap ),
  3736. 'appendlimit_from_capability: undef arg => undef'
  3737. ) ;
  3738. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3739. # Normal behavior
  3740. is( $NUMBER_123456, appendlimit_from_capability( $myimap ),
  3741. 'appendlimit_from_capability: APPENDLIMIT=123456 => 123456'
  3742. ) ;
  3743. # Not a number
  3744. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=ABC' ) ;
  3745. is( undef, appendlimit_from_capability( $myimap ),
  3746. 'appendlimit_from_capability: not a number => undef'
  3747. ) ;
  3748. note( 'Leaving tests_appendlimit_from_capability()' ) ;
  3749. return ;
  3750. }
  3751. sub appendlimit_from_capability
  3752. {
  3753. my $myimap = shift ;
  3754. if ( ! $myimap )
  3755. {
  3756. myprint( "Warn: no imap with call to appendlimit_from_capability\n" ) ;
  3757. return ;
  3758. }
  3759. #myprint( Data::Dumper->Dump( [ \$myimap ] ) ) ;
  3760. my $appendlimit = capability_of( $myimap, 'APPENDLIMIT' ) ;
  3761. #myprint( "has_capability APPENDLIMIT $appendlimit\n" ) ;
  3762. if ( is_integer( $appendlimit ) )
  3763. {
  3764. return $appendlimit ;
  3765. }
  3766. return ;
  3767. }
  3768. sub tests_appendlimit
  3769. {
  3770. note( 'Entering tests_appendlimit()' ) ;
  3771. is( undef, appendlimit( ),
  3772. 'appendlimit: no args => undef'
  3773. ) ;
  3774. my $mysync = { } ;
  3775. is( undef, appendlimit( $mysync ),
  3776. 'appendlimit: no imap2 => undef'
  3777. ) ;
  3778. my $myimap ;
  3779. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3780. $mysync->{ imap2 } = $myimap ;
  3781. is( 123456, appendlimit( $mysync ),
  3782. 'appendlimit: imap2 with APPENDLIMIT=123456 => 123456'
  3783. ) ;
  3784. note( 'Leaving tests_appendlimit()' ) ;
  3785. return ;
  3786. }
  3787. sub appendlimit
  3788. {
  3789. my $mysync = shift || return ;
  3790. my $myimap = $mysync->{ imap2 } ;
  3791. my $appendlimit = appendlimit_from_capability( $myimap ) ;
  3792. if ( defined $appendlimit )
  3793. {
  3794. myprint( "Host2: found APPENDLIMIT=$appendlimit in CAPABILITY (use --appendlimit xxxx to override this automatic setting)\n" ) ;
  3795. return $appendlimit ;
  3796. }
  3797. return ;
  3798. }
  3799. sub tests_maxsize_setting
  3800. {
  3801. note( 'Entering tests_maxsize_setting()' ) ;
  3802. is( undef, maxsize_setting( ),
  3803. 'maxsize_setting: no args => undef'
  3804. ) ;
  3805. my $mysync ;
  3806. is( undef, maxsize_setting( $mysync ),
  3807. 'maxsize_setting: undef arg => undef'
  3808. ) ;
  3809. $mysync = { } ;
  3810. $mysync->{ maxsize } = $NUMBER_123456 ;
  3811. # --maxsize alone
  3812. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3813. 'maxsize_setting: --maxsize 123456 alone => 123456'
  3814. ) ;
  3815. $mysync = { } ;
  3816. my $myimap ;
  3817. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=654321' ) ;
  3818. $mysync->{ imap2 } = $myimap ;
  3819. # APPENDLIMIT alone
  3820. is( $NUMBER_654321, maxsize_setting( $mysync ),
  3821. 'maxsize_setting: APPENDLIMIT 654321 alone => 654321'
  3822. ) ;
  3823. is( $NUMBER_654321, $mysync->{ maxsize },
  3824. 'maxsize_setting: APPENDLIMIT 654321 alone => maxsize 654321'
  3825. ) ;
  3826. # APPENDLIMIT with --appendlimit => --appendlimit wins
  3827. $mysync->{ appendlimit } = $NUMBER_123456 ;
  3828. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3829. 'maxsize_setting: APPENDLIMIT 654321 + --appendlimit 123456 => 123456'
  3830. ) ;
  3831. is( $NUMBER_123456, $mysync->{ maxsize },
  3832. 'maxsize_setting: APPENDLIMIT 654321 + --appendlimit 123456 => maxsize 123456'
  3833. ) ;
  3834. # Fresh
  3835. $mysync = { } ;
  3836. $mysync->{ imap2 } = $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=654321' ) ;
  3837. # Case: "APPENDLIMIT >= --maxsize" => maxsize.
  3838. $mysync->{ maxsize } = $NUMBER_123456 ;
  3839. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3840. 'maxsize_setting: APPENDLIMIT 654321 --maxsize 123456 => 123456'
  3841. ) ;
  3842. # Case: "APPENDLIMIT < --maxsize" => APPENDLIMIT.
  3843. # Fresh
  3844. $mysync = { } ;
  3845. $mysync->{ imap2 } = $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3846. $mysync->{ maxsize } = $NUMBER_654321 ;
  3847. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3848. 'maxsize_setting: APPENDLIMIT 123456 --maxsize 654321 => 123456 '
  3849. ) ;
  3850. # Now --truncmess stuff
  3851. note( 'Leaving tests_maxsize_setting()' ) ;
  3852. return ;
  3853. }
  3854. # Three variables to take account of
  3855. # appendlimit (given by --appendlimit or CAPABILITY...)
  3856. # maxsize
  3857. # truncmess
  3858. sub maxsize_setting
  3859. {
  3860. my $mysync = shift || return ;
  3861. if ( defined $mysync->{ appendlimit } )
  3862. {
  3863. myprint( "Host2: Getting appendlimit from --appendlimit $mysync->{ appendlimit }\n" ) ;
  3864. }
  3865. else
  3866. {
  3867. $mysync->{ appendlimit } = appendlimit( $mysync ) ;
  3868. }
  3869. if ( all_defined( $mysync->{ appendlimit }, $mysync->{ maxsize } ) )
  3870. {
  3871. my $min_maxsize_appendlimit = min( $mysync->{ maxsize }, $mysync->{ appendlimit } ) ;
  3872. myprint( "Host2: Setting maxsize to $min_maxsize_appendlimit (min of --maxsize $mysync->{ maxsize } and appendlimit $mysync->{ appendlimit }\n" ) ;
  3873. $mysync->{ maxsize } = $min_maxsize_appendlimit ;
  3874. return $mysync->{ maxsize } ;
  3875. }
  3876. elsif ( defined $mysync->{ appendlimit } )
  3877. {
  3878. myprint( "Host2: Setting maxsize to appendlimit $mysync->{ appendlimit }\n" ) ;
  3879. $mysync->{ maxsize } = $mysync->{ appendlimit } ;
  3880. return $mysync->{ maxsize } ;
  3881. }elsif ( defined $mysync->{ maxsize } )
  3882. {
  3883. return $mysync->{ maxsize } ;
  3884. }else
  3885. {
  3886. return ;
  3887. }
  3888. }
  3889. sub all_defined
  3890. {
  3891. if ( not @ARG ) {
  3892. return 0 ;
  3893. }
  3894. foreach my $elem ( @ARG ) {
  3895. if ( not defined $elem ) {
  3896. return 0 ;
  3897. }
  3898. }
  3899. return 1 ;
  3900. }
  3901. sub tests_all_defined
  3902. {
  3903. note( 'Entering tests_all_defined()' ) ;
  3904. is( 0, all_defined( ), 'all_defined: no param => 0' ) ;
  3905. is( 0, all_defined( () ), 'all_defined: void list => 0' ) ;
  3906. is( 0, all_defined( undef ), 'all_defined: undef => 0' ) ;
  3907. is( 0, all_defined( undef, undef ), 'all_defined: undef => 0' ) ;
  3908. is( 0, all_defined( 1, undef ), 'all_defined: 1 undef => 0' ) ;
  3909. is( 0, all_defined( undef, 1 ), 'all_defined: undef 1 => 0' ) ;
  3910. is( 1, all_defined( 1, 1 ), 'all_defined: 1 1 => 1' ) ;
  3911. is( 1, all_defined( (1, 1) ), 'all_defined: (1 1) => 1' ) ;
  3912. note( 'Leaving tests_all_defined()' ) ;
  3913. return ;
  3914. }
  3915. sub tests_hashsynclocal
  3916. {
  3917. note( 'Entering tests_hashsynclocal()' ) ;
  3918. my $mysync = {
  3919. host1 => q{},
  3920. user1 => q{},
  3921. password1 => q{},
  3922. host2 => q{},
  3923. user2 => q{},
  3924. password2 => q{},
  3925. } ;
  3926. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: no hashfile name' ) ;
  3927. $mysync->{ hashfile } = q{} ;
  3928. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: empty hashfile name' ) ;
  3929. $mysync->{ hashfile } = './noexist/rrr' ;
  3930. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: no exists hashfile dir' ) ;
  3931. SKIP: {
  3932. if ( 'MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) { skip( 'Tests only for non-root Unix', 1 ) ; }
  3933. $mysync->{ hashfile } = '/rrr' ;
  3934. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: permission denied' ) ;
  3935. }
  3936. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'hashsynclocal: mkpath W/tmp/tests/' ) ;
  3937. $mysync->{ hashfile } = 'W/tmp/tests/imapsync_hash' ;
  3938. ok( ! -e 'W/tmp/tests/imapsync_hash' || unlink 'W/tmp/tests/imapsync_hash', 'hashsynclocal: unlink W/tmp/tests/imapsync_hash' ) ;
  3939. ok( ! -e 'W/tmp/tests/imapsync_hash', 'hashsynclocal: verify there is no W/tmp/tests/imapsync_hash' ) ;
  3940. is( 'ecdeb4ede672794d173da4e08c52b8ee19b7d252', hashsynclocal( $mysync, 'mukksyhpmbixkxkpjlqivmlqsulpictj' ), 'hashsynclocal: creating/reading W/tmp/tests/imapsync_hash' ) ;
  3941. # A second time now
  3942. is( 'ecdeb4ede672794d173da4e08c52b8ee19b7d252', hashsynclocal( $mysync ), 'hashsynclocal: reading W/tmp/tests/imapsync_hash second time => same' ) ;
  3943. note( 'Leaving tests_hashsynclocal()' ) ;
  3944. return ;
  3945. }
  3946. sub hashsynclocal
  3947. {
  3948. my $mysync = shift ;
  3949. my $hashkey = shift ; # Optional, only there for tests
  3950. my $hashfile = $mysync->{ hashfile } ;
  3951. $hashfile = createhashfileifneeded( $hashfile, $hashkey ) ;
  3952. if ( ! $hashfile ) {
  3953. return ;
  3954. }
  3955. $hashkey = firstline( $hashfile ) ;
  3956. if ( ! $hashkey ) {
  3957. myprint( "No hashkey!\n" ) ;
  3958. return ;
  3959. }
  3960. my $hashsynclocal = hashsync( $mysync, $hashkey ) ;
  3961. return( $hashsynclocal ) ;
  3962. }
  3963. sub tests_hashsync
  3964. {
  3965. note( 'Entering tests_hashsync()' ) ;
  3966. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hashsync( ), 'hashsync: no args' ) ;
  3967. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hashsync( {}, q{} ), 'hashsync: empty args' ) ;
  3968. my $mysync ;
  3969. $mysync->{ host1 } = 'zzz' ;
  3970. is( 'e86a28a3611c1e7bbaf8057cd00ae122781a11fe', hashsync( $mysync, q{} ), 'hashsync: host1 zzz => ' ) ;
  3971. is( '6a7b451ac99eab1531ad8e6cd544b32420c552ac', hashsync( $mysync, q{A} ), 'hashsync: host1 zzz => ' ) ;
  3972. $mysync->{ host2 } = 'zzz' ;
  3973. is( '15959573e4a86763253a7aedb1a2b0c60d133dc2', hashsync( $mysync, q{} ), 'hashsync: + host2 zzz => ' ) ;
  3974. is( 'b8d4ab541b209c75928528020ca28ee43488bd8f', hashsync( $mysync, 'A' ), 'hashsync: + hashkey A => ' ) ;
  3975. $mysync = undef ;
  3976. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hashsync( $mysync, q{} ), 'hashsync: undef $mysync' ) ;
  3977. $mysync->{ password1 } = 'abcd' ;
  3978. is( 'afa29ab8534495251ac8346a985717c54bc49c26', hashsync( $mysync, q{} ), 'hashsync: password1: abcd' ) ;
  3979. # A user reported a massive failure on /X (Thomas V. 21/04/2020 Ã 21:41 Subject: Error)
  3980. # "Wide character in subroutine entry at /usr/local/lib/perl5/site_perl/Digest/HMAC.pm"
  3981. # I can reproduce it now
  3982. # The eval is there to avoid a complete crash
  3983. # this one is fatal so it is commented
  3984. # is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', 1 / 0 , 'hashsync: 1 / 0 fatal' ) ;
  3985. my $eval ;
  3986. # this one is not fatal
  3987. is( undef, $eval = eval { 1 / 0 } , 'hashsync: 1/0 not fatal' ) ;
  3988. # this one neither
  3989. $mysync->{ password1 } = 'Ö' ;
  3990. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', $eval = eval { hashsync( $mysync, q{} ) } , 'hashsync: password1: Ö with eval' ) ;
  3991. $mysync->{ password1 } = 'Ö' ;
  3992. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hashsync( $mysync, q{} ), 'hashsync: password1: Ö without eval' ) ;
  3993. $mysync->{ password1 } = qq{\x{00D6}} ;
  3994. is( 'bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a', $eval = eval { hashsync( $mysync, q{} ) }, 'hashsync: password1: \x{00D6}' ) ; #
  3995. print qq{1 00D6:Ö\n} ;
  3996. print encode_utf8( qq{2 00D6:Ö\n} ) ;
  3997. print qq{3 00D6:\x{00D6}\n} ;
  3998. print encode_utf8( qq{4 00D6:\x{00D6}\n} ) ;
  3999. print qq{5 6536:æ”¶\n} ;
  4000. print encode_utf8( qq{6 6536:æ”¶\n} ) ;
  4001. # the next one prints "Wide character in print at ./imapsync line xxxx"
  4002. print qq{7 6536:\x{6536}\n} ;
  4003. print encode_utf8( qq{8 6536:\x{6536}\n} ) ;
  4004. $mysync->{ password1 } = qq{æ”¶} ;
  4005. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hashsync( $mysync, q{} ), 'hashsync: password1: æ”¶' ) ;
  4006. $mysync->{ password1 } = qq{\x{6536}} ;
  4007. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', $eval = eval{ hashsync( $mysync, q{} ) }, 'hashsync: password1: \x{6536} with eval' ) ;
  4008. # No side effect.
  4009. $mysync->{ password1 } = 'abcd' ;
  4010. is( 'afa29ab8534495251ac8346a985717c54bc49c26', hashsync( $mysync, q{} ), 'hashsync: password1: abcd again' ) ;
  4011. note( 'Leaving tests_hashsync()' ) ;
  4012. return ;
  4013. }
  4014. sub hashsync
  4015. {
  4016. my $mysync = shift ;
  4017. my $hashkey = shift ;
  4018. my $mystring = join( q{},
  4019. $mysync->{ host1 } || q{},
  4020. $mysync->{ user1 } || q{},
  4021. $mysync->{ password1 } || q{},
  4022. $mysync->{ host2 } || q{},
  4023. $mysync->{ user2 } || q{},
  4024. $mysync->{ password2 } || q{},
  4025. ) ;
  4026. #my $hashsync = hmac_sha1_hex( $mystring, $hashkey ) ;
  4027. my $hashsync = hmac_sha1_hex_robust( $mystring, $hashkey ) ;
  4028. #myprint( "$hashsync\n" ) ;
  4029. return( $hashsync ) ;
  4030. }
  4031. sub tests_hmac_sha1_hex
  4032. {
  4033. note( 'Entering tests_hmac_sha1_hex()' ) ;
  4034. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex( ), 'hmac_sha1_hex: no args => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  4035. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex( '' ), 'hmac_sha1_hex: empty string => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  4036. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex( '', '' ), 'hmac_sha1_hex: empty strings => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  4037. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex( '', '', 'caca' ), 'hmac_sha1_hex: empty strings + caca => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  4038. # Good
  4039. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hmac_sha1_hex( 'Ö' ), 'hmac_sha1_hex: Ö => f1a3f3dac3f137fd658027c11678b895f773ce55' ) ;
  4040. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hmac_sha1_hex( encode_utf8(qq{\x{00D6}}) ), 'hmac_sha1_hex: encode_utf8 \x{00D6} => f1a3f3dac3f137fd658027c11678b895f773ce55' ) ;
  4041. # Bad
  4042. is( 'fe8dc3b9ba3e8850bb4a7b070b2279e911003af2', hmac_sha1_hex( encode_utf8( 'Ö' ) ), 'hmac_sha1_hex: encode_utf8 Ö => fe8dc3b9ba3e8850bb4a7b070b2279e911003af2' ) ;
  4043. is( 'bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a', hmac_sha1_hex( qq{\x{00D6}} ), 'hmac_sha1_hex: qq{\x{00D6}} => bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a' ) ;
  4044. # Good
  4045. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex( 'A' ), 'hmac_sha1_hex: A => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  4046. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex( encode_utf8(qq{\x{0041}}) ), 'hmac_sha1_hex: encode_utf8 \x{0041} => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  4047. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex( encode_utf8( 'A' ) ), 'hmac_sha1_hex: encode_utf8 A => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  4048. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex( qq{\x{0041}} ), 'hmac_sha1_hex: \x{0041} => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  4049. # Good
  4050. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex( 'A', 'B' ), 'hmac_sha1_hex: A B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  4051. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex( encode_utf8(qq{\x{0041}}), 'B' ), 'hmac_sha1_hex: encode_utf8 \x{0041} B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  4052. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex( encode_utf8( 'A' ), 'B' ), 'hmac_sha1_hex: encode_utf8 A B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  4053. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex( qq{\x{0041}}, 'B' ), 'hmac_sha1_hex: \x{0041} B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  4054. # http://unicode.scarfboy.com/?s=U%2B6536
  4055. # Good
  4056. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex( 'æ”¶' ), 'hmac_sha1_hex: æ”¶ => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  4057. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex( encode_utf8(qq{\x{6536}}) ), 'hmac_sha1_hex: encode_utf8 \x{6536} => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  4058. # Bad
  4059. is( 'e82217119628ad03e659cc89671d05ea4cee7238', hmac_sha1_hex( encode_utf8( 'æ”¶' ) ), 'hmac_sha1_hex: encode_utf8 æ”¶ => e82217119628ad03e659cc89671d05ea4cee7238' ) ;
  4060. # Very very bad, perl dies...
  4061. #is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex( qq{\x{6536}} ), 'hmac_sha1_hex: \x{6536} => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  4062. # Ok but well, bad indeed
  4063. is( undef, my $eval = eval{ hmac_sha1_hex( qq{\x{6536}} ) }, 'hmac_sha1_hex: \x{6536} => undef' ) ;
  4064. note( 'Leaving tests_hmac_sha1_hex()' ) ;
  4065. return ;
  4066. }
  4067. sub tests_hmac_sha1_hex_robust
  4068. {
  4069. note( 'Entering tests_hmac_sha1_hex_robust()' ) ;
  4070. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex_robust( ), 'hmac_sha1_hex_robust: no args => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  4071. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex_robust( '' ), 'hmac_sha1_hex_robust: empty string => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  4072. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex_robust( '', '' ), 'hmac_sha1_hex_robust: empty strings => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  4073. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hmac_sha1_hex_robust( '', '', 'caca' ), 'hmac_sha1_hex_robust: empty strings + caca => fbdb1d1b18aa6c08324b7d64b71fb76370690e1d' ) ;
  4074. # Good
  4075. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hmac_sha1_hex_robust( 'Ö' ), 'hmac_sha1_hex_robust: Ö => f1a3f3dac3f137fd658027c11678b895f773ce55' ) ;
  4076. is( 'f1a3f3dac3f137fd658027c11678b895f773ce55', hmac_sha1_hex_robust( encode_utf8(qq{\x{00D6}}) ), 'hmac_sha1_hex_robust: encode_utf8 \x{00D6} => f1a3f3dac3f137fd658027c11678b895f773ce55' ) ;
  4077. # Bad
  4078. is( 'fe8dc3b9ba3e8850bb4a7b070b2279e911003af2', hmac_sha1_hex_robust( encode_utf8( 'Ö' ) ), 'hmac_sha1_hex_robust: encode_utf8 Ö => fe8dc3b9ba3e8850bb4a7b070b2279e911003af2' ) ;
  4079. is( 'bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a', hmac_sha1_hex_robust( qq{\x{00D6}} ), 'hmac_sha1_hex_robust: qq{\x{00D6}} => bb5bfb461e79ecd3dbc6ade2aabb52d22fa8be1a' ) ;
  4080. # Good
  4081. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex_robust( 'A' ), 'hmac_sha1_hex_robust: A => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  4082. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex_robust( encode_utf8(qq{\x{0041}}) ), 'hmac_sha1_hex_robust: encode_utf8 \x{0041} => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  4083. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex_robust( encode_utf8( 'A' ) ), 'hmac_sha1_hex_robust: encode_utf8 A => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  4084. is( 'a6fda2a6acdd74630b20aac0c68716048ecd0333', hmac_sha1_hex_robust( qq{\x{0041}} ), 'hmac_sha1_hex_robust: \x{0041} => a6fda2a6acdd74630b20aac0c68716048ecd0333' ) ;
  4085. # Good
  4086. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex_robust( 'A', 'B' ), 'hmac_sha1_hex_robust: A B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  4087. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex_robust( encode_utf8(qq{\x{0041}}), 'B' ), 'hmac_sha1_hex_robust: encode_utf8 \x{0041} B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  4088. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex_robust( encode_utf8( 'A' ), 'B' ), 'hmac_sha1_hex_robust: encode_utf8 A B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  4089. is( '36c54f255b575a2db58921d116b37c8af94c08cd', hmac_sha1_hex_robust( qq{\x{0041}}, 'B' ), 'hmac_sha1_hex_robust: \x{0041} B => 36c54f255b575a2db58921d116b37c8af94c08cd' ) ;
  4090. # http://unicode.scarfboy.com/?s=U%2B6536
  4091. # Good
  4092. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex_robust( 'æ”¶' ), 'hmac_sha1_hex_robust: æ”¶ => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  4093. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex_robust( encode_utf8(qq{\x{6536}}) ), 'hmac_sha1_hex_robust: encode_utf8 \x{6536} => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  4094. # Bad
  4095. is( 'e82217119628ad03e659cc89671d05ea4cee7238', hmac_sha1_hex_robust( encode_utf8( 'æ”¶' ) ), 'hmac_sha1_hex_robust: encode_utf8 æ”¶ => e82217119628ad03e659cc89671d05ea4cee7238' ) ;
  4096. # Good
  4097. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', hmac_sha1_hex_robust( qq{\x{6536}} ), 'hmac_sha1_hex_robust: \x{6536} => 4199f02773d1cd5599b1a8f2d024bdceb8b48e0b' ) ;
  4098. # Good again
  4099. is( '4199f02773d1cd5599b1a8f2d024bdceb8b48e0b', my $eval = eval{ hmac_sha1_hex_robust( qq{\x{6536}} ) }, 'hmac_sha1_hex_robust: \x{6536} => undef' ) ;
  4100. note( 'Leaving tests_hmac_sha1_hex_robust()' ) ;
  4101. return ;
  4102. }
  4103. sub hmac_sha1_hex_robust
  4104. {
  4105. my $string = shift ;
  4106. my $val ;
  4107. if ( defined( $val = eval{ hmac_sha1_hex( $string, @ARG ) } ) )
  4108. {
  4109. return $val ;
  4110. }
  4111. elsif( defined( $val = eval{ hmac_sha1_hex( encode_utf8( $string ), @ARG ) } ) )
  4112. {
  4113. return $val ;
  4114. }
  4115. else
  4116. {
  4117. return ;
  4118. }
  4119. }
  4120. sub tests_createhashfileifneeded
  4121. {
  4122. note( 'Entering tests_createhashfileifneeded()' ) ;
  4123. is( undef, createhashfileifneeded( ), 'createhashfileifneeded: no parameters => undef' ) ;
  4124. note( 'Leaving tests_createhashfileifneeded()' ) ;
  4125. return ;
  4126. }
  4127. sub createhashfileifneeded
  4128. {
  4129. my $hashfile = shift ;
  4130. my $hashkey = shift || rand32( ) ;
  4131. # no name
  4132. if ( ! $hashfile ) {
  4133. return ;
  4134. }
  4135. # already there
  4136. if ( -e -r $hashfile ) {
  4137. return $hashfile ;
  4138. }
  4139. # not creatable
  4140. if ( ! -w dirname( $hashfile ) ) {
  4141. return ;
  4142. }
  4143. # creatable
  4144. open my $FILE_HANDLE, '>', $hashfile
  4145. or do {
  4146. myprint( "Could not open $hashfile for writing. Check permissions or disk space." ) ;
  4147. return ;
  4148. } ;
  4149. myprint( "Writing random hashkey in $hashfile, once for all times\n" ) ;
  4150. print $FILE_HANDLE $hashkey ;
  4151. close $FILE_HANDLE ;
  4152. # Should be there now
  4153. if ( -e -r $hashfile ) {
  4154. return $hashfile ;
  4155. }
  4156. # unknown failure
  4157. return ;
  4158. }
  4159. sub tests_rand32
  4160. {
  4161. note( 'Entering tests_rand32()' ) ;
  4162. my $string = rand32( ) ;
  4163. myprint( "$string\n" ) ;
  4164. is( 32, length( $string ), 'rand32: 32 characters long' ) ;
  4165. is( 32, length( rand32( ) ), 'rand32: 32 characters long, another one' ) ;
  4166. note( 'Leaving tests_rand32()' ) ;
  4167. return ;
  4168. }
  4169. sub rand32
  4170. {
  4171. my @chars = ( "a".."z" ) ;
  4172. my $string;
  4173. $string .= $chars[rand @chars] for 1..32 ;
  4174. return $string ;
  4175. }
  4176. sub imap_id_stuff
  4177. {
  4178. my $mysync = shift ;
  4179. if ( not $mysync->{id} ) { return ; } ;
  4180. $mysync->{h1_imap_id} = imap_id( $mysync, $mysync->{imap1}, 'Host1' ) ;
  4181. #myprint( 'Host1: ' . $mysync->{h1_imap_id} ) ;
  4182. $mysync->{h2_imap_id} = imap_id( $mysync, $mysync->{imap2}, 'Host2' ) ;
  4183. #myprint( 'Host2: ' . $mysync->{h2_imap_id} ) ;
  4184. return ;
  4185. }
  4186. sub imap_id
  4187. {
  4188. my ( $mysync, $imap, $Side ) = @_ ;
  4189. if ( not $mysync->{id} ) { return q{} ; } ;
  4190. $Side ||= q{} ;
  4191. my $imap_id_response = q{} ;
  4192. if ( not $imap->has_capability( 'ID' ) ) {
  4193. $imap_id_response = 'No ID capability' ;
  4194. myprint( "$Side: No ID capability\n" ) ;
  4195. }else{
  4196. my $id_inp = imapsync_id( $mysync, { side => lc $Side } ) ;
  4197. myprint( "\n$Side: found ID capability. Sending/receiving ID, presented in raw IMAP for now.\n"
  4198. . "In order to avoid sending/receiving ID, use option --noid\n" ) ;
  4199. my $debug_before = $imap->Debug( ) ;
  4200. $imap->Debug( 1 ) ;
  4201. my $id_out = $imap->tag_and_run( 'ID ' . $id_inp ) ;
  4202. #my $id_out = $imap->tag_and_run( 'ID NIL' ) ;
  4203. myprint( "\n" ) ;
  4204. $imap->Debug( $debug_before ) ;
  4205. #$imap_id_response = Data::Dumper->Dump( [ $id_out ], [ 'IMAP_ID' ] ) ;
  4206. }
  4207. return( $imap_id_response ) ;
  4208. }
  4209. sub imapsync_id
  4210. {
  4211. my $mysync = shift ;
  4212. my $overhashref = shift ;
  4213. # See http://tools.ietf.org/html/rfc2971.html
  4214. my $imapsync_id = { } ;
  4215. my $imapsync_id_lamiral = {
  4216. name => 'imapsync',
  4217. version => imapsync_version( $mysync ),
  4218. os => $OSNAME,
  4219. vendor => 'Gilles LAMIRAL',
  4220. 'support-url' => 'https://imapsync.lamiral.info/',
  4221. # Example of date-time: 19-Sep-2015 08:56:07
  4222. date => date_from_rcs( q{$Date: 2022/01/12 21:28:37 $ } ),
  4223. } ;
  4224. my $imapsync_id_github = {
  4225. name => 'imapsync',
  4226. version => imapsync_version( $mysync ),
  4227. os => $OSNAME,
  4228. vendor => 'github',
  4229. 'support-url' => 'https://github.com/imapsync/imapsync',
  4230. date => date_from_rcs( q{$Date: 2022/01/12 21:28:37 $ } ),
  4231. } ;
  4232. $imapsync_id = $imapsync_id_lamiral ;
  4233. #$imapsync_id = $imapsync_id_github ;
  4234. my %mix = ( %{ $imapsync_id }, %{ $overhashref } ) ;
  4235. my $imapsync_id_str = format_for_imap_arg( \%mix ) ;
  4236. #myprint( "$imapsync_id_str\n" ) ;
  4237. return( $imapsync_id_str ) ;
  4238. }
  4239. sub tests_imapsync_id
  4240. {
  4241. note( 'Entering tests_imapsync_id()' ) ;
  4242. my $mysync ;
  4243. ok( '("name" "imapsync" "version" "111" "os" "beurk" "vendor" "Gilles LAMIRAL" "support-url" "https://imapsync.lamiral.info/" "date" "22-12-1968" "side" "host1")'
  4244. eq imapsync_id( $mysync,
  4245. {
  4246. version => 111,
  4247. os => 'beurk',
  4248. date => '22-12-1968',
  4249. side => 'host1'
  4250. }
  4251. ),
  4252. 'tests_imapsync_id override'
  4253. ) ;
  4254. note( 'Leaving tests_imapsync_id()' ) ;
  4255. return ;
  4256. }
  4257. sub format_for_imap_arg
  4258. {
  4259. my $ref = shift ;
  4260. my $string = q{} ;
  4261. my %terms = %{ $ref } ;
  4262. my @terms = ( ) ;
  4263. if ( not ( %terms ) ) { return( 'NIL' ) } ;
  4264. # sort like in RFC then add extra key/values
  4265. foreach my $key ( qw( name version os os-version vendor support-url address date command arguments environment) ) {
  4266. if ( $terms{ $key } ) {
  4267. push @terms, $key, $terms{ $key } ;
  4268. delete $terms{ $key } ;
  4269. }
  4270. }
  4271. push @terms, %terms ;
  4272. $string = '(' . ( join q{ }, map { '"' . $_ . '"' } @terms ) . ')' ;
  4273. return( $string ) ;
  4274. }
  4275. sub tests_format_for_imap_arg
  4276. {
  4277. note( 'Entering tests_format_for_imap_arg()' ) ;
  4278. ok( 'NIL' eq format_for_imap_arg( { } ), 'format_for_imap_arg empty hash ref' ) ;
  4279. ok( '("name" "toto")' eq format_for_imap_arg( { name => 'toto' } ), 'format_for_imap_arg { name => toto }' ) ;
  4280. ok( '("name" "toto" "key" "val")' eq format_for_imap_arg( { name => 'toto', key => 'val' } ), 'format_for_imap_arg 2 x key val' ) ;
  4281. note( 'Leaving tests_format_for_imap_arg()' ) ;
  4282. return ;
  4283. }
  4284. sub quota
  4285. {
  4286. my ( $mysync, $imap, $side ) = @_ ;
  4287. my %side = (
  4288. h1 => 'Host1',
  4289. h2 => 'Host2',
  4290. ) ;
  4291. my $Side = $side{ $side } ;
  4292. my $debug_before = $imap->Debug( ) ;
  4293. $imap->Debug( 1 ) ;
  4294. if ( not $imap->has_capability( 'QUOTA' ) )
  4295. {
  4296. myprint( "$Side: No QUOTA capability found, skipping it.\n" ) ;
  4297. $imap->Debug( $debug_before ) ;
  4298. return ;
  4299. } ;
  4300. myprint( "\n$Side: QUOTA capability found, presented in raw IMAP on next lines\n" ) ;
  4301. my $getquotaroot = $imap->getquotaroot( 'INBOX' ) ;
  4302. # Gmail INBOX quotaroot is "" but with it Mail::IMAPClient does a literal GETQUOTA {2} \n ""
  4303. #$imap->quota( 'ROOT' ) ;
  4304. #$imap->quota( '""' ) ;
  4305. myprint( "\n" ) ;
  4306. $imap->Debug( $debug_before ) ;
  4307. my $quota_limit_bytes = quota_extract_storage_limit_in_bytes( $mysync, $getquotaroot ) ;
  4308. my $quota_current_bytes = quota_extract_storage_current_in_bytes( $mysync, $getquotaroot ) ;
  4309. $mysync->{$side}->{quota_limit_bytes} = $quota_limit_bytes ;
  4310. $mysync->{$side}->{quota_current_bytes} = $quota_current_bytes ;
  4311. my $quota_percent ;
  4312. if ( $quota_limit_bytes > 0 ) {
  4313. $quota_percent = mysprintf( '%.2f', $NUMBER_100 * $quota_current_bytes / $quota_limit_bytes ) ;
  4314. }else{
  4315. $quota_percent = 0 ;
  4316. }
  4317. myprint( "$Side: Quota current storage is $quota_current_bytes bytes. Limit is $quota_limit_bytes bytes. So $quota_percent % full\n" ) ;
  4318. if ( $QUOTA_PERCENT_LIMIT < $quota_percent ) {
  4319. my $error = "$Side: $quota_percent % full: it is time to find a bigger place! ( $quota_current_bytes bytes / $quota_limit_bytes bytes )\n" ;
  4320. errors_incr( $mysync, $error ) ;
  4321. }
  4322. return ;
  4323. }
  4324. sub tests_quota_extract_storage_limit_in_bytes
  4325. {
  4326. note( 'Entering tests_quota_extract_storage_limit_in_bytes()' ) ;
  4327. my $mysync = {} ;
  4328. my $imap_output = [
  4329. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  4330. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  4331. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  4332. '5 OK Getquotaroot completed.'
  4333. ] ;
  4334. ok( $NUMBER_104_857_600 * $KIBI == quota_extract_storage_limit_in_bytes( $mysync, $imap_output ), 'quota_extract_storage_limit_in_bytes ') ;
  4335. note( 'Leaving tests_quota_extract_storage_limit_in_bytes()' ) ;
  4336. return ;
  4337. }
  4338. sub quota_extract_storage_limit_in_bytes
  4339. {
  4340. my $mysync = shift ;
  4341. my $imap_output = shift ;
  4342. my $limit_kb ;
  4343. $limit_kb = ( map { /.*\(\s*STORAGE\s+\d+\s+(\d+)\s*\)/x ? $1 : () } @{ $imap_output } )[0] ;
  4344. $limit_kb ||= 0 ;
  4345. $mysync->{ debug } and myprint( "storage_limit_kb = $limit_kb\n" ) ;
  4346. return( $KIBI * $limit_kb ) ;
  4347. }
  4348. sub tests_quota_extract_storage_current_in_bytes
  4349. {
  4350. note( 'Entering tests_quota_extract_storage_current_in_bytes()' ) ;
  4351. my $mysync = {} ;
  4352. my $imap_output = [
  4353. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  4354. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  4355. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  4356. '5 OK Getquotaroot completed.'
  4357. ] ;
  4358. ok( 1*$KIBI == quota_extract_storage_current_in_bytes( $mysync, $imap_output ), 'quota_extract_storage_current_in_bytes: 1 => 1024 ') ;
  4359. note( 'Leaving tests_quota_extract_storage_current_in_bytes()' ) ;
  4360. return ;
  4361. }
  4362. sub quota_extract_storage_current_in_bytes
  4363. {
  4364. my $mysync = shift ;
  4365. my $imap_output = shift ;
  4366. my $current_kb ;
  4367. $current_kb = ( map { /.*\(\s*STORAGE\s+(\d+)\s+\d+\s*\)/x ? $1 : () } @{ $imap_output } )[0] ;
  4368. $current_kb ||= 0 ;
  4369. $mysync->{ debug } and myprint( "storage_current_kb = $current_kb\n" ) ;
  4370. return( $KIBI * $current_kb ) ;
  4371. }
  4372. sub automap
  4373. {
  4374. my ( $mysync ) = @_ ;
  4375. if ( $mysync->{automap} ) {
  4376. myprint( "Turned on automapping folders ( use --noautomap to turn off automapping )\n" ) ;
  4377. }else{
  4378. myprint( "Turned off automapping folders ( use --automap to turn on automapping )\n" ) ;
  4379. return ;
  4380. }
  4381. $mysync->{h1_special} = special_from_folders_hash( $mysync, $mysync->{imap1}, 'Host1' ) ;
  4382. $mysync->{h2_special} = special_from_folders_hash( $mysync, $mysync->{imap2}, 'Host2' ) ;
  4383. build_possible_special( $mysync ) ;
  4384. build_guess_special( $mysync ) ;
  4385. build_automap( $mysync ) ;
  4386. return ;
  4387. }
  4388. sub build_guess_special
  4389. {
  4390. my ( $mysync ) = shift ;
  4391. foreach my $h1_fold ( sort keys %{ $mysync->{h1_folders_all} } ) {
  4392. my $special = guess_special( $h1_fold, $mysync->{possible_special}, $mysync->{h1_prefix} ) ;
  4393. if ( $special ) {
  4394. $mysync->{h1_special_guessed}{$h1_fold} = $special ;
  4395. my $already_guessed = $mysync->{h1_special_guessed}{$special} ;
  4396. if ( $already_guessed ) {
  4397. myprint( "Host1: $h1_fold not $special because set to $already_guessed\n" ) ;
  4398. }else{
  4399. $mysync->{h1_special_guessed}{$special} = $h1_fold ;
  4400. }
  4401. }
  4402. }
  4403. foreach my $h2_fold ( sort keys %{ $mysync->{h2_folders_all} } ) {
  4404. my $special = guess_special( $h2_fold, $mysync->{possible_special}, $mysync->{h2_prefix} ) ;
  4405. if ( $special ) {
  4406. $mysync->{h2_special_guessed}{$h2_fold} = $special ;
  4407. my $already_guessed = $mysync->{h2_special_guessed}{$special} ;
  4408. if ( $already_guessed ) {
  4409. myprint( "Host2: $h2_fold not $special because set to $already_guessed\n" ) ;
  4410. }else{
  4411. $mysync->{h2_special_guessed}{$special} = $h2_fold ;
  4412. }
  4413. }
  4414. }
  4415. return ;
  4416. }
  4417. sub guess_special
  4418. {
  4419. my( $folder, $possible_special_ref, $prefix ) = @_ ;
  4420. my $folder_no_prefix = $folder ;
  4421. $folder_no_prefix =~ s/\Q${prefix}\E//xms ;
  4422. #$debug and myprint( "folder_no_prefix: $folder_no_prefix\n" ) ;
  4423. my $guess_special = $possible_special_ref->{ $folder }
  4424. || $possible_special_ref->{ $folder_no_prefix }
  4425. || q{} ;
  4426. return( $guess_special ) ;
  4427. }
  4428. sub tests_guess_special
  4429. {
  4430. note( 'Entering tests_guess_special()' ) ;
  4431. my $possible_special_ref = build_possible_special( my $mysync ) ;
  4432. ok( '\Sent' eq guess_special( 'Sent', $possible_special_ref, q{} ) ,'guess_special: Sent => \Sent' ) ;
  4433. ok( q{} eq guess_special( 'Blabla', $possible_special_ref, q{} ) ,'guess_special: Blabla => q{}' ) ;
  4434. ok( '\Sent' eq guess_special( 'INBOX.Sent', $possible_special_ref, 'INBOX.' ) ,'guess_special: INBOX.Sent => \Sent' ) ;
  4435. ok( '\Sent' eq guess_special( 'IN BOX.Sent', $possible_special_ref, 'IN BOX.' ) ,'guess_special: IN BOX.Sent => \Sent' ) ;
  4436. note( 'Leaving tests_guess_special()' ) ;
  4437. return ;
  4438. }
  4439. sub build_automap
  4440. {
  4441. my $mysync = shift ;
  4442. $mysync->{ debug } and myprint( "Entering build_automap\n" ) ;
  4443. foreach my $h1_fold ( @{ $mysync->{h1_folders_wanted} } ) {
  4444. my $h2_fold ;
  4445. my $h1_special = $mysync->{h1_special}{$h1_fold} ;
  4446. my $h1_special_guessed = $mysync->{h1_special_guessed}{$h1_fold} ;
  4447. # Case 1: special on both sides.
  4448. if ( $h1_special
  4449. and exists $mysync->{h2_special}{$h1_special} ) {
  4450. $h2_fold = $mysync->{h2_special}{$h1_special} ;
  4451. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  4452. next ;
  4453. }
  4454. # Case 2: special on host1, not on host2
  4455. if ( $h1_special
  4456. and ( not exists $mysync->{h2_special}{$h1_special} )
  4457. and ( exists $mysync->{h2_special_guessed}{$h1_special} )
  4458. ) {
  4459. # special_guessed on host2
  4460. $h2_fold = $mysync->{h2_special_guessed}{$h1_special} ;
  4461. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  4462. next ;
  4463. }
  4464. # Case 3: no special on host1, special on host2
  4465. if ( ( not $h1_special )
  4466. and ( $h1_special_guessed )
  4467. and ( exists $mysync->{h2_special}{$h1_special_guessed} )
  4468. ) {
  4469. $h2_fold = $mysync->{h2_special}{$h1_special_guessed} ;
  4470. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  4471. next ;
  4472. }
  4473. # Case 4: no special on both sides.
  4474. if ( ( not $h1_special )
  4475. and ( $h1_special_guessed )
  4476. and ( not exists $mysync->{h2_special}{$h1_special_guessed} )
  4477. and ( exists $mysync->{h2_special_guessed}{$h1_special_guessed} )
  4478. ) {
  4479. $h2_fold = $mysync->{h2_special_guessed}{$h1_special_guessed} ;
  4480. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  4481. next ;
  4482. }
  4483. }
  4484. return( $mysync->{f1f2auto} ) ;
  4485. }
  4486. # I will not add what there is at:
  4487. # http://stackoverflow.com/questions/2185391/localized-gmail-imap-folders/2185548#2185548
  4488. # because it works well without
  4489. sub build_possible_special
  4490. {
  4491. my $mysync = shift ;
  4492. my $possible_special = { } ;
  4493. # All|Archive|Drafts|Flagged|Junk|Sent|Trash
  4494. $possible_special->{'\All'} = [ 'All', 'All Messages', '&BBIEQQQ1-' ] ;
  4495. $possible_special->{'\Archive'} = [ 'Archive', 'Archives', '&BBAEQARFBDgEMg-' ] ;
  4496. $possible_special->{'\Drafts'} = [ 'Drafts', 'DRAFTS', '&BCcENQRABD0EPgQyBDgEOgQ4-', 'Szkice', 'Wersje robocze' ] ;
  4497. $possible_special->{'\Flagged'} = [ 'Flagged', 'Starred', '&BB8EPgQ8BDUERwQ1BD0EPQRLBDU-' ] ;
  4498. $possible_special->{'\Junk'} = [ 'Junk', 'junk', 'Spam', 'SPAM', '&BCEEPwQwBDw-',
  4499. 'Potwierdzony spam', 'Wiadomo&AVs-ci-&AVs-mieci',
  4500. 'Junk E-Mail', 'Junk Email'] ;
  4501. $possible_special->{'\Sent'} = [ 'Sent', 'Sent Messages', 'Sent Items',
  4502. 'Gesendete Elemente', 'Gesendete Objekte',
  4503. '&AMk-l&AOk-ments envoy&AOk-s', 'E&AwE-le&AwE-ments envoye&AwE-s', 'Envoy&AOk-', 'Objets envoy&AOk-s',
  4504. 'Elementos enviados',
  4505. '&kAFP4W4IMH8wojCkMMYw4A-',
  4506. '&BB4EQgQ,BEAEMAQyBDsENQQ9BD0ESwQ1-',
  4507. 'Elementy wys&AUI-ane'] ;
  4508. $possible_special->{'\Trash'} = [ 'Trash', 'TRASH',
  4509. '&BCMENAQwBDsENQQ9BD0ESwQ1-', '&BBoEPgRABDcEOAQ9BDA-',
  4510. 'Kosz',
  4511. 'Deleted Items', 'Deleted Messages' ] ;
  4512. foreach my $special ( qw( \All \Archive \Drafts \Flagged \Junk \Sent \Trash ) ){
  4513. foreach my $possible_folder ( @{ $possible_special->{$special} } ) {
  4514. $possible_special->{ $possible_folder } = $special ;
  4515. } ;
  4516. }
  4517. $mysync->{possible_special} = $possible_special ;
  4518. $mysync->{ debug } and myprint( Data::Dumper->Dump( [ $possible_special ], [ 'possible_special' ] ) ) ;
  4519. return( $possible_special ) ;
  4520. }
  4521. sub tests_special_from_folders_hash
  4522. {
  4523. note( 'Entering tests_special_from_folders_hash()' ) ;
  4524. my $mysync = {} ;
  4525. require_ok( "Test::MockObject" ) ;
  4526. my $imapT = Test::MockObject->new( ) ;
  4527. is( undef, special_from_folders_hash( ), 'special_from_folders_hash: no args' ) ;
  4528. is( undef, special_from_folders_hash( $mysync ), 'special_from_folders_hash: undef args' ) ;
  4529. is_deeply( {}, special_from_folders_hash( $mysync, $imapT ), 'special_from_folders_hash: $imap void' ) ;
  4530. $imapT->mock( 'folders_hash', sub { return( [ { name => 'Sent', attrs => [ '\Sent' ] } ] ) } ) ;
  4531. is_deeply( { Sent => '\Sent', '\Sent' => 'Sent' },
  4532. special_from_folders_hash( $mysync, $imapT ), 'special_from_folders_hash: $imap \Sent' ) ;
  4533. note( 'Leaving tests_special_from_folders_hash()' ) ;
  4534. return( ) ;
  4535. }
  4536. sub special_from_folders_hash
  4537. {
  4538. my ( $mysync, $imap, $side ) = @_ ;
  4539. my %special = ( ) ;
  4540. if ( ! defined $imap ) { return ; }
  4541. $side = defined $side ? $side : 'Host?' ;
  4542. if ( ! $imap->can( 'folders_hash' ) ) {
  4543. my $error = "$side: To have automagic rfc6154 folder mapping, upgrade Mail::IMAPClient >= 3.34\n" ;
  4544. errors_incr( $mysync, $error ) ;
  4545. return( \%special ) ; # empty hash ref
  4546. }
  4547. my $folders_hash = $imap->folders_hash( ) ;
  4548. foreach my $fhash (@{ $folders_hash } ) {
  4549. my @special = grep { /\\(?:All|Archive|Drafts|Flagged|Junk|Sent|Trash)/x } @{ $fhash->{attrs} } ;
  4550. if ( @special ) {
  4551. my $special = $special[0] ; # keep first one. Could be not very good.
  4552. if ( exists $special{ $special } ) {
  4553. myprintf( "%s: special %-20s = %s already assigned to %s\n",
  4554. $side, $fhash->{name}, join( q{ }, @special ), $special{ $special } ) ;
  4555. }else{
  4556. myprintf( "%s: special %-20s = %s\n",
  4557. $side, $fhash->{name}, join( q{ }, @special ) ) ;
  4558. $special{ $special } = $fhash->{name} ;
  4559. $special{ $fhash->{name} } = $special ; # double entry value => key
  4560. }
  4561. }
  4562. }
  4563. myprint( "\n" ) if ( %special ) ;
  4564. return( \%special ) ;
  4565. }
  4566. sub tests_errors_log
  4567. {
  4568. note( 'Entering tests_errors_log()' ) ;
  4569. is( undef, errors_log( ), 'errors_log: no args => undef' ) ;
  4570. my $mysync = {} ;
  4571. is( undef, errors_log( $mysync ), 'errors_log: empty => undef' ) ;
  4572. is_deeply( [ 'aieaie' ], [ errors_log( $mysync, 'aieaie' ) ], 'errors_log: aieaie => aieaie' ) ;
  4573. # cumulative
  4574. is_deeply( [ 'aieaie' ], [ errors_log( $mysync ) ], 'errors_log: nothing more => aieaie' ) ;
  4575. is_deeply( [ 'aieaie', 'ouille' ], [ errors_log( $mysync, 'ouille' ) ], 'errors_log: ouille => aieaie ouille' ) ;
  4576. is_deeply( [ 'aieaie', 'ouille' ], [ errors_log( $mysync ) ], 'errors_log: nothing more => aieaie ouille' ) ;
  4577. note( 'Leaving tests_errors_log()' ) ;
  4578. return ;
  4579. }
  4580. sub errors_log
  4581. {
  4582. my ( $mysync, @error ) = @ARG ;
  4583. if ( ! $mysync->{errors_log} ) {
  4584. $mysync->{errors_log} = [] ;
  4585. }
  4586. if ( @error ) {
  4587. push @{ $mysync->{errors_log} }, join( q{}, @error ) ;
  4588. }
  4589. if ( @{ $mysync->{errors_log} } ) {
  4590. return @{ $mysync->{errors_log} } ;
  4591. }
  4592. else {
  4593. return ;
  4594. }
  4595. }
  4596. sub tests_comment_of_error_type
  4597. {
  4598. note( 'Entering tests_comment_of_error_type()' ) ;
  4599. is( undef, comment_of_error_type( ), 'comment_of_error_type: no args => undef' ) ;
  4600. my $mysync = { } ;
  4601. is( undef, comment_of_error_type( $mysync ), 'comment_of_error_type: undef => undef' ) ;
  4602. is( "", comment_of_error_type( $mysync, '' ), 'comment_of_error_type: "" => ""' ) ;
  4603. is( "", comment_of_error_type( $mysync, 'blabla' ), 'comment_of_error_type: blabla => ""' ) ;
  4604. is( "", comment_of_error_type( $mysync, 'ERR_UNCLASSIFIED' ), 'comment_of_error_type: ERR_UNCLASSIFIED => ""' ) ;
  4605. like( comment_of_error_type( $mysync, 'ERR_OVERQUOTA' ), qr{100% full}, 'comment_of_error_type: ERR_OVERQUOTA => matches 100% full' ) ;
  4606. note( 'Leaving tests_comment_of_error_type()' ) ;
  4607. return ;
  4608. }
  4609. sub comment_of_error_type
  4610. {
  4611. my $mysync = shift @ARG ;
  4612. my $error_type = shift @ARG ;
  4613. if ( ! defined $mysync ) { return ; }
  4614. if ( ! defined $error_type ) { return ; }
  4615. my $comment ;
  4616. if ( exists( $COMMENT_OF_ERR_TYPE{ $error_type } ) )
  4617. {
  4618. $comment = $COMMENT_OF_ERR_TYPE{ $error_type }->( $mysync ) ;
  4619. }
  4620. else
  4621. {
  4622. $comment = "" ;
  4623. }
  4624. return $comment ;
  4625. }
  4626. sub tests_error_type
  4627. {
  4628. note( 'Entering tests_error_type()' ) ;
  4629. is( 'ERR_NOTHING_REPORTED', error_type( ), 'error_type: no args => ERR_NOTHING_REPORTED' ) ;
  4630. is( 'ERR_NOTHING_REPORTED', error_type( '' ), 'error_type: empty string => ERR_NOTHING_REPORTED' ) ;
  4631. is( 'ERR_UNCLASSIFIED', error_type( 'ERR_UNCLASSIFIED' ), 'error_type: ERR_UNCLASSIFIED => ERR_UNCLASSIFIED' ) ;
  4632. is( 'ERR_UNCLASSIFIED', error_type( 'aie' ), 'error_type: aie => ERR_UNCLASSIFIED' ) ;
  4633. is( 'ERR_UNCLASSIFIED', error_type( 'ouille' ), 'error_type: ouille => ERR_UNCLASSIFIED' ) ;
  4634. is( 'ERR_Host1_FETCH', error_type( 'Message xxx could not be fetched: blabla' ),
  4635. 'error_type: could not be fetched => ERR_Host1_FETCH'
  4636. ) ;
  4637. is( 'ERR_APPEND_SIZE',
  4638. error_type( 'could not append message xxx: BAD maximum message size exceeded' ),
  4639. 'error_type: could not append message xxx: BAD maximum message size exceeded => ERR_APPEND_SIZE'
  4640. ) ;
  4641. is( 'ERR_OVERQUOTA',
  4642. error_type( 'Quota limit will be exceeded' ),
  4643. 'error_type: Quota limit will be exceeded => ERR_OVERQUOTA'
  4644. ) ;
  4645. is( 'ERR_APPEND', error_type( 'could not append' ), 'error_type: could not append => ERR_APPEND' ) ;
  4646. is( 'ERR_CREATE',
  4647. error_type( 'Could not create folder' ),
  4648. 'error_type: Could not create folder => ERR_CREATE'
  4649. ) ;
  4650. is( 'ERR_SELECT',
  4651. error_type( 'Could not select: blabla' ),
  4652. 'error_type: Could not select: blabla => ERR_SELECT'
  4653. ) ;
  4654. #
  4655. #Maximum bytes transferred reached, 423 >= 100, ending sync
  4656. is( 'ERR_TRANSFER_EXCEEDED',
  4657. error_type( 'Maximum bytes transferred reached, blabla' ),
  4658. 'error_type: Maximum bytes transferred reached, blabla => ERR_TRANSFER_EXCEEDED'
  4659. ) ;
  4660. #
  4661. is( 'ERR_CONNECTION_FAILURE_HOST1',
  4662. error_type( 'Host1 failure: can not open imap connection on host1 [badhostkaka] with user [tata]: Unable to connect to badhostkaka: Invalid argument' ),
  4663. 'error_type: can not open imap connection on host1 => ERR_CONNECTION_FAILURE_HOST1'
  4664. ) ;
  4665. is( 'ERR_CONNECTION_FAILURE_HOST2',
  4666. error_type( 'Host2 failure: can not open imap connection on host2 [badhostkiki] with user [titi]: Unable to connect to badhostkiki: Invalid argument' ),
  4667. 'error_type: can not open imap connection on host2 => ERR_CONNECTION_FAILURE_HOST2'
  4668. ) ;
  4669. is( 'ERR_APPEND_VIRUS',
  4670. 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' ),
  4671. 'error_type: could not append ... virus => ERR_APPEND_VIRUS'
  4672. ) ;
  4673. is( 'ERR_FLAGS',
  4674. error_type( 'Host2: flags msg INBOX/957910 could not add flags [PasGlop \PasGlopRe]: 33 NO Error in IMAP command received by server.' ),
  4675. 'error_type: could not add flags => ERR_FLAGS'
  4676. ) ;
  4677. note( 'Leaving tests_error_type()' ) ;
  4678. return ;
  4679. }
  4680. # Could be implemented with https://metacpan.org/pod/Tie::RegexpHash
  4681. # with just a hash of error regexes as keys and types as values.
  4682. sub error_type
  4683. {
  4684. my $error = shift ;
  4685. if ( ! defined $error ) { return 'ERR_NOTHING_REPORTED' ; }
  4686. if ( ! $error ) { return 'ERR_NOTHING_REPORTED' ; }
  4687. #
  4688. if ( $error =~ m{Host1 failure: Error login on} ) { return 'ERR_AUTHENTICATION_FAILURE_USER1' } ;
  4689. if ( $error =~ m{Host2 failure: Error login on} ) { return 'ERR_AUTHENTICATION_FAILURE_USER2' } ;
  4690. if ( $error =~ m{Host. failure: Can not go to tls encryption on host.} ) { return 'ERR_EXIT_TLS_FAILURE' } ;
  4691. #
  4692. if ( $error =~ m{could not be fetched:} ) { return 'ERR_Host1_FETCH' } ;
  4693. # could not append .*BAD maximum message size exceeded
  4694. # could not append.*Maximum size of appendable message has been exceeded
  4695. if ( $error =~ m{could not append .*BAD maximum message size exceeded} )
  4696. { return 'ERR_APPEND_SIZE' ; } ;
  4697. if ( $error =~ m{could not append.*Maximum size of appendable message has been exceeded} )
  4698. { return 'ERR_APPEND_SIZE' ; } ;
  4699. # Could not create folder *[OVERQUOTA] Not enough disk quota
  4700. # could not append .*[OVERQUOTA] Not enough disk quota
  4701. # could not append .*[OVERQUOTA] Mailbox is full / Blocks limit exceeded / Inode limit exceeded
  4702. if ( $error =~ m{OVERQUOTA} ) { return 'ERR_OVERQUOTA' ; } ;
  4703. if ( $error =~ m{Quota limit will be exceeded} ) { return 'ERR_OVERQUOTA' ; } ;
  4704. if ( $error =~ m{full: it is time to find a bigger place} ) { return 'ERR_OVERQUOTA' ; } ;
  4705. # could not append ... to folder INBOX: 276 NO Message refused because it contains a virus
  4706. if ( $error =~ m{could not append.*virus} )
  4707. { return 'ERR_APPEND_VIRUS' ; } ;
  4708. # could not append .*Write failed 'Broken pipe'
  4709. # could not append .*timeout waiting .* for data from server
  4710. # could not append .*BAD Invalid Arguments: Unable to parse message
  4711. # could not append .*BAD Command Argument Error. 11
  4712. # could not append .*NO header limit reached
  4713. if ( $error =~ m{could not append} ) { return 'ERR_APPEND' ; } ;
  4714. # could not add flags
  4715. if ( $error =~ m{could not add flags} ) { return 'ERR_FLAGS' ; } ;
  4716. # Could not create folder .*Invalid mailbox name
  4717. if ( $error =~ m{Could not create folder} ) { return 'ERR_CREATE' ; } ;
  4718. # Could not select:.*NO [NOPERM] Permission denied
  4719. # Could not select:.*NO Mailbox doesn't exist
  4720. # Could not select:.*NO [SERVERBUG] Internal error occurred.
  4721. # Could not select:.*[CANNOT] Mailbox isn't a valid mbox file
  4722. if ( $error =~ m{Could not select:} ) { return 'ERR_SELECT' ; } ;
  4723. #Maximum bytes transferred reached, 423 >= 100, ending sync
  4724. if ( $error =~ m{Maximum bytes transferred reached} ) { return 'ERR_TRANSFER_EXCEEDED' ; } ;
  4725. if ( $error =~ m{can not open imap connection on host1} ) { return 'ERR_CONNECTION_FAILURE_HOST1' ; } ;
  4726. if ( $error =~ m{can not open imap connection on host2} ) { return 'ERR_CONNECTION_FAILURE_HOST2' ; } ;
  4727. # Default is ERR_UNCLASSIFIED
  4728. return 'ERR_UNCLASSIFIED' ;
  4729. }
  4730. sub tests_errorclassify
  4731. {
  4732. note( 'Entering tests_errorclassify()' ) ;
  4733. is( undef, errorclassify( ), 'errorclassify: no args => undef' ) ;
  4734. is_deeply( { 'ERR_UNCLASSIFIED' => 1 }, errorclassify( 'aie' ), 'errorclassify: aie => { ERR_UNCLASSIFIED => 1 }' ) ;
  4735. is_deeply( { 'ERR_UNCLASSIFIED' => 2 }, errorclassify( 'aie', 'ouille' ), 'errorclassify: aie ouille => { ERR_UNCLASSIFIED => 2 }' ) ;
  4736. is_deeply( { 'ERR_UNCLASSIFIED' => 2, 'ERR_NOTHING_REPORTED' => 1 }, errorclassify( 'aie', 'ouille', '' ), 'errorclassify: aie ouille "" => { ERR_UNCLASSIFIED => 2 }' ) ;
  4737. is_deeply( { 'ERR_UNCLASSIFIED' => 3 }, errorclassify( 'aie', 'ouille', 'aie' ), 'errorclassify: aie ouille aie => { ERR_UNCLASSIFIED => 3 }' ) ;
  4738. is_deeply( { 'ERR_UNCLASSIFIED' => 1, 'ERR_OVERQUOTA' => 2 }, errorclassify( 'aie', 'OVERQUOTA pipi', 'OVERQUOTA caca' ), 'errorclassify: aie OVERQUOTA OVERQUOTA' ) ;
  4739. is_deeply( { 'ERR_NOTHING_REPORTED' => 1 }, errorclassify( '' ), 'errorclassify: "" => { ERR_NOTHING_REPORTED => 1 }' ) ;
  4740. is_deeply( { 'ERR_NOTHING_REPORTED' => 2 }, errorclassify( '', '' ), 'errorclassify: "", "" => { ERR_NOTHING_REPORTED => 1 }' ) ;
  4741. note( 'Leaving tests_errorclassify()' ) ;
  4742. return ;
  4743. }
  4744. sub errorclassify
  4745. {
  4746. my @errors = @ARG ;
  4747. if ( ! @errors ) { return ; } ;
  4748. my $error_type_count = { } ;
  4749. foreach my $error ( @errors )
  4750. {
  4751. my $error_type = error_type( $error ) ;
  4752. $error_type_count->{ $error_type }++ ;
  4753. }
  4754. return $error_type_count ;
  4755. }
  4756. sub tests_most_common_error
  4757. {
  4758. note( 'Entering tests_most_common_error()' ) ;
  4759. is( 'ERR_NOTHING_REPORTED', most_common_error( ), 'most_common_error: no args => ERR_NOTHING_REPORTED' ) ;
  4760. is( 'ERR_NOTHING_REPORTED', most_common_error( {} ), 'most_common_error: empty hash ref => ERR_NOTHING_REPORTED' ) ;
  4761. is( 'ERR_NOTHING_REPORTED', most_common_error( 'blabla' ), 'most_common_error: not a hash ref => ERR_NOTHING_REPORTED' ) ;
  4762. is( 'ERR_FOO', most_common_error( { ERR_FOO => 1 } ), 'most_common_error: { ERR_FOO => 1 } => ERR_FOO' ) ;
  4763. is( 'ERR_BAR', most_common_error( { ERR_FOO => 1, ERR_BAR => 2 } ), 'most_common_error: { ERR_FOO => 1, ERR_BAR => 2 } => ERR_BAR' ) ;
  4764. is( 'ERR_FOO', most_common_error( { ERR_FOO => 2, ERR_BAR => 1 } ), 'most_common_error: { ERR_FOO => 2, ERR_BAR => 1 } => ERR_FOO' ) ;
  4765. # exaequo => first lexical wins. ERR_BAR <= ERR_FOO
  4766. is( 'ERR_BAR', most_common_error( { ERR_FOO => 2, ERR_BAR => 2 } ), 'most_common_error: { ERR_FOO => 2, ERR_BAR => 2 } => ERR_BAR' ) ;
  4767. is( 'A', most_common_error( { A => 5, B => 5, C => 5 } ), 'most_common_error: { A => 5, B => 5, C => 5 } => A' ) ;
  4768. is( 'B', most_common_error( { A => 5, B => 6, C => 6 } ), 'most_common_error: { A => 5, B => 6, C => 6 } => B' ) ;
  4769. is( 'C', most_common_error( { A => 5, B => 5, C => 7 } ), 'most_common_error: { A => 5, B => 5, C => 7 } => C' ) ;
  4770. is( 'C', most_common_error( { A => 5, B => 6, C => 7 } ), 'most_common_error: { A => 5, B => 5, C => 7 } => C' ) ;
  4771. note( 'Leaving tests_most_common_error()' ) ;
  4772. return ;
  4773. }
  4774. sub most_common_error
  4775. {
  4776. my $errors_counted_ref = shift ;
  4777. if ( ! defined $errors_counted_ref ) { return 'ERR_NOTHING_REPORTED' ; }
  4778. if ( 'HASH' ne ref $errors_counted_ref ) { return 'ERR_NOTHING_REPORTED' ; }
  4779. # empty hash
  4780. if ( !%{ $errors_counted_ref } ) { return 'ERR_NOTHING_REPORTED' ; }
  4781. # non empty hash
  4782. # in case of equality the winner error is the first in alphabetic order
  4783. my $most_common_error = ( sort
  4784. {
  4785. $errors_counted_ref->{$b} <=> $errors_counted_ref->{$a}
  4786. || $a cmp $b
  4787. } keys %{$errors_counted_ref} )[0] ;
  4788. return $most_common_error ;
  4789. }
  4790. sub tests_errorsanalyse
  4791. {
  4792. note( 'Entering tests_errorsanalyse()' ) ;
  4793. is( 'ERR_NOTHING_REPORTED', errorsanalyse( ), 'errorsanalyse: no args => ERR_NOTHING_REPORTED' ) ;
  4794. is( 'ERR_NOTHING_REPORTED', errorsanalyse( ( ) ), 'errorsanalyse: empty list => ERR_NOTHING_REPORTED' ) ;
  4795. is( 'ERR_UNCLASSIFIED', errorsanalyse( 'aie' ), 'errorsanalyse: aie => ERR_UNCLASSIFIED' ) ;
  4796. # in case of equality, empty wins
  4797. is( 'ERR_NOTHING_REPORTED', errorsanalyse( 'aie', '' ), 'errorsanalyse: aie => ERR_UNCLASSIFIED' ) ;
  4798. is( 'ERR_NOTHING_REPORTED', errorsanalyse( '', 'aie' ), 'errorsanalyse: aie => ERR_UNCLASSIFIED' ) ;
  4799. is( 'ERR_UNCLASSIFIED', errorsanalyse( 'aie', 'ouille' ), 'errorsanalyse: aie, ouille => ERR_UNCLASSIFIED' ) ;
  4800. is( 'ERR_UNCLASSIFIED', errorsanalyse( 'aie', 'ouille', '' ), 'errorsanalyse: aie, ouille, "" => ERR_UNCLASSIFIED' ) ;
  4801. is( 'ERR_UNCLASSIFIED', errorsanalyse( '', 'aie', 'ouille' ), 'errorsanalyse: aie, ouille, "" => ERR_UNCLASSIFIED' ) ;
  4802. is( 'ERR_NOTHING_REPORTED', errorsanalyse( '' ), 'errorsanalyse: "" => ERR_NOTHING_REPORTED' ) ;
  4803. is( 'ERR_NOTHING_REPORTED', errorsanalyse( ( '' ) ), 'errorsanalyse: ( "" ) => ERR_NOTHING_REPORTED' ) ;
  4804. is( 'ERR_NOTHING_REPORTED', errorsanalyse( ( '', '' ) ), 'errorsanalyse: ( "", "" ) => ERR_NOTHING_REPORTED' ) ;
  4805. note( 'Leaving tests_errorsanalyse()' ) ;
  4806. return ;
  4807. }
  4808. sub errorsanalyse
  4809. {
  4810. my @errors = @ARG ;
  4811. my $errors_types_counted = errorclassify( @errors ) ;
  4812. my $most_common_error = most_common_error( $errors_types_counted ) ;
  4813. return $most_common_error ;
  4814. }
  4815. sub tests_errorsdump
  4816. {
  4817. note( 'Entering tests_errorsdump()' ) ;
  4818. is( undef, errorsdump( ), 'errorsdump: no args => undef' ) ;
  4819. is( undef, errorsdump( ( ) ), 'errorsdump: empty list => undef' ) ;
  4820. is( "Err 1/1: ", errorsdump( '' ), 'errorsdump: one empty string => "Err 1/1: "' ) ;
  4821. is( "Err 1/1: aieaieaie", errorsdump( 'aieaieaie' ), 'errorsdump: aieaieaie => "Err 1/1: aieaieaie"' ) ;
  4822. is( "Err 1/2: Aie Err 2/2: Ouille", errorsdump( 'Aie ', 'Ouille' ), 'errorsdump: Aie Ouille => "Err 1/2: Aie Err 2/2: Ouille"' ) ;
  4823. note( 'Leaving tests_errorsdump()' ) ;
  4824. return ;
  4825. }
  4826. sub errorsdump
  4827. {
  4828. if ( ! @ARG ) { return ; }
  4829. my @errors_log = @ARG ;
  4830. my $nb_errors = @errors_log ;
  4831. my $error_num = 0 ;
  4832. my $errors_list = q{} ;
  4833. if ( @errors_log ) {
  4834. foreach my $error ( @errors_log )
  4835. {
  4836. $error_num++ ;
  4837. $errors_list .= "Err $error_num/$nb_errors: $error" ;
  4838. }
  4839. }
  4840. return( $errors_list ) ;
  4841. }
  4842. sub errors_listing
  4843. {
  4844. my $mysync = shift ;
  4845. $mysync->{ most_common_error } = errorsanalyse( errors_log( $mysync ) ) ;
  4846. my $errors_listing = '' ;
  4847. if ( $mysync->{ errorsdump } )
  4848. {
  4849. $errors_listing = join( '',
  4850. "++++ Listing $mysync->{nb_errors} errors encountered during the sync ( avoid this listing with --noerrorsdump ).\n",
  4851. errorsdump( errors_log( $mysync ) ),
  4852. ) ;
  4853. }
  4854. $errors_listing .= join( '',
  4855. "The most frequent error is $mysync->{ most_common_error }. ",
  4856. comment_of_error_type( $mysync, $mysync->{ most_common_error } ),
  4857. "\n",
  4858. ) ;
  4859. return $errors_listing ;
  4860. }
  4861. sub errors_incr
  4862. {
  4863. my ( $mysync, @error ) = @ARG ;
  4864. $mysync->{ nb_errors }++ ;
  4865. if ( @error ) {
  4866. errors_log( $mysync, @error ) ;
  4867. myprint( @error ) ;
  4868. }
  4869. $mysync->{ errorsmax } ||= $ERRORS_MAX ;
  4870. if ( $mysync->{ nb_errors } >= $mysync->{ errorsmax } )
  4871. {
  4872. myprint( errorsmax_msg( $mysync ) ) ;
  4873. myprint( errors_listing( $mysync ) ) ;
  4874. if ( $mysync->{ errorsdump } )
  4875. {
  4876. # again since errorsdump( ) can be very verbose and masquerade previous warning
  4877. myprint( errorsmax_msg( $mysync ) ) ;
  4878. }
  4879. my $exit_value = exit_value( $mysync, $mysync->{ most_common_error } ) ;
  4880. exit_clean( $mysync, $exit_value ) ;
  4881. }
  4882. return ;
  4883. }
  4884. sub errorsmax_msg
  4885. {
  4886. my $mysync = shift @ARG ;
  4887. my $msg = "Maximum number of errors $mysync->{errorsmax} reached "
  4888. . "( you can change $mysync->{errorsmax} to any value, for example 100 with --errorsmax 100 ). "
  4889. . "Exiting.\n" ;
  4890. return $msg ;
  4891. }
  4892. sub tests_live_result
  4893. {
  4894. note( 'Entering tests_live_result()' ) ;
  4895. my $nb_errors = shift ;
  4896. if ( $nb_errors ) {
  4897. myprint( "Live tests failed with $nb_errors errors\n" ) ;
  4898. } else {
  4899. myprint( "Live tests ended successfully\n" ) ;
  4900. }
  4901. note( 'Leaving tests_live_result()' ) ;
  4902. return ;
  4903. }
  4904. sub size_filtered_flag
  4905. {
  4906. my $mysync = shift ;
  4907. my $h1_size = shift ;
  4908. if ( defined $mysync->{ maxsize } and $h1_size >= $mysync->{ maxsize } ) {
  4909. return( 1 ) ;
  4910. }
  4911. if ( defined $minsize and $h1_size <= $minsize ) {
  4912. return( 1 ) ;
  4913. }
  4914. return( 0 ) ;
  4915. }
  4916. sub sync_flags_fir
  4917. {
  4918. my ( $mysync, $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) = @_ ;
  4919. if ( not defined $h1_msg ) { return } ;
  4920. if ( not defined $h2_msg ) { return } ;
  4921. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} ;
  4922. return if size_filtered_flag( $mysync, $h1_size ) ;
  4923. # used cached flag values for efficiency
  4924. my $h1_flags = $h1_fir_ref->{ $h1_msg }->{ 'FLAGS' } || q{} ;
  4925. my $h2_flags = $h2_fir_ref->{ $h2_msg }->{ 'FLAGS' } || q{} ;
  4926. sync_flags( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  4927. return ;
  4928. }
  4929. sub sync_flags_after_copy
  4930. {
  4931. # Activated with option --syncflagsaftercopy
  4932. my( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $permanentflags2 ) = @_ ;
  4933. if ( my @h2_flags = $mysync->{imap2}->flags( $h2_msg ) ) {
  4934. my $h2_flags = "@h2_flags" ;
  4935. ( $mysync->{ debug } or $debugflags ) and myprint( "Host2: msg $h2_fold/$h2_msg flags before sync flags after copy ( $h2_flags )\n" ) ;
  4936. sync_flags( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  4937. }else{
  4938. myprint( "Host2: msg $h2_fold/$h2_msg could not get its flags for sync flags after copy\n" ) ;
  4939. }
  4940. return ;
  4941. }
  4942. # Globals
  4943. # $debug
  4944. # $debugflags
  4945. # $permanentflags2
  4946. sub sync_flags
  4947. {
  4948. my( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) = @_ ;
  4949. ( $mysync->{ debug } or $debugflags ) and
  4950. myprint( "Host1: flags init msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 msg $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  4951. $h1_flags = flags_for_host2( $mysync, $h1_flags, $permanentflags2 ) ;
  4952. $h2_flags = flagscase( $h2_flags ) ;
  4953. ( $mysync->{ debug } or $debugflags ) and
  4954. myprint( "Host1: flags filt msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 msg $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  4955. # compare flags - set flags if there a difference
  4956. my @h1_flags = sort split(q{ }, $h1_flags );
  4957. my @h2_flags = sort split(q{ }, $h2_flags );
  4958. my $diff = compare_lists( \@h1_flags, \@h2_flags );
  4959. $diff and ( $mysync->{ debug } or $debugflags )
  4960. and myprint( "Host2: flags msg $h2_fold/$h2_msg replacing h2 flags( $h2_flags ) with h1 flags( $h1_flags )\n" ) ;
  4961. # This sets flags exactly. So flags can be removed with this.
  4962. # When you remove a \Seen flag on host1 you want it
  4963. # to be removed on host2. Just add flags is not what
  4964. # we need most of the time, so no + like in "+FLAGS.SILENT".
  4965. if ( not $mysync->{dry} and $diff and not $mysync->{imap2}->store( $h2_msg, "FLAGS.SILENT (@h1_flags)" ) ) {
  4966. my $error_msg = join q{}, "Host2: flags msg $h2_fold/$h2_msg could not add flags [@h1_flags]: ",
  4967. $mysync->{imap2}->LastError || q{}, "\n" ;
  4968. errors_incr( $mysync, $error_msg ) ;
  4969. }
  4970. return ;
  4971. }
  4972. sub _filter
  4973. {
  4974. my $mysync = shift ;
  4975. my $str = shift or return q{} ;
  4976. my $sz = $SIZE_MAX_STR ;
  4977. my $len = length $str ;
  4978. if ( not $mysync->{ debug } and $len > $sz*2 ) {
  4979. my $beg = substr $str, 0, $sz ;
  4980. my $end = substr $str, -$sz, $sz ;
  4981. $str = $beg . '...' . $end ;
  4982. }
  4983. $str =~ s/\012?\015$//x ;
  4984. return "(len=$len) " . $str ;
  4985. }
  4986. sub lost_connection
  4987. {
  4988. my( $mysync, $imap, $error_message ) = @_;
  4989. if ( $imap->IsUnconnected( ) ) {
  4990. $mysync->{nb_errors}++ ;
  4991. my $lcomm = $imap->LastIMAPCommand || q{} ;
  4992. my $einfo = imap_last_error( $imap ) ;
  4993. # if string is long try reduce to a more reasonable size
  4994. $lcomm = _filter( $mysync, $lcomm ) ;
  4995. $einfo = _filter( $mysync, $einfo ) ;
  4996. myprint( "Failure: last command: $lcomm\n") if ( $mysync->{ debug } && $lcomm) ;
  4997. myprint( "Failure: lost connection $error_message: ", $einfo, "\n") ;
  4998. return( 1 ) ;
  4999. }
  5000. else{
  5001. return( 0 ) ;
  5002. }
  5003. }
  5004. sub imap_last_error
  5005. {
  5006. my $imap = shift ;
  5007. my $einfo = $imap->LastError || @{$imap->History}[$LAST] || q{} ;
  5008. chomp( $einfo ) ;
  5009. return( $einfo ) ;
  5010. }
  5011. sub tests_max
  5012. {
  5013. note( 'Entering tests_max()' ) ;
  5014. is( 0, max( 0 ), 'max 0 => 0' ) ;
  5015. is( 1, max( 1 ), 'max 1 => 1' ) ;
  5016. is( $MINUS_ONE, max( $MINUS_ONE ), 'max -1 => -1') ;
  5017. is( undef, max( ), 'max no arg => undef' ) ;
  5018. is( undef, max( undef ), 'undef => undef' ) ;
  5019. is( undef, max( undef, undef ), 'undef, undef => undef' ) ;
  5020. is( $NUMBER_100, max( 1, $NUMBER_100 ), 'max 1 100 => 100' ) ;
  5021. is( $NUMBER_100, max( $NUMBER_100, 1 ), 'max 100 1 => 100' ) ;
  5022. is( $NUMBER_100, max( $NUMBER_100, $NUMBER_42, 1 ), 'max 100 42 1 => 100' ) ;
  5023. is( $NUMBER_100, max( $NUMBER_100, '42', 1 ), 'max 100 42 1 => 100' ) ;
  5024. is( $NUMBER_100, max( '100', '42', 1 ), 'max 100 42 1 => 100' ) ;
  5025. is( $NUMBER_100, max( $NUMBER_100, 'haha', 1 ), 'max 100 haha 1 => 100') ;
  5026. is( $NUMBER_100, max( 'bb', $NUMBER_100, 'haha' ), 'max bb 100 haha => 100') ;
  5027. is( $MINUS_ONE, max( q{}, $MINUS_ONE, 'haha' ), 'max "" -1 haha => -1') ;
  5028. is( $MINUS_ONE, max( q{}, $MINUS_ONE, $MINUS_TWO ), 'max "" -1 -2 => -1') ;
  5029. is( $MINUS_ONE, max( 'haha', $MINUS_ONE, $MINUS_TWO ), 'max haha -1 -2 => -1') ;
  5030. is( 1, max( $MINUS_ONE, 1 ), 'max -1 1 => 1') ;
  5031. is( 1, max( undef, 1 ), 'max undef 1 => 1' ) ;
  5032. is( 0, max( undef, 0 ), 'max undef 0 => 0' ) ;
  5033. is( 'haha', max( 'haha' ), 'max haha => haha') ;
  5034. is( 'bb', max( 'aa', 'bb' ), 'max aa bb => bb') ;
  5035. is( 'bb', max( 'bb', 'aa' ), 'max bb aa => bb') ;
  5036. is( 'bb', max( 'bb', 'aa', 'bb' ), 'max bb aa bb => bb') ;
  5037. note( 'Leaving tests_max()' ) ;
  5038. return ;
  5039. }
  5040. sub max
  5041. {
  5042. my @list = @_ ;
  5043. return( undef ) if ( 0 == scalar @list ) ;
  5044. my( @numbers, @notnumbers ) ;
  5045. foreach my $item ( @list )
  5046. {
  5047. if ( is_number( $item ) )
  5048. {
  5049. push @numbers, $item ;
  5050. }
  5051. elsif ( defined $item )
  5052. {
  5053. push @notnumbers, $item ;
  5054. }
  5055. }
  5056. my @sorted ;
  5057. if ( @numbers )
  5058. {
  5059. @sorted = sort { $a <=> $b } @numbers ;
  5060. }
  5061. elsif ( @notnumbers )
  5062. {
  5063. @sorted = sort { $a cmp $b } @notnumbers ;
  5064. }
  5065. else
  5066. {
  5067. return ;
  5068. }
  5069. return( pop @sorted ) ;
  5070. }
  5071. sub tests_is_number
  5072. {
  5073. note( 'Entering tests_is_number()' ) ;
  5074. is( undef, is_number( ), 'is_number: no args => undef ' ) ;
  5075. is( undef, is_number( undef ), 'is_number: undef => undef ' ) ;
  5076. ok( is_number( 1 ), 'is_number: 1 => 1' ) ;
  5077. ok( is_number( 1.1 ), 'is_number: 1.1 => 1' ) ;
  5078. ok( is_number( 0 ), 'is_number: 0 => 1' ) ;
  5079. ok( is_number( -1 ), 'is_number: -1 => 1' ) ;
  5080. ok( ! is_number( 1.1.1 ), 'is_number: 1.1.1 => no' ) ;
  5081. ok( ! is_number( q{} ), 'is_number: q{} => no' ) ;
  5082. ok( ! is_number( 'haha' ), 'is_number: haha => no' ) ;
  5083. ok( ! is_number( '0haha' ), 'is_number: 0haha => no' ) ;
  5084. ok( ! is_number( '2haha' ), 'is_number: 2haha => no' ) ;
  5085. ok( ! is_number( 'haha2' ), 'is_number: haha2 => no' ) ;
  5086. note( 'Leaving tests_is_number()' ) ;
  5087. return ;
  5088. }
  5089. sub is_number
  5090. {
  5091. my $item = shift ;
  5092. if ( ! defined $item ) { return ; }
  5093. if ( $item =~ /\A$RE{num}{real}\Z/ ) {
  5094. return 1 ;
  5095. }
  5096. return ;
  5097. }
  5098. sub tests_min
  5099. {
  5100. note( 'Entering tests_min()' ) ;
  5101. is( 0, min( 0 ), 'min 0 => 0' ) ;
  5102. is( 1, min( 1 ), 'min 1 => 1' ) ;
  5103. is( $MINUS_ONE, min( $MINUS_ONE ), 'min -1 => -1' ) ;
  5104. is( undef, min( ), 'min no arg => undef' ) ;
  5105. is( 1, min( 1, $NUMBER_100 ), 'min 1 100 => 1' ) ;
  5106. is( 1, min( $NUMBER_100, 1 ), 'min 100 1 => 1' ) ;
  5107. is( 1, min( $NUMBER_100, $NUMBER_42, 1 ), 'min 100 42 1 => 1' ) ;
  5108. is( 1, min( $NUMBER_100, '42', 1 ), 'min 100 42 1 => 1' ) ;
  5109. is( 1, min( '100', '42', 1 ), 'min 100 42 1 => 1' ) ;
  5110. is( 1, min( $NUMBER_100, 'haha', 1 ), 'min 100 haha 1 => 1') ;
  5111. is( $MINUS_ONE, min( $MINUS_ONE, 1 ), 'min -1 1 => -1') ;
  5112. is( 1, min( undef, 1 ), 'min undef 1 => 1' ) ;
  5113. is( 0, min( undef, 0 ), 'min undef 0 => 0' ) ;
  5114. is( 1, min( undef, 1 ), 'min undef 1 => 1' ) ;
  5115. is( 0, min( undef, 2, 0, 1 ), 'min undef, 2, 0, 1 => 0' ) ;
  5116. is( 'haha', min( 'haha' ), 'min haha => haha') ;
  5117. is( 'aa', min( 'aa', 'bb' ), 'min aa bb => aa') ;
  5118. is( 'aa', min( 'bb', 'aa' ), 'min bb aa bb => aa') ;
  5119. is( 'aa', min( 'bb', 'aa', 'bb' ), 'min bb aa bb => aa') ;
  5120. note( 'Leaving tests_min()' ) ;
  5121. return ;
  5122. }
  5123. sub min
  5124. {
  5125. my @list = @_ ;
  5126. return( undef ) if ( 0 == scalar @list ) ;
  5127. my( @numbers, @notnumbers ) ;
  5128. foreach my $item ( @list ) {
  5129. if ( is_number( $item ) ) {
  5130. push @numbers, $item ;
  5131. }else{
  5132. push @notnumbers, $item ;
  5133. }
  5134. }
  5135. my @sorted ;
  5136. if ( @numbers ) {
  5137. @sorted = sort { $a <=> $b } @numbers ;
  5138. }elsif( @notnumbers ) {
  5139. @sorted = sort { $a cmp $b } @notnumbers ;
  5140. }else{
  5141. return ;
  5142. }
  5143. return( shift @sorted ) ;
  5144. }
  5145. sub check_lib_version
  5146. {
  5147. my $mysync = shift ;
  5148. $mysync->{ debug } and myprint( "IMAPClient $Mail::IMAPClient::VERSION\n" ) ;
  5149. if ( '2.2.9' eq $Mail::IMAPClient::VERSION ) {
  5150. myprint( "imapsync no longer supports Mail::IMAPClient 2.2.9, upgrade it\n" ) ;
  5151. return 0 ;
  5152. }
  5153. else{
  5154. # 3.x.x is no longer buggy with imapsync.
  5155. # 3.30 or currently superior is imposed in the Perl "use Mail::IMAPClient line".
  5156. return 1 ;
  5157. }
  5158. return ;
  5159. }
  5160. sub module_version_str
  5161. {
  5162. my( $module_name, $module_version ) = @_ ;
  5163. my $str = mysprintf( "%-20s %s\n", $module_name, $module_version ) ;
  5164. return( $str ) ;
  5165. }
  5166. sub modulesversion
  5167. {
  5168. my @list_version;
  5169. my %modulesversion = (
  5170. 'Authen::NTLM' => sub { $Authen::NTLM::VERSION },
  5171. 'CGI' => sub { $CGI::VERSION },
  5172. 'Compress::Zlib' => sub { $Compress::Zlib::VERSION },
  5173. 'Crypt::OpenSSL::RSA' => sub { $Crypt::OpenSSL::RSA::VERSION },
  5174. 'Data::Uniqid' => sub { $Data::Uniqid::VERSION },
  5175. 'Digest::HMAC_MD5' => sub { $Digest::HMAC_MD5::VERSION },
  5176. 'Digest::HMAC_SHA1' => sub { $Digest::HMAC_SHA1::VERSION },
  5177. 'Digest::MD5' => sub { $Digest::MD5::VERSION },
  5178. 'Encode' => sub { $Encode::VERSION },
  5179. 'Encode::IMAPUTF7' => sub { $Encode::IMAPUTF7::VERSION },
  5180. 'File::Copy::Recursive' => sub { $File::Copy::Recursive::VERSION },
  5181. 'File::Spec' => sub { $File::Spec::VERSION },
  5182. 'Getopt::Long' => sub { $Getopt::Long::VERSION },
  5183. 'HTML::Entities' => sub { $HTML::Entities::VERSION },
  5184. 'IO::Socket' => sub { $IO::Socket::VERSION },
  5185. 'IO::Socket::INET' => sub { $IO::Socket::INET::VERSION },
  5186. 'IO::Socket::INET6' => sub { $IO::Socket::INET6::VERSION },
  5187. 'IO::Socket::IP' => sub { $IO::Socket::IP::VERSION },
  5188. 'IO::Socket::SSL' => sub { $IO::Socket::SSL::VERSION },
  5189. 'IO::Tee' => sub { $IO::Tee::VERSION },
  5190. 'JSON' => sub { $JSON::VERSION },
  5191. 'JSON::WebToken' => sub { $JSON::WebToken::VERSION },
  5192. 'LWP' => sub { $LWP::VERSION },
  5193. 'Mail::IMAPClient' => sub { $Mail::IMAPClient::VERSION },
  5194. 'MIME::Base64' => sub { $MIME::Base64::VERSION },
  5195. 'Net::Ping' => sub { $Net::Ping::VERSION },
  5196. 'Net::SSLeay' => sub { $Net::SSLeay::VERSION },
  5197. 'Term::ReadKey' => sub { $Term::ReadKey::VERSION },
  5198. 'Test::MockObject' => sub { $Test::MockObject::VERSION },
  5199. 'Time::HiRes' => sub { $Time::HiRes::VERSION },
  5200. 'Unicode::String' => sub { $Unicode::String::VERSION },
  5201. 'URI::Escape' => sub { $URI::Escape::VERSION },
  5202. #'Lalala' => sub { $Lalala::VERSION },
  5203. ) ;
  5204. foreach my $module_name ( sort keys %modulesversion ) {
  5205. # trick from http://www.perlmonks.org/?node_id=152122
  5206. my $file_name = $module_name . '.pm' ;
  5207. $file_name =~s,::,/,xmgs; # Foo::Bar::Baz => Foo/Bar/Baz.pm
  5208. my $v ;
  5209. eval {
  5210. require $file_name ;
  5211. $v = defined $modulesversion{ $module_name } ? $modulesversion{ $module_name }->() : q{?} ;
  5212. } or $v = q{Not installed} ;
  5213. push @list_version, module_version_str( $module_name, $v ) ;
  5214. }
  5215. return( @list_version ) ;
  5216. }
  5217. sub tests_command_line_nopassword
  5218. {
  5219. note( 'Entering tests_command_line_nopassword()' ) ;
  5220. ok( q{} eq command_line_nopassword(), 'command_line_nopassword void' );
  5221. my $mysync = {} ;
  5222. ok( '--blabla' eq command_line_nopassword( $mysync, '--blabla' ), 'command_line_nopassword --blabla' );
  5223. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  5224. ok( '--password1 MASKED' eq command_line_nopassword( $mysync, qw{ --password1 secret1}), 'command_line_nopassword --password1' );
  5225. ok( '--blabla --password1 MASKED --blibli'
  5226. eq command_line_nopassword( $mysync, qw{ --blabla --password1 secret1 --blibli } ), 'command_line_nopassword --password1 --blibli' );
  5227. $mysync->{showpasswords} = 1 ;
  5228. ok( q{} eq command_line_nopassword(), 'command_line_nopassword void' );
  5229. ok( '--blabla' eq command_line_nopassword( $mysync, '--blabla'), 'command_line_nopassword --blabla' );
  5230. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  5231. ok( '--password1 secret1' eq command_line_nopassword( $mysync, qw{ --password1 secret1} ), 'command_line_nopassword --password1' );
  5232. ok( '--blabla --password1 secret1 --blibli'
  5233. eq command_line_nopassword( $mysync, qw{ --blabla --password1 secret1 --blibli } ), 'command_line_nopassword --password1 --blibli' );
  5234. note( 'Leaving tests_command_line_nopassword()' ) ;
  5235. return ;
  5236. }
  5237. # Construct a command line copy with passwords replaced by MASKED.
  5238. sub command_line_nopassword
  5239. {
  5240. my $mysync = shift @ARG ;
  5241. my @argv = @ARG ;
  5242. my @argv_nopassword ;
  5243. if ( $mysync->{ cmdcgi } ) {
  5244. @argv_nopassword = mask_password_value( @{ $mysync->{ cmdcgi } } ) ;
  5245. return( "@argv_nopassword" ) ;
  5246. }
  5247. if ( $mysync->{showpasswords} )
  5248. {
  5249. return( "@argv" ) ;
  5250. }
  5251. @argv_nopassword = mask_password_value( @argv ) ;
  5252. return("@argv_nopassword") ;
  5253. }
  5254. sub mask_password_value
  5255. {
  5256. my @argv = @ARG ;
  5257. my @argv_nopassword ;
  5258. while ( @argv ) {
  5259. my $arg = shift @argv ; # option name or value
  5260. if ( $arg =~ m/-password[12]/x ) {
  5261. shift @argv ; # password value
  5262. push @argv_nopassword, $arg, 'MASKED' ; # option name and fake value
  5263. }else{
  5264. push @argv_nopassword, $arg ; # same option or value
  5265. }
  5266. }
  5267. return @argv_nopassword ;
  5268. }
  5269. sub tests_get_stdin_masked
  5270. {
  5271. note( 'Entering tests_get_stdin_masked()' ) ;
  5272. is( q{}, get_stdin_masked( ), 'get_stdin_masked: no args' ) ;
  5273. is( q{}, get_stdin_masked( 'Please ENTER: ' ), 'get_stdin_masked: ENTER' ) ;
  5274. note( 'Leaving tests_get_stdin_masked()' ) ;
  5275. return ;
  5276. }
  5277. #######################################################
  5278. # The issue is that prompt() does not prompt the prompt
  5279. # when the program is used like
  5280. # { sleep 2 ; echo blablabla ; } | ./imapsync ...--host1 lo --user1 tata --host2 lo --user2 titi
  5281. # use IO::Prompter ;
  5282. sub get_stdin_masked
  5283. {
  5284. my $prompt = shift || 'Say something: ' ;
  5285. local @ARGV = () ;
  5286. my $input = prompt(
  5287. -prompt => $prompt,
  5288. -echo => '*',
  5289. ) ;
  5290. #myprint( "You said: $input\n" ) ;
  5291. return $input ;
  5292. }
  5293. sub ask_for_password_new
  5294. {
  5295. my $prompt = shift ;
  5296. my $password = get_stdin_masked( $prompt ) ;
  5297. return $password ;
  5298. }
  5299. #########################################################
  5300. sub ask_for_password
  5301. {
  5302. my $prompt = shift ;
  5303. myprint( $prompt ) ;
  5304. Term::ReadKey::ReadMode( 2 ) ;
  5305. ## no critic (InputOutput::ProhibitExplicitStdin)
  5306. my $password = <STDIN> ;
  5307. chomp $password ;
  5308. myprint( "\nGot it\n" ) ;
  5309. Term::ReadKey::ReadMode( 0 ) ;
  5310. return $password ;
  5311. }
  5312. # Have to refactor get_password1() get_password2()
  5313. # to have only get_password() and two calls
  5314. sub get_password1
  5315. {
  5316. my $mysync = shift ;
  5317. $mysync->{ password1 }
  5318. || $mysync->{ passfile1 }
  5319. || 'PREAUTH' eq $mysync->{ acc1 }->{ authmech }
  5320. || 'EXTERNAL' eq $mysync->{ acc1 }->{ authmech }
  5321. || $ENV{IMAPSYNC_PASSWORD1}
  5322. || do
  5323. {
  5324. myprint( << 'FIN_PASSFILE' ) ;
  5325. If you are afraid of giving password on the command line arguments, you can put the
  5326. password of user1 in a file named file1 and use "--passfile1 file1" instead of typing it.
  5327. Then give this file restrictive permissions with the command "chmod 600 file1".
  5328. An other solution is to set the environment variable IMAPSYNC_PASSWORD1
  5329. FIN_PASSFILE
  5330. my $user = $mysync->{ acc1 }->{ authuser } || $mysync->{ user1 } ;
  5331. my $host = $mysync->{ host1 } ;
  5332. my $prompt = "What's the password for $user" . ' at ' . "$host? (not visible while you type, then enter RETURN) " ;
  5333. $mysync->{password1} = ask_for_password( $prompt ) ;
  5334. } ;
  5335. if ( defined $mysync->{ passfile1 } ) {
  5336. if ( ! -e -r $mysync->{ passfile1 } ) {
  5337. myprint( "Failure: file from parameter --passfile1 $mysync->{ passfile1 } does not exist or is not readable\n" ) ;
  5338. $mysync->{nb_errors}++ ;
  5339. exit_clean( $mysync, $EX_NOINPUT ) ;
  5340. }
  5341. # passfile1 readable
  5342. $mysync->{password1} = firstline ( $mysync->{ passfile1 } ) ;
  5343. return ;
  5344. }
  5345. if ( $ENV{IMAPSYNC_PASSWORD1} ) {
  5346. $mysync->{password1} = $ENV{IMAPSYNC_PASSWORD1} ;
  5347. return ;
  5348. }
  5349. return ;
  5350. }
  5351. sub get_password2
  5352. {
  5353. my $mysync = shift ;
  5354. $mysync->{password2}
  5355. || $mysync->{ passfile2 }
  5356. || 'PREAUTH' eq $mysync->{ acc2 }->{ authmech }
  5357. || 'EXTERNAL' eq $mysync->{ acc2 }->{ authmech }
  5358. || $ENV{IMAPSYNC_PASSWORD2}
  5359. || do
  5360. {
  5361. myprint( << 'FIN_PASSFILE' ) ;
  5362. If you are afraid of giving password on the command line arguments, you can put the
  5363. password of user2 in a file named file2 and use "--passfile2 file2" instead of typing it.
  5364. Then give this file restrictive permissions with the command "chmod 600 file2".
  5365. An other solution is to set the environment variable IMAPSYNC_PASSWORD2
  5366. FIN_PASSFILE
  5367. my $user = $mysync->{ acc2 }->{ authuser } || $mysync->{ user2 } ;
  5368. my $host = $mysync->{ host2 } ;
  5369. my $prompt = "What's the password for $user" . ' at ' . "$host? (not visible while you type, then enter RETURN) " ;
  5370. $mysync->{password2} = ask_for_password( $prompt ) ;
  5371. } ;
  5372. if ( defined $mysync->{ passfile2 } ) {
  5373. if ( ! -e -r $mysync->{ passfile2 } ) {
  5374. myprint( "Failure: file from parameter --passfile2 $mysync->{ passfile2 } does not exist or is not readable\n" ) ;
  5375. $mysync->{nb_errors}++ ;
  5376. exit_clean( $mysync, $EX_NOINPUT ) ;
  5377. }
  5378. # passfile2 readable
  5379. $mysync->{password2} = firstline ( $mysync->{ passfile2 } ) ;
  5380. return ;
  5381. }
  5382. if ( $ENV{IMAPSYNC_PASSWORD2} ) {
  5383. $mysync->{password2} = $ENV{IMAPSYNC_PASSWORD2} ;
  5384. return ;
  5385. }
  5386. return ;
  5387. }
  5388. sub remove_tmp_files
  5389. {
  5390. my $mysync = shift or return ;
  5391. $mysync->{pidfile} or return ;
  5392. if ( -e $mysync->{pidfile} ) {
  5393. myprint( "Removing pidfile $mysync->{pidfile}\n" ) ;
  5394. unlink $mysync->{pidfile} ;
  5395. }
  5396. if ( -e $mysync->{abortfile} ) {
  5397. myprint( "Removing pidfile $mysync->{abortfile}\n" ) ;
  5398. unlink $mysync->{abortfile} ;
  5399. }
  5400. return ;
  5401. }
  5402. sub cleanup_before_exit
  5403. {
  5404. my $mysync = shift ;
  5405. remove_tmp_files( $mysync ) ;
  5406. if ( $mysync->{imap1} and $mysync->{imap1}->IsConnected() )
  5407. {
  5408. myprint( "Disconnecting from host1 $mysync->{ host1 } user1 $mysync->{ user1 }\n" ) ;
  5409. $mysync->{imap1}->logout( ) ;
  5410. }
  5411. if ( $mysync->{imap2} and $mysync->{imap2}->IsConnected() )
  5412. {
  5413. myprint( "Disconnecting from host2 $mysync->{ host2 } user2 $mysync->{ user2 }\n" ) ;
  5414. $mysync->{imap2}->logout( ) ;
  5415. }
  5416. if ( $mysync->{log} ) {
  5417. myprint( "Log file is $mysync->{logfile} ( to change it, use --logfile filepath ; or use --nolog to turn off logging )\n" ) ;
  5418. }
  5419. else
  5420. {
  5421. myprint( "No log file because of option --nolog\n" ) ;
  5422. }
  5423. if ( $mysync->{log} and $mysync->{logfile_handle} ) {
  5424. #print( "Closing $mysync->{ logfile }\n" ) ;
  5425. teefinish( $mysync ) ;
  5426. }
  5427. return ;
  5428. }
  5429. sub tests_exit_value
  5430. {
  5431. note( 'Entering tests_exit_value()' ) ;
  5432. is( $EXIT_CATCH_ALL, exit_value( ), 'exit_value: no args => EXIT_CATCH_ALL' ) ;
  5433. my $mysync = { } ;
  5434. is( $EXIT_CATCH_ALL, exit_value( $mysync ), 'exit_value: undef => EXIT_CATCH_ALL' ) ;
  5435. is( $EXIT_CATCH_ALL, exit_value( $mysync, 'Blabla_unknown' ), 'exit_value: Blabla => EXIT_CATCH_ALL' ) ;
  5436. is( $EXIT_CATCH_ALL, exit_value( $mysync, '' ), 'exit_value: empty => EXIT_CATCH_ALL' ) ;
  5437. is( $EXIT_OVERQUOTA, exit_value( $mysync, 'ERR_OVERQUOTA' ), 'exit_value: ERR_OVERQUOTA => EXIT_OVERQUOTA' ) ;
  5438. is( $EXIT_TRANSFER_EXCEEDED, exit_value( $mysync, 'ERR_TRANSFER_EXCEEDED' ), 'exit_value: ERR_TRANSFER_EXCEEDED => EXIT_TRANSFER_EXCEEDED' ) ;
  5439. note( 'Leaving tests_exit_value()' ) ;
  5440. return ;
  5441. }
  5442. sub exit_value
  5443. {
  5444. my $mysync = shift @ARG ;
  5445. my $most_common_error = shift @ARG ;
  5446. if ( ! defined $most_common_error ) { return $EXIT_CATCH_ALL ; }
  5447. my $exit_value = $EXIT_VALUE_OF_ERR_TYPE{ $most_common_error } || $EXIT_CATCH_ALL ;
  5448. return $exit_value ;
  5449. }
  5450. sub exit_most_errors
  5451. {
  5452. my $mysync = shift @ARG ;
  5453. myprint( errors_listing( $mysync ) ) ;
  5454. my $exit_value = exit_value( $mysync, $mysync->{ most_common_error } ) ;
  5455. exit_clean( $mysync, $exit_value ) ;
  5456. return ;
  5457. }
  5458. sub exit_clean
  5459. {
  5460. my $mysync = shift @ARG ;
  5461. my $status = shift @ARG ;
  5462. my @messages = @ARG ;
  5463. if ( @messages )
  5464. {
  5465. myprint( @messages ) ;
  5466. }
  5467. myprint( "Exiting with return value $status ($EXIT_TXT{$status}) $mysync->{nb_errors}/$mysync->{errorsmax} nb_errors/max_errors PID $PROCESS_ID\n" ) ;
  5468. cleanup_before_exit( $mysync ) ;
  5469. exit $status ;
  5470. }
  5471. sub missing_option
  5472. {
  5473. my $mysync = shift ;
  5474. my $option = shift ;
  5475. $mysync->{nb_errors}++ ;
  5476. exit_clean( $mysync, $EX_USAGE, "$option option is mandatory, for help run $PROGRAM_NAME --help\n" ) ;
  5477. return ;
  5478. }
  5479. sub catch_ignore
  5480. {
  5481. my $mysync = shift ;
  5482. my $signame = shift ;
  5483. my $sigcounter = ++$mysync->{ sigcounter }{ $signame } ;
  5484. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ),
  5485. "). Received $sigcounter $signame signals so far. Thanks!\n" ) ;
  5486. do_and_print_stats( $mysync ) ;
  5487. return ;
  5488. }
  5489. sub catch_exit
  5490. {
  5491. my $mysync = shift ;
  5492. my $signame = shift || q{} ;
  5493. if ( $signame ) {
  5494. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ),
  5495. "). Asked to terminate\n" ) ;
  5496. if ( $mysync->{can_do_stats} ) {
  5497. do_and_print_stats( $mysync ) ;
  5498. myprint( "Ended by a signal $signame (my PID is $PROCESS_ID my PPID is ",
  5499. getppid( ), "). I am asked to terminate immediately.\n" ) ;
  5500. }
  5501. myprint( "You should resynchronize those accounts by running a sync again,\n",
  5502. "since some messages and entire folders might still be missing on host2.\n"
  5503. ) ;
  5504. ## no critic (RequireLocalizedPunctuationVars)
  5505. # Well, restore default action does not work well
  5506. $SIG{ $signame } = 'DEFAULT'; # restore default action
  5507. #$SIG{ 'TERM' } = 'DEFAULT'; # restore default action
  5508. # kill myself with $signame
  5509. # https://www.cons.org/cracauer/sigint.html
  5510. myprint( "Killing myself with signal $signame\n" ) ;
  5511. #cleanup_before_exit( $mysync ) ;
  5512. kill( $signame, $PROCESS_ID ) ;
  5513. #kill( 'TERM', $PROCESS_ID ) ;
  5514. #sleep 1 ;
  5515. #while ( 1 ) { } ;
  5516. $mysync->{nb_errors}++ ;
  5517. exit_clean( $mysync, $EXIT_BY_SIGNAL,
  5518. "Still there after killing myself with signal $signame...\n"
  5519. ) ;
  5520. }
  5521. else
  5522. {
  5523. $mysync->{nb_errors}++ ;
  5524. exit_clean( $mysync, $EXIT_BY_SIGNAL, "Exiting in catch_exit with no signal...\n" ) ;
  5525. }
  5526. return ;
  5527. }
  5528. sub catch_print
  5529. {
  5530. my $mysync = shift ;
  5531. my $signame = shift ;
  5532. my $sigcounter = ++$mysync->{ sigcounter }{ $signame } ;
  5533. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ),
  5534. "). Received $sigcounter $signame signals so far. Thanks!\n" ) ;
  5535. return ;
  5536. }
  5537. sub here_twice
  5538. {
  5539. my $mysync = shift ;
  5540. my $now = time ;
  5541. my $previous = $mysync->{lastcatch} || 0 ;
  5542. $mysync->{lastcatch} = $now ;
  5543. if ( $INTERVAL_TO_EXIT >= $now - $previous ) {
  5544. return $TRUE ;
  5545. }else{
  5546. return $FALSE ;
  5547. }
  5548. }
  5549. sub catch_reconnect
  5550. {
  5551. my $mysync = shift ;
  5552. my $signame = shift ;
  5553. if ( here_twice( $mysync ) ) {
  5554. myprint( "Got two signals $signame within $INTERVAL_TO_EXIT seconds. Exiting...\n" ) ;
  5555. catch_exit( $mysync, $signame ) ;
  5556. }else{
  5557. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ), ")\n",
  5558. "Hit 2 ctr-c within 2 seconds to exit the program\n",
  5559. "Hit only 1 ctr-c to reconnect to both imap servers\n",
  5560. ) ;
  5561. myprint( "For now only one signal $signame within $INTERVAL_TO_EXIT seconds.\n" ) ;
  5562. if ( ! defined $mysync->{imap1} ) { return ; }
  5563. if ( ! defined $mysync->{imap2} ) { return ; }
  5564. myprint( "Info: reconnecting to host1 imap server $mysync->{host1}\n" ) ;
  5565. $mysync->{imap1}->State( Mail::IMAPClient::Unconnected ) ;
  5566. $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  5567. if ( $mysync->{imap1}->reconnect( ) )
  5568. {
  5569. myprint( "Info: reconnected to host1 imap server $mysync->{host1}\n" ) ;
  5570. }
  5571. else
  5572. {
  5573. $mysync->{nb_errors}++ ;
  5574. exit_clean( $mysync, $EXIT_CONNECTION_FAILURE ) ;
  5575. }
  5576. myprint( "Info: reconnecting to host2 imap server\n" ) ;
  5577. $mysync->{imap2}->State( Mail::IMAPClient::Unconnected ) ;
  5578. $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  5579. if ( $mysync->{imap2}->reconnect( ) )
  5580. {
  5581. myprint( "Info: reconnected to host2 imap server $mysync->{host2}\n" ) ;
  5582. }
  5583. else
  5584. {
  5585. $mysync->{nb_errors}++ ;
  5586. exit_clean( $mysync, $EXIT_CONNECTION_FAILURE ) ;
  5587. }
  5588. myprint( "Info: reconnected to both imap servers\n" ) ;
  5589. }
  5590. return ;
  5591. }
  5592. sub install_signals
  5593. {
  5594. my $mysync = shift ;
  5595. if ( under_docker_context( $mysync ) )
  5596. {
  5597. # output( $mysync, "Under docker context so leaving signals as they are\n" ) ;
  5598. output( $mysync, "Under docker context so installing only signals to exit\n" ) ;
  5599. @{ $mysync->{ sigexit } } = ( defined( $mysync->{ sigexit } ) ) ? @{ $mysync->{ sigexit } } : ( 'INT', 'QUIT', 'TERM' ) ;
  5600. sig_install( $mysync, 'catch_exit', @{ $mysync->{ sigexit } } ) ;
  5601. }
  5602. else
  5603. {
  5604. # Unix signals
  5605. @{ $mysync->{ sigexit } } = ( defined( $mysync->{ sigexit } ) ) ? @{ $mysync->{ sigexit } } : ( 'QUIT', 'TERM' ) ;
  5606. @{ $mysync->{ sigreconnect } } = ( defined( $mysync->{ sigreconnect } ) ) ? @{ $mysync->{ sigreconnect } } : ( 'INT' ) ;
  5607. @{ $mysync->{ sigprint } } = ( defined( $mysync->{ sigprint } ) ) ? @{ $mysync->{ sigprint } } : ( 'HUP' ) ;
  5608. @{ $mysync->{ sigignore } } = ( defined( $mysync->{ sigignore } ) ) ? @{ $mysync->{ sigignore } } : ( ) ;
  5609. #local %SIG = %SIG ;
  5610. sig_install( $mysync, 'catch_exit', @{ $mysync->{ sigexit } } ) ;
  5611. sig_install( $mysync, 'catch_reconnect', @{ $mysync->{ sigreconnect } } ) ;
  5612. sig_install( $mysync, 'catch_print', @{ $mysync->{ sigprint } } ) ;
  5613. # --sigignore can override sigexit, sigreconnect and sigprint (for the same signals only)
  5614. sig_install( $mysync, 'catch_ignore', @{ $mysync->{ sigignore } } ) ;
  5615. # remove/add sleeping mechanism when receiving USR1 signal (except on Win32)
  5616. sig_install_toggle_sleep( $mysync ) ;
  5617. }
  5618. return ;
  5619. }
  5620. sub tests_reconnect_12_if_needed
  5621. {
  5622. note( 'Entering tests_reconnect_12_if_needed()' ) ;
  5623. my $mysync ;
  5624. $mysync->{imap1} = Mail::IMAPClient->new( ) ;
  5625. $mysync->{imap2} = Mail::IMAPClient->new( ) ;
  5626. $mysync->{imap1}->Server( 'test1.lamiral.info' ) ;
  5627. $mysync->{imap2}->Server( 'test2.lamiral.info' ) ;
  5628. is( 2, reconnect_12_if_needed( $mysync ), 'reconnect_12_if_needed: test1&test2 .lamiral.info => 1' ) ;
  5629. is( 1, $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_12_if_needed: test1.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  5630. is( 1, $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_12_if_needed: test2.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  5631. note( 'Leaving tests_reconnect_12_if_needed()' ) ;
  5632. return ;
  5633. }
  5634. sub reconnect_12_if_needed
  5635. {
  5636. my $mysync = shift ;
  5637. #return 2 ;
  5638. if ( ! reconnect_if_needed( $mysync->{imap1} ) ) {
  5639. return ;
  5640. }
  5641. if ( ! reconnect_if_needed( $mysync->{imap2} ) ) {
  5642. return ;
  5643. }
  5644. # both were good
  5645. return 2 ;
  5646. }
  5647. sub tests_reconnect_if_needed
  5648. {
  5649. note( 'Entering tests_reconnect_if_needed()' ) ;
  5650. my $myimap ;
  5651. is( undef, reconnect_if_needed( ), 'reconnect_if_needed: no args => undef' ) ;
  5652. is( undef, reconnect_if_needed( $myimap ), 'reconnect_if_needed: undef arg => undef' ) ;
  5653. $myimap = Mail::IMAPClient->new( ) ;
  5654. $myimap->Debug( 1 ) ;
  5655. is( undef, reconnect_if_needed( $myimap ), 'reconnect_if_needed: empty new Mail::IMAPClient => undef' ) ;
  5656. $myimap->Server( 'test.lamiral.info' ) ;
  5657. is( 1, reconnect_if_needed( $myimap ), 'reconnect_if_needed: test.lamiral.info => 1' ) ;
  5658. is( 1, $myimap->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_if_needed: test.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  5659. note( 'Leaving tests_reconnect_if_needed()' ) ;
  5660. return ;
  5661. }
  5662. sub reconnect_if_needed
  5663. {
  5664. # return undef upon failure.
  5665. # return 1 upon connection success, with or without reconnection.
  5666. my $imap = shift ;
  5667. if ( ! defined $imap ) { return ; }
  5668. if ( ! $imap->Server( ) ) { return ; }
  5669. if ( $imap->IsUnconnected( ) ) {
  5670. $imap->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  5671. if ( $imap->reconnect( ) ) {
  5672. return 1 ;
  5673. }
  5674. }else{
  5675. return 1 ;
  5676. }
  5677. # A last forced one
  5678. $imap->State( Mail::IMAPClient::Unconnected ) ;
  5679. $imap->reconnect( ) ;
  5680. $imap->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  5681. if ( $imap->noop ) {
  5682. # NOOP is ok
  5683. return 1 ;
  5684. }
  5685. return ;
  5686. }
  5687. sub justconnect
  5688. {
  5689. my $mysync = shift ;
  5690. my $justconnect1 = justconnect1( $sync ) ;
  5691. my $justconnect2 = justconnect2( $sync ) ;
  5692. return "$justconnect1 $justconnect2";
  5693. }
  5694. sub justconnect1
  5695. {
  5696. my $mysync = shift ;
  5697. if ( $mysync->{host1} )
  5698. {
  5699. myprint( "Host1: Will just connect to $mysync->{host1} without login\n" ) ;
  5700. $mysync->{imap1} = connect_imap(
  5701. $mysync->{host1}, $mysync->{port1},
  5702. $mysync->{ssl1}, $mysync->{tls1},
  5703. $mysync->{ acc1 } ) ;
  5704. imap_id( $mysync, $mysync->{imap1}, $mysync->{ acc1 }->{ Side } ) ;
  5705. $mysync->{imap1}->logout( ) ;
  5706. return $mysync->{host1} ;
  5707. }
  5708. return q{} ;
  5709. }
  5710. sub justconnect2
  5711. {
  5712. my $mysync = shift ;
  5713. if ( $mysync->{host2} )
  5714. {
  5715. myprint( "Host2: Will just connect to $mysync->{host2} without login\n" ) ;
  5716. $mysync->{imap2} = connect_imap(
  5717. $mysync->{host2}, $mysync->{port2},
  5718. $mysync->{ssl2}, $mysync->{tls2},
  5719. $mysync->{ acc2 } ) ;
  5720. imap_id( $mysync, $mysync->{imap2}, $mysync->{ acc2 }->{ Side } ) ;
  5721. $mysync->{imap2}->logout( ) ;
  5722. return $mysync->{host2} ;
  5723. }
  5724. return q{} ;
  5725. }
  5726. sub skip_macosx
  5727. {
  5728. #return ;
  5729. # hostname is sometimes "macosx.polarhome.com" sometimes "macosx"
  5730. return( ( ( 'macosx.polarhome.com' eq hostname( ) ) || ( 'macosx' eq hostname( ) ) )
  5731. && ( 'darwin' eq $OSNAME ) ) ;
  5732. }
  5733. sub skip_macosx_binary
  5734. {
  5735. #return ;
  5736. return( skip_macosx( ) && ( $PROGRAM_NAME =~ m{imapsync_bin_Darwin} ) ) ;
  5737. }
  5738. sub tests_mailimapclient_connect
  5739. {
  5740. note( 'Entering tests_mailimapclient_connect()' ) ;
  5741. my $imap ;
  5742. # ipv4
  5743. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv4: new' ) ;
  5744. is( 'Mail::IMAPClient', ref( $imap ), 'mailimapclient_connect ipv4: ref is Mail::IMAPClient' ) ;
  5745. # Mail::IMAPClient 3.40 die on this... So we skip it, thanks to "mature" IO::Socket::IP
  5746. # Mail::IMAPClient 3.42 is ok so this test is back.
  5747. is( undef, $imap->connect( ), 'mailimapclient_connect ipv4: connect with no server => failure' ) ;
  5748. is( 'test.lamiral.info', $imap->Server( 'test.lamiral.info' ), 'mailimapclient_connect ipv4: setting Server(test.lamiral.info)' ) ;
  5749. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4: setting Debug( 1 )' ) ;
  5750. is( 143, $imap->Port( 143 ), 'mailimapclient_connect ipv4: setting Port( 143 )' ) ;
  5751. is( 10, $imap->Timeout( 10 ), 'mailimapclient_connect ipv4: setting Timeout( 10 )' ) ;
  5752. like( ref( $imap->connect( ) ), qr/IO::Socket::INET|IO::Socket::IP/, 'mailimapclient_connect ipv4: connect to test.lamiral.info' ) ;
  5753. like( $imap->logout( ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv4: logout' ) ;
  5754. is( undef, undef $imap, 'mailimapclient_connect ipv4: free variable' ) ;
  5755. # ipv4 + ssl
  5756. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv4 + ssl: new' ) ;
  5757. is( 'test.lamiral.info', $imap->Server( 'test.lamiral.info' ), 'mailimapclient_connect ipv4 + ssl: setting Server(test.lamiral.info)' ) ;
  5758. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4 + ssl: setting Debug( 1 )' ) ;
  5759. ok( $imap->Ssl( [ SSL_verify_mode => SSL_VERIFY_NONE, SSL_cipher_list => 'DEFAULT:!DH' ] ), 'mailimapclient_connect ipv4 + ssl: setting Ssl( SSL_VERIFY_NONE )' ) ;
  5760. is( 993, $imap->Port( 993 ), 'mailimapclient_connect ipv4 + ssl: setting Port( 993 )' ) ;
  5761. like( ref( $imap->connect( ) ), qr/IO::Socket::SSL/, 'mailimapclient_connect ipv4 + ssl: connect to test.lamiral.info' ) ;
  5762. like( $imap->logout( ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv4 + ssl: logout in ssl does not cause failure' ) ;
  5763. is( undef, undef $imap, 'mailimapclient_connect ipv4 + ssl: free variable' ) ;
  5764. # ipv6 + ssl
  5765. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv6 + ssl: new' ) ;
  5766. is( 'petiteipv6.lamiral.info', $imap->Server( 'petiteipv6.lamiral.info' ), 'mailimapclient_connect ipv6 + ssl: setting Server petiteipv6.lamiral.info' ) ;
  5767. is( 10, $imap->Timeout( 10 ), 'mailimapclient_connect ipv6: setting Timeout( 10 )' ) ;
  5768. ok( $imap->Ssl( [ SSL_verify_mode => SSL_VERIFY_NONE, SSL_cipher_list => 'DEFAULT:!DH' ] ), 'mailimapclient_connect ipv6 + ssl: setting Ssl( SSL_VERIFY_NONE )' ) ;
  5769. is( 993, $imap->Port( 993 ), 'mailimapclient_connect ipv6 + ssl: setting Port( 993 )' ) ;
  5770. SKIP: {
  5771. if (
  5772. 'CUILLERE' eq hostname()
  5773. or
  5774. skip_macosx()
  5775. or
  5776. -e '/.dockerenv'
  5777. or
  5778. 'pcHPDV7-HP' eq hostname()
  5779. )
  5780. {
  5781. skip( 'Tests avoided on CUILLERE/pcHPDV7-HP/macosx.polarhome.com/docker cannot do ipv6', 4 ) ;
  5782. }
  5783. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4 + ssl: setting Debug( 1 )' ) ;
  5784. # It sounds stupid but it avoids failures on the next test about $imap->connect
  5785. is( '2a01:e34:ecde:70d0:223:54ff:fec2:36d7', resolv( 'petiteipv6.lamiral.info' ), 'resolv: petiteipv6.lamiral.info => 2a01:e34:ecde:70d0:223:54ff:fec2:36d7' ) ;
  5786. like( ref( $imap->connect( ) ), qr/IO::Socket::SSL/, 'mailimapclient_connect ipv6 + ssl: connect to petiteipv6.lamiral.info' ) ;
  5787. # This one is ok on petite, not on ks2, do not know why, so commented.
  5788. like( ref( $imap->logout( ) ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv6 + ssl: logout in ssl is ok on petiteipv6.lamiral.info' ) ;
  5789. }
  5790. is( undef, undef $imap, 'mailimapclient_connect ipv6 + ssl: free variable' ) ;
  5791. note( 'Leaving tests_mailimapclient_connect()' ) ;
  5792. return ;
  5793. }
  5794. sub tests_mailimapclient_connect_bug
  5795. {
  5796. note( 'Entering tests_mailimapclient_connect_bug()' ) ;
  5797. my $imap ;
  5798. # ipv6
  5799. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect_bug ipv6: new' ) ;
  5800. is( 'ks6ipv6.lamiral.info', $imap->Server( 'ks6ipv6.lamiral.info' ), 'mailimapclient_connect_bug ipv6: setting Server(ks6ipv6.lamiral.info)' ) ;
  5801. is( 143, $imap->Port( 143 ), 'mailimapclient_connect_bug ipv6: setting Port( 993 )' ) ;
  5802. SKIP: {
  5803. if (
  5804. 'CUILLERE' eq hostname()
  5805. or
  5806. skip_macosx()
  5807. or
  5808. -e '/.dockerenv'
  5809. or
  5810. 'pcHPDV7-HP' eq hostname()
  5811. )
  5812. {
  5813. skip( 'Tests avoided on CUILLERE/pcHPDV7-HP/macosx.polarhome.com/docker cannot do ipv6', 1 ) ;
  5814. }
  5815. like( ref( $imap->connect( ) ), qr/IO::Socket::INET/, 'mailimapclient_connect_bug ipv6: connect to ks6ipv6.lamiral.info' )
  5816. or diag( 'mailimapclient_connect_bug ipv6: ', $imap->LastError( ), $!, ) ;
  5817. }
  5818. #is( $imap->logout( ), undef, 'mailimapclient_connect_bug ipv6: logout in ssl causes failure' ) ;
  5819. is( undef, undef $imap, 'mailimapclient_connect_bug ipv6: free variable' ) ;
  5820. note( 'Leaving tests_mailimapclient_connect_bug()' ) ;
  5821. return ;
  5822. }
  5823. sub tests_connect_socket
  5824. {
  5825. note( 'Entering tests_connect_socket()' ) ;
  5826. is( undef, connect_socket( ), 'connect_socket: no args' ) ;
  5827. my $socket ;
  5828. my $imap ;
  5829. SKIP: {
  5830. if (
  5831. 'CUILLERE' eq hostname()
  5832. or
  5833. skip_macosx()
  5834. or
  5835. -e '/.dockerenv'
  5836. or
  5837. 'pcHPDV7-HP' eq hostname()
  5838. )
  5839. {
  5840. skip( 'Tests avoided on CUILLERE/pcHPDV7-HP/macosx.polarhome.com/docker cannot do ipv6', 2 ) ;
  5841. }
  5842. $socket = IO::Socket::INET6->new(
  5843. PeerAddr => 'ks6ipv6.lamiral.info',
  5844. PeerPort => 143,
  5845. ) ;
  5846. ok( $imap = connect_socket( $socket ), 'connect_socket: ks6ipv6.lamiral.info port 143 IO::Socket::INET6' ) ;
  5847. #$imap->Debug( 1 ) ;
  5848. # myprint( $imap->capability( ) ) ;
  5849. if ( $imap ) {
  5850. $imap->logout( ) ;
  5851. }
  5852. $IO::Socket::SSL::DEBUG = 4 ;
  5853. $socket = IO::Socket::SSL->new(
  5854. PeerHost => 'ks6ipv6.lamiral.info',
  5855. PeerPort => 993,
  5856. SSL_verify_mode => SSL_VERIFY_NONE,
  5857. SSL_cipher_list => 'DEFAULT:!DH',
  5858. ) ;
  5859. # myprint( $socket ) ;
  5860. ok( $imap = connect_socket( $socket ), 'connect_socket: ks6ipv6.lamiral.info port 993 IO::Socket::SSL' ) ;
  5861. #$imap->Debug( 1 ) ;
  5862. # myprint( $imap->capability( ) ) ;
  5863. # $socket->close( ) ;
  5864. if ( $imap ) {
  5865. $socket->close( ) ;
  5866. }
  5867. #$socket->close(SSL_no_shutdown => 1) ;
  5868. #$imap->logout( ) ;
  5869. #myprint( "\n" ) ;
  5870. #$imap->logout( ) ;
  5871. }
  5872. note( 'Leaving tests_connect_socket()' ) ;
  5873. return ;
  5874. }
  5875. sub connect_socket
  5876. {
  5877. my( $socket ) = @ARG ;
  5878. if ( ! defined $socket ) { return ; }
  5879. my $host = $socket->peerhost( ) ;
  5880. my $port = $socket->peerport( ) ;
  5881. #print "socket->peerhost: ", $socket->peerhost( ), "\n" ;
  5882. #print "socket->peerport: ", $socket->peerport( ), "\n" ;
  5883. my $imap = Mail::IMAPClient->new( ) ;
  5884. $imap->Socket( $socket ) ;
  5885. my $banner = $imap->Results()->[0] ;
  5886. #myprint( "banner: $banner" ) ;
  5887. return $imap ;
  5888. }
  5889. sub tests_probe_imapssl
  5890. {
  5891. note( 'Entering tests_probe_imapssl()' ) ;
  5892. is( undef, probe_imapssl( ), 'probe_imapssl: no args => undef' ) ;
  5893. is( undef, probe_imapssl( 'unknown' ), 'probe_imapssl: unknown => undef' ) ;
  5894. note( "hostname is: ", hostname() ) ;
  5895. SKIP: {
  5896. if (
  5897. 'CUILLERE' eq hostname()
  5898. or
  5899. skip_macosx()
  5900. or
  5901. -e '/.dockerenv'
  5902. or
  5903. 'pcHPDV7-HP' eq hostname()
  5904. )
  5905. {
  5906. skip( 'Tests avoided on CUILLERE or pcHPDV7-HP or Mac or docker: cannot do ipv6', 0 ) ;
  5907. }
  5908. # fed up with this one
  5909. #like( probe_imapssl( 'ks6ipv6.lamiral.info' ), qr/^\* OK/, 'probe_imapssl: ks6ipv6.lamiral.info matches "* OK"' ) ;
  5910. } ;
  5911. # It sounds stupid but it avoids failures on the next test about $imap->connect
  5912. ok( resolv( 'imap.gmail.com' ), 'resolv: imap.gmail.com => something' ) ;
  5913. like( probe_imapssl( 'imap.gmail.com' ), qr/^\* OK/, 'probe_imapssl: imap.gmail.com matches "* OK"' ) ;
  5914. like( probe_imapssl( 'test1.lamiral.info' ), qr/^\* OK/, 'probe_imapssl: test1.lamiral.info matches "* OK"' ) ;
  5915. note( 'Leaving tests_probe_imapssl()' ) ;
  5916. return ;
  5917. }
  5918. sub probe_imapssl
  5919. {
  5920. my $host = shift ;
  5921. if ( ! $host ) { return ; }
  5922. $sync->{ debug } and $IO::Socket::SSL::DEBUG = 4 ;
  5923. my $socket = IO::Socket::SSL->new(
  5924. PeerHost => $host,
  5925. PeerPort => $IMAP_SSL_PORT,
  5926. SSL_verifycn_scheme => 'imap',
  5927. SSL_verify_mode => $SSL_VERIFY_POLICY,
  5928. SSL_cipher_list => 'DEFAULT:!DH',
  5929. ) ;
  5930. if ( ! $socket ) { return ; }
  5931. $sync->{ debug } and print "socket: $socket\n" ;
  5932. my $banner ;
  5933. $socket->sysread( $banner, 65_536 ) ;
  5934. $sync->{ debug } and print "banner: $banner" ;
  5935. $socket->close( ) ;
  5936. return $banner ;
  5937. }
  5938. sub connect_imap
  5939. {
  5940. my( $host, $port, $ssl, $tls, $acc ) = @_ ;
  5941. my $imap = Mail::IMAPClient->new( ) ;
  5942. if ( $ssl ) { set_ssl( $imap, $acc ) }
  5943. $imap->Server( $host ) ;
  5944. $imap->Port( $port ) ;
  5945. $imap->Debug( $acc->{ debugimap } ) ;
  5946. $imap->Timeout( $acc->{ timeout } ) ;
  5947. #$imap->Keepalive( $acc->{ keepalive } ) ;
  5948. my $side = lc $acc->{ Side } ;
  5949. myprint( "$acc->{ Side }: connecting on $side [$host] port [$port]\n" ) ;
  5950. if ( ! $imap->connect( ) )
  5951. {
  5952. $sync->{nb_errors}++ ;
  5953. exit_clean( $sync, $EXIT_CONNECTION_FAILURE,
  5954. "$acc->{ Side }: Can not open imap connection on [$host]: ",
  5955. $imap->LastError,
  5956. " $OS_ERROR\n"
  5957. ) ;
  5958. }
  5959. myprint( "$acc->{ Side } IP address: ", $imap->Socket->peerhost(), "\n" ) ;
  5960. my $banner = $imap->Results()->[0] ;
  5961. myprint( "$acc->{ Side } banner: $banner" ) ;
  5962. myprint( "$acc->{ Side } capability: ", join(q{ }, @{ $imap->capability() || [] }), "\n" ) ;
  5963. if ( $tls ) {
  5964. set_tls( $imap, $acc ) ;
  5965. if ( ! $imap->starttls( ) )
  5966. {
  5967. $sync->{nb_errors}++ ;
  5968. exit_clean( $sync, $EXIT_TLS_FAILURE,
  5969. "$acc->{ Side }: Can not go to tls encryption on $side [$host]:",
  5970. $imap->LastError, "\n"
  5971. ) ;
  5972. }
  5973. myprint( "$acc->{ Side }: Socket successfully converted to SSL\n" ) ;
  5974. }
  5975. return( $imap ) ;
  5976. }
  5977. sub tests_compress_ssl
  5978. {
  5979. note( 'Entering tests_compress_ssl()' ) ;
  5980. SKIP: {
  5981. if ( skip_macosx( ) )
  5982. {
  5983. skip( 'Tests avoided on host polarhome macosx, no clue "ssl3_get_server_certificate:certificate verify failed"', 12 ) ;
  5984. }
  5985. else
  5986. {
  5987. my $myimap ;
  5988. my $acc = {} ;
  5989. $acc->{ Side } = 'HostK' ;
  5990. $acc->{ authmech } = 'LOGIN' ;
  5991. $acc->{ debugimap } = 1 ;
  5992. $acc->{ compress } = 1 ;
  5993. $acc->{ N } = 'K' ;
  5994. ok(
  5995. $myimap = login_imap( 'test1.lamiral.info', 993, 'test1', 'secret1',
  5996. 1, undef,
  5997. 1, 100, $acc, {},
  5998. ), 'acc_compress_imap: test1.lamiral.info test1 ssl' ) ;
  5999. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'acc_compress_imap: test1.lamiral.info test1 ssl IsAuthenticated' ) ;
  6000. is( $acc->{ imap }, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info ok" ) ;
  6001. is( undef, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info 2nd nok" ) ;
  6002. ok(
  6003. $myimap = login_imap( 'test1.lamiral.info', 143, 'test1', 'secret1',
  6004. 0, undef,
  6005. 1, 100, $acc, {},
  6006. ), 'acc_compress_imap: test1.lamiral.info test1 tls' ) ;
  6007. ok( $myimap && $myimap->IsAuthenticated( ), 'acc_compress_imap: test1.lamiral.info test1 tls IsAuthenticated' ) ;
  6008. is( $acc->{ imap }, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info tls ok" ) ;
  6009. is( undef, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info tls 2nd nok" ) ;
  6010. # Third, no compression
  6011. $acc->{ compress } = 0 ;
  6012. ok(
  6013. $myimap = login_imap( 'test1.lamiral.info', 993, 'test1', 'secret1',
  6014. 1, undef,
  6015. 1, 100, $acc, {},
  6016. ), 'acc_compress_imap: test1.lamiral.info test1 ssl' ) ;
  6017. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'acc_compress_imap: test1.lamiral.info test1 ssl IsAuthenticated' ) ;
  6018. is( undef, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info off ok" ) ;
  6019. is( undef, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info 2nd off ok" ) ;
  6020. }
  6021. }
  6022. note( 'Leaving tests_compress_ssl()' ) ;
  6023. return ;
  6024. }
  6025. sub tests_compress
  6026. {
  6027. note( 'Entering tests_compress()' ) ;
  6028. my $myimap ;
  6029. my $acc = {} ;
  6030. $acc->{ Side } = 'HostK' ;
  6031. $acc->{ authmech } = 'LOGIN' ;
  6032. $acc->{ debugimap } = 1 ;
  6033. $acc->{ compress } = 1 ;
  6034. $acc->{ N } = 'K' ;
  6035. ok(
  6036. $myimap = login_imap( 'test1.lamiral.info', 143, 'test1', 'secret1',
  6037. 0, 0,
  6038. 1, 100, $acc, {},
  6039. ), 'acc_compress_imap: test1.lamiral.info test1' ) ;
  6040. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'acc_compress_imap: test1.lamiral.info test1 IsAuthenticated' ) ;
  6041. is( $acc->{ imap }, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info ok" ) ;
  6042. is( undef, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info 2nd nok" ) ;
  6043. ok(
  6044. $myimap = login_imap( 'test1.lamiral.info', 143, 'test1', 'secret1',
  6045. 0, 0,
  6046. 1, 100, $acc, {},
  6047. ), 'acc_compress_imap: test1.lamiral.info test1 tls' ) ;
  6048. ok( $myimap && $myimap->IsAuthenticated( ), 'acc_compress_imap: test1.lamiral.info test1 tls IsAuthenticated' ) ;
  6049. is( $acc->{ imap }, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info tls ok" ) ;
  6050. is( undef, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info tls 2nd nok" ) ;
  6051. # Third, no compression
  6052. $acc->{ compress } = 0 ;
  6053. ok(
  6054. $myimap = login_imap( 'test1.lamiral.info', 143, 'test1', 'secret1',
  6055. 0, 0,
  6056. 1, 100, $acc, {},
  6057. ), 'acc_compress_imap: test1.lamiral.info test1 ssl' ) ;
  6058. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'acc_compress_imap: test1.lamiral.info test1 ssl IsAuthenticated' ) ;
  6059. is( undef, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info off ok" ) ;
  6060. is( undef, acc_compress_imap( $acc ), "acc_compress_imap: test1.lamiral.info 2nd off ok" ) ;
  6061. note( 'Leaving tests_compress()' ) ;
  6062. return ;
  6063. }
  6064. sub acc_compress_imap
  6065. {
  6066. my $acc = shift ;
  6067. if ( ! defined( $acc ) ) { return ; }
  6068. my $ret ;
  6069. my $imap = $acc->{ imap } ;
  6070. if ( ! defined $imap ) { return ; }
  6071. if ( $imap && $acc->{ compress } )
  6072. {
  6073. myprint( "$acc->{ Side }: Trying to turn imap compression on. Use --nocompress" . $acc->{ N } . " to avoid compression on " . lc( $acc->{ Side } ) . "\n" ) ;
  6074. if ( $ret = $imap->compress() )
  6075. {
  6076. myprint( "$acc->{ Side }: Compression is on now\n" ) ;
  6077. }
  6078. else
  6079. {
  6080. myprint( "$acc->{ Side }: Failed to turn compression on\n" ) ;
  6081. }
  6082. }
  6083. else
  6084. {
  6085. myprint( "$acc->{ Side }: Compression is off. Use --compress" . $acc->{ N } . " to allow compression on " . lc( $acc->{ Side } ) . "\n" ) ;
  6086. }
  6087. # $ret is $acc->{ imap } on success, undef on failure or when there is nothing to do.
  6088. return $ret ;
  6089. }
  6090. sub tests_login_imap
  6091. {
  6092. note( 'Entering tests_login_imap()' ) ;
  6093. is( undef, login_imap( ), 'login_imap: no args => undef' ) ;
  6094. SKIP: {
  6095. if ( skip_macosx( ) )
  6096. {
  6097. skip( 'Tests avoided only on binary on host polarhome macosx, no clue "ssl3_get_server_certificate:certificate verify failed"', 15 ) ;
  6098. }
  6099. else{
  6100. my $myimap ;
  6101. my $acc = {} ;
  6102. $acc->{ Side } = 'HostK' ;
  6103. $acc->{ authmech } = 'LOGIN' ;
  6104. #$IO::Socket::SSL::DEBUG = 4 ;
  6105. # Each month (trimester?):
  6106. # echo | openssl s_client -crlf -connect test1.lamiral.info:993
  6107. # ...
  6108. # certificate has expired
  6109. # Fix: ssh root@test1.lamiral.info 'apt update && apt upgrade && /etc/init.d/dovecot restart'
  6110. #
  6111. # or
  6112. # echo | openssl s_client -crlf -connect test1.lamiral.info:993
  6113. # ...
  6114. # Verify return code: 9 (certificate is not yet valid)
  6115. # Fix: /etc/init.d/openntpd restart
  6116. # 2021_09_04 done
  6117. ok(
  6118. $myimap = login_imap( 'test1.lamiral.info', 993, 'test1', 'secret1',
  6119. 1, undef,
  6120. 1, 100, $acc, {},
  6121. ), 'login_imap: test1.lamiral.info test1 ssl' ) ;
  6122. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'login_imap: test1.lamiral.info test1 ssl IsAuthenticated' ) ;
  6123. is( $myimap, $acc->{ imap }, "login_imap: acc->{ imap } ok test1 ssl") ;
  6124. ok(
  6125. $myimap = login_imap( 'test1.lamiral.info', 143, 'test1', 'secret1',
  6126. 0, undef,
  6127. 1, 100, $acc, {},
  6128. ), 'login_imap: test1.lamiral.info test1 tls' ) ;
  6129. ok( $myimap && $myimap->IsAuthenticated( ), 'login_imap: test1.lamiral.info test1 tls IsAuthenticated' ) ;
  6130. is( $myimap, $acc->{ imap }, "login_imap: acc->{ imap } ok test1 tls") ;
  6131. #$IO::Socket::SSL::DEBUG = 4 ;
  6132. $acc->{sslargs} = { SSL_version => 'SSLv2' } ;
  6133. # SSLv2 not supported
  6134. is(
  6135. undef, $myimap = login_imap( 'test1.lamiral.info', 143, 'test1', 'secret1',
  6136. 0, undef,
  6137. 1, 100, $acc, {},
  6138. ), 'login_imap: test1.lamiral.info test1 tls SSLv2 not supported' ) ;
  6139. #SSL_verify_mode => 1
  6140. #SSL_version => 'TLSv1_1'
  6141. is( undef, $acc->{ imap }, "login_imap: acc->{ imap } test1 tls error => undef") ;
  6142. # I have left ? exit_clean to be replaced by errors_incr( $mysync, 'error message' )
  6143. # 1 in login_imap()
  6144. my $mysync = {} ;
  6145. $acc = {} ;
  6146. $acc->{ Side } = 'Host2' ;
  6147. $acc->{ authmech } = 'LOGIN' ;
  6148. is(
  6149. undef, login_imap( 'noresol.lamiral.info', 143, 'test1', 'secret1',
  6150. 0, undef,
  6151. 1, 100, $acc, $mysync,
  6152. ), 'login_imap: noresol.lamiral.info undef' ) ;
  6153. is( 'ERR_CONNECTION_FAILURE_HOST2', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host2 noresol.lamiral.info => ERR_CONNECTION_FAILURE_HOST2' ) ;
  6154. is( undef, $acc->{ imap }, "login_imap: acc->{ imap } noresol error => undef") ;
  6155. # authentication failure for user2
  6156. $mysync = {} ;
  6157. is(
  6158. undef, login_imap( 'test1.lamiral.info', 143, 'test1', 'Ce crétin',
  6159. 0, undef,
  6160. 1, 100, $acc, $mysync,
  6161. ), 'login_imap: user2 bad passord => undef' ) ;
  6162. is( 'ERR_AUTHENTICATION_FAILURE_USER2', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host2 bad password => ERR_AUTHENTICATION_FAILURE_USER2' ) ;
  6163. # authentication failure for user1
  6164. $mysync = {} ;
  6165. $acc = {} ;
  6166. $acc->{ Side } = 'Host1' ;
  6167. $acc->{ authmech } = 'LOGIN' ;
  6168. is(
  6169. undef, login_imap( 'test1.lamiral.info', 143, 'test1', 'Ce crétin',
  6170. 0, undef,
  6171. 1, 100, $acc, $mysync,
  6172. ), 'login_imap: user1 bad passord => undef' ) ;
  6173. is( 'ERR_AUTHENTICATION_FAILURE_USER1', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host1 bad password => ERR_AUTHENTICATION_FAILURE_USER1' ) ;
  6174. }
  6175. }
  6176. note( 'Leaving tests_login_imap()' ) ;
  6177. return ;
  6178. }
  6179. sub oauthgenerateaccess
  6180. {
  6181. if ( "petite" eq hostname() )
  6182. {
  6183. myprint( "oauthgenerateaccess\n" ) ;
  6184. my @output = backtick( 'cd oauth2 && pwd && ./generate_gmail_token imapsync.gl0@gmail.com' ) ;
  6185. myprint( @output ) ;
  6186. }
  6187. return ;
  6188. }
  6189. sub tests_login_imap_oauth
  6190. {
  6191. note( 'Entering tests_login_imap_oauth()' ) ;
  6192. oauthgenerateaccess() ;
  6193. SKIP: {
  6194. if ( skip_macosx_binary( ) )
  6195. {
  6196. skip( 'Tests avoided only on binary on host polarhome macosx, no clue "ssl3_get_server_certificate:certificate verify failed"', 6 ) ;
  6197. }
  6198. else
  6199. {
  6200. my $mysync ;
  6201. my $acc ;
  6202. # oauthdirect authentication failure for user2
  6203. $mysync = {} ;
  6204. $acc = {} ;
  6205. $acc->{ oauthdirect } = 'caca2' ;
  6206. $acc->{ debugimap } = 1 ;
  6207. $mysync->{ showpasswords } = 1 ;
  6208. $acc->{ Side } = 'Host2' ;
  6209. $acc->{ authmech } = 'QQQ' ;
  6210. is(
  6211. undef, login_imap( 'imap.gmail.com', 993, 'test1', 'Ce crétin',
  6212. 1, undef,
  6213. 1, 100, $acc, $mysync,
  6214. ), 'login_imap: user2 bad oauthdirect => undef' ) ;
  6215. is( 'ERR_AUTHENTICATION_FAILURE_USER2', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host2 bad oauthdirect => ERR_AUTHENTICATION_FAILURE_USER2' ) ;
  6216. # oauthdirect authentication failure for user1
  6217. $mysync = {} ;
  6218. $acc = {} ;
  6219. $acc->{ Side } = 'Host1' ;
  6220. $acc->{ oauthdirect } = 'caca1' ;
  6221. $acc->{ debugimap } = 1 ;
  6222. $mysync->{ showpasswords } = 1 ;
  6223. $acc->{ authmech } = 'QQQ' ;
  6224. is(
  6225. undef, login_imap( 'imap.gmail.com', 993, 'test1', 'Ce crétin',
  6226. 1, undef,
  6227. 1, 100, $acc, $mysync,
  6228. ), 'login_imap: user1 bad oauthdirect => undef' ) ;
  6229. is( 'ERR_AUTHENTICATION_FAILURE_USER1', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host1 bad oauthdirect => ERR_AUTHENTICATION_FAILURE_USER1' ) ;
  6230. # oauthdirect authentication failure for user1
  6231. $mysync = {} ;
  6232. $acc = {} ;
  6233. $acc->{ Side } = 'Host1' ;
  6234. $acc->{ oauthdirect } = '' ;
  6235. $acc->{ debugimap } = 1 ;
  6236. $mysync->{ showpasswords } = 1 ;
  6237. $acc->{ authmech } = 'QQQ' ;
  6238. is(
  6239. undef, login_imap( 'imap.gmail.com', 993, 'test1', 'Ce crétin',
  6240. 1, undef,
  6241. 1, 100, $acc, $mysync,
  6242. ), 'login_imap: user1 bad oauthdirect => undef' ) ;
  6243. is( 'ERR_AUTHENTICATION_FAILURE_USER1', errorsanalyse( errors_log( $mysync ) ), 'login_imap: Host1 no oauthdirect value => ERR_AUTHENTICATION_FAILURE_USER1' ) ;
  6244. }
  6245. }
  6246. # oauthdirect authentication success for user1
  6247. SKIP: {
  6248. if ( ! -r 'oauth2/D_oauth2_oauthdirect_imapsync.gl0@gmail.com.txt' )
  6249. {
  6250. skip( 'oauthdirect: no oauthdirect file', 6 ) ;
  6251. }
  6252. my $myimap ;
  6253. my $mysync = {} ;
  6254. my $acc = {} ;
  6255. $acc->{ Side } = 'Host1' ;
  6256. $acc->{ oauthdirect } = 'oauth2/D_oauth2_oauthdirect_imapsync.gl0@gmail.com.txt' ;
  6257. $acc->{ debugimap } = 1 ;
  6258. $mysync->{ showpasswords } = 1 ;
  6259. $acc->{ authmech } = 'QQQ' ;
  6260. isa_ok(
  6261. $myimap = login_imap( 'imap.gmail.com', 993, 'user_useless', 'password_useless',
  6262. 1, undef,
  6263. 1, 100, $acc, $mysync,
  6264. ), 'Mail::IMAPClient', 'login_imap: user1 good oauthdirect => Mail::IMAPClient' ) ;
  6265. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'login_imap: gmail oauth2 oauthdirect IsAuthenticated' ) ;
  6266. ok( defined( $myimap ) && $myimap->logout( ), 'login_imap: gmail oauth2 oauthdirect logout' ) ;
  6267. ok( defined( $myimap ) && ! $myimap->IsAuthenticated( ), 'login_imap: gmail oauth2 oauthdirect not IsAuthenticated after logout' ) ;
  6268. ok( defined( $myimap ) && $myimap->reconnect( ), 'login_imap: gmail oauth2 oauthdirect reconnect ok' ) ;
  6269. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'login_imap: gmail oauth2 oauthdirect IsAuthenticated after reconnect' ) ;
  6270. }
  6271. # oauthaccesstoken authentication success for user1
  6272. SKIP: {
  6273. if ( ! -r 'oauth2/D_oauth2_access_token_imapsync.gl0@gmail.com.txt' )
  6274. {
  6275. skip( 'oauthaccesstoken: no access_token file', 6 ) ;
  6276. }
  6277. my $myimap ;
  6278. my $mysync = {} ;
  6279. my $acc = {} ;
  6280. $acc->{ Side } = 'Host1' ;
  6281. $acc->{ oauthaccesstoken } = 'oauth2/D_oauth2_access_token_imapsync.gl0@gmail.com.txt' ;
  6282. $acc->{ debugimap } = 1 ;
  6283. $mysync->{ showpasswords } = 1 ;
  6284. $acc->{ authmech } = 'QQQ' ;
  6285. isa_ok(
  6286. $myimap = login_imap( 'imap.gmail.com', 993, 'imapsync.gl0@gmail.com', 'password_useless',
  6287. 1, undef,
  6288. 1, 100, $acc, $mysync,
  6289. ), 'Mail::IMAPClient', 'login_imap: user1 good oauthaccesstoken => Mail::IMAPClient' ) ;
  6290. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'login_imap: gmail oauth2 oauthaccesstoken IsAuthenticated' ) ;
  6291. ok( defined( $myimap ) && $myimap->logout( ), 'login_imap: gmail oauth2 oauthaccesstoken logout' ) ;
  6292. ok( defined( $myimap ) && ! $myimap->IsAuthenticated( ), 'login_imap: gmail oauth2 oauthaccesstoken not IsAuthenticated after logout' ) ;
  6293. ok( defined( $myimap ) && $myimap->reconnect( ), 'login_imap: gmail oauth2 oauthaccesstoken reconnect ok' ) ;
  6294. ok( defined( $myimap ) && $myimap->IsAuthenticated( ), 'login_imap: gmail oauth2 oauthaccesstoken IsAuthenticated after reconnect' ) ;
  6295. }
  6296. note( 'Leaving tests_login_imap_oauth()' ) ;
  6297. return ;
  6298. }
  6299. sub login_imap
  6300. {
  6301. my @allargs = @_ ;
  6302. my(
  6303. $host, $port, $user, $password,
  6304. $ssl, $tls,
  6305. $uid, $split, $acc, $mysync ) = @allargs ;
  6306. $acc->{ imap } = undef ;
  6307. if ( ! all_defined( $host, $port, $user, $acc->{ Side } ) )
  6308. {
  6309. return ;
  6310. }
  6311. my $side = lc $acc->{ Side } ;
  6312. myprint( "$acc->{ Side }: connecting and login on $side [$host] port [$port] with user [$user]\n" ) ;
  6313. my $imap = init_imap( @allargs ) ;
  6314. if ( ! $imap->connect() )
  6315. {
  6316. my $error = "$acc->{ Side } failure: can not open imap connection on $side [$host] with user [$user]: "
  6317. . $imap->LastError . " $OS_ERROR\n" ;
  6318. errors_incr( $mysync, $error ) ;
  6319. return ;
  6320. }
  6321. myprint( "$acc->{ Side } IP address: ", $imap->Socket->peerhost(), "\n" ) ;
  6322. my $banner = $imap->Results()->[0] ;
  6323. myprint( "$acc->{ Side } banner: $banner" ) ;
  6324. myprint( "$acc->{ Side } capability before authentication: ", join(q{ }, @{ $imap->capability() || [] }), "\n" ) ;
  6325. if ( (! $ssl) and (! defined $tls ) and $imap->has_capability( 'STARTTLS' ) ) {
  6326. myprint( "$acc->{ Side }: going to ssl because STARTTLS is in CAPABILITY. Use --notls1 or --notls2 to avoid that behavior\n" ) ;
  6327. $tls = 1 ;
  6328. }
  6329. #myprint( Data::Dumper->Dump( [ @allargs ] ) ) ;
  6330. if ( $tls ) {
  6331. set_tls( $imap, $acc ) ;
  6332. if ( ! $imap->starttls( ) )
  6333. {
  6334. my $error = "$acc->{ Side } failure: Can not go to tls encryption on $side [$host]: "
  6335. . $imap->LastError . "\n" ;
  6336. errors_incr( $mysync, $error ) ;
  6337. return ;
  6338. }
  6339. myprint( "$acc->{ Side }: Socket successfully converted to SSL\n" ) ;
  6340. }
  6341. if ( $acc->{ authmech } eq 'PREAUTH' ) {
  6342. if ( $imap->IsAuthenticated( ) ) {
  6343. $imap->Socket ;
  6344. myprintf("%s: Assuming PREAUTH for %s\n", $acc->{ Side }, $imap->Server ) ;
  6345. }else{
  6346. $mysync->{nb_errors}++ ;
  6347. exit_clean(
  6348. $mysync, $EXIT_AUTHENTICATION_FAILURE,
  6349. "$acc->{ Side } failure: error login on $side [$host] with user [$user] auth [PREAUTH]\n"
  6350. ) ;
  6351. }
  6352. }
  6353. if ( authenticate_imap( $imap, @allargs ) )
  6354. {
  6355. myprint( "$acc->{ Side }: success login on [$host] with user [$user] auth [$acc->{ authmech }] or [LOGIN]\n" ) ;
  6356. $acc->{ imap } = $imap ;
  6357. return( $imap ) ;
  6358. }
  6359. else
  6360. {
  6361. # The errors are already printed
  6362. myprint( "$acc->{ Side }: failed login on [$host] with user [$user] auth [$acc->{ authmech }]\n" ) ;
  6363. return ;
  6364. }
  6365. }
  6366. sub init_imap
  6367. {
  6368. my(
  6369. $host, $port, $user, $password,
  6370. $ssl, $tls,
  6371. $uid, $split, $acc, $mysync ) = @_ ;
  6372. my ( $imap ) ;
  6373. $imap = Mail::IMAPClient->new() ;
  6374. if ( $mysync->{ tee } )
  6375. {
  6376. # Well, it does not change anything, does it?
  6377. # It does when suppressing the hack with *STDERR
  6378. $imap->Debug_fh( $mysync->{ tee } ) ;
  6379. }
  6380. if ( $ssl ) { set_ssl( $imap, $acc ) }
  6381. if ( $tls ) { } # can not do set_tls() here because connect() will directly do a STARTTLS
  6382. $imap->Clear( 1 ) ;
  6383. $imap->Server( $host ) ;
  6384. $imap->Port( $port ) ;
  6385. $imap->Fast_io( $acc->{ fastio } ) ;
  6386. $imap->Buffer( $buffersize || $DEFAULT_BUFFER_SIZE ) ;
  6387. $imap->Uid( $uid ) ;
  6388. $imap->Peek( 1 ) ;
  6389. $imap->Debug( $acc->{ debugimap } ) ;
  6390. if ( $mysync->{ showpasswords } ) {
  6391. $imap->Showcredentials( 1 ) ;
  6392. }
  6393. if ( defined( $acc->{ timeout } ) )
  6394. {
  6395. $imap->Timeout( $acc->{ timeout } ) ;
  6396. }
  6397. if ( defined $acc->{ keepalive } )
  6398. {
  6399. $imap->Keepalive( $acc->{ keepalive } ) ;
  6400. }
  6401. if ( defined $acc->{ reconnectretry } )
  6402. {
  6403. $imap->Reconnectretry( $acc->{ reconnectretry } ) ;
  6404. }
  6405. $imap->{IMAPSYNC_RECONNECT_COUNT} = 0 ;
  6406. $imap->Ignoresizeerrors( $allowsizemismatch ) ;
  6407. $split and $imap->Maxcommandlength( $SPLIT_FACTOR * $split ) ;
  6408. return( $imap ) ;
  6409. }
  6410. sub authenticate_imap
  6411. {
  6412. my( $imap,
  6413. $host, $port, $user, $password,
  6414. $ssl, $tls,
  6415. $uid, $split, $acc, $mysync ) = @_ ;
  6416. check_capability( $imap, $acc->{ authmech }, $acc->{ Side } ) ;
  6417. $imap->User( $user ) ;
  6418. if ( defined $acc->{ domain } )
  6419. {
  6420. $imap->Domain( $acc->{ domain } ) ;
  6421. $mysync->{ debug } and myprint( "Domain: $acc->{ domain }\n" ) ;
  6422. }
  6423. $imap->Authuser( $acc->{ authuser } ) ;
  6424. $imap->Password( $password ) ;
  6425. if ( 'X-MASTERAUTH' eq $acc->{ authmech } )
  6426. {
  6427. xmasterauth( $imap ) ;
  6428. return 1 ;
  6429. }
  6430. if ( defined $acc->{ oauthdirect } )
  6431. {
  6432. $acc->{ authmech } = 'XOAUTH2 direct' ;
  6433. return( oauthdirect( $mysync, $acc, $imap, $host, $user ) ) ;
  6434. }
  6435. if ( defined $acc->{ oauthaccesstoken } )
  6436. {
  6437. $acc->{ authmech } = 'XOAUTH2 accesstoken' ;
  6438. return( oauthaccesstoken( $mysync, $acc, $imap, $host, $user ) ) ;
  6439. }
  6440. if ( $acc->{ proxyauth } ) {
  6441. $imap->Authmechanism(q{}) ;
  6442. $imap->User( $acc->{ authuser } ) ;
  6443. } else {
  6444. $imap->Authmechanism( $acc->{ authmech } ) unless ( $acc->{ authmech } eq 'LOGIN' or $acc->{ authmech } eq 'PREAUTH' ) ;
  6445. }
  6446. $imap->Authcallback(\&xoauth2) if ( 'XOAUTH2' eq $acc->{ authmech } ) ;
  6447. $imap->Authcallback(\&plainauth) if ( ( 'PLAIN' eq $acc->{ authmech } ) or ( 'EXTERNAL' eq $acc->{ authmech } ) ) ;
  6448. unless ( $acc->{ authmech } eq 'PREAUTH' or $imap->login( ) ) {
  6449. my $info = "$acc->{ Side } failure: Error login on [$host] with user [$user] auth" ;
  6450. my $einfo = imap_last_error( $imap ) ;
  6451. my $error = "$info [$acc->{ authmech }]: $einfo\n" ;
  6452. if ( ( $acc->{ authmech } eq 'LOGIN' ) or $imap->IsUnconnected( ) or $acc->{ authuser } ) {
  6453. $acc->{ authuser } ||= "" ;
  6454. myprint( "$acc->{ Side } info: authmech [$acc->{ authmech }] user [$user] authuser [$acc->{ authuser }] IsUnconnected [", $imap->IsUnconnected( ), "]\n" ) ;
  6455. errors_incr( $mysync, $error ) ;
  6456. return ;
  6457. }else{
  6458. errors_incr( $mysync, $error ) ;
  6459. }
  6460. # It is not secure to try plain text LOGIN when another authmech failed
  6461. # but I do it anyway. This behavior is optional as option --notrylogin will skip it.
  6462. if ( $mysync->{ trylogin } )
  6463. {
  6464. 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" ) ;
  6465. $imap->Authmechanism(q{}) ;
  6466. if ( ! $imap->login( ) )
  6467. {
  6468. failure_login( $mysync, $acc, 'LOGIN', $imap, $host, $user ) ;
  6469. return ;
  6470. }
  6471. else
  6472. {
  6473. myprint( "$acc->{ Side }: success login on [$host] with user [$user] auth [LOGIN] after [$acc->{ authmech }] failure\n" ) ;
  6474. }
  6475. }
  6476. else
  6477. {
  6478. 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" ) ;
  6479. return ;
  6480. }
  6481. }
  6482. if ( $acc->{ proxyauth } ) {
  6483. if ( ! $imap->proxyauth( $user ) ) {
  6484. failure_proxyauth( $mysync, $acc, $acc->{ authmech }, $imap, $host, $user ) ;
  6485. return ;
  6486. }
  6487. }
  6488. return 1;
  6489. }
  6490. sub failure_login
  6491. {
  6492. my( $mysync, $acc, $authmech, $imap, $host, $user ) = @ARG ;
  6493. my $info = "$acc->{ Side } failure: Error login on [$host] with user [$user] auth" ;
  6494. my $einfo = imap_last_error( $imap ) ;
  6495. my $error = "$info [$authmech]: $einfo\n" ;
  6496. errors_incr( $mysync, $error ) ;
  6497. return ;
  6498. }
  6499. # failure_login and failure_proxyauth function are similar but
  6500. # variable $error so no factoring
  6501. sub failure_proxyauth
  6502. {
  6503. my( $mysync, $acc, $authmech, $imap, $host, $user ) = @ARG ;
  6504. my $info = "$acc->{ Side } failure: Error login on [$host] with user [$user] auth" ;
  6505. my $einfo = imap_last_error( $imap ) ;
  6506. my $error = "$info [$authmech] using proxy-login as [$acc->{ authuser }]: $einfo\n" ;
  6507. errors_incr( $mysync, $error ) ;
  6508. return ;
  6509. }
  6510. sub oauthdirect
  6511. {
  6512. my( $mysync, $acc, $imap, $host, $user ) = @_ ;
  6513. my $oauthdirect_str ;
  6514. if ( -f -r $acc->{ oauthdirect } )
  6515. {
  6516. $oauthdirect_str = firstline( $acc->{ oauthdirect } ) ;
  6517. }
  6518. else
  6519. {
  6520. $oauthdirect_str = $acc->{ oauthdirect } || 'Please define oauthdirect value' ;
  6521. }
  6522. $imap->Authmechanism( 'XOAUTH2' ) ;
  6523. $imap->Authcallback( sub { return $oauthdirect_str } ) ;
  6524. #if ( $imap->authenticate('XOAUTH2', sub { return $oauthdirect_str } ) )
  6525. if ( $imap->login( ) )
  6526. {
  6527. return 1 ;
  6528. }
  6529. else
  6530. {
  6531. failure_login( $mysync, $acc, $acc->{ authmech }, $imap, $host, $user ) ;
  6532. return ;
  6533. }
  6534. return ;
  6535. }
  6536. sub oauthaccesstoken
  6537. {
  6538. my( $mysync, $acc, $imap, $host, $user ) = @_ ;
  6539. my $oauthaccesstoken_str ;
  6540. if ( -f -r $acc->{ oauthaccesstoken } )
  6541. {
  6542. $oauthaccesstoken_str = firstline( $acc->{ oauthaccesstoken } ) ;
  6543. }
  6544. else
  6545. {
  6546. $oauthaccesstoken_str = $acc->{ oauthaccesstoken } || 'Please define oauthaccesstoken value' ;
  6547. }
  6548. my $oauth_string = "user=" . $user . "\x01auth=Bearer ". $oauthaccesstoken_str . "\x01\x01" ;
  6549. #myprint "oauth_string: $oauth_string\n" ;
  6550. my $oauth_string_base64 = encode_base64( $oauth_string , '' ) ;
  6551. #myprint "oauth_string_base64: $oauth_string_base64\n" ;
  6552. my $oauthdirect_str = $oauth_string_base64 ;
  6553. $imap->Authmechanism( 'XOAUTH2' ) ;
  6554. $imap->Authcallback( sub { return $oauthdirect_str } ) ;
  6555. #if ( $imap->authenticate('XOAUTH2', sub { return $oauthdirect_str } ) )
  6556. if ( $imap->login( ) )
  6557. {
  6558. return 1 ;
  6559. }
  6560. else
  6561. {
  6562. failure_login( $mysync, $acc, $acc->{ authmech }, $imap, $host, $user ) ;
  6563. return ;
  6564. }
  6565. return ;
  6566. }
  6567. sub check_capability
  6568. {
  6569. my( $imap, $authmech, $Side ) = @_ ;
  6570. if ( $imap->has_capability( "AUTH=$authmech" )
  6571. or $imap->has_capability( $authmech ) )
  6572. {
  6573. myprintf("%s: %s says it has CAPABILITY for AUTHENTICATE %s\n",
  6574. $Side, $imap->Server, $authmech) ;
  6575. return ;
  6576. }
  6577. if ( $authmech eq 'LOGIN' )
  6578. {
  6579. # Well, the warning is so common and useless that I prefer to remove it
  6580. # No more "... says it has NO CAPABILITY for AUTHENTICATE LOGIN"
  6581. return ;
  6582. }
  6583. myprintf( "%s: %s says it has NO CAPABILITY for AUTHENTICATE %s\n",
  6584. $Side, $imap->Server, $authmech ) ;
  6585. if ( $authmech eq 'PLAIN' )
  6586. {
  6587. myprint( "$Side: frequently PLAIN is only supported with SSL, try --ssl or --tls options\n" ) ;
  6588. }
  6589. return ;
  6590. }
  6591. sub set_ssl
  6592. {
  6593. my ( $imap, $acc ) = @_ ;
  6594. # SSL_version can be
  6595. # SSLv3 SSLv2 SSLv23 SSLv23:!SSLv2 (last one is the default in IO-Socket-SSL-1.953)
  6596. #
  6597. my $sslargs_hash = $acc->{sslargs} ;
  6598. my $sslargs_default = {
  6599. SSL_verify_mode => $SSL_VERIFY_POLICY,
  6600. SSL_verifycn_scheme => 'imap',
  6601. SSL_cipher_list => 'DEFAULT:!DH',
  6602. } ;
  6603. # initiate with default values
  6604. my %sslargs_mix = %{ $sslargs_default } ;
  6605. # now override with passed values
  6606. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  6607. # remove keys with undef values
  6608. foreach my $key ( keys %sslargs_mix ) {
  6609. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  6610. }
  6611. # back to an ARRAY
  6612. my @sslargs_mix = %sslargs_mix ;
  6613. #myprint( Data::Dumper->Dump( [ $sslargs_hash, $sslargs_default, \%sslargs_mix, \@sslargs_mix ] ) ) ;
  6614. $imap->Ssl( \@sslargs_mix ) ;
  6615. return ;
  6616. }
  6617. sub set_tls
  6618. {
  6619. my ( $imap, $acc ) = @_ ;
  6620. my $sslargs_hash = $acc->{sslargs} ;
  6621. my $sslargs_default = {
  6622. SSL_verify_mode => $SSL_VERIFY_POLICY,
  6623. SSL_cipher_list => 'DEFAULT:!DH',
  6624. } ;
  6625. #myprint( Data::Dumper->Dump( [ $acc, $sslargs_hash, $sslargs_default ] ) ) ;
  6626. # initiate with default values
  6627. my %sslargs_mix = %{ $sslargs_default } ;
  6628. # now override with passed values
  6629. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  6630. # remove keys with undef values
  6631. foreach my $key ( keys %sslargs_mix ) {
  6632. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  6633. }
  6634. # back to an ARRAY
  6635. my @sslargs_mix = %sslargs_mix ;
  6636. $imap->Starttls( \@sslargs_mix ) ;
  6637. return ;
  6638. }
  6639. sub plainauth
  6640. {
  6641. my $code = shift;
  6642. my $imap = shift;
  6643. my $string = mysprintf("%s\x00%s\x00%s", $imap->User,
  6644. defined $imap->Authuser ? $imap->Authuser : "", $imap->Password);
  6645. return encode_base64("$string", q{});
  6646. }
  6647. # Copy from https://github.com/imapsync/imapsync/pull/25/files
  6648. # Changes "use" pragmas to "require".
  6649. # The openssl system call shall be replaced by pure Perl and
  6650. # https://metacpan.org/pod/Crypt::OpenSSL::PKCS12
  6651. # Now the Joaquin Lopez code:
  6652. #
  6653. # Used this as an example: https://gist.github.com/gsainio/6322375
  6654. #
  6655. # And this as a reference: https://developers.google.com/accounts/docs/OAuth2ServiceAccount
  6656. # (note there is an http/rest tab, where the real info is hidden away... went on a witch hunt
  6657. # until I noticed that...)
  6658. #
  6659. # This is targeted at gmail to maintain compatibility after google's oauth1 service is deactivated
  6660. # on May 5th, 2015: https://developers.google.com/gmail/oauth_protocol
  6661. # If there are other oauth2 implementations out there, this would need to be modified to be
  6662. # compatible
  6663. #
  6664. # This is a good guide on setting up the google api/apps side of the equation:
  6665. # http://www.limilabs.com/blog/oauth2-gmail-imap-service-account
  6666. #
  6667. # 2016/05/27: Updated to support oauth/key data in the .json files Google now defaults to
  6668. # when creating gmail service accounts. They're easier to work with since they neither
  6669. # requiring decrypting nor specifying the oauth2 client id separately.
  6670. #
  6671. # If the password arg ends in .json, it will assume this new json method, otherwise it
  6672. # will fallback to the "oauth client id;.p12" format it was previously using.
  6673. sub xoauth2
  6674. {
  6675. require JSON::WebToken ;
  6676. require LWP::UserAgent ;
  6677. require HTML::Entities ;
  6678. require JSON ;
  6679. require JSON::WebToken::Crypt::RSA ;
  6680. require Crypt::OpenSSL::RSA ;
  6681. require Encode::Byte ;
  6682. require IO::Socket::SSL ;
  6683. my $code = shift;
  6684. my $imap = shift;
  6685. my ($iss,$key);
  6686. if( $imap->Password =~ /^(.*\.json)$/x )
  6687. {
  6688. my $json = JSON->new( ) ;
  6689. my $filename = $1;
  6690. $sync->{ debug } and myprint( "XOAUTH2 json file: $filename\n" ) ;
  6691. my $FILE ;
  6692. if ( ! open( $FILE, '<', $filename ) )
  6693. {
  6694. $sync->{nb_errors}++ ;
  6695. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6696. "error [$filename]: $OS_ERROR\n"
  6697. ) ;
  6698. }
  6699. my $jsonfile = $json->decode( join q{}, <$FILE> ) ;
  6700. close $FILE ;
  6701. $iss = $jsonfile->{client_id};
  6702. $key = $jsonfile->{private_key};
  6703. $sync->{ debug } and myprint( "Service account: $iss\n");
  6704. $sync->{ debug } and myprint( "Private key:\n$key\n");
  6705. }
  6706. else
  6707. {
  6708. # Get iss (service account address), keyfile name, and keypassword if necessary
  6709. ( $iss, my $keyfile, my $keypass ) = $imap->Password =~ /([\-\d\w\@\.]+);([a-zA-Z0-9 \_\-\.\/]+);?(.*)?/x ;
  6710. # Assume key password is google default if not provided
  6711. $keypass = 'notasecret' if not $keypass;
  6712. $sync->{ debug } and myprint( "Service account: $iss\nKey file: $keyfile\nKey password: $keypass\n");
  6713. # Get private key from p12 file (would be better in perl...)
  6714. $key = `openssl pkcs12 -in "$keyfile" -nodes -nocerts -passin pass:$keypass -nomacver`;
  6715. $sync->{ debug } and myprint( "Private key:\n$key\n");
  6716. }
  6717. # Create jwt of oauth2 request
  6718. my $time = time ;
  6719. my $jwt = JSON::WebToken->encode( {
  6720. 'iss' => $iss, # service account
  6721. 'scope' => 'https://mail.google.com/',
  6722. 'aud' => 'https://www.googleapis.com/oauth2/v3/token',
  6723. 'exp' => $time + $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12,
  6724. 'iat' => $time,
  6725. 'prn' => $imap->User # user to auth as
  6726. },
  6727. $key, 'RS256', {'typ' => 'JWT'} ); # Crypt::OpenSSL::RSA needed here.
  6728. # Post oauth2 request
  6729. my $ua = LWP::UserAgent->new( ) ;
  6730. $ua->env_proxy( ) ;
  6731. my $response = $ua->post('https://www.googleapis.com/oauth2/v3/token',
  6732. { grant_type => HTML::Entities::encode_entities('urn:ietf:params:oauth:grant-type:jwt-bearer'),
  6733. assertion => $jwt } ) ;
  6734. unless( $response->is_success( ) ) {
  6735. $sync->{nb_errors}++ ;
  6736. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6737. $response->code, "\n", $response->content, "\n"
  6738. ) ;
  6739. }else{
  6740. $sync->{ debug } and myprint( $response->content ) ;
  6741. }
  6742. # access_token in response is what we need
  6743. my $data = JSON::decode_json( $response->content ) ;
  6744. # format as oauth2 auth data
  6745. my $xoauth2_string = encode_base64( 'user=' . $imap->User . "\1auth=Bearer " . $data->{access_token} . "\1\1", q{} ) ;
  6746. $sync->{ debug } and myprint( "XOAUTH2 String: $xoauth2_string\n");
  6747. return($xoauth2_string);
  6748. }
  6749. sub xmasterauth
  6750. {
  6751. # This is Kerio auth admin
  6752. # This code comes from
  6753. # https://github.com/imapsync/imapsync/pull/53/files
  6754. my $imap = shift ;
  6755. my $user = $imap->User( ) ;
  6756. my $password = $imap->Password( ) ;
  6757. my $authmech = 'X-MASTERAUTH' ;
  6758. my @challenge = $imap->tag_and_run( $authmech, "+" ) ;
  6759. if ( not defined $challenge[0] )
  6760. {
  6761. $sync->{nb_errors}++ ;
  6762. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6763. "Failure authenticate with $authmech: ",
  6764. $imap->LastError, "\n"
  6765. ) ;
  6766. return ; # hahaha!
  6767. }
  6768. $sync->{ debug } and myprint( "X-MASTERAUTH challenge: [@challenge]\n" ) ;
  6769. $challenge[1] =~ s/^\+ |^\s+|\s+$//g ;
  6770. if ( ! $imap->_imap_command( { addcrlf => 1, addtag => 0, tag => $imap->Count }, md5_hex( $challenge[1] . $password ) ) )
  6771. {
  6772. $sync->{nb_errors}++ ;
  6773. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6774. "Failure authenticate with $authmech: ",
  6775. $imap->LastError, "\n"
  6776. ) ;
  6777. }
  6778. if ( ! $imap->tag_and_run( 'X-SETUSER ' . $user ) )
  6779. {
  6780. $sync->{nb_errors}++ ;
  6781. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  6782. "Failure authenticate with $authmech: ",
  6783. "X-SETUSER ", $imap->LastError, "\n"
  6784. ) ;
  6785. }
  6786. $imap->State( Mail::IMAPClient::Authenticated ) ;
  6787. # I comment this state because "Selected" state is usually done by SELECT or EXAMINE imap commands
  6788. # $imap->State( Mail::IMAPClient::Selected ) ;
  6789. return ;
  6790. }
  6791. sub keepalive1
  6792. {
  6793. my $mysync = shift ;
  6794. $mysync->{ acc1 }->{ keepalive } = defined $mysync->{ acc1 }->{ keepalive } ? $mysync->{ acc1 }->{ keepalive } : 1 ;
  6795. if ( $mysync->{ acc1 }->{ keepalive } )
  6796. {
  6797. myprint( "Host1: imap connection keepalive is on on host1. Use --nokeepalive1 to disable it.\n" ) ;
  6798. }
  6799. else
  6800. {
  6801. myprint( "Host1: imap connection keepalive is off on host1. Use --keepalive1 to enable it.\n" ) ;
  6802. }
  6803. }
  6804. sub keepalive2
  6805. {
  6806. my $mysync = shift ;
  6807. $mysync->{ acc2 }->{ keepalive } = defined $mysync->{ acc2 }->{ keepalive } ? $mysync->{ acc2 }->{ keepalive } : 1 ;
  6808. if ( $mysync->{ acc2 }->{ keepalive } )
  6809. {
  6810. myprint( "Host2: imap connection keepalive is on on host2. Use --nokeepalive2 to disable it.\n" ) ;
  6811. }
  6812. else
  6813. {
  6814. myprint( "Host2: imap connection keepalive is off on host2. Use --keepalive2 to enable it.\n" ) ;
  6815. }
  6816. }
  6817. sub banner_imapsync
  6818. {
  6819. my $mysync = shift @ARG ;
  6820. my @argv = @ARG ;
  6821. my $banner_imapsync = join q{},
  6822. q{$RCSfile: imapsync,v $ },
  6823. q{$Revision: 2.178 $ },
  6824. q{$Date: 2022/01/12 21:28:37 $ },
  6825. "\n",
  6826. "Command line used, run by $EXECUTABLE_NAME:\n",
  6827. "$PROGRAM_NAME ", command_line_nopassword( $mysync, @argv ), "\n" ;
  6828. return( $banner_imapsync ) ;
  6829. }
  6830. sub tests_do_valid_directory
  6831. {
  6832. note( 'Entering tests_do_valid_directory()' ) ;
  6833. is( 1, do_valid_directory( '.'), 'do_valid_directory: . good' ) ;
  6834. is( 1, do_valid_directory( './W/tmp/tests/valid/sub'), 'do_valid_directory: ./W/tmp/tests/valid/sub good' ) ;
  6835. Readonly my $NB_UNIX_tests_do_valid_directory_non_root => 2 ;
  6836. diag( "OSNAME=$OSNAME EFFECTIVE_USER_ID=$EFFECTIVE_USER_ID" ) ;
  6837. SKIP: {
  6838. skip( 'Tests only for non roor user', $NB_UNIX_tests_do_valid_directory_non_root ) if ( '0' eq $EFFECTIVE_USER_ID ) ;
  6839. diag( 'The "Error / is not writable" is on purpose' ) ;
  6840. ok( 0 == do_valid_directory( '/'), 'do_valid_directory: / bad' ) ;
  6841. diag( 'The "Error permission denied" on /noway is on purpose' ) ;
  6842. ok( 0 == do_valid_directory( '/noway'), 'do_valid_directory: /noway bad' ) ;
  6843. }
  6844. note( 'Leaving tests_do_valid_directory()' ) ;
  6845. return ;
  6846. }
  6847. sub do_valid_directory
  6848. {
  6849. my $dir = shift @ARG ;
  6850. # all good => return ok.
  6851. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  6852. # exist but bad
  6853. if ( -e $dir and not -d _ ) {
  6854. myprint( "Error: $dir exists but is not a directory\n" ) ;
  6855. return( 0 ) ;
  6856. }
  6857. if ( -e $dir and not -w _ ) {
  6858. my $sb = stat $dir ;
  6859. myprintf( "Error: directory %s is not writable for user %s, permissions are %04o and owner is %s ( uid %s )\n",
  6860. $dir, getpwuid_any_os( $EFFECTIVE_USER_ID ), ($sb->mode & oct($PERMISSION_FILTER) ), getpwuid_any_os( $sb->uid ), $sb->uid( ) ) ;
  6861. return( 0 ) ;
  6862. }
  6863. # Trying to create it
  6864. myprint( "Creating directory $dir (current directory is " . getcwd( ) . ")\n" ) ;
  6865. if ( ! eval { mkpath( $dir ) } ) {
  6866. myprint( "$EVAL_ERROR" ) if ( $EVAL_ERROR ) ;
  6867. }
  6868. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  6869. return( 0 ) ;
  6870. }
  6871. sub tests_match_a_pid_number
  6872. {
  6873. note( 'Entering tests_match_a_pid_number()' ) ;
  6874. is( undef, match_a_pid_number( ), 'match_a_pid_number: no args => undef' ) ;
  6875. is( undef, match_a_pid_number( q{} ), 'match_a_pid_number: "" => undef' ) ;
  6876. is( undef, match_a_pid_number( 'lalala' ), 'match_a_pid_number: lalala => undef' ) ;
  6877. is( 1, match_a_pid_number( 1 ), 'match_a_pid_number: 1 => 1' ) ;
  6878. is( 1, match_a_pid_number( 123 ), 'match_a_pid_number: 123 => 1' ) ;
  6879. is( 1, match_a_pid_number( -123 ), 'match_a_pid_number: -123 => 1' ) ;
  6880. is( 1, match_a_pid_number( '123' ), 'match_a_pid_number: "123" => 1' ) ;
  6881. is( 1, match_a_pid_number( '-123' ), 'match_a_pid_number: "-123" => 1' ) ;
  6882. is( undef, match_a_pid_number( 'a123' ), 'match_a_pid_number: a123 => undef' ) ;
  6883. is( undef, match_a_pid_number( '-a123' ), 'match_a_pid_number: -a123 => undef' ) ;
  6884. is( 1, match_a_pid_number( 99999 ), 'match_a_pid_number: 99999 => 1' ) ;
  6885. is( 1, match_a_pid_number( -99999 ), 'match_a_pid_number: -99999 => 1' ) ;
  6886. is( undef, match_a_pid_number( 0 ), 'match_a_pid_number: 0 => undef' ) ;
  6887. is( 1, match_a_pid_number( 100000 ), 'match_a_pid_number: 100000 => 1' ) ;
  6888. is( 1, match_a_pid_number( 123456 ), 'match_a_pid_number: 123456 => 1' ) ;
  6889. is( undef, match_a_pid_number( '-0' ), 'match_a_pid_number: "-0" => undef' ) ;
  6890. is( 1, match_a_pid_number( -100000 ), 'match_a_pid_number: -100000 => 1' ) ;
  6891. is( 1, match_a_pid_number( -123456 ), 'match_a_pid_number: -123456 => 1' ) ;
  6892. is( 1, match_a_pid_number( 2**22 ), 'match_a_pid_number: 2**22 => 1' ) ;
  6893. is( undef, match_a_pid_number( 2**22 + 1 ), 'match_a_pid_number: 2**22 + 1 => undef' ) ;
  6894. is( undef, match_a_pid_number( 4194304 + 1 ), 'match_a_pid_number: 2**22 + 1 = 4194305 => undef' ) ;
  6895. note( 'Leaving tests_match_a_pid_number()' ) ;
  6896. return ;
  6897. }
  6898. sub match_a_pid_number
  6899. {
  6900. my $pid = shift @ARG ;
  6901. if ( ! defined $pid ) { return ; }
  6902. #print "$pid\n" ;
  6903. if ( ! match( $pid, '^-?\d+$' ) ) { return ; }
  6904. #print "$pid\n" ;
  6905. # can be negative on Windows
  6906. #if ( 0 > $pid ) { return ; }
  6907. #if ( 65535 < $pid ) { return ; }
  6908. if ( 2**22 < abs( $pid ) ) { return ; }
  6909. if ( 0 == abs( $pid ) ) { return ; }
  6910. return 1 ;
  6911. }
  6912. sub tests_remove_pidfile_not_running
  6913. {
  6914. note( 'Entering tests_remove_pidfile_not_running()' ) ;
  6915. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'remove_pidfile_not_running: mkpath W/tmp/tests/' ) ;
  6916. is( undef, remove_pidfile_not_running( ), 'remove_pidfile_not_running: no args => undef' ) ;
  6917. is( undef, remove_pidfile_not_running( './W' ), 'remove_pidfile_not_running: a dir => undef' ) ;
  6918. is( undef, remove_pidfile_not_running( 'noexists' ), 'remove_pidfile_not_running: noexists => undef' ) ;
  6919. is( 1, touch( 'W/tmp/tests/empty.pid' ), 'remove_pidfile_not_running: prepa empty W/tmp/tests/empty.pid' ) ;
  6920. is( undef, remove_pidfile_not_running( 'W/tmp/tests/empty.pid' ), 'remove_pidfile_not_running: W/tmp/tests/empty.pid => undef' ) ;
  6921. is( 'lalala', string_to_file( 'lalala', 'W/tmp/tests/lalala.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/lalala.pid' ) ;
  6922. is( undef, remove_pidfile_not_running( 'W/tmp/tests/lalala.pid' ), 'remove_pidfile_not_running: W/tmp/tests/lalala.pid => undef' ) ;
  6923. is( '55555', string_to_file( '55555', 'W/tmp/tests/notrunning.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/notrunning.pid' ) ;
  6924. is( 1, remove_pidfile_not_running( 'W/tmp/tests/notrunning.pid' ), 'remove_pidfile_not_running: W/tmp/tests/notrunning.pid => 1' ) ;
  6925. is( $PROCESS_ID, string_to_file( $PROCESS_ID, 'W/tmp/tests/running.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/running.pid' ) ;
  6926. is( undef, remove_pidfile_not_running( 'W/tmp/tests/running.pid' ), 'remove_pidfile_not_running: W/tmp/tests/running.pid => undef' ) ;
  6927. note( 'Leaving tests_remove_pidfile_not_running()' ) ;
  6928. return ;
  6929. }
  6930. sub remove_pidfile_not_running
  6931. {
  6932. #
  6933. my $pid_filename = shift @ARG ;
  6934. #myprint( "In remove_pidfile_not_running $pid_filename\n" ) ;
  6935. if ( ! $pid_filename ) { myprint( "No variable pid_filename\n" ) ; return } ;
  6936. if ( ! -e $pid_filename )
  6937. {
  6938. myprint( "File $pid_filename does not exist\n" ) ;
  6939. return ;
  6940. }
  6941. #myprint( "Still In remove_pidfile_not_running $pid_filename\n" ) ;
  6942. if ( ! -f $pid_filename ) { myprint( "File $pid_filename is not a file\n" ) ; return } ;
  6943. my $pid = firstline( $pid_filename ) ;
  6944. if ( ! match_a_pid_number( $pid ) ) { myprint( "In remove_pidfile_not_running: pid $pid in $pid_filename is not a pid number\n" ) ; return } ;
  6945. # can't kill myself => do nothing
  6946. if ( ! kill 'ZERO', $PROCESS_ID ) { myprint( "Can not kill ZERO myself $PROCESS_ID\n" ) ; return } ;
  6947. # can't kill ZERO the pid => it is gone or own by another user => remove pidfile
  6948. if ( ! kill 'ZERO', $pid ) {
  6949. myprint( "Removing old $pid_filename since its PID $pid is not running anymore (oo-killed?)\n" ) ;
  6950. if ( unlink $pid_filename ) {
  6951. myprint( "Removed old $pid_filename\n" ) ;
  6952. return 1 ;
  6953. }else{
  6954. myprint( "Could not remove old $pid_filename because $!\n" ) ;
  6955. return ;
  6956. }
  6957. }
  6958. myprint( "Another imapsync process $pid is running as says pidfile $pid_filename\n" ) ;
  6959. return ;
  6960. }
  6961. sub tests_tail
  6962. {
  6963. note( 'Entering tests_tail()' ) ;
  6964. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'tail: mkpath W/tmp/tests/' ) ;
  6965. ok( ( ! -e 'W/tmp/tests/tail.pid' || unlink 'W/tmp/tests/tail.pid' ), 'tail: unlink W/tmp/tests/tail.pid' ) ;
  6966. ok( ( ! -e 'W/tmp/tests/tail.txt' || unlink 'W/tmp/tests/tail.txt' ), 'tail: unlink W/tmp/tests/tail.txt' ) ;
  6967. is( undef, tail( ), 'tail: no args => undef' ) ;
  6968. my $mysync ;
  6969. is( undef, tail( $mysync ), 'tail: no pidfile => undef' ) ;
  6970. $mysync->{pidfile} = 'W/tmp/tests/tail.pid' ;
  6971. is( undef, tail( $mysync ), 'tail: no pidfilelocking => undef' ) ;
  6972. $mysync->{pidfilelocking} = 1 ;
  6973. is( undef, tail( $mysync ), 'tail: pidfile no exists => undef' ) ;
  6974. my $pidandlog = "33333\nW/tmp/tests/tail.txt\n" ;
  6975. is( $pidandlog, string_to_file( $pidandlog, $mysync->{pidfile} ), 'tail: put pid 33333 and tail.txt in pidfile' ) ;
  6976. is( undef, tail( $mysync ), 'tail: logfile to tail no exists => undef' ) ;
  6977. my $tailcontent = "L1\nL2\nL3\nL4\nL5\n" ;
  6978. is( $tailcontent, string_to_file( $tailcontent, 'W/tmp/tests/tail.txt' ),
  6979. 'tail: put L1\nL2\nL3\nL4\nL5\n in W/tmp/tests/tail.txt' ) ;
  6980. is( undef, tail( $mysync ), 'tail: fake pid in pidfile + tail off => 1' ) ;
  6981. $mysync->{ tail } = 1 ;
  6982. is( 1, tail( $mysync ), 'tail: fake pid in pidfile + tail on=> 1' ) ;
  6983. # put my own pid, won't do tail
  6984. $pidandlog = "$PROCESS_ID\nW/tmp/tests/tail.txt\n" ;
  6985. is( $pidandlog, string_to_file( $pidandlog, $mysync->{pidfile} ), 'tail: put my own PID in pidfile' ) ;
  6986. is( undef, tail( $mysync ), 'tail: my own pid in pidfile => undef' ) ;
  6987. note( 'Leaving tests_tail()' ) ;
  6988. return ;
  6989. }
  6990. sub tail
  6991. {
  6992. # return undef on failures
  6993. # return 1 on success
  6994. my $mysync = shift ;
  6995. # no tail when aborting!
  6996. if ( $mysync->{ abort } ) { return ; }
  6997. my $pidfile = $mysync->{pidfile} ;
  6998. my $lock = $mysync->{pidfilelocking} ;
  6999. my $tail = $mysync->{tail} ;
  7000. if ( ! $pidfile ) { return ; }
  7001. if ( ! $lock ) { return ; }
  7002. if ( ! $tail ) { return ; }
  7003. if ( ! -e $pidfile ) { return ; }
  7004. my $pidtotail = firstline( $pidfile ) ;
  7005. if ( ! $pidtotail ) { return ; }
  7006. # It should not happen but who knows...
  7007. if ( $pidtotail eq $PROCESS_ID ) { return ; }
  7008. my $filetotail = secondline( $pidfile ) ;
  7009. if ( ! $filetotail ) { return ; }
  7010. if ( ! -r $filetotail )
  7011. {
  7012. #myprint( "Error: can not read $filetotail\n" ) ;
  7013. return ;
  7014. }
  7015. myprint( "Doing a tail -f on $filetotail for processus pid $pidtotail until it is finished.\n" ) ;
  7016. my $file = File::Tail->new(
  7017. name => $filetotail,
  7018. nowait => 1,
  7019. interval => 1,
  7020. tail => 1,
  7021. adjustafter => 2
  7022. );
  7023. my $moretimes = 200 ;
  7024. # print one line at least
  7025. my $line = $file->read ;
  7026. myprint( $line ) ;
  7027. while ( isrunning( $pidtotail, \$moretimes ) and defined( $line = $file->read ) )
  7028. {
  7029. myprint( $line );
  7030. sleep( 0.02 ) ;
  7031. }
  7032. return 1 ;
  7033. }
  7034. sub isrunning
  7035. {
  7036. my $pidtocheck = shift ;
  7037. my $moretimes_ref = shift ;
  7038. if ( kill 'ZERO', $pidtocheck )
  7039. {
  7040. #myprint( "$pidtocheck running\n" ) ;
  7041. return 1 ;
  7042. }
  7043. elsif ( $$moretimes_ref >= 0 )
  7044. {
  7045. # continue to consider it running
  7046. $$moretimes_ref-- ;
  7047. return 1 ;
  7048. }
  7049. else
  7050. {
  7051. myprint( "Tailed processus $pidtocheck ended\n" ) ;
  7052. return ;
  7053. }
  7054. }
  7055. sub tests_write_pidfile
  7056. {
  7057. note( 'Entering tests_write_pidfile()' ) ;
  7058. my $mysync ;
  7059. is( 1, write_pidfile( ), 'write_pidfile: no args => 1' ) ;
  7060. # no pidfile => ok
  7061. $mysync->{pidfile} = q{} ;
  7062. is( 1, write_pidfile( $mysync ), 'write_pidfile: no pidfile => undef' ) ;
  7063. # The pidfile path is bad => failure
  7064. $mysync->{pidfile} = '/no/no/no.pid' ;
  7065. is( undef, write_pidfile( $mysync ), 'write_pidfile: no permission for /no/no/no.pid, no lock => undef' ) ;
  7066. $mysync->{pidfilelocking} = 1 ;
  7067. is( undef, write_pidfile( $mysync ), 'write_pidfile: no permission for /no/no/no.pid + lock => undef' ) ;
  7068. $mysync->{pidfile} = 'W/tmp/tests/test.pid' ;
  7069. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'write_pidfile: mkpath W/tmp/tests/' ) ;
  7070. is( 1, touch( $mysync->{pidfile} ), 'write_pidfile: lock prepa' ) ;
  7071. $mysync->{pidfilelocking} = 0 ;
  7072. is( 1, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + no lock => 1' ) ;
  7073. is( $PROCESS_ID, firstline( 'W/tmp/tests/test.pid' ), "write_pidfile: W/tmp/tests/test.pid contains $PROCESS_ID" ) ;
  7074. is( q{}, secondline( 'W/tmp/tests/test.pid' ), "write_pidfile: W/tmp/tests/test.pid contains no second line" ) ;
  7075. $mysync->{pidfilelocking} = 1 ;
  7076. is( undef, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + lock => undef' ) ;
  7077. $mysync->{pidfilelocking} = 0 ;
  7078. $mysync->{ logfile } = 'rrrr.txt' ;
  7079. is( 1, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + no lock + logfile => 1' ) ;
  7080. is( $PROCESS_ID, firstline( 'W/tmp/tests/test.pid' ), "write_pidfile: + no lock + logfile W/tmp/tests/test.pid contains $PROCESS_ID" ) ;
  7081. is( q{rrrr.txt}, secondline( 'W/tmp/tests/test.pid' ), "write_pidfile: + no lock + logfile W/tmp/tests/test.pid contains rrrr.txt" ) ;
  7082. note( 'Leaving tests_write_pidfile()' ) ;
  7083. return ;
  7084. }
  7085. sub write_pidfile
  7086. {
  7087. # returns undef if something is considered fatal
  7088. # returns 1 otherwise
  7089. #myprint( "In write_pidfile\n" ) ;
  7090. if ( ! @ARG ) { return 1 ; }
  7091. my $mysync = shift @ARG ;
  7092. # Do not write the pid file if the current process goal is to abort the process designed by the pid file
  7093. if ( $mysync->{ abort } ) { return 1 ; }
  7094. #
  7095. my $pid_filename = $mysync->{ pidfile } ;
  7096. my $lock = $mysync->{ pidfilelocking } ;
  7097. if ( ! $pid_filename )
  7098. {
  7099. myprint( "PID file is unset ( to set it, use --pidfile filepath ; to avoid it use --pidfile \"\" )\n" ) ;
  7100. return( 1 ) ;
  7101. }
  7102. myprint( "PID file is $pid_filename ( to change it, use --pidfile filepath ; to avoid it use --pidfile \"\" )\n" ) ;
  7103. if ( -e $pid_filename and $lock ) {
  7104. myprint( "$pid_filename already exists, another imapsync may be curently running. Aborting imapsync.\n" ) ;
  7105. return ;
  7106. }
  7107. if ( -e $pid_filename ) {
  7108. myprint( "$pid_filename already exists, overwriting it ( use --pidfilelocking to avoid concurrent runs )\n" ) ;
  7109. }
  7110. my $pid_string = "$PROCESS_ID\n" ;
  7111. my $pid_message = "Writing my PID $PROCESS_ID in $pid_filename\n" ;
  7112. if ( $mysync->{ logfile } )
  7113. {
  7114. $pid_string .= "$mysync->{ logfile }\n" ;
  7115. $pid_message .= "Writing also my logfile name in $pid_filename : $mysync->{ logfile }\n" ;
  7116. }
  7117. if ( open my $FILE_HANDLE, '>', $pid_filename ) {
  7118. myprint( $pid_message ) ;
  7119. print $FILE_HANDLE $pid_string ;
  7120. close $FILE_HANDLE ;
  7121. return( 1 ) ;
  7122. }
  7123. else
  7124. {
  7125. myprint( "Could not open $pid_filename for writing. Check permissions or disk space: $OS_ERROR\n" ) ;
  7126. return ;
  7127. }
  7128. }
  7129. sub fix_Inbox_INBOX_mapping
  7130. {
  7131. my( $h1_all, $h2_all ) = @_ ;
  7132. my $regex = q{} ;
  7133. SWITCH: {
  7134. if ( exists $h1_all->{INBOX} and exists $h2_all->{INBOX} ) { $regex = q{} ; last SWITCH ; } ;
  7135. if ( exists $h1_all->{Inbox} and exists $h2_all->{Inbox} ) { $regex = q{} ; last SWITCH ; } ;
  7136. if ( exists $h1_all->{INBOX} and exists $h2_all->{Inbox} ) { $regex = q{s/^INBOX$/Inbox/x} ; last SWITCH ; } ;
  7137. if ( exists $h1_all->{Inbox} and exists $h2_all->{INBOX} ) { $regex = q{s/^Inbox$/INBOX/x} ; last SWITCH ; } ;
  7138. } ;
  7139. return( $regex ) ;
  7140. }
  7141. sub tests_fix_Inbox_INBOX_mapping
  7142. {
  7143. note( 'Entering tests_fix_Inbox_INBOX_mapping()' ) ;
  7144. my( $h1_all, $h2_all ) ;
  7145. $h1_all = { 'INBOX' => q{} } ;
  7146. $h2_all = { 'INBOX' => q{} } ;
  7147. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX INBOX' ) ;
  7148. $h1_all = { 'Inbox' => q{} } ;
  7149. $h2_all = { 'Inbox' => q{} } ;
  7150. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox Inbox' ) ;
  7151. $h1_all = { 'INBOX' => q{} } ;
  7152. $h2_all = { 'Inbox' => q{} } ;
  7153. ok( q{s/^INBOX$/Inbox/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX Inbox' ) ;
  7154. $h1_all = { 'Inbox' => q{} } ;
  7155. $h2_all = { 'INBOX' => q{} } ;
  7156. ok( q{s/^Inbox$/INBOX/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox INBOX' ) ;
  7157. $h1_all = { 'INBOX' => q{} } ;
  7158. $h2_all = { 'rrrrr' => q{} } ;
  7159. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX rrrrrr' ) ;
  7160. $h1_all = { 'rrrrr' => q{} } ;
  7161. $h2_all = { 'Inbox' => q{} } ;
  7162. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: rrrrr Inbox' ) ;
  7163. note( 'Leaving tests_fix_Inbox_INBOX_mapping()' ) ;
  7164. return ;
  7165. }
  7166. sub jux_utf8_list
  7167. {
  7168. my @s_inp = @_ ;
  7169. my $s_out = q{} ;
  7170. foreach my $s ( @s_inp ) {
  7171. $s_out .= jux_utf8( $s ) . "\n" ;
  7172. }
  7173. return( $s_out ) ;
  7174. }
  7175. sub tests_jux_utf8_list
  7176. {
  7177. note( 'Entering tests_jux_utf8_list()' ) ;
  7178. use utf8 ;
  7179. is( q{}, jux_utf8_list( ), 'jux_utf8_list: void' ) ;
  7180. is( "[]\n", jux_utf8_list( q{} ), 'jux_utf8_list: empty string' ) ;
  7181. is( "[INBOX]\n", jux_utf8_list( 'INBOX' ), 'jux_utf8_list: INBOX' ) ;
  7182. is( "[&ANY-] = [Ö]\n", jux_utf8_list( '&ANY-' ), 'jux_utf8_list: [&ANY-] = [Ö]' ) ;
  7183. note( 'Leaving tests_jux_utf8_list()' ) ;
  7184. return( 0 ) ;
  7185. }
  7186. # editing utf8 can be tricky without an utf8 editor
  7187. sub tests_jux_utf8_old
  7188. {
  7189. note( 'Entering tests_jux_utf8_old()' ) ;
  7190. no utf8 ;
  7191. is( '[]', jux_utf8_old( q{} ), 'jux_utf8_old: void => []' ) ;
  7192. is( '[INBOX]', jux_utf8_old( 'INBOX'), 'jux_utf8_old: INBOX => [INBOX]' ) ;
  7193. is( '[&ZTZO9nux-] = [æ”¶ä»¶ç®±]', jux_utf8_old( '&ZTZO9nux-'), 'jux_utf8_old: => [&ZTZO9nux-] = [æ”¶ä»¶ç®±]' ) ;
  7194. is( '[&ANY-] = [Ö]', jux_utf8_old( '&ANY-'), 'jux_utf8_old: &ANY- => [&ANY-] = [Ö]' ) ;
  7195. # +BD8EQAQ1BDQEOwQ+BDM- SHOULD stay as is!
  7196. is( '[+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]', jux_utf8_old( '+BD8EQAQ1BDQEOwQ+BDM-' ), 'jux_utf8_old: => [+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]' ) ;
  7197. is( '[&BB8EQAQ+BDUEOgRC-] = [Проект]', jux_utf8_old( '&BB8EQAQ+BDUEOgRC-' ), 'jux_utf8_old: => [&BB8EQAQ+BDUEOgRC-] = [Проект]' ) ;
  7198. note( 'Leaving tests_jux_utf8_old()' ) ;
  7199. return ;
  7200. }
  7201. sub jux_utf8_old
  7202. {
  7203. # juxtapose utf8 at the right if different
  7204. my ( $s_utf7 ) = shift ;
  7205. my ( $s_utf8 ) = imap_utf7_decode_old( $s_utf7 ) ;
  7206. if ( $s_utf7 eq $s_utf8 ) {
  7207. #myprint( "[$s_utf7]\n" ) ;
  7208. return( "[$s_utf7]" ) ;
  7209. }else{
  7210. #myprint( "[$s_utf7] = [$s_utf8]\n" ) ;
  7211. return( "[$s_utf7] = [$s_utf8]" ) ;
  7212. }
  7213. }
  7214. # Copied from http://cpansearch.perl.org/src/FABPOT/Unicode-IMAPUtf7-2.01/lib/Unicode/IMAPUtf7.pm
  7215. # and then fixed with
  7216. # https://rt.cpan.org/Public/Bug/Display.html?id=11172
  7217. sub imap_utf7_decode_old
  7218. {
  7219. my ( $s ) = shift ;
  7220. # Algorithm
  7221. # On remplace , par / dans les BASE 64 (, entre & et -)
  7222. # On remplace les &, non suivi d'un - par +
  7223. # On remplace les &- par &
  7224. $s =~ s/&([^,&\-]*),([^,\-&]*)\-/&$1\/$2\-/xg ;
  7225. $s =~ s/&(?!\-)/\+/xg ;
  7226. $s =~ s/&\-/&/xg ;
  7227. return( Unicode::String::utf7( $s )->utf8 ) ;
  7228. }
  7229. sub tests_jux_utf8
  7230. {
  7231. note( 'Entering tests_jux_utf8()' ) ;
  7232. #no utf8 ;
  7233. use utf8 ;
  7234. #binmode STDOUT, ":encoding(UTF-8)" ;
  7235. binmode STDERR, ":encoding(UTF-8)" ;
  7236. # This test is because the binary can fail on it, a PAR.pm issue.
  7237. # The failure was with the underlying Encode::IMAPUTF7 module line 66 release 1.05
  7238. # Was solved by including Encode in imapsync and using "pp -x".
  7239. ok( find_encoding( "UTF-16BE"), 'jux_utf8: Encode::find_encoding: UTF-16BE' ) ;
  7240. #
  7241. is( '[]', jux_utf8( q{} ), 'jux_utf8: void => []' ) ;
  7242. is( '[INBOX]', jux_utf8( 'INBOX'), 'jux_utf8: INBOX => [INBOX]' ) ;
  7243. is( '[&ANY-] = [Ö]', jux_utf8( '&ANY-'), 'jux_utf8: &ANY- => [&ANY-] = [Ö]' ) ;
  7244. # +BD8EQAQ1BDQEOwQ+BDM- must stay as is
  7245. is( '[+BD8EQAQ1BDQEOwQ+BDM-]', jux_utf8( '+BD8EQAQ1BDQEOwQ+BDM-' ), 'jux_utf8: => [+BD8EQAQ1BDQEOwQ+BDM-] = [+BD8EQAQ1BDQEOwQ+BDM-]' ) ;
  7246. is( '[&BB8EQAQ+BDUEOgRC-] = [Проект]', jux_utf8( '&BB8EQAQ+BDUEOgRC-' ), 'jux_utf8: => [&BB8EQAQ+BDUEOgRC-] = [Проект]' ) ;
  7247. 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]' ) ;
  7248. my $str = Encode::IMAPUTF7::encode("IMAP-UTF-7", 'Réponses 1200+1201+1202' ) ;
  7249. is( '[R&AOk-ponses 1200+1201+1202] = [Réponses 1200+1201+1202]', jux_utf8( $str ), "jux_utf8: [$str] = [Réponses 1200+1201+1202]" ) ;
  7250. is( '[INBOX.&AOkA4ADnAPk-&-*] = [INBOX.éà çù&*]', jux_utf8( 'INBOX.&AOkA4ADnAPk-&-*' ), "jux_utf8: [INBOX.&AOkA4ADnAPk-&-*] = [INBOX.éà çù&*]" ) ;
  7251. is( '[&ZTZO9nux-] = [æ”¶ä»¶ç®±]', jux_utf8( '&ZTZO9nux-'), 'jux_utf8: => [&ZTZO9nux-] = [æ”¶ä»¶ç®±]' ) ;
  7252. #
  7253. #
  7254. is( '[!Old Emails]', jux_utf8( '!Old Emails'), 'jux_utf8: !Old Emails => [!Old Emails]' ) ;
  7255. is( '[2006 Budget & Fcst]', jux_utf8( '2006 Budget & Fcst'), 'jux_utf8: 2006 Budget & Fcst => [2006 Budget & Fcst]' ) ;
  7256. note( 'Leaving tests_jux_utf8()' ) ;
  7257. return ;
  7258. }
  7259. sub jux_utf8
  7260. {
  7261. #use utf8 ;
  7262. # juxtapose utf8 at the right if different
  7263. my ( $s_utf7 ) = shift ;
  7264. my ( $s_utf8 ) = imap_utf7_decode( $s_utf7 ) ;
  7265. if ( $s_utf7 eq $s_utf8 ) {
  7266. #myprint( "[$s_utf7]\n" ) ;
  7267. return( "[$s_utf7]" ) ;
  7268. }else{
  7269. #myprint( "[$s_utf7] = [$s_utf8]\n" ) ;
  7270. return( "[$s_utf7] = [$s_utf8]" ) ;
  7271. }
  7272. }
  7273. sub imap_utf7_decode
  7274. {
  7275. #use utf8 ;
  7276. my ( $s ) = shift ;
  7277. return( Encode::IMAPUTF7::decode("IMAP-UTF-7", $s ) ) ;
  7278. }
  7279. sub imap_utf7_encode
  7280. {
  7281. #use utf8 ;
  7282. my ( $s ) = shift ;
  7283. return( Encode::IMAPUTF7::encode("IMAP-UTF-7", $s ) ) ;
  7284. }
  7285. sub imap_utf7_encode_old
  7286. {
  7287. my ( $s ) = @_ ;
  7288. $s = Unicode::String::utf8( $s )->utf7 ;
  7289. $s =~ s/\+([^\/&\-]*)\/([^\/\-&]*)\-/\+$1,$2\-/xg ;
  7290. $s =~ s/&/&\-/xg ;
  7291. $s =~ s/\+([^+\-]+)?\-/&$1\-/xg ;
  7292. return( $s ) ;
  7293. }
  7294. sub select_folder
  7295. {
  7296. my ( $mysync, $imap, $folder, $hostside ) = @_ ;
  7297. if ( ! $imap->select( $folder ) ) {
  7298. my $error = join q{},
  7299. "$hostside folder $folder: Could not select: ",
  7300. $imap->LastError, "\n" ;
  7301. errors_incr( $mysync, $error ) ;
  7302. return( 0 ) ;
  7303. }else{
  7304. # ok select succeeded
  7305. return( 1 ) ;
  7306. }
  7307. }
  7308. sub examine_folder
  7309. {
  7310. my ( $mysync, $imap, $folder, $hostside ) = @_ ;
  7311. if ( ! $imap->examine( $folder ) ) {
  7312. my $error = join q{},
  7313. "$hostside folder $folder: Could not examine: ",
  7314. $imap->LastError, "\n" ;
  7315. errors_incr( $mysync, $error ) ;
  7316. return( 0 ) ;
  7317. }else{
  7318. # ok select succeeded
  7319. return( 1 ) ;
  7320. }
  7321. }
  7322. sub count_from_select
  7323. {
  7324. my @lines = @ARG ;
  7325. my $count ;
  7326. foreach my $line ( @lines ) {
  7327. #myprint( "line = [$line]\n" ) ;
  7328. if ( $line =~ m/^\*\s+(\d+)\s+EXISTS/x ) {
  7329. $count = $1 ;
  7330. return( $count ) ;
  7331. }
  7332. }
  7333. return( undef ) ;
  7334. }
  7335. sub create_folder_old
  7336. {
  7337. my $mysync = shift @ARG ;
  7338. my( $imap, $h2_fold, $h1_fold ) = @ARG ;
  7339. myprint( "Creating (old way) folder [$h2_fold] on host2\n" ) ;
  7340. if ( ( 'INBOX' eq uc $h2_fold )
  7341. and ( $imap->exists( $h2_fold ) ) ) {
  7342. myprint( "Folder [$h2_fold] already exists\n" ) ;
  7343. return( 1 ) ;
  7344. }
  7345. if ( ! $mysync->{dry} ){
  7346. if ( ! $imap->create( $h2_fold ) ) {
  7347. my $error = join q{},
  7348. "Could not create folder [$h2_fold] from [$h1_fold]: ",
  7349. $imap->LastError( ), "\n" ;
  7350. errors_incr( $mysync, $error ) ;
  7351. # success if folder exists ("already exists" error)
  7352. return( 1 ) if $imap->exists( $h2_fold ) ;
  7353. # failure since create failed
  7354. return( 0 ) ;
  7355. }else{
  7356. #create succeeded
  7357. myprint( "Created ( the old way ) folder [$h2_fold] on host2\n" ) ;
  7358. return( 1 ) ;
  7359. }
  7360. }else{
  7361. # dry mode, no folder so many imap will fail, assuming failure
  7362. myprint( "Created ( the old way ) folder [$h2_fold] on host2 $mysync->{dry_message}\n" ) ;
  7363. return( 0 ) ;
  7364. }
  7365. }
  7366. sub create_folder
  7367. {
  7368. my $mysync = shift @ARG ;
  7369. my( $myimap2 , $h2_fold , $h1_fold ) = @ARG ;
  7370. my( @parts , $parent ) ;
  7371. if ( $myimap2->IsUnconnected( ) ) {
  7372. myprint( "Host2: Unconnected state\n" ) ;
  7373. return( 0 ) ;
  7374. }
  7375. if ( $create_folder_old ) {
  7376. return( create_folder_old( $mysync, $myimap2 , $h2_fold , $h1_fold ) ) ;
  7377. }
  7378. # $imap->exists() calls $imap->status() that does an IMAP STATUS folder
  7379. myprint( "Creating folder [$h2_fold] on host2\n" ) ;
  7380. if ( ( 'INBOX' eq uc $h2_fold )
  7381. and ( $myimap2->exists( $h2_fold ) ) ) {
  7382. myprint( "Folder [$h2_fold] already exists\n" ) ;
  7383. return( 1 ) ;
  7384. }
  7385. if ( $mixfolders and $myimap2->exists( $h2_fold ) ) {
  7386. myprint( "Folder [$h2_fold] already exists (--nomixfolders is not set)\n" ) ;
  7387. return( 1 ) ;
  7388. }
  7389. if ( ( not $mixfolders ) and ( $myimap2->exists( $h2_fold ) ) ) {
  7390. myprint( "Folder [$h2_fold] already exists and --nomixfolders is set\n" ) ;
  7391. return( 0 ) ;
  7392. }
  7393. @parts = split /\Q$mysync->{ h2_sep }\E/x, $h2_fold ;
  7394. pop @parts ;
  7395. $parent = join $mysync->{ h2_sep }, @parts ;
  7396. $parent =~ s/^\s+|\s+$//xg ;
  7397. if ( ( $parent ne q{} ) and ( ! $myimap2->exists( $parent ) ) ) {
  7398. create_folder( $mysync, $myimap2 , $parent , $h1_fold ) ;
  7399. }
  7400. if ( ! $mysync->{dry} ) {
  7401. if ( ! $myimap2->create( $h2_fold ) ) {
  7402. my $error = join q{},
  7403. "Could not create folder [$h2_fold] from [$h1_fold]: " ,
  7404. $myimap2->LastError( ), "\n" ;
  7405. errors_incr( $mysync, $error ) ;
  7406. # success if folder exists ("already exists" error) or selectable
  7407. if ( $myimap2->exists( $h2_fold ) or select_folder( $mysync, $myimap2, $h2_fold, 'Host2' ) )
  7408. {
  7409. return( 1 ) ;
  7410. }
  7411. # failure since create failed + not exist + not selectable
  7412. return( 0 ) ;
  7413. }else{
  7414. #create succeeded
  7415. myprint( "Created folder [$h2_fold] on host2\n" ) ;
  7416. return( 1 ) ;
  7417. }
  7418. }else{
  7419. # dry mode, no folder so many imap will fail, assuming failure
  7420. myprint( "Created folder [$h2_fold] on host2 $mysync->{dry_message}\n" ) ;
  7421. if ( ! $mysync->{ justfolders } ) {
  7422. myprint( "Since --dry mode is on and folder [$h2_fold] on host2 does not exist yet, syncing messages will not be simulated.\n"
  7423. . "To simulate message syncing, use --justfolders without --dry to first create the missing folders then rerun the --dry sync.\n" ) ;
  7424. # The messages that could be transferred are counted and the number is given at the end.
  7425. }
  7426. return( 0 ) ;
  7427. }
  7428. }
  7429. sub tests_folder_routines
  7430. {
  7431. note( 'Entering tests_folder_routines()' ) ;
  7432. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 1' );
  7433. ok( add_to_requested_folders('folder_foo'), 'add_to_requested_folders folder_foo' );
  7434. ok( is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 2' );
  7435. ok( !is_requested_folder('folder_NO_EXIST'), 'is_requested_folder folder_NO_EXIST' );
  7436. is_deeply( [ 'folder_foo' ], [ remove_from_requested_folders( 'folder_foo' ) ], 'removed folder_foo => folder_foo' ) ;
  7437. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 3' );
  7438. my @f ;
  7439. ok( @f = add_to_requested_folders('folder_bar', 'folder_toto'), "add result: @f" );
  7440. ok( is_requested_folder('folder_bar'), 'is_requested_folder 4' );
  7441. ok( is_requested_folder('folder_toto'), 'is_requested_folder 5' );
  7442. ok( remove_from_requested_folders('folder_toto'), 'remove_from_requested_folders: ' );
  7443. ok( !is_requested_folder('folder_toto'), 'is_requested_folder 6' );
  7444. is_deeply( [ 'folder_bar' ], [ remove_from_requested_folders('folder_bar') ], 'remove_from_requested_folders: empty' ) ;
  7445. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [] ), 'sort_requested_folders: all empty' ) ;
  7446. ok( add_to_requested_folders( 'A_99', 'M_55', 'Z_11' ), 'add_to_requested_folders M_55 Z_11' );
  7447. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'A_99', 'M_55', 'Z_11' ] ), 'sort_requested_folders: middle' ) ;
  7448. @folderfirst = ( 'Z_11' ) ;
  7449. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'A_99', 'M_55' ] ), 'sort_requested_folders: first+middle' ) ;
  7450. is_deeply( [ 'Z_11', 'A_99', 'M_55' ], [ sort_requested_folders( ) ], 'sort_requested_folders: first+middle is_deeply' ) ;
  7451. @folderlast = ( 'A_99' ) ;
  7452. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_55', 'A_99' ] ), 'sort_requested_folders: first+middle+last 1' ) ;
  7453. ok( add_to_requested_folders('M_55', 'M_44',), 'add_to_requested_folders M_55 M_44' ) ;
  7454. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_44', 'M_55', 'A_99'] ), 'sort_requested_folders: first+middle+last 2' ) ;
  7455. ok( add_to_requested_folders('A_88', 'Z_22',), 'add_to_requested_folders A_88 Z_22' ) ;
  7456. @folderfirst = qw( Z_22 Z_11 ) ;
  7457. @folderlast = qw( A_99 A_88 ) ;
  7458. 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' ) ;
  7459. undef @folderfirst ;
  7460. undef @folderlast ;
  7461. note( 'Leaving tests_folder_routines()' ) ;
  7462. return ;
  7463. }
  7464. sub sort_requested_folders
  7465. {
  7466. my @requested_folders_sorted = () ;
  7467. $sync->{ debug } and myprint "folderfirst: @folderfirst\n" ;
  7468. my @folderfirst_requested = remove_from_requested_folders( @folderfirst ) ;
  7469. #myprint "folderfirst_requested: @folderfirst_requested\n" ;
  7470. my @folderlast_requested = remove_from_requested_folders( @folderlast ) ;
  7471. my @middle = sort keys %requested_folder ;
  7472. @requested_folders_sorted = ( @folderfirst_requested, @middle, @folderlast_requested ) ;
  7473. $sync->{ debug } and myprint "requested_folders_sorted: @requested_folders_sorted\n" ;
  7474. add_to_requested_folders( @requested_folders_sorted ) ;
  7475. return( @requested_folders_sorted ) ;
  7476. }
  7477. sub is_requested_folder
  7478. {
  7479. my ( $folder ) = @_;
  7480. return( defined $requested_folder{ $folder } ) ;
  7481. }
  7482. sub add_to_requested_folders
  7483. {
  7484. my @wanted_folders = @_ ;
  7485. foreach my $folder ( @wanted_folders ) {
  7486. ++$requested_folder{ $folder } ;
  7487. }
  7488. return( keys %requested_folder ) ;
  7489. }
  7490. sub tests_remove_from_requested_folders
  7491. {
  7492. note( 'Entering tests_remove_from_requested_folders()' ) ;
  7493. is( undef, undef, 'remove_from_requested_folders: undef is undef' ) ;
  7494. is_deeply( [], [ remove_from_requested_folders( ) ], 'remove_from_requested_folders: no args' ) ;
  7495. %requested_folder = (
  7496. 'F1' => 1,
  7497. ) ;
  7498. is_deeply( [], [ remove_from_requested_folders( ) ], 'remove_from_requested_folders: remove nothing among F1 => nothing' ) ;
  7499. is_deeply( [], [ remove_from_requested_folders( 'Fno' ) ], 'remove_from_requested_folders: remove Fno among F1 => nothing' ) ;
  7500. is_deeply( [ 'F1' ], [ remove_from_requested_folders( 'F1' ) ], 'remove_from_requested_folders: remove F1 among F1 => F1' ) ;
  7501. is_deeply( { }, { %requested_folder }, 'remove_from_requested_folders: remove F1 among F1 => %requested_folder emptied' ) ;
  7502. %requested_folder = (
  7503. 'F1' => 1,
  7504. 'F2' => 1,
  7505. ) ;
  7506. is_deeply( [], [ remove_from_requested_folders( ) ], 'remove_from_requested_folders: remove nothing among F1 F2 => nothing' ) ;
  7507. is_deeply( [], [ remove_from_requested_folders( 'Fno' ) ], 'remove_from_requested_folders: remove Fno among F1 F2 => nothing' ) ;
  7508. is_deeply( [ 'F1' ], [ remove_from_requested_folders( 'F1' ) ], 'remove_from_requested_folders: remove F1 among F1 F2 => F1' ) ;
  7509. is_deeply( { 'F2' => 1 }, { %requested_folder }, 'remove_from_requested_folders: remove F1 among F1 F2 => %requested_folder F2' ) ;
  7510. is_deeply( [], [ remove_from_requested_folders( 'F1' ) ], 'remove_from_requested_folders: remove F1 among F2 => nothing' ) ;
  7511. is_deeply( [ 'F2' ], [ remove_from_requested_folders( 'F1', 'F2' ) ], 'remove_from_requested_folders: remove F1 F2 among F2 => F2' ) ;
  7512. is_deeply( {}, { %requested_folder }, 'remove_from_requested_folders: remove F1 among F1 F2 => %requested_folder F2' ) ;
  7513. %requested_folder = (
  7514. 'F1' => 1,
  7515. 'F2' => 1,
  7516. 'F3' => 1,
  7517. ) ;
  7518. is_deeply( [ 'F1', 'F2' ], [ remove_from_requested_folders( 'F1', 'F2' ) ], 'remove_from_requested_folders: remove F1 F2 among F1 F2 F3 => F1 F2' ) ;
  7519. is_deeply( { 'F3' => 1 }, { %requested_folder }, 'remove_from_requested_folders: remove F1 F2 among F1 F2 F3 => %requested_folder F3' ) ;
  7520. undef %requested_folder ;
  7521. note( 'Leaving tests_remove_from_requested_folders()' ) ;
  7522. return ;
  7523. }
  7524. sub remove_from_requested_folders
  7525. {
  7526. my @unwanted_folders = @_ ;
  7527. my @removed_folders = () ;
  7528. foreach my $folder ( @unwanted_folders ) {
  7529. if ( exists $requested_folder{ $folder } )
  7530. {
  7531. delete $requested_folder{ $folder } ;
  7532. push @removed_folders, $folder ;
  7533. }
  7534. }
  7535. return( @removed_folders ) ;
  7536. }
  7537. sub compare_lists
  7538. {
  7539. my ($list_1_ref, $list_2_ref) = @_;
  7540. return($MINUS_ONE) if ((not defined $list_1_ref) and defined $list_2_ref);
  7541. return(0) if ((not defined $list_1_ref) and not defined $list_2_ref); # end if no list
  7542. return(1) if (not defined $list_2_ref); # end if only one list
  7543. if (not ref $list_1_ref ) {$list_1_ref = [$list_1_ref]};
  7544. if (not ref $list_2_ref ) {$list_2_ref = [$list_2_ref]};
  7545. my $last_used_indice = $MINUS_ONE;
  7546. ELEMENT:
  7547. foreach my $indice ( 0 .. $#{ $list_1_ref } ) {
  7548. $last_used_indice = $indice ;
  7549. # End of list_2
  7550. return 1 if ($indice > $#{ $list_2_ref } ) ;
  7551. my $element_list_1 = $list_1_ref->[$indice] ;
  7552. my $element_list_2 = $list_2_ref->[$indice] ;
  7553. my $balance = $element_list_1 cmp $element_list_2 ;
  7554. next ELEMENT if ($balance == 0) ;
  7555. return $balance ;
  7556. }
  7557. # each element equal until last indice of list_1
  7558. return $MINUS_ONE if ($last_used_indice < $#{ $list_2_ref } ) ;
  7559. # same size, each element equal
  7560. return 0 ;
  7561. }
  7562. sub tests_compare_lists
  7563. {
  7564. note( 'Entering tests_compare_lists()' ) ;
  7565. my $empty_list_ref = [];
  7566. ok( 0 == compare_lists() , 'compare_lists, no args');
  7567. ok( 0 == compare_lists(undef) , 'compare_lists, undef = nothing');
  7568. ok( 0 == compare_lists(undef, undef) , 'compare_lists, undef = undef');
  7569. ok($MINUS_ONE == compare_lists(undef , []) , 'compare_lists, undef < []');
  7570. ok($MINUS_ONE == compare_lists(undef , [1]) , 'compare_lists, undef < [1]');
  7571. ok($MINUS_ONE == compare_lists(undef , [0]) , 'compare_lists, undef < [0]');
  7572. ok(+1 == compare_lists([]) , 'compare_lists, [] > nothing');
  7573. ok(+1 == compare_lists([], undef) , 'compare_lists, [] > undef');
  7574. ok( 0 == compare_lists([] , []) , 'compare_lists, [] = []');
  7575. ok($MINUS_ONE == compare_lists([] , [1]) , 'compare_lists, [] < [1]');
  7576. ok(+1 == compare_lists([1] , []) , 'compare_lists, [1] > []');
  7577. ok( 0 == compare_lists( [1], 1 ) , 'compare_lists, [1] = 1 ') ;
  7578. ok( 0 == compare_lists( 1 , [1] ) , 'compare_lists, 1 = [1]') ;
  7579. ok( 0 == compare_lists( 1 , 1 ) , 'compare_lists, 1 = 1 ') ;
  7580. ok( $MINUS_ONE == compare_lists( 0 , 1 ) , 'compare_lists, 0 < 1 ') ;
  7581. ok( $MINUS_ONE == compare_lists( $MINUS_ONE , 0 ) , 'compare_lists, -1 < 0 ') ;
  7582. ok( $MINUS_ONE == compare_lists( 1 , 2 ) , 'compare_lists, 1 < 2 ') ;
  7583. ok( +1 == compare_lists( 2 , 1 ) , 'compare_lists, 2 > 1 ') ;
  7584. ok( 0 == compare_lists([1,2], [1,2]) , 'compare_lists, [1,2] = [1,2]' ) ;
  7585. ok($MINUS_ONE == compare_lists([1], [1,2]) , 'compare_lists, [1] < [1,2]' ) ;
  7586. ok(+1 == compare_lists([2], [1,2]) , 'compare_lists, [2] > [1,2]' ) ;
  7587. ok($MINUS_ONE == compare_lists([1], [1,1]) , 'compare_lists, [1] < [1,1]' ) ;
  7588. ok(+1 == compare_lists([1, 1], [1]) , 'compare_lists, [1, 1] > [1]' ) ;
  7589. ok( 0 == compare_lists([1 .. $NUMBER_20_000] , [1 .. $NUMBER_20_000])
  7590. , 'compare_lists, [1..20_000] = [1..20_000]' ) ;
  7591. ok($MINUS_ONE == compare_lists([1], [2]) , 'compare_lists, [1] < [2]') ;
  7592. ok( 0 == compare_lists([2], [2]) , 'compare_lists, [0] = [2]') ;
  7593. ok(+1 == compare_lists([2], [1]) , 'compare_lists, [2] > [1]') ;
  7594. ok($MINUS_ONE == compare_lists(['a'], ['b']) , 'compare_lists, ["a"] < ["b"]') ;
  7595. ok( 0 == compare_lists(['a'], ['a']) , 'compare_lists, ["a"] = ["a"]') ;
  7596. ok( 0 == compare_lists(['ab'], ['ab']) , 'compare_lists, ["ab"] = ["ab"]') ;
  7597. ok(+1 == compare_lists(['b'], ['a']) , 'compare_lists, ["b"] > ["a"]') ;
  7598. ok($MINUS_ONE == compare_lists(['a'], ['aa']) , 'compare_lists, ["a"] < ["aa"]') ;
  7599. ok($MINUS_ONE == compare_lists(['a'], ['a', 'a']), 'compare_lists, ["a"] < ["a", "a"]') ;
  7600. ok( 0 == compare_lists([split q{ }, 'a b' ], ['a', 'b']), 'compare_lists, split') ;
  7601. ok( 0 == compare_lists([sort split q{ }, 'b a' ], ['a', 'b']), 'compare_lists, sort split') ;
  7602. note( 'Leaving tests_compare_lists()' ) ;
  7603. return ;
  7604. }
  7605. sub guess_prefix
  7606. {
  7607. my @foldernames = @_ ;
  7608. my $prefix_guessed = q{} ;
  7609. foreach my $folder ( @foldernames ) {
  7610. next if ( $folder =~ m{^INBOX$}xi ) ; # no guessing from INBOX
  7611. if ( $folder !~ m{^INBOX}xi ) {
  7612. $prefix_guessed = q{} ; # prefix empty guessed
  7613. last ;
  7614. }
  7615. if ( $folder =~ m{^(INBOX(?:\.|\/))}xi ) {
  7616. $prefix_guessed = $1 ; # prefix Inbox/ or INBOX. guessed
  7617. }
  7618. }
  7619. return( $prefix_guessed ) ;
  7620. }
  7621. sub tests_guess_prefix
  7622. {
  7623. note( 'Entering tests_guess_prefix()' ) ;
  7624. is( guess_prefix( ), q{}, 'guess_prefix: no args => empty string' ) ;
  7625. is( q{} , guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  7626. is( q{} , guess_prefix( 'Inbox' ), 'guess_prefix: Inbox alone' ) ;
  7627. is( q{} , guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  7628. is( 'INBOX/' , guess_prefix( 'INBOX', 'INBOX/Junk' ), 'guess_prefix: INBOX INBOX/Junk' ) ;
  7629. is( 'INBOX.' , guess_prefix( 'INBOX', 'INBOX.Junk' ), 'guess_prefix: INBOX INBOX.Junk' ) ;
  7630. is( 'Inbox/' , guess_prefix( 'Inbox', 'Inbox/Junk' ), 'guess_prefix: Inbox Inbox/Junk' ) ;
  7631. is( 'Inbox.' , guess_prefix( 'Inbox', 'Inbox.Junk' ), 'guess_prefix: Inbox Inbox.Junk' ) ;
  7632. is( 'INBOX/' , guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr' ) ;
  7633. is( q{} , guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr', 'zzz' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr zzz' ) ;
  7634. is( q{} , guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  7635. is( q{} , guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  7636. note( 'Leaving tests_guess_prefix()' ) ;
  7637. return ;
  7638. }
  7639. sub get_prefix
  7640. {
  7641. my( $imap, $prefix_in, $prefix_opt, $Side, $folders_ref ) = @_ ;
  7642. my( $prefix_out, $prefix_guessed ) ;
  7643. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: Getting prefix\n" ) ;
  7644. $prefix_guessed = guess_prefix( @{ $folders_ref } ) ;
  7645. myprint( "$Side: guessing prefix from folder listing: [$prefix_guessed]\n" ) ;
  7646. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: Calling namespace capability\n" ) ;
  7647. if ( $imap->has_capability( 'namespace' ) ) {
  7648. my $r_namespace = $imap->namespace( ) ;
  7649. $prefix_out = $r_namespace->[0][0][0] ;
  7650. myprint( "$Side: prefix given by NAMESPACE: [$prefix_out]\n" ) ;
  7651. if ( defined $prefix_in ) {
  7652. myprint( "$Side: but using [$prefix_in] given by $prefix_opt\n" ) ;
  7653. $prefix_out = $prefix_in ;
  7654. return( $prefix_out ) ;
  7655. }else{
  7656. # all good
  7657. return( $prefix_out ) ;
  7658. }
  7659. }
  7660. else{
  7661. if ( defined $prefix_in ) {
  7662. myprint( "$Side: using [$prefix_in] given by $prefix_opt\n" ) ;
  7663. $prefix_out = $prefix_in ;
  7664. return( $prefix_out ) ;
  7665. }else{
  7666. myprint(
  7667. "$Side: No NAMESPACE capability so using guessed prefix [$prefix_guessed]\n",
  7668. help_to_guess_prefix( $imap, $prefix_opt ) ) ;
  7669. return( $prefix_guessed ) ;
  7670. }
  7671. }
  7672. return ;
  7673. }
  7674. sub guess_separator
  7675. {
  7676. my @foldernames = @_ ;
  7677. #return( undef ) unless ( @foldernames ) ;
  7678. my $sep_guessed ;
  7679. my %counter ;
  7680. foreach my $folder ( @foldernames ) {
  7681. $counter{'/'}++ while ( $folder =~ m{/}xg ) ; # count /
  7682. $counter{'.'}++ while ( $folder =~ m{\.}xg ) ; # count .
  7683. $counter{'\\\\'}++ while ( $folder =~ m{(\\){2}}xg ) ; # count \\
  7684. $counter{'\\'}++ while ( $folder =~ m{[^\\](\\){1}(?=[^\\])}xg ) ; # count \
  7685. }
  7686. my @race_sorted = sort { $counter{ $b } <=> $counter{ $a } } keys %counter ;
  7687. $sync->{ debug } and myprint( "@foldernames\n@race_sorted\n", %counter, "\n" ) ;
  7688. $sep_guessed = shift @race_sorted || $LAST_RESSORT_SEPARATOR ; # / when nothing found.
  7689. return( $sep_guessed ) ;
  7690. }
  7691. sub tests_guess_separator
  7692. {
  7693. note( 'Entering tests_guess_separator()' ) ;
  7694. ok( '/' eq guess_separator( ), 'guess_separator: no args' ) ;
  7695. ok( '/' eq guess_separator( 'abcd' ), 'guess_separator: abcd' ) ;
  7696. ok( '/' eq guess_separator( 'a/b/c.d' ), 'guess_separator: a/b/c.d' ) ;
  7697. ok( '.' eq guess_separator( 'a.b/c.d' ), 'guess_separator: a.b/c.d' ) ;
  7698. ok( '\\\\' eq guess_separator( 'a\\\\b\\\\c.c\\\\d/e/f' ), 'guess_separator: a\\\\b\\\\c.c\\\\d/e/f' ) ;
  7699. ok( '\\' eq guess_separator( 'a\\b\\c.c\\d/e/f' ), 'guess_separator: a\\b\\c.c\\d/e/f' ) ;
  7700. ok( '\\' eq guess_separator( 'a\\b' ), 'guess_separator: a\\b' ) ;
  7701. ok( '\\' eq guess_separator( 'a\\b\\c' ), 'guess_separator: a\\b\\c' ) ;
  7702. note( 'Leaving tests_guess_separator()' ) ;
  7703. return ;
  7704. }
  7705. sub get_separator
  7706. {
  7707. my( $imap, $sep_in, $sep_opt, $Side, $folders_ref ) = @_ ;
  7708. my( $sep_out, $sep_guessed ) ;
  7709. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: Getting separator\n" ) ;
  7710. $sep_guessed = guess_separator( @{ $folders_ref } ) ;
  7711. myprint( "$Side: guessing separator from folder listing: [$sep_guessed]\n" ) ;
  7712. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: calling namespace capability\n" ) ;
  7713. if ( $imap->has_capability( 'namespace' ) )
  7714. {
  7715. $sep_out = $imap->separator( ) ;
  7716. if ( defined $sep_out ) {
  7717. myprint( "$Side: separator given by NAMESPACE: [$sep_out]\n" ) ;
  7718. if ( defined $sep_in ) {
  7719. myprint( "$Side: but using [$sep_in] given by $sep_opt\n" ) ;
  7720. $sep_out = $sep_in ;
  7721. return( $sep_out ) ;
  7722. }else{
  7723. return( $sep_out ) ;
  7724. }
  7725. }else{
  7726. if ( defined $sep_in ) {
  7727. myprint( "$Side: NAMESPACE request failed but using [$sep_in] given by $sep_opt\n" ) ;
  7728. $sep_out = $sep_in ;
  7729. return( $sep_out ) ;
  7730. }else{
  7731. myprint(
  7732. "$Side: NAMESPACE request failed so using guessed separator [$sep_guessed]\n",
  7733. help_to_guess_sep( $imap, $sep_opt ) ) ;
  7734. return( $sep_guessed ) ;
  7735. }
  7736. }
  7737. }
  7738. else
  7739. {
  7740. if ( defined $sep_in ) {
  7741. myprint( "$Side: No NAMESPACE capability but using [$sep_in] given by $sep_opt\n" ) ;
  7742. $sep_out = $sep_in ;
  7743. return( $sep_out ) ;
  7744. }else{
  7745. myprint(
  7746. "$Side: No NAMESPACE capability, so using guessed separator [$sep_guessed]\n",
  7747. help_to_guess_sep( $imap, $sep_opt ) ) ;
  7748. return( $sep_guessed ) ;
  7749. }
  7750. }
  7751. return ;
  7752. }
  7753. sub help_to_guess_sep
  7754. {
  7755. my( $imap, $sep_opt ) = @_ ;
  7756. my $help_to_guess_sep = "You can set the separator character with the $sep_opt option,\n"
  7757. . "the complete listing of folders may help you to find it\n"
  7758. . folders_list_to_help( $imap ) ;
  7759. return( $help_to_guess_sep ) ;
  7760. }
  7761. sub help_to_guess_prefix
  7762. {
  7763. my( $imap, $prefix_opt ) = @_ ;
  7764. my $help_to_guess_prefix = "You can set the prefix namespace with the $prefix_opt option,\n"
  7765. . "the folowing listing of folders may help you to find it:\n"
  7766. . folders_list_to_help( $imap ) ;
  7767. return( $help_to_guess_prefix ) ;
  7768. }
  7769. sub folders_list_to_help
  7770. {
  7771. my( $imap ) = shift ;
  7772. my @folders = $imap->folders ;
  7773. my $listing = join q{}, map { "[$_]\n" } @folders ;
  7774. return( $listing ) ;
  7775. }
  7776. # Globals are $sync @h1_folders_all @h2_folders_all $prefix1 $prefix2
  7777. sub private_folders_separators_and_prefixes
  7778. {
  7779. # what are the private folders separators and prefixes for each server ?
  7780. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "Getting separators\n" ) ;
  7781. $sync->{ h1_sep } = get_separator( $sync->{imap1}, $sync->{ sep1 }, '--sep1', 'Host1', \@h1_folders_all ) ;
  7782. $sync->{ h2_sep } = get_separator( $sync->{imap2}, $sync->{ sep2 }, '--sep2', 'Host2', \@h2_folders_all ) ;
  7783. $sync->{ h1_prefix } = get_prefix( $sync->{imap1}, $prefix1, '--prefix1', 'Host1', \@h1_folders_all ) ;
  7784. $sync->{ h2_prefix } = get_prefix( $sync->{imap2}, $prefix2, '--prefix2', 'Host2', \@h2_folders_all ) ;
  7785. myprint( "Host1: separator and prefix: [$sync->{ h1_sep }][$sync->{ h1_prefix }]\n" ) ;
  7786. myprint( "Host2: separator and prefix: [$sync->{ h2_sep }][$sync->{ h2_prefix }]\n" ) ;
  7787. return ;
  7788. }
  7789. sub subfolder1
  7790. {
  7791. my $mysync = shift ;
  7792. my $subfolder1 = sanitize_subfolder( $mysync->{ subfolder1 } ) ;
  7793. if ( $subfolder1 )
  7794. {
  7795. # turns off automap
  7796. myprint( "Turning off automapping folders because of --subfolder1\n" ) ;
  7797. $mysync->{ automap } = undef ;
  7798. myprint( "Sanitizing subfolder1: [$mysync->{ subfolder1 }] => [$subfolder1]\n" ) ;
  7799. $mysync->{ subfolder1 } = $subfolder1 ;
  7800. if ( ! add_subfolder1_to_folderrec( $mysync ) )
  7801. {
  7802. $mysync->{nb_errors}++ ;
  7803. exit_clean( $mysync, $EXIT_SUBFOLDER1_NO_EXISTS, "subfolder1 $subfolder1 does not exist\n" ) ;
  7804. }
  7805. }
  7806. else
  7807. {
  7808. $mysync->{ subfolder1 } = undef ;
  7809. }
  7810. return ;
  7811. }
  7812. sub subfolder2
  7813. {
  7814. my $mysync = shift ;
  7815. my $subfolder2 = sanitize_subfolder( $mysync->{ subfolder2 } ) ;
  7816. if ( $subfolder2 )
  7817. {
  7818. # turns off automap
  7819. myprint( "Turning off automapping folders because of --subfolder2\n" ) ;
  7820. $mysync->{ automap } = undef ;
  7821. myprint( "Sanitizing subfolder2: [$mysync->{ subfolder2 }] => [$subfolder2]\n" ) ;
  7822. $mysync->{ subfolder2 } = $subfolder2 ;
  7823. set_regextrans2_for_subfolder2( $mysync ) ;
  7824. }
  7825. else
  7826. {
  7827. $mysync->{ subfolder2 } = undef ;
  7828. }
  7829. return ;
  7830. }
  7831. sub tests_sanitize_subfolder
  7832. {
  7833. note( 'Entering tests_sanitize_subfolder()' ) ;
  7834. is( undef, sanitize_subfolder( ), 'sanitize_subfolder: no args => undef' ) ;
  7835. is( undef, sanitize_subfolder( q{} ), 'sanitize_subfolder: empty => undef' ) ;
  7836. is( undef, sanitize_subfolder( ' ' ), 'sanitize_subfolder: blank => undef' ) ;
  7837. is( undef, sanitize_subfolder( ' ' ), 'sanitize_subfolder: blanks => undef' ) ;
  7838. is( 'abcd', sanitize_subfolder( 'abcd' ), 'sanitize_subfolder: abcd => abcd' ) ;
  7839. is( 'ab cd', sanitize_subfolder( ' ab cd ' ), 'sanitize_subfolder: " ab cd " => "ab cd"' ) ;
  7840. is( 'abcd', sanitize_subfolder( q{a&~b#\\c[]=d;} ), 'sanitize_subfolder: "a&~b#\\c[]=d;" => "abcd"' ) ;
  7841. is( 'aA.b-_ 8c/dD', sanitize_subfolder( 'aA.b-_ 8c/dD' ), 'sanitize_subfolder: aA.b-_ 8c/dD => aA.b-_ 8c/dD' ) ;
  7842. note( 'Leaving tests_sanitize_subfolder()' ) ;
  7843. return ;
  7844. }
  7845. sub sanitize_subfolder
  7846. {
  7847. my $subfolder = shift ;
  7848. if ( ! $subfolder )
  7849. {
  7850. return ;
  7851. }
  7852. # Remove edging blanks
  7853. $subfolder =~ s,^ +| +$,,g ;
  7854. # Keep only abcd...ABCD...0123... and -_./
  7855. $subfolder =~ tr,-_a-zA-Z0-9./ ,,cd ;
  7856. # A blank subfolder is not a subfolder
  7857. if ( ! $subfolder )
  7858. {
  7859. return ;
  7860. }
  7861. else
  7862. {
  7863. return $subfolder ;
  7864. }
  7865. }
  7866. sub tests_sanitize_host
  7867. {
  7868. note( 'Entering tests_sanitize_host()' ) ;
  7869. is( undef, sanitize_host( ), 'sanitize_host: no args => undef' ) ;
  7870. is( '', sanitize_host( '' ), 'sanitize_host: empty => empty' ) ;
  7871. is( 'imap.example.org', sanitize_host( 'imap.example.org' ), 'sanitize_host: imap.example.org => imap.example.org' ) ;
  7872. is( 'imap.example.org', sanitize_host( ' imap.example.org' ), 'sanitize_host: imap.example.org 1 => imap.example.org' ) ;
  7873. is( 'imap.example.org', sanitize_host( 'imap.example.org ' ), 'sanitize_host: imap.example.org 2 => imap.example.org' ) ;
  7874. is( 'imap.example.org', sanitize_host( 'imap.exam ple.org' ), 'sanitize_host: imap.example.org 3 => imap.example.org' ) ;
  7875. is( 'imap.example.org', sanitize_host( ' imap.exam ple.org ' ), 'sanitize_host: imap.example.org 4 => imap.example.org' ) ;
  7876. is( 'imap.example.org', sanitize_host( 'imap.exa/mple.org/' ), 'sanitize_host: imap.example.org/ => imap.example.org' ) ;
  7877. note( 'Leaving tests_sanitize_host()' ) ;
  7878. return ;
  7879. }
  7880. sub sanitize_host
  7881. {
  7882. my $host = shift ;
  7883. if ( ! defined $host ) { return ; }
  7884. $host =~ tr{ /}{}d ;
  7885. return $host ;
  7886. }
  7887. sub tests_add_subfolder1_to_folderrec
  7888. {
  7889. note( 'Entering tests_add_subfolder1_to_folderrec()' ) ;
  7890. is( undef, add_subfolder1_to_folderrec( ), 'add_subfolder1_to_folderrec: undef => undef' ) ;
  7891. is_deeply( [], [ add_subfolder1_to_folderrec( ) ], 'add_subfolder1_to_folderrec: no args => empty array' ) ;
  7892. @folderrec = () ;
  7893. my $mysync = {} ;
  7894. is_deeply( [ ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: empty => empty array' ) ;
  7895. is_deeply( [ ], [ @folderrec ], 'add_subfolder1_to_folderrec: empty => empty folderrec' ) ;
  7896. $mysync->{ subfolder1 } = 'SUBI' ;
  7897. $h1_folders_all{ 'SUBI' } = 1 ;
  7898. $mysync->{ h1_prefix } = 'INBOX/' ;
  7899. is_deeply( [ 'SUBI' ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: SUBI => SUBI' ) ;
  7900. is_deeply( [ 'SUBI' ], [ @folderrec ], 'add_subfolder1_to_folderrec: SUBI => folderrec SUBI ' ) ;
  7901. @folderrec = () ;
  7902. $mysync->{ subfolder1 } = 'SUBO' ;
  7903. is_deeply( [ ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: SUBO no exists => empty array' ) ;
  7904. is_deeply( [ ], [ @folderrec ], 'add_subfolder1_to_folderrec: SUBO no exists => empty folderrec' ) ;
  7905. $h1_folders_all{ 'INBOX/SUBO' } = 1 ;
  7906. is_deeply( [ 'INBOX/SUBO' ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: SUBO + INBOX/SUBO exists => INBOX/SUBO' ) ;
  7907. is_deeply( [ 'INBOX/SUBO' ], [ @folderrec ], 'add_subfolder1_to_folderrec: SUBO + INBOX/SUBO exists => INBOX/SUBO folderrec' ) ;
  7908. note( 'Leaving tests_add_subfolder1_to_folderrec()' ) ;
  7909. return ;
  7910. }
  7911. sub add_subfolder1_to_folderrec
  7912. {
  7913. my $mysync = shift ;
  7914. if ( ! $mysync || ! $mysync->{ subfolder1 } )
  7915. {
  7916. return ;
  7917. }
  7918. my $subfolder1 = $mysync->{ subfolder1 } ;
  7919. my $subfolder1_extended = $mysync->{ h1_prefix } . $subfolder1 ;
  7920. if ( exists $h1_folders_all{ $subfolder1 } )
  7921. {
  7922. myprint( qq{Acting like --folderrec "$subfolder1"\n} ) ;
  7923. push @folderrec, $subfolder1 ;
  7924. }
  7925. elsif ( exists $h1_folders_all{ $subfolder1_extended } )
  7926. {
  7927. myprint( qq{Acting like --folderrec "$subfolder1_extended"\n} ) ;
  7928. push @folderrec, $subfolder1_extended ;
  7929. }
  7930. else
  7931. {
  7932. myprint( qq{Nor folder "$subfolder1" nor "$subfolder1_extended" exists on host1\n} ) ;
  7933. }
  7934. return @folderrec ;
  7935. }
  7936. sub set_regextrans2_for_subfolder2
  7937. {
  7938. my $mysync = shift ;
  7939. unshift @{ $mysync->{ regextrans2 } },
  7940. q(s,^$mysync->{ h2_prefix }(.*),$mysync->{ h2_prefix }$mysync->{ subfolder2 }$mysync->{ h2_sep }$1,),
  7941. q(s,^INBOX$,$mysync->{ h2_prefix }$mysync->{ subfolder2 }$mysync->{ h2_sep }INBOX,),
  7942. q(s,^($mysync->{ h2_prefix }){2},$mysync->{ h2_prefix },);
  7943. #myprint( "@{ $mysync->{ regextrans2 } }\n" ) ;
  7944. return ;
  7945. }
  7946. # Looks like no globals here
  7947. sub tests_imap2_folder_name
  7948. {
  7949. note( 'Entering tests_imap2_folder_name()' ) ;
  7950. my $mysync = {} ;
  7951. $mysync->{ h1_prefix } = q{} ;
  7952. $mysync->{ h2_prefix } = q{} ;
  7953. $mysync->{ h1_sep } = '/';
  7954. $mysync->{ h2_sep } = '.';
  7955. $mysync->{ debug } and myprint( <<"EOS"
  7956. prefix1: [$mysync->{ h1_prefix }]
  7957. prefix2: [$mysync->{ h2_prefix }]
  7958. sep1: [$sync->{ h1_sep }]
  7959. sep2: [$sync->{ h2_sep }]
  7960. EOS
  7961. ) ;
  7962. $mysync->{ fixslash2 } = 0 ;
  7963. is( q{INBOX}, imap2_folder_name( $mysync, q{} ), 'imap2_folder_name: empty string' ) ;
  7964. is( 'blabla', imap2_folder_name( $mysync, 'blabla' ), 'imap2_folder_name: blabla' ) ;
  7965. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam' ), 'imap2_folder_name: spam/spam' ) ;
  7966. is( 'spam/spam', imap2_folder_name( $mysync, 'spam.spam' ), 'imap2_folder_name: spam.spam') ;
  7967. is( 'spam.spam/spam', imap2_folder_name( $mysync, 'spam/spam.spam' ), 'imap2_folder_name: spam/spam.spam' ) ;
  7968. is( 's pam.spam/sp am', imap2_folder_name( $mysync, 's pam/spam.sp am' ), 'imap2_folder_name: s pam/spam.sp am' ) ;
  7969. $mysync->{f1f2h}{ 'auto' } = 'moto' ;
  7970. is( 'moto', imap2_folder_name( $mysync, 'auto' ), 'imap2_folder_name: auto' ) ;
  7971. $mysync->{f1f2h}{ 'auto/auto' } = 'moto x 2' ;
  7972. is( 'moto x 2', imap2_folder_name( $mysync, 'auto/auto' ), 'imap2_folder_name: auto/auto' ) ;
  7973. @{ $mysync->{ regextrans2 } } = ( 's,/,X,g' ) ;
  7974. is( q{INBOX}, imap2_folder_name( $mysync, q{} ), 'imap2_folder_name: empty string [s,/,X,g]' ) ;
  7975. is( 'blabla', imap2_folder_name( $mysync, 'blabla' ), 'imap2_folder_name: blabla [s,/,X,g]' ) ;
  7976. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam'), 'imap2_folder_name: spam/spam [s,/,X,g]');
  7977. is('spamXspam', imap2_folder_name( $mysync, 'spam.spam'), 'imap2_folder_name: spam.spam [s,/,X,g]');
  7978. is('spam.spamXspam', imap2_folder_name( $mysync, 'spam/spam.spam'), 'imap2_folder_name: spam/spam.spam [s,/,X,g]');
  7979. @{ $mysync->{ regextrans2 } } = ( 's, ,_,g' ) ;
  7980. is('blabla', imap2_folder_name( $mysync, 'blabla'), 'imap2_folder_name: blabla [s, ,_,g]');
  7981. is('bla_bla', imap2_folder_name( $mysync, 'bla bla'), 'imap2_folder_name: blabla [s, ,_,g]');
  7982. @{ $mysync->{ regextrans2 } } = ( q{s,(.*),\U$1,} ) ;
  7983. is( 'BLABLA', imap2_folder_name( $mysync, 'blabla' ), q{imap2_folder_name: blabla [s,\U(.*)\E,$1,]} ) ;
  7984. $mysync->{ fixslash2 } = 1 ;
  7985. @{ $mysync->{ regextrans2 } } = ( ) ;
  7986. is(q{INBOX}, imap2_folder_name( $mysync, q{}), 'imap2_folder_name: empty string');
  7987. is('blabla', imap2_folder_name( $mysync, 'blabla'), 'imap2_folder_name: blabla');
  7988. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  7989. is('spam_spam', imap2_folder_name( $mysync, 'spam.spam'), 'imap2_folder_name: spam.spam -> spam_spam');
  7990. is('spam.spam_spam', imap2_folder_name( $mysync, 'spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam_spam');
  7991. 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');
  7992. $mysync->{ h1_sep } = '.';
  7993. $mysync->{ h2_sep } = '/';
  7994. is( q{INBOX}, imap2_folder_name( $mysync, q{}), 'imap2_folder_name: empty string');
  7995. is('blabla', imap2_folder_name( $mysync, 'blabla'), 'imap2_folder_name: blabla');
  7996. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  7997. is('spam/spam', imap2_folder_name( $mysync, 'spam.spam'), 'imap2_folder_name: spam.spam -> spam/spam');
  7998. is('spam.spam/spam', imap2_folder_name( $mysync, 'spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam');
  7999. $mysync->{ fixslash2 } = 0 ;
  8000. $mysync->{ h1_prefix } = q{ };
  8001. is( 'spam.spam/spam', imap2_folder_name( $mysync, 'spam/spam.spam' ), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam' ) ;
  8002. is( 'spam.spam/spam', imap2_folder_name( $mysync, ' spam/spam.spam' ), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam' ) ;
  8003. $mysync->{ h1_sep } = '.' ;
  8004. $mysync->{ h2_sep } = '/' ;
  8005. $mysync->{ h1_prefix } = 'INBOX.' ;
  8006. $mysync->{ h2_prefix } = q{} ;
  8007. @{ $mysync->{ regextrans2 } } = ( q{s,(.*),\U$1,} ) ;
  8008. is( 'BLABLA', imap2_folder_name( $mysync, 'blabla' ), 'imap2_folder_name: blabla' ) ;
  8009. is( 'TEST/TEST/TEST/TEST', imap2_folder_name( $mysync, 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  8010. @{ $mysync->{ regextrans2 } } = ( q{s,(.*),\L$1,} ) ;
  8011. is( 'test/test/test/test', imap2_folder_name( $mysync, 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  8012. # INBOX
  8013. $mysync = {} ;
  8014. $mysync->{ h1_prefix } = q{Pf1.} ;
  8015. $mysync->{ h2_prefix } = q{Pf2/} ;
  8016. $mysync->{ h1_sep } = '.';
  8017. $mysync->{ h2_sep } = '/';
  8018. #
  8019. #$mysync->{ debug } = 1 ;
  8020. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'F1.F2.F3' ), 'imap2_folder_name: F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  8021. is( 'Pf2/F1/INBOX', imap2_folder_name( $mysync, 'F1.INBOX' ), 'imap2_folder_name: F1.INBOX -> Pf2/F1/INBOX' ) ;
  8022. is( 'INBOX', imap2_folder_name( $mysync, 'INBOX' ), 'imap2_folder_name: INBOX -> INBOX' ) ;
  8023. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'Pf1.F1.F2.F3' ), 'imap2_folder_name: Pf1.F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  8024. is( 'Pf2/F1/INBOX', imap2_folder_name( $mysync, 'Pf1.F1.INBOX' ), 'imap2_folder_name: Pf1.F1.INBOX -> Pf2/F1/INBOX' ) ;
  8025. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.INBOX' ), 'imap2_folder_name: Pf1.INBOX -> INBOX' ) ; # not Pf2/INBOX: Yes I can!
  8026. # subfolder2
  8027. $mysync = {} ;
  8028. $mysync->{ h1_prefix } = q{} ;
  8029. $mysync->{ h2_prefix } = q{} ;
  8030. $mysync->{ h1_sep } = '/';
  8031. $mysync->{ h2_sep } = '.';
  8032. set_regextrans2_for_subfolder2( $mysync ) ;
  8033. $mysync->{ subfolder2 } = 'S1.S2' ;
  8034. is( 'S1.S2.F1.F2.F3', imap2_folder_name( $mysync, 'F1/F2/F3' ), 'imap2_folder_name: F1/F2/F3 -> S1.S2.F1.F2.F3' ) ;
  8035. is( 'S1.S2.INBOX', imap2_folder_name( $mysync, 'INBOX' ), 'imap2_folder_name: F1/F2/F3 -> S1.S2.INBOX' ) ;
  8036. $mysync = {} ;
  8037. $mysync->{ h1_prefix } = q{Pf1/} ;
  8038. $mysync->{ h2_prefix } = q{Pf2.} ;
  8039. $mysync->{ h1_sep } = '/';
  8040. $mysync->{ h2_sep } = '.';
  8041. #$mysync->{ debug } = 1 ;
  8042. set_regextrans2_for_subfolder2( $mysync ) ;
  8043. $mysync->{ subfolder2 } = 'Pf2.S1.S2' ;
  8044. 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' ) ;
  8045. is( 'Pf2.S1.S2.INBOX', imap2_folder_name( $mysync, 'INBOX' ), 'imap2_folder_name: INBOX -> Pf2.S1.S2.INBOX' ) ;
  8046. 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' ) ;
  8047. is( 'Pf2.S1.S2.INBOX', imap2_folder_name( $mysync, 'Pf1/INBOX' ), 'imap2_folder_name: INBOX -> Pf2.S1.S2.INBOX' ) ;
  8048. # subfolder1
  8049. # scenario as the reverse of the previous tests, separators point of vue
  8050. $mysync = {} ;
  8051. $mysync->{ h1_prefix } = q{Pf1.} ;
  8052. $mysync->{ h2_prefix } = q{Pf2/} ;
  8053. $mysync->{ h1_sep } = '.';
  8054. $mysync->{ h2_sep } = '/';
  8055. #$mysync->{ debug } = 1 ;
  8056. $mysync->{ subfolder1 } = 'S1.S2' ;
  8057. 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' ) ;
  8058. 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' ) ;
  8059. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.INBOX' ), 'imap2_folder_name: S1.S2.INBOX -> INBOX' ) ;
  8060. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2' ), 'imap2_folder_name: S1.S2 -> INBOX' ) ;
  8061. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.' ), 'imap2_folder_name: S1.S2. -> INBOX' ) ;
  8062. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.INBOX' ), 'imap2_folder_name: Pf1.S1.S2.INBOX -> INBOX' ) ;
  8063. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2' ), 'imap2_folder_name: Pf1.S1.S2 -> INBOX' ) ;
  8064. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.' ), 'imap2_folder_name: Pf1.S1.S2. -> INBOX' ) ;
  8065. $mysync->{ subfolder1 } = 'S1.S2.' ;
  8066. 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' ) ;
  8067. 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' ) ;
  8068. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.INBOX' ), 'imap2_folder_name: S1.S2.INBOX -> INBOX' ) ;
  8069. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2' ), 'imap2_folder_name: S1.S2 -> INBOX' ) ;
  8070. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.' ), 'imap2_folder_name: S1.S2. -> INBOX' ) ;
  8071. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.INBOX' ), 'imap2_folder_name: Pf1.S1.S2.INBOX -> INBOX' ) ;
  8072. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2' ), 'imap2_folder_name: Pf1.S1.S2 -> INBOX' ) ;
  8073. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.' ), 'imap2_folder_name: Pf1.S1.S2. -> INBOX' ) ;
  8074. # subfolder1
  8075. # scenario as Gmail
  8076. $mysync = {} ;
  8077. $mysync->{ h1_prefix } = q{} ;
  8078. $mysync->{ h2_prefix } = q{} ;
  8079. $mysync->{ h1_sep } = '/';
  8080. $mysync->{ h2_sep } = '/';
  8081. #$mysync->{ debug } = 1 ;
  8082. $mysync->{ subfolder1 } = 'S1/S2' ;
  8083. is( 'F1/F2/F3', imap2_folder_name( $mysync, 'S1/S2/F1/F2/F3' ), 'imap2_folder_name: S1/S2/F1/F2/F3 -> F1/F2/F3' ) ;
  8084. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/INBOX' ), 'imap2_folder_name: S1/S2/INBOX -> INBOX' ) ;
  8085. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2' ), 'imap2_folder_name: S1/S2 -> INBOX' ) ;
  8086. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/' ), 'imap2_folder_name: S1/S2/ -> INBOX' ) ;
  8087. $mysync->{ subfolder1 } = 'S1/S2/' ;
  8088. is( 'F1/F2/F3', imap2_folder_name( $mysync, 'S1/S2/F1/F2/F3' ), 'imap2_folder_name: S1/S2/F1/F2/F3 -> F1/F2/F3' ) ;
  8089. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/INBOX' ), 'imap2_folder_name: S1/S2/INBOX -> INBOX' ) ;
  8090. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2' ), 'imap2_folder_name: S1/S2 -> INBOX' ) ;
  8091. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/' ), 'imap2_folder_name: S1/S2/ -> INBOX' ) ;
  8092. note( 'Leaving tests_imap2_folder_name()' ) ;
  8093. return ;
  8094. }
  8095. # Global variables to remove:
  8096. # None?
  8097. sub imap2_folder_name
  8098. {
  8099. my $mysync = shift ;
  8100. my ( $h1_fold ) = shift ;
  8101. my ( $h2_fold ) ;
  8102. if ( $mysync->{f1f2h}{ $h1_fold } ) {
  8103. $h2_fold = $mysync->{f1f2h}{ $h1_fold } ;
  8104. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "f1f2 [$h1_fold] -> [$h2_fold]\n" ) ;
  8105. return( $h2_fold ) ;
  8106. }
  8107. if ( $mysync->{f1f2auto}{ $h1_fold } ) {
  8108. $h2_fold = $mysync->{f1f2auto}{ $h1_fold } ;
  8109. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "automap [$h1_fold] -> [$h2_fold]\n" ) ;
  8110. return( $h2_fold ) ;
  8111. }
  8112. if ( $mysync->{ subfolder1 } )
  8113. {
  8114. my $esc_h1_sep = "\\" . $mysync->{ h1_sep } ;
  8115. # case where subfolder1 has the sep1 at the end, then remove it
  8116. my $part_to_removed = remove_last_char_if_is( $mysync->{ subfolder1 }, $mysync->{ h1_sep } ) ;
  8117. # remove the subfolder1 part and the sep1 if present after
  8118. $h1_fold =~ s{$part_to_removed($esc_h1_sep)?}{} ;
  8119. #myprint( "h1_fold=$h1_fold\n" ) ;
  8120. }
  8121. if ( ( q{} eq $h1_fold ) or ( $mysync->{ h1_prefix } eq $h1_fold ) )
  8122. {
  8123. $h1_fold = 'INBOX' ;
  8124. }
  8125. $h2_fold = prefix_seperator_invertion( $mysync, $h1_fold ) ;
  8126. $h2_fold = regextrans2( $mysync, $h2_fold ) ;
  8127. return( $h2_fold ) ;
  8128. }
  8129. sub tests_remove_last_char_if_is
  8130. {
  8131. note( 'Entering tests_remove_last_char_if_is()' ) ;
  8132. is( undef, remove_last_char_if_is( ), 'remove_last_char_if_is: no args => undef' ) ;
  8133. is( q{}, remove_last_char_if_is( q{} ), 'remove_last_char_if_is: empty => empty' ) ;
  8134. is( q{}, remove_last_char_if_is( q{}, 'Z' ), 'remove_last_char_if_is: empty Z => empty' ) ;
  8135. is( q{}, remove_last_char_if_is( 'Z', 'Z' ), 'remove_last_char_if_is: Z Z => empty' ) ;
  8136. is( 'abc', remove_last_char_if_is( 'abcZ', 'Z' ), 'remove_last_char_if_is: abcZ Z => abc' ) ;
  8137. is( 'abcY', remove_last_char_if_is( 'abcY', 'Z' ), 'remove_last_char_if_is: abcY Z => abcY' ) ;
  8138. note( 'Leaving tests_remove_last_char_if_is()' ) ;
  8139. return ;
  8140. }
  8141. sub remove_last_char_if_is
  8142. {
  8143. my $string = shift ;
  8144. my $char = shift ;
  8145. if ( ! defined $string )
  8146. {
  8147. return ;
  8148. }
  8149. if ( ! defined $char )
  8150. {
  8151. return $string ;
  8152. }
  8153. my $last_char = substr $string, -1 ;
  8154. if ( $char eq $last_char )
  8155. {
  8156. chop $string ;
  8157. return $string ;
  8158. }
  8159. else
  8160. {
  8161. return $string ;
  8162. }
  8163. }
  8164. sub tests_prefix_seperator_invertion
  8165. {
  8166. note( 'Entering tests_prefix_seperator_invertion()' ) ;
  8167. is( undef, prefix_seperator_invertion( ), 'prefix_seperator_invertion: no args => undef' ) ;
  8168. is( q{}, prefix_seperator_invertion( undef, q{} ), 'prefix_seperator_invertion: empty string => empty string' ) ;
  8169. is( 'lalala', prefix_seperator_invertion( undef, 'lalala' ), 'prefix_seperator_invertion: lalala => lalala' ) ;
  8170. is( 'lal/ala', prefix_seperator_invertion( undef, 'lal/ala' ), 'prefix_seperator_invertion: lal/ala => lal/ala' ) ;
  8171. is( 'lal.ala', prefix_seperator_invertion( undef, 'lal.ala' ), 'prefix_seperator_invertion: lal.ala => lal.ala' ) ;
  8172. is( '////', prefix_seperator_invertion( undef, '////' ), 'prefix_seperator_invertion: //// => ////' ) ;
  8173. is( '.....', prefix_seperator_invertion( undef, '.....' ), 'prefix_seperator_invertion: ..... => .....' ) ;
  8174. my $mysync = {
  8175. h1_prefix => q{},
  8176. h2_prefix => q{},
  8177. h1_sep => '/',
  8178. h2_sep => '/',
  8179. } ;
  8180. is( q{}, prefix_seperator_invertion( $mysync, q{} ), 'prefix_seperator_invertion: $mysync empty string => empty string' ) ;
  8181. is( 'lalala', prefix_seperator_invertion( $mysync, 'lalala' ), 'prefix_seperator_invertion: $mysync lalala => lalala' ) ;
  8182. is( 'lal/ala', prefix_seperator_invertion( $mysync, 'lal/ala' ), 'prefix_seperator_invertion: $mysync lal/ala => lal/ala' ) ;
  8183. is( 'lal.ala', prefix_seperator_invertion( $mysync, 'lal.ala' ), 'prefix_seperator_invertion: $mysync lal.ala => lal.ala' ) ;
  8184. is( '////', prefix_seperator_invertion( $mysync, '////' ), 'prefix_seperator_invertion: $mysync //// => ////' ) ;
  8185. is( '.....', prefix_seperator_invertion( $mysync, '.....' ), 'prefix_seperator_invertion: $mysync ..... => .....' ) ;
  8186. $mysync = {
  8187. h1_prefix => 'PPP',
  8188. h2_prefix => 'QQQ',
  8189. h1_sep => 's',
  8190. h2_sep => 't',
  8191. } ;
  8192. is( q{QQQ}, prefix_seperator_invertion( $mysync, q{} ), 'prefix_seperator_invertion: PPPQQQst empty string => QQQ' ) ;
  8193. is( 'QQQlalala', prefix_seperator_invertion( $mysync, 'lalala' ), 'prefix_seperator_invertion: PPPQQQst lalala => QQQlalala' ) ;
  8194. is( 'QQQlal/ala', prefix_seperator_invertion( $mysync, 'lal/ala' ), 'prefix_seperator_invertion: PPPQQQst lal/ala => QQQlal/ala' ) ;
  8195. is( 'QQQlal.ala', prefix_seperator_invertion( $mysync, 'lal.ala' ), 'prefix_seperator_invertion: PPPQQQst lal.ala => QQQlal.ala' ) ;
  8196. is( 'QQQ////', prefix_seperator_invertion( $mysync, '////' ), 'prefix_seperator_invertion: PPPQQQst //// => QQQ////' ) ;
  8197. is( 'QQQ.....', prefix_seperator_invertion( $mysync, '.....' ), 'prefix_seperator_invertion: PPPQQQst ..... => QQQ.....' ) ;
  8198. is( 'QQQPlalala', prefix_seperator_invertion( $mysync, 'PPPPlalala' ), 'prefix_seperator_invertion: PPPQQQst PPPPlalala => QQQPlalala' ) ;
  8199. is( 'QQQ', prefix_seperator_invertion( $mysync, 'PPP' ), 'prefix_seperator_invertion: PPPQQQst PPP => QQQ' ) ;
  8200. is( 'QQQttt', prefix_seperator_invertion( $mysync, 'sss' ), 'prefix_seperator_invertion: PPPQQQst sss => QQQttt' ) ;
  8201. is( 'QQQt', prefix_seperator_invertion( $mysync, 's' ), 'prefix_seperator_invertion: PPPQQQst s => QQQt' ) ;
  8202. is( 'QQQtAAAtBBB', prefix_seperator_invertion( $mysync, 'PPPsAAAsBBB' ), 'prefix_seperator_invertion: PPPQQQst PPPsAAAsBBB => QQQtAAAtBBB' ) ;
  8203. note( 'Leaving tests_prefix_seperator_invertion()' ) ;
  8204. return ;
  8205. }
  8206. # Global variables to remove:
  8207. sub prefix_seperator_invertion
  8208. {
  8209. my $mysync = shift ;
  8210. my $h1_fold = shift ;
  8211. my $h2_fold ;
  8212. if ( not defined $h1_fold ) { return ; }
  8213. my $my_h1_prefix = $mysync->{ h1_prefix } || q{} ;
  8214. my $my_h2_prefix = $mysync->{ h2_prefix } || q{} ;
  8215. my $my_h1_sep = $mysync->{ h1_sep } || '/' ;
  8216. my $my_h2_sep = $mysync->{ h2_sep } || '/' ;
  8217. # first we remove the prefix
  8218. $h1_fold =~ s/^\Q$my_h1_prefix\E//x ;
  8219. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "removed host1 prefix: [$h1_fold]\n" ) ;
  8220. $h2_fold = separator_invert( $mysync, $h1_fold, $my_h1_sep, $my_h2_sep ) ;
  8221. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "inverted separators: [$h2_fold]\n" ) ;
  8222. # Adding the prefix supplied by namespace or the --prefix2 option
  8223. # except for INBOX or Inbox
  8224. if ( $h2_fold !~ m/^INBOX$/xi )
  8225. {
  8226. $h2_fold = $my_h2_prefix . $h2_fold ;
  8227. }
  8228. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "added host2 prefix: [$h2_fold]\n" ) ;
  8229. return( $h2_fold ) ;
  8230. }
  8231. sub tests_separator_invert
  8232. {
  8233. note( 'Entering tests_separator_invert()' ) ;
  8234. my $mysync = {} ;
  8235. $mysync->{ fixslash2 } = 0 ;
  8236. ok( not( defined separator_invert( ) ), 'separator_invert: no args' ) ;
  8237. ok( not( defined separator_invert( q{} ) ), 'separator_invert: not enough args' ) ;
  8238. ok( not( defined separator_invert( q{}, q{} ) ), 'separator_invert: not enough args' ) ;
  8239. ok( q{} eq separator_invert( $mysync, q{}, q{}, q{} ), 'separator_invert: 3 empty strings' ) ;
  8240. ok( 'lalala' eq separator_invert( $mysync, 'lalala', q{}, q{} ), 'separator_invert: empty separator' ) ;
  8241. ok( 'lalala' eq separator_invert( $mysync, 'lalala', '/', '/' ), 'separator_invert: same separator /' ) ;
  8242. ok( 'lal/ala' eq separator_invert( $mysync, 'lal/ala', '/', '/' ), 'separator_invert: same separator / 2' ) ;
  8243. ok( 'lal.ala' eq separator_invert( $mysync, 'lal/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  8244. ok( 'lal/ala' eq separator_invert( $mysync, 'lal.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  8245. ok( 'la.l/ala' eq separator_invert( $mysync, 'la/l.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  8246. ok( 'l/al.ala' eq separator_invert( $mysync, 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  8247. $mysync->{ fixslash2 } = 1 ;
  8248. ok( 'l_al.ala' eq separator_invert( $mysync, 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  8249. note( 'Leaving tests_separator_invert()' ) ;
  8250. return ;
  8251. }
  8252. # Global variables to remove:
  8253. #
  8254. sub separator_invert
  8255. {
  8256. my( $mysync, $h1_fold, $h1_separator, $h2_separator ) = @_ ;
  8257. return( undef ) if ( not all_defined( $mysync, $h1_fold, $h1_separator, $h2_separator ) ) ;
  8258. # The separator we hope we'll never encounter: 00000000 == 0x00
  8259. my $o_sep = "\000" ;
  8260. my $h2_fold = $h1_fold ;
  8261. $h2_fold =~ s,\Q$h2_separator,$o_sep,xg ;
  8262. $h2_fold =~ s,\Q$h1_separator,$h2_separator,xg ;
  8263. $h2_fold =~ s,\Q$o_sep,$h1_separator,xg ;
  8264. $h2_fold =~ s,/,_,xg if( $mysync->{ fixslash2 } and '/' ne $h2_separator and '/' eq $h1_separator ) ;
  8265. return( $h2_fold ) ;
  8266. }
  8267. sub regextrans2
  8268. {
  8269. my( $mysync, $h2_fold ) = @_ ;
  8270. # Transforming the folder name by the --regextrans2 option(s)
  8271. foreach my $regextrans2 ( @{ $mysync->{ regextrans2 } } ) {
  8272. my $h2_fold_before = $h2_fold ;
  8273. my $ret = eval "\$h2_fold =~ $regextrans2 ; 1 " ;
  8274. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "[$h2_fold_before] -> [$h2_fold] using regextrans2 [$regextrans2]\n" ) ;
  8275. if ( not ( defined $ret ) or $EVAL_ERROR ) {
  8276. $mysync->{nb_errors}++ ;
  8277. exit_clean( $mysync, $EX_USAGE,
  8278. "error: eval regextrans2 '$regextrans2': $EVAL_ERROR\n"
  8279. ) ;
  8280. }
  8281. }
  8282. return( $h2_fold ) ;
  8283. }
  8284. sub tests_decompose_regex
  8285. {
  8286. note( 'Entering tests_decompose_regex()' ) ;
  8287. ok( 1, 'decompose_regex 1' ) ;
  8288. ok( 0 == compare_lists( [ q{}, q{} ], [ decompose_regex( q{} ) ] ), 'decompose_regex empty string' ) ;
  8289. ok( 0 == compare_lists( [ '.*', 'lala' ], [ decompose_regex( 's/.*/lala/' ) ] ), 'decompose_regex s/.*/lala/' ) ;
  8290. note( 'Leaving tests_decompose_regex()' ) ;
  8291. return ;
  8292. }
  8293. sub decompose_regex
  8294. {
  8295. my $regex = shift ;
  8296. my( $left_part, $right_part ) ;
  8297. ( $left_part, $right_part ) = $regex =~ m{^s/((?:[^/]|\\/)+)/((?:[^/]|\\/)+)/}x;
  8298. return( q{}, q{} ) if not $left_part ;
  8299. return( $left_part, $right_part ) ;
  8300. }
  8301. sub tests_timenext
  8302. {
  8303. note( 'Entering tests_timenext()' ) ;
  8304. is( undef, timenext( ), 'timenext: no args => undef' ) ;
  8305. my $mysync ;
  8306. is( undef, timenext( $mysync ), 'timenext: undef => undef' ) ;
  8307. $mysync = {} ;
  8308. ok( time - timenext( $mysync ) <= 1e-02, 'timenext: defined first time => ~ time' ) ;
  8309. ok( timenext( $mysync ) <= 1e-02, 'timenext: second time => less than 1e-02' ) ;
  8310. ok( timenext( $mysync ) <= 1e-02, 'timenext: third time => less than 1e-02' ) ;
  8311. note( 'Leaving tests_timenext()' ) ;
  8312. return ;
  8313. }
  8314. sub timenext
  8315. {
  8316. my $mysync = shift ;
  8317. if ( ! defined $mysync )
  8318. {
  8319. return ;
  8320. }
  8321. my ( $timenow, $timediff ) ;
  8322. $mysync->{ timebefore } ||= 0; # epoch...
  8323. $timenow = time ;
  8324. $timediff = $timenow - $mysync->{ timebefore } ;
  8325. $mysync->{ timebefore } = $timenow ;
  8326. # myprint( "timenext: $timediff\n" ) ;
  8327. return( $timediff ) ;
  8328. }
  8329. sub tests_timesince
  8330. {
  8331. note( 'Entering tests_timesince()' ) ;
  8332. ok( timesince( time - 1 ) - 1 <= 1e-02, 'timesince: time - 1 => <= 1 + 1e-02' ) ;
  8333. ok( timesince( time ) <= 1e-02, 'timesince: time => <= 1e-02' ) ;
  8334. ok( timesince( ) - time <= 1e-02, 'timesince: no args => <= time + 1e-02' ) ;
  8335. note( 'Leaving tests_timesince()' ) ;
  8336. return ;
  8337. }
  8338. sub timesince
  8339. {
  8340. my $timeinit = shift || 0 ;
  8341. my ( $timenow, $timediff ) ;
  8342. $timenow = time ;
  8343. $timediff = $timenow - $timeinit ;
  8344. # Often used in a division so no 0 but a nano seconde.
  8345. return( max( $timediff, min( 1e-09, $timediff ) ) ) ;
  8346. }
  8347. sub tests_regexflags
  8348. {
  8349. note( 'Entering tests_regexflags()' ) ;
  8350. my $mysync = {} ;
  8351. ok( q{} eq regexflags( $mysync, q{} ), 'regexflags, null string q{}' ) ;
  8352. ok( q{\Seen NonJunk $Spam} eq regexflags( $mysync, q{\Seen NonJunk $Spam} ), q{regexflags, nothing to do} ) ;
  8353. @{ $mysync->{ regexflag } } = ('I am BAD' ) ;
  8354. ok( not ( defined regexflags( $mysync, q{} ) ), 'regexflags, bad regex' ) ;
  8355. @{ $mysync->{ regexflag } } = ( 's/NonJunk//g' ) ;
  8356. ok( q{\Seen $Spam} eq regexflags( $mysync, q{\Seen NonJunk $Spam} ), q{regexflags, remove NonJunk: 's/NonJunk//g'} ) ;
  8357. @{ $mysync->{ regexflag } } = ( q{s/\$Spam//g} ) ;
  8358. ok( q{\Seen NonJunk } eq regexflags( $mysync, q{\Seen NonJunk $Spam} ), q{regexflags, remove $Spam: 's/\$Spam//g'} ) ;
  8359. @{ $mysync->{ regexflag } } = ( 's/\\\\Seen//g' ) ;
  8360. ok( q{ NonJunk $Spam} eq regexflags( $mysync, q{\Seen NonJunk $Spam} ), q{regexflags, remove \Seen: 's/\\\\\\\\Seen//g'} ) ;
  8361. @{ $mysync->{ regexflag } } = ( 's/(\s|^)[^\\\\]\w+//g' ) ;
  8362. ok( q{\Seen \Middle \End} eq regexflags( $mysync, q{\Seen NonJunk \Middle $Spam \End} ), q{regexflags: only \word among \Seen NonJunk \Middle $Spam \End} ) ;
  8363. ok( q{ \Seen \Middle \End1} eq regexflags( $mysync, q{Begin \Seen NonJunk \Middle $Spam \End1 End} ),
  8364. q{regexflags: only \word among Begin \Seen NonJunk \Middle $Spam \End1 End} ) ;
  8365. @{ $mysync->{ regexflag } } = ( q{s/.*?(Keep1|Keep2|Keep3)/$1 /g} ) ;
  8366. ok( 'Keep1 Keep2 ReB' eq regexflags( $mysync, 'ReA Keep1 REM Keep2 ReB' ), 'Keep only regex' ) ;
  8367. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM REM Keep1 Keep2' ), 'Keep only regex' ) ;
  8368. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 REM REM Keep2' ), 'Keep only regex' ) ;
  8369. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM Keep1 REM REM Keep2' ), 'Keep only regex' ) ;
  8370. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 Keep2' ), 'Keep only regex' ) ;
  8371. ok( 'Keep1 ' eq regexflags( $mysync, 'REM Keep1' ), 'Keep only regex' ) ;
  8372. @{ $mysync->{ regexflag } } = ( q{s/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g} ) ;
  8373. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 Keep2 ReB' ), 'Keep only regex' ) ;
  8374. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 Keep2 REM REM REM' ), 'Keep only regex' ) ;
  8375. ok( 'Keep2 ' eq regexflags( $mysync, 'Keep2 REM REM REM' ), 'Keep only regex' ) ;
  8376. @{ $mysync->{ regexflag } } = ( q{s/.*?(Keep1|Keep2|Keep3)/$1 /g},
  8377. 's/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g' ) ;
  8378. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM Keep1 REM Keep2 REM' ), 'Keep only regex' ) ;
  8379. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'Keep1 REM Keep2 REM' ), 'Keep only regex' ) ;
  8380. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM Keep1 Keep2 REM' ), 'Keep only regex' ) ;
  8381. ok( 'Keep1 Keep2 ' eq regexflags( $mysync, 'REM Keep1 REM Keep2' ), 'Keep only regex' ) ;
  8382. ok( 'Keep1 Keep2 Keep3 ' eq regexflags( $mysync, 'REM Keep1 REM Keep2 REM REM Keep3 REM' ), 'Keep only regex' ) ;
  8383. ok( 'Keep1 ' eq regexflags( $mysync, 'REM REM Keep1 REM REM REM ' ), 'Keep only regex' ) ;
  8384. ok( 'Keep1 Keep3 ' eq regexflags( $mysync, 'RE1 Keep1 RE2 Keep3 RE3 RE4 RE5 ' ), 'Keep only regex' ) ;
  8385. @{ $mysync->{ regexflag } } = ( 's/(.*)/$1 jrdH8u/' ) ;
  8386. ok('REM REM REM REM REM jrdH8u' eq regexflags( $mysync, 'REM REM REM REM REM' ), q{Add jrdH8u 's/(.*)/\$1 jrdH8u/'} ) ;
  8387. @{ $mysync->{ regexflag } } = ('s/jrdH8u *//' );
  8388. ok('REM REM REM REM REM ' eq regexflags( $mysync, 'REM REM REM REM REM jrdH8u' ), q{Remove jrdH8u s/jrdH8u *//} ) ;
  8389. @{ $mysync->{ regexflag } } = (
  8390. 's/.*?(?:(\\\\(?:Answered|Flagged|Deleted|Seen|Draft)\s?)|$)/defined($1)?$1:q()/eg'
  8391. );
  8392. ok( '\\Deleted \\Answered '
  8393. eq regexflags( $mysync, 'Blabla \$Junk \\Deleted machin \\Answered truc' ),
  8394. 'Keep only regex: Exchange case (Phil)' ) ;
  8395. ok( q{} eq regexflags( $mysync, q{} ), 'Keep only regex: Exchange case, null string (Phil)' ) ;
  8396. ok( q{}
  8397. eq regexflags( $mysync, 'Blabla $Junk machin truc' ),
  8398. 'Keep only regex: Exchange case, no accepted flags (Phil)' ) ;
  8399. ok('\\Deleted \\Answered \\Draft \\Flagged '
  8400. eq regexflags( $mysync, '\\Deleted \\Answered \\Draft \\Flagged ' ),
  8401. 'Keep only regex: Exchange case (Phil)' ) ;
  8402. @{ $mysync->{ regexflag } } = ( 's/\\\\Flagged//g' ) ;
  8403. is('\Deleted \Answered \Draft ',
  8404. regexflags( $mysync, '\\Deleted \\Answered \\Draft \\Flagged ' ),
  8405. 'regexflags: remove \Flagged 1' ) ;
  8406. is('\\Deleted \\Answered \\Draft',
  8407. regexflags( $mysync, '\\Deleted \\Flagged \\Answered \\Draft' ),
  8408. 'regexflags: remove \Flagged 2' ) ;
  8409. # I didn't understand why it gives \F
  8410. # https://perldoc.perl.org/perlrebackslash.html
  8411. # \F Foldcase till \E. Not in [].
  8412. # https://perldoc.perl.org/functions/fc.html
  8413. # \F Not available in old Perl so I comment the test
  8414. # @{ $mysync->{ regexflag } } = ( 's/\\Flagged/X/g' ) ;
  8415. #is('\Deleted FX \Answered \FX \Draft \FX',
  8416. #regexflags( '\Deleted Flagged \Answered \Flagged \Draft \Flagged' ),
  8417. # 'regexflags: remove \Flagged 3 mistery...' ) ;
  8418. $mysync->{ regexflag } = [ ] ;
  8419. $mysync->{ filterbuggyflags } = 1 ;
  8420. filterbuggyflags( $mysync ) ;
  8421. is( '\Deleted \Answered \Draft \Flagged',
  8422. regexflags( $mysync, '\\Deleted \\Answered \\RECEIPTCHECKED \\Draft \\Indexed \\Flagged' ),
  8423. 'regexflags: remove famous /X 1' ) ;
  8424. is( '\\Deleted \\Flagged \\Answered \\Draft',
  8425. regexflags( $mysync, '\\Deleted \\RECEIPTCHECKED \\Flagged \\Answered \\Indexed \\Draft' ),
  8426. 'regexflags: remove famous /X 2' ) ;
  8427. is( '\ ', '\\ ', 'regexflags: \ is \\ ' ) ;
  8428. is( '\\ ', '\\ ', 'regexflags: \\ is \\ ' ) ;
  8429. is( '\\ \ ', '\ \\ ', 'regexflags: \\ \ is \ \\ ' ) ;
  8430. note( 'Leaving tests_regexflags()' ) ;
  8431. return ;
  8432. }
  8433. sub regexflags
  8434. {
  8435. my $mysync = shift ;
  8436. my $flags = shift ;
  8437. foreach my $regexflag ( @{ $mysync->{ regexflag } } )
  8438. {
  8439. my $flags_orig = $flags ;
  8440. $debugflags and myprint( "eval \$flags =~ $regexflag\n" ) ;
  8441. my $ret = eval "\$flags =~ $regexflag ; 1 " ;
  8442. $debugflags and myprint( "regexflag $regexflag [$flags_orig] -> [$flags]\n" ) ;
  8443. if( not ( defined $ret ) or $EVAL_ERROR ) {
  8444. myprint( "Error: eval regexflag '$regexflag': $EVAL_ERROR\n" ) ;
  8445. return( undef ) ;
  8446. }
  8447. }
  8448. return( $flags ) ;
  8449. }
  8450. sub filterbuggyflags
  8451. {
  8452. my $mysync = shift ;
  8453. if ( $mysync->{ filterbuggyflags } )
  8454. {
  8455. unshift @{ $mysync->{ regexflag } }, buggyflagsregex( ) ;
  8456. }
  8457. return ;
  8458. }
  8459. sub tests_remove_doublequotes_if_any
  8460. {
  8461. note( 'Entering tests_remove_doublequotes_if_any()' ) ;
  8462. # the number of tests is stupid here
  8463. is( undef, remove_doublequotes_if_any( ), 'remove_doublequotes_if_any: no args => undef' ) ;
  8464. is( q{}, remove_doublequotes_if_any( q{} ), 'remove_doublequotes_if_any: empty string => empty string' ) ;
  8465. is( q{}, remove_doublequotes_if_any( q{""} ), 'remove_doublequotes_if_any: double-quotes => empty string' ) ;
  8466. is( q{}, remove_doublequotes_if_any( q{"""} ), 'remove_doublequotes_if_any: double-quotes => empty string' ) ;
  8467. is( q{}, remove_doublequotes_if_any( q{"""} ), 'remove_doublequotes_if_any: double-quotes => empty string' ) ;
  8468. is( q{toto}, remove_doublequotes_if_any( q{"toto"} ), 'remove_doublequotes_if_any: "toto" => toto' ) ;
  8469. is( q{toto}, remove_doublequotes_if_any( q{toto} ), 'remove_doublequotes_if_any: toto => toto' ) ;
  8470. is( q{toto}, remove_doublequotes_if_any( q{to"to} ), 'remove_doublequotes_if_any: to"to => toto' ) ;
  8471. is( q{toto}, remove_doublequotes_if_any( q{toto"} ), 'remove_doublequotes_if_any: toto" => toto' ) ;
  8472. is( q{toto}, remove_doublequotes_if_any( q{"toto} ), 'remove_doublequotes_if_any: "toto => toto' ) ;
  8473. is( q{toto}, remove_doublequotes_if_any( q{"to"to} ), 'remove_doublequotes_if_any: "to"to => toto' ) ;
  8474. is( q{toto}, remove_doublequotes_if_any( q{to"to"} ), 'remove_doublequotes_if_any: to"to" => toto' ) ;
  8475. is( q{toto}, remove_doublequotes_if_any( q{to\"to} ), 'remove_doublequotes_if_any: to\"to => toto' ) ;
  8476. is( q{toto}, remove_doublequotes_if_any( q{toto\"} ), 'remove_doublequotes_if_any: toto\" => toto' ) ;
  8477. is( q{toto}, remove_doublequotes_if_any( q{\"toto} ), 'remove_doublequotes_if_any: \"toto => toto' ) ;
  8478. is( q{toto}, remove_doublequotes_if_any( q{\"to\"to} ), 'remove_doublequotes_if_any: \"to\"to => toto' ) ;
  8479. is( q{toto}, remove_doublequotes_if_any( q{to\"to\"} ), 'remove_doublequotes_if_any: to\"to" => toto' ) ;
  8480. note( 'Leaving tests_remove_doublequotes_if_any()' ) ;
  8481. return ;
  8482. }
  8483. sub remove_doublequotes_if_any
  8484. {
  8485. my $string = shift ;
  8486. if ( ! defined $string ) { return ; }
  8487. $string =~ s/\\\"//g ;
  8488. $string =~ tr/"//d ;
  8489. return $string ;
  8490. }
  8491. # No globals here
  8492. sub acls_sync
  8493. {
  8494. # https://tools.ietf.org/html/rfc4314
  8495. # Standard Rights:
  8496. # https://tools.ietf.org/html/rfc4314#section-2.1
  8497. my( $mysync, $h1_fold, $h2_fold ) = @_ ;
  8498. if ( $mysync->{ syncacls } ) {
  8499. my $h1_hash = $mysync->{imap1}->getacl($h1_fold)
  8500. or myprint( "Host1: Could not getacl for $h1_fold: $EVAL_ERROR\n" ) ;
  8501. my $h2_hash = $mysync->{imap2}->getacl($h2_fold)
  8502. or myprint( "Host2: Could not getacl for $h2_fold: $EVAL_ERROR\n" ) ;
  8503. my %users = map { ($_, 1) } ( keys %{ $h1_hash} , keys %{ $h2_hash } ) ;
  8504. foreach my $user (sort keys %users ) {
  8505. my $h1_acl = remove_doublequotes_if_any( $h1_hash->{$user} ) || '' ;
  8506. my $h2_acl = remove_doublequotes_if_any( $h2_hash->{$user} ) || '' ;
  8507. myprint( "Host1: user $user has acl [$h1_acl] on host1\n" ) ;
  8508. myprint( "Host2: user $user has acl [$h2_acl] on host2\n" ) ;
  8509. # removes surrounding double-quotes if any
  8510. my $user_no_quotes = remove_doublequotes_if_any( $user ) ;
  8511. if ( $h1_hash->{$user}
  8512. && $h2_hash->{$user}
  8513. && $h1_hash->{$user} eq $h2_hash->{$user} )
  8514. {
  8515. myprint( "Host2: user $user_no_quotes has already the same acl, no need to set it.\n" ) ;
  8516. next ;
  8517. }
  8518. myprint( "Host2: setting acl for folder $h2_fold user $user_no_quotes acl $h1_acl $mysync->{dry_message}\n" ) ;
  8519. unless ( $mysync->{dry} ) {
  8520. $mysync->{imap2}->setacl( $h2_fold, $user_no_quotes, $h1_acl )
  8521. or myprint( "Could not set acl for user $user_no_quotes on host2: $EVAL_ERROR\n" ) ;
  8522. }
  8523. }
  8524. }
  8525. return ;
  8526. }
  8527. sub tests_permanentflags
  8528. {
  8529. note( 'Entering tests_permanentflags()' ) ;
  8530. my $mysync = { } ;
  8531. ok( q{} eq permanentflags( $mysync, ' * OK [PERMANENTFLAGS (\* \Draft \Answered)] Limited' ),
  8532. 'permanentflags \*' ) ;
  8533. ok( '\Draft \Answered' eq permanentflags( $mysync, ' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited' ),
  8534. 'permanentflags \Draft \Answered' ) ;
  8535. ok( '\Draft \Answered'
  8536. eq permanentflags( $mysync, 'Blabla',
  8537. ' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited',
  8538. 'Blabla' ),
  8539. 'permanentflags \Draft \Answered'
  8540. ) ;
  8541. ok( q{} eq permanentflags( $mysync, 'Blabla' ), 'permanentflags nothing' ) ;
  8542. note( 'Leaving tests_permanentflags()' ) ;
  8543. return ;
  8544. }
  8545. sub permanentflags
  8546. {
  8547. my $mysync = shift ;
  8548. my @lines = @_ ;
  8549. foreach my $line (@lines) {
  8550. if ( $line =~ m{\[PERMANENTFLAGS\s\(([^)]+?)\)\]}x ) {
  8551. ( $debugflags or $sync->{ debug } ) and myprint( "permanentflags: $line" ) ;
  8552. my $permanentflags = $1 ;
  8553. if ( $permanentflags =~ m{\\\*}x )
  8554. {
  8555. $permanentflags = q{} ;
  8556. }
  8557. return( $permanentflags ) ;
  8558. } ;
  8559. }
  8560. return( q{} ) ;
  8561. }
  8562. sub tests_flags_filter
  8563. {
  8564. note( 'Entering tests_flags_filter()' ) ;
  8565. ok( '\Seen' eq flags_filter('\Seen', '\Draft \Seen \Answered'), 'flags_filter ' );
  8566. ok( q{} eq flags_filter('\Seen', '\Draft \Answered'), 'flags_filter ' );
  8567. ok( '\Seen' eq flags_filter('\Seen', '\Seen'), 'flags_filter ' );
  8568. ok( '\Seen' eq flags_filter('\Seen', ' \Seen '), 'flags_filter ' );
  8569. ok( '\Seen \Draft'
  8570. eq flags_filter('\Seen \Draft', '\Draft \Seen \Answered'), 'flags_filter ' );
  8571. ok( '\Seen \Draft'
  8572. eq flags_filter('\Seen \Draft', ' \Draft \Seen \Answered '), 'flags_filter ' );
  8573. note( 'Leaving tests_flags_filter()' ) ;
  8574. return ;
  8575. }
  8576. sub flags_filter
  8577. {
  8578. my( $flags, $allowed_flags ) = @_ ;
  8579. my @flags = split /\s+/x, $flags ;
  8580. my %allowed_flags = map { $_ => 1 } split q{ }, $allowed_flags ;
  8581. my @flags_out = map { exists $allowed_flags{$_} ? $_ : () } @flags ;
  8582. my $flags_out = join q{ }, @flags_out ;
  8583. return( $flags_out ) ;
  8584. }
  8585. sub tests_flagscase
  8586. {
  8587. note( 'Entering tests_flagscase()' ) ;
  8588. ok( '\Seen' eq flagscase( '\Seen' ), 'flagscase: \Seen -> \Seen' ) ;
  8589. ok( '\Seen' eq flagscase( '\SEEN' ), 'flagscase: \SEEN -> \Seen' ) ;
  8590. ok( '\Seen \Draft' eq flagscase( '\SEEN \DRAFT' ), 'flagscase: \SEEN \DRAFT -> \Seen \Draft' ) ;
  8591. ok( '\Draft \Seen' eq flagscase( '\DRAFT \SEEN' ), 'flagscase: \DRAFT \SEEN -> \Draft \Seen' ) ;
  8592. ok( '\Draft LALA \Seen' eq flagscase( '\DRAFT LALA \SEEN' ), 'flagscase: \DRAFT LALA \SEEN -> \Draft LALA \Seen' ) ;
  8593. ok( '\Draft lala \Seen' eq flagscase( '\DRAFT lala \SEEN' ), 'flagscase: \DRAFT lala \SEEN -> \Draft lala \Seen' ) ;
  8594. note( 'Leaving tests_flagscase()' ) ;
  8595. return ;
  8596. }
  8597. sub flagscase
  8598. {
  8599. my $flags = shift ;
  8600. my @flags = split /\s+/x, $flags ;
  8601. my %rfc_flags = map { $_ => 1 } split q{ }, '\Answered \Flagged \Deleted \Seen \Draft' ;
  8602. my @flags_out = map { exists $rfc_flags{ ucsecond( lc $_ ) } ? ucsecond( lc $_ ) : $_ } @flags ;
  8603. my $flags_out = join q{ }, @flags_out ;
  8604. return( $flags_out ) ;
  8605. }
  8606. sub tests_flags_for_host2
  8607. {
  8608. note( 'Entering tests_flags_for_host2()' ) ;
  8609. is( undef, flags_for_host2( ), 'flags_for_host2: no args => undef' ) ;
  8610. my $mysync ;
  8611. is( undef, flags_for_host2( $mysync ), 'flags_for_host2: undef => undef' ) ;
  8612. $mysync = { } ;
  8613. is( undef, flags_for_host2( $mysync ), 'flags_for_host2: nothing => undef' ) ;
  8614. is( q{}, flags_for_host2( $mysync, '' ), 'flags_for_host2: no flags => empty string' ) ;
  8615. is( q{}, flags_for_host2( $mysync, '\Recent' ), 'flags_for_host2: \Recent => empty string' ) ;
  8616. is( q{\Seen}, flags_for_host2( $mysync, '\Recent \Seen' ), 'flags_for_host2: \Recent \Seen => \Seen' ) ;
  8617. is( q{\Deleted \Seen}, flags_for_host2( $mysync, '\Deleted \Recent \Seen' ), 'flags_for_host2: \Deleted \Recent \Seen => \Deleted \Seen' ) ;
  8618. $mysync->{ flagscase } = 0 ;
  8619. is( q{\DELETED \Seen}, flags_for_host2( $mysync, '\DELETED \Seen' ), 'flags_for_host2: flagscase = 0 \DELETED \Seen => \DELETED \Seen' ) ;
  8620. $mysync->{ flagscase } = 1 ;
  8621. is( q{\Deleted \Seen}, flags_for_host2( $mysync, '\DELETED \Seen' ), 'flags_for_host2: flagscase = 1 \DELETED \Seen => \Deleted \Seen' ) ;
  8622. $mysync->{ filterflags } = 0 ;
  8623. is( q{\Seen \Blabla}, flags_for_host2( $mysync, '\Seen \Blabla', '\Seen \Junk' ), 'flags_for_host2: filterflags = 0 \Seen \Blabla among \Seen \Junk => \Seen \Blabla' ) ;
  8624. $mysync->{ filterflags } = 1 ;
  8625. is( q{\Seen}, flags_for_host2( $mysync, '\Seen \Blabla', '\Seen \Junk' ), 'flags_for_host2: filterflags = 1 \Seen \Blabla among \Seen \Junk => \Seen' ) ;
  8626. $mysync->{ filterflags } = 1 ;
  8627. is( q{\Seen \Blabla}, flags_for_host2( $mysync, '\Seen \Blabla', '' ), 'flags_for_host2: filterflags = 1 \Seen \Blabla among "" => \Seen \Blabla' ) ;
  8628. note( 'Leaving tests_flags_for_host2()' ) ;
  8629. return ;
  8630. }
  8631. sub flags_for_host2
  8632. {
  8633. my $mysync = shift ;
  8634. my $h1_flags = shift ;
  8635. my $permanentflags2 = shift ;
  8636. if ( ! all_defined( $mysync, $h1_flags ) ) { return ; } ;
  8637. # RFC 2060: This flag can not be altered by any client
  8638. $h1_flags =~ s@\\Recent\s?@@xgi ;
  8639. my $h1_flags_re ;
  8640. if ( $mysync->{ regexflag } and defined( $h1_flags_re = regexflags( $mysync, $h1_flags ) ) ) {
  8641. $h1_flags = $h1_flags_re ;
  8642. }
  8643. if ( $mysync->{ flagscase } )
  8644. {
  8645. $h1_flags = flagscase( $h1_flags ) ;
  8646. }
  8647. if ( $permanentflags2 and $mysync->{ filterflags } )
  8648. {
  8649. $h1_flags = flags_filter( $h1_flags, $permanentflags2 ) ;
  8650. }
  8651. return( $h1_flags ) ;
  8652. }
  8653. sub ucsecond
  8654. {
  8655. my $string = shift ;
  8656. my $output ;
  8657. return( $string ) if ( 1 >= length $string ) ;
  8658. $output = ( substr( $string, 0, 1) ) . ( uc substr $string, 1, 1 ) . ( substr $string, 2 ) ;
  8659. #myprint( "UUU $string -> $output\n" ) ;
  8660. return( $output ) ;
  8661. }
  8662. sub tests_ucsecond
  8663. {
  8664. note( 'Entering tests_ucsecond()' ) ;
  8665. ok( 'aBcde' eq ucsecond( 'abcde' ), 'ucsecond: abcde -> aBcde' ) ;
  8666. ok( 'ABCDE' eq ucsecond( 'ABCDE' ), 'ucsecond: ABCDE -> ABCDE' ) ;
  8667. ok( 'ABCDE' eq ucsecond( 'AbCDE' ), 'ucsecond: AbCDE -> ABCDE' ) ;
  8668. ok( 'ABCde' eq ucsecond( 'AbCde' ), 'ucsecond: AbCde -> ABCde' ) ;
  8669. ok( 'A' eq ucsecond( 'A' ), 'ucsecond: A -> A' ) ;
  8670. ok( 'AB' eq ucsecond( 'Ab' ), 'ucsecond: Ab -> AB' ) ;
  8671. ok( '\B' eq ucsecond( '\b' ), 'ucsecond: \b -> \B' ) ;
  8672. ok( '\Bcde' eq ucsecond( '\bcde' ), 'ucsecond: \bcde -> \Bcde' ) ;
  8673. note( 'Leaving tests_ucsecond()' ) ;
  8674. return ;
  8675. }
  8676. sub select_msgs
  8677. {
  8678. my ( $imap, $msgs_all_hash_ref, $search_cmd, $abletosearch, $folder ) = @_ ;
  8679. my ( @msgs ) ;
  8680. if ( $abletosearch ) {
  8681. @msgs = select_msgs_by_search( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  8682. }else{
  8683. @msgs = select_msgs_by_fetch( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  8684. }
  8685. return( @msgs ) ;
  8686. }
  8687. sub select_msgs_by_search
  8688. {
  8689. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  8690. my ( @msgs, @msgs_all ) ;
  8691. # Need to have the whole list in msgs_all_hash_ref
  8692. # without calling messages() several times.
  8693. # Need all messages list to avoid deleting useful cache part
  8694. # in case of --search or --minage or --maxage
  8695. if ( ( defined $msgs_all_hash_ref and $usecache )
  8696. or ( not defined $maxage and not defined $minage and not defined $search_cmd )
  8697. ) {
  8698. $debugdev and myprint( "Calling messages()\n" ) ;
  8699. @msgs_all = $imap->messages( ) ;
  8700. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  8701. if ( defined $msgs_all_hash_ref ) {
  8702. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  8703. }
  8704. # return all messages
  8705. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  8706. return( @msgs_all ) ;
  8707. }
  8708. }
  8709. if ( defined $search_cmd ) {
  8710. @msgs = $imap->search( $search_cmd ) ;
  8711. return( @msgs ) ;
  8712. }
  8713. # we are here only if $maxage or $minage is defined
  8714. @msgs = select_msgs_by_age( $imap ) ;
  8715. return( @msgs );
  8716. }
  8717. sub select_msgs_by_fetch
  8718. {
  8719. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  8720. my ( @msgs, @msgs_all, %fetch ) ;
  8721. # Need to have the whole list in msgs_all_hash_ref
  8722. # without calling messages() several times.
  8723. # Need all messages list to avoid deleting useful cache part
  8724. # in case of --search or --minage or --maxage
  8725. $debugdev and myprint( "Calling fetch_hash()\n" ) ;
  8726. my $fetch_hash_uids = $fetch_hash_set || "1:*" ;
  8727. %fetch = %{$imap->fetch_hash( $fetch_hash_uids, 'INTERNALDATE' ) } ;
  8728. @msgs_all = sort { $a <=> $b } keys %fetch ;
  8729. $debugdev and myprint( "Done fetch_hash()\n" ) ;
  8730. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  8731. if ( defined $msgs_all_hash_ref ) {
  8732. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  8733. }
  8734. # return all messages
  8735. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  8736. return( @msgs_all ) ;
  8737. }
  8738. if ( defined $search_cmd ) {
  8739. myprint( "Warning: strange to see --search with --noabletosearch, an error can happen\n" ) ;
  8740. @msgs = $imap->search( $search_cmd ) ;
  8741. return( @msgs ) ;
  8742. }
  8743. # we are here only if $maxage or $minage is defined
  8744. my( @max, @min, $maxage_epoch, $minage_epoch ) ;
  8745. if ( defined $maxage ) { $maxage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ; }
  8746. if ( defined $minage ) { $minage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ; }
  8747. foreach my $msg ( @msgs_all ) {
  8748. my $idate = $fetch{ $msg }->{'INTERNALDATE'} ;
  8749. #myprint( "$idate\n" ) ;
  8750. if ( defined $maxage and ( epoch( $idate ) >= $maxage_epoch ) ) {
  8751. push @max, $msg ;
  8752. }
  8753. if ( defined $minage and ( epoch( $idate ) <= $minage_epoch ) ) {
  8754. push @min, $msg ;
  8755. }
  8756. }
  8757. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  8758. return( @msgs ) ;
  8759. }
  8760. sub select_msgs_by_age
  8761. {
  8762. my( $imap ) = @_ ;
  8763. my( @max, @min, @msgs, @inter, @union ) ;
  8764. if ( defined $maxage ) {
  8765. @max = $imap->sentsince( $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ) ;
  8766. }
  8767. if ( defined $minage ) {
  8768. @min = $imap->sentbefore( $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ) ;
  8769. }
  8770. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  8771. return( @msgs ) ;
  8772. }
  8773. sub msgs_from_maxmin
  8774. {
  8775. my( $max_ref, $min_ref ) = @_ ;
  8776. my( @max, @min, @msgs, @inter, @union ) ;
  8777. @max = @{ $max_ref } ;
  8778. @min = @{ $min_ref } ;
  8779. SWITCH: {
  8780. if ( not ( defined $minage or defined $maxage ) )
  8781. {
  8782. return ;
  8783. }
  8784. unless( defined $minage ) { @msgs = @max ; last SWITCH } ;
  8785. unless( defined $maxage ) { @msgs = @min ; last SWITCH } ;
  8786. my ( %union, %inter ) ;
  8787. foreach my $m ( @min, @max ) { $union{ $m }++ && $inter{ $m }++ }
  8788. @inter = sort { $a <=> $b } keys %inter ;
  8789. @union = sort { $a <=> $b } keys %union ;
  8790. # normal case
  8791. if ( $minage <= $maxage ) { @msgs = @inter ; last SWITCH } ;
  8792. # just exclude messages between
  8793. if ( $minage > $maxage ) { @msgs = @union ; last SWITCH } ;
  8794. }
  8795. return( @msgs ) ;
  8796. }
  8797. sub tests_msgs_from_maxmin
  8798. {
  8799. note( 'Entering tests_msgs_from_maxmin()' ) ;
  8800. my @msgs ;
  8801. # no maxage nor minage
  8802. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8803. is_deeply( [ ], \@msgs , 'msgs_from_maxmin: no maxage nor minage => empty result' ) ;
  8804. # maxage alone
  8805. $maxage = $NUMBER_200 ;
  8806. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8807. is_deeply( [ '1', '2' ], \@msgs , 'msgs_from_maxmin: maxage++' ) ;
  8808. # maxage > minage -> intersection
  8809. $minage = $NUMBER_100 ;
  8810. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8811. is_deeply( [ '2' ], \@msgs , 'msgs_from_maxmin: -maxage++minage-' ) ;
  8812. # maxage < minage -> union
  8813. $minage = $NUMBER_300 ;
  8814. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8815. is_deeply( [ '1', '2', '3' ], \@msgs, 'msgs_from_maxmin: ++maxage-minage++' ) ;
  8816. # minage alone
  8817. $maxage = undef ;
  8818. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  8819. is_deeply( [ '2', '3' ], \@msgs, 'msgs_from_maxmin: ++minage-' ) ;
  8820. note( 'Leaving tests_msgs_from_maxmin()' ) ;
  8821. return ;
  8822. }
  8823. sub tests_info_date_from_uid
  8824. {
  8825. note( 'Entering tests_info_date_from_uid()' ) ;
  8826. note( 'Leaving tests_info_date_from_uid()' ) ;
  8827. return ;
  8828. }
  8829. sub info_date_from_uid
  8830. {
  8831. #my $first_uid = $msgs_all[ 0 ] ;
  8832. #my $first_idate = $fetch{ $first_uid }->{'INTERNALDATE'} ;
  8833. #my $first_epoch = epoch( $first_idate ) ;
  8834. #my $first_days = ( $timestart_int - $first_epoch ) / $NB_SECONDS_IN_A_DAY ;
  8835. #myprint( "\nOldest msg has UID $first_uid INTERNALDATE $first_idate EPOCH $first_epoch DAYS AGO $first_days\n" ) ;
  8836. }
  8837. sub lastuid
  8838. {
  8839. my $imap = shift ;
  8840. my $folder = shift ;
  8841. my $lastuid_guess = shift ;
  8842. my $lastuid ;
  8843. # rfc3501: The only reliable way to identify recent messages is to
  8844. # look at message flags to see which have the \Recent flag
  8845. # set, or to do a SEARCH RECENT.
  8846. # SEARCH RECENT doesn't work this way on courrier.
  8847. my @recent_messages ;
  8848. # SEARCH RECENT for each transfer can be expensive with a big folder
  8849. # Call commented for now
  8850. #@recent_messages = $imap->recent( ) ;
  8851. #myprint( "Recent: @recent_messages\n" ) ;
  8852. my $max_recent ;
  8853. $max_recent = max( @recent_messages ) ;
  8854. if ( defined $max_recent and ($lastuid_guess <= $max_recent ) ) {
  8855. $lastuid = $max_recent ;
  8856. }else{
  8857. $lastuid = $lastuid_guess
  8858. }
  8859. return( $lastuid ) ;
  8860. }
  8861. sub size_filtered
  8862. {
  8863. my( $h1_size, $h1_msg, $h1_fold, $h2_fold ) = @_ ;
  8864. $h1_size = 0 if ( ! $h1_size ) ; # null if empty or undef
  8865. if ( defined $sync->{ maxsize } and $h1_size > $sync->{ maxsize } ) {
  8866. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size exceeds maxsize limit $sync->{ maxsize } bytes)\n" ) ;
  8867. $sync->{ total_bytes_skipped } += $h1_size;
  8868. $sync->{ nb_msg_skipped } += 1;
  8869. return( 1 ) ;
  8870. }
  8871. if ( defined $minsize and $h1_size <= $minsize ) {
  8872. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size smaller than minsize $minsize bytes)\n" ) ;
  8873. $sync->{ total_bytes_skipped } += $h1_size;
  8874. $sync->{ nb_msg_skipped } += 1;
  8875. return( 1 ) ;
  8876. }
  8877. return( 0 ) ;
  8878. }
  8879. sub message_exists
  8880. {
  8881. my( $imap, $msg ) = @_ ;
  8882. return( 1 ) if not $imap->Uid( ) ;
  8883. my $search_uid ;
  8884. ( $search_uid ) = $imap->search( "UID $msg" ) ;
  8885. #myprint( "$search ? $msg\n" ) ;
  8886. return( 1 ) if ( $search_uid eq $msg ) ;
  8887. return( 0 ) ;
  8888. }
  8889. # Globals
  8890. # $sync->{ total_bytes_skipped }
  8891. # $sync->{ nb_msg_skipped }
  8892. # $mysync->{ h1_nb_msg_processed }
  8893. sub stats_update_skip_message
  8894. {
  8895. my $mysync = shift ; # to be used
  8896. my $h1_size = shift ;
  8897. $mysync->{ total_bytes_skipped } += $h1_size ;
  8898. $mysync->{ nb_msg_skipped } += 1 ;
  8899. $mysync->{ h1_nb_msg_processed } +=1 ;
  8900. return ;
  8901. }
  8902. sub copy_message
  8903. {
  8904. # copy
  8905. my ( $mysync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) = @_ ;
  8906. ( $mysync->{ debug } or $mysync->{dry} )
  8907. and myprint( "msg $h1_fold/$h1_msg copying to $h2_fold $mysync->{dry_message} " . eta( $mysync ) . "\n" ) ;
  8908. if ( $mysync->{dry1} )
  8909. {
  8910. $mysync->{ h1_nb_msg_processed } +=1 ;
  8911. $nb_msg_skipped_dry_mode += 1 ;
  8912. return ;
  8913. }
  8914. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} || 0 ;
  8915. my $h1_flags = $h1_fir_ref->{$h1_msg}->{'FLAGS'} || q{} ;
  8916. my $h1_idate = $h1_fir_ref->{$h1_msg}->{'INTERNALDATE'} || q{} ;
  8917. if ( size_filtered( $h1_size, $h1_msg, $h1_fold, $h2_fold ) ) {
  8918. $mysync->{ h1_nb_msg_processed } +=1 ;
  8919. return ;
  8920. }
  8921. debugsleep( $mysync ) ;
  8922. myprint( "- msg $h1_fold/$h1_msg S[$h1_size] F[$h1_flags] I[$h1_idate] has RFC822.SIZE null!\n" ) if ( ! $h1_size ) ;
  8923. if ( $checkmessageexists and not message_exists( $mysync->{imap1}, $h1_msg ) ) {
  8924. stats_update_skip_message( $mysync, $h1_size ) ;
  8925. return ;
  8926. }
  8927. myprint( debugmemory( $mysync, " at C1" ) ) ;
  8928. my ( $string, $string_len ) ;
  8929. ( $string_len ) = message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, \$string ) ;
  8930. myprint( debugmemory( $mysync, " at C2" ) ) ;
  8931. # not defined or empty $string
  8932. if ( ( not $string ) or ( not $string_len ) ) {
  8933. myprint( "- msg $h1_fold/$h1_msg skipped.\n" ) ;
  8934. stats_update_skip_message( $mysync, $h1_size ) ;
  8935. return ;
  8936. }
  8937. # Lines too long (or not enough) => do no copy or fix
  8938. if ( ( defined $maxlinelength ) or ( defined $minmaxlinelength ) ) {
  8939. $string = linelengthstuff( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) ;
  8940. if ( not defined $string ) {
  8941. stats_update_skip_message( $mysync, $h1_size ) ;
  8942. return ;
  8943. }
  8944. }
  8945. my $h1_date = date_for_host2( $h1_msg, $h1_idate ) ;
  8946. ( $mysync->{ debug } or $debugflags ) and
  8947. myprint( "Host1: flags init msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  8948. $h1_flags = flags_for_host2( $mysync, $h1_flags, $permanentflags2 ) ;
  8949. ( $mysync->{ debug } or $debugflags ) and
  8950. myprint( "Host1: flags filt msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  8951. $h1_date = undef if ( $h1_date eq q{} ) ;
  8952. 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 ) ;
  8953. if ( $new_id and $syncflagsaftercopy ) {
  8954. sync_flags_after_copy( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $new_id, $permanentflags2 ) ;
  8955. }
  8956. myprint( debugmemory( $mysync, " at C3" ) ) ;
  8957. return $new_id ;
  8958. }
  8959. sub linelengthstuff
  8960. {
  8961. my( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) = @_ ;
  8962. my $maxlinelength_string = max_line_length( $string ) ;
  8963. $debugmaxlinelength and myprint( "msg $h1_fold/$h1_msg maxlinelength: $maxlinelength_string\n" ) ;
  8964. if ( ( defined $minmaxlinelength ) and ( $maxlinelength_string <= $minmaxlinelength ) ) {
  8965. my $subject = subject( $string ) ;
  8966. $debugdev and myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  8967. . "(Subject:[$subject]) (max line length under minmaxlinelength $minmaxlinelength bytes)\n" ) ;
  8968. return ;
  8969. }
  8970. if ( ( defined $maxlinelength ) and ( $maxlinelength_string > $maxlinelength ) ) {
  8971. my $subject = subject( $string ) ;
  8972. if ( $maxlinelengthcmd ) {
  8973. $string = pipemess( $string, $maxlinelengthcmd ) ;
  8974. # string undef means something was bad.
  8975. if ( not ( defined $string ) ) {
  8976. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] "
  8977. . "(Subject:[$subject]) could not be successfully transformed by --maxlinelengthcmd option\n" ) ;
  8978. return ;
  8979. }else{
  8980. return $string ;
  8981. }
  8982. }
  8983. myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  8984. . "(Subject:[$subject]) (line length exceeds maxlinelength $maxlinelength bytes)\n" ) ;
  8985. return ;
  8986. }
  8987. return $string ;
  8988. }
  8989. sub message_for_host2
  8990. {
  8991. # global variable list:
  8992. # @skipmess
  8993. # @regexmess
  8994. # @pipemess
  8995. # $debugcontent
  8996. # $debug
  8997. #
  8998. # API current
  8999. #
  9000. # at failure:
  9001. # * return nothing ( will then be undef or () )
  9002. # * $string_ref content is undef or empty
  9003. # at success:
  9004. # * return string length ($string_ref content length)
  9005. # * $string_ref content filled with message
  9006. # API future
  9007. #
  9008. #
  9009. my ( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) = @_ ;
  9010. # abort when missing a parameter
  9011. if ( ( ! $mysync ) or ( ! $h1_msg ) or ( ! $h1_fold ) or ( ! defined $h1_size )
  9012. or ( ! defined $h1_flags) or ( ! defined $h1_idate )
  9013. or ( ! $h1_fir_ref) or ( ! $string_ref ) )
  9014. {
  9015. return ;
  9016. }
  9017. myprint( debugmemory( $mysync, " at M1" ) ) ;
  9018. my $string_ok = $mysync->{imap1}->message_to_file( $string_ref, $h1_msg ) ;
  9019. myprint( debugmemory( $mysync, " at M2" ) ) ;
  9020. my $string_len = length_ref( $string_ref ) ;
  9021. unless ( defined $string_ok and $string_len ) {
  9022. # undef or 0 length
  9023. my $error = join q{},
  9024. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] could not be fetched: ",
  9025. $mysync->{imap1}->LastError || q{}, "\n" ;
  9026. errors_incr( $mysync, $error ) ;
  9027. $mysync->{ h1_nb_msg_processed } +=1 ;
  9028. return ;
  9029. }
  9030. if ( @skipmess ) {
  9031. my $match = skipmess( ${ $string_ref } ) ;
  9032. # string undef means the eval regex was bad.
  9033. if ( not ( defined $match ) ) {
  9034. myprint(
  9035. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  9036. . " could not be skipped by --skipmess option, bad regex\n" ) ;
  9037. return ;
  9038. }
  9039. if ( $match ) {
  9040. my $subject = subject( ${ $string_ref } ) ;
  9041. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  9042. . " (Subject:[$subject]) skipped by --skipmess\n" ) ;
  9043. return ;
  9044. }
  9045. }
  9046. if ( @regexmess ) {
  9047. ${ $string_ref } = regexmess( ${ $string_ref } ) ;
  9048. # string undef means the eval regex was bad.
  9049. if ( not ( defined ${ $string_ref } ) ) {
  9050. myprint(
  9051. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  9052. . " could not be transformed by --regexmess\n" ) ;
  9053. return ;
  9054. }
  9055. }
  9056. if ( @pipemess ) {
  9057. ${ $string_ref } = pipemess( ${ $string_ref }, @pipemess ) ;
  9058. # string undef means something was bad.
  9059. if ( not ( defined ${ $string_ref } ) ) {
  9060. myprint(
  9061. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  9062. . " could not be successfully transformed by --pipemess option\n" ) ;
  9063. return ;
  9064. }
  9065. }
  9066. if ( $mysync->{addheader} and defined $h1_fir_ref->{$h1_msg}->{'NO_HEADER'} ) {
  9067. my $header = add_header( $h1_msg ) ;
  9068. $mysync->{ debug } and myprint( "msg $h1_fold/$h1_msg adding custom header [$header]\n" ) ;
  9069. ${ $string_ref } = $header . "\r\n" . ${ $string_ref } ;
  9070. }
  9071. if ( ( defined $mysync->{ truncmess } ) and is_integer( $mysync->{ truncmess } ) )
  9072. {
  9073. ${ $string_ref } = truncmess( ${ $string_ref }, $mysync->{ truncmess } ) ;
  9074. }
  9075. $string_len = length_ref( $string_ref ) ;
  9076. $mysync->{ debugcontent } and myprint( debugcontent( $mysync, $string_ref ) ) ;
  9077. myprint( debugmemory( $mysync, " at M3" ) ) ;
  9078. return $string_len ;
  9079. }
  9080. sub tests_debugcontent
  9081. {
  9082. note( 'Entering tests_debugcontent()' ) ;
  9083. is( undef, debugcontent( ), 'debugcontent: no args => undef' ) ;
  9084. my $mysync = { } ;
  9085. is( undef, debugcontent( $mysync ), 'debugcontent: undef => undef' ) ;
  9086. is( undef, debugcontent( $mysync, 'mm' ), 'debugcontent: undef, mm => undef' ) ;
  9087. #my $string_ref = \'zztop' ;
  9088. my $string = '================================================================================
  9089. F message content begin next line (2 characters long)
  9090. mm
  9091. F message content ended on previous line
  9092. ================================================================================
  9093. ' ;
  9094. is( $string, debugcontent( $mysync, \'mm' ), 'debugcontent: undef, mm => mm' ) ;
  9095. note( 'Leaving tests_debugcontent()' ) ;
  9096. return ;
  9097. }
  9098. sub debugcontent
  9099. {
  9100. my $mysync = shift @ARG ;
  9101. if ( ! defined $mysync ) { return ; }
  9102. my $string_ref = shift @ARG ;
  9103. if ( ! defined $string_ref ) { return ; }
  9104. if ( 'SCALAR' ne ref( $string_ref ) ) { return ; }
  9105. my $string_len = length_ref( $string_ref ) ;
  9106. my $string = join( '',
  9107. q{=} x $STD_CHAR_PER_LINE, "\n",
  9108. "F message content begin next line ($string_len characters long)\n",
  9109. ${ $string_ref },
  9110. "\nF message content ended on previous line\n", q{=} x $STD_CHAR_PER_LINE, "\n",
  9111. ) ;
  9112. return $string ;
  9113. }
  9114. sub tests_truncmess
  9115. {
  9116. note( 'Entering tests_truncmess()' ) ;
  9117. is( undef, truncmess( ), 'truncmess: no args => undef' ) ;
  9118. is( 'abc', truncmess( 'abc' ), 'truncmess: abc => abc' ) ;
  9119. is( 'ab', truncmess( 'abc', 2 ), 'truncmess: abc 2 => ab' ) ;
  9120. is( 'abc', truncmess( 'abc', 3 ), 'truncmess: abc 3 => abc' ) ;
  9121. is( 'abc', truncmess( 'abc', 4 ), 'truncmess: abc 4 => abc' ) ;
  9122. is( '12345', truncmess( "123456789\n", 5 ), 'truncmess: "123456789\n", 5 => 12345' ) ;
  9123. is( "123456789\n" x 5000, truncmess( "123456789\n" x 100000, 50000 ), 'truncmess: "123456789\n" x 100000, 50000 => "123456789\n" x 5000' ) ;
  9124. note( 'Leaving tests_truncmess()' ) ;
  9125. return ;
  9126. }
  9127. sub truncmess
  9128. {
  9129. my $string = shift ;
  9130. my $length = shift ;
  9131. if ( not defined $string ) { return ; }
  9132. if ( not defined $length ) { return $string ; }
  9133. $string = substr $string, 0, $length ;
  9134. return $string ;
  9135. }
  9136. sub tests_message_for_host2
  9137. {
  9138. note( 'Entering tests_message_for_host2()' ) ;
  9139. my ( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) ;
  9140. is( undef, message_for_host2( ), q{message_for_host2: no args} ) ;
  9141. 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} ) ;
  9142. require_ok( "Test::MockObject" ) ;
  9143. my $imapT = Test::MockObject->new( ) ;
  9144. $mysync->{imap1} = $imapT ;
  9145. my $string ;
  9146. $h1_msg = 1 ;
  9147. $h1_fold = 'FoldFoo';
  9148. $h1_size = 9 ;
  9149. $h1_flags = q{} ;
  9150. $h1_idate = '10-Jul-2015 09:00:00 +0200' ;
  9151. $h1_fir_ref = {} ;
  9152. $string_ref = \$string ;
  9153. $imapT->mock( 'message_to_file',
  9154. sub {
  9155. my ( $imap, $mystring_ref, $msg ) = @_ ;
  9156. ${$mystring_ref} = 'blablabla' ;
  9157. return length ${$mystring_ref} ;
  9158. }
  9159. ) ;
  9160. is( 9, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  9161. q{message_for_host2: msg 1 == "blablabla", length} ) ;
  9162. is( 'blablabla', $string, q{message_for_host2: msg 1 == "blablabla", value} ) ;
  9163. # so far so good
  9164. # now the --pipemess stuff
  9165. SKIP: {
  9166. Readonly my $NB_WIN_tests_message_for_host2 => 0 ;
  9167. skip( 'Not on MSWin32', $NB_WIN_tests_message_for_host2 ) if ('MSWin32' ne $OSNAME) ;
  9168. # Windows
  9169. # "type" command does not accept redirection of STDIN with <
  9170. # "sort" does
  9171. } ;
  9172. SKIP: {
  9173. Readonly my $NB_UNX_tests_message_for_host2 => 6 ;
  9174. skip( 'Not on Unix', $NB_UNX_tests_message_for_host2 ) if ('MSWin32' eq $OSNAME) ;
  9175. # Unix
  9176. # no change by cat
  9177. @pipemess = ( 'cat' ) ;
  9178. is( 9, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  9179. q{message_for_host2: --pipemess 'cat', length} ) ;
  9180. is( 'blablabla', $string, q{message_for_host2: --pipemess 'cat', value} ) ;
  9181. # failure by false
  9182. @pipemess = ( 'false' ) ;
  9183. is( undef, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  9184. q{message_for_host2: --pipemess 'false', length} ) ;
  9185. is( undef, $string, q{message_for_host2: --pipemess 'false', value} ) ;
  9186. # failure by true since no output
  9187. @pipemess = ( 'true' ) ;
  9188. is( undef, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  9189. q{message_for_host2: --pipemess 'true', length} ) ;
  9190. is( undef, $string, q{message_for_host2: --pipemess 'true', value} ) ;
  9191. }
  9192. note( 'Leaving tests_message_for_host2()' ) ;
  9193. return ;
  9194. }
  9195. sub tests_labels_remove_subfolder1
  9196. {
  9197. note( 'Entering tests_labels_remove_subfolder1()' ) ;
  9198. is( undef, labels_remove_subfolder1( ), 'labels_remove_subfolder1: no parameters => undef' ) ;
  9199. is( 'Blabla', labels_remove_subfolder1( 'Blabla' ), 'labels_remove_subfolder1: one parameter Blabla => Blabla' ) ;
  9200. is( 'Blan blue', labels_remove_subfolder1( 'Blan blue' ), 'labels_remove_subfolder1: one parameter Blan blue => Blan blue' ) ;
  9201. is( '\Bla "Blan blan" Blabla', labels_remove_subfolder1( '\Bla "Blan blan" Blabla' ),
  9202. 'labels_remove_subfolder1: one parameter \Bla "Blan blan" Blabla => \Bla "Blan blan" Blabla' ) ;
  9203. is( 'Bla', labels_remove_subfolder1( 'Subf/Bla', 'Subf' ), 'labels_remove_subfolder1: Subf/Bla Subf => "Bla"' ) ;
  9204. is( '"\\\\Bla"', labels_remove_subfolder1( '"\\\\Bla"', 'Subf' ), 'labels_remove_subfolder1: "\\\\Bla" Subf => "\\\\Bla"' ) ;
  9205. is( 'Bla Kii', labels_remove_subfolder1( 'Subf/Bla Subf/Kii', 'Subf' ),
  9206. 'labels_remove_subfolder1: Subf/Bla Subf/Kii, Subf => "Bla" "Kii"' ) ;
  9207. is( '"\\\\Bla" Kii', labels_remove_subfolder1( '"\\\\Bla" Subf/Kii', 'Subf' ),
  9208. 'labels_remove_subfolder1: "\\\\Bla" Subf/Kii Subf => "\\\\Bla" Kii' ) ;
  9209. is( '"Blan blan"', labels_remove_subfolder1( '"Subf/Blan blan"', 'Subf' ),
  9210. 'labels_remove_subfolder1: "Subf/Blan blan" Subf => "Blan blan"' ) ;
  9211. is( '"\\\\Loo" "Blan blan" Kii', labels_remove_subfolder1( '"\\\\Loo" "Subf/Blan blan" Subf/Kii', 'Subf' ),
  9212. 'labels_remove_subfolder1: "\\\\Loo" "Subf/Blan blan" Subf/Kii + Subf => "\\\\Loo" "Blan blan" Kii' ) ;
  9213. is( '"\\\\Inbox"', labels_remove_subfolder1( 'Subf/INBOX', 'Subf' ),
  9214. 'labels_remove_subfolder1: Subf/INBOX + Subf => "\\\\Inbox"' ) ;
  9215. is( '"\\\\Loo" "Blan blan" Kii "\\\\Inbox"', labels_remove_subfolder1( '"\\\\Loo" "Subf/Blan blan" Subf/Kii Subf/INBOX', 'Subf' ),
  9216. 'labels_remove_subfolder1: "\\\\Loo" "Subf/Blan blan" Subf/Kii Subf/INBOX + Subf => "\\\\Loo" "Blan blan" Kii "\\\\Inbox"' ) ;
  9217. note( 'Leaving tests_labels_remove_subfolder1()' ) ;
  9218. return ;
  9219. }
  9220. sub labels_remove_subfolder1
  9221. {
  9222. my $labels = shift ;
  9223. my $subfolder1 = shift ;
  9224. if ( not defined $labels ) { return ; }
  9225. if ( not defined $subfolder1 ) { return $labels ; }
  9226. my @labels = quotewords('\s+', 1, $labels ) ;
  9227. #myprint( "@labels\n" ) ;
  9228. my @labels_subfolder2 ;
  9229. foreach my $label ( @labels )
  9230. {
  9231. if ( $label =~ m{zzzzzzzzzz} )
  9232. {
  9233. # \Seen \Deleted ... stay the same
  9234. push @labels_subfolder2, $label ;
  9235. }
  9236. else
  9237. {
  9238. # Remove surrounding quotes if any, to add them again in case of space
  9239. $label = join( q{}, quotewords('\s+', 0, $label ) ) ;
  9240. $label =~ s{$subfolder1/?}{} ;
  9241. if ( 'INBOX' eq $label )
  9242. {
  9243. push @labels_subfolder2, q{"\\\\Inbox"} ;
  9244. }
  9245. elsif ( $label =~ m{\\} )
  9246. {
  9247. push @labels_subfolder2, qq{"\\$label"} ;
  9248. }
  9249. elsif ( $label =~ m{ } )
  9250. {
  9251. push @labels_subfolder2, qq{"$label"} ;
  9252. }
  9253. else
  9254. {
  9255. push @labels_subfolder2, $label ;
  9256. }
  9257. }
  9258. }
  9259. my $labels_subfolder2 = join( ' ', sort uniq( @labels_subfolder2 ) ) ;
  9260. return $labels_subfolder2 ;
  9261. }
  9262. sub tests_labels_remove_special
  9263. {
  9264. note( 'Entering tests_labels_remove_special()' ) ;
  9265. is( undef, labels_remove_special( ), 'labels_remove_special: no parameters => undef' ) ;
  9266. is( q{}, labels_remove_special( q{} ), 'labels_remove_special: empty string => empty string' ) ;
  9267. is( q{}, labels_remove_special( '"\\\\Inbox"' ), 'labels_remove_special:"\\\\Inbox" => empty string' ) ;
  9268. is( q{}, labels_remove_special( '"\\\\Inbox" "\\\\Starred"' ), 'labels_remove_special:"\\\\Inbox" "\\\\Starred" => empty string' ) ;
  9269. is( 'Bar Foo', labels_remove_special( 'Foo Bar' ), 'labels_remove_special:Foo Bar => Bar Foo' ) ;
  9270. is( 'Bar Foo', labels_remove_special( 'Foo Bar "\\\\Inbox"' ), 'labels_remove_special:Foo Bar "\\\\Inbox" => Bar Foo' ) ;
  9271. note( 'Leaving tests_labels_remove_special()' ) ;
  9272. return ;
  9273. }
  9274. sub labels_remove_special
  9275. {
  9276. my $labels = shift ;
  9277. if ( not defined $labels ) { return ; }
  9278. my @labels = quotewords('\s+', 1, $labels ) ;
  9279. myprint( "labels before remove_non_folded: @labels\n" ) ;
  9280. my @labels_remove_special ;
  9281. foreach my $label ( @labels )
  9282. {
  9283. if ( $label =~ m{^\"\\\\} )
  9284. {
  9285. # not kept
  9286. }
  9287. else
  9288. {
  9289. push @labels_remove_special, $label ;
  9290. }
  9291. }
  9292. my $labels_remove_special = join( ' ', sort @labels_remove_special ) ;
  9293. return $labels_remove_special ;
  9294. }
  9295. sub tests_labels_add_subfolder2
  9296. {
  9297. note( 'Entering tests_labels_add_subfolder2()' ) ;
  9298. is( undef, labels_add_subfolder2( ), 'labels_add_subfolder2: no parameters => undef' ) ;
  9299. is( 'Blabla', labels_add_subfolder2( 'Blabla' ), 'labels_add_subfolder2: one parameter Blabla => Blabla' ) ;
  9300. is( 'Blan blue', labels_add_subfolder2( 'Blan blue' ), 'labels_add_subfolder2: one parameter Blan blue => Blan blue' ) ;
  9301. is( '\Bla "Blan blan" Blabla', labels_add_subfolder2( '\Bla "Blan blan" Blabla' ),
  9302. 'labels_add_subfolder2: one parameter \Bla "Blan blan" Blabla => \Bla "Blan blan" Blabla' ) ;
  9303. is( 'Subf/Bla', labels_add_subfolder2( 'Bla', 'Subf' ), 'labels_add_subfolder2: Bla Subf => "Subf/Bla"' ) ;
  9304. is( 'Subf/\Bla', labels_add_subfolder2( '\\\\Bla', 'Subf' ), 'labels_add_subfolder2: \Bla Subf => \Bla' ) ;
  9305. is( 'Subf/Bla Subf/Kii', labels_add_subfolder2( 'Bla Kii', 'Subf' ),
  9306. 'labels_add_subfolder2: Bla Kii Subf => "Subf/Bla" "Subf/Kii"' ) ;
  9307. is( 'Subf/Kii Subf/\Bla', labels_add_subfolder2( '\\\\Bla Kii', 'Subf' ),
  9308. 'labels_add_subfolder2: \Bla Kii Subf => \Bla Subf/Kii' ) ;
  9309. is( '"Subf/Blan blan"', labels_add_subfolder2( '"Blan blan"', 'Subf' ),
  9310. 'labels_add_subfolder2: "Blan blan" Subf => "Subf/Blan blan"' ) ;
  9311. is( '"Subf/Blan blan" Subf/Kii Subf/\Loo', labels_add_subfolder2( '\\\\Loo "Blan blan" Kii', 'Subf' ),
  9312. 'labels_add_subfolder2: \Loo "Blan blan" Kii + Subf => "Subf/Blan blan" Subf/Kii Subf/\Loo' ) ;
  9313. # "\\Inbox" is special, add to subfolder INBOX also because Gmail will but ...
  9314. is( '"Subf/\\\\Inbox" Subf/INBOX', labels_add_subfolder2( '"\\\\Inbox"', 'Subf' ),
  9315. 'labels_add_subfolder2: "\\\\Inbox" Subf => "Subf/\\\\Inbox" Subf/INBOX' ) ;
  9316. # but not with INBOX folder
  9317. is( '"Subf/\\\\Inbox"', labels_add_subfolder2( '"\\\\Inbox"', 'Subf', 'INBOX' ),
  9318. 'labels_add_subfolder2: "\\\\Inbox" Subf INBOX => "Subf/\\\\Inbox"' ) ;
  9319. # two times => one time
  9320. is( '"Subf/\\\\Inbox" Subf/INBOX', labels_add_subfolder2( '"\\\\Inbox" "\\\\Inbox"', 'Subf' ),
  9321. 'labels_add_subfolder2: "\\\\Inbox" "\\\\Inbox" Subf => "Subf/\\\\Inbox"' ) ;
  9322. is( '"Subf/\\\\Starred"', labels_add_subfolder2( '"\\\\Starred"', 'Subf' ),
  9323. 'labels_add_subfolder2: "\\\\Starred" Subf => "Subf/\\\\Starred"' ) ;
  9324. note( 'Leaving tests_labels_add_subfolder2()' ) ;
  9325. return ;
  9326. }
  9327. sub labels_add_subfolder2
  9328. {
  9329. my $labels = shift ;
  9330. my $subfolder2 = shift ;
  9331. my $h1_folder = shift || q{} ;
  9332. if ( not defined $labels ) { return ; }
  9333. if ( not defined $subfolder2 ) { return $labels ; }
  9334. # Isn't it messy?
  9335. if ( 'INBOX' eq $h1_folder )
  9336. {
  9337. $labels .= ' "\\\\Inbox"' ;
  9338. }
  9339. my @labels = uniq( quotewords('\s+', 1, $labels ) ) ;
  9340. myprint( "labels before subfolder2: @labels\n" ) ;
  9341. my @labels_subfolder2 ;
  9342. foreach my $label ( @labels )
  9343. {
  9344. # Isn't it more messy?
  9345. if ( ( q{"\\\\Inbox"} eq $label ) and ( 'INBOX' ne $h1_folder ) )
  9346. {
  9347. if ( $subfolder2 =~ m{ } )
  9348. {
  9349. push @labels_subfolder2, qq{"$subfolder2/INBOX"} ;
  9350. }
  9351. else
  9352. {
  9353. push @labels_subfolder2, "$subfolder2/INBOX" ;
  9354. }
  9355. }
  9356. if ( $label =~ m{^\"\\\\} )
  9357. {
  9358. # \Seen \Deleted ... stay the same
  9359. #push @labels_subfolder2, $label ;
  9360. # Remove surrounding quotes if any, to add them again
  9361. $label = join( q{}, quotewords('\s+', 0, $label ) ) ;
  9362. push @labels_subfolder2, qq{"$subfolder2/\\$label"} ;
  9363. }
  9364. else
  9365. {
  9366. # Remove surrounding quotes if any, to add them again in case of space
  9367. $label = join( q{}, quotewords('\s+', 0, $label ) ) ;
  9368. if ( $label =~ m{ } )
  9369. {
  9370. push @labels_subfolder2, qq{"$subfolder2/$label"} ;
  9371. }
  9372. else
  9373. {
  9374. push @labels_subfolder2, "$subfolder2/$label" ;
  9375. }
  9376. }
  9377. }
  9378. my $labels_subfolder2 = join( ' ', sort @labels_subfolder2 ) ;
  9379. return $labels_subfolder2 ;
  9380. }
  9381. sub tests_labels
  9382. {
  9383. note( 'Entering tests_labels()' ) ;
  9384. is( undef, labels( ), 'labels: no parameters => undef' ) ;
  9385. is( undef, labels( undef ), 'labels: undef => undef' ) ;
  9386. require_ok( "Test::MockObject" ) ;
  9387. my $myimap = Test::MockObject->new( ) ;
  9388. $myimap->mock( 'fetch_hash',
  9389. sub {
  9390. return(
  9391. { '1' => {
  9392. 'X-GM-LABELS' => '\Seen Blabla'
  9393. }
  9394. }
  9395. ) ;
  9396. }
  9397. ) ;
  9398. $myimap->mock( 'Debug' , sub { } ) ;
  9399. $myimap->mock( 'Unescape', sub { return Mail::IMAPClient::Unescape( @_ ) } ) ; # real one
  9400. is( undef, labels( $myimap ), 'labels: one parameter => undef' ) ;
  9401. is( '\Seen Blabla', labels( $myimap, '1' ), 'labels: $mysync UID_1 => \Seen Blabla' ) ;
  9402. note( 'Leaving tests_labels()' ) ;
  9403. return ;
  9404. }
  9405. sub labels
  9406. {
  9407. my ( $myimap, $uid ) = @ARG ;
  9408. if ( not all_defined( $myimap, $uid ) ) {
  9409. return ;
  9410. }
  9411. my $hash = $myimap->fetch_hash( [ $uid ], 'X-GM-LABELS' ) ;
  9412. my $labels = $hash->{ $uid }->{ 'X-GM-LABELS' } ;
  9413. #$labels = $myimap->Unescape( $labels ) ;
  9414. return $labels ;
  9415. }
  9416. sub tests_synclabels
  9417. {
  9418. note( 'Entering tests_synclabels()' ) ;
  9419. is( undef, synclabels( ), 'synclabels: no parameters => undef' ) ;
  9420. is( undef, synclabels( undef ), 'synclabels: undef => undef' ) ;
  9421. my $mysync ;
  9422. is( undef, synclabels( $mysync ), 'synclabels: var undef => undef' ) ;
  9423. require_ok( "Test::MockObject" ) ;
  9424. $mysync = {} ;
  9425. my $myimap1 = Test::MockObject->new( ) ;
  9426. $myimap1->mock( 'fetch_hash',
  9427. sub {
  9428. return(
  9429. { '1' => {
  9430. 'X-GM-LABELS' => '\Seen Blabla'
  9431. }
  9432. }
  9433. ) ;
  9434. }
  9435. ) ;
  9436. $myimap1->mock( 'Debug', sub { } ) ;
  9437. $myimap1->mock( 'Unescape', sub { return Mail::IMAPClient::Unescape( @_ ) } ) ; # real one
  9438. my $myimap2 = Test::MockObject->new( ) ;
  9439. $myimap2->mock( 'store',
  9440. sub {
  9441. return 1 ;
  9442. }
  9443. ) ;
  9444. $mysync->{imap1} = $myimap1 ;
  9445. $mysync->{imap2} = $myimap2 ;
  9446. is( undef, synclabels( $mysync ), 'synclabels: fresh $mysync => undef' ) ;
  9447. is( undef, synclabels( $mysync, '1' ), 'synclabels: $mysync UID_1 alone => undef' ) ;
  9448. is( 1, synclabels( $mysync, '1', '2' ), 'synclabels: $mysync UID_1 UID_2 => 1' ) ;
  9449. note( 'Leaving tests_synclabels()' ) ;
  9450. return ;
  9451. }
  9452. sub synclabels
  9453. {
  9454. my( $mysync, $uid1, $uid2 ) = @ARG ;
  9455. if ( not all_defined( $mysync, $uid1, $uid2 ) ) {
  9456. return ;
  9457. }
  9458. my $myimap1 = $mysync->{ 'imap1' } || return ;
  9459. my $myimap2 = $mysync->{ 'imap2' } || return ;
  9460. $mysync->{debuglabels} and $myimap1->Debug( 1 ) ;
  9461. my $labels1 = labels( $myimap1, $uid1 ) ;
  9462. $mysync->{debuglabels} and $myimap1->Debug( 0 ) ;
  9463. $mysync->{debuglabels} and myprint( "Host1 labels: $labels1\n" ) ;
  9464. if ( $mysync->{ subfolder1 } and $labels1 )
  9465. {
  9466. $labels1 = labels_remove_subfolder1( $labels1, $mysync->{ subfolder1 } ) ;
  9467. $mysync->{debuglabels} and myprint( "Host1 labels with subfolder1: $labels1\n" ) ;
  9468. }
  9469. if ( $mysync->{ subfolder2 } and $labels1 )
  9470. {
  9471. $labels1 = labels_add_subfolder2( $labels1, $mysync->{ subfolder2 } ) ;
  9472. $mysync->{debuglabels} and myprint( "Host1 labels with subfolder2: $labels1\n" ) ;
  9473. }
  9474. my $store ;
  9475. if ( $labels1 and not $mysync->{ dry } )
  9476. {
  9477. $mysync->{ debuglabels } and $myimap2->Debug( 1 ) ;
  9478. $store = $myimap2->store( $uid2, "X-GM-LABELS ($labels1)" ) ;
  9479. $mysync->{ debuglabels } and $myimap2->Debug( 0 ) ;
  9480. }
  9481. return $store ;
  9482. }
  9483. sub tests_resynclabels
  9484. {
  9485. note( 'Entering tests_resynclabels()' ) ;
  9486. is( undef, resynclabels( ), 'resynclabels: no parameters => undef' ) ;
  9487. is( undef, resynclabels( undef ), 'resynclabels: undef => undef' ) ;
  9488. my $mysync ;
  9489. is( undef, resynclabels( $mysync ), 'resynclabels: var undef => undef' ) ;
  9490. my ( $h1_fir_ref, $h2_fir_ref ) ;
  9491. $mysync->{ debuglabels } = 1 ;
  9492. $h1_fir_ref->{ 11 }->{ 'X-GM-LABELS' } = '\Seen Baa Kii' ;
  9493. $h2_fir_ref->{ 22 }->{ 'X-GM-LABELS' } = '\Seen Baa Kii' ;
  9494. # labels are equal
  9495. is( 1, resynclabels( $mysync, 11, 22, $h1_fir_ref, $h2_fir_ref ),
  9496. 'resynclabels: $mysync UID_1 UID_2 labels are equal => 1' ) ;
  9497. # labels are different
  9498. $h2_fir_ref->{ 22 }->{ 'X-GM-LABELS' } = '\Seen Zuu' ;
  9499. require_ok( "Test::MockObject" ) ;
  9500. my $myimap2 = Test::MockObject->new( ) ;
  9501. $myimap2->mock( 'store',
  9502. sub {
  9503. return 1 ;
  9504. }
  9505. ) ;
  9506. $myimap2->mock( 'Debug', sub { } ) ;
  9507. $mysync->{imap2} = $myimap2 ;
  9508. is( 1, resynclabels( $mysync, 11, 22, $h1_fir_ref, $h2_fir_ref ),
  9509. 'resynclabels: $mysync UID_1 UID_2 labels are not equal => store => 1' ) ;
  9510. note( 'Leaving tests_resynclabels()' ) ;
  9511. return ;
  9512. }
  9513. sub resynclabels
  9514. {
  9515. my( $mysync, $uid1, $uid2, $h1_fir_ref, $h2_fir_ref, $h1_folder ) = @ARG ;
  9516. if ( not all_defined( $mysync, $uid1, $uid2, $h1_fir_ref, $h2_fir_ref ) ) {
  9517. return ;
  9518. }
  9519. my $labels1 = $h1_fir_ref->{ $uid1 }->{ 'X-GM-LABELS' } || q{} ;
  9520. my $labels2 = $h2_fir_ref->{ $uid2 }->{ 'X-GM-LABELS' } || q{} ;
  9521. if ( $mysync->{ subfolder1 } and $labels1 )
  9522. {
  9523. $labels1 = labels_remove_subfolder1( $labels1, $mysync->{ subfolder1 } ) ;
  9524. }
  9525. if ( $mysync->{ subfolder2 } and $labels1 )
  9526. {
  9527. $labels1 = labels_add_subfolder2( $labels1, $mysync->{ subfolder2 }, $h1_folder ) ;
  9528. $labels2 = labels_remove_special( $labels2 ) ;
  9529. }
  9530. $mysync->{ debuglabels } and myprint( "Host1 labels fixed: $labels1\n" ) ;
  9531. $mysync->{ debuglabels } and myprint( "Host2 labels : $labels2\n" ) ;
  9532. my $store ;
  9533. if ( $labels1 eq $labels2 )
  9534. {
  9535. # no sync needed
  9536. $mysync->{ debuglabels } and myprint( "Labels are already equal\n" ) ;
  9537. return 1 ;
  9538. }
  9539. elsif ( not $mysync->{ dry } )
  9540. {
  9541. # sync needed
  9542. $mysync->{debuglabels} and $mysync->{imap2}->Debug( 1 ) ;
  9543. $store = $mysync->{imap2}->store( $uid2, "X-GM-LABELS ($labels1)" ) ;
  9544. $mysync->{debuglabels} and $mysync->{imap2}->Debug( 0 ) ;
  9545. }
  9546. return $store ;
  9547. }
  9548. sub tests_uniq
  9549. {
  9550. note( 'Entering tests_uniq()' ) ;
  9551. is( 0, uniq( ), 'uniq: undef => 0' ) ;
  9552. is_deeply( [ 'one' ], [ uniq( 'one' ) ], 'uniq: one => one' ) ;
  9553. is_deeply( [ 'one' ], [ uniq( 'one', 'one' ) ], 'uniq: one one => one' ) ;
  9554. is_deeply( [ 'one', 'two' ], [ uniq( 'one', 'one', 'two', 'one', 'two' ) ], 'uniq: one one two one two => one two' ) ;
  9555. note( 'Leaving tests_uniq()' ) ;
  9556. return ;
  9557. }
  9558. sub uniq
  9559. {
  9560. my @list = @ARG ;
  9561. my %seen = ( ) ;
  9562. my @uniq = ( ) ;
  9563. foreach my $item ( @list ) {
  9564. if ( ! $seen{ $item } ) {
  9565. $seen{ $item } = 1 ;
  9566. push( @uniq, $item ) ;
  9567. }
  9568. }
  9569. return @uniq ;
  9570. }
  9571. sub length_ref
  9572. {
  9573. my $string_ref = shift ;
  9574. my $string_len = defined ${ $string_ref } ? length( ${ $string_ref } ) : q{} ; # length or empty string
  9575. return $string_len ;
  9576. }
  9577. sub tests_length_ref
  9578. {
  9579. note( 'Entering tests_length_ref()' ) ;
  9580. my $notdefined ;
  9581. is( q{}, length_ref( \$notdefined ), q{length_ref: value not defined} ) ;
  9582. my $notref ;
  9583. is( q{}, length_ref( $notref ), q{length_ref: param not a ref} ) ;
  9584. my $lala = 'lala' ;
  9585. is( 4, length_ref( \$lala ), q{length_ref: lala length == 4} ) ;
  9586. is( 4, length_ref( \'lili' ), q{length_ref: lili length == 4} ) ;
  9587. note( 'Leaving tests_length_ref()' ) ;
  9588. return ;
  9589. }
  9590. sub date_for_host2
  9591. {
  9592. my( $h1_msg, $h1_idate ) = @_ ;
  9593. my $h1_date = q{} ;
  9594. if ( $syncinternaldates ) {
  9595. $h1_date = $h1_idate ;
  9596. $sync->{ debug } and myprint( "internal date from host1: [$h1_date]\n" ) ;
  9597. $h1_date = good_date( $h1_date ) ;
  9598. $sync->{ debug } and myprint( "internal date from host1: [$h1_date] (fixed)\n" ) ;
  9599. }
  9600. if ( $idatefromheader ) {
  9601. $h1_date = $sync->{imap1}->get_header( $h1_msg, 'Date' ) ;
  9602. $sync->{ debug } and myprint( "header date from host1: [$h1_date]\n" ) ;
  9603. $h1_date = good_date( $h1_date ) ;
  9604. $sync->{ debug } and myprint( "header date from host1: [$h1_date] (fixed)\n" ) ;
  9605. }
  9606. return( $h1_date ) ;
  9607. }
  9608. sub subject
  9609. {
  9610. my $string = shift ;
  9611. my $subject = q{} ;
  9612. my $header = extract_header( $string ) ;
  9613. if( $header =~ m/^Subject:[ \t]*([^\n\r]*)\r?$/msx ) {
  9614. #myprint( "MMM[$1]\n" ) ;
  9615. $subject = $1 ;
  9616. }
  9617. return( $subject ) ;
  9618. }
  9619. sub tests_subject
  9620. {
  9621. note( 'Entering tests_subject()' ) ;
  9622. ok( q{} eq subject( q{} ), 'subject: null') ;
  9623. is( '', subject( 'Subject:' ), 'Subject:') ;
  9624. is( '', subject( "Subject:\r\n" ), 'Subject:\r\n') ;
  9625. ok( 'toto le hero' eq subject( 'Subject: toto le hero' ), 'Subject: toto le hero') ;
  9626. ok( 'toto le hero' eq subject( 'Subject:toto le hero' ), 'Subject:toto le hero') ;
  9627. ok( 'toto le hero' eq subject( "Subject:toto le hero\r\n" ), 'Subject: toto le hero\r\n') ;
  9628. my $MESS ;
  9629. $MESS = <<'EOF';
  9630. From: lalala
  9631. Subject: toto le hero
  9632. Date: zzzzzz
  9633. Boogie boogie
  9634. EOF
  9635. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 2') ;
  9636. $MESS = <<'EOF';
  9637. Subject: toto le hero
  9638. From: lalala
  9639. Date: zzzzzz
  9640. Boogie boogie
  9641. EOF
  9642. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 3') ;
  9643. $MESS = <<'EOF';
  9644. From: lalala
  9645. Subject: cuicui
  9646. Date: zzzzzz
  9647. Subject: toto le hero
  9648. EOF
  9649. ok( 'cuicui' eq subject( $MESS ), 'subject: cuicui') ;
  9650. $MESS = <<'EOF';
  9651. From: lalala
  9652. Date: zzzzzz
  9653. Subject: toto le hero
  9654. EOF
  9655. ok( q{} eq subject( $MESS ), 'subject: null but body could') ;
  9656. $MESS = <<'EOF';
  9657. From: lalala
  9658. Subject:
  9659. Date: zzzzzz
  9660. Subject: toto le hero
  9661. EOF
  9662. is( '', subject( $MESS ), 'Subject:') ;
  9663. note( 'Leaving tests_subject()' ) ;
  9664. return ;
  9665. }
  9666. # GlobVar
  9667. # $h2_uidguess
  9668. # ...
  9669. #
  9670. #
  9671. sub append_message_on_host2
  9672. {
  9673. my( $mysync, $string_ref, $h1_fold, $h1_msg, $string_len, $h2_fold, $h1_size, $h1_flags, $h1_date, $cache_dir ) = @_ ;
  9674. myprint( debugmemory( $mysync, " at A1" ) ) ;
  9675. my $new_id ;
  9676. if ( ! $mysync->{dry} ) {
  9677. $new_id = $mysync->{imap2}->append_string( $h2_fold, ${ $string_ref }, $h1_flags, $h1_date ) ;
  9678. myprint( debugmemory( $mysync, " at A2" ) ) ;
  9679. if ( ! defined $new_id ){
  9680. my $subject = subject( ${ $string_ref } ) ;
  9681. my $error_imap = $mysync->{imap2}->LastError || q{} ;
  9682. 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" ;
  9683. errors_incr( $mysync, $error ) ;
  9684. $mysync->{ h1_nb_msg_processed } +=1 ;
  9685. return ;
  9686. }
  9687. else{
  9688. # good
  9689. # $new_id is an id if the IMAP server has the
  9690. # UIDPLUS capability else just a ref
  9691. if ( $new_id !~ m{^\d+$}x ) {
  9692. $new_id = lastuid( $mysync->{imap2}, $h2_fold, $h2_uidguess ) ;
  9693. }
  9694. if ( $mysync->{ synclabels } ) { synclabels( $mysync, $h1_msg, $new_id ) }
  9695. $h2_uidguess += 1 ;
  9696. $mysync->{ total_bytes_transferred } += $string_len ;
  9697. $mysync->{ nb_msg_transferred } += 1 ;
  9698. $mysync->{ h1_nb_msg_processed } +=1 ;
  9699. $mysync->{ biggest_message_transferred } = max( $string_len, $mysync->{ biggest_message_transferred } ) ;
  9700. my $time_spent = timesince( $mysync->{begin_transfer_time} ) ;
  9701. my $rate = bytes_display_string_bin( $mysync->{total_bytes_transferred} / $time_spent ) ;
  9702. my $eta = eta( $mysync ) ;
  9703. my $amount_transferred = bytes_display_string_bin( $mysync->{total_bytes_transferred} ) ;
  9704. myprintf( "msg %s/%-19s copied to %s/%-10s %.2f msgs/s %s/s %s copied %s\n",
  9705. $h1_fold, "$h1_msg {$string_len}", $h2_fold, $new_id, $mysync->{nb_msg_transferred}/$time_spent, $rate,
  9706. $amount_transferred,
  9707. $eta );
  9708. sleep_if_needed( $mysync ) ;
  9709. if ( $usecache and $cacheaftercopy and $new_id =~ m{^\d+$}x ) {
  9710. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$new_id\n" ) ;
  9711. touch( "$cache_dir/${h1_msg}_$new_id" )
  9712. or croak( "Couldn't touch $cache_dir/${h1_msg}_$new_id" ) ;
  9713. }
  9714. if ( $mysync->{ delete1 } ) {
  9715. delete_message_on_host1( $mysync, $h1_fold, $mysync->{ expungeaftereach }, $h1_msg ) ;
  9716. }
  9717. #myprint( "PRESS ENTER" ) and my $a = <> ;
  9718. return( $new_id ) ;
  9719. }
  9720. }
  9721. else{
  9722. $nb_msg_skipped_dry_mode += 1 ;
  9723. $mysync->{ h1_nb_msg_processed } += 1 ;
  9724. }
  9725. return ;
  9726. }
  9727. sub tests_sleep_if_needed
  9728. {
  9729. note( 'Entering tests_sleep_if_needed()' ) ;
  9730. is( undef, sleep_if_needed( ), 'sleep_if_needed: no args => undef' ) ;
  9731. my $mysync ;
  9732. is( undef, sleep_if_needed( $mysync ), 'sleep_if_needed: arg undef => undef' ) ;
  9733. $mysync->{maxbytespersecond} = 1000 ;
  9734. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: maxbytespersecond only => no sleep => 0' ) ;
  9735. $mysync->{begin_transfer_time} = time ; # now
  9736. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: begin_transfer_time now => no sleep => 0' ) ;
  9737. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before
  9738. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 0 => no sleep => 0' ) ;
  9739. $mysync->{total_bytes_transferred} = 2200 ;
  9740. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before
  9741. is( '0.20', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 2200 since 2s => sleep 0.2s' ) ;
  9742. is( '0', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 2200 since 2+2 == 4s => no sleep' ) ;
  9743. $mysync->{maxsleep} = 0.1 ;
  9744. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before again
  9745. is( '0.10', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 4000 since 2s but maxsleep 0.1s => sleep 0.1s' ) ;
  9746. $mysync->{maxbytesafter} = 4000 ;
  9747. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before again
  9748. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: maxbytesafter == total_bytes_transferred => no sleep => 0' ) ;
  9749. note( 'Leaving tests_sleep_if_needed()' ) ;
  9750. return ;
  9751. }
  9752. sub sleep_if_needed
  9753. {
  9754. my( $mysync ) = shift ;
  9755. if ( ! $mysync ) {
  9756. return ;
  9757. }
  9758. # No need to go further if there is no limit set
  9759. if (
  9760. not (
  9761. $mysync->{maxmessagespersecond}
  9762. or $mysync->{maxbytespersecond}
  9763. )
  9764. ) {
  9765. return ;
  9766. }
  9767. $mysync->{maxsleep} = defined $mysync->{maxsleep} ? $mysync->{maxsleep} : $MAX_SLEEP ;
  9768. # Must be positive
  9769. $mysync->{maxsleep} = max( 0, $mysync->{maxsleep} ) ;
  9770. my $time_spent = timesince( $mysync->{begin_transfer_time} ) ;
  9771. my $sleep_max_messages = sleep_max_messages( $mysync->{nb_msg_transferred}, $time_spent, $mysync->{maxmessagespersecond} ) ;
  9772. my $maxbytesafter = $mysync->{maxbytesafter} || 0 ;
  9773. my $total_bytes_transferred = $mysync->{total_bytes_transferred} || 0 ;
  9774. my $total_bytes_to_consider = $total_bytes_transferred - $maxbytesafter ;
  9775. #myprint( "maxbytesafter:$maxbytesafter\n" ) ;
  9776. #myprint( "total_bytes_to_consider:$total_bytes_to_consider\n" ) ;
  9777. my $sleep_max_bytes = sleep_max_bytes( $total_bytes_to_consider, $time_spent, $mysync->{maxbytespersecond} ) ;
  9778. my $sleep_max = min( $mysync->{maxsleep}, max( $sleep_max_messages, $sleep_max_bytes ) ) ;
  9779. $sleep_max = mysprintf( "%.2f", $sleep_max ) ; # round with 2 decimals.
  9780. if ( $sleep_max > 0 ) {
  9781. myprint( "sleeping $sleep_max s\n" ) ;
  9782. sleep $sleep_max ;
  9783. # Slept
  9784. return $sleep_max ;
  9785. }
  9786. # No sleep
  9787. return 0 ;
  9788. }
  9789. sub sleep_max_messages
  9790. {
  9791. # how long we have to sleep to go under max_messages_per_second
  9792. my( $nb_msg_transferred, $time_spent, $maxmessagespersecond ) = @_ ;
  9793. if ( ( not defined $maxmessagespersecond ) or $maxmessagespersecond <= 0 ) { return( 0 ) } ;
  9794. my $sleep = ( $nb_msg_transferred / $maxmessagespersecond ) - $time_spent ;
  9795. # the sleep must be positive
  9796. return( max( 0, $sleep ) ) ;
  9797. }
  9798. sub tests_sleep_max_messages
  9799. {
  9800. note( 'Entering tests_sleep_max_messages()' ) ;
  9801. ok( 0 == sleep_max_messages( 4, 2, undef ), 'sleep_max_messages: maxmessagespersecond = undef') ;
  9802. ok( 0 == sleep_max_messages( 4, 2, 0 ), 'sleep_max_messages: maxmessagespersecond = 0') ;
  9803. ok( 0 == sleep_max_messages( 4, 2, $MINUS_ONE ), 'sleep_max_messages: maxmessagespersecond = -1') ;
  9804. ok( 0 == sleep_max_messages( 4, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max reached') ;
  9805. ok( 2 == sleep_max_messages( 8, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max over') ;
  9806. ok( 0 == sleep_max_messages( 2, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max not reached') ;
  9807. note( 'Leaving tests_sleep_max_messages()' ) ;
  9808. return ;
  9809. }
  9810. sub sleep_max_bytes
  9811. {
  9812. # how long we have to sleep to go under max_bytes_per_second
  9813. my( $total_bytes_to_consider, $time_spent, $maxbytespersecond ) = @_ ;
  9814. $total_bytes_to_consider ||= 0 ;
  9815. $time_spent ||= 0 ;
  9816. if ( ( not defined $maxbytespersecond ) or $maxbytespersecond <= 0 ) { return( 0 ) } ;
  9817. #myprint( "total_bytes_to_consider:$total_bytes_to_consider\n" ) ;
  9818. my $sleep = ( $total_bytes_to_consider / $maxbytespersecond ) - $time_spent ;
  9819. # the sleep must be positive
  9820. return( max( 0, $sleep ) ) ;
  9821. }
  9822. sub tests_sleep_max_bytes
  9823. {
  9824. note( 'Entering tests_sleep_max_bytes()' ) ;
  9825. ok( 0 == sleep_max_bytes( 4000, 2, undef ), 'sleep_max_bytes: maxbytespersecond == undef => sleep 0' ) ;
  9826. ok( 0 == sleep_max_bytes( 4000, 2, 0 ), 'sleep_max_bytes: maxbytespersecond = 0 => sleep 0') ;
  9827. ok( 0 == sleep_max_bytes( 4000, 2, $MINUS_ONE ), 'sleep_max_bytes: maxbytespersecond = -1 => sleep 0') ;
  9828. ok( 0 == sleep_max_bytes( 4000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max reached sharp => sleep 0') ;
  9829. ok( 2 == sleep_max_bytes( 8000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max over => sleep a little') ;
  9830. ok( 0 == sleep_max_bytes( -8000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max not reached => sleep 0') ;
  9831. ok( 0 == sleep_max_bytes( 2000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max not reached => sleep 0') ;
  9832. ok( 0 == sleep_max_bytes( -2000, 2, 1000 ), 'sleep_max_bytes: maxbytespersecond = 1k max not reached => sleep 0') ;
  9833. note( 'Leaving tests_sleep_max_bytes()' ) ;
  9834. return ;
  9835. }
  9836. sub delete_message_on_host1
  9837. {
  9838. my( $mysync, $h1_fold, $expunge, @h1_msg ) = @_ ;
  9839. if ( ! $mysync->{ delete1 } ) { return ; }
  9840. if ( ! @h1_msg ) { return ; }
  9841. delete_messages_on_any(
  9842. $mysync,
  9843. $mysync->{ acc1 },
  9844. $mysync->{ imap1 },
  9845. "Host1: $h1_fold",
  9846. $expunge,
  9847. $split1,
  9848. @h1_msg ) ;
  9849. return ;
  9850. }
  9851. sub tests_operators_and_exclam_precedence
  9852. {
  9853. note( 'Entering tests_operators_and_exclam_precedence()' ) ;
  9854. is( 1, ! 0, 'tests_operators_and_exclam_precedence: ! 0 => 1' ) ;
  9855. is( "", ! 1, 'tests_operators_and_exclam_precedence: ! 1 => ""' ) ;
  9856. is( 1, not( 0 ), 'tests_operators_and_exclam_precedence: not( 0 ) => 1' ) ;
  9857. is( "", not( 1 ), 'tests_operators_and_exclam_precedence: not( 1 ) => ""' ) ;
  9858. # I wrote those tests to avoid perlcrit "Mixed high and low-precedence booleans"
  9859. # and change sub delete_messages_on_any() but got 4 more warnings... So now commented.
  9860. #is( 0, ( ! 0 and 0 ), 'tests_operators_and_exclam_precedence: ! 0 and 0 ) => 0' ) ;
  9861. #is( 1, ( ! 0 and 1 ), 'tests_operators_and_exclam_precedence: ! 0 and 1 ) => 1' ) ;
  9862. #is( "", ( ! 1 and 0 ), 'tests_operators_and_exclam_precedence: ! 1 and 0 ) => ""' ) ;
  9863. #is( "", ( ! 1 and 1 ), 'tests_operators_and_exclam_precedence: ! 1 and 1 ) => ""' ) ;
  9864. is( 0, ( ! 0 && 0 ), 'tests_operators_and_exclam_precedence: ! 0 && 0 ) => 0' ) ;
  9865. is( 1, ( ! 0 && 1 ), 'tests_operators_and_exclam_precedence: ! 0 && 1 ) => 1' ) ;
  9866. is( "", ( ! 1 && 0 ), 'tests_operators_and_exclam_precedence: ! 1 && 0 ) => ""' ) ;
  9867. is( "", ( ! 1 && 1 ), 'tests_operators_and_exclam_precedence: ! 1 && 1 ) => ""' ) ;
  9868. is( 2, ( ! 0 && 2 ), 'tests_operators_and_exclam_precedence: ! 0 && 2 ) => 1' ) ;
  9869. note( 'Leaving tests_operators_and_exclam_precedence()' ) ;
  9870. return ;
  9871. }
  9872. sub delete_messages_on_any
  9873. {
  9874. # $acc is not used yet,
  9875. #
  9876. my( $mysync, $acc, $imap, $hostX_folder, $expunge, $split, @messages ) = @_ ;
  9877. my $expunge_message = q{} ;
  9878. my $dry_message = $mysync->{ dry_message } ;
  9879. $expunge_message = 'and expunged' if ( $expunge ) ;
  9880. # "Host1: msg "
  9881. # $imap->Debug( 1 ) ;
  9882. my @messages_to_mark_deleted = @messages ;
  9883. while ( my @messages_part = splice @messages_to_mark_deleted, 0, $split )
  9884. {
  9885. foreach my $message ( @messages_part )
  9886. {
  9887. myprint( "$hostX_folder/$message marking deleted $expunge_message $dry_message\n" ) ;
  9888. }
  9889. if ( ! $mysync->{dry} && @messages_part )
  9890. {
  9891. my $nb_deleted = $imap->delete_message( $imap->Range( @messages_part ) ) ;
  9892. if ( defined $nb_deleted )
  9893. {
  9894. # $nb_deleted is not accurate
  9895. $acc->{ nb_msg_deleted } += scalar @messages_part ;
  9896. }
  9897. else
  9898. {
  9899. my $error_imap = $imap->LastError || q{} ;
  9900. my $error = join( q{}, "$hostX_folder folder, could not delete ",
  9901. scalar @messages_part, ' messages: ', $error_imap, "\n" ) ;
  9902. errors_incr( $mysync, $error ) ;
  9903. }
  9904. }
  9905. }
  9906. if ( $expunge ) {
  9907. uidexpunge_or_expunge( $mysync, $imap, @messages ) ;
  9908. }
  9909. #$imap->Debug( 0 ) ;
  9910. return ;
  9911. }
  9912. sub tests_uidexpunge_or_expunge
  9913. {
  9914. note( 'Entering tests_uidexpunge_or_expunge()' ) ;
  9915. is( undef, uidexpunge_or_expunge( ), 'uidexpunge_or_expunge: no args => undef' ) ;
  9916. my $mysync ;
  9917. is( undef, uidexpunge_or_expunge( $mysync ), 'uidexpunge_or_expunge: undef args => undef' ) ;
  9918. $mysync = {} ;
  9919. is( undef, uidexpunge_or_expunge( $mysync ), 'uidexpunge_or_expunge: arg empty => undef' ) ;
  9920. my $imap ;
  9921. is( undef, uidexpunge_or_expunge( $mysync, $imap ), 'uidexpunge_or_expunge: undef Mail-IMAPClient instance => undef' ) ;
  9922. require_ok( "Test::MockObject" ) ;
  9923. $imap = Test::MockObject->new( ) ;
  9924. is( undef, uidexpunge_or_expunge( $mysync, $imap ), 'uidexpunge_or_expunge: no message (1) to uidexpunge => undef' ) ;
  9925. my @messages = ( ) ;
  9926. is( undef, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: no message (2) to uidexpunge => undef' ) ;
  9927. @messages = ( '2', '1' ) ;
  9928. $imap->mock( 'uidexpunge', sub { return ; } ) ;
  9929. $imap->mock( 'expunge', sub { return ; } ) ;
  9930. is( undef, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: uidexpunge failure => expunge failure => undef' ) ;
  9931. $imap->mock( 'expunge', sub { return 1 ; } ) ;
  9932. is( 1, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: uidexpunge failure => expunge ok => 1' ) ;
  9933. $imap->mock( 'uidexpunge', sub { return 1 ; } ) ;
  9934. is( 1, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: messages to uidexpunge ok => 1' ) ;
  9935. note( 'Leaving tests_uidexpunge_or_expunge()' ) ;
  9936. return ;
  9937. }
  9938. sub uidexpunge_or_expunge
  9939. {
  9940. my $mysync = shift ;
  9941. my $imap = shift ;
  9942. my @messages = @ARG ;
  9943. if ( ! $imap ) { return ; } ;
  9944. if ( ! @messages ) { return ; } ;
  9945. # Doing uidexpunge
  9946. my @uidexpunge_result = $imap->uidexpunge( @messages ) ;
  9947. if ( @uidexpunge_result ) {
  9948. return 1 ;
  9949. }
  9950. # Failure so doing expunge
  9951. my $expunge_result = $imap->expunge( ) ;
  9952. if ( $expunge_result ) {
  9953. return 1 ;
  9954. }
  9955. # bad trip
  9956. return ;
  9957. }
  9958. sub eta_print
  9959. {
  9960. my $mysync = shift ;
  9961. if ( my $eta = eta( $mysync ) )
  9962. {
  9963. myprint( "$eta\n" ) ;
  9964. }
  9965. return ;
  9966. }
  9967. sub tests_eta
  9968. {
  9969. note( 'Entering tests_eta()' ) ;
  9970. is( q{}, eta( ), 'eta: no args => ""' ) ;
  9971. is( q{}, eta( undef ), 'eta: undef => ""' ) ;
  9972. my $mysync = {} ;
  9973. # No foldersizes
  9974. is( q{}, eta( $mysync ), 'eta: No foldersizes => ""' ) ;
  9975. $mysync->{ foldersizes } = 1 ;
  9976. $mysync->{ begin_transfer_time } = time ; # Now
  9977. $mysync->{ h1_nb_msg_processed } = 0 ;
  9978. is( "ETA: " . localtimez( time ) . " 0 s 0/0 msgs left",
  9979. eta( $mysync ),
  9980. 'eta: no args => ETA: "Now" 0 s 0/0 msgs left' ) ;
  9981. $mysync->{ h1_nb_msg_processed } = 1 ;
  9982. $mysync->{ h1_nb_msg_start } = 2 ;
  9983. is( "ETA: " . localtimez( time ) . " 0 s 1/2 msgs left",
  9984. eta( $mysync ),
  9985. 'eta: 1, 1, 2 => ETA: "Now" 0 s 1/2 msgs left' ) ;
  9986. note( 'Leaving tests_eta()' ) ;
  9987. return ;
  9988. }
  9989. sub eta
  9990. {
  9991. my( $mysync ) = shift ;
  9992. if ( ! $mysync )
  9993. {
  9994. return q{} ;
  9995. }
  9996. return( q{} ) if not $mysync->{ foldersizes } ;
  9997. my $h1_nb_msg_start = $mysync->{ h1_nb_msg_start } ;
  9998. my $h1_nb_processed = $mysync->{ h1_nb_msg_processed } ;
  9999. my $nb_msg_transferred = ( $mysync->{dry} ) ? $mysync->{ h1_nb_msg_processed } : $mysync->{ nb_msg_transferred } ;
  10000. my $time_spent = timesince( $mysync->{ begin_transfer_time } ) ;
  10001. $h1_nb_processed ||= 0 ;
  10002. $h1_nb_msg_start ||= 0 ;
  10003. $time_spent ||= 0 ;
  10004. my $time_remaining = time_remaining( $time_spent, $h1_nb_processed, $h1_nb_msg_start, $nb_msg_transferred ) ;
  10005. $mysync->{ debug } and myprint( "time_spent: $time_spent time_remaining: $time_remaining\n" ) ;
  10006. my $nb_msg_remaining = $h1_nb_msg_start - $h1_nb_processed ;
  10007. my $eta_date = localtimez( time + $time_remaining ) ;
  10008. return( mysprintf( 'ETA: %s %1.0f s %s/%s msgs left',
  10009. $eta_date, $time_remaining, $nb_msg_remaining, $h1_nb_msg_start ) ) ;
  10010. }
  10011. sub time_remaining
  10012. {
  10013. my( $my_time_spent, $h1_nb_processed, $h1_nb_msg_start, $nb_transferred ) = @_ ;
  10014. $nb_transferred ||= 1 ; # At least one is done (no division by zero)
  10015. $h1_nb_processed ||= 0 ;
  10016. $h1_nb_msg_start ||= $h1_nb_processed ;
  10017. $my_time_spent ||= 0 ;
  10018. my $time_remaining = ( $my_time_spent / $nb_transferred ) * ( $h1_nb_msg_start - $h1_nb_processed ) ;
  10019. return( $time_remaining ) ;
  10020. }
  10021. sub tests_time_remaining
  10022. {
  10023. note( 'Entering tests_time_remaining()' ) ;
  10024. # time_spent, nb_processed, nb_to_do_total, nb_transferred
  10025. is( 0, time_remaining( ), 'time_remaining: no args -> 0' ) ;
  10026. is( 0, time_remaining( 0, 0, 0, 0 ), 'time_remaining: 0, 0, 0, 0 -> 0' ) ;
  10027. is( 1, time_remaining( 1, 1, 2, 1 ), 'time_remaining: 1, 1, 2, 1 -> 1' ) ;
  10028. is( 1, time_remaining( 9, 9, 10, 9 ), 'time_remaining: 9, 9, 10, 9 -> 1' ) ;
  10029. is( 9, time_remaining( 1, 1, 10, 1 ), 'time_remaining: 1, 1, 10, 1 -> 9' ) ;
  10030. is( 5, time_remaining( 5, 5, 10, 5 ), 'time_remaining: 5, 5, 10, 5 -> 5' ) ;
  10031. is( 25, time_remaining( 5, 5, 10, 0 ), 'time_remaining: 5, 5, 10, 0 -> ( 5 / 1 ) * ( 10 - 5) = 25' ) ;
  10032. is( 25, time_remaining( 5, 5, 10, 1 ), 'time_remaining: 5, 5, 10, 1 -> ( 5 / 1 ) * ( 10 - 5) = 25' ) ;
  10033. note( 'Leaving tests_time_remaining()' ) ;
  10034. return ;
  10035. }
  10036. sub cache_map
  10037. {
  10038. my ( $cache_files_ref, $h1_msgs_ref, $h2_msgs_ref ) = @_;
  10039. my ( %map1_2, %map2_1, %done2 ) ;
  10040. my $h1_msgs_hash_ref = { } ;
  10041. my $h2_msgs_hash_ref = { } ;
  10042. @{ $h1_msgs_hash_ref }{ @{ $h1_msgs_ref } } = ( ) ;
  10043. @{ $h2_msgs_hash_ref }{ @{ $h2_msgs_ref } } = ( ) ;
  10044. foreach my $file ( sort @{ $cache_files_ref } ) {
  10045. $debugcache and myprint( "C12: $file\n" ) ;
  10046. ( $uid1, $uid2 ) = match_a_cache_file( $file ) ;
  10047. if ( exists( $h1_msgs_hash_ref->{ defined $uid1 ? $uid1 : q{} } )
  10048. and exists( $h2_msgs_hash_ref->{ defined $uid2 ? $uid2 : q{} } ) ) {
  10049. # keep only the greatest uid2
  10050. # 130_2301 and
  10051. # 130_231 => keep only 130 -> 2301
  10052. # keep only the greatest uid1
  10053. # 1601_260 and
  10054. # 161_260 => keep only 1601 -> 260
  10055. my $max_uid2 = max( $uid2, $map1_2{ $uid1 } || $MINUS_ONE ) ;
  10056. if ( exists $done2{ $max_uid2 } ) {
  10057. if ( $done2{ $max_uid2 } < $uid1 ) {
  10058. $map1_2{ $uid1 } = $max_uid2 ;
  10059. delete $map1_2{ $done2{ $max_uid2 } } ;
  10060. $done2{ $max_uid2 } = $uid1 ;
  10061. }
  10062. }else{
  10063. $map1_2{ $uid1 } = $max_uid2 ;
  10064. $done2{ $max_uid2 } = $uid1 ;
  10065. }
  10066. };
  10067. }
  10068. %map2_1 = reverse %map1_2 ;
  10069. return( \%map1_2, \%map2_1) ;
  10070. }
  10071. sub tests_cache_map
  10072. {
  10073. note( 'Entering tests_cache_map()' ) ;
  10074. #$debugcache = 1 ;
  10075. my @cache_files = qw (
  10076. 100_200
  10077. 101_201
  10078. 120_220
  10079. 142_242
  10080. 143_243
  10081. 177_277
  10082. 177_278
  10083. 177_279
  10084. 155_255
  10085. 180_280
  10086. 181_280
  10087. 182_280
  10088. 130_231
  10089. 130_2301
  10090. 161_260
  10091. 1601_260
  10092. ) ;
  10093. my $msgs_1 = [120, 142, 143, 144, 161, 1601, 177, 182, 130 ];
  10094. my $msgs_2 = [ 242, 243, 260, 299, 377, 279, 255, 280, 231, 2301 ];
  10095. my( $c12, $c21 ) ;
  10096. ok( ( $c12, $c21 ) = cache_map( \@cache_files, $msgs_1, $msgs_2 ), 'cache_map: 02' );
  10097. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  10098. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  10099. ok( 0 == compare_lists( [ 130, 142, 143, 177, 182, 1601 ], $a1 ), 'cache_map: 03' );
  10100. ok( 0 == compare_lists( [ 242, 243, 260, 279, 280, 2301 ], $a2 ), 'cache_map: 04' );
  10101. ok( ! $c12->{161}, 'cache_map: ! 161 -> 260' );
  10102. ok( 260 == $c12->{1601}, 'cache_map: 1601 -> 260' );
  10103. ok( 2301 == $c12->{130}, 'cache_map: 130 -> 2301' );
  10104. #myprint( $c12->{1601}, "\n" ) ;
  10105. note( 'Leaving tests_cache_map()' ) ;
  10106. return ;
  10107. }
  10108. sub cache_dir_fix
  10109. {
  10110. my $cache_dir = shift ;
  10111. $cache_dir =~ s/([;<>\*\|`&\$!#\(\)\[\]\{\}:'"\\])/\\$1/xg ;
  10112. #myprint( "cache_dir_fix: $cache_dir\n" ) ;
  10113. return( $cache_dir ) ;
  10114. }
  10115. sub tests_cache_dir_fix
  10116. {
  10117. note( 'Entering tests_cache_dir_fix()' ) ;
  10118. ok( 'lalala' eq cache_dir_fix('lalala'), 'cache_dir_fix: lalala -> lalala' );
  10119. ok( 'ii\\\\ii' eq cache_dir_fix('ii\ii'), 'cache_dir_fix: ii\ii -> ii\\\\ii' );
  10120. ok( 'ii@ii' eq cache_dir_fix('ii@ii'), 'cache_dir_fix: ii@ii -> ii@ii' );
  10121. ok( 'ii@ii\\:ii' eq cache_dir_fix('ii@ii:ii'), 'cache_dir_fix: ii@ii:ii -> ii@ii\\:ii' );
  10122. ok( 'i\\\\i\\\\ii' eq cache_dir_fix('i\i\ii'), 'cache_dir_fix: i\i\ii -> i\\\\i\\\\ii' );
  10123. ok( 'i\\\\ii' eq cache_dir_fix('i\\ii'), 'cache_dir_fix: i\\ii -> i\\\\\\\\ii' );
  10124. ok( '\\\\ ' eq cache_dir_fix('\\ '), 'cache_dir_fix: \\ -> \\\\\ ' );
  10125. ok( '\\\\ ' eq cache_dir_fix('\ '), 'cache_dir_fix: \ -> \\\\\ ' );
  10126. ok( '\[bracket\]' eq cache_dir_fix('[bracket]'), 'cache_dir_fix: [bracket] -> \[bracket\]' );
  10127. note( 'Leaving tests_cache_dir_fix()' ) ;
  10128. return ;
  10129. }
  10130. sub cache_dir_fix_win
  10131. {
  10132. my $cache_dir = shift ;
  10133. $cache_dir =~ s/(\[|\])/[$1]/xg ;
  10134. #myprint( "cache_dir_fix_win: $cache_dir\n" ) ;
  10135. return( $cache_dir ) ;
  10136. }
  10137. sub tests_cache_dir_fix_win
  10138. {
  10139. note( 'Entering tests_cache_dir_fix_win()' ) ;
  10140. ok( 'lalala' eq cache_dir_fix_win('lalala'), 'cache_dir_fix_win: lalala -> lalala' );
  10141. ok( '[[]bracket[]]' eq cache_dir_fix_win('[bracket]'), 'cache_dir_fix_win: [bracket] -> [[]bracket[]]' );
  10142. note( 'Leaving tests_cache_dir_fix_win()' ) ;
  10143. return ;
  10144. }
  10145. sub get_cache
  10146. {
  10147. my ( $cache_dir, $h1_msgs_ref, $h2_msgs_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_;
  10148. $debugcache and myprint( "Entering get_cache\n" ) ;
  10149. -d $cache_dir or return( undef ); # exit if cache directory doesn't exist
  10150. $debugcache and myprint( "cache_dir : $cache_dir\n" ) ;
  10151. if ( 'MSWin32' ne $OSNAME ) {
  10152. $cache_dir = cache_dir_fix( $cache_dir ) ;
  10153. }else{
  10154. $cache_dir = cache_dir_fix_win( $cache_dir ) ;
  10155. }
  10156. $debugcache and myprint( "cache_dir_fix: $cache_dir\n" ) ;
  10157. my @cache_files = bsd_glob( "$cache_dir/*" ) ;
  10158. #$debugcache and myprint( "cache_files: [@cache_files]\n" ) ;
  10159. $debugcache and myprint( 'cache_files: ', scalar @cache_files , " files found\n" ) ;
  10160. my( $cache_1_2_ref, $cache_2_1_ref )
  10161. = cache_map( \@cache_files, $h1_msgs_ref, $h2_msgs_ref ) ;
  10162. clean_cache( \@cache_files, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  10163. $debugcache and myprint( "Exiting get_cache\n" ) ;
  10164. return( $cache_1_2_ref, $cache_2_1_ref ) ;
  10165. }
  10166. sub tests_get_cache
  10167. {
  10168. note( 'Entering tests_get_cache()' ) ;
  10169. ok( not( get_cache('/cache_no_exist') ), 'get_cache: /cache_no_exist' );
  10170. ok( ( not -d 'W/tmp/cache/F1/F2' or rmtree( 'W/tmp/cache/F1/F2' ) ), 'get_cache: rmtree W/tmp/cache/F1/F2' ) ;
  10171. ok( mkpath( 'W/tmp/cache/F1/F2' ), 'get_cache: mkpath W/tmp/cache/F1/F2' ) ;
  10172. my @test_files_cache = ( qw(
  10173. W/tmp/cache/F1/F2/100_200
  10174. W/tmp/cache/F1/F2/101_201
  10175. W/tmp/cache/F1/F2/120_220
  10176. W/tmp/cache/F1/F2/142_242
  10177. W/tmp/cache/F1/F2/143_243
  10178. W/tmp/cache/F1/F2/177_277
  10179. W/tmp/cache/F1/F2/177_377
  10180. W/tmp/cache/F1/F2/177_777
  10181. W/tmp/cache/F1/F2/155_255
  10182. ) ) ;
  10183. ok( touch( @test_files_cache ), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  10184. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  10185. # on live:
  10186. my $msgs_1 = [120, 142, 143, 144, 177 ];
  10187. my $msgs_2 = [ 242, 243, 299, 377, 777, 255 ];
  10188. my $msgs_all_1 = { 120 => 0, 142 => 0, 143 => 0, 144 => 0, 177 => 0 } ;
  10189. my $msgs_all_2 = { 242 => 0, 243 => 0, 299 => 0, 377 => 0, 777 => 0, 255 => 0 } ;
  10190. my( $c12, $c21 ) ;
  10191. ok( ( $c12, $c21 ) = get_cache( 'W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  10192. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  10193. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  10194. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: 03' );
  10195. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: 04' );
  10196. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  10197. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  10198. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file removed 100_200');
  10199. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file removed 101_201');
  10200. # test clean_cache executed
  10201. $maxage = 2 ;
  10202. ok( touch(@test_files_cache), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  10203. ok( ( $c12, $c21 ) = get_cache('W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  10204. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  10205. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  10206. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file NOT removed 100_200');
  10207. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file NOT removed 101_201');
  10208. # strange files
  10209. #$debugcache = 1 ;
  10210. $maxage = undef ;
  10211. ok( ( not -d 'W/tmp/cache/rr\uee' or rmtree( 'W/tmp/cache/rr\uee' )), 'get_cache: rmtree W/tmp/cache/rr\uee' ) ;
  10212. ok( mkpath( 'W/tmp/cache/rr\uee' ), 'get_cache: mkpath W/tmp/cache/rr\uee' ) ;
  10213. @test_files_cache = ( qw(
  10214. W/tmp/cache/rr\uee/100_200
  10215. W/tmp/cache/rr\uee/101_201
  10216. W/tmp/cache/rr\uee/120_220
  10217. W/tmp/cache/rr\uee/142_242
  10218. W/tmp/cache/rr\uee/143_243
  10219. W/tmp/cache/rr\uee/177_277
  10220. W/tmp/cache/rr\uee/177_377
  10221. W/tmp/cache/rr\uee/177_777
  10222. W/tmp/cache/rr\uee/155_255
  10223. ) ) ;
  10224. ok( touch(@test_files_cache), 'get_cache: touch strange W/tmp/cache/...' ) ;
  10225. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  10226. # on live:
  10227. $msgs_1 = [120, 142, 143, 144, 177 ] ;
  10228. $msgs_2 = [ 242, 243, 299, 377, 777, 255 ] ;
  10229. $msgs_all_1 = { 120 => q{}, 142 => q{}, 143 => q{}, 144 => q{}, 177 => q{} } ;
  10230. $msgs_all_2 = { 242 => q{}, 243 => q{}, 299 => q{}, 377 => q{}, 777 => q{}, 255 => q{} } ;
  10231. 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' );
  10232. $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  10233. $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  10234. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: strange path 03' );
  10235. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: strange path 04' );
  10236. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 142_242');
  10237. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 143_243');
  10238. ok( ! -f 'W/tmp/cache/rr\uee/100_200', 'get_cache: strange path file removed 100_200');
  10239. ok( ! -f 'W/tmp/cache/rr\uee/101_201', 'get_cache: strange path file removed 101_201');
  10240. note( 'Leaving tests_get_cache()' ) ;
  10241. return ;
  10242. }
  10243. sub match_a_cache_file
  10244. {
  10245. my $file = shift ;
  10246. my ( $cache_uid1, $cache_uid2 ) ;
  10247. return( ( undef, undef ) ) if ( ! $file ) ;
  10248. if ( $file =~ m{(?:^|/)(\d+)_(\d+)$}x ) {
  10249. $cache_uid1 = $1 ;
  10250. $cache_uid2 = $2 ;
  10251. }
  10252. return( $cache_uid1, $cache_uid2 ) ;
  10253. }
  10254. sub tests_match_a_cache_file
  10255. {
  10256. note( 'Entering tests_match_a_cache_file()' ) ;
  10257. my ( $tuid1, $tuid2 ) ;
  10258. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( ), 'match_a_cache_file: no arg' ) ;
  10259. ok( ! defined $tuid1 , 'match_a_cache_file: no arg 1' ) ;
  10260. ok( ! defined $tuid2 , 'match_a_cache_file: no arg 2' ) ;
  10261. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( q{} ), 'match_a_cache_file: empty arg' ) ;
  10262. ok( ! defined $tuid1 , 'match_a_cache_file: empty arg 1' ) ;
  10263. ok( ! defined $tuid2 , 'match_a_cache_file: empty arg 2' ) ;
  10264. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '000_000' ), 'match_a_cache_file: 000_000' ) ;
  10265. ok( '000' eq $tuid1, 'match_a_cache_file: 000_000 1' ) ;
  10266. ok( '000' eq $tuid2, 'match_a_cache_file: 000_000 2' ) ;
  10267. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '123_456' ), 'match_a_cache_file: 123_456' ) ;
  10268. ok( '123' eq $tuid1, 'match_a_cache_file: 123_456 1' ) ;
  10269. ok( '456' eq $tuid2, 'match_a_cache_file: 123_456 2' ) ;
  10270. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/tmp/truc/123_456' ), 'match_a_cache_file: /tmp/truc/123_456' ) ;
  10271. ok( '123' eq $tuid1, 'match_a_cache_file: /tmp/truc/123_456 1' ) ;
  10272. ok( '456' eq $tuid2, 'match_a_cache_file: /tmp/truc/123_456 2' ) ;
  10273. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/lala123_456' ), 'match_a_cache_file: NO /lala123_456' ) ;
  10274. ok( ! $tuid1, 'match_a_cache_file: /lala123_456 1' ) ;
  10275. ok( ! $tuid2, 'match_a_cache_file: /lala123_456 2' ) ;
  10276. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( 'la123_456' ), 'match_a_cache_file: NO la123_456' ) ;
  10277. ok( ! $tuid1, 'match_a_cache_file: la123_456 1' ) ;
  10278. ok( ! $tuid2, 'match_a_cache_file: la123_456 2' ) ;
  10279. note( 'Leaving tests_match_a_cache_file()' ) ;
  10280. return ;
  10281. }
  10282. sub clean_cache
  10283. {
  10284. my ( $cache_files_ref, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_ ;
  10285. $debugcache and myprint( "Entering clean_cache\n" ) ;
  10286. $debugcache and myprint( map { "$_ -> " . $cache_1_2_ref->{ $_ } . "\n" } keys %{ $cache_1_2_ref } ) ;
  10287. foreach my $file ( @{ $cache_files_ref } ) {
  10288. $debugcache and myprint( "$file\n" ) ;
  10289. my ( $cache_uid1, $cache_uid2 ) = match_a_cache_file( $file ) ;
  10290. $debugcache and myprint( "u1: $cache_uid1 u2: $cache_uid2 c12: ", $cache_1_2_ref->{ $cache_uid1 } || q{}, "\n") ;
  10291. # or ( ! exists( $cache_1_2_ref->{ $cache_uid1 } ) )
  10292. # or ( ! ( $cache_uid2 == $cache_1_2_ref->{ $cache_uid1 } ) )
  10293. if ( ( not defined $cache_uid1 )
  10294. or ( not defined $cache_uid2 )
  10295. or ( not exists $h1_msgs_all_hash_ref->{ $cache_uid1 } )
  10296. or ( not exists $h2_msgs_all_hash_ref->{ $cache_uid2 } )
  10297. ) {
  10298. $debugcache and myprint( "remove $file\n" ) ;
  10299. unlink $file or myprint( "$OS_ERROR" ) ;
  10300. }
  10301. }
  10302. $debugcache and myprint( "Exiting clean_cache\n" ) ;
  10303. return( 1 ) ;
  10304. }
  10305. sub tests_clean_cache
  10306. {
  10307. note( 'Entering tests_clean_cache()' ) ;
  10308. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache: rmtree W/tmp/cache/G1/G2' ) ;
  10309. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache: mkpath W/tmp/cache/G1/G2' ) ;
  10310. my @test_files_cache = ( qw(
  10311. W/tmp/cache/G1/G2/100_200
  10312. W/tmp/cache/G1/G2/101_201
  10313. W/tmp/cache/G1/G2/120_220
  10314. W/tmp/cache/G1/G2/142_242
  10315. W/tmp/cache/G1/G2/143_243
  10316. W/tmp/cache/G1/G2/177_277
  10317. W/tmp/cache/G1/G2/177_377
  10318. W/tmp/cache/G1/G2/177_777
  10319. W/tmp/cache/G1/G2/155_255
  10320. ) ) ;
  10321. ok( touch(@test_files_cache), 'clean_cache: touch W/tmp/cache/G1/G2/...' ) ;
  10322. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 before' );
  10323. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 before' );
  10324. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 before' );
  10325. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 before' );
  10326. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 before' );
  10327. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 before' );
  10328. my $cache = {
  10329. 142 => 242,
  10330. 177 => 777,
  10331. } ;
  10332. my $all_1 = {
  10333. 142 => q{},
  10334. 177 => q{},
  10335. } ;
  10336. my $all_2 = {
  10337. 200 => q{},
  10338. 242 => q{},
  10339. 777 => q{},
  10340. } ;
  10341. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache: ' ) ;
  10342. ok( ! -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 after' );
  10343. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 after' );
  10344. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 after' );
  10345. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 after' );
  10346. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 after' );
  10347. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 after' );
  10348. note( 'Leaving tests_clean_cache()' ) ;
  10349. return ;
  10350. }
  10351. sub tests_clean_cache_2
  10352. {
  10353. note( 'Entering tests_clean_cache_2()' ) ;
  10354. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache_2: rmtree W/tmp/cache/G1/G2' ) ;
  10355. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache_2: mkpath W/tmp/cache/G1/G2' ) ;
  10356. my @test_files_cache = ( qw(
  10357. W/tmp/cache/G1/G2/100_200
  10358. W/tmp/cache/G1/G2/101_201
  10359. W/tmp/cache/G1/G2/120_220
  10360. W/tmp/cache/G1/G2/142_242
  10361. W/tmp/cache/G1/G2/143_243
  10362. W/tmp/cache/G1/G2/177_277
  10363. W/tmp/cache/G1/G2/177_377
  10364. W/tmp/cache/G1/G2/177_777
  10365. W/tmp/cache/G1/G2/155_255
  10366. ) ) ;
  10367. ok( touch(@test_files_cache), 'clean_cache_2: touch W/tmp/cache/G1/G2/...' ) ;
  10368. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 before' );
  10369. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 before' );
  10370. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 before' );
  10371. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 before' );
  10372. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 before' );
  10373. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 before' );
  10374. my $cache = {
  10375. 142 => 242,
  10376. 177 => 777,
  10377. } ;
  10378. my $all_1 = {
  10379. $NUMBER_100 => q{},
  10380. 142 => q{},
  10381. 177 => q{},
  10382. } ;
  10383. my $all_2 = {
  10384. 200 => q{},
  10385. 242 => q{},
  10386. 777 => q{},
  10387. } ;
  10388. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache_2: ' ) ;
  10389. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 after' );
  10390. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 after' );
  10391. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 after' );
  10392. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 after' );
  10393. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 after' );
  10394. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 after' );
  10395. note( 'Leaving tests_clean_cache_2()' ) ;
  10396. return ;
  10397. }
  10398. sub tests_mkpath
  10399. {
  10400. note( 'Entering tests_mkpath()' ) ;
  10401. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' )), 'mkpath: mkpath W/tmp/tests/' ) ;
  10402. SKIP: {
  10403. skip( 'Tests only for Unix', 10 ) if ( 'MSWin32' eq $OSNAME ) ;
  10404. my $long_path_unix = '123456789/' x 30 ;
  10405. ok( ( -d "W/tmp/tests/long/$long_path_unix" or mkpath( "W/tmp/tests/long/$long_path_unix" ) ), 'mkpath: mkpath 300 char' ) ;
  10406. ok( -d "W/tmp/tests/long/$long_path_unix", 'mkpath: mkpath > 300 char verified' ) ;
  10407. ok( ( -d "W/tmp/tests/long/$long_path_unix" and rmtree( 'W/tmp/tests/long/' ) ), 'mkpath: rmtree 300 char' ) ;
  10408. ok( ! -d "W/tmp/tests/long/$long_path_unix", 'mkpath: rmtree 300 char verified' ) ;
  10409. ok( ( -d 'W/tmp/tests/trailing_dots...' or mkpath( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: mkpath trailing_dots...' ) ;
  10410. ok( -d 'W/tmp/tests/trailing_dots...', 'mkpath: mkpath trailing_dots... verified' ) ;
  10411. ok( ( -d 'W/tmp/tests/trailing_dots...' and rmtree( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: rmtree trailing_dots...' ) ;
  10412. ok( ! -d 'W/tmp/tests/trailing_dots...', 'mkpath: rmtree trailing_dots... verified' ) ;
  10413. eval { ok( 1 / 0, 'mkpath: divide by 0' ) ; } or ok( 1, 'mkpath: can not divide by 0' ) ;
  10414. ok( 1, 'mkpath: still alive' ) ;
  10415. } ;
  10416. SKIP: {
  10417. skip( 'Tests only for MSWin32', 13 ) if ( 'MSWin32' ne $OSNAME ) ;
  10418. my $long_path_2_prefix = ".\\imapsync_tests" || '\\\?\\E:\\TEMP\\imapsync_tests' ;
  10419. myprint( "long_path_2_prefix: $long_path_2_prefix\n" ) ;
  10420. my $long_path_100 = $long_path_2_prefix . '\\' . '123456789\\' x 10 . 'END' ;
  10421. my $long_path_300 = $long_path_2_prefix . '\\' . '123456789\\' x 30 . 'END' ;
  10422. #myprint( "$long_path_100\n" ) ;
  10423. ok( ( -d $long_path_2_prefix or mkpath( $long_path_2_prefix ) ), 'mkpath: -d mkpath small path' ) ;
  10424. ok( ( -d $long_path_2_prefix ), 'mkpath: -d mkpath small path done' ) ;
  10425. ok( ( -d $long_path_100 or mkpath( $long_path_100 ) ), 'mkpath: mkpath > 100 char' ) ;
  10426. ok( ( -d $long_path_100 ), 'mkpath: -d mkpath > 200 char done' ) ;
  10427. ok( ( -d $long_path_2_prefix and rmtree( $long_path_2_prefix ) ), 'mkpath: rmtree > 100 char' ) ;
  10428. ok( (! -d $long_path_2_prefix ), 'mkpath: ! -d rmtree done' ) ;
  10429. # Without the eval the following mkpath 300 just kill the whole process without a whisper
  10430. #myprint( "$long_path_300\n" ) ;
  10431. eval { ok( ( -d $long_path_300 or mkpath( $long_path_300 ) ), 'mkpath: create a path with 300 characters' ) ; }
  10432. or ok( 1, 'mkpath: can not create a path with 300 characters' ) ;
  10433. ok( ( ( ! -d $long_path_300 ) or -d $long_path_300 and rmtree( $long_path_300 ) ), 'mkpath: rmtree the 300 character path' ) ;
  10434. ok( 1, 'mkpath: still alive' ) ;
  10435. ok( ( -d 'W/tmp/tests/trailing_dots...' or mkpath( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: mkpath trailing_dots...' ) ;
  10436. ok( -d 'W/tmp/tests/trailing_dots...', 'mkpath: mkpath trailing_dots... verified' ) ;
  10437. ok( ( -d 'W/tmp/tests/trailing_dots...' and rmtree( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: rmtree trailing_dots...' ) ;
  10438. ok( ! -d 'W/tmp/tests/trailing_dots...', 'mkpath: rmtree trailing_dots... verified' ) ;
  10439. } ;
  10440. note( 'Leaving tests_mkpath()' ) ;
  10441. # Keep this because of the eval used by the caller (failed badly?)
  10442. return 1 ;
  10443. }
  10444. sub tests_touch
  10445. {
  10446. note( 'Entering tests_touch()' ) ;
  10447. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' )), 'touch: mkpath W/tmp/tests/' ) ;
  10448. ok( 1 == touch( 'W/tmp/tests/lala'), 'touch: W/tmp/tests/lala') ;
  10449. ok( 1 == touch( 'W/tmp/tests/\y'), 'touch: W/tmp/tests/\y') ;
  10450. ok( 0 == touch( '/no/no/no/aaa'), 'touch: not /aaa') ;
  10451. ok( 1 == touch( 'W/tmp/tests/lili', 'W/tmp/tests/lolo'), 'touch: 2 files') ;
  10452. ok( 0 == touch( 'W/tmp/tests/\y', '/no/no/aaa'), 'touch: 2 files, 1 fails' ) ;
  10453. note( 'Leaving tests_touch()' ) ;
  10454. return ;
  10455. }
  10456. sub touch
  10457. {
  10458. my @files = @_ ;
  10459. my $failures = 0 ;
  10460. foreach my $file ( @files ) {
  10461. my $fh = IO::File->new ;
  10462. if ( $fh->open(">> $file" ) ) {
  10463. $fh->close ;
  10464. }else{
  10465. myprint( "Could not open file $file in write/append mode\n" ) ;
  10466. $failures++ ;
  10467. }
  10468. }
  10469. return( ! $failures );
  10470. }
  10471. sub tests_tmpdir_has_colon_bug
  10472. {
  10473. note( 'Entering tests_tmpdir_has_colon_bug()' ) ;
  10474. ok( 0 == tmpdir_has_colon_bug( q{} ), 'tmpdir_has_colon_bug: ' ) ;
  10475. ok( 0 == tmpdir_has_colon_bug( '/tmp' ), 'tmpdir_has_colon_bug: /tmp' ) ;
  10476. ok( 1 == tmpdir_has_colon_bug( 'C:' ), 'tmpdir_has_colon_bug: C:' ) ;
  10477. ok( 1 == tmpdir_has_colon_bug( 'C:\temp' ), 'tmpdir_has_colon_bug: C:\temp' ) ;
  10478. note( 'Leaving tests_tmpdir_has_colon_bug()' ) ;
  10479. return ;
  10480. }
  10481. sub tmpdir_has_colon_bug
  10482. {
  10483. my $path = shift ;
  10484. my $path_filtered = filter_forbidden_characters( $path ) ;
  10485. if ( $path_filtered ne $path ) {
  10486. ( -d $path_filtered ) and myprint( "Path $path was previously mistakely changed to $path_filtered\n" ) ;
  10487. return( 1 ) ;
  10488. }
  10489. return( 0 ) ;
  10490. }
  10491. sub tmpdir_fix_colon_bug
  10492. {
  10493. my $mysync = shift ;
  10494. my $err = 0 ;
  10495. if ( not (-d $mysync->{ tmpdir } and -r _ and -w _) ) {
  10496. myprint( "tmpdir $mysync->{ tmpdir } is not valid\n" ) ;
  10497. return( 0 ) ;
  10498. }
  10499. my $cachedir_new = "$mysync->{ tmpdir }/imapsync_cache" ;
  10500. if ( not tmpdir_has_colon_bug( $cachedir_new ) ) { return( 0 ) } ;
  10501. # check if old cache directory already exists
  10502. my $cachedir_old = filter_forbidden_characters( $cachedir_new ) ;
  10503. if ( not ( -d $cachedir_old ) ) {
  10504. myprint( "Old cache directory $cachedir_new no exists, nothing to do\n" ) ;
  10505. return( 1 ) ;
  10506. }
  10507. # check if new cache directory already exists
  10508. if ( -d $cachedir_new ) {
  10509. myprint( "New fixed cache directory $cachedir_new already exists, not moving the old one $cachedir_old. Fix this manually.\n" ) ;
  10510. return( 0 ) ;
  10511. }else{
  10512. # move the old one to the new place
  10513. myprint( "Moving $cachedir_old to $cachedir_new Do not interrupt this task.\n" ) ;
  10514. File::Copy::Recursive::rmove( $cachedir_old, $cachedir_new )
  10515. or do {
  10516. myprint( "Could not move $cachedir_old to $cachedir_new\n" ) ;
  10517. $err++ ;
  10518. } ;
  10519. # check it succeeded
  10520. if ( -d $cachedir_new and -r _ and -w _ ) {
  10521. myprint( "New fixed cache directory $cachedir_new ok\n" ) ;
  10522. }else{
  10523. myprint( "New fixed cache directory $cachedir_new does not exist\n" ) ;
  10524. $err++ ;
  10525. }
  10526. if ( -d $cachedir_old ) {
  10527. myprint( "Old cache directory $cachedir_old still exists\n" ) ;
  10528. $err++ ;
  10529. }else{
  10530. myprint( "Old cache directory $cachedir_old successfully moved\n" ) ;
  10531. }
  10532. }
  10533. return( not $err ) ;
  10534. }
  10535. sub tests_cache_folder
  10536. {
  10537. note( 'Entering tests_cache_folder()' ) ;
  10538. ok( '/path/fold1/fold2' eq cache_folder( q{}, '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  10539. ok( '/pa_th/fold1/fold2' eq cache_folder( q{}, '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  10540. 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' ) ;
  10541. ok( 'D:/path/fold1/fold2' eq cache_folder( 'D:', '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  10542. ok( 'D:/pa_th/fold1/fold2' eq cache_folder( 'D:', '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  10543. 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' ) ;
  10544. ok( '//' eq cache_folder( q{}, q{}, q{}, q{}), 'cache_folder: -> //' ) ;
  10545. ok( '//_______' eq cache_folder( q{}, q{}, q{}, '*|?:"<>'), 'cache_folder: *|?:"<> -> //_______' ) ;
  10546. note( 'Leaving tests_cache_folder()' ) ;
  10547. return ;
  10548. }
  10549. sub cache_folder
  10550. {
  10551. my( $cache_base, $cache_dir, $h1_fold, $h2_fold ) = @_ ;
  10552. my $sep_1 = $sync->{ h1_sep } || '/';
  10553. my $sep_2 = $sync->{ h2_sep } || '/';
  10554. #myprint( "$cache_dir h1_fold $h1_fold sep1 $sep_1 h2_fold $h2_fold sep2 $sep_2\n" ) ;
  10555. $h1_fold = convert_sep_to_slash( $h1_fold, $sep_1 ) ;
  10556. $h2_fold = convert_sep_to_slash( $h2_fold, $sep_2 ) ;
  10557. my $cache_folder = "$cache_base" . filter_forbidden_characters( "$cache_dir/$h1_fold/$h2_fold" ) ;
  10558. #myprint( "cache_folder [$cache_folder]\n" ) ;
  10559. return( $cache_folder ) ;
  10560. }
  10561. sub tests_filter_forbidden_characters
  10562. {
  10563. note( 'Entering tests_filter_forbidden_characters()' ) ;
  10564. is( undef , filter_forbidden_characters( ), 'filter_forbidden_characters: no args -> undef' ) ;
  10565. is( 'a_b' , filter_forbidden_characters( 'a_b' ), 'filter_forbidden_characters: a_b -> a_b' ) ;
  10566. is( 'a_b' , filter_forbidden_characters( 'a*b' ), 'filter_forbidden_characters: a*b -> a_b' ) ;
  10567. is( 'a_b' , filter_forbidden_characters( 'a|b' ), 'filter_forbidden_characters: a|b -> a_b' ) ;
  10568. is( 'a_b' , filter_forbidden_characters( 'a?b' ), 'filter_forbidden_characters: a?b -> a_b' ) ;
  10569. is( 'a________b', filter_forbidden_characters( q{a*|?:"<>'b} ), q{filter_forbidden_characters: a*|?:"<>'b -> a________b} ) ;
  10570. is( 'a_b_' , filter_forbidden_characters( 'a b ' ), 'filter_forbidden_characters: "a b " -> "a_b_"' ) ;
  10571. is( 'a_b' , filter_forbidden_characters( "a\tb" ), 'filter_forbidden_characters: a\tb -> a_b' ) ;
  10572. is( "a_b" , filter_forbidden_characters( "a\rb" ), 'filter_forbidden_characters: a\rb -> a_b' ) ;
  10573. is( "a_b" , filter_forbidden_characters( "a\nb" ), 'filter_forbidden_characters: a\nb -> a_b' ) ;
  10574. is( "a_b" , filter_forbidden_characters( "a\\b" ), 'filter_forbidden_characters: a\b -> a_b' ) ;
  10575. is( 'a-b' , filter_forbidden_characters( 'a-b' ), 'filter_forbidden_characters: a-b -> a-b' ) ;
  10576. is( 'a__-__-__-__-__b' , filter_forbidden_characters( 'aé-è-à -ç-Öb' ), 'filter_forbidden_characters: aé-è-à -ç-Öb -> a__-__-__-__-__b' ) ;
  10577. is( 'abcdABCDwxyzWXYZ012789' , filter_forbidden_characters( 'abcdABCDwxyzWXYZ012789' ),
  10578. 'filter_forbidden_characters: abcdABCDwxyzWXYZ012789 -> abcdABCDwxyzWXYZ012789' ) ;
  10579. note( 'Leaving tests_filter_forbidden_characters()' ) ;
  10580. return ;
  10581. }
  10582. sub filter_forbidden_characters
  10583. {
  10584. my $string = shift ;
  10585. if ( ! defined $string ) { return ; }
  10586. $string =~ s{[\Q*|?:"<>' \E\t\r\n\\]}{_}xg ;
  10587. # replace all non-ascii and control characters by _
  10588. $string =~ s/[[:^ascii:][:cntrl:]]/_/xg ;
  10589. #myprint( "[$string]\n" ) ;
  10590. return( $string ) ;
  10591. }
  10592. sub tests_convert_sep_to_slash
  10593. {
  10594. note( 'Entering tests_convert_sep_to_slash()' ) ;
  10595. ok(q{} eq convert_sep_to_slash(q{}, '/'), 'convert_sep_to_slash: no folder');
  10596. ok('INBOX' eq convert_sep_to_slash('INBOX', '/'), 'convert_sep_to_slash: INBOX');
  10597. ok('INBOX/foo' eq convert_sep_to_slash('INBOX/foo', '/'), 'convert_sep_to_slash: INBOX/foo');
  10598. ok('INBOX/foo' eq convert_sep_to_slash('INBOX_foo', '_'), 'convert_sep_to_slash: INBOX_foo');
  10599. ok('INBOX/foo/zob' eq convert_sep_to_slash('INBOX_foo_zob', '_'), 'convert_sep_to_slash: INBOX_foo_zob');
  10600. ok('INBOX/foo' eq convert_sep_to_slash('INBOX.foo', '.'), 'convert_sep_to_slash: INBOX.foo');
  10601. ok('INBOX/foo/hi' eq convert_sep_to_slash('INBOX.foo.hi', '.'), 'convert_sep_to_slash: INBOX.foo.hi');
  10602. note( 'Leaving tests_convert_sep_to_slash()' ) ;
  10603. return ;
  10604. }
  10605. sub convert_sep_to_slash
  10606. {
  10607. my ( $folder, $sep ) = @_ ;
  10608. $folder =~ s{\Q$sep\E}{/}xg ;
  10609. return( $folder ) ;
  10610. }
  10611. sub tests_regexmess
  10612. {
  10613. note( 'Entering tests_regexmess()' ) ;
  10614. ok( 'blabla' eq regexmess( 'blabla' ), 'regexmess: no regexmess, nothing to do' ) ;
  10615. @regexmess = ( 'lalala' ) ;
  10616. ok( not( defined regexmess( 'popopo' ) ), 'regexmess: bad regex lalala' ) ;
  10617. @regexmess = ( 's/p/Z/g' ) ;
  10618. ok( 'ZoZoZo' eq regexmess( 'popopo' ), 'regexmess: s/p/Z/g' ) ;
  10619. @regexmess = ( 's{c}{C}gxms' ) ;
  10620. ok("H1: abC\nH2: Cde\n\nBody abC"
  10621. eq regexmess( "H1: abc\nH2: cde\n\nBody abc"),
  10622. 'regexmess: c->C');
  10623. @regexmess = ( 's{\AFrom\ }{From:}gxms' ) ;
  10624. ok( q{}
  10625. eq regexmess(q{}),
  10626. 'regexmess: From mbox 1 add colon blank');
  10627. ok( 'From:<tartanpion@machin.truc>'
  10628. eq regexmess('From <tartanpion@machin.truc>'),
  10629. 'regexmess: From mbox 2 add colo');
  10630. ok( "\n" . 'From <tartanpion@machin.truc>'
  10631. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  10632. 'regexmess: From mbox 3 add colo') ;
  10633. ok( "From: zzz\n" . 'From <tartanpion@machin.truc>'
  10634. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  10635. 'regexmess: From mbox 4 add colo') ;
  10636. @regexmess = ( 's{\AFrom\ [^\n]*(\n)?}{}gxms' ) ;
  10637. ok( q{}
  10638. eq regexmess(q{}),
  10639. 'regexmess: From mbox 1 remove, blank');
  10640. ok( q{}
  10641. eq regexmess('From <tartanpion@machin.truc>'),
  10642. 'regexmess: From mbox 2 remove');
  10643. ok( "\n" . 'From <tartanpion@machin.truc>'
  10644. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  10645. 'regexmess: From mbox 3 remove');
  10646. #myprint( "[", regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'), "]" ) ;
  10647. ok( q{} . 'From <tartanpion@machin.truc>'
  10648. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  10649. 'regexmess: From mbox 4 remove');
  10650. is(
  10651. <<'EOM'
  10652. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10653. From:<tartanpion@machin.truc>
  10654. Hello,
  10655. Bye.
  10656. EOM
  10657. , regexmess(
  10658. <<'EOM'
  10659. From zzz
  10660. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10661. From:<tartanpion@machin.truc>
  10662. Hello,
  10663. Bye.
  10664. EOM
  10665. ), 'regexmess: From mbox 5 remove');
  10666. @regexmess = ( 's{\A((?:[^\n]+\n)+|)^Disposition-Notification-To:[^\n]*\n(\r?\n|.*\n\r?\n)}{$1$2}xms' ) ; # SUPER SUPER BEST!
  10667. ok(
  10668. <<'EOM'
  10669. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10670. From:<tartanpion@machin.truc>
  10671. Hello,
  10672. Bye.
  10673. EOM
  10674. eq regexmess(
  10675. <<'EOM'
  10676. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10677. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10678. From:<tartanpion@machin.truc>
  10679. Hello,
  10680. Bye.
  10681. EOM
  10682. ),
  10683. 'regexmess: 1 Delete header Disposition-Notification-To:');
  10684. ok(
  10685. <<'EOM'
  10686. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10687. From:<tartanpion@machin.truc>
  10688. Hello,
  10689. Bye.
  10690. EOM
  10691. eq regexmess(
  10692. <<'EOM'
  10693. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10694. From:<tartanpion@machin.truc>
  10695. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10696. Hello,
  10697. Bye.
  10698. EOM
  10699. ),
  10700. 'regexmess: 2 Delete header Disposition-Notification-To:');
  10701. ok(
  10702. <<'EOM'
  10703. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10704. From:<tartanpion@machin.truc>
  10705. Hello,
  10706. Bye.
  10707. EOM
  10708. eq regexmess(
  10709. <<'EOM'
  10710. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10711. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10712. From:<tartanpion@machin.truc>
  10713. Hello,
  10714. Bye.
  10715. EOM
  10716. ),
  10717. 'regexmess: 3 Delete header Disposition-Notification-To:');
  10718. ok(
  10719. <<'EOM'
  10720. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10721. From:<tartanpion@machin.truc>
  10722. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10723. Bye.
  10724. EOM
  10725. eq regexmess(
  10726. <<'EOM'
  10727. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10728. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10729. From:<tartanpion@machin.truc>
  10730. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10731. Bye.
  10732. EOM
  10733. ),
  10734. 'regexmess: 4 Delete header Disposition-Notification-To:');
  10735. ok(
  10736. <<'EOM'
  10737. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10738. From:<tartanpion@machin.truc>
  10739. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10740. Bye.
  10741. EOM
  10742. eq regexmess(
  10743. <<'EOM'
  10744. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10745. From:<tartanpion@machin.truc>
  10746. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10747. Bye.
  10748. EOM
  10749. ),
  10750. 'regexmess: 5 Delete header Disposition-Notification-To:');
  10751. ok(
  10752. <<'EOM'
  10753. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10754. From:<tartanpion@machin.truc>
  10755. Hello,
  10756. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10757. Bye.
  10758. EOM
  10759. eq regexmess(
  10760. <<'EOM'
  10761. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10762. From:<tartanpion@machin.truc>
  10763. Hello,
  10764. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10765. Bye.
  10766. EOM
  10767. ),
  10768. 'regexmess: 6 Delete header Disposition-Notification-To:');
  10769. ok(
  10770. <<'EOM'
  10771. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10772. From:<tartanpion@machin.truc>
  10773. Hello,
  10774. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10775. Bye.
  10776. EOM
  10777. eq regexmess(
  10778. <<'EOM'
  10779. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10780. From:<tartanpion@machin.truc>
  10781. Hello,
  10782. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10783. Bye.
  10784. EOM
  10785. ),
  10786. 'regexmess: 7 Delete header Disposition-Notification-To:');
  10787. ok(
  10788. <<'EOM'
  10789. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10790. From:<tartanpion@machin.truc>
  10791. Hello,
  10792. Bye.
  10793. EOM
  10794. eq regexmess(
  10795. <<'EOM'
  10796. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10797. From:<tartanpion@machin.truc>
  10798. Hello,
  10799. Bye.
  10800. EOM
  10801. ),
  10802. 'regexmess: 8 Delete header Disposition-Notification-To:');
  10803. ok(
  10804. <<'EOM'
  10805. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10806. From:<tartanpion@machin.truc>
  10807. Hello,
  10808. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10809. Bye.
  10810. EOM
  10811. eq regexmess(
  10812. <<'EOM'
  10813. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10814. From:<tartanpion@machin.truc>
  10815. Hello,
  10816. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10817. Bye.
  10818. EOM
  10819. ),
  10820. 'regexmess: 9 Delete header Disposition-Notification-To:');
  10821. ok(
  10822. <<'EOM'
  10823. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10824. From:<tartanpion@machin.truc>
  10825. Hello,
  10826. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10827. Bye.
  10828. EOM
  10829. eq regexmess(
  10830. <<'EOM'
  10831. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10832. From:<tartanpion@machin.truc>
  10833. Hello,
  10834. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10835. Bye.
  10836. EOM
  10837. ),
  10838. 'regexmess: 10 Delete header Disposition-Notification-To:');
  10839. ok(
  10840. <<'EOM'
  10841. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10842. From:<tartanpion@machin.truc>
  10843. Hello,
  10844. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10845. Bye.
  10846. EOM
  10847. eq regexmess(
  10848. <<'EOM'
  10849. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10850. From:<tartanpion@machin.truc>
  10851. Hello,
  10852. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10853. Bye.
  10854. EOM
  10855. ),
  10856. 'regexmess: 11 Delete header Disposition-Notification-To:');
  10857. ok(
  10858. <<'EOM'
  10859. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10860. From:<tartanpion@machin.truc>
  10861. Hello,
  10862. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10863. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10864. Bye.
  10865. EOM
  10866. eq regexmess(
  10867. <<'EOM'
  10868. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10869. From:<tartanpion@machin.truc>
  10870. Hello,
  10871. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10872. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10873. Bye.
  10874. EOM
  10875. ),
  10876. 'regexmess: 12 Delete header Disposition-Notification-To:');
  10877. @regexmess = ( 's{\A(.*?(?! ^$))^Disposition-Notification-To:(.*?)$}{$1X-Disposition-Notification-To:$2}igxms' ) ; # BAD!
  10878. @regexmess = ( 's{\A((?:[^\n]+\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims' ) ;
  10879. ok(
  10880. <<'EOM'
  10881. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10882. From:<tartanpion@machin.truc>
  10883. Hello,
  10884. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10885. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10886. Bye.
  10887. EOM
  10888. eq regexmess(
  10889. <<'EOM'
  10890. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10891. From:<tartanpion@machin.truc>
  10892. Hello,
  10893. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10894. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10895. Bye.
  10896. EOM
  10897. ),
  10898. 'regexmess: 13 Delete header Disposition-Notification-To:');
  10899. ok(
  10900. <<'EOM'
  10901. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10902. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10903. From:<tartanpion@machin.truc>
  10904. Hello,
  10905. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10906. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10907. Bye.
  10908. EOM
  10909. eq regexmess(
  10910. <<'EOM'
  10911. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10912. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10913. From:<tartanpion@machin.truc>
  10914. Hello,
  10915. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10916. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10917. Bye.
  10918. EOM
  10919. ),
  10920. 'regexmess: 14 Delete header Disposition-Notification-To:');
  10921. ok(
  10922. <<'EOM'
  10923. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10924. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10925. From:<tartanpion@machin.truc>
  10926. Hello,
  10927. Bye.
  10928. EOM
  10929. eq regexmess(
  10930. <<'EOM'
  10931. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10932. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10933. From:<tartanpion@machin.truc>
  10934. Hello,
  10935. Bye.
  10936. EOM
  10937. ),
  10938. 'regexmess: 15 Delete header Disposition-Notification-To:');
  10939. ok(
  10940. <<'EOM'
  10941. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10942. From:<tartanpion@machin.truc>
  10943. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10944. Hello,
  10945. Bye.
  10946. EOM
  10947. eq regexmess(
  10948. <<'EOM'
  10949. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10950. From:<tartanpion@machin.truc>
  10951. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10952. Hello,
  10953. Bye.
  10954. EOM
  10955. ),
  10956. 'regexmess: 16 Delete header Disposition-Notification-To:');
  10957. ok(
  10958. <<'EOM'
  10959. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10960. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10961. From:<tartanpion@machin.truc>
  10962. Hello,
  10963. Bye.
  10964. EOM
  10965. eq regexmess(
  10966. <<'EOM'
  10967. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  10968. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10969. From:<tartanpion@machin.truc>
  10970. Hello,
  10971. Bye.
  10972. EOM
  10973. ),
  10974. 'regexmess: 17 Delete header Disposition-Notification-To:');
  10975. @regexmess = ( 's/.{11}\K.*//gs' ) ;
  10976. is( "0123456789\n", regexmess( "0123456789\n" x 100 ), 'regexmess: truncate whole message after 11 characters' ) ;
  10977. is( "0123456789\n", regexmess( "0123456789\n" x 100_000 ), 'regexmess: truncate whole message after 11 characters ~ 1MB' ) ;
  10978. @regexmess = ( 's/.{10000}\K.*//gs' ) ;
  10979. is( "123456789\n" x 1000, regexmess( "123456789\n" x 100_000 ), 'regexmess: truncate whole message after 10000 characters ~ 1MB' ) ;
  10980. @regexmess = ( 's/^(X-Ham-Report.*?\n)^X-/X-/sm' ) ;
  10981. is(
  10982. <<'EOM'
  10983. X-Spam-Score: -1
  10984. X-Spam-Bar: /
  10985. X-Spam-Flag: NO
  10986. Date: Sat, 10 Jul 2010 05:34:45 -0700
  10987. From:<tartanpion@machin.truc>
  10988. Hello,
  10989. Bye.
  10990. EOM
  10991. ,
  10992. regexmess(
  10993. <<'EOM'
  10994. X-Spam-Score: -1
  10995. X-Spam-Bar: /
  10996. X-Ham-Report: =?utf-8?Q?Spam_detection_software=2C_running?=
  10997. =?utf-8?Q?_on_the_system_=22ohp-ag006.int200?=
  10998. _has_NOT_identified_thi?=
  10999. =?utf-8?Q?s_incoming_email_as_spam.__The_o?=
  11000. _message_has_been_attac?=
  11001. =?utf-8?Q?hed_to_this_so_you_can_view_it_o?=
  11002. ___________________________?=
  11003. =?utf-8?Q?__author's_domain
  11004. X-Spam-Flag: NO
  11005. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11006. From:<tartanpion@machin.truc>
  11007. Hello,
  11008. Bye.
  11009. EOM
  11010. ),
  11011. 'regexmess: Delete header X-Ham-Report:');
  11012. # regex to play with Date: from the FAQ
  11013. #@regexmess = 's{\A(.*?(?! ^$))^Date:(.*?)$}{$1Date:$2\nX-Date:$2}gxms'
  11014. # Change 8bit characters in whole email to X characters
  11015. @regexmess = ( 's{[\x80-\xff]}{X}gxms' ) ;
  11016. is( 'X-8bit: kaka 1 XX kiki', regexmess('X-8bit: kaka 1 ¤ kiki'), 'regexmess: 1 Change 8bit characters in whole email to X characters');
  11017. # Same change but using tr
  11018. @regexmess = ( 'tr [\x80-\xff] [X]' ) ;
  11019. 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');
  11020. # Add a final \r\n if missing
  11021. @regexmess = ( 's{(?<![\n])\z}{\r\n}gxms' ) ;
  11022. is( "\r\n", regexmess(""), 'regexmess: 1. Add a final \r\n if missing. Missing' ) ;
  11023. is( "abc\r\n", regexmess("abc"), 'regexmess: 2. Add a final \r\n if missing. Missing' ) ;
  11024. is( "abc\ndef\r\n", regexmess("abc\ndef"), 'regexmess: 3. Add a final \r\n if missing. Missing' ) ;
  11025. is( "abc\r\ndef\r\n", regexmess("abc\r\ndef"), 'regexmess: 3. Add a final \r\n if missing. Missing' ) ;
  11026. is( "\r\n", regexmess("\r\n"), 'regexmess: 3. Add a final \r\n if missing. Not missing' ) ;
  11027. is( "abc\n", regexmess("abc\n"), 'regexmess: 4. Add a final \r\n if missing. Not missing' ) ;
  11028. is( "abc\r\n", regexmess("abc\r\n"), 'regexmess: 4. Add a final \r\n if missing. Not missing' ) ;
  11029. is( "abc\ndef\n", regexmess("abc\ndef\n"), 'regexmess: 4. Add a final \r\n if missing. Not missing' ) ;
  11030. is( "abc\r\ndef\r\n", regexmess("abc\r\ndef\r\n"), 'regexmess: 4. Add a final \r\n if missing. Not missing' ) ;
  11031. # Remove the fucking buggy X-Spam-Report: a bad header on several lines that can even begin without a space!
  11032. @regexmess = ( 's{X-Spam-Report:.*?\n(^[^\n]+:|^\r?\n)}{$1}xms' ) ;
  11033. # Damien regexes:
  11034. #@regexmess = ( 's{X-Spam-Report:.*?\n(^[a-zA-Z0-9\-]+:)}{$1}xms' ) ;
  11035. #@regexmess = ( 's{X-Spam-Report:.*?\n(^[a-zA-Z0-9\-]+:|^\r?\n)}{$1}xms' ) ;
  11036. is(
  11037. <<'EOM'
  11038. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11039. From:<tartanpion@machin.truc>
  11040. LaSuite: super
  11041. Hello,
  11042. Bye.
  11043. EOM
  11044. , regexmess(
  11045. <<'EOM'
  11046. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11047. From:<tartanpion@machin.truc>
  11048. X-Spam-Report: caca
  11049. caca
  11050. caca
  11051. caca
  11052. LaSuite: super
  11053. Hello,
  11054. Bye.
  11055. EOM
  11056. ), 'regexmess: 1 remove buggy X-Spam-Report: across several lines, not the final header');
  11057. is(
  11058. <<'EOM'
  11059. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11060. From:<tartanpion@machin.truc>
  11061. LaSuite: super
  11062. LaSuite2: super 2
  11063. Hello,
  11064. Bye.
  11065. EOM
  11066. , regexmess(
  11067. <<'EOM'
  11068. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11069. From:<tartanpion@machin.truc>
  11070. X-Spam-Report: caca
  11071. caca
  11072. caca
  11073. caca
  11074. LaSuite: super
  11075. LaSuite2: super 2
  11076. Hello,
  11077. Bye.
  11078. EOM
  11079. ), 'regexmess: 2 remove buggy X-Spam-Report: across several lines, not the final header');
  11080. is(
  11081. <<'EOM'
  11082. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11083. From:<tartanpion@machin.truc>
  11084. LaSuite: super
  11085. LaSuite2: super 2
  11086. Hello,
  11087. Bye.
  11088. EOM
  11089. , regexmess(
  11090. <<'EOM'
  11091. X-Spam-Report: caca
  11092. caca
  11093. caca
  11094. caca
  11095. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11096. From:<tartanpion@machin.truc>
  11097. LaSuite: super
  11098. LaSuite2: super 2
  11099. Hello,
  11100. Bye.
  11101. EOM
  11102. ), 'regexmess: 3 remove buggy X-Spam-Report: across several lines, first header');
  11103. is(
  11104. <<'EOM'
  11105. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11106. From:<tartanpion@machin.truc>
  11107. Hello,
  11108. Bye.
  11109. EOM
  11110. , regexmess(
  11111. <<'EOM'
  11112. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11113. From:<tartanpion@machin.truc>
  11114. X-Spam-Report: caca
  11115. caca
  11116. caca
  11117. caca
  11118. Hello,
  11119. Bye.
  11120. EOM
  11121. ), 'regexmess: 4 remove buggy X-Spam-Report: across several lines, final header');
  11122. is(
  11123. <<'EOM'
  11124. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11125. From:<tartanpion@machin.truc>
  11126. Hello,
  11127. Bye.
  11128. EOM
  11129. , regexmess(
  11130. <<'EOM'
  11131. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11132. From:<tartanpion@machin.truc>
  11133. Hello,
  11134. Bye.
  11135. EOM
  11136. ), 'regexmess: 5 remove buggy X-Spam-Report: not there at all');
  11137. is(
  11138. <<"EOM"
  11139. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  11140. From:<tartanpion>\r
  11141. LaSuite: super\r
  11142. LaSuite2: super 2\r
  11143. \r
  11144. Hello,\r
  11145. Bye.\r
  11146. EOM
  11147. , regexmess(
  11148. <<"EOM"
  11149. X-Spam-Report: caca\r
  11150. caca\r
  11151. caca\r
  11152. caca\r
  11153. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  11154. From:<tartanpion>\r
  11155. LaSuite: super\r
  11156. LaSuite2: super 2\r
  11157. \r
  11158. Hello,\r
  11159. Bye.\r
  11160. EOM
  11161. ), 'regexmess: 6 remove buggy X-Spam-Report: across several lines, first header, with \r');
  11162. is(
  11163. <<"EOM"
  11164. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  11165. From:<tartanpion>\r
  11166. LaSuite: super\r
  11167. LaSuite2: super 2\r
  11168. \r
  11169. Hello,\r
  11170. Bye.\r
  11171. EOM
  11172. , regexmess(
  11173. <<"EOM"
  11174. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  11175. From:<tartanpion>\r
  11176. X-Spam-Report: caca\r
  11177. caca\r
  11178. caca\r
  11179. caca\r
  11180. LaSuite: super\r
  11181. LaSuite2: super 2\r
  11182. \r
  11183. Hello,\r
  11184. Bye.\r
  11185. EOM
  11186. ), 'regexmess: 7 remove buggy X-Spam-Report: across several lines, middle header, with \r');
  11187. is(
  11188. <<"EOM"
  11189. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  11190. From:<tartanpion>\r
  11191. \r
  11192. Hello,\r
  11193. Bye.\r
  11194. EOM
  11195. , regexmess(
  11196. <<"EOM"
  11197. Date: Sat, 10 Jul 2010 05:34:45 -0700\r
  11198. From:<tartanpion>\r
  11199. X-Spam-Report: caca\r
  11200. caca\r
  11201. caca\r
  11202. caca\r
  11203. \r
  11204. Hello,\r
  11205. Bye.\r
  11206. EOM
  11207. ), 'regexmess: 8 remove buggy X-Spam-Report: across several lines, final header, with \r');
  11208. undef @regexmess ;
  11209. note( 'Leaving tests_regexmess()' ) ;
  11210. return ;
  11211. }
  11212. sub regexmess
  11213. {
  11214. my ( $string ) = @_ ;
  11215. foreach my $regexmess ( @regexmess ) {
  11216. $sync->{ debug } and myprint( "eval \$string =~ $regexmess\n" ) ;
  11217. my $ret = eval "\$string =~ $regexmess ; 1" ;
  11218. #myprint( "eval [$ret]\n" ) ;
  11219. if ( ( not $ret ) or $EVAL_ERROR ) {
  11220. myprint( "Error: eval regexmess '$regexmess': $EVAL_ERROR" ) ;
  11221. return( undef ) ;
  11222. }
  11223. }
  11224. $sync->{ debug } and myprint( "$string\n" ) ;
  11225. return( $string ) ;
  11226. }
  11227. sub tests_skipmess
  11228. {
  11229. note( 'Entering tests_skipmess()' ) ;
  11230. ok( not( defined skipmess( 'blabla' ) ), 'skipmess, no skipmess, no skip' ) ;
  11231. @skipmess = ('[') ;
  11232. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex [' ) ;
  11233. @skipmess = ('lalala') ;
  11234. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex lalala' ) ;
  11235. @skipmess = ('/popopo/') ;
  11236. ok( 1 == skipmess( 'popopo' ), 'skipmess, popopo match regex /popopo/' ) ;
  11237. @skipmess = ('/popopo/') ;
  11238. ok( 0 == skipmess( 'rrrrrr' ), 'skipmess, rrrrrr does not match regex /popopo/' ) ;
  11239. @skipmess = ('m{^$}') ;
  11240. ok( 1 == skipmess( q{} ), 'skipmess: empty string yes' ) ;
  11241. ok( 0 == skipmess( 'Hi!' ), 'skipmess: empty string no' ) ;
  11242. @skipmess = ('m{i}') ;
  11243. ok( 1 == skipmess( 'Hi!' ), 'skipmess: i string yes' ) ;
  11244. ok( 0 == skipmess( 'Bye!' ), 'skipmess: i string no' ) ;
  11245. @skipmess = ('m{[\x80-\xff]}') ;
  11246. ok( 0 == skipmess( 'Hi!' ), 'skipmess: i 8bit no' ) ;
  11247. ok( 1 == skipmess( "\xff" ), 'skipmess: \xff 8bit yes' ) ;
  11248. @skipmess = ('m{A}', 'm{B}') ;
  11249. ok( 0 == skipmess( 'Hi!' ), 'skipmess: A or B no' ) ;
  11250. ok( 0 == skipmess( 'lala' ), 'skipmess: A or B no' ) ;
  11251. ok( 0 == skipmess( "\xff" ), 'skipmess: A or B no' ) ;
  11252. ok( 1 == skipmess( 'AB' ), 'skipmess: A or B yes' ) ;
  11253. ok( 1 == skipmess( 'BA' ), 'skipmess: A or B yes' ) ;
  11254. ok( 1 == skipmess( 'AA' ), 'skipmess: A or B yes' ) ;
  11255. ok( 1 == skipmess( 'Ok Bye' ), 'skipmess: A or B yes' ) ;
  11256. @skipmess = ( 'm#\A((?:[^\n]+\n)+|)^Content-Type: Message/Partial;[^\n]*\n(?:\n|.*\n\n)#ism' ) ; # SUPER BEST!
  11257. ok( 1 == skipmess(
  11258. <<'EOM'
  11259. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11260. Content-Type: Message/Partial; blabla
  11261. From:<tartanpion@machin.truc>
  11262. Hello!
  11263. Bye.
  11264. EOM
  11265. ),
  11266. 'skipmess: 1 match Content-Type: Message/Partial' ) ;
  11267. ok( 0 == skipmess(
  11268. <<'EOM'
  11269. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11270. From:<tartanpion@machin.truc>
  11271. Hello!
  11272. Bye.
  11273. EOM
  11274. ),
  11275. 'skipmess: 2 not match Content-Type: Message/Partial' ) ;
  11276. ok( 1 == skipmess(
  11277. <<'EOM'
  11278. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11279. From:<tartanpion@machin.truc>
  11280. Content-Type: Message/Partial; blabla
  11281. Hello!
  11282. Bye.
  11283. EOM
  11284. ),
  11285. 'skipmess: 3 match Content-Type: Message/Partial' ) ;
  11286. ok( 0 == skipmess(
  11287. <<'EOM'
  11288. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11289. From:<tartanpion@machin.truc>
  11290. Hello!
  11291. Content-Type: Message/Partial; blabla
  11292. Bye.
  11293. EOM
  11294. ),
  11295. 'skipmess: 4 not match Content-Type: Message/Partial' ) ;
  11296. ok( 0 == skipmess(
  11297. <<'EOM'
  11298. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11299. From:<tartanpion@machin.truc>
  11300. Hello!
  11301. Content-Type: Message/Partial; blabla
  11302. Bye.
  11303. EOM
  11304. ),
  11305. 'skipmess: 5 not match Content-Type: Message/Partial' ) ;
  11306. ok( 1 == skipmess(
  11307. <<'EOM'
  11308. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11309. Content-Type: Message/Partial; blabla
  11310. From:<tartanpion@machin.truc>
  11311. Hello!
  11312. Content-Type: Message/Partial; blabla
  11313. Bye.
  11314. EOM
  11315. ),
  11316. 'skipmess: 6 match Content-Type: Message/Partial' ) ;
  11317. ok( 1 == skipmess(
  11318. <<'EOM'
  11319. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11320. Content-Type: Message/Partial;
  11321. From:<tartanpion@machin.truc>
  11322. Hello!
  11323. Bye.
  11324. EOM
  11325. ),
  11326. 'skipmess: 7 match Content-Type: Message/Partial' ) ;
  11327. ok( 1 == skipmess(
  11328. <<'EOM'
  11329. Date: Wed, 2 Jul 2014 02:26:40 +0000
  11330. MIME-Version: 1.0
  11331. Content-Type: message/partial;
  11332. id="TAN_U_P<1404267997.00007489ed17>";
  11333. number=3;
  11334. total=3
  11335. 6HQ6Hh3CdXj77qEGixerQ6zHx0OnQ/Cf5On4W0Y6vtU2crABZQtD46Hx1EOh8dDz4+OnTr1G
  11336. Hello!
  11337. Bye.
  11338. EOM
  11339. ),
  11340. 'skipmess: 8 match Content-Type: Message/Partial' ) ;
  11341. ok( 1 == skipmess(
  11342. <<'EOM'
  11343. Return-Path: <gilles@lamiral.info>
  11344. Received: by lamiral.info (Postfix, from userid 1000)
  11345. id 21EB12443BF; Mon, 2 Mar 2015 15:38:35 +0100 (CET)
  11346. Subject: test: aethaecohngiexao
  11347. To: <tata@petite.lamiral.info>
  11348. X-Mailer: mail (GNU Mailutils 2.2)
  11349. Message-Id: <20150302143835.21EB12443BF@lamiral.info>
  11350. Content-Type: message/partial;
  11351. id="TAN_U_P<1404267997.00007489ed17>";
  11352. number=3;
  11353. total=3
  11354. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  11355. From: gilles@lamiral.info (Gilles LAMIRAL)
  11356. test: aethaecohngiexao
  11357. EOM
  11358. ),
  11359. 'skipmess: 9 match Content-Type: Message/Partial' ) ;
  11360. ok( 1 == skipmess(
  11361. <<'EOM'
  11362. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  11363. From: gilles@lamiral.info (Gilles LAMIRAL)
  11364. Content-Type: message/partial;
  11365. id="TAN_U_P<1404267997.00007489ed17>";
  11366. number=3;
  11367. total=3
  11368. test: aethaecohngiexao
  11369. EOM
  11370. . "lalala\n" x 3_000_000
  11371. ),
  11372. 'skipmess: 10 match Content-Type: Message/Partial' ) ;
  11373. ok( 0 == skipmess(
  11374. <<'EOM'
  11375. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  11376. From: gilles@lamiral.info (Gilles LAMIRAL)
  11377. test: aethaecohngiexao
  11378. EOM
  11379. . "lalala\n" x 3_000_000
  11380. ),
  11381. 'skipmess: 11 match Content-Type: Message/Partial' ) ;
  11382. ok( 0 == skipmess(
  11383. <<"EOM"
  11384. From: fff\r
  11385. To: fff\r
  11386. Subject: Testing imapsync --skipmess\r
  11387. Date: Mon, 22 Aug 2011 08:40:20 +0800\r
  11388. Mime-Version: 1.0\r
  11389. Content-Type: text/plain; charset=iso-8859-1\r
  11390. Content-Transfer-Encoding: 7bit\r
  11391. \r
  11392. EOM
  11393. . qq{!#"d%&'()*+,-./0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg\r\n } x 32_730
  11394. ),
  11395. 'skipmess: 12 not match Content-Type: Message/Partial' ) ;
  11396. # Complex regular subexpression recursion limit (32766) exceeded with more lines
  11397. # exit;
  11398. undef @skipmess ;
  11399. note( 'Leaving tests_skipmess()' ) ;
  11400. return ;
  11401. }
  11402. sub tests_skipmess_neg
  11403. {
  11404. note( 'Entering tests_skipmess_neg()' ) ;
  11405. @skipmess = ('m{i}') ;
  11406. ok( 1 == skipmess( 'Hi!' ), 'skipmess: i string yes' ) ;
  11407. ok( 0 == skipmess( 'Ho!' ), 'skipmess: i string no' ) ;
  11408. @skipmess = ('m{\A(?!.*i)}') ;
  11409. ok( 0 == skipmess( 'Hi!' ), 'skipmess: not i string no' ) ;
  11410. ok( 1 == skipmess( 'Ho!' ), 'skipmess: not i string yes' ) ;
  11411. @skipmess = ('m{\A(?!.*^From:[^\n]*tartanpion\@machin\.truc)}xms') ;
  11412. ok( 0 == skipmess(
  11413. <<'EOM'
  11414. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11415. From: <tartanpion@machin.truc>
  11416. Bye.
  11417. EOM
  11418. ),
  11419. 'skipmess: 1 not From tartanpion@machin.truc' ) ;
  11420. ok( 1 == skipmess(
  11421. <<'EOM'
  11422. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11423. From: <kikiki@machin.truc>
  11424. Bye.
  11425. EOM
  11426. ),
  11427. 'skipmess: 2 not From tartanpion@machin.truc' ) ;
  11428. ok( 0 == skipmess(
  11429. <<'EOM'
  11430. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11431. From: <tartanpion@machin.truc>
  11432. From: <tartanpion@machin.truc>
  11433. Bye.
  11434. EOM
  11435. ),
  11436. 'skipmess: 3 not From tartanpion@machin.truc' ) ;
  11437. ok( 1 == skipmess(
  11438. <<'EOM'
  11439. Date: Sat, 10 Jul 2010 05:34:45 -0700
  11440. From: <kikiki@machin.truc>
  11441. From: <tartanpion@machin.truc>
  11442. Bye.
  11443. EOM
  11444. ),
  11445. 'skipmess: 4 not From tartanpion@machin.truc' ) ;
  11446. undef @skipmess ;
  11447. note( 'Leaving tests_skipmess_neg()' ) ;
  11448. return ;
  11449. }
  11450. sub skipmess
  11451. {
  11452. my ( $string ) = @_ ;
  11453. my $match ;
  11454. #myprint( "$string\n" ) ;
  11455. foreach my $skipmess ( @skipmess ) {
  11456. $sync->{ debug } and myprint( "eval \$match = \$string =~ $skipmess\n" ) ;
  11457. my $ret = eval "\$match = \$string =~ $skipmess ; 1" ;
  11458. #myprint( "eval [$ret]\n" ) ;
  11459. $sync->{ debug } and myprint( "match [$match]\n" ) ;
  11460. if ( ( not $ret ) or $EVAL_ERROR ) {
  11461. myprint( "Error: eval skipmess '$skipmess': $EVAL_ERROR" ) ;
  11462. return( undef ) ;
  11463. }
  11464. return( $match ) if ( $match ) ;
  11465. }
  11466. return( $match ) ;
  11467. }
  11468. sub tests_bytes_display_string_bin
  11469. {
  11470. note( 'Entering tests_bytes_display_string_bin()' ) ;
  11471. is( 'NA', bytes_display_string_bin( ), 'bytes_display_string_bin: no args => NA' ) ;
  11472. is( 'NA', bytes_display_string_bin( undef ), 'bytes_display_string_bin: undef => NA' ) ;
  11473. is( 'NA', bytes_display_string_bin( 'blabla' ), 'bytes_display_string_bin: blabla => NA' ) ;
  11474. is( '0.000 KiB', bytes_display_string_bin( 0 ), 'bytes_display_string_bin: 0 => 0.000 KiB' ) ;
  11475. is( '0.001 KiB', bytes_display_string_bin( 1 ), 'bytes_display_string_bin: 1 => 0.001 KiB' ) ;
  11476. is( '0.010 KiB', bytes_display_string_bin( 10 ), 'bytes_display_string_bin: 10 => 0.010 KiB' ) ;
  11477. is( '0.976 KiB', bytes_display_string_bin( 999 ), 'bytes_display_string_bin: 999 => 0.976 KiB' ) ;
  11478. note( bytes_display_string_bin( 999 ) ) ;
  11479. is( '0.999 KiB', bytes_display_string_bin( 1023 ), 'bytes_display_string_bin: 1023 => 0.999 KiB' ) ;
  11480. note( bytes_display_string_bin( 1023 ) ) ;
  11481. is( '1.000 KiB', bytes_display_string_bin( 1024 ), 'bytes_display_string_bin: 1024 => 1.000 KiB' ) ;
  11482. note( bytes_display_string_bin( 1024 ) ) ;
  11483. is( '1.001 KiB', bytes_display_string_bin( 1025 ), 'bytes_display_string_bin: 1025 => 1.001 KiB' ) ;
  11484. is( '9.999 KiB', bytes_display_string_bin( 10_239 ), 'bytes_display_string_bin: 10_239 => 9.999 KiB' ) ;
  11485. note( bytes_display_string_bin( 10_239 ) ) ;
  11486. is( '10.000 KiB', bytes_display_string_bin( 10_240 ), 'bytes_display_string_bin: 10_240 => 10.000 KiB' ) ;
  11487. note( bytes_display_string_bin( 10_240 ) ) ;
  11488. is( '999.999 KiB', bytes_display_string_bin( 1_023_999 ), 'bytes_display_string_bin: 1_023_999 => 999.999 KiB' ) ;
  11489. note( bytes_display_string_bin( 1_023_999 ) ) ;
  11490. is( '0.977 MiB', bytes_display_string_bin( 1_024_000 ), 'bytes_display_string_bin: 1_024_000 => 0.977 MiB' ) ;
  11491. note( bytes_display_string_bin( 1_024_000 ) ) ;
  11492. is( '0.999 MiB', bytes_display_string_bin( 1_047_527 ), 'bytes_display_string_bin: 1_047_527 => 0.999 MiB' ) ;
  11493. note( bytes_display_string_bin( 1_047_527 ) ) ;
  11494. is( '0.999 MiB', bytes_display_string_bin( 1_048_051 ), 'bytes_display_string_bin: 1_048_051 => 0.999 MiB' ) ;
  11495. note( bytes_display_string_bin( 1_048_051 ) ) ;
  11496. is( '1.000 MiB', bytes_display_string_bin( 1_048_052 ), 'bytes_display_string_bin: 1_048_052 => 1.000 MiB' ) ;
  11497. note( bytes_display_string_bin( 1_048_052 ) ) ;
  11498. is( '1.000 MiB', bytes_display_string_bin( 1_048_575 ), 'bytes_display_string_bin: 1_048_575 => 1.000 MiB' ) ;
  11499. is( '1.000 MiB', bytes_display_string_bin( 1_048_576 ), 'bytes_display_string_bin: 1_048_576 => 1.000 MiB' ) ;
  11500. is( '1.000 GiB', bytes_display_string_bin( 1_073_741_823 ), 'bytes_display_string_bin: 1_073_741_823 => 1.000 GiB' ) ;
  11501. is( '1.000 GiB', bytes_display_string_bin( 1_073_741_824 ), 'bytes_display_string_bin: 1_073_741_824 => 1.000 GiB' ) ;
  11502. is( '1.000 TiB', bytes_display_string_bin( 1_099_511_627_775 ), 'bytes_display_string_bin: 1_099_511_627_775 => 1.000 TiB' ) ;
  11503. is( '1.000 TiB', bytes_display_string_bin( 1_099_511_627_776 ), 'bytes_display_string_bin: 1_099_511_627_776 => 1.000 TiB' ) ;
  11504. is( '1.000 PiB', bytes_display_string_bin( 1_125_899_906_842_623 ), 'bytes_display_string_bin: 1_125_899_906_842_623 => 1.000 PiB' ) ;
  11505. is( '1.000 PiB', bytes_display_string_bin( 1_125_899_906_842_624 ), 'bytes_display_string_bin: 1_125_899_906_842_624 => 1.000 PiB' ) ;
  11506. is( '1024.000 PiB', bytes_display_string_bin( 1_152_921_504_606_846_975 ), 'bytes_display_string_bin: 1_152_921_504_606_846_975 => 1024.000 PiB' ) ;
  11507. is( '1024.000 PiB', bytes_display_string_bin( 1_152_921_504_606_846_976 ), 'bytes_display_string_bin: 1_152_921_504_606_846_976 => 1024.000 PiB' ) ;
  11508. is( '1048576.000 PiB', bytes_display_string_bin( 1_180_591_620_717_411_303_424 ), 'bytes_display_string_bin: 1_180_591_620_717_411_303_424 => 1048576.000 PiB' ) ;
  11509. note( bytes_display_string_bin( 1_180_591_620_717_411_303_424 ) ) ;
  11510. note( bytes_display_string_bin( 3_000_000_000 ) ) ;
  11511. note( 'Leaving tests_bytes_display_string_bin()' ) ;
  11512. return ;
  11513. }
  11514. sub bytes_display_string_bin
  11515. {
  11516. my ( $bytes ) = @_ ;
  11517. my $readable_value = q{} ;
  11518. if ( ! defined( $bytes ) ) {
  11519. return( 'NA' ) ;
  11520. }
  11521. if ( not match_number( $bytes ) ) {
  11522. return( 'NA' ) ;
  11523. }
  11524. SWITCH: {
  11525. if ( abs( $bytes ) < ( 1000 * $KIBI ) ) {
  11526. $readable_value = mysprintf( '%.3f KiB', $bytes / $KIBI) ;
  11527. last SWITCH ;
  11528. }
  11529. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI ) ) {
  11530. $readable_value = mysprintf( '%.3f MiB', $bytes / ($KIBI * $KIBI) ) ;
  11531. last SWITCH ;
  11532. }
  11533. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI) ) {
  11534. $readable_value = mysprintf( '%.3f GiB', $bytes / ($KIBI * $KIBI * $KIBI) ) ;
  11535. last SWITCH ;
  11536. }
  11537. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI * $KIBI) ) {
  11538. $readable_value = mysprintf( '%.3f TiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI) ) ;
  11539. last SWITCH ;
  11540. } else {
  11541. $readable_value = mysprintf( '%.3f PiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI * $KIBI) ) ;
  11542. }
  11543. # if you have exabytes (EiB) of email to transfer, you have too much email!
  11544. }
  11545. #myprint( "$bytes = $readable_value\n" ) ;
  11546. return( $readable_value ) ;
  11547. }
  11548. sub tests_bytes_display_string_dec
  11549. {
  11550. note( 'Entering tests_bytes_display_string_dec()' ) ;
  11551. is( 'NA', bytes_display_string_dec( ), 'bytes_display_string_dec: no args => NA' ) ;
  11552. is( 'NA', bytes_display_string_dec( undef ), 'bytes_display_string_dec: undef => NA' ) ;
  11553. is( 'NA', bytes_display_string_dec( 'blabla' ), 'bytes_display_string_dec: blabla => NA' ) ;
  11554. is( '0 bytes', bytes_display_string_dec( 0 ), 'bytes_display_string_dec: 0 => 0 bytes' ) ;
  11555. is( '1 bytes', bytes_display_string_dec( 1 ), 'bytes_display_string_dec: 1 => 1 bytes' ) ;
  11556. is( '10 bytes', bytes_display_string_dec( 10 ), 'bytes_display_string_dec: 10 => 10 bytes' ) ;
  11557. is( '999 bytes', bytes_display_string_dec( 999 ), 'bytes_display_string_dec: 999 => 999 bytes' ) ;
  11558. is( '1.000 KB', bytes_display_string_dec( 1000 ), 'bytes_display_string_dec: 1000 => 1.000 KB' ) ;
  11559. is( '1.001 KB', bytes_display_string_dec( 1001 ), 'bytes_display_string_dec: 1000 => 1.1001 KB' ) ;
  11560. is( '999.999 KB', bytes_display_string_dec( 999_999 ), 'bytes_display_string_dec: 999_999 => 999.999 KB' ) ;
  11561. is( '1.000 MB', bytes_display_string_dec( 1_000_000 ), 'bytes_display_string_dec: 1_000_000 => 1.000 MB' ) ;
  11562. is( '1.000 MB', bytes_display_string_dec( 1_000_500 ), 'bytes_display_string_dec: 1_000_500 => 1.000 MB' ) ;
  11563. is( '1.001 MB', bytes_display_string_dec( 1_000_501 ), 'bytes_display_string_dec: 1_000_501 => 1.001 MB' ) ;
  11564. is( '999.999 MB', bytes_display_string_dec( 999_999_000 ), 'bytes_display_string_dec: 999_999_000 => 999.999 MB' ) ;
  11565. is( '999.999 MB', bytes_display_string_dec( 999_999_499 ), 'bytes_display_string_dec: 999_999_499 => 999.999 MB' ) ;
  11566. is( '1.000 GB', bytes_display_string_dec( 999_999_500 ), 'bytes_display_string_dec: 999_999_500 => 1.000 GB' ) ;
  11567. is( '1.000 GB', bytes_display_string_dec( 1_000_000_000 ), 'bytes_display_string_dec: 1_000_000_000 => 1.000 GB' ) ;
  11568. is( '1.000 GB', bytes_display_string_dec( 1_000_500_000 ), 'bytes_display_string_dec: 1_000_500_000 => 1.000 GB' ) ;
  11569. is( '1.001 GB', bytes_display_string_dec( 1_000_500_001 ), 'bytes_display_string_dec: 1_000_501_000 => 1.001 GB' ) ;
  11570. is( '999.999 GB', bytes_display_string_dec( 999_999_000_000 ), 'bytes_display_string_dec: 999_999_000_000 => 999.999 GB' ) ;
  11571. is( '999.999 GB', bytes_display_string_dec( 999_999_499_999 ), 'bytes_display_string_dec: 999_999_499_999 => 999.999 GB' ) ;
  11572. is( '1.000 TB', bytes_display_string_dec( 999_999_500_000 ), 'bytes_display_string_dec: 999_999_500_000 => 1.000 TB' ) ;
  11573. is( '1.000 TB', bytes_display_string_dec( 1_000_000_000_000 ), 'bytes_display_string_dec: 1_000_000_000_000 => 1.000 TB' ) ;
  11574. is( '1.000 TB', bytes_display_string_dec( 1_000_500_000_000 ), 'bytes_display_string_dec: 1_000_500_000_000 => 1.000 TB' ) ;
  11575. is( '1.001 TB', bytes_display_string_dec( 1_000_500_000_001 ), 'bytes_display_string_dec: 1_000_500_000_000 => 1.000 TB' ) ;
  11576. is( '999.999 TB', bytes_display_string_dec( 999_999_000_000_000 ), 'bytes_display_string_dec: 999_999_000_000_000 => 999.999 TB' ) ;
  11577. is( '999.999 TB', bytes_display_string_dec( 999_999_499_999_999 ), 'bytes_display_string_dec: 999_999_499_999_999 => 999.999 TB' ) ;
  11578. is( '1.000 PB', bytes_display_string_dec( 999_999_500_000_000 ), 'bytes_display_string_dec: 999_999_500_000_000 => 1.000 PB' ) ;
  11579. is( '3.000 GB', bytes_display_string_dec( 3_000_000_000 ), 'bytes_display_string_dec: 3_000_000_000 => 3.000 GB' ) ;
  11580. note( 'Leaving tests_bytes_display_string_dec()' ) ;
  11581. return ;
  11582. }
  11583. sub bytes_display_string_dec
  11584. {
  11585. my ( $bytes ) = @_ ;
  11586. my $readable_value = q{} ;
  11587. if ( ! defined( $bytes ) ) {
  11588. return( 'NA' ) ;
  11589. }
  11590. if ( not match_number( $bytes ) ) {
  11591. return( 'NA' ) ;
  11592. }
  11593. SWITCH: {
  11594. if ( abs( $bytes ) < ( 1000 ) ) {
  11595. $readable_value = mysprintf( '%.0f bytes', $bytes ) ;
  11596. last SWITCH ;
  11597. }
  11598. if ( abs( $bytes ) < ( 1000**2 ) ) {
  11599. $readable_value = mysprintf( '%.3f KB', $bytes / 1000 ) ;
  11600. last SWITCH ;
  11601. }
  11602. if ( abs( $bytes ) < ( 999_999_500 ) ) {
  11603. $readable_value = mysprintf( '%.3f MB', $bytes / ( 1000**2 ) ) ;
  11604. last SWITCH ;
  11605. }
  11606. if ( abs( $bytes ) < ( 999_999_500_000 ) ) {
  11607. $readable_value = mysprintf( '%.3f GB', $bytes / ( 1000**3 ) ) ;
  11608. last SWITCH ;
  11609. }
  11610. if ( abs( $bytes ) < ( 999_999_500_000_000 ) ) {
  11611. $readable_value = mysprintf( '%.3f TB', $bytes / ( 1000**4 ) ) ;
  11612. last SWITCH ;
  11613. } else {
  11614. $readable_value = mysprintf( '%.3f PB', $bytes / ( 1000**5 ) ) ;
  11615. }
  11616. # if you have exabytes (EiB) of email to transfer, you have too much email!
  11617. }
  11618. #myprint( "$bytes = $readable_value\n" ) ;
  11619. return( $readable_value ) ;
  11620. }
  11621. sub tests_useheader_suggestion
  11622. {
  11623. note( 'Entering tests_useheader_suggestion()' ) ;
  11624. is( undef, useheader_suggestion( ), 'useheader_suggestion: no args => undef' ) ;
  11625. my $mysync = {} ;
  11626. $mysync->{ h1_nb_msg_noheader } = 0 ;
  11627. is( q{}, useheader_suggestion( $mysync ), 'useheader_suggestion: h1_nb_msg_noheader count null => no suggestion' ) ;
  11628. $mysync->{ h1_nb_msg_noheader } = 2 ;
  11629. is( q{in order to sync those 2 unidentified messages, add option --addheader}, useheader_suggestion( $mysync ),
  11630. 'useheader_suggestion: h1_nb_msg_noheader count 2 => suggestion of --addheader' ) ;
  11631. note( 'Leaving tests_useheader_suggestion()' ) ;
  11632. return ;
  11633. }
  11634. sub useheader_suggestion
  11635. {
  11636. my $mysync = shift ;
  11637. if ( ! defined $mysync->{ h1_nb_msg_noheader } )
  11638. {
  11639. return ;
  11640. }
  11641. elsif ( 1 <= $mysync->{ h1_nb_msg_noheader } )
  11642. {
  11643. return qq{in order to sync those $mysync->{ h1_nb_msg_noheader } unidentified messages, add option --addheader} ;
  11644. }
  11645. else
  11646. {
  11647. return q{} ;
  11648. }
  11649. return ;
  11650. }
  11651. sub do_and_print_stats
  11652. {
  11653. my $mysync = shift ;
  11654. if ( ! $mysync->{can_do_stats} ) {
  11655. return ;
  11656. }
  11657. my $timeend = time ;
  11658. my $timediff = $timeend - $mysync->{timestart} ;
  11659. my $timeend_str = localtimez( $timeend ) ;
  11660. my $cpu_time = cpu_time( $mysync ) ;
  11661. my $cpu_percent = cpu_percent( $mysync, $cpu_time, $timediff ) ;
  11662. my $cpu_percent_global = cpu_percent_global( $mysync, $cpu_percent ) ;
  11663. my $memory_consumption_at_end = memory_consumption( ) || 0 ;
  11664. my $memory_consumption_at_start = $mysync->{ memory_consumption_at_start } || 0 ;
  11665. my $memory_ratio = ( $mysync->{ biggest_message_transferred } ) ?
  11666. mysprintf( '%.1f', $memory_consumption_at_end / $mysync->{ biggest_message_transferred } ) : 'NA' ;
  11667. # my $useheader_suggestion = useheader_suggestion( $mysync ) ;
  11668. myprint( "++++ Statistics\n" ) ;
  11669. myprint( "Transfer started on : $mysync->{ timestart_str }\n" ) ;
  11670. myprint( "Transfer ended on : $timeend_str\n" ) ;
  11671. myprintf( "Transfer time : %.1f sec\n", $timediff ) ;
  11672. myprint( "Folders synced : $h1_folders_wanted_ct/$h1_folders_wanted_nb synced\n" ) ;
  11673. myprint( "Messages transferred : $mysync->{ nb_msg_transferred } " ) ;
  11674. myprint( "(could be $nb_msg_skipped_dry_mode without dry mode)" ) if ( $mysync->{dry} ) ;
  11675. myprint( "\n" ) ;
  11676. myprint( "Messages skipped : $mysync->{ nb_msg_skipped }\n" ) ;
  11677. myprint( "Messages found duplicate on host1 : $mysync->{ acc1 }->{ nb_msg_duplicate }\n" ) ;
  11678. myprint( "Messages found duplicate on host2 : $mysync->{ acc2 }->{ nb_msg_duplicate }\n" ) ;
  11679. myprint( "Messages found crossduplicate on host2 : $mysync->{ h2_nb_msg_crossdup }\n" ) ;
  11680. myprint( "Messages void (noheader) on host1 : $mysync->{ h1_nb_msg_noheader } ", useheader_suggestion( $mysync ), "\n" ) ;
  11681. myprint( "Messages void (noheader) on host2 : $h2_nb_msg_noheader\n" ) ;
  11682. nb_messages_in_1_not_in_2( $mysync ) ;
  11683. nb_messages_in_2_not_in_1( $mysync ) ;
  11684. myprintf( "Messages found in host1 not in host2 : %s messages\n", $mysync->{ nb_messages_in_1_not_in_2 } ) ;
  11685. myprintf( "Messages found in host2 not in host1 : %s messages\n", $mysync->{ nb_messages_in_2_not_in_1 } ) ;
  11686. myprint( "Messages deleted on host1 : $mysync->{ acc1 }->{ nb_msg_deleted }\n" ) ;
  11687. myprint( "Messages deleted on host2 : $mysync->{ acc2 }->{ nb_msg_deleted }\n" ) ;
  11688. myprintf( "Total bytes transferred : %s (%s)\n",
  11689. $mysync->{total_bytes_transferred},
  11690. bytes_display_string_bin( $mysync->{total_bytes_transferred} ) ) ;
  11691. myprintf( "Total bytes skipped : %s (%s)\n",
  11692. $mysync->{ total_bytes_skipped },
  11693. bytes_display_string_bin( $mysync->{ total_bytes_skipped } ) ) ;
  11694. $timediff ||= 1 ; # No division per 0
  11695. myprintf("Message rate : %.1f messages/s\n", $mysync->{nb_msg_transferred} / $timediff ) ;
  11696. myprintf("Average bandwidth rate : %.1f KiB/s\n", $mysync->{total_bytes_transferred} / $KIBI / $timediff ) ;
  11697. myprint( "Reconnections to host1 : $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT}\n" ) ;
  11698. myprint( "Reconnections to host2 : $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT}\n" ) ;
  11699. myprintf("Memory consumption at the end : %.1f MiB (started with %.1f MiB)\n",
  11700. $memory_consumption_at_end / $KIBI / $KIBI,
  11701. $memory_consumption_at_start / $KIBI / $KIBI ) ;
  11702. myprint( "Load end is : " . ( join( q{ }, loadavg( ) ) || 'unknown' ), " on $mysync->{cpu_number} cores\n" ) ;
  11703. myprint( "CPU time and %cpu : $cpu_time sec $cpu_percent %cpu $cpu_percent_global %allcpus\n" ) ;
  11704. myprintf("Biggest message transferred : %s bytes (%s)\n",
  11705. $mysync->{ biggest_message_transferred },
  11706. bytes_display_string_bin( $mysync->{ biggest_message_transferred } ) ) ;
  11707. myprint( "Memory/biggest message ratio : $memory_ratio\n" ) ;
  11708. if ( $mysync->{ foldersizesatend } and $mysync->{ foldersizes } ) {
  11709. my $nb_msg_start_diff = diff_or_NA( $mysync->{ h2_nb_msg_start }, $mysync->{ h1_nb_msg_start } ) ;
  11710. my $bytes_start_diff = diff_or_NA( $mysync->{ h2_bytes_start }, $mysync->{ h1_bytes_start } ) ;
  11711. myprintf("Start difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_start_diff,
  11712. $bytes_start_diff,
  11713. bytes_display_string_bin( $bytes_start_diff ) ) ;
  11714. my $nb_msg_end_diff = diff_or_NA( $h2_nb_msg_end, $h1_nb_msg_end ) ;
  11715. my $bytes_end_diff = diff_or_NA( $h2_bytes_end, $h1_bytes_end ) ;
  11716. myprintf("Final difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_end_diff,
  11717. $bytes_end_diff,
  11718. bytes_display_string_bin( $bytes_end_diff ) ) ;
  11719. }
  11720. comment_on_final_diff_in_1_not_in_2( $mysync ) ;
  11721. comment_on_final_diff_in_2_not_in_1( $mysync ) ;
  11722. myprint( "Detected $mysync->{nb_errors} errors\n\n" ) ;
  11723. myprint( $mysync->{ warn_release }, "\n" ) ;
  11724. myprint( homepage( ), "\n" ) ;
  11725. return ;
  11726. }
  11727. sub diff_or_NA
  11728. {
  11729. my( $n1, $n2 ) = @ARG ;
  11730. if ( not defined $n1 or not defined $n2 ) {
  11731. return 'NA' ;
  11732. }
  11733. if ( not match_number( $n1 )
  11734. or not match_number( $n2 ) ) {
  11735. return 'NA' ;
  11736. }
  11737. return( $n1 - $n2 ) ;
  11738. }
  11739. sub match_number
  11740. {
  11741. my $n = shift @ARG ;
  11742. if ( not defined $n ) {
  11743. return 0 ;
  11744. }
  11745. if ( $n =~ /[0-9]+\.?[0-9]?/x ) {
  11746. return 1 ;
  11747. }
  11748. else {
  11749. return 0 ;
  11750. }
  11751. }
  11752. sub tests_match_number
  11753. {
  11754. note( 'Entering tests_match_number()' ) ;
  11755. is( 0, match_number( ), 'match_number: no parameters => 0' ) ;
  11756. is( 0, match_number( undef ), 'match_number: undef => 0' ) ;
  11757. is( 0, match_number( 'blabla' ), 'match_number: blabla => 0' ) ;
  11758. is( 1, match_number( 0 ), 'match_number: 0 => 1' ) ;
  11759. is( 1, match_number( 1 ), 'match_number: 1 => 1' ) ;
  11760. is( 1, match_number( 1.0 ), 'match_number: 1.0 => 1' ) ;
  11761. is( 1, match_number( 0.0 ), 'match_number: 0.0 => 1' ) ;
  11762. note( 'Leaving tests_match_number()' ) ;
  11763. return ;
  11764. }
  11765. sub tests_diff_or_NA
  11766. {
  11767. note( 'Entering tests_diff_or_NA()' ) ;
  11768. is( 'NA', diff_or_NA( ), 'diff_or_NA: no parameters => NA' ) ;
  11769. is( 'NA', diff_or_NA( undef ), 'diff_or_NA: undef => NA' ) ;
  11770. is( 'NA', diff_or_NA( undef, undef ), 'diff_or_NA: undef undef => NA' ) ;
  11771. is( 'NA', diff_or_NA( undef, 1 ), 'diff_or_NA: undef 1 => NA' ) ;
  11772. is( 'NA', diff_or_NA( 1, undef ), 'diff_or_NA: 1 undef => NA' ) ;
  11773. is( 'NA', diff_or_NA( 'blabla', 1 ), 'diff_or_NA: blabla 1 => NA' ) ;
  11774. is( 'NA', diff_or_NA( 1, 'blabla' ), 'diff_or_NA: 1 blabla => NA' ) ;
  11775. is( 0, diff_or_NA( 1, 1 ), 'diff_or_NA: 1 1 => 0' ) ;
  11776. is( 1, diff_or_NA( 1, 0 ), 'diff_or_NA: 1 0 => 1' ) ;
  11777. is( -1, diff_or_NA( 0, 1 ), 'diff_or_NA: 0 1 => -1' ) ;
  11778. is( 0, diff_or_NA( 1.0, 1 ), 'diff_or_NA: 1.0 1 => 0' ) ;
  11779. is( 1, diff_or_NA( 1.0, 0 ), 'diff_or_NA: 1.0 0 => 1' ) ;
  11780. is( -1, diff_or_NA( 0, 1.0 ), 'diff_or_NA: 0 1.0 => -1' ) ;
  11781. note( 'Leaving tests_diff_or_NA()' ) ;
  11782. return ;
  11783. }
  11784. sub homepage
  11785. {
  11786. return( 'Homepage: https://imapsync.lamiral.info/' ) ;
  11787. }
  11788. sub load_modules
  11789. {
  11790. if ( $sync->{ssl1}
  11791. or $sync->{ssl2}
  11792. or $sync->{tls1}
  11793. or $sync->{tls2}) {
  11794. if ( $sync->{inet4} ) {
  11795. IO::Socket::SSL->import( 'inet4' ) ;
  11796. }
  11797. if ( $sync->{inet6} ) {
  11798. IO::Socket::SSL->import( 'inet6' ) ;
  11799. }
  11800. }
  11801. return ;
  11802. }
  11803. # Globals: $skipsize $wholeheaderifneeded
  11804. sub parse_header_msg
  11805. {
  11806. my ( $mysync, $imap, $m_uid, $s_heads, $s_fir, $side, $s_hash ) = @_ ;
  11807. my $head = $s_heads->{$m_uid} ;
  11808. my $headnum = scalar keys %{ $head } ;
  11809. $mysync->{ debug } and myprint( "$side: uid $m_uid number of headers, pass one: ", $headnum, "\n" ) ;
  11810. if ( ( ! $headnum ) and ( $wholeheaderifneeded ) ){
  11811. $mysync->{ debug } and myprint( "$side: uid $m_uid no header by parse_headers so taking whole header with BODY.PEEK[HEADER]\n" ) ;
  11812. $imap->fetch($m_uid, 'BODY.PEEK[HEADER]' ) ;
  11813. my $whole_header = $imap->_transaction_literals ;
  11814. #myprint( $whole_header ) ;
  11815. $head = decompose_header( $whole_header ) ;
  11816. $headnum = scalar keys %{ $head } ;
  11817. $mysync->{ debug } and myprint( "$side: uid $m_uid number of headers, pass two: ", $headnum, "\n" ) ;
  11818. }
  11819. #myprint( Data::Dumper->Dump( [ $head, \%useheader ] ) ) ;
  11820. my $headstr = header_construct( $mysync, $head, $side, $m_uid ) ;
  11821. if ( ( ! $headstr ) and ( $mysync->{addheader} ) and ( $side eq 'Host1' ) ) {
  11822. my $header = add_header( $m_uid ) ;
  11823. $mysync->{ debug } and myprint( "$side: uid $m_uid no header found so adding our own [$header]\n" ) ;
  11824. $headstr .= uc $header ;
  11825. $s_fir->{$m_uid}->{NO_HEADER} = 1;
  11826. }
  11827. return if ( ! $headstr ) ;
  11828. my $size = $s_fir->{$m_uid}->{'RFC822.SIZE'} ;
  11829. my $flags = $s_fir->{$m_uid}->{'FLAGS'} ;
  11830. my $idate = $s_fir->{$m_uid}->{'INTERNALDATE'} ;
  11831. $size = length $headstr unless ( $size ) ;
  11832. my $m_md5 = md5_base64( $headstr ) ;
  11833. my $key ;
  11834. if ( $skipsize ) {
  11835. $key = "$m_md5";
  11836. }
  11837. else {
  11838. $key = "$m_md5:$size";
  11839. }
  11840. if ( exists $s_hash->{"$key"} )
  11841. {
  11842. # 0 return code is used to identify duplicate message hash
  11843. my $dup_ref = $s_hash->{"$key"}->{'U'} ;
  11844. my $num = scalar( @{ $dup_ref } ) ;
  11845. push( @{ $dup_ref }, $m_uid ) ;
  11846. my $keydup = "$key#$num" ;
  11847. $mysync->{ debug } and myprint( "$side: uid $m_uid sig $keydup size $size idate $idate dup @{ $dup_ref }\n" ) ;
  11848. if ( $mysync->{ syncduplicates } )
  11849. {
  11850. $s_hash->{"$keydup"}{'5'} = $m_md5 ;
  11851. $s_hash->{"$keydup"}{'s'} = $size ;
  11852. $s_hash->{"$keydup"}{'D'} = $idate ;
  11853. $s_hash->{"$keydup"}{'F'} = $flags ;
  11854. $s_hash->{"$keydup"}{'m'} = $m_uid ;
  11855. }
  11856. return 0 ;
  11857. }
  11858. else
  11859. {
  11860. $s_hash->{"$key"}{'5'} = $m_md5 ;
  11861. $s_hash->{"$key"}{'s'} = $size ;
  11862. $s_hash->{"$key"}{'D'} = $idate ;
  11863. $s_hash->{"$key"}{'F'} = $flags ;
  11864. $s_hash->{"$key"}{'m'} = $m_uid ;
  11865. $s_hash->{"$key"}{'U'} = [ $m_uid ] ; # ? or [ ] ?
  11866. $mysync->{ debug } and myprint( "$side: uid $m_uid sig $key size $size idate $idate\n" ) ;
  11867. return( 1 ) ;
  11868. }
  11869. # we should not be here
  11870. return ;
  11871. }
  11872. sub tests_header_construct
  11873. {
  11874. note( 'Entering tests_header_construct()' ) ;
  11875. is( undef, header_construct( ), 'header_construct: no args => undef' ) ;
  11876. my $mysync = {} ;
  11877. my $head = {
  11878. 'key1' => [ 'val1_key1' ]
  11879. } ;
  11880. is( undef, header_construct( $mysync, $head, 'Host1', '1' ), 'header_construct: key1 val1_key1 no useheader => undef' ) ;
  11881. $mysync->{useheader}->{ 'KEY1' } = 1 ;
  11882. is( 'KEY1: VAL1_KEY1', header_construct( $mysync, $head, 'Host1', '1' ), 'header_construct: key1 val1_key1 => KEY1: VAL1_KEY1' ) ;
  11883. $head = {
  11884. 'key1' => [ 'val1_key1', 'val3_key1', 'val2_key1' ]
  11885. } ;
  11886. is( 'KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1', header_construct( $mysync, $head, 'Host1', '1' ),
  11887. 'header_construct: key1 val1_key1 val3_key1 val2_key1 => KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1' ) ;
  11888. $head = {
  11889. 'key1' => [ 'val1_key1', 'val3_key1', ' val2_key1' ]
  11890. } ;
  11891. is( 'KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1', header_construct( $mysync, $head, 'Host1', '1' ),
  11892. 'header_construct: key1 val1_key1 val3_key1 val2_key1 => KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1' ) ;
  11893. $mysync->{useheader}->{ 'ALL' } = 1 ;
  11894. is( 'KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1', header_construct( $mysync, $head, 'Host1', '1' ),
  11895. 'header_construct: key1 val1_key1 val3_key1 val2_key1 useheader ALL => KEY1: VAL1_KEY1KEY1: VAL2_KEY1KEY1: VAL3_KEY1' ) ;
  11896. $mysync->{skipheader} = 'key1' ;
  11897. is( undef, header_construct( $mysync, $head, 'Host1', '1' ),
  11898. 'header_construct: key1 val1_key1 val3_key1 val2_key1 useheader ALL => undef' ) ;
  11899. $head = {
  11900. 'key1' => [ 'val1_key1', 'val3_key1', ' val2_key1' ],
  11901. 'key2' => [ 'val1_key2', 'val3_key2', ' val2_key2' ]
  11902. } ;
  11903. is( 'KEY2: VAL1_KEY2KEY2: VAL2_KEY2KEY2: VAL3_KEY2', header_construct( $mysync, $head, 'Host1', '1' ),
  11904. 'header_construct: ... useheader ALL skipheader key1 => KEY2: VAL1_KEY2KEY2: VAL2_KEY2KEY2: VAL3_KEY2' ) ;
  11905. note( 'Leaving tests_header_construct()' ) ;
  11906. return ;
  11907. }
  11908. # No global in header_construct
  11909. sub header_construct
  11910. {
  11911. my( $mysync, $head, $side, $m_uid ) = @_ ;
  11912. my @headstr ;
  11913. foreach my $h ( sort keys %{ $head } ) {
  11914. next if ( not ( exists $mysync->{useheader}->{ uc $h } )
  11915. and ( not exists $mysync->{useheader}->{ 'ALL' } )
  11916. ) ;
  11917. foreach my $val ( @{$head->{$h}} ) {
  11918. my $H = header_line_normalize( $h, $val ) ;
  11919. # show stuff in debug mode
  11920. $mysync->{ debug } and myprint( "$side uid $m_uid header [$H]", "\n" ) ;
  11921. if ( $mysync->{skipheader} and $H =~ m/$mysync->{skipheader}/xi) {
  11922. $mysync->{ debug } and myprint( "$side uid $m_uid skipping header [$H]\n" ) ;
  11923. next ;
  11924. }
  11925. push @headstr, $H ;
  11926. }
  11927. }
  11928. my $headstr = join( '', sort @headstr ) || undef ;
  11929. return( $headstr ) ;
  11930. }
  11931. sub header_line_normalize
  11932. {
  11933. my( $header_key, $header_val ) = @_ ;
  11934. # no 8-bit data in headers !
  11935. $header_val =~ s/[\x80-\xff]/X/xog;
  11936. # change tabulations to space (Gmail bug on with "Received:" on multilines)
  11937. $header_val =~ s/\t/\ /xgo ;
  11938. # remove the first blanks ( dbmail bug? )
  11939. $header_val =~ s/^\s*//xo;
  11940. # remove the last blanks ( Gmail bug )
  11941. $header_val =~ s/\s*$//xo;
  11942. # remove successive blanks ( Mailenable does it )
  11943. $header_val =~ s/\s+/ /xgo;
  11944. # remove Message-Id value domain part ( Mailenable changes it )
  11945. if ( ( $messageidnodomain ) and ( 'MESSAGE-ID' eq uc $header_key ) ) { $header_val =~ s/^([^@]+).*$/$1/xo ; }
  11946. # and uppercase header line
  11947. # (dbmail and dovecot)
  11948. my $header_line = uc "$header_key: $header_val" ;
  11949. return( $header_line ) ;
  11950. }
  11951. sub tests_header_line_normalize
  11952. {
  11953. note( 'Entering tests_header_line_normalize()' ) ;
  11954. ok( ': ' eq header_line_normalize( q{}, q{} ), 'header_line_normalize: empty args' ) ;
  11955. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', 'vvv' ), 'header_line_normalize: hhh vvv ' ) ;
  11956. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', ' vvv' ), 'header_line_normalize: remove first blancs' ) ;
  11957. ok( 'HHH: AA BB CCC D' eq header_line_normalize( 'hhh', 'aa bb ccc d' ), 'header_line_normalize: remove succesive blanks' ) ;
  11958. ok( 'HHH: AA BB CCC' eq header_line_normalize( 'hhh', 'aa bb ccc ' ), 'header_line_normalize: remove last blanks' ) ;
  11959. ok( 'HHH: VVV XX YY' eq header_line_normalize( 'hhh', "vvv\t\txx\tyy" ), 'header_line_normalize: tabs' ) ;
  11960. ok( 'HHH: XABX' eq header_line_normalize( 'hhh', "\x80AB\xff" ), 'header_line_normalize: 8bit' ) ;
  11961. note( 'Leaving tests_header_line_normalize()' ) ;
  11962. return ;
  11963. }
  11964. sub tests_firstline
  11965. {
  11966. note( 'Entering tests_firstline()' ) ;
  11967. is( q{}, firstline( 'W/tmp/tests/noexist.txt' ), 'firstline: getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  11968. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'firstline: mkpath W/tmp/tests/' ) ;
  11969. is( "blabla\n" , string_to_file( "blabla\n", 'W/tmp/tests/firstline.txt' ), 'firstline: put blabla in W/tmp/tests/firstline.txt' ) ;
  11970. is( 'blabla' , firstline( 'W/tmp/tests/firstline.txt' ), 'firstline: get blabla from W/tmp/tests/firstline.txt' ) ;
  11971. is( q{} , string_to_file( q{}, 'W/tmp/tests/firstline2.txt' ), 'firstline: put empty string in W/tmp/tests/firstline2.txt' ) ;
  11972. is( q{} , firstline( 'W/tmp/tests/firstline2.txt' ), 'firstline: get empty string from W/tmp/tests/firstline2.txt' ) ;
  11973. is( "\n" , string_to_file( "\n", 'W/tmp/tests/firstline3.txt' ), 'firstline: put CR in W/tmp/tests/firstline3.txt' ) ;
  11974. is( q{} , firstline( 'W/tmp/tests/firstline3.txt' ), 'firstline: get empty string from W/tmp/tests/firstline3.txt' ) ;
  11975. 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' ) ;
  11976. is( 'blabla' , firstline( 'W/tmp/tests/firstline4.txt' ), 'firstline: get blabla from W/tmp/tests/firstline4.txt' ) ;
  11977. note( 'Leaving tests_firstline()' ) ;
  11978. return ;
  11979. }
  11980. sub firstline
  11981. {
  11982. # extract the first line of a file (without \n)
  11983. # return empty string if error or empty string
  11984. my $file = shift ;
  11985. my $line ;
  11986. $line = nthline( $file, 1 ) ;
  11987. return $line ;
  11988. }
  11989. sub tests_secondline
  11990. {
  11991. note( 'Entering tests_secondline()' ) ;
  11992. is( q{}, secondline( 'W/tmp/tests/noexist.txt' ), 'secondline: getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  11993. is( q{}, secondline( 'W/tmp/tests/noexist.txt', 2 ), 'secondline: 2nd getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  11994. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'secondline: mkpath W/tmp/tests/' ) ;
  11995. 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' ) ;
  11996. is( 'L2' , secondline( 'W/tmp/tests/secondline.txt' ), 'secondline: get L2 from W/tmp/tests/secondline.txt' ) ;
  11997. note( 'Leaving tests_secondline()' ) ;
  11998. return ;
  11999. }
  12000. sub secondline
  12001. {
  12002. # extract the second line of a file (without \n)
  12003. # return empty string if error or empty string
  12004. my $file = shift ;
  12005. my $line ;
  12006. $line = nthline( $file, 2 ) ;
  12007. return $line ;
  12008. }
  12009. sub tests_nthline
  12010. {
  12011. note( 'Entering tests_nthline()' ) ;
  12012. is( q{}, nthline( 'W/tmp/tests/noexist.txt' ), 'nthline: getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  12013. is( q{}, nthline( 'W/tmp/tests/noexist.txt', 2 ), 'nthline: 2nd getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  12014. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'nthline: mkpath W/tmp/tests/' ) ;
  12015. 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' ) ;
  12016. is( 'L3' , nthline( 'W/tmp/tests/nthline.txt', 3 ), 'nthline: get L3 from W/tmp/tests/nthline.txt' ) ;
  12017. note( 'Leaving tests_nthline()' ) ;
  12018. return ;
  12019. }
  12020. sub nthline
  12021. {
  12022. # extract the nth line of a file (without \n)
  12023. # return empty string if error or empty string
  12024. my $file = shift ;
  12025. my $num = shift ;
  12026. if ( ! all_defined( $file, $num ) ) { return q{} ; }
  12027. my $line ;
  12028. $line = ( file_to_array( $file ) )[$num - 1] ;
  12029. if ( ! defined $line )
  12030. {
  12031. return q{} ;
  12032. }
  12033. else
  12034. {
  12035. chomp $line ;
  12036. return $line ;
  12037. }
  12038. }
  12039. sub tests_file_to_array
  12040. {
  12041. note( 'Entering tests_file_to_array()' ) ;
  12042. is( undef, file_to_array( ), 'file_to_array: no args => undef' ) ;
  12043. is( undef, file_to_array( '/noexist' ), 'file_to_array: /noexist => undef' ) ;
  12044. is( undef, file_to_array( '/' ), 'file_to_array: reading a directory => undef' ) ;
  12045. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'file_to_array: mkpath W/tmp/tests/' ) ;
  12046. 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' ) ;
  12047. 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' ) ;
  12048. note( 'Leaving tests_file_to_array()' ) ;
  12049. return ;
  12050. }
  12051. sub file_to_array
  12052. {
  12053. my( $file ) = shift ;
  12054. if ( ! $file ) { return ; }
  12055. if ( ! -e $file ) { return ; }
  12056. if ( ! -f $file ) { return ; }
  12057. if ( ! -r $file ) { return ; }
  12058. my @string ;
  12059. if ( open my $FILE, '<', $file )
  12060. {
  12061. @string = <$FILE> ;
  12062. close $FILE ;
  12063. return( @string ) ;
  12064. }
  12065. else
  12066. {
  12067. myprint( "Error reading file $file : $OS_ERROR\n" ) ;
  12068. return ;
  12069. }
  12070. }
  12071. sub tests_file_to_string
  12072. {
  12073. note( 'Entering tests_file_to_string()' ) ;
  12074. is( undef, file_to_string( ), 'file_to_string: no args => undef' ) ;
  12075. is( undef, file_to_string( '/noexist' ), 'file_to_string: /noexist => undef' ) ;
  12076. is( undef, file_to_string( '/' ), 'file_to_string: reading a directory => undef' ) ;
  12077. ok( file_to_string( $PROGRAM_NAME ), 'file_to_string: reading myself' ) ;
  12078. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'file_to_string: mkpath W/tmp/tests/' ) ;
  12079. is( 'lilili', string_to_file( 'lilili', 'W/tmp/tests/canbewritten' ), 'file_to_string: string_to_file filling W/tmp/tests/canbewritten with lilili' ) ;
  12080. is( 'lilili', file_to_string( 'W/tmp/tests/canbewritten' ), 'file_to_string: reading W/tmp/tests/canbewritten is lilili' ) ;
  12081. is( q{}, string_to_file( q{}, 'W/tmp/tests/empty' ), 'file_to_string: string_to_file filling W/tmp/tests/empty with empty string' ) ;
  12082. is( q{}, file_to_string( 'W/tmp/tests/empty' ), 'file_to_string: reading W/tmp/tests/empty is empty' ) ;
  12083. note( 'Leaving tests_file_to_string()' ) ;
  12084. return ;
  12085. }
  12086. sub file_to_string
  12087. {
  12088. my $file = shift ;
  12089. if ( ! $file ) { return ; }
  12090. if ( ! -e $file ) { return ; }
  12091. if ( ! -f $file ) { return ; }
  12092. if ( ! -r $file ) { return ; }
  12093. return( join q{}, file_to_array( $file ) ) ;
  12094. }
  12095. sub tests_string_to_file
  12096. {
  12097. note( 'Entering tests_string_to_file()' ) ;
  12098. is( undef, string_to_file( ), 'string_to_file: no args => undef' ) ;
  12099. is( undef, string_to_file( 'lalala' ), 'string_to_file: one arg => undef' ) ;
  12100. is( undef, string_to_file( 'lalala', '.' ), 'string_to_file: writing a directory => undef' ) ;
  12101. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'string_to_file: mkpath W/tmp/tests/' ) ;
  12102. is( 'lalala', string_to_file( 'lalala', 'W/tmp/tests/canbewritten' ), 'string_to_file: W/tmp/tests/canbewritten with lalala' ) ;
  12103. is( q{}, string_to_file( q{}, 'W/tmp/tests/empty' ), 'string_to_file: W/tmp/tests/empty with empty string' ) ;
  12104. SKIP: {
  12105. Readonly my $NB_UNX_tests_string_to_file => 1 ;
  12106. skip( 'Not on Unix non-root', $NB_UNX_tests_string_to_file ) if ('MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) ;
  12107. is( undef, string_to_file( 'lalala', '/cantouch' ), 'string_to_file: /cantouch denied => undef' ) ;
  12108. }
  12109. note( 'Leaving tests_string_to_file()' ) ;
  12110. return ;
  12111. }
  12112. sub string_to_file
  12113. {
  12114. my( $string, $file ) = @_ ;
  12115. if( ! defined $string ) { return ; }
  12116. if( ! defined $file ) { return ; }
  12117. if ( ! -e $file && ! -w dirname( $file ) ) {
  12118. myprint( "string_to_file: directory of $file is not writable\n" ) ;
  12119. return ;
  12120. }
  12121. if ( ! sysopen( FILE, $file, O_WRONLY|O_TRUNC|O_CREAT, 0600) ) {
  12122. myprint( "string_to_file: failure writing to $file with error: $OS_ERROR\n" ) ;
  12123. return ;
  12124. }
  12125. print FILE $string ;
  12126. close FILE ;
  12127. return $string ;
  12128. }
  12129. 0 and <<'MULTILINE_COMMENT' ;
  12130. This is a multiline comment.
  12131. Based on David Carter discussion, to do:
  12132. * Call parameters stay the same.
  12133. * Now always "return( $string, $error )". Descriptions below.
  12134. OK * Still capture STDOUT via "1> $output_tmpfile" to finish in $string and "return( $string, $error )"
  12135. OK * Now also capture STDERR via "2> $error_tmpfile" to finish in $error and "return( $string, $error )"
  12136. OK * in case of CHILD_ERROR, return( undef, $error )
  12137. and print $error, with folder/UID/maybeSubject context,
  12138. on console and at the end with the final error listing. Count this as a sync error.
  12139. * in case of good command, take final $string as is, unless void. In case $error with value then print it.
  12140. * in case of good command and final $string empty, consider it like CHILD_ERROR =>
  12141. return( undef, $error ) and print $error, with folder/UID/maybeSubject context,
  12142. on console and at the end with the final error listing. Count this as a sync error.
  12143. MULTILINE_COMMENT
  12144. # End of multiline comment.
  12145. sub pipemess
  12146. {
  12147. my ( $string, @commands ) = @_ ;
  12148. my $error = q{} ;
  12149. foreach my $command ( @commands ) {
  12150. my $input_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.inp.txt" ;
  12151. my $output_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.out.txt" ;
  12152. my $error_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.err.txt" ;
  12153. string_to_file( $string, $input_tmpfile ) ;
  12154. ` $command < $input_tmpfile 1> $output_tmpfile 2> $error_tmpfile ` ;
  12155. my $is_command_ko = $CHILD_ERROR ;
  12156. my $error_cmd = file_to_string( $error_tmpfile ) ;
  12157. chomp( $error_cmd ) ;
  12158. $string = file_to_string( $output_tmpfile ) ;
  12159. my $string_len = length( $string ) ;
  12160. unlink $input_tmpfile, $output_tmpfile, $error_tmpfile ;
  12161. if ( $is_command_ko or ( ! $string_len ) ) {
  12162. my $cmd_exit_value = $CHILD_ERROR >> 8 ;
  12163. my $cmd_end_signal = $CHILD_ERROR & 127 ;
  12164. my $signal_log = ( $cmd_end_signal ) ? " signal $cmd_end_signal and" : q{} ;
  12165. 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} ;
  12166. myprint( $error_log ) ;
  12167. if ( wantarray ) {
  12168. return @{ [ undef, $error_log ] }
  12169. }else{
  12170. return ;
  12171. }
  12172. }
  12173. if ( $error_cmd ) {
  12174. $error .= qq{STDERR of --pipemess "$command": $error_cmd\n} ;
  12175. myprint( qq{STDERR of --pipemess "$command": $error_cmd\n} ) ;
  12176. }
  12177. }
  12178. #myprint( "[$string]\n" ) ;
  12179. if ( wantarray ) {
  12180. return ( $string, $error ) ;
  12181. }else{
  12182. return $string ;
  12183. }
  12184. }
  12185. sub tests_pipemess
  12186. {
  12187. note( 'Entering tests_pipemess()' ) ;
  12188. SKIP: {
  12189. Readonly my $NB_WIN_tests_pipemess => 3 ;
  12190. skip( 'Not on MSWin32', $NB_WIN_tests_pipemess ) if ('MSWin32' ne $OSNAME) ;
  12191. # Windows
  12192. # "type" command does not accept redirection of STDIN with <
  12193. # "sort" does
  12194. ok( "nochange\n" eq pipemess( 'nochange', 'sort' ), 'pipemess: nearly no change by sort' ) ;
  12195. ok( "nochange2\n" eq pipemess( 'nochange2', qw( sort sort ) ), 'pipemess: nearly no change by sort,sort' ) ;
  12196. # command not found
  12197. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  12198. ok( ! defined( pipemess( q{}, 'cacaprout' ) ), 'pipemess: command not found' ) ;
  12199. } ;
  12200. my ( $stringT, $errorT ) ;
  12201. SKIP: {
  12202. Readonly my $NB_UNX_tests_pipemess => 25 ;
  12203. skip( 'Not on Unix', $NB_UNX_tests_pipemess ) if ('MSWin32' eq $OSNAME) ;
  12204. # Unix
  12205. ok( 'nochange' eq pipemess( 'nochange', 'cat' ), 'pipemess: no change by cat' ) ;
  12206. ok( 'nochange2' eq pipemess( 'nochange2', 'cat', 'cat' ), 'pipemess: no change by cat,cat' ) ;
  12207. ok( " 1\tnumberize\n" eq pipemess( "numberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  12208. ok( " 1\tnumberize\n 2\tnumberize\n" eq pipemess( "numberize\nnumberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  12209. ok( "A\nB\nC\n" eq pipemess( "A\nC\nB\n", 'sort' ), 'pipemess: sort' ) ;
  12210. # command not found
  12211. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  12212. is( undef, pipemess( q{}, 'cacaprout' ), 'pipemess: command not found' ) ;
  12213. # success with true but no output at all
  12214. is( undef, pipemess( q{blabla}, 'true' ), 'pipemess: true but no output' ) ;
  12215. # failure with false and no output at all
  12216. is( undef, pipemess( q{blabla}, 'false' ), 'pipemess: false and no output' ) ;
  12217. # Failure since pipemess is not a real pipe, so first cat wait for standard input
  12218. is( q{blabla}, pipemess( q{blabla}, '( cat|cat ) ' ), 'pipemess: ok by ( cat|cat )' ) ;
  12219. ( $stringT, $errorT ) = pipemess( 'nochange', 'cat' ) ;
  12220. is( $stringT, 'nochange', 'pipemess: list context, no change by cat, string' ) ;
  12221. is( $errorT, q{}, 'pipemess: list context, no change by cat, no error' ) ;
  12222. ( $stringT, $errorT ) = pipemess( 'dontcare', 'true' ) ;
  12223. is( $stringT, undef, 'pipemess: list context, true but no output, string' ) ;
  12224. 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' ) ;
  12225. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false' ) ;
  12226. is( $stringT, undef, 'pipemess: list context, false and no output, string' ) ;
  12227. like( $errorT, qr{\QFailure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""\E}xm,
  12228. 'pipemess: list context, false and no output, error' ) ;
  12229. ( $stringT, $errorT ) = pipemess( 'dontcare', '/bin/echo -n blablabla' ) ;
  12230. is( $stringT, q{blablabla}, 'pipemess: list context, "echo -n blablabla", string' ) ;
  12231. is( $errorT, q{}, 'pipemess: list context, "echo blablabla", error' ) ;
  12232. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  12233. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla", string' ) ;
  12234. like( $errorT, qr{blablabla"}xm, 'pipemess: list context, "no output STDERR blablabla", error' ) ;
  12235. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )', 'false' ) ;
  12236. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla then false", string' ) ;
  12237. like( $errorT, qr{blablabla"}xm, 'pipemess: list context, "no output STDERR blablabla then false", error' ) ;
  12238. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  12239. is( $stringT, undef, 'pipemess: list context, "false then STDERR blablabla", string' ) ;
  12240. like( $errorT, qr{\QFailure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""\E}xm,
  12241. 'pipemess: list context, "false then STDERR blablabla", error' ) ;
  12242. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo rrrrr ; echo -n error_blablabla 3>&1 1>&2 2>&3 )' ) ;
  12243. like( $stringT, qr{rrrrr}xm, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", string' ) ;
  12244. like( $errorT, qr{STDERR.*error_blablabla}xm, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", error' ) ;
  12245. }
  12246. ( $stringT, $errorT ) = pipemess( 'dontcare', 'cacaprout' ) ;
  12247. is( $stringT, undef, 'pipemess: list context, cacaprout not found, string' ) ;
  12248. like( $errorT, qr{\QFailure: --pipemess command "cacaprout" ended with "0" characters exit value\E}xm,
  12249. 'pipemess: list context, cacaprout not found, error' ) ;
  12250. note( 'Leaving tests_pipemess()' ) ;
  12251. return ;
  12252. }
  12253. sub tests_is_a_release_number
  12254. {
  12255. note( 'Entering tests_is_a_release_number()' ) ;
  12256. is( undef, is_a_release_number( ), 'is_a_release_number: no args => undef' ) ;
  12257. ok( is_a_release_number( $RELEASE_NUMBER_EXAMPLE_1 ), 'is_a_release_number 1.351' ) ;
  12258. ok( is_a_release_number( $RELEASE_NUMBER_EXAMPLE_2 ), 'is_a_release_number 42.4242' ) ;
  12259. ok( is_a_release_number( imapsync_version( $sync ) ), 'is_a_release_number imapsync_version( )' ) ;
  12260. ok( ! is_a_release_number( 'blabla' ), '! is_a_release_number blabla' ) ;
  12261. note( 'Leaving tests_is_a_release_number()' ) ;
  12262. return ;
  12263. }
  12264. sub is_a_release_number
  12265. {
  12266. my $number = shift ;
  12267. if ( ! defined $number ) { return ; }
  12268. return( $number =~ m{^\d+\.\d+$}xo ) ;
  12269. }
  12270. sub imapsync_version_public
  12271. {
  12272. my $local_version = imapsync_version( $sync ) ;
  12273. my $imapsync_basename = imapsync_basename( ) ;
  12274. my $context = imapsync_context( ) ;
  12275. my $agent_info = "$OSNAME system, perl "
  12276. . mysprintf( '%vd', $PERL_VERSION)
  12277. . ", Mail::IMAPClient $Mail::IMAPClient::VERSION"
  12278. . " $imapsync_basename"
  12279. . " $context" ;
  12280. my $sock = IO::Socket::INET->new(
  12281. PeerAddr => 'imapsync.lamiral.info',
  12282. PeerPort => 80,
  12283. Proto => 'tcp',
  12284. ) ;
  12285. return( 'unknown' ) if not $sock ;
  12286. print $sock
  12287. "GET /prj/imapsync/VERSION HTTP/1.0\r\n",
  12288. "User-Agent: imapsync/$local_version ($agent_info)\r\n",
  12289. "Host: ks.lamiral.info\r\n\r\n" ;
  12290. my @line = <$sock> ;
  12291. close $sock ;
  12292. my $last_release = $line[$LAST] ;
  12293. chomp $last_release ;
  12294. return( $last_release ) ;
  12295. }
  12296. sub not_long_imapsync_version_public
  12297. {
  12298. #myprint( "Entering not_long_imapsync_version_public\n" ) ;
  12299. my $fake = shift ;
  12300. if ( $fake ) { return $fake }
  12301. my $val ;
  12302. # Doesn't work with gethostbyname (see perlipc)
  12303. #local $SIG{ALRM} = sub { die "alarm\n" } ;
  12304. if ('MSWin32' eq $OSNAME) {
  12305. local $SIG{ALRM} = sub { die "alarm\n" } ;
  12306. }else{
  12307. POSIX::sigaction(SIGALRM,
  12308. POSIX::SigAction->new(sub { croak 'alarm' } ) )
  12309. or myprint( "Error setting SIGALRM handler: $OS_ERROR\n" ) ;
  12310. }
  12311. my $ret = eval {
  12312. alarm 3 ;
  12313. {
  12314. $val = imapsync_version_public( ) ;
  12315. #sleep 4 ;
  12316. #myprint( "End of imapsync_version_public\n" ) ;
  12317. }
  12318. alarm 0 ;
  12319. 1 ;
  12320. } ;
  12321. #myprint( "eval [$ret]\n" ) ;
  12322. if ( ( not $ret ) or $EVAL_ERROR ) {
  12323. #myprint( "$EVAL_ERROR" ) ;
  12324. if ($EVAL_ERROR =~ /alarm/) {
  12325. # timed out
  12326. return('timeout') ;
  12327. }else{
  12328. alarm 0 ;
  12329. return( 'unknown' ) ; # propagate unexpected errors
  12330. }
  12331. }else {
  12332. # Good!
  12333. return( $val ) ;
  12334. }
  12335. }
  12336. sub tests_not_long_imapsync_version_public
  12337. {
  12338. note( 'Entering tests_not_long_imapsync_version_public()' ) ;
  12339. is( 1, is_a_release_number( not_long_imapsync_version_public( ) ),
  12340. 'not_long_imapsync_version_public: public release is a number' ) ;
  12341. note( 'Leaving tests_not_long_imapsync_version_public()' ) ;
  12342. return ;
  12343. }
  12344. sub check_last_release
  12345. {
  12346. my $fake = shift ;
  12347. my $public_release = not_long_imapsync_version_public( $fake ) ;
  12348. $sync->{ debug } and myprint( "check_last_release: [$public_release]\n" ) ;
  12349. my $inline_help_when_on = '( Use --noreleasecheck to avoid this release check. )' ;
  12350. if ( $public_release eq 'unknown' ) {
  12351. return( 'Imapsync public release is unknown.' . $inline_help_when_on ) ;
  12352. }
  12353. if ( $public_release eq 'timeout' ) {
  12354. return( 'Imapsync public release is unknown (timeout).' . $inline_help_when_on ) ;
  12355. }
  12356. if ( ! is_a_release_number( $public_release ) ) {
  12357. return( "Imapsync public release is unknown ($public_release)." . $inline_help_when_on ) ;
  12358. }
  12359. my $imapsync_here = imapsync_version( $sync ) ;
  12360. if ( $public_release > $imapsync_here ) {
  12361. return( 'This imapsync is not up to date. ' . "( local $imapsync_here < official $public_release )" . $inline_help_when_on ) ;
  12362. }else{
  12363. return( 'This imapsync is up to date. ' . "( local $imapsync_here >= official $public_release )" . $inline_help_when_on ) ;
  12364. }
  12365. return( 'really unknown' ) ; # Should never arrive here
  12366. }
  12367. sub tests_check_last_release
  12368. {
  12369. note( 'Entering tests_check_last_release()' ) ;
  12370. diag( check_last_release( 1.1 ) ) ;
  12371. # \Q \E here to avoid putting \ before each space
  12372. like( check_last_release( 1.1 ), qr/\Qis up to date\E/mxs, 'check_last_release: up to date' ) ;
  12373. like( check_last_release( 1.1 ), qr/1\.1/mxs, 'check_last_release: up to date, include number' ) ;
  12374. diag( check_last_release( 999.999 ) ) ;
  12375. like( check_last_release( 999.999 ), qr/\Qnot up to date\E/mxs, 'check_last_release: not up to date' ) ;
  12376. like( check_last_release( 999.999 ), qr/999\.999/mxs, 'check_last_release: not up to date, include number' ) ;
  12377. like( check_last_release( 'unknown' ), qr/\QImapsync public release is unknown\E/mxs, 'check_last_release: unknown' ) ;
  12378. like( check_last_release( 'timeout' ), qr/\QImapsync public release is unknown (timeout)\E/mxs, 'check_last_release: timeout' ) ;
  12379. like( check_last_release( 'lalala' ), qr/\QImapsync public release is unknown (lalala)\E/mxs, 'check_last_release: lalala' ) ;
  12380. diag( check_last_release( ) ) ;
  12381. note( 'Leaving tests_check_last_release()' ) ;
  12382. return ;
  12383. }
  12384. sub tests_imapsync_context
  12385. {
  12386. note( 'Entering tests_imapsync_context()' ) ;
  12387. like( imapsync_context( ), qr/^CGI|^Docker|^DockerCGI|^Standard/, 'imapsync_context: CGI or Docker or DockerCGI or Standard' ) ;
  12388. note( 'Leaving tests_imapsync_context()' ) ;
  12389. return ;
  12390. }
  12391. sub imapsync_context
  12392. {
  12393. my $mysync = shift ;
  12394. my $context = q{} ;
  12395. if ( under_docker_context( $mysync ) && under_cgi_context( $mysync ) )
  12396. {
  12397. $context = 'DockerCGI' ;
  12398. }
  12399. elsif ( under_docker_context( $mysync ) )
  12400. {
  12401. $context = 'Docker' ;
  12402. }
  12403. elsif ( under_cgi_context( $mysync ) )
  12404. {
  12405. $context = 'CGI' ;
  12406. }
  12407. else
  12408. {
  12409. $context = 'Standard' ;
  12410. }
  12411. return $context ;
  12412. }
  12413. sub imapsync_version
  12414. {
  12415. my $mysync = shift ;
  12416. my $rcs = $mysync->{rcs} ;
  12417. my $version ;
  12418. $version = version_from_rcs( $rcs ) ;
  12419. return( $version ) ;
  12420. }
  12421. sub tests_version_from_rcs
  12422. {
  12423. note( 'Entering tests_version_from_rcs()' ) ;
  12424. is( undef, version_from_rcs( ), 'version_from_rcs: no args => undef' ) ;
  12425. 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' ) ;
  12426. is( 'UNKNOWN', version_from_rcs( 1.831 ), 'version_from_rcs: 1.831 => UNKNOWN' ) ;
  12427. note( 'Leaving tests_version_from_rcs()' ) ;
  12428. return ;
  12429. }
  12430. sub version_from_rcs
  12431. {
  12432. my $rcs = shift ;
  12433. if ( ! $rcs ) { return ; }
  12434. my $version = 'UNKNOWN' ;
  12435. if ( $rcs =~ m{,v\s+(\d+\.\d+)}mxso ) {
  12436. $version = $1
  12437. }
  12438. return( $version ) ;
  12439. }
  12440. sub tests_imapsync_basename
  12441. {
  12442. note( 'Entering tests_imapsync_basename()' ) ;
  12443. ok( imapsync_basename() =~ m/imapsync/, 'imapsync_basename: match imapsync');
  12444. ok( 'blabla' ne imapsync_basename(), 'imapsync_basename: do not equal blabla');
  12445. note( 'Leaving tests_imapsync_basename()' ) ;
  12446. return ;
  12447. }
  12448. sub imapsync_basename
  12449. {
  12450. return basename( $PROGRAM_NAME ) ;
  12451. }
  12452. sub localhost_info
  12453. {
  12454. my $mysync = shift ;
  12455. my( $infos ) = join( q{},
  12456. "Here is imapsync ", imapsync_version( $mysync ),
  12457. " on host " . hostname(),
  12458. ", a $OSNAME system with ",
  12459. ram_memory_info( ),
  12460. "\n",
  12461. 'with Perl ',
  12462. mysprintf( '%vd ', $PERL_VERSION),
  12463. "and Mail::IMAPClient $Mail::IMAPClient::VERSION",
  12464. ) ;
  12465. return( $infos ) ;
  12466. }
  12467. sub tests_cpu_number
  12468. {
  12469. note( 'Entering tests_cpu_number()' ) ;
  12470. is( 1, is_integer( cpu_number( ) ), "cpu_number: is_integer" ) ;
  12471. ok( 1 <= cpu_number( ), "cpu_number: 1 or more" ) ;
  12472. is( 1, cpu_number( 1 ), "cpu_number: 1 => 1" ) ;
  12473. is( 1, cpu_number( $MINUS_ONE ), "cpu_number: -1 => 1" ) ;
  12474. is( 1, cpu_number( 'lalala' ), "cpu_number: lalala => 1" ) ;
  12475. is( $NUMBER_42, cpu_number( $NUMBER_42 ), "cpu_number: $NUMBER_42 => $NUMBER_42" ) ;
  12476. note( "cpu_number = " . cpu_number( ) . "\n" ) ;
  12477. note( "hostname = " . hostname( ) . "\n" ) ;
  12478. SKIP: {
  12479. if ( ! ( 'i005' eq hostname() ) )
  12480. {
  12481. skip( 'cpu_number on host != i005 (FreeBSD)', 1 ) ;
  12482. }
  12483. is( 4, cpu_number( ), "cpu_number: on i005 (FreeBSD) => 4" ) ;
  12484. } ;
  12485. SKIP: {
  12486. if ( ! ( 'petite' eq hostname() ) )
  12487. {
  12488. skip( 'cpu_number on host != petite (Linux)', 1 ) ;
  12489. }
  12490. is( 2, cpu_number( ), "cpu_number: on petite (Linux) => 2" ) ;
  12491. } ;
  12492. SKIP: {
  12493. if ( ! ( skip_macosx( ) ) )
  12494. {
  12495. skip( 'cpu_number on host != polarhome macosx (Darwin MacOS X 10.7.5 Lion)', 1 ) ;
  12496. }
  12497. is( 2, cpu_number( ), "cpu_number: on polarhome macosx (Darwin MacOS X 10.7.5 Lion) => 2" ) ;
  12498. } ;
  12499. SKIP: {
  12500. if ( ! ( 'pcHPDV7-HP' eq hostname() ) )
  12501. {
  12502. skip( 'cpu_number on host != pcHPDV7-HP (Windows 7, 64bits)', 1 ) ;
  12503. }
  12504. is( 2, cpu_number( ), "cpu_number: on pcHPDV7-HP (Windows 7, 64bits) => 2" ) ;
  12505. } ;
  12506. SKIP: {
  12507. if ( ! ( 'CUILLERE' eq hostname() ) )
  12508. {
  12509. skip( 'cpu_number on host != CUILLERE (Windows XP, 32bits)', 1 ) ;
  12510. }
  12511. is( 1, cpu_number( ), "cpu_number: on CUILLERE (Windows XP, 32bits) => 1" ) ;
  12512. } ;
  12513. note( 'Leaving tests_cpu_number()' ) ;
  12514. return ;
  12515. }
  12516. sub cpu_number {
  12517. my $cpu_number_forced = shift ;
  12518. # Well, here 1 is better than 0 or undef
  12519. my $cpu_number = 1 ; # Default value, erased if better found
  12520. my @cpuinfo ;
  12521. if ( $ENV{"NUMBER_OF_PROCESSORS"} )
  12522. {
  12523. # might be under a Windows system
  12524. $cpu_number = $ENV{"NUMBER_OF_PROCESSORS"} ;
  12525. #myprint( "Number of processors found by env var NUMBER_OF_PROCESSORS: $cpu_number\n" ) ;
  12526. }
  12527. if ( 'darwin' eq $OSNAME )
  12528. {
  12529. $cpu_number = backtick( "sysctl -n hw.ncpu" ) ;
  12530. chomp( $cpu_number ) ;
  12531. #myprint( "Number of processors found by cmd 'sysctl -n hw.ncpu': $cpu_number\n" ) ;
  12532. }
  12533. if ( 'freebsd' eq $OSNAME )
  12534. {
  12535. $cpu_number = backtick( "sysctl -n kern.smp.cpus" ) ;
  12536. chomp( $cpu_number ) ;
  12537. #myprint( "Number of processors found by cmd 'sysctl -n kern.smp.cpus': $cpu_number\n" ) ;
  12538. }
  12539. if ( 'linux' eq $OSNAME && -e '/proc/cpuinfo' )
  12540. {
  12541. @cpuinfo = file_to_array( '/proc/cpuinfo' ) ;
  12542. $cpu_number = grep { /^processor/mxs } @cpuinfo ;
  12543. #myprint( "Number of processors found via /proc/cpuinfo: $cpu_number\n" ) ;
  12544. }
  12545. if ( defined $cpu_number_forced )
  12546. {
  12547. $cpu_number = $cpu_number_forced ;
  12548. }
  12549. return( integer_or_1( $cpu_number ) ) ;
  12550. }
  12551. sub tests_integer_or_1
  12552. {
  12553. note( 'Entering tests_integer_or_1()' ) ;
  12554. is( 1, integer_or_1( ), 'integer_or_1: no args => 1' ) ;
  12555. is( 1, integer_or_1( undef ), 'integer_or_1: undef => 1' ) ;
  12556. is( $NUMBER_10, integer_or_1( $NUMBER_10 ), 'integer_or_1: 10 => 10' ) ;
  12557. is( 1, integer_or_1( q{} ), 'integer_or_1: empty string => 1' ) ;
  12558. is( 1, integer_or_1( 'lalala' ), 'integer_or_1: lalala => 1' ) ;
  12559. note( 'Leaving tests_integer_or_1()' ) ;
  12560. return ;
  12561. }
  12562. sub integer_or_1
  12563. {
  12564. my $number = shift ;
  12565. if ( is_integer( $number ) ) {
  12566. return $number ;
  12567. }
  12568. # else
  12569. return 1 ;
  12570. }
  12571. sub tests_is_integer
  12572. {
  12573. note( 'Entering tests_is_integer()' ) ;
  12574. is( undef, is_integer( ), 'is_integer: no args => undef ' ) ;
  12575. ok( is_integer( 1 ), 'is_integer: 1 => yes ') ;
  12576. ok( is_integer( $NUMBER_42 ), 'is_integer: 42 => yes ') ;
  12577. ok( is_integer( "$NUMBER_42" ), 'is_integer: "$NUMBER_42" => yes ') ;
  12578. ok( is_integer( '42' ), 'is_integer: "42" => yes ') ;
  12579. ok( is_integer( $NUMBER_104_857_600 ), 'is_integer: 104_857_600 => yes') ;
  12580. ok( is_integer( "$NUMBER_104_857_600" ), 'is_integer: "$NUMBER_104_857_600" => yes') ;
  12581. ok( is_integer( '104857600' ), 'is_integer: 104857600 => yes') ;
  12582. ok( ! is_integer( 'blabla' ), 'is_integer: blabla => no' ) ;
  12583. ok( ! is_integer( q{} ), 'is_integer: empty string => no' ) ;
  12584. note( 'Leaving tests_is_integer()' ) ;
  12585. return ;
  12586. }
  12587. sub is_integer
  12588. {
  12589. my $number = shift ;
  12590. if ( ! defined $number ) { return ; }
  12591. return( $number =~ m{^\d+$}xo ) ;
  12592. }
  12593. sub tests_loadavg
  12594. {
  12595. note( 'Entering tests_loadavg()' ) ;
  12596. SKIP: {
  12597. skip( 'Tests for darwin', 3 ) if ('darwin' ne $OSNAME) ;
  12598. is( undef, loadavg( '/noexist' ), 'loadavg: /noexist => undef' ) ;
  12599. is_deeply(
  12600. [ '0.11', '0.22', '0.33' ],
  12601. [ loadavg( 'vm.loadavg: { 0.11 0.22 0.33 }' ) ],
  12602. 'loadavg: "vm.loadavg: { 0.11 0.22 0.33 }" => 0.11 0.22 0.33'
  12603. ) ;
  12604. note( join( " ", "loadavg:", loadavg( ) ) ) ;
  12605. is( 3, scalar( my @loadavg = loadavg( ) ), 'loadavg: 3 values' ) ;
  12606. } ;
  12607. SKIP: {
  12608. skip( 'Tests for linux', 3 ) if ('linux' ne $OSNAME) ;
  12609. is( undef, loadavg( '/noexist' ), 'loadavg: /noexist => undef' ) ;
  12610. ok( loadavg( ), 'loadavg: no args' ) ;
  12611. is_deeply( [ '0.39', '0.30', '0.37', '1/602' ],
  12612. [ loadavg( '0.39 0.30 0.37 1/602 6073' ) ],
  12613. 'loadavg 0.39 0.30 0.37 1/602 6073 => [0.39, 0.30, 0.37, 1/602]' ) ;
  12614. } ;
  12615. SKIP: {
  12616. skip( 'Tests for Windows', 1 ) if ('MSWin32' ne $OSNAME) ;
  12617. is_deeply( [ 0 ],
  12618. [ loadavg( ) ],
  12619. 'loadavg on MSWin32 => 0' ) ;
  12620. } ;
  12621. note( 'Leaving tests_loadavg()' ) ;
  12622. return ;
  12623. }
  12624. sub loadavg
  12625. {
  12626. if ( 'linux' eq $OSNAME ) {
  12627. return ( loadavg_linux( @ARG ) ) ;
  12628. }
  12629. if ( 'freebsd' eq $OSNAME ) {
  12630. return ( loadavg_freebsd( @ARG ) ) ;
  12631. }
  12632. if ( 'darwin' eq $OSNAME ) {
  12633. return ( loadavg_darwin( @ARG ) ) ;
  12634. }
  12635. if ( 'MSWin32' eq $OSNAME ) {
  12636. return ( loadavg_windows( @ARG ) ) ;
  12637. }
  12638. return( 'unknown' ) ;
  12639. }
  12640. sub loadavg_linux
  12641. {
  12642. my $line = shift ;
  12643. if ( ! $line ) {
  12644. $line = firstline( '/proc/loadavg' ) or return ;
  12645. }
  12646. my ( $avg_1_min, $avg_5_min, $avg_15_min, $current_runs ) = split /\s/mxs, $line ;
  12647. if ( all_defined( $avg_1_min, $avg_5_min, $avg_15_min ) ) {
  12648. $sync->{ debug } and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min $current_runs\n" ) ;
  12649. return ( $avg_1_min, $avg_5_min, $avg_15_min, $current_runs ) ;
  12650. }
  12651. return ;
  12652. }
  12653. sub loadavg_freebsd
  12654. {
  12655. my $file = shift ;
  12656. # Example of output of command "sysctl vm.loadavg":
  12657. # vm.loadavg: { 0.15 0.08 0.08 }
  12658. my $loadavg ;
  12659. if ( ! defined $file ) {
  12660. eval {
  12661. $loadavg = `/sbin/sysctl vm.loadavg` ;
  12662. #myprint( "LOADAVG FREEBSD: $loadavg\n" ) ;
  12663. } ;
  12664. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  12665. }else{
  12666. $loadavg = firstline( $file ) or return ;
  12667. }
  12668. my ( $avg_1_min, $avg_5_min, $avg_15_min )
  12669. = $loadavg =~ /vm\.loadavg\s*[:=]\s*\{?\s*(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)/mxs ;
  12670. $sync->{ debug } and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min\n" ) ;
  12671. return ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  12672. }
  12673. sub loadavg_darwin
  12674. {
  12675. my $line = shift ;
  12676. # Example of output of command "sysctl vm.loadavg":
  12677. # vm.loadavg: { 0.15 0.08 0.08 }
  12678. my $loadavg ;
  12679. if ( ! defined $line ) {
  12680. eval {
  12681. # $loadavg = `/usr/sbin/sysctl vm.loadavg` ;
  12682. $loadavg = `LANG= /usr/sbin/sysctl vm.loadavg` ;
  12683. #myprint( "LOADAVG DARWIN: $loadavg\n" ) ;
  12684. } ;
  12685. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  12686. }else{
  12687. $loadavg = $line ;
  12688. }
  12689. my ( $avg_1_min, $avg_5_min, $avg_15_min )
  12690. = $loadavg =~ /vm\.loadavg\s*[:=]\s*\{?\s*(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)/mxs ;
  12691. #$sync->{ debug } and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min\n" ) ;
  12692. return ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  12693. }
  12694. sub loadavg_windows
  12695. {
  12696. my $file = shift ;
  12697. # Example of output of command "wmic cpu get loadpercentage":
  12698. # LoadPercentage
  12699. # 12
  12700. my $loadavg ;
  12701. if ( ! defined $file ) {
  12702. eval {
  12703. #$loadavg = `CMD wmic cpu get loadpercentage` ;
  12704. $loadavg = "LoadPercentage\n0\n" ;
  12705. #myprint( "LOADAVG WIN: $loadavg\n" ) ;
  12706. } ;
  12707. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  12708. }else{
  12709. $loadavg = file_to_string( $file ) or return ;
  12710. #myprint( "$loadavg" ) ;
  12711. }
  12712. $loadavg =~ /LoadPercentage\n(\d+)/xms ;
  12713. my $num = $1 ;
  12714. $num /= 100 ;
  12715. $sync->{ debug } and myprint( "System load: $num\n" ) ;
  12716. return ( $num ) ;
  12717. }
  12718. sub tests_load_and_delay
  12719. {
  12720. note( 'Entering tests_load_and_delay()' ) ;
  12721. is( undef, load_and_delay( ), 'load_and_delay: no args => undef ' ) ;
  12722. is( undef, load_and_delay( 1 ), 'load_and_delay: not 4 args => undef ' ) ;
  12723. is( undef, load_and_delay( 0, 1, 1, 1 ), 'load_and_delay: division per 0 => undef ' ) ;
  12724. # ( $cpu_num, $avg_1_min, $avg_5_min, $avg_15_min )
  12725. is( 0, load_and_delay( 1, 1, 1, 1 ), 'load_and_delay: one core, loads are all 1 => ok ' ) ;
  12726. is( 0, load_and_delay( 1, 1, 1, 1, 'lalala' ), 'load_and_delay: five arguments is ok' ) ;
  12727. is( 0, load_and_delay( 2, 2, 2, 2 ), 'load_and_delay: two core, loads are all 2 => ok ' ) ;
  12728. is( 0, load_and_delay( 2, 2, 4, 5 ), 'load_and_delay: two core, load1m is 2 => ok ' ) ;
  12729. is( 0, load_and_delay( 1, 0, 0, 0 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=0 => 0 ' ) ;
  12730. is( 0, load_and_delay( 1, 0, 0, 2 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=2 => 0 ' ) ;
  12731. is( 0, load_and_delay( 1, 0, 2, 0 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=0 => 0 ' ) ;
  12732. is( 0, load_and_delay( 1, 0, 2, 2 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=2 => 0 ' ) ;
  12733. is( 0, load_and_delay( 1, 0, 3, 3 ), 'load_and_delay: one core, load1m=0 load5m=3 load15m=3 => 0 ' ) ;
  12734. is( 0, load_and_delay( 1, 0, 4, 4 ), 'load_and_delay: one core, load1m=0 load5m=3 load15m=3 => 0 ' ) ;
  12735. is( 0, load_and_delay( 1, 2, 0, 0 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=0 => 0 ' ) ;
  12736. is( 0, load_and_delay( 1, 2, 0, 2 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=2 => 0 ' ) ;
  12737. is( 0, load_and_delay( 1, 2, 2, 0 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=0 => 0 ' ) ;
  12738. is( 0, load_and_delay( 1, 2, 2, 2 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=2 => 0 ' ) ;
  12739. 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 ' ) ;
  12740. is( 0, load_and_delay( 1, 3, 0, 0 ), 'load_and_delay: one core, load1m=3 load5m=0 load15m=0 => 0 ' ) ;
  12741. 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 ' ) ;
  12742. is( 0, load_and_delay( 1, 3, 3, 2.9 ), 'load_and_delay: one core, load1m=3 load5m=3 load15m=2.9 => 0 ' ) ;
  12743. is( 0, load_and_delay( 1, 3, 3, 3 ), 'load_and_delay: one core, load1m=3 load5m=3 load15m=3 => 0 ' ) ;
  12744. is( 1, load_and_delay( 1, 6, 0, 0 ), 'load_and_delay: one core, load1m=3 load5m=0 load15m=0 => 1 ' ) ;
  12745. 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 ' ) ;
  12746. is( 5, load_and_delay( 1, 6, 6, 5.9 ), 'load_and_delay: one core, load1m=3 load5m=3 load15m=2.9 => 5 ' ) ;
  12747. is( 15, load_and_delay( 1, 6, 6, 6 ), 'load_and_delay: one core, load1m=3 load5m=3 load15m=3 => 15 ' ) ;
  12748. note( 'Leaving tests_load_and_delay()' ) ;
  12749. return ;
  12750. }
  12751. sub load_and_delay
  12752. {
  12753. # Basically return 0 if load is not heavy, ie <= 1 per processor
  12754. # Not enough arguments
  12755. if ( 4 > scalar @ARG ) { return ; }
  12756. my ( $cpu_num, $avg_1_min, $avg_5_min, $avg_15_min ) = @ARG ;
  12757. if ( 0 == $cpu_num ) { return ; }
  12758. # Let divide by number of cores
  12759. ( $avg_1_min, $avg_5_min, $avg_15_min ) = map { $_ / $cpu_num } ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  12760. # One of avg ok => ok, for now it is a OR
  12761. if ( $avg_1_min < 6 ) { return 0 ; }
  12762. if ( $avg_5_min < 6 ) { return 1 ; } # Retry in 1 minute
  12763. if ( $avg_15_min < 6 ) { return 5 ; } # Retry in 5 minutes
  12764. return 15 ; # Retry in 15 minutes
  12765. }
  12766. sub tests_cpu_time
  12767. {
  12768. note( 'Entering tests_cpu_time()' ) ;
  12769. ok( is_number( cpu_time( ) ), 'cpu_time: no args => a number' ) ;
  12770. my $mysync = { } ;
  12771. $mysync->{ debug } = 1 ;
  12772. ok( is_number( cpu_time( $mysync ) ), 'cpu_time: {} => a number' ) ;
  12773. note( 'Leaving tests_cpu_time()' ) ;
  12774. return ;
  12775. }
  12776. sub cpu_time
  12777. {
  12778. my $mysync = shift ;
  12779. my @cpu_times = times ;
  12780. if ( ! @cpu_times ) { return ; }
  12781. my $cpu_time = 0 ;
  12782. # last element is the sum of all elements
  12783. $cpu_time = ( map { $cpu_time += $_ } @cpu_times )[ -1 ] ;
  12784. my $cpu_time_round = mysprintf( '%.2f', $cpu_time ) ;
  12785. $mysync->{ debug } and myprint( join(' + ', @cpu_times), " = $cpu_time ~ $cpu_time_round\n" ) ;
  12786. return $cpu_time ;
  12787. }
  12788. sub tests_cpu_percent
  12789. {
  12790. note( 'Entering tests_cpu_percent()' ) ;
  12791. is( '0.0', cpu_percent( ), 'cpu_percent: no args => 0.0' ) ;
  12792. my $mysync = { } ;
  12793. $mysync->{ debug } = 1 ;
  12794. is( '0.0', cpu_percent( $mysync ), 'cpu_percent: {} => 0.0' ) ;
  12795. is( '0.0', cpu_percent( $mysync, 0 ), 'cpu_percent: {} 0 => 0.0' ) ;
  12796. is( '300.0', cpu_percent( $mysync, 3 ), 'cpu_percent: {} 3 => 300.0' ) ;
  12797. is( '30.0', cpu_percent( $mysync, 3, 10 ), 'cpu_percent: {} 3 10 => 30.0' ) ;
  12798. is( '0.0', cpu_percent( $mysync, 0, 10 ), 'cpu_percent: {} 0 10 => 0.0' ) ;
  12799. note( 'Leaving tests_cpu_percent()' ) ;
  12800. return ;
  12801. }
  12802. sub cpu_percent
  12803. {
  12804. my $mysync = shift ;
  12805. my $cpu_time = shift || 0 ;
  12806. my $timediff = shift || 1 ; # no division by 0
  12807. if ( $cpu_time > $timediff )
  12808. {
  12809. myprint( "Strange: cpu_time $cpu_time > timediff $timediff\n" ) ;
  12810. }
  12811. my $cpu_percent = 0 ;
  12812. $cpu_percent = mysprintf( '%.1f', 100 * $cpu_time / $timediff ) ;
  12813. $mysync->{ debug } and myprint( "cpu_percent: $cpu_percent \n" ) ;
  12814. return $cpu_percent ;
  12815. }
  12816. sub tests_cpu_percent_global
  12817. {
  12818. note( 'Entering tests_cpu_percent_global()' ) ;
  12819. is( '0.0', cpu_percent_global( ), 'cpu_percent_global: no args => 0' ) ;
  12820. my $mysync = { } ;
  12821. $mysync->{ debug } = 1 ;
  12822. is( '0.0', cpu_percent_global( $mysync ), 'cpu_percent_global: {} => 0' ) ;
  12823. is( '0.0', cpu_percent_global( $mysync, 0 ), 'cpu_percent_global: {} 0 => 0' ) ;
  12824. SKIP: {
  12825. if ( ! ( 'i005' eq hostname() ) )
  12826. {
  12827. skip( 'cpu_percent_global on host != i005', 1 ) ;
  12828. }
  12829. is( '25.0', cpu_percent_global( $mysync, 100 ), 'cpu_percent_global: {} 100 => 25 on host i005' ) ;
  12830. } ;
  12831. SKIP: {
  12832. if ( ! ( 'petite' eq hostname() ) )
  12833. {
  12834. skip( 'cpu_percent_global on host != petite', 1 ) ;
  12835. }
  12836. is( '50.0', cpu_percent_global( $mysync, 100 ), 'cpu_percent_global: {} 100 => 50 on host petite' ) ;
  12837. } ;
  12838. note( 'Leaving tests_cpu_percent_global()' ) ;
  12839. return ;
  12840. }
  12841. sub cpu_percent_global
  12842. {
  12843. my $mysync = shift ;
  12844. my $cpu_percent = shift || 0 ;
  12845. my $cpu_number = cpu_number( ) ;
  12846. my $cpu_percent_global ;
  12847. $cpu_percent_global = mysprintf( '%.1f', $cpu_percent / $cpu_number ) ;
  12848. $mysync->{ debug } and myprint( "cpu_percent_global: $cpu_percent_global \n" ) ;
  12849. return( $cpu_percent_global ) ;
  12850. }
  12851. sub ram_memory_info
  12852. {
  12853. # In GigaBytes so division by 1024 * 1024 * 1024
  12854. #
  12855. return(
  12856. sprintf( "%.1f/%.1f free GiB of RAM",
  12857. Sys::MemInfo::get("freemem") / ( $KIBI ** 3 ),
  12858. Sys::MemInfo::get("totalmem") / ( $KIBI ** 3 ),
  12859. )
  12860. ) ;
  12861. }
  12862. sub tests_memory_stress
  12863. {
  12864. note( 'Entering tests_memory_stress()' ) ;
  12865. is( undef, memory_stress( ), 'memory_stress: => undef' ) ;
  12866. note( 'Leaving tests_memory_stress()' ) ;
  12867. return ;
  12868. }
  12869. sub memory_stress
  12870. {
  12871. my $total_ram_in_MB = Sys::MemInfo::get("totalmem") / ( $KIBI * $KIBI ) ;
  12872. my $i = 1 ;
  12873. myprintf("Stress memory consumption before: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  12874. while ( $i < $total_ram_in_MB / 1.7 ) { $a .= "A" x 1000_000; $i++ } ;
  12875. myprintf("Stress memory consumption after: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  12876. return ;
  12877. }
  12878. sub tests_memory_consumption
  12879. {
  12880. note( 'Entering tests_memory_consumption()' ) ;
  12881. note( "memory_consumption: " . memory_consumption() . " bytes aka " . bytes_display_string_dec( memory_consumption() ) ) ;
  12882. like( memory_consumption( ), qr{\d+}xms,'memory_consumption no args') ;
  12883. like( memory_consumption( 1 ), qr{\d+}xms,'memory_consumption 1') ;
  12884. like( memory_consumption( $PROCESS_ID ), qr{\d+}xms,"memory_consumption_of_pids $PROCESS_ID") ;
  12885. like( memory_consumption_ratio(), qr{\d+}xms, 'memory_consumption_ratio' ) ;
  12886. like( memory_consumption_ratio(1), qr{\d+}xms, 'memory_consumption_ratio 1' ) ;
  12887. like( memory_consumption_ratio(10), qr{\d+}xms, 'memory_consumption_ratio 10' ) ;
  12888. note( 'Leaving tests_memory_consumption()' ) ;
  12889. return ;
  12890. }
  12891. sub memory_consumption
  12892. {
  12893. # memory consumed by imapsync until now in bytes
  12894. return( ( memory_consumption_of_pids( ) )[0] );
  12895. }
  12896. sub debugmemory
  12897. {
  12898. my $mysync = shift ;
  12899. if ( ! $mysync->{debugmemory} ) { return q{} ; }
  12900. my $precision = shift ;
  12901. return( mysprintf( "Memory consumption$precision: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ) ;
  12902. }
  12903. sub memory_consumption_of_pids
  12904. {
  12905. my @pid = @_;
  12906. @pid = ( @pid ) ? @pid : ( $PROCESS_ID ) ;
  12907. $sync->{ debug } and myprint( "memory_consumption_of_pids PIDs: @pid\n" ) ;
  12908. my @val ;
  12909. if ( ( 'MSWin32' eq $OSNAME ) or ( 'cygwin' eq $OSNAME ) ) {
  12910. @val = memory_consumption_of_pids_win32( @pid ) ;
  12911. }
  12912. elsif ( 'darwin' eq $OSNAME )
  12913. {
  12914. @val = memory_consumption_of_pids_mac( @pid ) ;
  12915. }
  12916. else
  12917. {
  12918. # Unix
  12919. my @ps = qx{ ps -o vsz -p @pid } ;
  12920. shift @ps ; # First line is column name "VSZ"
  12921. chomp @ps ;
  12922. # convert to octets
  12923. @val = map { $_ * $KIBI } @ps ;
  12924. }
  12925. return( @val ) ;
  12926. }
  12927. sub memory_consumption_of_pids_mac
  12928. {
  12929. my @pid = @_ ;
  12930. # Use IPC::Open3 from perlcrit -3
  12931. # But it stalls on Darwin, I don't understand why!
  12932. #my @ps = backtick( "ps -o rss -p @pid" ) ;
  12933. #myprint( "ps: @ps" ) ;
  12934. my @ps = qx{ ps -o rss -p @pid } ;
  12935. shift @ps ; # First line is column name "RSS"
  12936. chomp @ps ;
  12937. my @val = map { $_ * $KIBI } @ps ;
  12938. return( @val ) ;
  12939. }
  12940. sub memory_consumption_of_pids_win32
  12941. {
  12942. # Windows
  12943. my @PID = @_;
  12944. my %PID;
  12945. # hash of pids as key values
  12946. map { $PID{$_}++ } @PID;
  12947. # Does not work but should work reading the tasklist documentation
  12948. #@ps = qx{ tasklist /FI "PID eq @PID" };
  12949. my @ps = qx{ tasklist /NH /FO CSV } ;
  12950. #my @ps = backtick( 'tasklist /NH /FO CSV' ) ;
  12951. #myprint( "-" x $STD_CHAR_PER_LINE, "\n", @ps, "-" x $STD_CHAR_PER_LINE, "\n" ) ;
  12952. my @val;
  12953. foreach my $line (@ps) {
  12954. my($name, $pid, $mem) = (split ',', $line )[0,1,4];
  12955. next if (! $pid);
  12956. #myprint( "[$name][$pid][$mem]" ) ;
  12957. if ($PID{remove_qq($pid)}) {
  12958. #myprint( "MATCH !\n" ) ;
  12959. chomp $mem ;
  12960. $mem = remove_qq($mem);
  12961. $mem = remove_Ko($mem);
  12962. $mem = remove_not_num($mem);
  12963. #myprint( "[$mem]\n" ) ;
  12964. push @val, $mem * $KIBI;
  12965. }
  12966. }
  12967. return(@val);
  12968. }
  12969. sub tests_backtick
  12970. {
  12971. note( 'Entering tests_backtick()' ) ;
  12972. is( undef, backtick( ), 'backtick: no args' ) ;
  12973. is( undef, backtick( q{} ), 'backtick: empty command' ) ;
  12974. SKIP: {
  12975. skip( 'test for MSWin32', 5 ) if ('MSWin32' ne $OSNAME) ;
  12976. my @output ;
  12977. @output = backtick( 'echo Hello World!' ) ;
  12978. # Add \r on Windows.
  12979. ok( "Hello World!\r\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  12980. $sync->{ debug } and myprint( "[@output]" ) ;
  12981. @output = backtick( 'echo Hello & echo World!' ) ;
  12982. ok( "Hello \r\n" eq $output[0], 'backtick: echo Hello & echo World! line 1' ) ;
  12983. ok( "World!\r\n" eq $output[1], 'backtick: echo Hello & echo World! line 2' ) ;
  12984. $sync->{ debug } and myprint( "[@output][$output[0]][$output[1]]" ) ;
  12985. # Scalar context
  12986. ok( "Hello World!\r\n" eq backtick( 'echo Hello World!' ),
  12987. 'backtick: echo Hello World! scalar' ) ;
  12988. ok( "Hello \r\nWorld!\r\n" eq backtick( 'echo Hello & echo World!' ),
  12989. 'backtick: echo Hello & echo World! scalar 2 lines' ) ;
  12990. } ;
  12991. SKIP: {
  12992. skip( 'test for Unix', 7 ) if ('MSWin32' eq $OSNAME) ;
  12993. is( undef, backtick( 'aaaarrrg' ), 'backtick: aaaarrrg command not found' ) ;
  12994. # Array context
  12995. my @output ;
  12996. @output = backtick( 'echo Hello World!' ) ;
  12997. ok( "Hello World!\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  12998. $sync->{ debug } and myprint( "[@output]" ) ;
  12999. @output = backtick( "echo Hello\necho World!" ) ;
  13000. ok( "Hello\n" eq $output[0], 'backtick: echo Hello; echo World! line 1' ) ;
  13001. ok( "World!\n" eq $output[1], 'backtick: echo Hello; echo World! line 2' ) ;
  13002. $sync->{ debug } and myprint( "[@output]" ) ;
  13003. # Scalar context
  13004. ok( "Hello World!\n" eq backtick( 'echo Hello World!' ),
  13005. 'backtick: echo Hello World! scalar' ) ;
  13006. ok( "Hello\nWorld!\n" eq backtick( "echo Hello\necho World!" ),
  13007. 'backtick: echo Hello; echo World! scalar 2 lines' ) ;
  13008. # Return error positive value, that's ok
  13009. is( undef, backtick( 'false' ), 'backtick: false returns no output' ) ;
  13010. my $mem = backtick( "ps -o vsz -p $PROCESS_ID" ) ;
  13011. $sync->{ debug } and myprint( "MEM=$mem\n" ) ;
  13012. }
  13013. note( 'Leaving tests_backtick()' ) ;
  13014. return ;
  13015. }
  13016. sub backtick
  13017. {
  13018. my $command = shift ;
  13019. if ( ! $command ) { return ; }
  13020. my ( $writer, $reader, $err ) ;
  13021. my @output ;
  13022. my $pid ;
  13023. my $eval = eval {
  13024. $pid = IPC::Open3::open3( $writer, $reader, $err, $command ) ;
  13025. } ;
  13026. if ( $EVAL_ERROR ) {
  13027. myprint( $EVAL_ERROR ) ;
  13028. return ;
  13029. }
  13030. if ( ! $eval ) { return ; }
  13031. if ( ! $pid ) { return ; }
  13032. waitpid( $pid, 0 ) ;
  13033. @output = <$reader>; # Output here
  13034. #
  13035. #my @errors = <$err>; #Errors here, instead of the console
  13036. if ( not @output ) { return ; }
  13037. #myprint( @output ) ;
  13038. if ( $output[0] =~ /\Qopen3: exec of $command failed\E/mxs ) { return ; }
  13039. if ( wantarray ) {
  13040. return( @output ) ;
  13041. } else {
  13042. return( join( q{}, @output) ) ;
  13043. }
  13044. }
  13045. sub tests_check_binary_embed_all_dyn_libs
  13046. {
  13047. note( 'Entering tests_check_binary_embed_all_dyn_libs()' ) ;
  13048. is( 1, check_binary_embed_all_dyn_libs( ), 'check_binary_embed_all_dyn_libs: no args => 1' ) ;
  13049. note( 'Leaving tests_check_binary_embed_all_dyn_libs()' ) ;
  13050. return ;
  13051. }
  13052. sub check_binary_embed_all_dyn_libs
  13053. {
  13054. my @search_dyn_lib_locale = search_dyn_lib_locale( ) ;
  13055. if ( @search_dyn_lib_locale )
  13056. {
  13057. myprint( "Found myself $PROGRAM_NAME pid $PROCESS_ID using locale dynamic libraries that seems out of myself:\n" ) ;
  13058. myprint( @search_dyn_lib_locale ) ;
  13059. if ( $PROGRAM_NAME =~ m{imapsync_bin_Darwin} )
  13060. {
  13061. return 0 ;
  13062. }
  13063. elsif ( $PROGRAM_NAME =~ m{imapsync.*\.exe} )
  13064. {
  13065. return 0 ;
  13066. }
  13067. else
  13068. {
  13069. # is always ok for non binary
  13070. return 1 ;
  13071. }
  13072. }
  13073. else
  13074. {
  13075. # Found only embedded dynamic lib
  13076. myprint( "Found only embedded dynamic lib. Good!\n" ) ;
  13077. return 1 ;
  13078. }
  13079. }
  13080. sub search_dyn_lib_locale
  13081. {
  13082. if ( 'darwin' eq $OSNAME )
  13083. {
  13084. return search_dyn_lib_locale_darwin( ) ;
  13085. }
  13086. if ( 'linux' eq $OSNAME )
  13087. {
  13088. return search_dyn_lib_locale_linux( ) ;
  13089. }
  13090. if ( 'MSWin32' eq $OSNAME )
  13091. {
  13092. return search_dyn_lib_locale_MSWin32( ) ;
  13093. }
  13094. }
  13095. sub search_dyn_lib_locale_darwin
  13096. {
  13097. my $command = qq{ lsof -p $PROCESS_ID | grep ' REG ' | grep .dylib | grep -v '/par-' } ;
  13098. myprint( "Search non embeded dynamic libs with the command: $command\n" ) ;
  13099. return backtick( $command ) ;
  13100. }
  13101. sub search_dyn_lib_locale_linux
  13102. {
  13103. my $command = qq{ lsof -p $PROCESS_ID | grep ' REG ' | grep -v '/tmp/par-' | grep '\.so' } ;
  13104. myprint( "Search non embeded dynamic libs with the command: $command\n" ) ;
  13105. return backtick( $command ) ;
  13106. }
  13107. sub search_dyn_lib_locale_MSWin32
  13108. {
  13109. my $command = qq{ Listdlls.exe $PROCESS_ID|findstr Strawberry } ;
  13110. # $command = qq{ Listdlls.exe $PROCESS_ID|findstr Strawberry } ;
  13111. myprint( "Search non embeded dynamic libs with the command: $command\n" ) ;
  13112. return qx( $command ) ;
  13113. }
  13114. sub remove_not_num
  13115. {
  13116. my $string = shift ;
  13117. $string =~ tr/0-9//cd ;
  13118. #myprint( "tr [$string]\n" ) ;
  13119. return( $string ) ;
  13120. }
  13121. sub tests_remove_not_num
  13122. {
  13123. note( 'Entering tests_remove_not_num()' ) ;
  13124. ok( '123' eq remove_not_num( 123 ), 'remove_not_num( 123 )' ) ;
  13125. ok( '123' eq remove_not_num( '123' ), q{remove_not_num( '123' )} ) ;
  13126. ok( '123' eq remove_not_num( '12 3' ), q{remove_not_num( '12 3' )} ) ;
  13127. ok( '123' eq remove_not_num( 'a 12 3 Ko' ), q{remove_not_num( 'a 12 3 Ko' )} ) ;
  13128. note( 'Leaving tests_remove_not_num()' ) ;
  13129. return ;
  13130. }
  13131. sub remove_Ko
  13132. {
  13133. my $string = shift;
  13134. if ($string =~ /^(.*)\sKo$/xo) {
  13135. return($1);
  13136. }else{
  13137. return($string);
  13138. }
  13139. }
  13140. sub remove_qq
  13141. {
  13142. my $string = shift;
  13143. if ($string =~ /^"(.*)"$/xo) {
  13144. return($1);
  13145. }else{
  13146. return($string);
  13147. }
  13148. }
  13149. sub memory_consumption_ratio
  13150. {
  13151. my ($base) = @_;
  13152. $base ||= 1;
  13153. my $consu = memory_consumption();
  13154. return($consu / $base);
  13155. }
  13156. sub date_from_rcs
  13157. {
  13158. my $d = shift ;
  13159. 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 ) ;
  13160. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  13161. # Handles the following format
  13162. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  13163. #myprint( "$d\n" ) ;
  13164. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  13165. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  13166. $month = $num2mon{$month} ;
  13167. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  13168. #myprint( "$d\n" ) ;
  13169. }
  13170. return( $d ) ;
  13171. }
  13172. sub tests_date_from_rcs
  13173. {
  13174. note( 'Entering tests_date_from_rcs()' ) ;
  13175. ok('19-Sep-2015 16:11:07 +0000'
  13176. eq date_from_rcs('Date: 2015/09/19 16:11:07 '), 'date_from_rcs from RCS date' ) ;
  13177. note( 'Leaving tests_date_from_rcs()' ) ;
  13178. return ;
  13179. }
  13180. sub good_date
  13181. {
  13182. # two incoming formats:
  13183. # header Tue, 24 Aug 2010 16:00:00 +0200
  13184. # internal 24-Aug-2010 16:00:00 +0200
  13185. # outgoing format: internal date format
  13186. # 24-Aug-2010 16:00:00 +0200
  13187. my $d = shift ;
  13188. return(q{}) if not defined $d;
  13189. SWITCH: {
  13190. if ( $d =~ m{(\d?)(\d-...-\d{4})(\s\d{2}:\d{2}:\d{2})(\s(?:\+|-)\d{4})?}xo ) {
  13191. #myprint( "internal: [$1][$2][$3][$4]\n" ) ;
  13192. my ($day_1, $date_rest, $hour, $zone) = ($1,$2,$3,$4) ;
  13193. $day_1 = '0' if ($day_1 eq q{}) ;
  13194. $zone = ' +0000' if not defined $zone ;
  13195. $d = $day_1 . $date_rest . $hour . $zone ;
  13196. last SWITCH ;
  13197. }
  13198. 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 ) {
  13199. # Handles any combination of following formats
  13200. # Tue, 24 Aug 2010 16:00:00 +0200 -- Standard
  13201. # 24 Aug 2010 16:00:00 +0200 -- Missing Day of Week
  13202. # Tue, 24 Aug 97 16:00:00 +0200 -- Two digit year
  13203. # Tue, 24 Aug 1997 16.00.00 +0200 -- Periods instead of colons
  13204. # Tue, 24 Aug 1997 16:00:00 +0200 -- Extra whitespace between year and hour
  13205. # Tue, 24 Aug 1997 6:5:2 +0200 -- Single digit hour, min, or second
  13206. # Tue, 24, Aug 1997 16:00:00 +0200 -- Extra comma
  13207. #myprint( "header: [$1][$2][$3][$4][$5][$6][$7][$8]\n" ) ;
  13208. my ($day, $month, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7,$8);
  13209. $year = '19' . $year if length($year) == 2 && $year =~ m/^[789]/xo;
  13210. $year = '20' . $year if length($year) == 2;
  13211. $month = substr $month, 0, 3 if length($month) > 4;
  13212. $day = mysprintf( '%02d', $day);
  13213. $hour = mysprintf( '%02d', $hour);
  13214. $min = mysprintf( '%02d', $min);
  13215. $sec = '00' if not defined $sec ;
  13216. $sec = mysprintf( '%02d', $sec ) ;
  13217. $zone = '+0000' if not defined $zone ;
  13218. $d = "$day-$month-$year $hour:$min:$sec $zone" ;
  13219. last SWITCH ;
  13220. }
  13221. 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 ) {
  13222. # Handles any combination of following formats
  13223. # Sun Aug 20 11:55:09 2006
  13224. # Wed Jan 24 11:58:38 MST 2007
  13225. # Wed Jan 2 08:40:57 2008
  13226. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  13227. my ($month, $day, $hour, $min, $sec, $year) = ($1,$2,$3,$4,$5,$6);
  13228. $day = mysprintf( '%02d', $day ) ;
  13229. $hour = mysprintf( '%02d', $hour ) ;
  13230. $min = mysprintf( '%02d', $min ) ;
  13231. $sec = mysprintf( '%02d', $sec ) ;
  13232. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  13233. last SWITCH ;
  13234. }
  13235. 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 ) ;
  13236. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  13237. # Handles the following format
  13238. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  13239. #myprint( "$d\n" ) ;
  13240. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  13241. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  13242. $month = $num2mon{$month} ;
  13243. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  13244. #myprint( "$d\n" ) ;
  13245. last SWITCH ;
  13246. }
  13247. if ($d =~ m{(\d{2})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  13248. # Handles the following format
  13249. # 02/06/09 22:18:08 -- Generated by AVTECH TemPageR devices
  13250. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  13251. my ($month, $day, $year, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6);
  13252. $year = '20' . $year;
  13253. $month = $num2mon{$month};
  13254. $d = "$day-$month-$year $hour:$min:$sec +0000";
  13255. last SWITCH ;
  13256. }
  13257. 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 ) {
  13258. # Handles the following format
  13259. # Saturday, December 14, 2002 05:00 PM - KBtoys.com order confirmations
  13260. my ($month, $day, $year, $hour, $min, $apm) = ($1,$2,$3,$4,$5,$6);
  13261. $hour += 12 if $apm eq 'PM' ;
  13262. $day = mysprintf( '%02d', $day ) ;
  13263. $d = "$day-$month-$year $hour:$min:00 +0000" ;
  13264. last SWITCH ;
  13265. }
  13266. if ($d =~ m{(\w{3})\s(\d{1,2})\s(\d{4})\s(\d{2}):(\d{2}):(\d{2})\s((?:\+|-)\d{4})}xo ) {
  13267. # Handles the following format
  13268. # Saturday, December 14, 2002 05:00 PM - jr.com order confirmations
  13269. my ($month, $day, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7);
  13270. $day = mysprintf( '%02d', $day ) ;
  13271. $d = "$day-$month-$year $hour:$min:$sec $zone";
  13272. last SWITCH ;
  13273. }
  13274. if ($d =~ m{(\d{1,2})-(\w{3})-(\d{4})}xo ) {
  13275. # Handles the following format
  13276. # 21-Jun-2001 - register.com domain transfer email circa 2001
  13277. my ($day, $month, $year) = ($1,$2,$3);
  13278. $day = mysprintf( '%02d', $day);
  13279. $d = "$day-$month-$year 11:11:11 +0000";
  13280. last SWITCH ;
  13281. }
  13282. # unknown or unmatch => return same string
  13283. return($d);
  13284. }
  13285. $d = qq("$d") ;
  13286. return( $d ) ;
  13287. }
  13288. sub tests_good_date
  13289. {
  13290. note( 'Entering tests_good_date()' ) ;
  13291. ok(q{} eq good_date(), 'good_date no arg');
  13292. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('24-Aug-2010 16:00:00 +0200'), 'good_date internal 2digit zone');
  13293. ok('"24-Aug-2010 16:00:00 +0000"' eq good_date('24-Aug-2010 16:00:00'), 'good_date internal 2digit no zone');
  13294. ok('"01-Sep-2010 16:00:00 +0200"' eq good_date( '1-Sep-2010 16:00:00 +0200'), 'good_date internal SP 1digit');
  13295. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('Tue, 24 Aug 2010 16:00:00 +0200'), 'good_date header 2digit zone');
  13296. ok('"01-Sep-2010 16:00:00 +0000"' eq good_date('Wed, 1 Sep 2010 16:00:00'), 'good_date header SP 1digit zone');
  13297. 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');
  13298. 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');
  13299. ok('"06-Feb-2009 22:18:08 +0000"' eq good_date('02/06/09 22:18:08'), 'good_date header TemPageR');
  13300. 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');
  13301. 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');
  13302. 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');
  13303. 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');
  13304. ok('"24-Aug-2067 16:00:00 +0200"' eq good_date('Tue, 24 Aug 67 16:00:00 +0200'), 'good_date header 2digit year');
  13305. ok('"24-Aug-1977 16:00:00 +0200"' eq good_date('Tue, 24 Aug 77 16:00:00 +0200'), 'good_date header 2digit year');
  13306. ok('"24-Aug-1987 16:00:00 +0200"' eq good_date('Tue, 24 Aug 87 16:00:00 +0200'), 'good_date header 2digit year');
  13307. ok('"24-Aug-1997 16:00:00 +0200"' eq good_date('Tue, 24 Aug 97 16:00:00 +0200'), 'good_date header 2digit year');
  13308. ok('"24-Aug-2004 16:00:00 +0200"' eq good_date('Tue, 24 Aug 04 16:00:00 +0200'), 'good_date header 2digit year');
  13309. 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');
  13310. 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');
  13311. 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');
  13312. ok('"24-Aug-1997 05:06:02 +0200"' eq good_date('Tue, 24, Aug 1997 05:06:02 +0200'), 'good_date header extra commas');
  13313. ok('"01-Oct-2003 12:45:24 +0000"' eq good_date('Wednesday, 01 October 2003 12:45:24 CDT'), 'good_date header no abbrev');
  13314. ok('"11-Jan-2005 17:58:27 -0500"' eq good_date('Tue, 11 Jan 2005 17:58:27 -0500'), 'good_date extra white space');
  13315. ok('"18-Dec-2002 15:07:00 +0000"' eq good_date('Wednesday, December 18, 2002 03:07 PM'), 'good_date kbtoys.com orders');
  13316. ok('"16-Dec-2004 02:01:49 -0500"' eq good_date('Dec 16 2004 02:01:49 -0500'), 'good_date jr.com orders');
  13317. ok('"21-Jun-2001 11:11:11 +0000"' eq good_date('21-Jun-2001'), 'good_date register.com domain transfer');
  13318. 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)');
  13319. ok('"19-Sep-2015 16:11:07 +0000"' eq good_date('Date: 2015/09/19 16:11:07 '), 'good_date from RCS date' ) ;
  13320. note( 'Leaving tests_good_date()' ) ;
  13321. return ;
  13322. }
  13323. sub tests_list_keys_in_2_not_in_1
  13324. {
  13325. note( 'Entering tests_list_keys_in_2_not_in_1()' ) ;
  13326. my @list;
  13327. ok( ! list_keys_in_2_not_in_1( {}, {}), 'list_keys_in_2_not_in_1: {} {}');
  13328. ok( 0 == compare_lists( [], [ list_keys_in_2_not_in_1( {}, {} ) ] ), 'list_keys_in_2_not_in_1: {} {}');
  13329. 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}');
  13330. 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}');
  13331. 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}');
  13332. 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}');
  13333. 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}');
  13334. note( 'Leaving tests_list_keys_in_2_not_in_1()' ) ;
  13335. return ;
  13336. }
  13337. sub list_keys_in_2_not_in_1
  13338. {
  13339. my $hash_1_ref = shift;
  13340. my $hash_2_ref = shift;
  13341. my @list;
  13342. foreach my $key ( sort keys %{ $hash_2_ref } ) {
  13343. #$sync->{ debug } and print "$key\n" ;
  13344. if ( exists $hash_1_ref->{$key} )
  13345. {
  13346. next ;
  13347. }
  13348. #$sync->{ debug } and print "list_keys_in_2_not_in_1: $key\n" ;
  13349. push @list, $key ;
  13350. }
  13351. #$sync->{ debug } and print "@list\n" ;
  13352. return( @list ) ;
  13353. }
  13354. sub list_folders_in_2_not_in_1
  13355. {
  13356. my ( @h2_folders_not_in_h1, %h2_folders_not_in_h1 ) ;
  13357. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h1_folders_all, \%h2_folders_all ) ;
  13358. map { $h2_folders_not_in_h1{$_} = 1} @h2_folders_not_in_h1 ;
  13359. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h2_folders_from_1_all, \%h2_folders_not_in_h1 ) ;
  13360. #$sync->{ debug } and print "h2_folders_not_in_h1: @h2_folders_not_in_h1\n" ;
  13361. return( reverse @h2_folders_not_in_h1 ) ;
  13362. }
  13363. sub tests_nb_messages_in_2_not_in_1
  13364. {
  13365. note( 'Entering tests_stats_across_folders()' ) ;
  13366. is( undef, nb_messages_in_2_not_in_1( ), 'nb_messages_in_2_not_in_1: no args => undef' ) ;
  13367. my $mysync->{ h1_folders_of_md5 }->{ 'some_id_01' }->{ 'some_folder_01' } = 1 ;
  13368. is( 0, nb_messages_in_2_not_in_1( $mysync ), 'nb_messages_in_2_not_in_1: no messages in 2 => 0' ) ;
  13369. $mysync->{ h1_folders_of_md5 }->{ 'some_id_in_1_and_2' }->{ 'some_folder_01' } = 2 ;
  13370. $mysync->{ h2_folders_of_md5 }->{ 'some_id_in_1_and_2' }->{ 'some_folder_02' } = 4 ;
  13371. is( 0, nb_messages_in_2_not_in_1( $mysync ), 'nb_messages_in_2_not_in_1: a common message => 0' ) ;
  13372. $mysync->{ h2_folders_of_md5 }->{ 'some_id_in_2_not_in_1' }->{ 'some_folder_02' } = 1 ;
  13373. 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' ) ;
  13374. $mysync->{ h2_folders_of_md5 }->{ 'some_other_id_in_2_not_in_1' }->{ 'some_folder_02' } = 3 ;
  13375. 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' ) ;
  13376. note( 'Leaving tests_stats_across_folders()' ) ;
  13377. return ;
  13378. }
  13379. sub nb_messages_in_2_not_in_1
  13380. {
  13381. my $mysync = shift ;
  13382. if ( not defined $mysync ) { return ; }
  13383. $mysync->{ nb_messages_in_2_not_in_1 } = scalar(
  13384. list_keys_in_2_not_in_1(
  13385. $mysync->{ h1_folders_of_md5 },
  13386. $mysync->{ h2_folders_of_md5 } ) ) ;
  13387. return $mysync->{ nb_messages_in_2_not_in_1 } ;
  13388. }
  13389. sub nb_messages_in_1_not_in_2
  13390. {
  13391. my $mysync = shift ;
  13392. if ( not defined $mysync ) { return ; }
  13393. $mysync->{ nb_messages_in_1_not_in_2 } = scalar(
  13394. list_keys_in_2_not_in_1(
  13395. $mysync->{ h2_folders_of_md5 },
  13396. $mysync->{ h1_folders_of_md5 } ) ) ;
  13397. return $mysync->{ nb_messages_in_1_not_in_2 } ;
  13398. }
  13399. sub comment_on_final_diff_in_1_not_in_2
  13400. {
  13401. my $mysync = shift ;
  13402. if ( not defined $mysync
  13403. or $mysync->{ justfolders }
  13404. or $mysync->{ useuid }
  13405. )
  13406. {
  13407. return ;
  13408. }
  13409. my $nb_identified_h1_messages = scalar( keys %{ $mysync->{ h1_folders_of_md5 } } ) ;
  13410. my $nb_identified_h2_messages = scalar( keys %{ $mysync->{ h2_folders_of_md5 } } ) ;
  13411. $mysync->{ debug } and myprint( "nb_keys h1_folders_of_md5 $nb_identified_h1_messages\n" ) ;
  13412. $mysync->{ debug } and myprint( "nb_keys h2_folders_of_md5 $nb_identified_h2_messages\n" ) ;
  13413. if ( 0 == $nb_identified_h1_messages ) { return ; }
  13414. # Calculate if not yet done
  13415. if ( not defined $mysync->{ nb_messages_in_1_not_in_2 } )
  13416. {
  13417. nb_messages_in_1_not_in_2( $mysync ) ;
  13418. }
  13419. if ( 0 == $mysync->{ nb_messages_in_1_not_in_2 } )
  13420. {
  13421. myprint( "The sync looks good, all ",
  13422. $nb_identified_h1_messages,
  13423. " identified messages in host1 are on host2.\n" ) ;
  13424. }
  13425. else
  13426. {
  13427. myprint( "The sync is not finished, there are ",
  13428. $mysync->{ nb_messages_in_1_not_in_2 },
  13429. " among ",
  13430. $nb_identified_h1_messages,
  13431. " identified messages in host1 that are not on host2.\n" ) ;
  13432. }
  13433. if ( 1 <= $mysync->{ h1_nb_msg_noheader } )
  13434. {
  13435. myprint( "There are ",
  13436. $mysync->{ h1_nb_msg_noheader },
  13437. " unidentified messages (usually Sent or Draft messages).",
  13438. " To sync them add option --addheader\n" ) ;
  13439. }
  13440. else
  13441. {
  13442. myprint( "There is no unidentified message on host1.\n" ) ;
  13443. }
  13444. return ;
  13445. }
  13446. sub comment_on_final_diff_in_2_not_in_1
  13447. {
  13448. my $mysync = shift ;
  13449. if ( not defined $mysync
  13450. or $mysync->{ justfolders }
  13451. or $mysync->{ useuid }
  13452. )
  13453. {
  13454. return ;
  13455. }
  13456. my $nb_identified_h2_messages = scalar( keys %{ $mysync->{ h2_folders_of_md5 } } ) ;
  13457. # Calculate if not done yet
  13458. if ( not defined $mysync->{ nb_messages_in_2_not_in_1 } )
  13459. {
  13460. nb_messages_in_2_not_in_1( $mysync ) ;
  13461. }
  13462. if ( 0 == $mysync->{ nb_messages_in_2_not_in_1 } )
  13463. {
  13464. myprint( "The sync is strict, all ",
  13465. $nb_identified_h2_messages,
  13466. " identified messages in host2 are on host1.\n" ) ;
  13467. }
  13468. else
  13469. {
  13470. myprint( "The sync is not strict, there are ",
  13471. $mysync->{ nb_messages_in_2_not_in_1 },
  13472. " among ",
  13473. $nb_identified_h2_messages,
  13474. " identified messages in host2 that are not on host1.",
  13475. " Use --delete2 and sync again to delete them and have a strict sync.\n"
  13476. ) ;
  13477. }
  13478. return ;
  13479. }
  13480. sub tests_match
  13481. {
  13482. note( 'Entering tests_match()' ) ;
  13483. # undef serie
  13484. is( undef, match( ), 'match: no args => undef' ) ;
  13485. is( undef, match( 'lalala' ), 'match: one args => undef' ) ;
  13486. # This one gives 0 under a binary made by pp
  13487. # but 1 under "normal" Perl interpreter. So a PAR bug?
  13488. #is( 1, match( q{}, q{} ), 'match: q{} =~ q{} => 1' ) ;
  13489. is( 'lalala', match( 'lalala', 'lalala' ), 'match: lalala =~ lalala => lalala' ) ;
  13490. is( 'lalala', match( 'lalala', '^lalala' ), 'match: lalala =~ ^lalala => lalala' ) ;
  13491. is( 'lalala', match( 'lalala', 'lalala$' ), 'match: lalala =~ lalala$ => lalala' ) ;
  13492. is( 'lalala', match( 'lalala', '^lalala$' ), 'match: lalala =~ ^lalala$ => lalala' ) ;
  13493. is( '_lalala_', match( '_lalala_', 'lalala' ), 'match: _lalala_ =~ lalala => _lalala_' ) ;
  13494. is( 'lalala', match( 'lalala', '.*' ), 'match: lalala =~ .* => lalala' ) ;
  13495. is( 'lalala', match( 'lalala', '.' ), 'match: lalala =~ . => lalala' ) ;
  13496. is( '/lalala/', match( '/lalala/', '/lalala/' ), 'match: /lalala/ =~ /lalala/ => /lalala/' ) ;
  13497. is( 0, match( 'foo', 's/foo/bar/g' ), 'match: foo =~ s/foo/bar/g => 0' ) ;
  13498. 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' ) ;
  13499. is( 0, match( 'lalala', 'ooo' ), 'match: lalala =~ ooo => 0' ) ;
  13500. is( 0, match( 'lalala', 'lal_ala' ), 'match: lalala =~ lal_ala => 0' ) ;
  13501. is( 0, match( 'lalala', '\.' ), 'match: lalala =~ \. => 0' ) ;
  13502. is( 0, match( 'lalalaX', '^lalala$' ), 'match: lalalaX =~ ^lalala$ => 0' ) ;
  13503. is( 0, match( 'lalala', '/lalala/' ), 'match: lalala =~ /lalala/ => 0' ) ;
  13504. is( 'LALALA', match( 'LALALA', '(?i:lalala)' ), 'match: LALALA =~ (?i:lalala) => 1' ) ;
  13505. is( undef, match( 'LALALA', '(?{`ls /`})' ), 'match: LALALA =~ (?{`ls /`}) => undef' ) ;
  13506. is( undef, match( 'LALALA', '(?{print "CACA"})' ), 'match: LALALA =~ (?{print "CACA"}) => undef' ) ;
  13507. is( undef, match( 'CACA', '(??{print "CACA"})' ), 'match: CACA =~ (??{print "CACA"}) => undef' ) ;
  13508. note( 'Leaving tests_match()' ) ;
  13509. return ;
  13510. }
  13511. sub match
  13512. {
  13513. my( $var, $regex ) = @ARG ;
  13514. # undef cases
  13515. if ( ( ! defined $var ) or ( ! defined $regex ) ) { return ; }
  13516. # normal cases
  13517. if ( eval { $var =~ qr{$regex} } ) {
  13518. return $var ;
  13519. }elsif ( $EVAL_ERROR ) {
  13520. myprint( "Fatal regex $regex\n" ) ;
  13521. return ;
  13522. } else {
  13523. return 0 ;
  13524. }
  13525. return ;
  13526. }
  13527. sub tests_notmatch
  13528. {
  13529. note( 'Entering tests_notmatch()' ) ;
  13530. # undef serie
  13531. is( undef, notmatch( ), 'notmatch: no args => undef' ) ;
  13532. is( undef, notmatch( 'lalala' ), 'notmatch: one args => undef' ) ;
  13533. is( 1, notmatch( 'lalala', '/lalala/' ), 'notmatch: lalala !~ /lalala/ => 1' ) ;
  13534. is( 0, notmatch( '/lalala/', '/lalala/' ), 'notmatch: /lalala/ !~ /lalala/ => 0' ) ;
  13535. is( 1, notmatch( 'lalala', '/ooo/' ), 'notmatch: lalala !~ /ooo/ => 1' ) ;
  13536. # This one gives 1 under a binary made by pp
  13537. # but 0 under "normal" Perl interpreter. So a PAR bug, same in tests_match .
  13538. #is( 0, notmatch( q{}, q{} ), 'notmatch: q{} !~ q{} => 0' ) ;
  13539. is( 0, notmatch( 'lalala', 'lalala' ), 'notmatch: lalala !~ lalala => 0' ) ;
  13540. is( 0, notmatch( 'lalala', '^lalala' ), 'notmatch: lalala !~ ^lalala => 0' ) ;
  13541. is( 0, notmatch( 'lalala', 'lalala$' ), 'notmatch: lalala !~ lalala$ => 0' ) ;
  13542. is( 0, notmatch( 'lalala', '^lalala$' ), 'notmatch: lalala !~ ^lalala$ => 0' ) ;
  13543. is( 0, notmatch( '_lalala_', 'lalala' ), 'notmatch: _lalala_ !~ lalala => 0' ) ;
  13544. is( 0, notmatch( 'lalala', '.*' ), 'notmatch: lalala !~ .* => 0' ) ;
  13545. is( 0, notmatch( 'lalala', '.' ), 'notmatch: lalala !~ . => 0' ) ;
  13546. is( 1, notmatch( 'lalala', 'ooo' ), 'notmatch: does not match regex => 1' ) ;
  13547. is( 1, notmatch( 'lalala', 'lal_ala' ), 'notmatch: does not match regex => 1' ) ;
  13548. is( 1, notmatch( 'lalala', '\.' ), 'notmatch: matches regex => 0' ) ;
  13549. is( 1, notmatch( 'lalalaX', '^lalala$' ), 'notmatch: does not match regex => 1' ) ;
  13550. note( 'Leaving tests_notmatch()' ) ;
  13551. return ;
  13552. }
  13553. sub notmatch
  13554. {
  13555. my( $var, $regex ) = @ARG ;
  13556. # undef cases
  13557. if ( ( ! defined $var ) or ( ! defined $regex ) ) { return ; }
  13558. # normal cases
  13559. if ( eval { $var !~ $regex } ) {
  13560. return 1 ;
  13561. }elsif ( $EVAL_ERROR ) {
  13562. myprint( "Fatal regex $regex\n" ) ;
  13563. return ;
  13564. }else{
  13565. return 0 ;
  13566. }
  13567. return ;
  13568. }
  13569. sub delete_folders_in_2_not_in_1
  13570. {
  13571. foreach my $folder ( @h2_folders_not_in_1 ) {
  13572. if ( defined $delete2foldersonly and eval "\$folder !~ $delete2foldersonly" ) {
  13573. myprint( "Not deleting $folder because of --delete2foldersonly $delete2foldersonly\n" ) ;
  13574. next ;
  13575. }
  13576. if ( defined $delete2foldersbutnot and eval "\$folder =~ $delete2foldersbutnot" ) {
  13577. myprint( "Not deleting $folder because of --delete2foldersbutnot $delete2foldersbutnot\n" ) ;
  13578. next ;
  13579. }
  13580. my $res = $sync->{dry} ; # always success in dry mode!
  13581. $sync->{imap2}->unsubscribe( $folder ) if ( ! $sync->{dry} ) ;
  13582. $res = $sync->{imap2}->delete( $folder ) if ( ! $sync->{dry} ) ;
  13583. if ( $res ) {
  13584. myprint( "Deleted $folder", "$sync->{dry_message}", "\n" ) ;
  13585. }else{
  13586. myprint( "Deleting $folder failed", "\n" ) ;
  13587. }
  13588. }
  13589. return ;
  13590. }
  13591. sub delete_folder
  13592. {
  13593. my ( $mysync, $imap, $folder, $Side ) = @_ ;
  13594. if ( ! $mysync ) { return ; }
  13595. if ( ! $imap ) { return ; }
  13596. if ( ! $folder ) { return ; }
  13597. $Side ||= 'HostX' ;
  13598. my $res = $mysync->{dry} ; # always success in dry mode!
  13599. if ( ! $mysync->{dry} ) {
  13600. $imap->unsubscribe( $folder ) ;
  13601. $res = $imap->delete( $folder ) ;
  13602. }
  13603. if ( $res ) {
  13604. myprint( "$Side deleted $folder", $mysync->{dry_message}, "\n" ) ;
  13605. return 1 ;
  13606. }else{
  13607. myprint( "$Side deleting $folder failed", "\n" ) ;
  13608. return ;
  13609. }
  13610. }
  13611. sub delete1emptyfolders
  13612. {
  13613. my $mysync = shift ;
  13614. if ( ! $mysync ) { return ; } # abort if no parameter
  13615. if ( ! $mysync->{delete1emptyfolders} ) { return ; } # abort if --delete1emptyfolders off
  13616. my $imap = $mysync->{imap1} ;
  13617. if ( ! $imap ) { return ; } # abort if no imap
  13618. if ( $imap->IsUnconnected( ) ) { return ; } # abort if disconnected
  13619. my %folders_kept ;
  13620. myprint( qq{Host1 deleting empty folders\n} ) ;
  13621. foreach my $folder ( reverse sort @{ $mysync->{h1_folders_wanted} } ) {
  13622. my $parenthood = $imap->is_parent( $folder ) ;
  13623. if ( defined $parenthood and $parenthood ) {
  13624. myprint( "Host1: folder $folder has subfolders\n" ) ;
  13625. $folders_kept{ $folder }++ ;
  13626. next ;
  13627. }
  13628. my $nb_messages_select = examine_folder_and_count( $mysync, $imap, $folder, 'Host1' ) ;
  13629. if ( ! defined $nb_messages_select ) { next ; } # Select failed => Neither continue nor keep this folder }
  13630. my $nb_messages_search = scalar( @{ $imap->messages( ) } ) ;
  13631. if ( 0 != $nb_messages_select and 0 != $nb_messages_search ) {
  13632. myprint( "Host1: folder $folder has messages: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  13633. $folders_kept{ $folder }++ ;
  13634. next ;
  13635. }
  13636. if ( 0 != $nb_messages_select + $nb_messages_search ) {
  13637. myprint( "Host1: folder $folder odd messages count: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  13638. $folders_kept{ $folder }++ ;
  13639. next ;
  13640. }
  13641. # Here we must have 0 messages by messages() aka "SEARCH ALL" and also "EXAMINE"
  13642. if ( uc $folder eq 'INBOX' ) {
  13643. myprint( "Host1: Not deleting $folder\n" ) ;
  13644. $folders_kept{ $folder }++ ;
  13645. next ;
  13646. }
  13647. myprint( "Host1: deleting empty folder $folder\n" ) ;
  13648. # can not delete a SELECTed or EXAMINEd folder so closing it
  13649. # could changed be SELECT INBOX
  13650. $imap->close( ) ; # close after examine does not expunge; anyway expunging an empty folder...
  13651. if ( delete_folder( $mysync, $imap, $folder, 'Host1' ) ) {
  13652. next ; # Deleted, good!
  13653. }else{
  13654. $folders_kept{ $folder }++ ;
  13655. next ; # Not deleted, bad!
  13656. }
  13657. }
  13658. remove_deleted_folders_from_wanted_list( $mysync, %folders_kept ) ;
  13659. myprint( qq{Host1 ended deleting empty folders\n} ) ;
  13660. return ;
  13661. }
  13662. sub remove_deleted_folders_from_wanted_list
  13663. {
  13664. my ( $mysync, %folders_kept ) = @ARG ;
  13665. my @h1_folders_wanted_init = @{ $mysync->{h1_folders_wanted} } ;
  13666. my @h1_folders_wanted_last ;
  13667. foreach my $folder ( @h1_folders_wanted_init ) {
  13668. if ( $folders_kept{ $folder } ) {
  13669. push @h1_folders_wanted_last, $folder ;
  13670. }
  13671. }
  13672. @{ $mysync->{h1_folders_wanted} } = @h1_folders_wanted_last ;
  13673. return ;
  13674. }
  13675. sub examine_folder_and_count
  13676. {
  13677. my ( $mysync, $imap, $folder, $Side ) = @_ ;
  13678. $Side ||= 'HostX' ;
  13679. if ( ! examine_folder( $mysync, $imap, $folder, $Side ) ) {
  13680. return ;
  13681. }
  13682. my $nb_messages_select = count_from_select( $imap->History ) ;
  13683. return $nb_messages_select ;
  13684. }
  13685. sub tests_delete1emptyfolders
  13686. {
  13687. note( 'Entering tests_delete1emptyfolders()' ) ;
  13688. is( undef, delete1emptyfolders( ), q{delete1emptyfolders: undef} ) ;
  13689. my $syncT ;
  13690. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef 2} ) ;
  13691. my $imapT ;
  13692. $syncT->{imap1} = $imapT ;
  13693. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef imap} ) ;
  13694. require_ok( "Test::MockObject" ) ;
  13695. $imapT = Test::MockObject->new( ) ;
  13696. $syncT->{imap1} = $imapT ;
  13697. $imapT->set_true( 'IsUnconnected' ) ;
  13698. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: Unconnected imap} ) ;
  13699. # Now connected tests
  13700. $imapT->set_false( 'IsUnconnected' ) ;
  13701. $imapT->mock( 'LastError', sub { q{LastError mocked} } ) ;
  13702. $syncT->{delete1emptyfolders} = 0 ;
  13703. tests_delete1emptyfolders_unit(
  13704. $syncT,
  13705. [ qw{ INBOX DELME1 DELME2 } ],
  13706. [ qw{ INBOX DELME1 DELME2 } ],
  13707. q{tests_delete1emptyfolders: --delete1emptyfolders OFF}
  13708. ) ;
  13709. # All are parents => no deletion at all
  13710. $imapT->set_true( 'is_parent' ) ;
  13711. $syncT->{delete1emptyfolders} = 1 ;
  13712. tests_delete1emptyfolders_unit(
  13713. $syncT,
  13714. [ qw{ INBOX DELME1 DELME2 } ],
  13715. [ qw{ INBOX DELME1 DELME2 } ],
  13716. q{tests_delete1emptyfolders: --delete1emptyfolders ON}
  13717. ) ;
  13718. # No parents but examine false for all => skip all
  13719. $imapT->set_false( 'is_parent', 'examine' ) ;
  13720. tests_delete1emptyfolders_unit(
  13721. $syncT,
  13722. [ qw{ INBOX DELME1 DELME2 } ],
  13723. [ ],
  13724. q{tests_delete1emptyfolders: EXAMINE fails}
  13725. ) ;
  13726. # examine ok for all but History bad => skip all
  13727. $imapT->set_true( 'examine' ) ;
  13728. $imapT->mock( 'History', sub { ( q{History badly mocked} ) } ) ;
  13729. tests_delete1emptyfolders_unit(
  13730. $syncT,
  13731. [ qw{ INBOX DELME1 DELME2 } ],
  13732. [ ],
  13733. q{tests_delete1emptyfolders: examine ok but History badly mocked so count messages fails}
  13734. ) ;
  13735. # History good but some messages EXISTS == messages() => no deletion
  13736. $imapT->mock( 'History', sub { ( q{* 2 EXISTS} ) } ) ;
  13737. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  13738. tests_delete1emptyfolders_unit(
  13739. $syncT,
  13740. [ qw{ INBOX DELME1 DELME2 } ],
  13741. [ qw{ INBOX DELME1 DELME2 } ],
  13742. q{tests_delete1emptyfolders: History EXAMINE ok, several messages}
  13743. ) ;
  13744. # 0 EXISTS but != messages() => no deletion
  13745. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  13746. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  13747. tests_delete1emptyfolders_unit(
  13748. $syncT,
  13749. [ qw{ INBOX DELME1 DELME2 } ],
  13750. [ qw{ INBOX DELME1 DELME2 } ],
  13751. q{tests_delete1emptyfolders: 0 EXISTS but 2 by messages()}
  13752. ) ;
  13753. # 1 EXISTS but != 0 == messages() => no deletion
  13754. $imapT->mock( 'History', sub { ( q{* 1 EXISTS} ) } ) ;
  13755. $imapT->mock( 'messages', sub { [ ] } ) ;
  13756. tests_delete1emptyfolders_unit(
  13757. $syncT,
  13758. [ qw{ INBOX DELME1 DELME2 } ],
  13759. [ qw{ INBOX DELME1 DELME2 } ],
  13760. q{tests_delete1emptyfolders: 1 EXISTS but 0 by messages()}
  13761. ) ;
  13762. # 0 EXISTS and 0 == messages() => deletion except INBOX
  13763. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  13764. $imapT->mock( 'messages', sub { [ ] } ) ;
  13765. $imapT->set_true( qw{ delete close unsubscribe } ) ;
  13766. $syncT->{dry_message} = q{ (not really since in a mocked test)} ;
  13767. tests_delete1emptyfolders_unit(
  13768. $syncT,
  13769. [ qw{ INBOX DELME1 DELME2 } ],
  13770. [ qw{ INBOX } ],
  13771. q{tests_delete1emptyfolders: 0 EXISTS 0 by messages() delete folders, keep INBOX}
  13772. ) ;
  13773. note( 'Leaving tests_delete1emptyfolders()' ) ;
  13774. return ;
  13775. }
  13776. sub tests_delete1emptyfolders_unit
  13777. {
  13778. note( 'Entering tests_delete1emptyfolders_unit()' ) ;
  13779. my $syncT = shift ;
  13780. my $folders1wanted_init_ref = shift ;
  13781. my $folders1wanted_after_ref = shift ;
  13782. my $comment = shift || q{delete1emptyfolders:} ;
  13783. my @folders1wanted_init = @{ $folders1wanted_init_ref } ;
  13784. my @folders1wanted_after = @{ $folders1wanted_after_ref } ;
  13785. @{ $syncT->{h1_folders_wanted} } = @folders1wanted_init ;
  13786. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_init, qq{$comment, init check} ) ;
  13787. delete1emptyfolders( $syncT ) ;
  13788. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_after, qq{$comment, after check} ) ;
  13789. note( 'Leaving tests_delete1emptyfolders_unit()' ) ;
  13790. return ;
  13791. }
  13792. sub extract_header
  13793. {
  13794. my $string = shift ;
  13795. my ( $header ) = split /\n\n/x, $string ;
  13796. if ( ! $header ) { return( q{} ) ; }
  13797. #myprint( "[$header]\n" ) ;
  13798. return( $header ) ;
  13799. }
  13800. sub tests_extract_header
  13801. {
  13802. note( 'Entering tests_extract_header()' ) ;
  13803. my $h = <<'EOM';
  13804. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  13805. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  13806. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  13807. EOM
  13808. chomp $h ;
  13809. ok( $h eq extract_header(
  13810. <<'EOM'
  13811. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  13812. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  13813. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  13814. body
  13815. lalala
  13816. EOM
  13817. ), 'extract_header: 1') ;
  13818. note( 'Leaving tests_extract_header()' ) ;
  13819. return ;
  13820. }
  13821. sub decompose_header{
  13822. my $string = shift ;
  13823. # a hash, for a keyword header KEY value are list of strings [VAL1, VAL1_other, etc]
  13824. # Think of multiple "Received:" header lines.
  13825. my $header = { } ;
  13826. my ($key, $val ) ;
  13827. my @line = split /\n|\r\n/x, $string ;
  13828. foreach my $line ( @line ) {
  13829. #myprint( "DDD $line\n" ) ;
  13830. # End of header
  13831. last if ( $line =~ m{^$}xo ) ;
  13832. # Key: value
  13833. if ( $line =~ m/(^[^:]+):\s(.*)/xo ) {
  13834. $key = $1 ;
  13835. $val = $2 ;
  13836. $debugdev and myprint( "DDD KV [$key] [$val]\n" ) ;
  13837. push @{ $header->{ $key } }, $val ;
  13838. # blanc and value => value from previous line continues
  13839. }elsif( $line =~ m/^(\s+)(.*)/xo ) {
  13840. $val = $2 ;
  13841. $debugdev and myprint( "DDD V [$val]\n" ) ;
  13842. @{ $header->{ $key } }[ $LAST ] .= " $val" if $key ;
  13843. # dirty line?
  13844. }else{
  13845. next ;
  13846. }
  13847. }
  13848. #myprint( Data::Dumper->Dump( [ $header ] ) ) ;
  13849. return( $header ) ;
  13850. }
  13851. sub tests_decompose_header{
  13852. note( 'Entering tests_decompose_header()' ) ;
  13853. my $header_dec ;
  13854. $header_dec = decompose_header(
  13855. <<'EOH'
  13856. KEY_1: VAL_1
  13857. KEY_2: VAL_2
  13858. VAL_2_+
  13859. VAL_2_++
  13860. KEY_3: VAL_3
  13861. KEY_1: VAL_1_other
  13862. KEY_4: VAL_4
  13863. VAL_4_+
  13864. KEY_5 BLANC: VAL_5
  13865. KEY_6_BAD_BODY: VAL_6
  13866. EOH
  13867. ) ;
  13868. ok( 'VAL_3'
  13869. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: VAL_3' ) ;
  13870. ok( 'VAL_1'
  13871. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: VAL_1' ) ;
  13872. ok( 'VAL_1_other'
  13873. eq $header_dec->{ 'KEY_1' }[1], 'decompose_header: VAL_1_other' ) ;
  13874. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  13875. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: VAL_2 VAL_2_+ VAL_2_++' ) ;
  13876. ok( 'VAL_4 VAL_4_+'
  13877. eq $header_dec->{ 'KEY_4' }[0], 'decompose_header: VAL_4 VAL_4_+' ) ;
  13878. ok( ' VAL_5'
  13879. eq $header_dec->{ 'KEY_5 BLANC' }[0], 'decompose_header: KEY_5 BLANC' ) ;
  13880. ok( not( defined $header_dec->{ 'KEY_6_BAD_BODY' }[0] ), 'decompose_header: KEY_6_BAD_BODY' ) ;
  13881. $header_dec = decompose_header(
  13882. <<'EOH'
  13883. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  13884. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  13885. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  13886. EOH
  13887. ) ;
  13888. ok( '<20100428101817.A66CB162474E@plume.est.belle>'
  13889. eq $header_dec->{ 'Message-Id' }[0], 'decompose_header: 1' ) ;
  13890. $header_dec = decompose_header(
  13891. <<'EOH'
  13892. Return-Path: <gilles@louloutte.dyndns.org>
  13893. Received: by plume.est.belle (Postfix, from userid 1000)
  13894. id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)
  13895. Subject: test:eekahceishukohpe
  13896. EOH
  13897. ) ;
  13898. ok(
  13899. 'by plume.est.belle (Postfix, from userid 1000) id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)'
  13900. eq $header_dec->{ 'Received' }[0], 'decompose_header: 2' ) ;
  13901. $header_dec = decompose_header(
  13902. <<'EOH'
  13903. Received: from plume (localhost [127.0.0.1])
  13904. by plume.est.belle (Postfix) with ESMTP id C6EB73F6C9
  13905. for <gilles@localhost>; Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  13906. Received: from plume [192.168.68.7]
  13907. by plume with POP3 (fetchmail-6.3.6)
  13908. for <gilles@localhost> (single-drop); Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  13909. EOH
  13910. ) ;
  13911. ok(
  13912. '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)'
  13913. eq $header_dec->{ 'Received' }[0], 'decompose_header: 3' ) ;
  13914. ok(
  13915. '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)'
  13916. eq $header_dec->{ 'Received' }[1], 'decompose_header: 3' ) ;
  13917. # Bad header beginning with a blank character
  13918. $header_dec = decompose_header(
  13919. <<'EOH'
  13920. KEY_1: VAL_1
  13921. KEY_2: VAL_2
  13922. VAL_2_+
  13923. VAL_2_++
  13924. KEY_3: VAL_3
  13925. KEY_1: VAL_1_other
  13926. EOH
  13927. ) ;
  13928. ok( 'VAL_3'
  13929. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: Bad header VAL_3' ) ;
  13930. ok( 'VAL_1_other'
  13931. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: Bad header VAL_1_other' ) ;
  13932. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  13933. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: Bad header VAL_2 VAL_2_+ VAL_2_++' ) ;
  13934. note( 'Leaving tests_decompose_header()' ) ;
  13935. return ;
  13936. }
  13937. sub tests_epoch
  13938. {
  13939. note( 'Entering tests_epoch()' ) ;
  13940. ok( '1282658400' eq epoch( '24-Aug-2010 16:00:00 +0200' ), 'epoch 24-Aug-2010 16:00:00 +0200 -> 1282658400' ) ;
  13941. ok( '1282658400' eq epoch( '24-Aug-2010 14:00:00 +0000' ), 'epoch 24-Aug-2010 14:00:00 +0000 -> 1282658400' ) ;
  13942. ok( '1282658400' eq epoch( '24-Aug-2010 12:00:00 -0200' ), 'epoch 24-Aug-2010 12:00:00 -0200 -> 1282658400' ) ;
  13943. ok( '1282658400' eq epoch( '24-Aug-2010 16:01:00 +0201' ), 'epoch 24-Aug-2010 16:01:00 +0201 -> 1282658400' ) ;
  13944. ok( '1282658400' eq epoch( '24-Aug-2010 14:01:00 +0001' ), 'epoch 24-Aug-2010 14:01:00 +0001 -> 1282658400' ) ;
  13945. ok( '1280671200' eq epoch( '1-Aug-2010 16:00:00 +0200' ), 'epoch 1-Aug-2010 16:00:00 +0200 -> 1280671200' ) ;
  13946. ok( '1280671200' eq epoch( '1-Aug-2010 14:00:00 +0000' ), 'epoch 1-Aug-2010 14:00:00 +0000 -> 1280671200' ) ;
  13947. ok( '1280671200' eq epoch( '1-Aug-2010 12:00:00 -0200' ), 'epoch 1-Aug-2010 12:00:00 -0200 -> 1280671200' ) ;
  13948. ok( '1280671200' eq epoch( '1-Aug-2010 16:01:00 +0201' ), 'epoch 1-Aug-2010 16:01:00 +0201 -> 1280671200' ) ;
  13949. ok( '1280671200' eq epoch( '1-Aug-2010 14:01:00 +0001' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  13950. is( '1280671200', epoch( '1-Aug-2010 14:01:00 +0001' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  13951. is( '946684800', epoch( '00-Jan-0000 00:00:00 +0000' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  13952. note( 'Leaving tests_epoch()' ) ;
  13953. return ;
  13954. }
  13955. sub epoch
  13956. {
  13957. # incoming format:
  13958. # internal date 24-Aug-2010 16:00:00 +0200
  13959. # outgoing format: epoch
  13960. my $d = shift ;
  13961. return(q{}) if not defined $d;
  13962. my ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m ) ;
  13963. my $time ;
  13964. 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 ) {
  13965. #myprint( "internal: [$1][$2][$3][$4][$5][$6][$7][$8][$9]\n" ) ;
  13966. ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )
  13967. = ( $1, $2, $3, $4, $5, $6, $7, $8, $9 ) ;
  13968. #myprint( "( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )\n" ) ;
  13969. $sign = +1 if ( '+' eq $sign ) ;
  13970. $sign = $MINUS_ONE if ( '-' eq $sign ) ;
  13971. if ( 0 == $mday ) {
  13972. myprint( "buggy day in $d. Fixed to 01\n" ) ;
  13973. $mday = '01' ;
  13974. }
  13975. $time = timegm( $sec, $min, $hour, $mday, $month_abrev{$month}, $year )
  13976. - $sign * ( 3600 * $zone_h + 60 * $zone_m ) ;
  13977. #myprint( "$time ", scalar localtime($time), "\n");
  13978. }
  13979. return( $time ) ;
  13980. }
  13981. sub tests_add_header
  13982. {
  13983. note( 'Entering tests_add_header()' ) ;
  13984. ok( 'Message-Id: <mistake@imapsync>' eq add_header(), 'add_header no arg' ) ;
  13985. ok( 'Message-Id: <123456789@imapsync>' eq add_header( '123456789' ), 'add_header 123456789' ) ;
  13986. note( 'Leaving tests_add_header()' ) ;
  13987. return ;
  13988. }
  13989. sub add_header
  13990. {
  13991. my $header_uid = shift || 'mistake' ;
  13992. my $header_Message_Id = 'Message-Id: <' . $header_uid . '@imapsync>' ;
  13993. return( $header_Message_Id ) ;
  13994. }
  13995. sub tests_max_line_length
  13996. {
  13997. note( 'Entering tests_max_line_length()' ) ;
  13998. ok( 0 == max_line_length( q{} ), 'max_line_length: 0 == null string' ) ;
  13999. ok( 1 == max_line_length( "\n" ), 'max_line_length: 1 == \n' ) ;
  14000. ok( 1 == max_line_length( "\n\n" ), 'max_line_length: 1 == \n\n' ) ;
  14001. ok( 1 == max_line_length( "\n" x 500 ), 'max_line_length: 1 == 500 \n' ) ;
  14002. ok( 1 == max_line_length( 'a' ), 'max_line_length: 1 == a' ) ;
  14003. ok( 2 == max_line_length( "a\na" ), 'max_line_length: 2 == a\na' ) ;
  14004. ok( 2 == max_line_length( "a\na\n" ), 'max_line_length: 2 == a\na\n' ) ;
  14005. ok( 3 == max_line_length( "a\nab\n" ), 'max_line_length: 3 == a\nab\n' ) ;
  14006. ok( 3 == max_line_length( "a\nab\n" x 1_000 ), 'max_line_length: 3 == 1_000 a\nab\n' ) ;
  14007. ok( 3 == max_line_length( "a\nab\nabc" ), 'max_line_length: 3 == a\nab\nabc' ) ;
  14008. ok( 4 == max_line_length( "a\nab\nabc\n" ), 'max_line_length: 4 == a\nab\nabc\n' ) ;
  14009. ok( 5 == max_line_length( "a\nabcd\nabc\n" ), 'max_line_length: 5 == a\nabcd\nabc\n' ) ;
  14010. 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' ) ;
  14011. note( 'Leaving tests_max_line_length()' ) ;
  14012. return ;
  14013. }
  14014. sub max_line_length
  14015. {
  14016. my $string = shift ;
  14017. my $max = 0 ;
  14018. while ( $string =~ m/([^\n]*\n?)/msxg ) {
  14019. $max = max( $max, length $1 ) ;
  14020. }
  14021. return( $max ) ;
  14022. }
  14023. sub set_checknoabletosearch
  14024. {
  14025. my $mysync = shift @ARG ;
  14026. if ( defined $mysync->{ checknoabletosearch } )
  14027. {
  14028. return ;
  14029. }
  14030. elsif ( $mysync->{ justfolders } )
  14031. {
  14032. $mysync->{ checknoabletosearch } = 0 ;
  14033. }
  14034. else
  14035. {
  14036. $mysync->{ checknoabletosearch } = 1 ;
  14037. }
  14038. return ;
  14039. }
  14040. sub tests_setlogfile
  14041. {
  14042. note( 'Entering tests_setlogfile()' ) ;
  14043. my $mysync = {} ;
  14044. $mysync->{logdir} = 'vallogdir' ;
  14045. $mysync->{logfile} = 'vallogfile.txt' ;
  14046. is( 'vallogdir/vallogfile.txt', setlogfile( $mysync ),
  14047. 'setlogfile: logdir vallogdir, logfile vallogfile.txt, vallogdir/vallogfile.txt' ) ;
  14048. SKIP: {
  14049. skip( 'Too hard to have a well known timezone on Windows', 9 ) if ( 'MSWin32' eq $OSNAME ) ;
  14050. local $ENV{TZ} = 'GMT' ;
  14051. $mysync = {
  14052. timestart => 2,
  14053. } ;
  14054. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000__.txt", setlogfile( $mysync ),
  14055. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000__.txt" ) ;
  14056. $mysync = {
  14057. timestart => 2,
  14058. user1 => 'user1',
  14059. user2 => 'user2',
  14060. abort => 1,
  14061. } ;
  14062. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_abort.txt", setlogfile( $mysync ),
  14063. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_abort.txt" ) ;
  14064. $mysync = {
  14065. timestart => 2,
  14066. user1 => 'user1',
  14067. user2 => 'user2',
  14068. remote => 'zzz',
  14069. } ;
  14070. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote.txt", setlogfile( $mysync ),
  14071. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote.txt" ) ;
  14072. $mysync = {
  14073. timestart => 2,
  14074. user1 => 'user1',
  14075. user2 => 'user2',
  14076. remote => 'zzz',
  14077. abort => 1,
  14078. } ;
  14079. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote_abort.txt", setlogfile( $mysync ),
  14080. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote_abort.txt" ) ;
  14081. $mysync = {
  14082. timestart => 2,
  14083. user1 => 'user1',
  14084. user2 => 'user2',
  14085. } ;
  14086. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt", setlogfile( $mysync ),
  14087. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt" ) ;
  14088. $mysync->{logdir} = undef ;
  14089. $mysync->{logfile} = undef ;
  14090. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt", setlogfile( $mysync ),
  14091. "setlogfile: logdir undef, $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt" ) ;
  14092. $mysync->{logdir} = q{} ;
  14093. $mysync->{logfile} = undef ;
  14094. is( '1970_01_01_00_00_02_000_user1_user2.txt', setlogfile( $mysync ),
  14095. 'setlogfile: logdir empty, 1970_01_01_00_00_02_000_user1_user2.txt' ) ;
  14096. $mysync->{logdir} = 'vallogdir' ;
  14097. $mysync->{logfile} = undef ;
  14098. is( 'vallogdir/1970_01_01_00_00_02_000_user1_user2.txt', setlogfile( $mysync ),
  14099. 'setlogfile: logdir vallogdir, vallogdir/1970_01_01_00_00_02_000_user1_user2.txt' ) ;
  14100. $mysync = {
  14101. user1 => 'us/er1a*|?:"<>b',
  14102. user2 => 'u/ser2a*|?:"<>b',
  14103. } ;
  14104. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_00_000_us_er1a_______b_u_ser2a_______b.txt", setlogfile( $mysync ),
  14105. "setlogfile: logdir undef, $DEFAULT_LOGDIR/1970_01_01_00_00_00_000_us_er1a_______b_u_ser2a_______b.txt" ) ;
  14106. } ;
  14107. note( 'Leaving tests_setlogfile()' ) ;
  14108. return ;
  14109. }
  14110. sub setlogfile
  14111. {
  14112. my( $mysync ) = shift ;
  14113. # When aborting another process the log file name finishes with "_abort.txt"
  14114. my $abort_suffix = ( $mysync->{ abort } ) ? '_abort' : q{} ;
  14115. # When acting as a proxy the log file name finishes with "_remote.txt"
  14116. # proxy mode is not done in imapsync, it is done by proximapsync
  14117. my $remote_suffix = ( $mysync->{ remote } ) ? '_remote' : q{} ;
  14118. my $suffix = (
  14119. filter_forbidden_characters( slash_to_underscore( $mysync->{ user1 } ) ) || q{} )
  14120. . '_'
  14121. . ( filter_forbidden_characters( slash_to_underscore( $mysync->{ user2 } ) ) || q{} )
  14122. . $remote_suffix . $abort_suffix ;
  14123. $mysync->{ logdir } = defined $mysync->{ logdir } ? $mysync->{ logdir } : $DEFAULT_LOGDIR ;
  14124. $mysync->{ logfile } = defined $mysync->{ logfile }
  14125. ? "$mysync->{ logdir }/$mysync->{ logfile }"
  14126. : logfile( $mysync->{ timestart }, $suffix, $mysync->{ logdir } ) ;
  14127. return( $mysync->{ logfile } ) ;
  14128. }
  14129. sub tests_logfile
  14130. {
  14131. note( 'Entering tests_logfile()' ) ;
  14132. SKIP: {
  14133. # Too hard to have a well known timezone on Windows
  14134. skip( 'Too hard to have a well known timezone on Windows', 10 ) if ( 'MSWin32' eq $OSNAME ) ;
  14135. local $ENV{TZ} = 'GMT' ;
  14136. {
  14137. POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  14138. is( '1970_01_01_00_00_00_000.txt', logfile( ), 'logfile: no args => 1970_01_01_00_00_00.txt' ) ;
  14139. is( '1970_01_01_00_00_00_000.txt', logfile( 0 ), 'logfile: 0 => 1970_01_01_00_00_00.txt' ) ;
  14140. is( '1970_01_01_00_01_01_000.txt', logfile( 61 ), 'logfile: 0 => 1970_01_01_00_01_01.txt' ) ;
  14141. is( '1970_01_01_00_01_01_234.txt', logfile( 61.234 ), 'logfile: 0 => 1970_01_01_00_01_01.txt' ) ;
  14142. 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' ) ;
  14143. 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' ) ;
  14144. 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' ) ;
  14145. 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' ) ;
  14146. is( '2010_08_24_14_01_01_234_poup.txt', logfile( 1_282_658_461.2347, 'poup' ),
  14147. 'logfile: 1_282_658_461.2347 poup => 2010_08_24_14_01_01_234_poup.txt' ) ;
  14148. is( 'dirdir/2010_08_24_14_01_01_234_poup.txt', logfile( 1_282_658_461.2347, 'poup', 'dirdir' ),
  14149. 'logfile: 1_282_658_461.2347 poup dirdir => dirdir/2010_08_24_14_01_01_234_poup.txt' ) ;
  14150. }
  14151. POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  14152. } ;
  14153. note( 'Leaving tests_logfile()' ) ;
  14154. return ;
  14155. }
  14156. sub logfile
  14157. {
  14158. my ( $time, $suffix, $dir ) = @_ ;
  14159. $time ||= 0 ;
  14160. $suffix ||= q{} ;
  14161. $suffix =~ tr/ //ds ;
  14162. my $sep_suffix = ( $suffix ) ? '_' : q{} ;
  14163. $dir ||= q{} ;
  14164. my $sep_dir = ( $dir ) ? '/' : q{} ;
  14165. my $date_str = POSIX::strftime( '%Y_%m_%d_%H_%M_%S', localtime $time ) ;
  14166. # Because of ab tests or web accesses, more than one sync withing one second is possible
  14167. # so we add also milliseconds
  14168. $date_str .= sprintf "_%03d", ($time - int( $time ) ) * 1000 ; # without rounding
  14169. my $logfile = "${dir}${sep_dir}${date_str}${sep_suffix}${suffix}.txt" ;
  14170. return( $logfile ) ;
  14171. }
  14172. sub tests_localtimez
  14173. {
  14174. note( 'Entering tests_localtimez()' ) ;
  14175. SKIP: {
  14176. # Too hard to have a well known timezone on Windows
  14177. skip( 'Too hard to have a well known timezone on Windows', 1 ) if ( 'MSWin32' eq $OSNAME ) ;
  14178. local $ENV{TZ} = 'GMT' ;
  14179. like( localtimez( 0 ), qr'1970-01-01 00:00:00 \+0000 (GMT|UTC)', 'localtimez: 0 => match 1970-01-01 00:00:00 +0000 GMT' ) ;
  14180. }
  14181. is( localtimez( ), localtimez( time ), 'localtimez: undef => equals currrent' ) ;
  14182. note( 'Leaving tests_localtimez()' ) ;
  14183. return ;
  14184. }
  14185. sub localtimez
  14186. {
  14187. my $time = shift ;
  14188. $time = defined( $time ) ? $time : time ;
  14189. my $datetimestr = POSIX::strftime( '%A %e %B %Y-%m-%d %H:%M:%S %z %Z', localtime( $time ) ) ;
  14190. #myprint( "$datetimestr\n" ) ;
  14191. return $datetimestr ;
  14192. }
  14193. sub tests_slash_to_underscore
  14194. {
  14195. note( 'Entering tests_slash_to_underscore()' ) ;
  14196. is( undef, slash_to_underscore( ), 'slash_to_underscore: no parameters => undef' ) ;
  14197. is( '_', slash_to_underscore( '/' ), 'slash_to_underscore: / => _' ) ;
  14198. is( '_abc_def_', slash_to_underscore( '/abc/def/' ), 'slash_to_underscore: /abc/def/ => _abc_def_' ) ;
  14199. note( 'Leaving tests_slash_to_underscore()' ) ;
  14200. return ;
  14201. }
  14202. sub slash_to_underscore
  14203. {
  14204. my $string = shift ;
  14205. if ( ! defined $string ) { return ; }
  14206. $string =~ tr{/}{_} ;
  14207. return( $string ) ;
  14208. }
  14209. sub tests_million_folders_baby_2
  14210. {
  14211. note( 'Entering tests_million_folders_baby_2()' ) ;
  14212. my %long ;
  14213. @long{ 1 .. 900_000 } = (1) x 900_000 ;
  14214. #myprint( %long, "\n" ) ;
  14215. my $pasglop = 0 ;
  14216. foreach my $elem ( 1 .. 900_000 ) {
  14217. #$debug and myprint( "$elem " ) ;
  14218. if ( not exists $long{ $elem } ) {
  14219. $pasglop++ ;
  14220. }
  14221. }
  14222. ok( 0 == $pasglop, 'tests_million_folders_baby_2: search among 900_000' ) ;
  14223. # myprint( "$pasglop\n" ) ;
  14224. note( 'Leaving tests_million_folders_baby_2()' ) ;
  14225. return ;
  14226. }
  14227. sub tests_always_fail
  14228. {
  14229. note( 'Entering tests_always_fail()' ) ;
  14230. is( 0, 1, 'always_fail: 0 is 1' ) ;
  14231. note( 'Leaving tests_always_fail()' ) ;
  14232. return ;
  14233. }
  14234. sub tests_logfileprepa
  14235. {
  14236. note( 'Entering tests_logfileprepa()' ) ;
  14237. is( undef, logfileprepa( ), 'logfileprepa: no args => undef' ) ;
  14238. my $logfile = 'W/tmp/tests/tests_logfileprepa.txt' ;
  14239. is( 1, logfileprepa( $logfile ), 'logfileprepa: W/tmp/tests/tests_logfileprepa.txt => 1' ) ;
  14240. note( 'Leaving tests_logfileprepa()' ) ;
  14241. return ;
  14242. }
  14243. sub logfileprepa
  14244. {
  14245. my $logfile = shift ;
  14246. if ( ! defined( $logfile ) )
  14247. {
  14248. return ;
  14249. }else
  14250. {
  14251. #myprint( "[$logfile]\n" ) ;
  14252. my $dirname = dirname( $logfile ) ;
  14253. do_valid_directory( $dirname ) || return( 0 ) ;
  14254. return( 1 ) ;
  14255. }
  14256. }
  14257. sub tests_teelaunch
  14258. {
  14259. note( 'Entering tests_teelaunch()' ) ;
  14260. is( undef, teelaunch( ), 'teelaunch: no args => undef' ) ;
  14261. my $mysync = {} ;
  14262. is( undef, teelaunch( $mysync ), 'teelaunch: arg empty {} => undef' ) ;
  14263. $mysync->{logfile} = q{} ;
  14264. is( undef, teelaunch( $mysync ), 'teelaunch: logfile empty string => undef' ) ;
  14265. # First time, learning IO::Tee intrasics
  14266. $mysync->{logfile} = 'W/tmp/tests/tests_teelaunch.txt' ;
  14267. isa_ok( my $tee = teelaunch( $mysync ), 'IO::Tee' , 'teelaunch: logfile W/tmp/tests/tests_teelaunch.txt' ) ;
  14268. is( 1, print( $tee "Hi!\n" ), 'teelaunch: write Hi!') ;
  14269. is( "Hi!\n", file_to_string( 'W/tmp/tests/tests_teelaunch.txt' ), 'teelaunch: reading W/tmp/tests/tests_teelaunch.txt is Hi!\n' ) ;
  14270. is( 1, print( $tee "Hoo\n" ), 'teelaunch: write Hoo') ;
  14271. 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' ) ;
  14272. # closing so tee won't be happy
  14273. close $mysync->{logfile_handle} ;
  14274. is( undef, print( $tee "Argh1\n" ), 'teelaunch: write Argh1') ;
  14275. is( undef, print( $tee "Argh2\n" ), 'teelaunch: write Argh2') ;
  14276. # write not done
  14277. 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' ) ;
  14278. print join( ' ', $tee->handles ), "\n";
  14279. is( 2, scalar $tee->handles, 'teelaunch: 2 handles') ;
  14280. shift @{*{$tee}};
  14281. print join(' ', $tee->handles), "\n" ;
  14282. is( 1, scalar $tee->handles, 'teelaunch: 1 handle') ;
  14283. is( 1, print( $tee "Argh3\n" ), 'teelaunch: write Argh3 yeah') ;
  14284. shift @{*{$tee}};
  14285. # will not print anything now
  14286. is( 0, scalar $tee->handles, 'teelaunch: 0 handle') ;
  14287. is( 1, print( $tee "Argh 4\n" ), 'teelaunch: write Argh4 no') ;
  14288. # Second time, lesson learnt IO::Tee
  14289. $mysync->{logfile} = 'W/tmp/tests/tests_teelaunch2.txt' ;
  14290. isa_ok( $tee = teelaunch( $mysync ), 'IO::Tee' , 'teelaunch: logfile W/tmp/tests/tests_teelaunch2.txt' ) ;
  14291. is( 1, print( $tee "Hi!\n" ), 'teelaunch: write Hi!') ;
  14292. is( "Hi!\n", file_to_string( 'W/tmp/tests/tests_teelaunch2.txt' ), 'teelaunch: reading W/tmp/tests/tests_teelaunch2.txt is Hi!\n' ) ;
  14293. is( 1, print( $tee "Hoo\n" ), 'teelaunch: write Hoo') ;
  14294. 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' ) ;
  14295. is( 1, teefinish( $mysync ), 'teefinish: return 1') ;
  14296. is( 1, print( $tee "Argh1\n" ), 'teelaunch: write Argh1') ;
  14297. is( 1, print( $tee "Argh2\n" ), 'teelaunch: write Argh2') ;
  14298. 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' ) ;
  14299. is( 1, teefinish( $mysync ), 'teefinish: still return 1') ;
  14300. note( 'Leaving tests_teelaunch()' ) ;
  14301. return ;
  14302. }
  14303. sub teelaunch
  14304. {
  14305. my $mysync = shift ;
  14306. if ( ! defined( $mysync ) )
  14307. {
  14308. return ;
  14309. }
  14310. my $logfile = $mysync->{logfile} ;
  14311. if ( ! $logfile )
  14312. {
  14313. return ;
  14314. }
  14315. logfileprepa( $logfile ) || croak "Error no valid directory to write log file $logfile : $OS_ERROR" ;
  14316. # This is a log file opened during the whole sync
  14317. ## no critic (InputOutput::RequireBriefOpen)
  14318. open my $logfile_handle, '>', $logfile
  14319. or croak( "Can not open $logfile for write: $OS_ERROR" ) ;
  14320. binmode $logfile_handle, ":encoding(UTF-8)" ;
  14321. my $tee = IO::Tee->new( $logfile_handle, \*STDOUT ) ;
  14322. $tee->autoflush( 1 ) ;
  14323. $mysync->{logfile_handle} = $logfile_handle ;
  14324. $mysync->{tee} = $tee ;
  14325. return $tee ;
  14326. }
  14327. sub teefinish
  14328. {
  14329. my $mysync = shift ;
  14330. if ( ! defined( $mysync ) ) { return ; }
  14331. my $tee = $mysync->{tee} ;
  14332. if ( ! defined( $tee ) ) { return ; }
  14333. if ( 2 == scalar $tee->handles )
  14334. {
  14335. shift @{*{$tee}};
  14336. }
  14337. else
  14338. {
  14339. # nothing
  14340. }
  14341. return scalar $tee->handles ;
  14342. }
  14343. sub getpwuid_any_os
  14344. {
  14345. my $uid = shift ;
  14346. return( scalar getlogin ) if ( 'MSWin32' eq $OSNAME ) ; # Windows system
  14347. return( scalar getpwuid $uid ) ; # Unix system
  14348. }
  14349. sub abortifneeded
  14350. {
  14351. my $mysync = shift ;
  14352. if ( -e $mysync->{ abortfile } )
  14353. {
  14354. myprint( "Asked to terminate by file $mysync->{ abortfile }\n" ) ;
  14355. do_and_print_stats( $mysync ) ;
  14356. myprint( "You should resynchronize those accounts by running a sync again,\n",
  14357. "since some messages and entire folders might still be missing on host2.\n"
  14358. ) ;
  14359. exit_clean( $mysync, $EXIT_BY_FILE ) ;
  14360. return ;
  14361. }
  14362. else
  14363. {
  14364. return ;
  14365. }
  14366. }
  14367. sub simulong
  14368. {
  14369. my $mysync = shift ;
  14370. my $max_seconds = $mysync->{ simulong } ;
  14371. if ( ! $max_seconds ) { return ; }
  14372. my $division = 5 ;
  14373. my $last_count = int( $division * $max_seconds ) ;
  14374. $mysync->{ debug } and myprint "last_count $last_count = int( division $division * max_seconds $max_seconds)\n" ;
  14375. foreach my $i ( 1 .. ( $last_count ) ) {
  14376. myprint( "Are you still here ETA: " . ( $last_count - $i ) . "/$last_count msgs left\n" ) ;
  14377. #this one is for testing huge page behavior
  14378. #myprint( "Are you still here ETA: " . ($last_count - $i) . "/$last_count msgs left\n" . ( "Ah" x 40 . "\n") x 4000 ) ;
  14379. sleep( 1 / $division ) ;
  14380. abortifneeded( $mysync ) ;
  14381. }
  14382. return ;
  14383. }
  14384. sub printenv
  14385. {
  14386. myprint( "Environment variables listing:\n",
  14387. ( map { "$_ => $ENV{$_}\n" } sort keys %ENV),
  14388. "Environment variables listing end\n" ) ;
  14389. return ;
  14390. }
  14391. sub unittestssuite
  14392. {
  14393. my $mysync = shift ;
  14394. if ( ! ( $mysync->{ tests } or $mysync->{ testsdebug } or $mysync->{ testsunit } ) ) {
  14395. return ;
  14396. }
  14397. my $test_builder = Test::More->builder ;
  14398. tests( $mysync ) ;
  14399. testsdebug( $mysync ) ;
  14400. testunitsession( $mysync ) ;
  14401. my @summary = $test_builder->summary() ;
  14402. my @details = $test_builder->details() ;
  14403. my $nb_tests_run = scalar( @summary ) ;
  14404. my $nb_tests_expected = $test_builder->expected_tests() ;
  14405. my $nb_tests_failed = count_0s( @summary ) ;
  14406. my $tests_failed = report_failures( @details ) ;
  14407. if ( $nb_tests_failed or ( $nb_tests_run != $nb_tests_expected ) ) {
  14408. #$test_builder->reset( ) ;
  14409. myprint( "Summary of tests: failed $nb_tests_failed tests, run $nb_tests_run tests, expected to run $nb_tests_expected tests.\n",
  14410. "List of failed tests:\n", $tests_failed ) ;
  14411. return $EXIT_TESTS_FAILED ;
  14412. }
  14413. cleanup_mess_from_tests( ) ;
  14414. return 0 ;
  14415. }
  14416. sub cleanup_mess_from_tests
  14417. {
  14418. undef @pipemess ;
  14419. return ;
  14420. }
  14421. sub after_get_options
  14422. {
  14423. my $mysync = shift ;
  14424. my $numopt = shift ;
  14425. # exit with --help option or no option at all
  14426. $mysync->{ debug } and myprint( "numopt:$numopt\n" ) ;
  14427. if ( $help or not $numopt ) {
  14428. myprint( usage( $mysync ) ) ;
  14429. exit ;
  14430. }
  14431. return ;
  14432. }
  14433. sub tests_remove_edging_blanks
  14434. {
  14435. note( 'Entering tests_remove_edging_blanks()' ) ;
  14436. is( undef, remove_edging_blanks( ), 'remove_edging_blanks: no args => undef' ) ;
  14437. is( 'abcd', remove_edging_blanks( 'abcd' ), 'remove_edging_blanks: abcd => abcd' ) ;
  14438. is( 'ab cd', remove_edging_blanks( ' ab cd ' ), 'remove_edging_blanks: " ab cd " => "ab cd"' ) ;
  14439. note( 'Leaving tests_remove_edging_blanks()' ) ;
  14440. return ;
  14441. }
  14442. sub remove_edging_blanks
  14443. {
  14444. my $string = shift ;
  14445. if ( ! defined $string )
  14446. {
  14447. return ;
  14448. }
  14449. $string =~ s,^ +| +$,,g ;
  14450. return $string ;
  14451. }
  14452. sub tests_sanitize
  14453. {
  14454. note( 'Entering tests_remove_edging_blanks()' ) ;
  14455. is( undef, sanitize( ), 'sanitize: no args => undef' ) ;
  14456. my $mysync = {} ;
  14457. $mysync->{ host1 } = ' example.com ' ;
  14458. $mysync->{ user1 } = ' to to ' ;
  14459. $mysync->{ password1 } = ' sex is good! ' ;
  14460. is( undef, sanitize( $mysync ), 'sanitize: => undef' ) ;
  14461. is( 'example.com', $mysync->{ host1 }, 'sanitize: host1 " example.com " => "example.com"' ) ;
  14462. is( 'to to', $mysync->{ user1 }, 'sanitize: user1 " to to " => "to to"' ) ;
  14463. is( 'sex is good!', $mysync->{ password1 }, 'sanitize: password1 " sex is good! " => "sex is good!"' ) ;
  14464. note( 'Leaving tests_remove_edging_blanks()' ) ;
  14465. return ;
  14466. }
  14467. sub sanitize
  14468. {
  14469. my $mysync = shift ;
  14470. if ( ! defined $mysync )
  14471. {
  14472. return ;
  14473. }
  14474. foreach my $parameter ( qw( host1 host2 user1 user2 password1 password2 ) )
  14475. {
  14476. $mysync->{ $parameter } = remove_edging_blanks( $mysync->{ $parameter } ) ;
  14477. }
  14478. return ;
  14479. }
  14480. sub easyany
  14481. {
  14482. my $mysync = shift ;
  14483. # Gmail
  14484. if ( $mysync->{gmail1} and $mysync->{gmail2} ) {
  14485. $mysync->{ debug } and myprint( "gmail1 gmail2\n") ;
  14486. gmail12( $mysync ) ;
  14487. return ;
  14488. }
  14489. if ( $mysync->{gmail1} ) {
  14490. $mysync->{ debug } and myprint( "gmail1\n" ) ;
  14491. gmail1( $mysync ) ;
  14492. }
  14493. if ( $mysync->{gmail2} ) {
  14494. $mysync->{ debug } and myprint( "gmail2\n" ) ;
  14495. gmail2( $mysync ) ;
  14496. }
  14497. # Office 365
  14498. if ( $mysync->{office1} ) {
  14499. office1( $mysync ) ;
  14500. }
  14501. if ( $mysync->{office2} ) {
  14502. office2( $mysync ) ;
  14503. }
  14504. # Exchange
  14505. if ( $mysync->{exchange1} ) {
  14506. exchange1( $mysync ) ;
  14507. }
  14508. if ( $mysync->{exchange2} ) {
  14509. exchange2( $mysync ) ;
  14510. }
  14511. # Domino
  14512. if ( $mysync->{domino1} ) {
  14513. domino1( $mysync ) ;
  14514. }
  14515. if ( $mysync->{domino2} ) {
  14516. domino2( $mysync ) ;
  14517. }
  14518. return ;
  14519. }
  14520. # From and for https://imapsync.lamiral.info/FAQ.d/FAQ.Gmail.txt
  14521. sub gmail12
  14522. {
  14523. my $mysync = shift ;
  14524. # Gmail at host1 and host2
  14525. $mysync->{host1} ||= 'imap.gmail.com' ;
  14526. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  14527. $mysync->{host2} ||= 'imap.gmail.com' ;
  14528. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  14529. $mysync->{maxbytespersecond} ||= 20_000 ; # should be less than 10_000 when computed from Gmail documentation
  14530. $mysync->{maxbytesafter} ||= 1_000_000_000 ; # In fact it is documented as half: 500_000_000
  14531. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  14532. $mysync->{maxsleep} = ( defined $mysync->{maxsleep} ) ? $mysync->{maxsleep} : $MAX_SLEEP ; ;
  14533. $skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 0 ;
  14534. $mysync->{ synclabels } = ( defined $mysync->{ synclabels } ) ? $mysync->{ synclabels } : 1 ;
  14535. $mysync->{ resynclabels } = ( defined $mysync->{ resynclabels } ) ? $mysync->{ resynclabels } : 1 ;
  14536. push @useheader, 'X-Gmail-Received', 'Message-Id' ;
  14537. push @exclude, '\[Gmail\]$' ;
  14538. push @folderlast, '[Gmail]/All Mail' ;
  14539. return ;
  14540. }
  14541. sub gmail1
  14542. {
  14543. my $mysync = shift ;
  14544. # Gmail at host2
  14545. $mysync->{host1} ||= 'imap.gmail.com' ;
  14546. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  14547. $mysync->{maxbytespersecond} ||= 40_000 ; # should be 30_000 computed from by Gmail documentation
  14548. $mysync->{maxbytesafter} ||= 3_000_000_000 ; #
  14549. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  14550. $mysync->{maxsleep} = ( defined $mysync->{maxsleep} ) ? $mysync->{maxsleep} : $MAX_SLEEP ; ;
  14551. $skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 1 ;
  14552. push @useheader, 'X-Gmail-Received', 'Message-Id' ;
  14553. push @{ $mysync->{ regextrans2 } }, 's,\[Gmail\].,,' ;
  14554. push @folderlast, '[Gmail]/All Mail' ;
  14555. return ;
  14556. }
  14557. sub gmail2
  14558. {
  14559. my $mysync = shift ;
  14560. # Gmail at host2
  14561. $mysync->{ host2 } ||= 'imap.gmail.com' ;
  14562. $mysync->{ ssl2 } = ( defined $mysync->{ ssl2 } ) ? $mysync->{ ssl2 } : 1 ;
  14563. $mysync->{ maxbytespersecond } ||= 20_000 ; # should be less than 10_000 computed from by Gmail documentation
  14564. $mysync->{ maxbytesafter } ||= 1_000_000_000 ; # In fact it is documented as half: 500_000_000
  14565. $mysync->{ automap } = ( defined $mysync->{ automap } ) ? $mysync->{ automap } : 1 ;
  14566. #$skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 1 ;
  14567. $mysync->{ expunge1 } = ( defined $mysync->{ expunge1 } ) ? $mysync->{ expunge1 } : 1 ;
  14568. $mysync->{ addheader } = ( defined $mysync->{ addheader } ) ? $mysync->{ addheader } : 1 ;
  14569. $mysync->{ maxsleep } = ( defined $mysync->{ maxsleep } ) ? $mysync->{ maxsleep } : $MAX_SLEEP ; ;
  14570. #$mysync->{ maxsize } = ( defined $mysync->{ maxsize } ) ? $mysync->{ maxsize } : $GMAIL_MAXSIZE ;
  14571. if ( ! $mysync->{ noexclude } ) {
  14572. push @exclude, '\[Gmail\]$' ;
  14573. }
  14574. push @useheader, 'Message-Id' ;
  14575. push @{ $mysync->{ regextrans2 } }, 's,\[Gmail\].,,' ;
  14576. # push @{ $mysync->{ regextrans2 } }, 's/[ ]+/_/g' ; # is now replaced
  14577. # by the two more specific following regexes,
  14578. # they remove just the beginning and trailing blanks, not all.
  14579. push @{ $mysync->{ regextrans2 } }, 's,^ +| +$,,g' ;
  14580. push @{ $mysync->{ regextrans2 } }, 's,/ +| +/,/,g' ;
  14581. #
  14582. push @{ $mysync->{ regextrans2 } }, q{s/['\\^"]/_/g} ; # Verified this
  14583. push @folderlast, '[Gmail]/All Mail' ;
  14584. return ;
  14585. }
  14586. # From https://imapsync.lamiral.info/FAQ.d/FAQ.Exchange.txt
  14587. sub office1
  14588. {
  14589. # Office 365 at host1
  14590. my $mysync = shift ;
  14591. output( $mysync, q{Option --office1 is like: --host1 outlook.office365.com --ssl1 --exclude "^Files$"} . "\n" ) ;
  14592. output( $mysync, "Option --office1 (cont) : unless overrided with --host1 otherhost --nossl1 --noexclude\n" ) ;
  14593. $mysync->{host1} ||= 'outlook.office365.com' ;
  14594. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  14595. if ( ! $mysync->{noexclude} ) {
  14596. push @exclude, '^Files$' ;
  14597. }
  14598. return ;
  14599. }
  14600. sub office2
  14601. {
  14602. # Office 365 at host2
  14603. my $mysync = shift ;
  14604. output( $mysync, qq{Option --office2 is like: --host2 outlook.office365.com --ssl2 --maxsize 45_000_000 --maxmessagespersecond 4\n} ) ;
  14605. output( $mysync, qq{Option --office2 (cont) : --disarmreadreceipts --regexmess "wrap 10500" --f1f2 "Files=Files_renamed_by_imapsync"\n} ) ;
  14606. output( $mysync, qq{Option --office2 (cont) : unless overrided with --host2 otherhost --nossl2 ... --nodisarmreadreceipts --noregexmess\n} ) ;
  14607. output( $mysync, qq{Option --office2 (cont) : and --nof1f2 to avoid Files folder renamed to Files_renamed_by_imapsync\n} ) ;
  14608. $mysync->{host2} ||= 'outlook.office365.com' ;
  14609. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  14610. $mysync->{ maxsize } ||= 45_000_000 ;
  14611. $mysync->{maxmessagespersecond} ||= 4 ;
  14612. #push @{ $mysync->{ regexflag } }, 's/\\\\Flagged//g' ; # No problem without! tested 2018_09_10
  14613. $disarmreadreceipts = ( defined $disarmreadreceipts ) ? $disarmreadreceipts : 1 ;
  14614. # I dislike double negation but here is one
  14615. if ( ! $mysync->{noregexmess} )
  14616. {
  14617. push @regexmess, 's,(.{10239}),$1\r\n,g' ;
  14618. }
  14619. # and another...
  14620. if ( ! $mysync->{nof1f2} )
  14621. {
  14622. push @{ $mysync->{f1f2} }, 'Files=Files_renamed_by_imapsync' ;
  14623. }
  14624. return ;
  14625. }
  14626. sub exchange1
  14627. {
  14628. # Exchange 2010/2013 at host1
  14629. my $mysync = shift ;
  14630. output( $mysync, "Option --exchange1 does nothing (except printing this line...)\n" ) ;
  14631. # Well nothing to do so far
  14632. return ;
  14633. }
  14634. sub exchange2
  14635. {
  14636. # Exchange 2010/2013 at host2
  14637. my $mysync = shift ;
  14638. output( $mysync, "Option --exchange2 is like: --maxsize 10_000_000 --maxmessagespersecond 4 --disarmreadreceipts\n" ) ;
  14639. output( $mysync, "Option --exchange2 (cont) : --regexflag del Flagged --regexmess wrap 10500\n" ) ;
  14640. output( $mysync, "Option --exchange2 (cont) : unless overrided with --maxsize xxx --nodisarmreadreceipts --noregexflag --noregexmess\n" ) ;
  14641. $mysync->{ maxsize } ||= 10_000_000 ;
  14642. $mysync->{maxmessagespersecond} ||= 4 ;
  14643. $disarmreadreceipts = ( defined $disarmreadreceipts ) ? $disarmreadreceipts : 1 ;
  14644. # I dislike double negation but here are two
  14645. if ( ! $mysync->{noregexflag} ) {
  14646. push @{ $mysync->{ regexflag } }, 's/\\\\Flagged//g' ;
  14647. }
  14648. if ( ! $mysync->{noregexmess} ) {
  14649. push @regexmess, 's,(.{10239}),$1\r\n,g' ;
  14650. }
  14651. return ;
  14652. }
  14653. sub domino1
  14654. {
  14655. # Domino at host1
  14656. my $mysync = shift ;
  14657. $mysync->{ sep1 } = q{\\} ;
  14658. $prefix1 = q{} ;
  14659. $messageidnodomain = ( defined $messageidnodomain ) ? $messageidnodomain : 1 ;
  14660. return ;
  14661. }
  14662. sub domino2
  14663. {
  14664. # Domino at host1
  14665. my $mysync = shift ;
  14666. $mysync->{ sep2 } = q{\\} ;
  14667. $prefix2 = q{} ;
  14668. $messageidnodomain = ( defined $messageidnodomain ) ? $messageidnodomain : 1 ;
  14669. push @{ $mysync->{ regextrans2 } }, 's,^Inbox\\\\(.*),$1,i' ;
  14670. return ;
  14671. }
  14672. sub tests_resolv
  14673. {
  14674. note( 'Entering tests_resolv()' ) ;
  14675. # is( , resolv( ), 'resolv: => ' ) ;
  14676. is( undef, resolv( ), 'resolv: no args => undef' ) ;
  14677. is( undef, resolv( q{} ), 'resolv: empty string => undef' ) ;
  14678. is( undef, resolv( 'hostnotexist' ), 'resolv: hostnotexist => undef' ) ;
  14679. is( '127.0.0.1', resolv( '127.0.0.1' ), 'resolv: 127.0.0.1 => 127.0.0.1' ) ;
  14680. is( '127.0.0.1', resolv( 'localhost' ), 'resolv: localhost => 127.0.0.1' ) ;
  14681. is( '2001:41d0:2:84e0::1', resolv( 'imapsync.lamiral.info' ), 'resolv: imapsync.lamiral.info => 2001:41d0:2:84e0::1' ) ;
  14682. # ip6-localhost ( in /etc/hosts )
  14683. is( '::1', resolv( 'ip6-localhost' ), 'resolv: ip6-localhost => ::1' ) ;
  14684. is( '::1', resolv( '::1' ), 'resolv: ::1 => ::1' ) ;
  14685. # ks2ipv6 now has CNAME ks6ipv6
  14686. is( '2001:41d0:8:d8b6::1', resolv( '2001:41d0:8:d8b6::1' ), 'resolv: 2001:41d0:8:d8b6::1 => 2001:41d0:8:d8b6::1' ) ;
  14687. is( '2001:41d0:8:9951::1', resolv( 'ks6ipv6.lamiral.info' ), 'resolv: ks6ipv6.lamiral.info => 2001:41d0:8:9951::1' ) ;
  14688. # ks6
  14689. is( '2001:41d0:8:9951::1', resolv( '2001:41d0:8:9951::1' ), 'resolv: 2001:41d0:8:9951::1 => 2001:41d0:8:9951::1' ) ;
  14690. is( '2001:41d0:8:9951::1', resolv( 'ks6ipv6.lamiral.info' ), 'resolv: ks6ipv6.lamiral.info => 2001:41d0:8:9951::1' ) ;
  14691. # ks3
  14692. is( '2001:41d0:8:bebd::1', resolv( '2001:41d0:8:bebd::1' ), 'resolv: 2001:41d0:8:bebd::1 => 2001:41d0:8:bebd::1' ) ;
  14693. is( '2001:41d0:8:bebd::1', resolv( 'ks3ipv6.lamiral.info' ), 'resolv: ks3ipv6.lamiral.info => 2001:41d0:8:bebd::1' ) ;
  14694. note( 'Leaving tests_resolv()' ) ;
  14695. return ;
  14696. }
  14697. sub resolv
  14698. {
  14699. my $host = shift @ARG ;
  14700. if ( ! $host ) { return ; }
  14701. my $addr ;
  14702. if ( defined &Socket::getaddrinfo ) {
  14703. $addr = resolv_with_getaddrinfo( $host ) ;
  14704. return( $addr ) ;
  14705. }
  14706. my $iaddr = inet_aton( $host ) ;
  14707. if ( ! $iaddr ) { return ; }
  14708. $addr = inet_ntoa( $iaddr ) ;
  14709. return $addr ;
  14710. }
  14711. sub resolv_with_getaddrinfo
  14712. {
  14713. my $host = shift @ARG ;
  14714. $sync->{ debug } and myprint( "Entering resolv_with_getaddrinfo( $host )\n" ) ;
  14715. if ( ! $host ) { return ; }
  14716. my ( $err_getaddrinfo, @res ) = Socket::getaddrinfo( $host, "", { socktype => Socket::SOCK_RAW } ) ;
  14717. if ( $err_getaddrinfo ) {
  14718. myprint( "Cannot getaddrinfo of $host: $err_getaddrinfo\n" ) ;
  14719. return ;
  14720. }
  14721. my @addr ;
  14722. while( my $ai = shift @res ) {
  14723. my ( $err_getnameinfo, $ipaddr ) = Socket::getnameinfo( $ai->{addr}, Socket::NI_NUMERICHOST(), Socket::NIx_NOSERV() ) ;
  14724. if ( $err_getnameinfo ) {
  14725. myprint( "Cannot getnameinfo of $host: $err_getnameinfo\n" ) ;
  14726. return ;
  14727. }else{
  14728. $sync->{ debug } and myprint( "$host => $ipaddr\n" ) ;
  14729. push @addr, $ipaddr ;
  14730. my $reverse ;
  14731. ( $err_getnameinfo, $reverse ) = Socket::getnameinfo( $ai->{addr}, 0, Socket::NIx_NOSERV() ) ;
  14732. $sync->{ debug } and myprint( "$host => $ipaddr => $reverse\n" ) ;
  14733. }
  14734. $sync->{ debug } and myprint( "$host => $ipaddr\n" ) ;
  14735. }
  14736. $sync->{ debug } and myprint( "Leaving resolv_with_getaddrinfo( $host => $addr[0])\n" ) ;
  14737. return $addr[0] ;
  14738. }
  14739. sub tests_resolvrev
  14740. {
  14741. note( 'Entering tests_resolvrev()' ) ;
  14742. # is( , resolvrev( ), 'resolvrev: => ' ) ;
  14743. is( undef, resolvrev( ), 'resolvrev: no args => undef' ) ;
  14744. is( undef, resolvrev( q{} ), 'resolvrev: empty string => undef' ) ;
  14745. is( undef, resolvrev( 'hostnotexist' ), 'resolvrev: hostnotexist => undef' ) ;
  14746. is( 'localhost', resolvrev( '127.0.0.1' ), 'resolvrev: 127.0.0.1 => localhost' ) ;
  14747. is( 'localhost', resolvrev( 'localhost' ), 'resolvrev: localhost => localhost' ) ;
  14748. is( 'ks.lamiral.info', resolvrev( 'imapsync.lamiral.info' ), 'resolvrev: imapsync.lamiral.info => ks.lamiral.info' ) ;
  14749. # ip6-localhost ( in /etc/hosts )
  14750. is( 'ip6-localhost', resolvrev( 'ip6-localhost' ), 'resolvrev: ip6-localhost => ip6-localhost' ) ;
  14751. is( 'ip6-localhost', resolvrev( '::1' ), 'resolvrev: ::1 => ip6-localhost' ) ;
  14752. # ks2
  14753. is( 'ks6ipv6.lamiral.info', resolvrev( '2001:41d0:8:d8b6::1' ), 'resolvrev: 2001:41d0:8:d8b6::1 => ks6ipv6.lamiral.info' ) ;
  14754. is( 'ks6ipv6.lamiral.info', resolvrev( 'ks6ipv6.lamiral.info' ), 'resolvrev: ks6ipv6.lamiral.info => ks6ipv6.lamiral.info' ) ;
  14755. # ks3
  14756. is( 'ks3ipv6.lamiral.info', resolvrev( '2001:41d0:8:bebd::1' ), 'resolvrev: 2001:41d0:8:bebd::1 => ks3ipv6.lamiral.info' ) ;
  14757. is( 'ks3ipv6.lamiral.info', resolvrev( 'ks3ipv6.lamiral.info' ), 'resolvrev: ks3ipv6.lamiral.info => ks3ipv6.lamiral.info' ) ;
  14758. note( 'Leaving tests_resolvrev()' ) ;
  14759. return ;
  14760. }
  14761. sub resolvrev
  14762. {
  14763. my $host = shift @ARG ;
  14764. if ( ! $host ) { return ; }
  14765. if ( defined &Socket::getaddrinfo ) {
  14766. my $name = resolvrev_with_getaddrinfo( $host ) ;
  14767. return( $name ) ;
  14768. }
  14769. return ;
  14770. }
  14771. sub resolvrev_with_getaddrinfo
  14772. {
  14773. my $host = shift @ARG ;
  14774. if ( ! $host ) { return ; }
  14775. my ( $err, @res ) = Socket::getaddrinfo( $host, "", { socktype => Socket::SOCK_RAW } ) ;
  14776. if ( $err ) {
  14777. myprint( "Cannot getaddrinfo of $host: $err\n" ) ;
  14778. return ;
  14779. }
  14780. my @name ;
  14781. while( my $ai = shift @res ) {
  14782. my ( $err, $reverse ) = Socket::getnameinfo( $ai->{addr}, 0, Socket::NIx_NOSERV() ) ;
  14783. if ( $err ) {
  14784. myprint( "Cannot getnameinfo of $host: $err\n" ) ;
  14785. return ;
  14786. }
  14787. $sync->{ debug } and myprint( "$host => $reverse\n" ) ;
  14788. push @name, $reverse ;
  14789. }
  14790. return $name[0] ;
  14791. }
  14792. sub tests_imapsping
  14793. {
  14794. note( 'Entering tests_imapsping()' ) ;
  14795. is( undef, imapsping( ), 'imapsping: no args => undef' ) ;
  14796. is( undef, imapsping( 'hostnotexist' ), 'imapsping: hostnotexist => undef' ) ;
  14797. is( 1, imapsping( 'imapsync.lamiral.info' ), 'imapsping: imapsync.lamiral.info => 1' ) ;
  14798. is( 1, imapsping( 'ks6ipv6.lamiral.info' ), 'imapsping: ks6ipv6.lamiral.info => 1' ) ;
  14799. note( 'Leaving tests_imapsping()' ) ;
  14800. return ;
  14801. }
  14802. sub imapsping
  14803. {
  14804. my $host = shift ;
  14805. return tcpping( $host, $IMAP_SSL_PORT ) ;
  14806. }
  14807. sub tests_tcpping
  14808. {
  14809. note( 'Entering tests_tcpping()' ) ;
  14810. is( undef, tcpping( ), 'tcpping: no args => undef' ) ;
  14811. is( undef, tcpping( 'hostnotexist' ), 'tcpping: one arg => undef' ) ;
  14812. is( undef, tcpping( undef, 888 ), 'tcpping: arg undef, port => undef' ) ;
  14813. is( undef, tcpping( 'hostnotexist', 993 ), 'tcpping: hostnotexist 993 => undef' ) ;
  14814. is( undef, tcpping( 'hostnotexist', 888 ), 'tcpping: hostnotexist 888 => undef' ) ;
  14815. is( 1, tcpping( 'imapsync.lamiral.info', 993 ), 'tcpping: imapsync.lamiral.info 993 => 1' ) ;
  14816. is( 0, tcpping( 'imapsync.lamiral.info', 888 ), 'tcpping: imapsync.lamiral.info 888 => 0' ) ;
  14817. is( 1, tcpping( '5.135.158.182', 993 ), 'tcpping: 5.135.158.182 993 => 1' ) ;
  14818. is( 0, tcpping( '5.135.158.182', 888 ), 'tcpping: 5.135.158.182 888 => 0' ) ;
  14819. # Net::Ping supports ipv6 only after release 1.50
  14820. # http://cpansearch.perl.org/src/RURBAN/Net-Ping-2.59/Changes
  14821. # Anyway I plan to avoid Net-Ping for that too long standing feature
  14822. # Net-Ping is integrated in Perl itself, who knows ipv6 for a long time
  14823. is( 1, tcpping( '2001:41d0:8:d8b6::1', 993 ), 'tcpping: 2001:41d0:8:d8b6::1 993 => 1' ) ;
  14824. is( 0, tcpping( '2001:41d0:8:d8b6::1', 888 ), 'tcpping: 2001:41d0:8:d8b6::1 888 => 0' ) ;
  14825. note( 'Leaving tests_tcpping()' ) ;
  14826. return ;
  14827. }
  14828. sub tcpping
  14829. {
  14830. if ( 2 != scalar( @ARG ) ) {
  14831. return ;
  14832. }
  14833. my ( $host, $port ) = @ARG ;
  14834. if ( ! $host ) { return ; }
  14835. if ( ! $port ) { return ; }
  14836. my $mytimeout = $TCP_PING_TIMEOUT ;
  14837. require Net::Ping ;
  14838. #my $p = Net::Ping->new( 'tcp' ) ;
  14839. my $p = Net::Ping->new( ) ;
  14840. $p->{port_num} = $port ;
  14841. $p->service_check( 1 ) ;
  14842. $p->hires( 1 ) ;
  14843. my ($ping_ok, $rtt, $ip ) = $p->ping( $host, $mytimeout ) ;
  14844. if ( ! defined $ping_ok ) { return ; }
  14845. my $rtt_approx = sprintf( "%.3f", $rtt ) ;
  14846. $sync->{ debug } and myprint( "Host $host timeout $mytimeout port $port ok $ping_ok ip $ip acked in $rtt_approx s\n" ) ;
  14847. $p->close( ) ;
  14848. if( $ping_ok ) {
  14849. return 1 ;
  14850. }else{
  14851. return 0 ;
  14852. }
  14853. }
  14854. sub tests_sslcheck
  14855. {
  14856. note( 'Entering tests_sslcheck()' ) ;
  14857. my $mysync ;
  14858. is( undef, sslcheck( $mysync ), 'sslcheck: no sslcheck => undef' ) ;
  14859. $mysync = {
  14860. sslcheck => 1,
  14861. } ;
  14862. is( 0, sslcheck( $mysync ), 'sslcheck: no host => 0' ) ;
  14863. $mysync = {
  14864. sslcheck => 1,
  14865. host1 => 'test1.lamiral.info',
  14866. tls1 => 1,
  14867. } ;
  14868. is( 0, sslcheck( $mysync ), 'sslcheck: tls1 => 0' ) ;
  14869. $mysync = {
  14870. sslcheck => 1,
  14871. host1 => 'test1.lamiral.info',
  14872. } ;
  14873. is( 1, sslcheck( $mysync ), 'sslcheck: test1.lamiral.info => 1' ) ;
  14874. is( 1, $mysync->{ssl1}, 'sslcheck: test1.lamiral.info => ssl1 1' ) ;
  14875. $mysync->{sslcheck} = 0 ;
  14876. is( undef, sslcheck( $mysync ), 'sslcheck: sslcheck off => undef' ) ;
  14877. $mysync = {
  14878. sslcheck => 1,
  14879. host1 => 'test1.lamiral.info',
  14880. host2 => 'test2.lamiral.info',
  14881. } ;
  14882. is( 2, sslcheck( $mysync ), 'sslcheck: test1.lamiral.info + test2.lamiral.info => 2' ) ;
  14883. $mysync = {
  14884. sslcheck => 1,
  14885. host1 => 'test1.lamiral.info',
  14886. host2 => 'test2.lamiral.info',
  14887. tls1 => 1,
  14888. } ;
  14889. is( 1, sslcheck( $mysync ), 'sslcheck: test1.lamiral.info + test2.lamiral.info + tls1 => 1' ) ;
  14890. note( 'Leaving tests_sslcheck()' ) ;
  14891. return ;
  14892. }
  14893. sub sslcheck
  14894. {
  14895. my $mysync = shift ;
  14896. if ( ! $mysync->{sslcheck} ) {
  14897. return ;
  14898. }
  14899. my $nb_on = 0 ;
  14900. $mysync->{ debug } and myprint( "sslcheck\n" ) ;
  14901. if (
  14902. ( ! defined $mysync->{port1} )
  14903. and
  14904. ( ! defined $mysync->{tls1} )
  14905. and
  14906. ( ! defined $mysync->{ssl1} )
  14907. and
  14908. ( defined $mysync->{host1} )
  14909. ) {
  14910. myprint( "Host1: probing ssl on port $IMAP_SSL_PORT ( use --nosslcheck to avoid this ssl probe ) \n" ) ;
  14911. if ( probe_imapssl( $mysync->{host1} ) ) {
  14912. $mysync->{ssl1} = 1 ;
  14913. 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" ) ;
  14914. $nb_on++ ;
  14915. }else{
  14916. myprint( "Host1: sslcheck did not detected open ssl port $IMAP_SSL_PORT. Will use standard $IMAP_PORT port.\n" ) ;
  14917. }
  14918. }
  14919. if (
  14920. ( ! defined $mysync->{port2} )
  14921. and
  14922. ( ! defined $mysync->{tls2} )
  14923. and
  14924. ( ! defined $mysync->{ssl2} )
  14925. and
  14926. ( defined $mysync->{host2} )
  14927. ) {
  14928. myprint( "Host2: probing ssl on port $IMAP_SSL_PORT ( use --nosslcheck to avoid this ssl probe ) \n" ) ;
  14929. if ( probe_imapssl( $mysync->{host2} ) ) {
  14930. $mysync->{ssl2} = 1 ;
  14931. 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" ) ;
  14932. $nb_on++ ;
  14933. }else{
  14934. myprint( "Host2: sslcheck did not detected open ssl port $IMAP_SSL_PORT. Will use standard $IMAP_PORT port.\n" ) ;
  14935. }
  14936. }
  14937. return $nb_on ;
  14938. }
  14939. sub testslive_init
  14940. {
  14941. my $mysync = shift ;
  14942. $mysync->{host1} ||= 'test1.lamiral.info' ;
  14943. $mysync->{user1} ||= 'test1' ;
  14944. $mysync->{password1} ||= 'secret1' ;
  14945. $mysync->{host2} ||= 'test2.lamiral.info' ;
  14946. $mysync->{user2} ||= 'test2' ;
  14947. $mysync->{password2} ||= 'secret2' ;
  14948. return ;
  14949. }
  14950. sub testslive6_init
  14951. {
  14952. my $mysync = shift ;
  14953. $mysync->{host1} ||= 'ks6ipv6.lamiral.info' ;
  14954. $mysync->{user1} ||= 'test1' ;
  14955. $mysync->{password1} ||= 'secret1' ;
  14956. $mysync->{host2} ||= 'ks6ipv6.lamiral.info' ;
  14957. $mysync->{user2} ||= 'test2' ;
  14958. $mysync->{password2} ||= 'secret2' ;
  14959. return ;
  14960. }
  14961. sub tests_backslash_caret
  14962. {
  14963. note( 'Entering tests_backslash_caret()' ) ;
  14964. is( "lalala", backslash_caret( "lalala" ), 'backslash_caret: lalala => lalala' ) ;
  14965. is( "lalala\n", backslash_caret( "lalala\n" ), 'backslash_caret: lalala => lalala 2nd' ) ;
  14966. is( '^', backslash_caret( '\\' ), 'backslash_caret: \\ => ^' ) ;
  14967. is( "^\n", backslash_caret( "\\\n" ), 'backslash_caret: \\ => ^' ) ;
  14968. is( "\\lalala", backslash_caret( "\\lalala" ), 'backslash_caret: \\lalala => \\lalala' ) ;
  14969. is( "\\lal\\ala", backslash_caret( "\\lal\\ala" ), 'backslash_caret: \\lal\\ala => \\lal\\ala' ) ;
  14970. is( "\\lalala\n", backslash_caret( "\\lalala\n" ), 'backslash_caret: \\lalala => \\lalala 2nd' ) ;
  14971. is( "lalala^\n", backslash_caret( "lalala\\\n" ), 'backslash_caret: lalala\\\n => lalala^\n' ) ;
  14972. is( "lalala^\nlalala^\n", backslash_caret( "lalala\\\nlalala\\\n" ), 'backslash_caret: lalala\\\nlalala\\\n => lalala^\nlalala^\n' ) ;
  14973. is( "lal\\ala^\nlalala^\n", backslash_caret( "lal\\ala\\\nlalala\\\n" ), 'backslash_caret: lal\\ala\\\nlalala\\\n => lal\\ala^\nlalala^\n' ) ;
  14974. note( 'Leaving tests_backslash_caret()' ) ;
  14975. return ;
  14976. }
  14977. sub backslash_caret
  14978. {
  14979. my $string = shift ;
  14980. $string =~ s{\\ $ }{^}gxms ;
  14981. return $string ;
  14982. }
  14983. sub tests_split_around_equal
  14984. {
  14985. note( 'Entering tests_split_around_equal()' ) ;
  14986. is( undef, split_around_equal( ), 'split_around_equal: no args => undef' ) ;
  14987. is_deeply( { toto => 'titi' }, { split_around_equal( 'toto=titi' ) }, 'split_around_equal: toto=titi => toto => titi' ) ;
  14988. is_deeply( { A => 'B', C => 'D' }, { split_around_equal( 'A=B=C=D' ) }, 'split_around_equal: toto=titi => toto => titi' ) ;
  14989. is_deeply( { A => 'B', C => 'D' }, { split_around_equal( 'A=B', 'C=D' ) }, 'split_around_equal: A=B C=D => A => B, C=>D' ) ;
  14990. note( 'Leaving tests_split_around_equal()' ) ;
  14991. return ;
  14992. }
  14993. sub split_around_equal
  14994. {
  14995. if ( ! @ARG ) { return ; } ;
  14996. return map { split /=/mxs, $_ } @ARG ;
  14997. }
  14998. sub tests_sig_install
  14999. {
  15000. note( 'Entering tests_sig_install()' ) ;
  15001. my $mysync ;
  15002. is( undef, sig_install( ), 'sig_install: no args => undef' ) ;
  15003. is( undef, sig_install( $mysync ), 'sig_install: arg undef => undef' ) ;
  15004. $mysync = { } ;
  15005. is( undef, sig_install( $mysync ), 'sig_install: empty hash => undef' ) ;
  15006. SKIP: {
  15007. Readonly my $SKIP_15 => 15 ;
  15008. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests only for Unix', $SKIP_15 ) ; }
  15009. # Default to ignore USR1 USR2 in case future install fails
  15010. local $SIG{ USR1 } = local $SIG{ USR2 } = sub { } ;
  15011. kill( 'USR1', $PROCESS_ID ) ;
  15012. $mysync->{ debugsig } = 1 ;
  15013. # Assign USR1 to call sub tototo
  15014. # Surely a better value than undef should be returned when doing real signal stuff
  15015. is( undef, sig_install( $mysync, 'tototo', 'USR1' ), 'sig_install: USR1 tototo' ) ;
  15016. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 1' ) ;
  15017. is( 1, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 1' ) ;
  15018. #return ;
  15019. # Assign USR2 to call sub tototo
  15020. is( undef, sig_install( $mysync, 'tototo', 'USR2' ), 'sig_install: USR2 tototo' ) ;
  15021. is( 1, kill( 'USR2', $PROCESS_ID ), 'sig_install: kill USR2 myself 1' ) ;
  15022. is( 2, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 2' ) ;
  15023. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 2' ) ;
  15024. is( 3, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 3' ) ;
  15025. local $SIG{ USR1 } = local $SIG{ USR2 } = sub { } ;
  15026. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 3' ) ;
  15027. is( 3, $mysync->{ tototo_calls }, 'sig_install: tototo call still nb 3' ) ;
  15028. # Assign USR1 + USR2 to call sub tototo
  15029. is( undef, sig_install( $mysync, 'tototo', 'USR1', 'USR2' ), 'sig_install: USR1 USR2 tototo' ) ;
  15030. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 4' ) ;
  15031. is( 4, $mysync->{ tototo_calls }, 'sig_install: tototo call now nb 4' ) ;
  15032. is( 1, kill( 'USR2', $PROCESS_ID ), 'sig_install: kill USR1 myself 2' ) ;
  15033. is( 5, $mysync->{ tototo_calls }, 'sig_install: tototo call now nb 5' ) ;
  15034. }
  15035. note( 'Leaving tests_sig_install()' ) ;
  15036. return ;
  15037. }
  15038. #
  15039. sub sig_install
  15040. {
  15041. my $mysync = shift ;
  15042. if ( ! $mysync ) { return ; }
  15043. my $mysubname = shift ;
  15044. if ( ! $mysubname ) { return ; }
  15045. if ( ! @ARG ) { return ; }
  15046. my @signals = @ARG ;
  15047. my $mysub = \&$mysubname ;
  15048. #$mysync->{ debugsig } = 1 ;
  15049. $mysync->{ debugsig } and myprint( "In sig_install with sub $mysubname and signal @ARG\n" ) ;
  15050. my $subsignal = sub {
  15051. my $signame = shift ;
  15052. $mysync->{ debugsig } and myprint( "In subsignal with $signame and $mysubname\n" ) ;
  15053. &$mysub( $mysync, $signame ) ;
  15054. } ;
  15055. foreach my $signal ( @signals ) {
  15056. $mysync->{ debugsig } and myprint( "Installing signal $signal to call sub $mysubname\n") ;
  15057. output( $mysync, "kill -$signal $PROCESS_ID # special behavior: call to sub $mysubname\n" ) ;
  15058. ## no critic (RequireLocalizedPunctuationVars)
  15059. $SIG{ $signal } = $subsignal ;
  15060. }
  15061. return ;
  15062. }
  15063. sub tototo
  15064. {
  15065. my $mysync = shift ;
  15066. myprint("In tototo with @ARG\n" ) ;
  15067. $mysync->{ tototo_calls } += 1 ;
  15068. return ;
  15069. }
  15070. sub mygetppid
  15071. {
  15072. if ( 'MSWin32' eq $OSNAME ) {
  15073. return( 'unknown under MSWin32 (too complicated)' ) ;
  15074. } else {
  15075. # Unix
  15076. return( getppid( ) ) ;
  15077. }
  15078. }
  15079. sub tests_toggle_sleep
  15080. {
  15081. note( 'Entering tests_toggle_sleep()' ) ;
  15082. is( undef, toggle_sleep( ), 'toggle_sleep: no args => undef' ) ;
  15083. my $mysync ;
  15084. is( undef, toggle_sleep( $mysync ), 'toggle_sleep: undef => undef' ) ;
  15085. $mysync = { } ;
  15086. is( undef, toggle_sleep( $mysync ), 'toggle_sleep: no maxsleep => undef' ) ;
  15087. $mysync->{maxsleep} = 3 ;
  15088. is( 0, toggle_sleep( $mysync ), 'toggle_sleep: 3 => 0' ) ;
  15089. is( $MAX_SLEEP, toggle_sleep( $mysync ), "toggle_sleep: 0 => $MAX_SLEEP" ) ;
  15090. is( 0, toggle_sleep( $mysync ), "toggle_sleep: $MAX_SLEEP => 0" ) ;
  15091. is( $MAX_SLEEP, toggle_sleep( $mysync ), "toggle_sleep: 0 => $MAX_SLEEP" ) ;
  15092. is( 0, toggle_sleep( $mysync ), "toggle_sleep: $MAX_SLEEP => 0" ) ;
  15093. SKIP: {
  15094. Readonly my $SKIP_9 => 9 ;
  15095. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests only for Unix', $SKIP_9 ) ; }
  15096. # Default to ignore USR1 USR2 in case future install fails
  15097. local $SIG{ USR1 } = sub { } ;
  15098. kill( 'USR1', $PROCESS_ID ) ;
  15099. $mysync->{ debugsig } = 1 ;
  15100. # Assign USR1 to call sub toggle_sleep
  15101. is( undef, sig_install( $mysync, \&toggle_sleep, 'USR1' ), 'toggle_sleep: install USR1 toggle_sleep' ) ;
  15102. $mysync->{maxsleep} = 4 ;
  15103. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself' ) ;
  15104. is( 0, $mysync->{ maxsleep }, 'toggle_sleep: toggle_sleep called => sleeps are 0s' ) ;
  15105. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself again' ) ;
  15106. is( $MAX_SLEEP, $mysync->{ maxsleep }, "toggle_sleep: toggle_sleep called => sleeps are ${MAX_SLEEP}s" ) ;
  15107. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself' ) ;
  15108. is( 0, $mysync->{ maxsleep }, 'toggle_sleep: toggle_sleep called => sleeps are 0s' ) ;
  15109. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself again' ) ;
  15110. is( $MAX_SLEEP, $mysync->{ maxsleep }, "toggle_sleep: toggle_sleep called => sleeps are ${MAX_SLEEP}s" ) ;
  15111. }
  15112. note( 'Leaving tests_toggle_sleep()' ) ;
  15113. return ;
  15114. }
  15115. sub toggle_sleep
  15116. {
  15117. my $mysync = shift ;
  15118. myprint("In toggle_sleep with @ARG\n" ) ;
  15119. if ( !defined( $mysync ) ) { return ; }
  15120. if ( !defined( $mysync->{maxsleep} ) ) { return ; }
  15121. $mysync->{ maxsleep } = max( 0, $MAX_SLEEP - $mysync->{maxsleep} ) ;
  15122. myprint("Resetting maxsleep to ", $mysync->{maxsleep}, "s\n" ) ;
  15123. return $mysync->{maxsleep} ;
  15124. }
  15125. sub mypod2usage
  15126. {
  15127. my $fh_pod2usage = shift ;
  15128. pod2usage(
  15129. -exitval => 'NOEXIT',
  15130. -noperldoc => 1,
  15131. -verbose => 99,
  15132. -sections => [ qw(NAME VERSION USAGE OPTIONS) ],
  15133. -indent => 1,
  15134. -loose => 1,
  15135. -output => $fh_pod2usage,
  15136. ) ;
  15137. return ;
  15138. }
  15139. sub usage
  15140. {
  15141. my $mysync = shift ;
  15142. if ( ! defined $mysync ) { return ; }
  15143. my $usage = q{} ;
  15144. my $usage_from_pod ;
  15145. my $usage_footer = usage_footer( $mysync ) ;
  15146. # pod2usage writes on a filehandle only and I want a variable
  15147. open my $fh_pod2usage, ">", \$usage_from_pod
  15148. or do { warn $OS_ERROR ; return ; } ;
  15149. mypod2usage( $fh_pod2usage ) ;
  15150. close $fh_pod2usage ;
  15151. if ( 'MSWin32' eq $OSNAME ) {
  15152. $usage_from_pod = backslash_caret( $usage_from_pod ) ;
  15153. }
  15154. $usage = join( q{}, $usage_from_pod, $usage_footer ) ;
  15155. return( $usage ) ;
  15156. }
  15157. sub tests_usage
  15158. {
  15159. note( 'Entering tests_usage()' ) ;
  15160. my $usage ;
  15161. like( $usage = usage( $sync ), qr/Name:/, 'usage: contains Name:' ) ;
  15162. myprint( $usage ) ;
  15163. like( $usage, qr/Version:/, 'usage: contains Version:' ) ;
  15164. like( $usage, qr/Usage:/, 'usage: contains Usage:' ) ;
  15165. like( $usage, qr/imapsync/, 'usage: contains imapsync' ) ;
  15166. is( undef, usage( ), 'usage: no args => undef' ) ;
  15167. note( 'Leaving tests_usage()' ) ;
  15168. return ;
  15169. }
  15170. sub usage_footer
  15171. {
  15172. my $mysync = shift ;
  15173. my $footer = q{} ;
  15174. my $localhost_info = localhost_info( $mysync ) ;
  15175. my $rcs = $mysync->{rcs} ;
  15176. my $homepage = homepage( ) ;
  15177. my $imapsync_release = $STR_use_releasecheck ;
  15178. if ( $mysync->{releasecheck} ) {
  15179. $imapsync_release = check_last_release( ) ;
  15180. }
  15181. $footer = qq{$localhost_info
  15182. $rcs
  15183. $imapsync_release
  15184. $homepage
  15185. } ;
  15186. return( $footer ) ;
  15187. }
  15188. sub usage_complete
  15189. {
  15190. # Unused, I guess this function could be deleted
  15191. my $usage = <<'EOF' ;
  15192. --skipheader reg : Don't take into account header keyword
  15193. matching reg ex: --skipheader 'X.*'
  15194. --skipsize : Don't take message size into account to compare
  15195. messages on both sides. On by default.
  15196. Use --no-skipsize for using size comparaison.
  15197. --allowsizemismatch : allow RFC822.SIZE != fetched msg size
  15198. consider also --skipsize to avoid duplicate messages
  15199. when running syncs more than one time per mailbox
  15200. --reconnectretry1 int : reconnect to host1 if connection is lost up to
  15201. int times per imap command (default is 3)
  15202. --reconnectretry2 int : same as --reconnectretry1 but for host2
  15203. --split1 int : split the requests in several parts on host1.
  15204. int is the number of messages handled per request.
  15205. default is like --split1 100.
  15206. --split2 int : same thing on host2.
  15207. --nofixInboxINBOX : Don't fix Inbox INBOX mapping.
  15208. EOF
  15209. return( $usage ) ;
  15210. }
  15211. sub setvalfromcgikey
  15212. {
  15213. my ( $mysync, $mycgi, $key, $val ) = @ARG ;
  15214. my $badthings = 0 ;
  15215. my ( $name, $type, $struct ) ;
  15216. if ( $key !~ m/^([\w\d\|]+)([=:][isf])?([\+!\@\%])?$/mxs )
  15217. {
  15218. $badthings++ ;
  15219. next ; # Unknown item
  15220. }
  15221. else
  15222. {
  15223. $name = [ split '|', $1, 1 ]->[0] ; # option name ab|cd|ef => keep only ab
  15224. $type = $2 ; # = or : followed by i or s or f
  15225. $struct = $3 ; # + or ! or @ or %
  15226. }
  15227. if ( ( $struct || q{} ) eq '+' )
  15228. {
  15229. ${$val} = $mycgi->param( $name ) ; # "Incremental" integer
  15230. }
  15231. elsif ( $type )
  15232. {
  15233. my @values = $mycgi->multi_param( $name ) ;
  15234. #myprint( "type[$type]values[@values]\$struct[", $struct || q{}, "]val[$val]ref(val)[", ref($val), "]\n" ) ;
  15235. if ( ( $struct || q{} ) eq '%' or ref( $val ) eq 'HASH' )
  15236. {
  15237. setvalfromhash( $val, $type, @values ) ;
  15238. }
  15239. else
  15240. {
  15241. setvalfromlist( $mysync, $val, $name, $type, $struct, @values ) ;
  15242. }
  15243. }
  15244. else
  15245. {
  15246. setvalfromcheckbox( $mysync, $mycgi, $key, $name, $val ) ;
  15247. }
  15248. return $badthings ;
  15249. }
  15250. sub setvalfromlist
  15251. {
  15252. my ( $mysync, $val, $name, $type, $struct, @values ) = @ARG ;
  15253. if ( $type =~ m/i$/mxs )
  15254. {
  15255. @values = map { q{} ne $_ ? int $_ : undef } @values ;
  15256. }
  15257. elsif ( $type =~ m/f$/mxs )
  15258. {
  15259. @values = map { 0 + $_ } @values ;
  15260. }
  15261. if ( ( $struct || q{} ) eq '@' )
  15262. {
  15263. @{ ${$val} } = @values ;
  15264. my @option = map { +( "--$name", "$_" ) } @values ;
  15265. push @{ $mysync->{ cmdcgi } }, @option ;
  15266. }
  15267. elsif ( ref( $val ) eq 'ARRAY' )
  15268. {
  15269. @{$val} = @values ;
  15270. }
  15271. elsif ( my $value = $values[0] )
  15272. {
  15273. ${$val} = $value ;
  15274. push @{ $mysync->{ cmdcgi } }, "--$name", $value ;
  15275. }
  15276. else
  15277. {
  15278. }
  15279. return ;
  15280. }
  15281. sub setvalfromhash
  15282. {
  15283. my ( $val, $type, @values ) = @ARG ;
  15284. my %values = map { split /=/mxs, $_ } @values ;
  15285. if ( $type =~ m/i$/mxs )
  15286. {
  15287. foreach my $k ( keys %values )
  15288. {
  15289. $values{$k} = int $values{$k} ;
  15290. }
  15291. }
  15292. elsif ( $type =~ m/f$/mxs )
  15293. {
  15294. foreach my $k ( keys %values ) {
  15295. $values{$k} = 0 + $values{$k};
  15296. }
  15297. }
  15298. if ( 'REF' eq ref $val )
  15299. {
  15300. %{ ${$val} } = %values ;
  15301. }
  15302. else
  15303. {
  15304. %{$val} = %values ;
  15305. }
  15306. return ;
  15307. }
  15308. sub setvalfromcheckbox
  15309. {
  15310. my ( $mysync, $mycgi, $key, $name, $val ) = @ARG ;
  15311. # Checkbox
  15312. # --noname is set by name=0 or name=
  15313. my $value = $mycgi->param( $name ) ;
  15314. if ( defined $value )
  15315. {
  15316. ${$val} = $value ;
  15317. if ( $value )
  15318. {
  15319. push @{ $mysync->{ cmdcgi } }, "--$name" ;
  15320. }
  15321. else
  15322. {
  15323. push @{ $mysync->{ cmdcgi } }, "--no$name" ;
  15324. }
  15325. }
  15326. else
  15327. {
  15328. ${$val} = undef ;
  15329. }
  15330. return ;
  15331. }
  15332. sub myGetOptions
  15333. {
  15334. # Started as a copy of Luke Ross Getopt::Long::CGI
  15335. # https://metacpan.org/release/Getopt-Long-CGI
  15336. # So this sub function is under the same license as Getopt-Long-CGI Luke Ross wants it,
  15337. # which was Perl 5.6 or later licenses at the date of the copy.
  15338. # It also applies for the sub functions called from this one.
  15339. my $mysync = shift @ARG ;
  15340. my $arguments_ref = shift @ARG ;
  15341. my %options = @ARG ;
  15342. my $mycgi = $mysync->{cgi} ;
  15343. if ( not under_cgi_context() ) {
  15344. # Not CGI - pass upstream for normal command line handling
  15345. return Getopt::Long::GetOptionsFromArray( $arguments_ref, %options ) ;
  15346. }
  15347. # We must be in CGI context now
  15348. if ( ! defined( $mycgi ) ) { return ; }
  15349. my $badthings = 0 ;
  15350. foreach my $key ( sort keys %options ) {
  15351. my $val = $options{$key} ;
  15352. $badthings += setvalfromcgikey( $mysync, $mycgi, $key, $val ) ;
  15353. }
  15354. if ( $badthings ) {
  15355. return ; # undef or ()
  15356. }
  15357. else {
  15358. return ( 1 ) ;
  15359. }
  15360. }
  15361. sub tests_get_options_extra
  15362. {
  15363. note( 'Entering tests_get_options_extra()' ) ;
  15364. is( undef, get_options_extra( ), 'get_options_extra: no args => undef' ) ;
  15365. my $mysync = { } ;
  15366. is( undef, get_options_extra( $mysync ), 'get_options_extra: undef => undef' ) ;
  15367. my $cwd_save = getcwd( ) ;
  15368. ok( (-d 'W/tmp/tests/options_extra/' or mkpath( 'W/tmp/tests/options_extra/' )), 'get_options_extra: mkpath W/tmp/tests/options_extra/' ) ;
  15369. chdir 'W/tmp/tests/options_extra/' ;
  15370. is( '--debugimap1', string_to_file( '--debugimap1', 'options_extra.txt' ), 'get_options_extra: string_to_file filling options_extra.txt with --debugimap1' ) ;
  15371. is( '--debugimap1', file_to_string( 'options_extra.txt' ), 'get_options_extra: reading options_extra.txt is --debugimap1' ) ;
  15372. is( '', get_options_extra( $mysync ), 'get_options_extra: --debugimap1 in options_extra.txt => nothing left, empty string return' ) ;
  15373. is( 1, $mysync->{ acc1 }->{ debugimap }, 'get_options_extra: --debugimap1 in options_extra.txt => ok, acc1->debugimap = 1' ) ;
  15374. is( '--tls1 proutcaca', string_to_file( '--tls1 proutcaca', 'options_extra.txt' ), 'get_options_extra: string_to_file filling options_extra.txt with --tls1 proutcaca' ) ;
  15375. is( 'proutcaca', get_options_extra( $mysync ), 'get_options_extra: --tls1 proutcaca in options_extra.txt => proutcaca left, proutcaca return' ) ;
  15376. chdir $cwd_save ;
  15377. note( 'Leaving tests_get_options_extra()' ) ;
  15378. return ;
  15379. }
  15380. sub get_options_extra
  15381. {
  15382. my $mysync = shift @ARG ;
  15383. if ( ! defined $mysync ) { return ; }
  15384. if ( -f -r 'options_extra.txt' )
  15385. {
  15386. my $cwd = getcwd( ) ;
  15387. my $string = firstline( 'options_extra.txt' ) ;
  15388. my $rest = get_options_from_string( $mysync, $string ) ;
  15389. output( $mysync, "Reading extra options from file options_extra.txt (cwd: $cwd) : $string\n" ) ;
  15390. return $rest ;
  15391. }
  15392. else
  15393. {
  15394. return ;
  15395. }
  15396. }
  15397. sub tests_get_options_from_string
  15398. {
  15399. note( 'Entering tests_get_options_from_string()' ) ;
  15400. is( undef, get_options_from_string( ), 'get_options_from_string: no args => undef' ) ;
  15401. my $mysync = { } ;
  15402. is( undef, get_options_from_string( $mysync ), 'get_options_from_string: undef => undef' ) ;
  15403. is( '', get_options_from_string( $mysync, '--debugimap1' ),
  15404. 'get_options_from_string: --debugimap1 => ok, nothing left, empty string return' ) ;
  15405. is( 1, $mysync->{ acc1 }->{ debugimap }, 'get_options_from_string: --debugimap1 => ok, acc1->debugimap = 1' ) ;
  15406. $mysync = { } ; # reset
  15407. is( 'caca', get_options_from_string( $mysync, '--debugimap1 caca' ),
  15408. 'get_options_from_string: --debugimap1 caca => ok, caca left, caca return' ) ;
  15409. is( 1, $mysync->{ acc1 }->{ debugimap }, 'get_options_from_string: --debugimap1 => ok, acc1->debugimap = 1' ) ;
  15410. is( 'popo roro', get_options_from_string( $mysync, '--debugimap2 popo roro' ),
  15411. 'get_options_from_string: --debugimap1 popo roro => ok, popo roro left, popo roro return' ) ;
  15412. is( 1, $mysync->{ acc2 }->{ debugimap }, 'get_options_from_string: --debugimap2 popo roro => ok, acc2->debugimap = 1' ) ;
  15413. is( 1, $mysync->{ acc1 }->{ debugimap }, 'get_options_from_string: acc1->debugimap = 1 still' ) ;
  15414. is( '', get_options_from_string( $mysync, '--nodebugimap1 --debugflags --errorsmax 2' ),
  15415. 'get_options_from_string: --nodebugimap1 --debugflags --errorsmax 2 => ok, empty string return' ) ;
  15416. is( 0, $mysync->{ acc1 }->{ debugimap }, 'get_options_from_string: acc1->debugimap = 0 now' ) ;
  15417. is( 1, $debugflags, 'get_options_from_string: debugflags = 1 now' ) ;
  15418. is( 2, $mysync->{ errorsmax }, 'get_options_from_string: mysync->errorsmax = 2 now' ) ;
  15419. is( '', get_options_from_string( $mysync, '--folder "IN BOX" --folder JOE' ),
  15420. 'get_options_from_string: --folder "IN BOX" --folder JOE => ok, empty string return' ) ;
  15421. is_deeply( [ 'IN BOX', 'JOE' ], [@{$mysync->{ folder }}], 'get_options_from_string: "IN BOX" "JOE"' ) ;
  15422. is( '', get_options_from_string( $mysync, '--debugflags --koko' ),
  15423. 'get_options_from_string: --debugflags --koko => ok, empty string return, with "Unknown option: koko" on STDERR' ) ;
  15424. note( 'Leaving tests_get_options_from_string()' ) ;
  15425. return ;
  15426. }
  15427. sub get_options_from_string
  15428. {
  15429. my $mysync = shift @ARG ;
  15430. my $mystring = shift @ARG ;
  15431. if ( ! defined $mystring ) { return ; }
  15432. my ( $ret, $args ) = Getopt::Long::GetOptionsFromString( $mystring,
  15433. 'debugimap!' => \$mysync->{ debugimap },
  15434. 'debugimap1!' => \$mysync->{ acc1 }->{ debugimap },
  15435. 'debugimap2!' => \$mysync->{ acc2 }->{ debugimap },
  15436. 'debugflags!' => \$debugflags,
  15437. 'debugsleep=f' => \$mysync->{ debugsleep },
  15438. 'errorsmax=i' => \$mysync->{ errorsmax },
  15439. 'folder=s@' => \$mysync->{ folder },
  15440. 'timeout=f' => \$mysync->{ timeout },
  15441. 'timeout1=f' => \$mysync->{ acc1 }->{ timeout },
  15442. 'timeout2=f' => \$mysync->{ acc2 }->{ timeout },
  15443. 'keepalive1!' => \$mysync->{ acc1 }->{ keepalive },
  15444. 'keepalive2!' => \$mysync->{ acc2 }->{ keepalive },
  15445. 'reconnectretry1=i' => \$mysync->{ acc1 }->{ reconnectretry },
  15446. 'reconnectretry2=i' => \$mysync->{ acc2 }->{ reconnectretry },
  15447. 'ssl1!' => \$mysync->{ ssl1 },
  15448. 'ssl2!' => \$mysync->{ ssl2 },
  15449. 'tls1!' => \$mysync->{ tls1 },
  15450. 'tls2!' => \$mysync->{ tls2 },
  15451. 'compress1!' => \$mysync->{ acc1 }->{ compress },
  15452. 'compress2!' => \$mysync->{ acc2 }->{ compress },
  15453. ) ;
  15454. my $left = join( ' ', @$args ) ;
  15455. return $left ;
  15456. }
  15457. sub tests_get_options_cgi_context
  15458. {
  15459. note( 'Entering tests_get_options_cgi_context()' ) ;
  15460. # Temporary, have to think harder about testing CGI context in command line --tests
  15461. # API:
  15462. # * input arguments: two ways, command line or CGI
  15463. # * the program arguments
  15464. # * QUERY_STRING env variable
  15465. # * return
  15466. # * QUERY_STRING length
  15467. # CGI context
  15468. local $ENV{SERVER_SOFTWARE} = 'Votre serviteur' ;
  15469. # Real full test
  15470. # = 'host1=test1.lamiral.info&user1=test1&password1=secret1&host2=test2.lamiral.info&user2=test2&password2=secret2&debugenv=on'
  15471. my $mysync ;
  15472. is( undef, get_options( $mysync ), 'get_options cgi context: no CGI module => undef' ) ;
  15473. # skip all next tests if the CGI module is not available
  15474. SKIP: {
  15475. if ( ! eval { require CGI ; } ) {
  15476. skip( "CGI Perl module is not installed", 19 ) ;
  15477. }
  15478. CGI->import( qw( -no_debug -utf8 ) ) ;
  15479. is( undef, get_options( $mysync ), 'get_options cgi context: no CGI param => undef' ) ;
  15480. # Testing boolean
  15481. $mysync->{cgi} = CGI->new( 'version=on&debugenv=on' ) ;
  15482. local $ENV{'QUERY_STRING'} = 'version=on&debugenv=on' ;
  15483. is( 22, get_options( $mysync ), 'get_options cgi context: QUERY_STRING => 22' ) ;
  15484. is( 'on', $mysync->{ version }, 'get_options cgi context: --version => on' ) ;
  15485. # debugenv is not allowed in cgi context
  15486. is( undef, $mysync->{debugenv}, 'get_options cgi context: $mysync->{debugenv} => undef' ) ;
  15487. # QUERY_STRING in this test is only for return value of get_options
  15488. # Have to think harder, GET/POST context, is this return value a good thing?
  15489. local $ENV{'QUERY_STRING'} = 'host1=test1.lamiral.info&user1=test1' ;
  15490. $mysync->{cgi} = CGI->new( 'host1=test1.lamiral.info&user1=test1' ) ;
  15491. is( 36, get_options( $mysync, ), 'get_options cgi context: QUERY_STRING => 36' ) ;
  15492. is( 'test1', $mysync->{user1}, 'get_options cgi context: $mysync->{user1} => test1' ) ;
  15493. #local $ENV{'QUERY_STRING'} = undef ;
  15494. # Testing s@ as ref
  15495. $mysync->{cgi} = CGI->new( 'folder=fd1' ) ;
  15496. get_options( $mysync ) ;
  15497. is_deeply( [ 'fd1' ], $mysync->{ folder }, 'get_options cgi context: $mysync->{ folder } => fd1' ) ;
  15498. $mysync->{cgi} = CGI->new( 'folder=fd1&folder=fd2' ) ;
  15499. get_options( $mysync ) ;
  15500. is_deeply( [ 'fd1', 'fd2' ], $mysync->{ folder }, 'get_options cgi context: $mysync->{ folder } => fd1, fd2' ) ;
  15501. # Testing %
  15502. $mysync->{cgi} = CGI->new( 'f1f2h=s1=d1&f1f2h=s2=d2&f1f2h=s3=d3' ) ;
  15503. get_options( $mysync ) ;
  15504. is_deeply( { 's1' => 'd1', 's2' => 'd2', 's3' => 'd3' },
  15505. $mysync->{f1f2h}, 'get_options cgi context: f1f2h => s1=d1 s2=d2 s3=d3' ) ;
  15506. # Testing boolean ! with --noxxx, doesnot work
  15507. $mysync->{cgi} = CGI->new( 'nodry=on' ) ;
  15508. get_options( $mysync ) ;
  15509. is( undef, $mysync->{dry}, 'get_options cgi context: --nodry => $mysync->{dry} => undef' ) ;
  15510. $mysync->{cgi} = CGI->new( 'host1=example.com' ) ;
  15511. get_options( $mysync ) ;
  15512. is( 'example.com', $mysync->{host1}, 'get_options cgi context: --host1=example.com => $mysync->{host1} => example.com' ) ;
  15513. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  15514. $mysync->{cgi} = CGI->new( 'simulong=' ) ;
  15515. get_options( $mysync ) ;
  15516. is( undef, $mysync->{simulong}, 'get_options cgi context: --simulong= => $mysync->{simulong} => undef' ) ;
  15517. $mysync->{cgi} = CGI->new( 'simulong' ) ;
  15518. get_options( $mysync ) ;
  15519. is( undef, $mysync->{simulong}, 'get_options cgi context: --simulong => $mysync->{simulong} => undef' ) ;
  15520. $mysync->{cgi} = CGI->new( 'simulong=4' ) ;
  15521. get_options( $mysync ) ;
  15522. is( 4, $mysync->{simulong}, 'get_options cgi context: --simulong=4 => $mysync->{simulong} => 4' ) ;
  15523. is( undef, $mysync->{ folder }, 'get_options cgi context: --simulong=4 => $mysync->{ folder } => undef' ) ;
  15524. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  15525. $mysync ={} ;
  15526. $mysync->{cgi} = CGI->new( 'testslive=on' ) ;
  15527. get_options( $mysync ) ;
  15528. is( 'on', $mysync->{ testslive }, 'get_options cgi context: --testslive=on => testslive => on' ) ;
  15529. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  15530. $mysync ={} ;
  15531. $mysync->{cgi} = CGI->new( 'log=0' ) ;
  15532. get_options( $mysync ) ;
  15533. is( 0, $mysync->{ log }, 'get_options cgi context: --log=0 => log => 0' ) ;
  15534. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  15535. # What is this fucked up indentation?
  15536. }
  15537. note( 'Leaving tests_get_options_cgi_context()' ) ;
  15538. return ;
  15539. }
  15540. sub get_options_cgi
  15541. {
  15542. # In CGI context arguments are not in @ARGV but in QUERY_STRING variable (with GET).
  15543. my $mysync = shift @ARG ;
  15544. $mysync->{cgi} || return ;
  15545. my @arguments = @ARG ;
  15546. # final 0 is used to print usage when no option is given
  15547. my $numopt = length $ENV{'QUERY_STRING'} || 1 ;
  15548. $mysync->{f1f2h} = {} ;
  15549. my $opt_ret = myGetOptions(
  15550. $mysync,
  15551. \@arguments,
  15552. 'abort' => \$mysync->{ abort },
  15553. 'abortbyfile' => \$mysync->{ abortbyfile },
  15554. 'host1=s' => \$mysync->{ host1 },
  15555. 'host2=s' => \$mysync->{ host2 },
  15556. 'user1=s' => \$mysync->{ user1 },
  15557. 'user2=s' => \$mysync->{ user2 },
  15558. 'password1=s' => \$mysync->{ password1 },
  15559. 'password2=s' => \$mysync->{ password2 },
  15560. 'dry!' => \$mysync->{ dry },
  15561. 'dry1!' => \$mysync->{ dry1 },
  15562. 'version' => \$mysync->{ version },
  15563. 'ssl1!' => \$mysync->{ ssl1 },
  15564. 'ssl2!' => \$mysync->{ ssl2 },
  15565. 'tls1!' => \$mysync->{ tls1 },
  15566. 'tls2!' => \$mysync->{ tls2 },
  15567. 'compress1!' => \$mysync->{ acc1 }->{ compress },
  15568. 'compress2!' => \$mysync->{ acc2 }->{ compress },
  15569. 'justbanner!' => \$mysync->{ justbanner },
  15570. 'justlogin!' => \$mysync->{ justlogin },
  15571. 'justconnect!' => \$mysync->{ justconnect },
  15572. 'addheader!' => \$mysync->{ addheader },
  15573. 'automap!' => \$mysync->{ automap },
  15574. 'justautomap!' => \$mysync->{ justautomap },
  15575. 'gmail1' => \$mysync->{ gmail1 },
  15576. 'gmail2' => \$mysync->{ gmail2 },
  15577. 'office1' => \$mysync->{ office1 },
  15578. 'office2' => \$mysync->{ office2 },
  15579. 'exchange1' => \$mysync->{ exchange1 },
  15580. 'exchange2' => \$mysync->{ exchange2 },
  15581. 'domino1' => \$mysync->{ domino1 },
  15582. 'domino2' => \$mysync->{ domino2 },
  15583. 'f1f2=s@' => \$mysync->{ f1f2 },
  15584. 'f1f2h=s%' => \$mysync->{ f1f2h },
  15585. 'folder=s@' => \$mysync->{ folder },
  15586. 'testslive!' => \$mysync->{ testslive },
  15587. 'testslive6!' => \$mysync->{ testslive6 },
  15588. 'releasecheck!' => \$mysync->{ releasecheck },
  15589. 'simulong=f' => \$mysync->{ simulong },
  15590. 'debugsleep=f' => \$mysync->{ debugsleep },
  15591. 'subfolder1=s' => \$mysync->{ subfolder1 },
  15592. 'subfolder2=s' => \$mysync->{ subfolder2 },
  15593. 'justfolders!' => \$mysync->{ justfolders },
  15594. 'justfoldersizes!' => \$mysync->{ justfoldersizes },
  15595. 'delete1!' => \$mysync->{ delete1 },
  15596. 'delete2!' => \$mysync->{ delete2 },
  15597. 'delete2duplicates!' => \$mysync->{ delete2duplicates },
  15598. 'tail!' => \$mysync->{ tail },
  15599. 'tmphash=s' => \$mysync->{ tmphash },
  15600. 'exitwhenover=i' => \$mysync->{ exitwhenover },
  15601. 'syncduplicates!' => \$mysync->{ syncduplicates },
  15602. 'log!' => \$mysync->{ log },
  15603. 'loglogfile!' => \$mysync->{ loglogfile },
  15604. # f1f2h=s% could be removed but
  15605. # tests_get_options_cgi() should be split before
  15606. # with a sub tests_myGetOptions()
  15607. ) ;
  15608. $mysync->{ debug } and output( $mysync, "get options: [$opt_ret][$numopt]\n" ) ;
  15609. if ( ! $opt_ret ) {
  15610. return ;
  15611. }
  15612. return $numopt ;
  15613. }
  15614. sub get_options_cmd
  15615. {
  15616. my $mysync = shift @ARG ;
  15617. my @arguments = @ARG ;
  15618. my $mycgi = $mysync->{cgi} ;
  15619. # final 0 is used to print usage when no option is given on command line
  15620. my $numopt = scalar @arguments || 0 ;
  15621. my $argv = join "\x00", @arguments ;
  15622. if ( $argv =~ m/-delete\x002/x ) {
  15623. output( $mysync, "May be you mean --delete2 instead of --delete 2\n" ) ;
  15624. return ;
  15625. }
  15626. $mysync->{f1f2h} = {} ;
  15627. my $opt_ret = myGetOptions(
  15628. $mysync,
  15629. \@arguments,
  15630. 'debug!' => \$mysync->{ debug },
  15631. 'debuglist!' => \$debuglist,
  15632. 'debugcontent!' => \$mysync->{ debugcontent },
  15633. 'debugsleep=f' => \$mysync->{ debugsleep },
  15634. 'debugflags!' => \$debugflags,
  15635. 'debugimap!' => \$mysync->{ debugimap },
  15636. 'debugimap1!' => \$mysync->{ acc1 }->{ debugimap },
  15637. 'debugimap2!' => \$mysync->{ acc2 }->{ debugimap },
  15638. 'debugdev!' => \$debugdev,
  15639. 'debugmemory!' => \$mysync->{debugmemory},
  15640. 'debugfolders!' => \$mysync->{debugfolders},
  15641. 'debugssl=i' => \$mysync->{debugssl},
  15642. 'debugcgi!' => \$debugcgi,
  15643. 'debugenv!' => \$mysync->{debugenv},
  15644. 'debugsig!' => \$mysync->{debugsig},
  15645. 'debuglabels!' => \$mysync->{debuglabels},
  15646. 'simulong=f' => \$mysync->{simulong},
  15647. 'abort' => \$mysync->{abort},
  15648. 'abortbyfile' => \$mysync->{abortbyfile},
  15649. 'host1=s' => \$mysync->{ host1 },
  15650. 'host2=s' => \$mysync->{ host2 },
  15651. 'port1=i' => \$mysync->{ port1 },
  15652. 'port2=i' => \$mysync->{ port2 },
  15653. 'inet4|ipv4' => \$mysync->{ inet4 },
  15654. 'inet6|ipv6' => \$mysync->{ inet6 },
  15655. 'user1=s' => \$mysync->{ user1 },
  15656. 'user2=s' => \$mysync->{ user2 },
  15657. 'gmail1' => \$mysync->{gmail1},
  15658. 'gmail2' => \$mysync->{gmail2},
  15659. 'office1' => \$mysync->{office1},
  15660. 'office2' => \$mysync->{office2},
  15661. 'exchange1' => \$mysync->{exchange1},
  15662. 'exchange2' => \$mysync->{exchange2},
  15663. 'domino1' => \$mysync->{domino1},
  15664. 'domino2' => \$mysync->{domino2},
  15665. 'domain1=s' => \$mysync->{ acc1 }->{ domain },
  15666. 'domain2=s' => \$mysync->{ acc2 }->{ domain },
  15667. 'password1=s' => \$mysync->{password1},
  15668. 'password2=s' => \$mysync->{password2},
  15669. 'passfile1=s' => \$mysync->{ passfile1 },
  15670. 'passfile2=s' => \$mysync->{ passfile2 },
  15671. 'authmd5!' => \$authmd5,
  15672. 'authmd51!' => \$authmd51,
  15673. 'authmd52!' => \$authmd52,
  15674. 'trylogin!' => \$mysync->{ trylogin },
  15675. 'oauthdirect1=s' => \$mysync->{ acc1 }->{ oauthdirect },
  15676. 'oauthdirect2=s' => \$mysync->{ acc2 }->{ oauthdirect },
  15677. 'oauthaccesstoken1=s' => \$mysync->{ acc1 }->{ oauthaccesstoken },
  15678. 'oauthaccesstoken2=s' => \$mysync->{ acc2 }->{ oauthaccesstoken },
  15679. 'sep1=s' => \$mysync->{ sep1 },
  15680. 'sep2=s' => \$mysync->{ sep2 },
  15681. 'sanitize!' => \$mysync->{ sanitize },
  15682. 'folder=s@' => \$mysync->{ folder },
  15683. 'folderrec=s' => \@folderrec,
  15684. 'include=s' => \@include,
  15685. 'exclude=s' => \@exclude,
  15686. 'noexclude' => \$mysync->{noexclude},
  15687. 'folderfirst=s' => \@folderfirst,
  15688. 'folderlast=s' => \@folderlast,
  15689. 'prefix1=s' => \$prefix1,
  15690. 'prefix2=s' => \$prefix2,
  15691. 'subfolder1=s' => \$mysync->{ subfolder1 },
  15692. 'subfolder2=s' => \$mysync->{ subfolder2 },
  15693. 'fixslash2!' => \$mysync->{ fixslash2 },
  15694. 'fixInboxINBOX!' => \$fixInboxINBOX,
  15695. 'regextrans2=s@' => \$mysync->{ regextrans2 },
  15696. 'mixfolders!' => \$mixfolders,
  15697. 'skipemptyfolders!' => \$mysync->{ skipemptyfolders },
  15698. 'regexmess=s' => \@regexmess,
  15699. 'noregexmess' => \$mysync->{noregexmess},
  15700. 'skipmess=s' => \@skipmess,
  15701. 'pipemess=s' => \@pipemess,
  15702. 'pipemesscheck!' => \$pipemesscheck,
  15703. 'disarmreadreceipts!' => \$disarmreadreceipts,
  15704. 'regexflag=s@' => \$mysync->{ regexflag },
  15705. 'noregexflag' => \$mysync->{ noregexflag },
  15706. 'filterflags!' => \$mysync->{ filterflags },
  15707. 'filterbuggyflags!' => \$mysync->{ filterbuggyflags },
  15708. 'flagscase!' => \$mysync->{ flagscase },
  15709. 'syncflagsaftercopy!' => \$syncflagsaftercopy,
  15710. 'resyncflags!' => \$mysync->{ resyncflags },
  15711. 'synclabels!' => \$mysync->{ synclabels },
  15712. 'resynclabels!' => \$mysync->{ resynclabels },
  15713. 'delete|delete1!' => \$mysync->{ delete1 },
  15714. 'delete2!' => \$mysync->{ delete2 },
  15715. 'delete2duplicates!' => \$mysync->{ delete2duplicates },
  15716. 'delete2folders!' => \$delete2folders,
  15717. 'delete2foldersonly=s' => \$delete2foldersonly,
  15718. 'delete2foldersbutnot=s' => \$delete2foldersbutnot,
  15719. 'syncinternaldates!' => \$syncinternaldates,
  15720. 'idatefromheader!' => \$idatefromheader,
  15721. 'syncacls!' => \$mysync->{ syncacls },
  15722. 'maxsize=i' => \$mysync->{ maxsize },
  15723. 'appendlimit=i' => \$mysync->{ appendlimit },
  15724. 'truncmess=i' => \$mysync->{ truncmess },
  15725. 'minsize=i' => \$minsize,
  15726. 'maxage=f' => \$maxage,
  15727. 'minage=f' => \$minage,
  15728. 'search=s' => \$search,
  15729. 'search1=s' => \$mysync->{ search1 },
  15730. 'search2=s' => \$mysync->{ search2 },
  15731. 'foldersizes!' => \$mysync->{ foldersizes },
  15732. 'foldersizesatend!' => \$mysync->{ foldersizesatend },
  15733. 'dry!' => \$mysync->{dry},
  15734. 'dry1!' => \$mysync->{dry1},
  15735. 'expunge1|expunge!' => \$mysync->{ expunge1 },
  15736. 'expunge2!' => \$mysync->{ expunge2 },
  15737. 'uidexpunge2!' => \$mysync->{ uidexpunge2 },
  15738. 'subscribed' => \$subscribed,
  15739. 'subscribe!' => \$subscribe,
  15740. 'subscribeall|subscribe_all!' => \$subscribeall,
  15741. 'justbanner!' => \$mysync->{ justbanner },
  15742. 'justfolders!'=> \$mysync->{ justfolders },
  15743. 'justfoldersizes!' => \$mysync->{ justfoldersizes },
  15744. 'version' => \$mysync->{version},
  15745. 'help' => \$help,
  15746. 'timeout=f' => \$mysync->{timeout},
  15747. 'timeout1=f' => \$mysync->{ acc1 }->{timeout},
  15748. 'timeout2=f' => \$mysync->{ acc2 }->{timeout},
  15749. 'skipheader=s' => \$mysync->{ skipheader },
  15750. 'useheader=s' => \@useheader,
  15751. 'wholeheaderifneeded!' => \$wholeheaderifneeded,
  15752. 'messageidnodomain!' => \$messageidnodomain,
  15753. 'skipsize!' => \$skipsize,
  15754. 'allowsizemismatch!' => \$allowsizemismatch,
  15755. 'fastio1!' => \$mysync->{ acc1 }->{ fastio },
  15756. 'fastio2!' => \$mysync->{ acc2 }->{ fastio },
  15757. 'sslcheck!' => \$mysync->{sslcheck},
  15758. 'ssl1!' => \$mysync->{ssl1},
  15759. 'ssl2!' => \$mysync->{ssl2},
  15760. 'ssl1_ssl_version=s' => \$mysync->{ acc1 }->{sslargs}->{SSL_version},
  15761. 'ssl2_ssl_version=s' => \$mysync->{ acc2 }->{sslargs}->{SSL_version},
  15762. 'sslargs1=s%' => \$mysync->{ acc1 }->{sslargs},
  15763. 'sslargs2=s%' => \$mysync->{ acc2 }->{sslargs},
  15764. 'tls1!' => \$mysync->{tls1},
  15765. 'tls2!' => \$mysync->{tls2},
  15766. 'uid1!' => \$uid1,
  15767. 'uid2!' => \$uid2,
  15768. 'authmech1=s' => \$mysync->{ acc1 }->{ authmech },
  15769. 'authmech2=s' => \$mysync->{ acc2 }->{ authmech },
  15770. 'authuser1=s' => \$mysync->{ acc1 }->{ authuser },
  15771. 'authuser2=s' => \$mysync->{ acc2 }->{ authuser },
  15772. 'proxyauth1' => \$mysync->{ acc1 }->{ proxyauth },
  15773. 'proxyauth2' => \$mysync->{ acc2 }->{ proxyauth },
  15774. 'compress1!' => \$mysync->{ acc1 }->{ compress },
  15775. 'compress2!' => \$mysync->{ acc2 }->{ compress },
  15776. 'keepalive1!' => \$mysync->{ acc1 }->{ keepalive },
  15777. 'keepalive2!' => \$mysync->{ acc2 }->{ keepalive },
  15778. 'split1=i' => \$split1,
  15779. 'split2=i' => \$split2,
  15780. 'buffersize=i' => \$buffersize,
  15781. 'reconnectretry1=i' => \$mysync->{ acc1 }->{ reconnectretry },
  15782. 'reconnectretry2=i' => \$mysync->{ acc2 }->{ reconnectretry },
  15783. 'tests!' => \$mysync->{ tests },
  15784. 'testsdebug|tests_debug!' => \$mysync->{ testsdebug },
  15785. 'testsunit=s@' => \$mysync->{testsunit},
  15786. 'testslive!' => \$mysync->{testslive},
  15787. 'testslive6!' => \$mysync->{testslive6},
  15788. 'justlogin!' => \$mysync->{justlogin},
  15789. 'justconnect!' => \$mysync->{justconnect},
  15790. 'tmpdir=s' => \$mysync->{ tmpdir },
  15791. 'pidfile=s' => \$mysync->{pidfile},
  15792. 'pidfilelocking!' => \$mysync->{pidfilelocking},
  15793. 'sigexit=s@' => \$mysync->{ sigexit },
  15794. 'sigreconnect=s@' => \$mysync->{ sigreconnect },
  15795. 'sigignore=s@' => \$mysync->{ sigignore },
  15796. 'releasecheck!' => \$mysync->{releasecheck},
  15797. 'modulesversion|modules_version!' => \$modulesversion,
  15798. 'usecache!' => \$usecache,
  15799. 'cacheaftercopy!' => \$cacheaftercopy,
  15800. 'debugcache!' => \$debugcache,
  15801. 'useuid!' => \$useuid,
  15802. 'addheader!' => \$mysync->{addheader},
  15803. 'exitwhenover=i' => \$mysync->{ exitwhenover },
  15804. 'checkselectable!' => \$mysync->{ checkselectable },
  15805. 'checkfoldersexist!' => \$mysync->{ checkfoldersexist },
  15806. 'checkmessageexists!' => \$checkmessageexists,
  15807. 'expungeaftereach!' => \$mysync->{ expungeaftereach },
  15808. 'abletosearch!' => \$mysync->{abletosearch},
  15809. 'abletosearch1!' => \$mysync->{abletosearch1},
  15810. 'abletosearch2!' => \$mysync->{abletosearch2},
  15811. 'showpasswords!' => \$mysync->{showpasswords},
  15812. 'maxlinelength=i' => \$maxlinelength,
  15813. 'maxlinelengthcmd=s' => \$maxlinelengthcmd,
  15814. 'minmaxlinelength=i' => \$minmaxlinelength,
  15815. 'debugmaxlinelength!' => \$debugmaxlinelength,
  15816. 'fixcolonbug!' => \$fixcolonbug,
  15817. 'create_folder_old!' => \$create_folder_old,
  15818. 'maxmessagespersecond=f' => \$mysync->{maxmessagespersecond},
  15819. 'maxbytespersecond=i' => \$mysync->{maxbytespersecond},
  15820. 'maxbytesafter=i' => \$mysync->{maxbytesafter},
  15821. 'maxsleep=f' => \$mysync->{maxsleep},
  15822. 'skipcrossduplicates!' => \$skipcrossduplicates,
  15823. 'debugcrossduplicates!' => \$debugcrossduplicates,
  15824. 'log!' => \$mysync->{log},
  15825. 'tail!' => \$mysync->{tail},
  15826. 'logfile=s' => \$mysync->{logfile},
  15827. 'logdir=s' => \$mysync->{logdir},
  15828. 'errorsmax=i' => \$mysync->{errorsmax},
  15829. 'errorsdump!' => \$mysync->{ errorsdump },
  15830. 'fetch_hash_set=s' => \$fetch_hash_set,
  15831. 'automap!' => \$mysync->{automap},
  15832. 'justautomap!' => \$mysync->{justautomap},
  15833. 'id!' => \$mysync->{id},
  15834. 'f1f2=s@' => \$mysync->{f1f2},
  15835. 'nof1f2' => \$mysync->{nof1f2},
  15836. 'f1f2h=s%' => \$mysync->{f1f2h},
  15837. 'justfolderlists!' => \$mysync->{justfolderlists},
  15838. 'delete1emptyfolders' => \$mysync->{delete1emptyfolders},
  15839. 'checknoabletosearch!' => \$mysync->{checknoabletosearch},
  15840. 'syncduplicates!' => \$mysync->{ syncduplicates },
  15841. 'dockercontext!' => \$mysync->{ dockercontext },
  15842. ) ;
  15843. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  15844. $mysync->{ debug } and output( $mysync, "get options: [$opt_ret][$numopt]\n" ) ;
  15845. my $numopt_after = scalar @arguments ;
  15846. #myprint( "get options: [$opt_ret][$numopt][$numopt_after]\n" ) ;
  15847. # The $arguments[0] test is just because parallel adds "" when it is
  15848. # used with {=7=} in sync_parallel_unix.sh
  15849. if ( $numopt_after and $arguments[0] ) {
  15850. myprint(
  15851. "Found ", scalar( @arguments ), " extra arguments : [@arguments]\n",
  15852. "It usually means a quoting issue in the command line ",
  15853. "or some misspelling options.\n",
  15854. ) ;
  15855. return ;
  15856. }
  15857. if ( ! $opt_ret ) {
  15858. return ;
  15859. }
  15860. return $numopt ;
  15861. }
  15862. sub tests_get_options
  15863. {
  15864. note( 'Entering tests_get_options()' ) ;
  15865. # CAVEAT: still setting global variables, be careful
  15866. # with tests, the context increases! $debug stays on for example.
  15867. # API:
  15868. # * input arguments: two ways, command line or CGI
  15869. # * the program arguments
  15870. # * QUERY_STRING env variable
  15871. # * return
  15872. # * undef if bad things happened like
  15873. # * options not known
  15874. # * --delete 2 input
  15875. # * number of arguments or QUERY_STRING length
  15876. my $mysync = { } ;
  15877. is( undef, get_options( $mysync, qw( --noexist ) ), 'get_options: --noexist => undef' ) ;
  15878. is( undef, $mysync->{ noexist }, 'get_options: --noexist => undef' ) ;
  15879. $mysync = { } ;
  15880. is( undef, get_options( $mysync, qw( --lalala --noexist --version ) ), 'get_options: --lalala --noexist --version => undef' ) ;
  15881. is( 1, $mysync->{ version }, 'get_options: --version => 1' ) ;
  15882. is( undef, $mysync->{ noexist }, 'get_options: --noexist => undef' ) ;
  15883. $mysync = { } ;
  15884. is( 1, get_options( $mysync, qw( --delete2 ) ), 'get_options: --delete2 => 1' ) ;
  15885. is( 1, $mysync->{ delete2 }, 'get_options: --delete2 => var delete2 = 1' ) ;
  15886. $mysync = { } ;
  15887. is( undef, get_options( $mysync, qw( --delete 2 ) ), 'get_options: --delete 2 => var undef' ) ;
  15888. is( undef, $mysync->{ delete1 }, 'get_options: --delete 2 => var still undef ; good!' ) ;
  15889. $mysync = { } ;
  15890. is( undef, get_options( $mysync, "--delete 2" ), 'get_options: --delete 2 => undef' ) ;
  15891. is( 1, get_options( $mysync, "--version" ), 'get_options: --version => 1' ) ;
  15892. is( 1, get_options( $mysync, "--help" ), 'get_options: --help => 1' ) ;
  15893. is( undef, get_options( $mysync, qw( --noexist --version ) ), 'get_options: --debug --noexist --version => undef' ) ;
  15894. is( 1, get_options( $mysync, qw( --version ) ), 'get_options: --version => 1' ) ;
  15895. is( undef, get_options( $mysync, qw( extra ) ), 'get_options: extra => undef' ) ;
  15896. is( undef, get_options( $mysync, qw( extra1 --version extra2 ) ), 'get_options: extra1 --version extra2 => undef' ) ;
  15897. $mysync = { } ;
  15898. is( 2, get_options( $mysync, qw( --host1 HOST_01) ), 'get_options: --host1 HOST_01 => 1' ) ;
  15899. is( 'HOST_01', $mysync->{ host1 }, 'get_options: --host1 HOST_01 => HOST_01' ) ;
  15900. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  15901. note( 'Leaving tests_get_options()' ) ;
  15902. return ;
  15903. }
  15904. sub get_options
  15905. {
  15906. my $mysync = shift @ARG ;
  15907. my @arguments = @ARG ;
  15908. #myprint( "1 mysync: ", Data::Dumper->Dump( [ $mysync ] ) ) ;
  15909. my $ret ;
  15910. if ( under_cgi_context( ) ) {
  15911. # CGI context
  15912. $ret = get_options_cgi( $mysync, @arguments ) ;
  15913. }else{
  15914. # Command line context ;
  15915. $ret = get_options_cmd( $mysync, @arguments ) ;
  15916. } ;
  15917. #myprint( "2 mysync: ", Data::Dumper->Dump( [ $mysync ] ) ) ;
  15918. foreach my $key ( sort keys %{ $mysync } ) {
  15919. if ( ! defined $mysync->{$key} ) {
  15920. delete $mysync->{$key} ;
  15921. next ;
  15922. }
  15923. if ( 'ARRAY' eq ref( $mysync->{$key} )
  15924. and 0 == scalar( @{ $mysync->{$key} } ) ) {
  15925. delete $mysync->{$key} ;
  15926. }
  15927. }
  15928. return $ret ;
  15929. }
  15930. sub tests_infos
  15931. {
  15932. note( 'Entering tests_infos()' ) ;
  15933. note( "OSNAME=$OSNAME" ) ;
  15934. note( "hostname=". hostname() ) ;
  15935. note( "cwd=" . getcwd( ) ) ;
  15936. note( "PROGRAM_NAME=$PROGRAM_NAME" ) ;
  15937. my $stat = stat("$PROGRAM_NAME") ;
  15938. my $perms = sprintf( "%04o\n", $stat->mode & oct($PERMISSION_FILTER) ) ;
  15939. note( "permissions=$perms" ) ;
  15940. note( "PROCESS_ID=$PROCESS_ID" ) ;
  15941. note( "REAL_USER_ID=$REAL_USER_ID" ) ;
  15942. note( "EFFECTIVE_USER_ID=$EFFECTIVE_USER_ID" ) ;
  15943. note( "context: " . imapsync_context( $sync ) ) ;
  15944. note( "memory_consumption: " . memory_consumption() . " bytes aka " . bytes_display_string_dec( memory_consumption() ) ) ;
  15945. cpu_number
  15946. note( "cpu_number: " . cpu_number() ) ;
  15947. note( $sync->{rcs} ) ;
  15948. note( 'Leaving tests_infos()' ) ;
  15949. return ;
  15950. }
  15951. sub condition_to_leave_after_tests
  15952. {
  15953. my $mysync = shift ;
  15954. if ( $mysync->{ testslive } or $mysync->{ testslive6 } )
  15955. {
  15956. return 0 ;
  15957. }
  15958. if ( $mysync->{ tests }
  15959. or $mysync->{ testsdebug }
  15960. or $mysync->{ testsunit }
  15961. )
  15962. {
  15963. return 1 ;
  15964. }
  15965. }
  15966. sub testunitsession
  15967. {
  15968. my $mysync = shift ;
  15969. if ( ! $mysync ) { return ; }
  15970. if ( ! $mysync->{ testsunit } ) { return ; }
  15971. my @functions = @{ $mysync->{ testsunit } } ;
  15972. if ( ! @functions ) { return ; }
  15973. SKIP: {
  15974. if ( ! @functions ) { skip 'No test in normal run' ; }
  15975. testsunit( @functions ) ;
  15976. done_testing( ) ;
  15977. }
  15978. return ;
  15979. }
  15980. sub tests_count_0s
  15981. {
  15982. note( 'Entering tests_count_zeros()' ) ;
  15983. is( 0, count_0s( ), 'count_0s: no parameters => 0' ) ;
  15984. is( 1, count_0s( 0 ), 'count_0s: 0 => 1' ) ;
  15985. is( 0, count_0s( 1 ), 'count_0s: 1 => 0' ) ;
  15986. is( 1, count_0s( 1, 0, 1 ), 'count_0s: 1, 0, 1 => 1' ) ;
  15987. is( 2, count_0s( 1, 0, 1, 0 ), 'count_0s: 1, 0, 1, 0 => 2' ) ;
  15988. note( 'Leaving tests_count_zeros()' ) ;
  15989. return ;
  15990. }
  15991. sub count_0s
  15992. {
  15993. my @array = @ARG ;
  15994. if ( ! @array ) { return 0 ; }
  15995. my $nb_zeros = 0 ;
  15996. map { $_ == 0 and $nb_zeros += 1 } @array ;
  15997. return $nb_zeros ;
  15998. }
  15999. sub tests_report_failures
  16000. {
  16001. note( 'Entering tests_report_failures()' ) ;
  16002. is( undef, report_failures( ), 'report_failures: no parameters => undef' ) ;
  16003. is( "nb 1 - first\n", report_failures( ({'ok' => 0, name => 'first'}) ), 'report_failures: "first" failed => nb 1 - first' ) ;
  16004. is( q{}, report_failures( ( {'ok' => 1, name => 'first'} ) ), 'report_failures: "first" success =>' ) ;
  16005. is( "nb 2 - second\n", report_failures( ( {'ok' => 1, name => 'second'}, {'ok' => 0, name => 'second'} ) ), 'report_failures: "second" failed => nb 2 - second' ) ;
  16006. 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' ) ;
  16007. note( 'Leaving tests_report_failures()' ) ;
  16008. return ;
  16009. }
  16010. sub report_failures
  16011. {
  16012. my @details = @ARG ;
  16013. if ( ! @details ) { return ; }
  16014. my $counter = 1 ;
  16015. my $report = q{} ;
  16016. foreach my $details ( @details ) {
  16017. if ( ! $details->{ 'ok' } ) {
  16018. my $name = $details->{ 'name' } || 'NONAME' ;
  16019. $report .= "nb $counter - $name\n" ;
  16020. }
  16021. $counter += 1 ;
  16022. }
  16023. return $report ;
  16024. }
  16025. sub tests_true
  16026. {
  16027. note( 'Entering tests_true()' ) ;
  16028. is( 1, 1, 'true: 1 is 1' ) ;
  16029. note( 'Leaving tests_true()' ) ;
  16030. return ;
  16031. }
  16032. sub tests_testsunit
  16033. {
  16034. note( 'Entering tests_testunit()' ) ;
  16035. is( undef, testsunit( ), 'testsunit: no parameters => undef' ) ;
  16036. is( undef, testsunit( undef ), 'testsunit: an undef parameter => undef' ) ;
  16037. is( undef, testsunit( q{} ), 'testsunit: an empty parameter => undef' ) ;
  16038. is( undef, testsunit( 'idonotexist' ), 'testsunit: a do not exist function as parameter => undef' ) ;
  16039. is( undef, testsunit( 'tests_true' ), 'testsunit: tests_true => undef' ) ;
  16040. note( 'Leaving tests_testunit()' ) ;
  16041. return ;
  16042. }
  16043. sub testsunit
  16044. {
  16045. my @functions = @ARG ;
  16046. if ( ! @functions ) { #
  16047. myprint( "testsunit warning: no argument given\n" ) ;
  16048. return ;
  16049. }
  16050. foreach my $function ( @functions ) {
  16051. if ( ! $function ) {
  16052. myprint( "testsunit warning: argument is empty\n" ) ;
  16053. next ;
  16054. }
  16055. if ( ! exists &$function ) {
  16056. myprint( "testsunit warning: function $function does not exist\n" ) ;
  16057. next ;
  16058. }
  16059. if ( ! defined &$function ) {
  16060. myprint( "testsunit warning: function $function is not defined\n" ) ;
  16061. next ;
  16062. }
  16063. my $function_ref = \&{ $function } ;
  16064. &$function_ref() ;
  16065. }
  16066. return ;
  16067. }
  16068. sub testsdebug
  16069. {
  16070. # Now a little obsolete since there is
  16071. # imapsync ... --testsunit "anyfunction"
  16072. my $mysync = shift ;
  16073. if ( ! $mysync->{ testsdebug } ) { return ; }
  16074. SKIP: {
  16075. if ( ! $mysync->{ testsdebug } ) {
  16076. skip 'No test in normal run' ;
  16077. }
  16078. note( 'Entering testsdebug()' ) ;
  16079. #ok( ( ( not -d 'W/tmp/tests' ) or rmtree( 'W/tmp/tests/' ) ), 'testsdebug: rmtree W/tmp/tests' ) ;
  16080. #tests_check_binary_embed_all_dyn_libs( ) ;
  16081. #tests_killpid_by_parent( ) ;
  16082. #tests_killpid_by_brother( ) ;
  16083. #tests_kill_zero( ) ;
  16084. #tests_connect_socket( ) ;
  16085. #tests_probe_imapssl( ) ;
  16086. #tests_cpu_number( ) ;
  16087. #tests_mailimapclient_connect( ) ;
  16088. tests_loadavg( ) ;
  16089. #tests_always_fail( ) ;
  16090. note( 'Leaving testsdebug()' ) ;
  16091. done_testing( ) ;
  16092. }
  16093. return ;
  16094. }
  16095. sub tests
  16096. {
  16097. my $mysync = shift ;
  16098. if ( ! $mysync->{ tests } ) { return ; }
  16099. SKIP: {
  16100. skip 'No test in normal run' if ( ! $mysync->{ tests } ) ;
  16101. note( 'Entering tests()' ) ;
  16102. tests_folder_routines( ) ;
  16103. tests_compare_lists( ) ;
  16104. tests_regexmess( ) ;
  16105. tests_skipmess( ) ;
  16106. tests_regexflags( );
  16107. tests_ucsecond( ) ;
  16108. tests_permanentflags();
  16109. tests_flags_filter( ) ;
  16110. tests_separator_invert( ) ;
  16111. tests_imap2_folder_name( ) ;
  16112. tests_command_line_nopassword( ) ;
  16113. tests_good_date( ) ;
  16114. tests_max( ) ;
  16115. tests_remove_not_num();
  16116. tests_memory_consumption( ) ;
  16117. tests_is_a_release_number();
  16118. tests_imapsync_basename();
  16119. tests_list_keys_in_2_not_in_1();
  16120. tests_convert_sep_to_slash( ) ;
  16121. tests_match_a_cache_file( ) ;
  16122. tests_cache_map( ) ;
  16123. tests_get_cache( ) ;
  16124. tests_clean_cache( ) ;
  16125. tests_clean_cache_2( ) ;
  16126. tests_touch( ) ;
  16127. tests_flagscase( ) ;
  16128. tests_mkpath( ) ;
  16129. tests_extract_header( ) ;
  16130. tests_decompose_header( ) ;
  16131. tests_epoch( ) ;
  16132. tests_add_header( ) ;
  16133. tests_cache_dir_fix( ) ;
  16134. tests_cache_dir_fix_win( ) ;
  16135. tests_filter_forbidden_characters( ) ;
  16136. tests_cache_folder( ) ;
  16137. tests_time_remaining( ) ;
  16138. tests_decompose_regex( ) ;
  16139. tests_backtick( ) ;
  16140. tests_bytes_display_string_bin( ) ;
  16141. tests_bytes_display_string_dec( ) ;
  16142. tests_header_line_normalize( ) ;
  16143. tests_fix_Inbox_INBOX_mapping( ) ;
  16144. tests_max_line_length( ) ;
  16145. tests_subject( ) ;
  16146. tests_msgs_from_maxmin( ) ;
  16147. tests_tmpdir_has_colon_bug( ) ;
  16148. tests_sleep_max_messages( ) ;
  16149. tests_sleep_max_bytes( ) ;
  16150. tests_logfile( ) ;
  16151. tests_setlogfile( ) ;
  16152. tests_jux_utf8_old( ) ;
  16153. tests_jux_utf8( ) ;
  16154. tests_pipemess( ) ;
  16155. tests_jux_utf8_list( ) ;
  16156. tests_guess_prefix( ) ;
  16157. tests_guess_separator( ) ;
  16158. tests_format_for_imap_arg( ) ;
  16159. tests_imapsync_id( ) ;
  16160. tests_date_from_rcs( ) ;
  16161. tests_quota_extract_storage_limit_in_bytes( ) ;
  16162. tests_quota_extract_storage_current_in_bytes( ) ;
  16163. tests_guess_special( ) ;
  16164. tests_do_valid_directory( ) ;
  16165. tests_delete1emptyfolders( ) ;
  16166. tests_message_for_host2( ) ;
  16167. tests_length_ref( ) ;
  16168. tests_firstline( ) ;
  16169. tests_diff_or_NA( ) ;
  16170. tests_match_number( ) ;
  16171. tests_all_defined( ) ;
  16172. tests_special_from_folders_hash( ) ;
  16173. tests_notmatch( ) ;
  16174. tests_match( ) ;
  16175. tests_get_options( ) ;
  16176. tests_get_options_cgi_context( ) ;
  16177. tests_rand32( ) ;
  16178. tests_hashsynclocal( ) ;
  16179. tests_hashsync( ) ;
  16180. tests_output( ) ;
  16181. tests_output_reset_with( ) ;
  16182. tests_output_start( ) ;
  16183. tests_check_last_release( ) ;
  16184. tests_loadavg( ) ;
  16185. tests_cpu_number( ) ;
  16186. tests_load_and_delay( ) ;
  16187. #tests_imapsping( ) ;
  16188. #tests_tcpping( ) ;
  16189. tests_sslcheck( ) ;
  16190. tests_not_long_imapsync_version_public( ) ;
  16191. tests_reconnect_if_needed( ) ;
  16192. tests_reconnect_12_if_needed( ) ;
  16193. tests_sleep_if_needed( ) ;
  16194. tests_string_to_file( ) ;
  16195. tests_file_to_string( ) ;
  16196. tests_under_cgi_context( ) ;
  16197. tests_umask( ) ;
  16198. tests_umask_str( ) ;
  16199. tests_set_umask( ) ;
  16200. tests_createhashfileifneeded( ) ;
  16201. tests_slash_to_underscore( ) ;
  16202. tests_testsunit( ) ;
  16203. tests_count_0s( ) ;
  16204. tests_report_failures( ) ;
  16205. tests_min( ) ;
  16206. #tests_connect_socket( ) ;
  16207. #tests_resolvrev( ) ;
  16208. tests_usage( ) ;
  16209. tests_version_from_rcs( ) ;
  16210. tests_backslash_caret( ) ;
  16211. #tests_mailimapclient_connect_bug( ) ; # it fails with Mail-IMAPClient <= 3.39
  16212. tests_write_pidfile( ) ;
  16213. tests_remove_pidfile_not_running( ) ;
  16214. tests_match_a_pid_number( ) ;
  16215. tests_prefix_seperator_invertion( ) ;
  16216. tests_is_integer( ) ;
  16217. tests_integer_or_1( ) ;
  16218. tests_is_number( ) ;
  16219. tests_sig_install( ) ;
  16220. tests_template( ) ;
  16221. tests_split_around_equal( ) ;
  16222. tests_toggle_sleep( ) ;
  16223. tests_labels( ) ;
  16224. tests_synclabels( ) ;
  16225. tests_uidexpunge_or_expunge( ) ;
  16226. tests_appendlimit_from_capability( ) ;
  16227. tests_maxsize_setting( ) ;
  16228. tests_mock_capability( ) ;
  16229. tests_appendlimit( ) ;
  16230. tests_capability_of( ) ;
  16231. tests_search_in_array( ) ;
  16232. tests_operators_and_exclam_precedence( ) ;
  16233. tests_teelaunch( ) ;
  16234. tests_logfileprepa( ) ;
  16235. tests_useheader_suggestion( ) ;
  16236. tests_nb_messages_in_2_not_in_1( ) ;
  16237. tests_labels_add_subfolder2( ) ;
  16238. tests_labels_remove_subfolder1( ) ;
  16239. tests_resynclabels( ) ;
  16240. tests_labels_remove_special( ) ;
  16241. tests_uniq( ) ;
  16242. tests_remove_from_requested_folders( ) ;
  16243. tests_errors_log( ) ;
  16244. tests_add_subfolder1_to_folderrec( ) ;
  16245. tests_sanitize_subfolder( ) ;
  16246. tests_remove_edging_blanks( ) ;
  16247. tests_sanitize( ) ;
  16248. tests_remove_last_char_if_is( ) ;
  16249. tests_check_binary_embed_all_dyn_libs( ) ;
  16250. tests_nthline( ) ;
  16251. tests_secondline( ) ;
  16252. tests_tail( ) ;
  16253. tests_truncmess( ) ;
  16254. tests_eta( ) ;
  16255. tests_timesince( ) ;
  16256. tests_timenext( ) ;
  16257. tests_foldersize( ) ;
  16258. tests_imapsync_context( ) ;
  16259. tests_abort( ) ;
  16260. tests_probe_imapssl( ) ;
  16261. tests_mailimapclient_connect( ) ;
  16262. tests_checknoabletosearch( ) ;
  16263. tests_errorsdump( ) ;
  16264. tests_errorsanalyse( ) ;
  16265. tests_most_common_error( ) ;
  16266. tests_errorclassify( ) ;
  16267. tests_error_type( ) ;
  16268. tests_sanitize_host( ) ;
  16269. tests_hmac_sha1_hex( ) ;
  16270. tests_total_bytes_max_reached( ) ;
  16271. tests_header_construct( ) ;
  16272. tests_remove_doublequotes_if_any( ) ;
  16273. tests_login_imap( ) ;
  16274. tests_login_imap_oauth( ) ;
  16275. tests_skipmess_neg( ) ;
  16276. tests_localtimez( ) ;
  16277. tests_file_to_array( ) ;
  16278. tests_cpu_time( ) ;
  16279. tests_cpu_percent( ) ;
  16280. tests_cpu_percent_global( ) ;
  16281. tests_flags_for_host2( ) ;
  16282. tests_under_docker_context( ) ;
  16283. tests_exit_value( ) ;
  16284. tests_comment_of_error_type( ) ;
  16285. tests_debugcontent( ) ;
  16286. tests_compress_ssl( ) ;
  16287. tests_compress( ) ;
  16288. tests_get_options_extra( ) ;
  16289. tests_get_options_from_string( ) ;
  16290. tests_infos( ) ;
  16291. #tests_resolv( ) ;
  16292. # Those three are for later use, when webserver will be inside imapsync
  16293. # or will be deleted them if I abandon the project.
  16294. #tests_killpid_by_parent( ) ;
  16295. #tests_killpid_by_brother( ) ;
  16296. #tests_kill_zero( ) ;
  16297. #tests_always_fail( ) ;
  16298. done_testing( 1860 ) ;
  16299. note( 'Leaving tests()' ) ;
  16300. }
  16301. return ;
  16302. }
  16303. sub tests_template
  16304. {
  16305. note( 'Entering tests_template()' ) ;
  16306. is( undef, template( ), 'template: no args => undef' ) ;
  16307. my $mysync = { } ;
  16308. is( undef, template( $mysync ), 'template: undef => undef' ) ;
  16309. is_deeply( {}, {}, 'template: a hash is a hash' ) ;
  16310. is_deeply( [], [], 'template: an array is an array' ) ;
  16311. note( 'Leaving tests_template()' ) ;
  16312. return ;
  16313. }
  16314. sub template
  16315. {
  16316. my $mysync = shift @ARG ;
  16317. return ;
  16318. }