imapsync 633 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261
  1. #!/usr/bin/env perl
  2. # $Id: imapsync,v 1.977 2019/12/23 20:18:02 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: 1.977 $
  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 messages 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 a strict sync).
  46. How imapsync knows 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. All flags are preserved, unread messages will stay unread,
  52. read ones will stay read, deleted will stay deleted.
  53. You can abort the transfer at any time and restart it later,
  54. imapsync works well with bad connections and interruptions,
  55. by design. On a terminal hit Ctr-c twice within two seconds
  56. in order to abort the program. Hit Ctr-c just once makes
  57. imapsync reconnect to both imap servers.
  58. A classical scenario is synchronizing a mailbox B from another mailbox A
  59. where you just want to keep a strict copy of A in B. Strict meaning
  60. all messages in A will be in B but no more.
  61. For this, option --delete2 has to be used, it deletes messages in host2
  62. folder B that are not in host1 folder A. If you also need to destroy
  63. host2 folders that are not in host1 then use --delete2folders. See also
  64. --delete2foldersonly and --delete2foldersbutnot to set up exceptions
  65. on folders to destroy. INBOX will never be destroy, it's a mandatory
  66. folder in IMAP.
  67. A different scenario is to delete the messages from the source mailbox
  68. after a successful transfer, it can be a good feature when migrating
  69. mailboxes since messages will be only on one side. The source account
  70. will only have messages that are not on the destination yet, ie,
  71. messages that arrived after a sync or that failed to be copied.
  72. In that case, use the --delete1 option. Option --delete1 implies also
  73. option --expunge1 so all messages marked deleted on host1 will be really
  74. deleted. In IMAP protocol deleting a message does not really delete it,
  75. it marks it with the flag \Deleted, allowing an undelete. Expunging
  76. a folder removes, definitively, all the messages marked as \Deleted
  77. in this folder.
  78. You can also decide to remove empty folders once all of their messages
  79. have been transferred. Add --delete1emptyfolders to obtain this
  80. behavior.
  81. Imapsync is not adequate for maintaining two active imap accounts
  82. in synchronization when the user plays independently on both sides.
  83. Use offlineimap (written by John Goerzen) or mbsync (written by
  84. Michael R. Elkins) for a 2 ways synchronization.
  85. =head1 OPTIONS
  86. usage: imapsync [options]
  87. The standard options are the six values forming the credentials.
  88. Three values on each side are needed in order to log in into the IMAP
  89. servers. These six values are a host, a username, and a password, two times.
  90. Conventions used in the following descriptions of the options:
  91. str means string
  92. int means integer
  93. reg means regular expression
  94. cmd means command
  95. --dry : Makes imapsync doing nothing for real, just print what
  96. would be done without --dry.
  97. =head2 OPTIONS/credentials
  98. --host1 str : Source or "from" imap server.
  99. --port1 int : Port to connect on host1.
  100. Optional since default ports are the
  101. well known ports imap/143 or imaps/993.
  102. --user1 str : User to login on host1.
  103. --password1 str : Password for the user1.
  104. --host2 str : "destination" imap server.
  105. --port2 int : Port to connect on host2. Optional
  106. --user2 str : User to login on host2.
  107. --password2 str : Password for the user2.
  108. --showpasswords : Shows passwords on output instead of "MASKED".
  109. Useful to restart a complete run by just reading
  110. the command line used in the log,
  111. or to debug passwords.
  112. It's not a secure practice at all.
  113. --passfile1 str : Password file for the user1. It must contain the
  114. password on the first line. This option avoids showing
  115. the password on the command line like --password1 does.
  116. --passfile2 str : Password file for the user2.
  117. You can also pass the passwords in the environment variables
  118. IMAPSYNC_PASSWORD1 and IMAPSYNC_PASSWORD2
  119. =head2 OPTIONS/encryption
  120. --nossl1 : Do not use a SSL connection on host1.
  121. --ssl1 : Use a SSL connection on host1. On by default if possible.
  122. --nossl2 : Do not use a SSL connection on host2.
  123. --ssl2 : Use a SSL connection on host2. On by default if possible.
  124. --notls1 : Do not use a TLS connection on host1.
  125. --tls1 : Use a TLS connection on host1. On by default if possible.
  126. --notls2 : Do not use a TLS connection on host2.
  127. --tls2 : Use a TLS connection on host2. On by default if possible.
  128. --debugssl int : SSL debug mode from 0 to 4.
  129. --sslargs1 str : Pass any ssl parameter for host1 ssl or tls connection. Example:
  130. --sslargs1 SSL_verify_mode=1 --sslargs1 SSL_version=SSLv3
  131. See all possibilities in the new() method of IO::Socket::SSL
  132. http://search.cpan.org/perldoc?IO::Socket::SSL#Description_Of_Methods
  133. --sslargs2 str : Pass any ssl parameter for host2 ssl or tls connection.
  134. See --sslargs1
  135. --timeout1 int : Connection timeout in seconds for host1.
  136. Default is 120 and 0 means no timeout at all.
  137. --timeout2 int : Connection timeout in seconds for host2.
  138. Default is 120 and 0 means no timeout at all.
  139. =head2 OPTIONS/authentication
  140. --authmech1 str : Auth mechanism to use with host1:
  141. PLAIN, LOGIN, CRAM-MD5 etc. Use UPPERCASE.
  142. --authmech2 str : Auth mechanism to use with host2. See --authmech1
  143. --authuser1 str : User to auth with on host1 (admin user).
  144. Avoid using --authmech1 SOMETHING with --authuser1.
  145. --authuser2 str : User to auth with on host2 (admin user).
  146. --proxyauth1 : Use proxyauth on host1. Requires --authuser1.
  147. Required by Sun/iPlanet/Netscape IMAP servers to
  148. be able to use an administrative user.
  149. --proxyauth2 : Use proxyauth on host2. Requires --authuser2.
  150. --authmd51 : Use MD5 authentication for host1.
  151. --authmd52 : Use MD5 authentication for host2.
  152. --domain1 str : Domain on host1 (NTLM authentication).
  153. --domain2 str : Domain on host2 (NTLM authentication).
  154. =head2 OPTIONS/folders
  155. --folder str : Sync this folder.
  156. --folder str : and this one, etc.
  157. --folderrec str : Sync this folder recursively.
  158. --folderrec str : and this one, etc.
  159. --folderfirst str : Sync this folder first. Ex. --folderfirst "INBOX"
  160. --folderfirst str : then this one, etc.
  161. --folderlast str : Sync this folder last. --folderlast "[Gmail]/All Mail"
  162. --folderlast str : then this one, etc.
  163. --nomixfolders : Do not merge folders when host1 is case-sensitive
  164. while host2 is not (like Exchange). Only the first
  165. similar folder is synced (example: with folders
  166. "Sent", "SENT" and "sent"
  167. on host1 only "Sent" will be synced to host2).
  168. --skipemptyfolders : Empty host1 folders are not created on host2.
  169. --include reg : Sync folders matching this regular expression
  170. --include reg : or this one, etc.
  171. If both --include --exclude options are used, then
  172. include is done before.
  173. --exclude reg : Skips folders matching this regular expression
  174. Several folders to avoid:
  175. --exclude 'fold1|fold2|f3' skips fold1, fold2 and f3.
  176. --exclude reg : or this one, etc.
  177. --automap : guesses folders mapping, for folders well known as
  178. "Sent", "Junk", "Drafts", "All", "Archive", "Flagged".
  179. --f1f2 str1=str2 : Force folder str1 to be synced to str2,
  180. --f1f2 overrides --automap and --regextrans2.
  181. --subfolder2 str : Syncs the whole host1 folders hierarchy under the
  182. host2 folder named str.
  183. It does it internally by adding three
  184. --regextrans2 options before all others.
  185. Add --debug to see what's really going on.
  186. --subfolder1 str : Syncs the host1 folders hierarchy which is under folder
  187. str to the root hierarchy of host2.
  188. It's the couterpart of a sync done by --subfolder2
  189. when doing it in the reverse order.
  190. Backup/Restore scenario:
  191. Use --subfolder2 str for a backup to the folder str
  192. on host2. Then use --subfolder1 str for restoring
  193. from the folder str, after inverting
  194. host1/host2 user1/user2 values.
  195. --subscribed : Transfers subscribed folders.
  196. --subscribe : Subscribe to the folders transferred on the
  197. host2 that are subscribed on host1. On by default.
  198. --subscribeall : Subscribe to the folders transferred on the
  199. host2 even if they are not subscribed on host1.
  200. --prefix1 str : Remove prefix str to all destination folders,
  201. usually "INBOX." or "INBOX/" or an empty string "".
  202. imapsync guesses the prefix if host1 imap server
  203. does not have NAMESPACE capability. So this option
  204. should not be used most of the time.
  205. --prefix2 str : Add prefix to all host2 folders. See --prefix1
  206. --sep1 str : Host1 separator. This option should not be used
  207. most of the time.
  208. Imapsync gets the separator from the server itself,
  209. by using NAMESPACE, or it tries to guess it
  210. from the folders listing (it counts
  211. characters / . \\ \ in folder names and choose the
  212. more frequent, or finally / if nothing is found.
  213. --sep2 str : Host2 separator. See --sep1
  214. --regextrans2 reg : Apply the whole regex to each destination folders.
  215. --regextrans2 reg : and this one. etc.
  216. When you play with the --regextrans2 option, first
  217. add also the safe options --dry --justfolders
  218. Then, when happy, remove --dry for a run, then
  219. remove --justfolders for the next ones.
  220. Have in mind that --regextrans2 is applied after
  221. the automatic prefix and separator inversion.
  222. For examples see:
  223. https://imapsync.lamiral.info/FAQ.d/FAQ.Folders_Mapping.txt
  224. =head2 OPTIONS/folders sizes
  225. --nofoldersizes : Do not calculate the size of each folder at the
  226. beginning of the sync. Default is to calculate them.
  227. --nofoldersizesatend: Do not calculate the size of each folder at the
  228. end of the sync. Default is to calculate them.
  229. --justfoldersizes : Exit after having printed the initial folder sizes.
  230. =head2 OPTIONS/tmp
  231. --tmpdir str : Where to store temporary files and subdirectories.
  232. Will be created if it doesn't exist.
  233. Default is system specific, Unix is /tmp but
  234. /tmp is often too small and deleted at reboot.
  235. --tmpdir /var/tmp should be better.
  236. --pidfile str : The file where imapsync pid is written,
  237. it can be dirname/filename.
  238. Default name is imapsync.pid in tmpdir.
  239. --pidfilelocking : Abort if pidfile already exists. Useful to avoid
  240. concurrent transfers on the same mailbox.
  241. =head2 OPTIONS/log
  242. --nolog : Turn off logging on file
  243. --logfile str : Change the default log filename (can be dirname/filename).
  244. --logdir str : Change the default log directory. Default is LOG_imapsync/
  245. The default logfile name is for example
  246. LOG_imapsync/2019_12_22_23_57_59_532_user1_user2.txt
  247. where:
  248. 2019_12_22_23_57_59_532 is nearly the date of the start
  249. YYYY_MM_DD_HH_MM_SS_mmm
  250. year_month_day_hour_minute_seconde_millisecond
  251. and user1 user2 are the --user1 --user2 values.
  252. =head2 OPTIONS/messages
  253. --skipmess reg : Skips messages matching the regex.
  254. Example: 'm/[\x80-ff]/' # to avoid 8bits messages.
  255. --skipmess is applied before --regexmess
  256. --skipmess reg : or this one, etc.
  257. --skipcrossduplicates : Avoid copying messages that are already copied
  258. in another folder, good from Gmail to X when
  259. X is not also Gmail.
  260. Activated with --gmail1 unless --noskipcrossduplicates
  261. --debugcrossduplicates : Prints which messages (UIDs) are skipped with
  262. --skipcrossduplicates (and in what other folders
  263. they are).
  264. --pipemess cmd : Apply this cmd command to each message content
  265. before the copy.
  266. --pipemess cmd : and this one, etc.
  267. With several --pipemess, the output of each cmd
  268. command (STDOUT) is given to the input (STDIN)
  269. of the next command.
  270. For example,
  271. --pipemess cmd1 --pipemess cmd2 --pipemess cmd3
  272. is like a Unix pipe:
  273. "cat message | cmd1 | cmd2 | cmd3"
  274. --disarmreadreceipts : Disarms read receipts (host2 Exchange issue)
  275. --regexmess reg : Apply the whole regex to each message before transfer.
  276. Example: 's/\000/ /g' # to replace null by space.
  277. --regexmess reg : and this one, etc.
  278. =head2 OPTIONS/labels
  279. Gmail present labels as folders in imap. Imapsync can accelerate the sync
  280. by syncing X-GM-LABELS, it will avoid to transfer messages when they are
  281. already on host2.
  282. --synclabels : Syncs also Gmail labels when a message is copied to host2.
  283. Activated by default with --gmail1 --gmail2 unless
  284. --nosynclabels is added.
  285. --resynclabels : Resyncs Gmail labels when a message is already on host2.
  286. Activated by default with --gmail1 --gmail2 unless
  287. --noresynclabels is added.
  288. For Gmail syncs, see also:
  289. https://imapsync.lamiral.info/FAQ.d/FAQ.Gmail.txt
  290. =head2 OPTIONS/flags
  291. If you encounter flag problems see also:
  292. https://imapsync.lamiral.info/FAQ.d/FAQ.Flags.txt
  293. --regexflag reg : Apply the whole regex to each flags list.
  294. Example: 's/"Junk"//g' # to remove "Junk" flag.
  295. --regexflag reg : then this one, etc.
  296. --resyncflags : Resync flags for already transferred messages.
  297. On by default.
  298. --noresyncflags : Do not resync flags for already transferred messages.
  299. May be useful when a user has already started to play
  300. with its host2 account.
  301. =head2 OPTIONS/deletions
  302. --delete1 : Deletes messages on host1 server after a successful
  303. transfer. Option --delete1 has the following behavior:
  304. it marks messages as deleted with the IMAP flag
  305. \Deleted, then messages are really deleted with an
  306. EXPUNGE IMAP command. If expunging after each message
  307. slows down too much the sync then use
  308. --noexpungeaftereach to speed up, expunging will then be
  309. done only twice per folder, one at the beginning and
  310. one at the end of a folder sync.
  311. --expunge1 : Expunge messages on host1 just before syncing a folder.
  312. Expunge is done per folder.
  313. Expunge aims is to really delete messages marked deleted.
  314. An expunge is also done after each message copied
  315. if option --delete1 is set (unless --noexpungeaftereach).
  316. --noexpunge1 : Do not expunge messages on host1.
  317. --delete1emptyfolders : Deletes empty folders on host1, INBOX excepted.
  318. Useful with --delete1 since what remains on host1
  319. is only what failed to be synced.
  320. --delete2 : Delete messages in host2 that are not in
  321. host1 server. Useful for backup or pre-sync.
  322. --delete2 implies --uidexpunge2
  323. --delete2duplicates : Delete messages in host2 that are duplicates.
  324. Works only without --useuid since duplicates are
  325. detected with an header part of each message.
  326. --delete2folders : Delete folders in host2 that are not in host1 server.
  327. For safety, first try it like this (it is safe):
  328. --delete2folders --dry --justfolders --nofoldersizes
  329. and see what folders will be deleted.
  330. --delete2foldersonly reg : Delete only folders matching the regex reg.
  331. Example: --delete2foldersonly "/^Junk$|^INBOX.Junk$/"
  332. This option activates --delete2folders
  333. --delete2foldersbutnot reg : Do not delete folders matching the regex rex.
  334. Example: --delete2foldersbutnot "/Tasks$|Contacts$|Foo$/"
  335. This option activates --delete2folders
  336. --noexpunge2 : Do not expunge messages on host2.
  337. --nouidexpunge2 : Do not uidexpunge messages on the host2 account
  338. that are not on the host1 account.
  339. =head2 OPTIONS/dates
  340. If you encounter problems with dates, see also:
  341. https://imapsync.lamiral.info/FAQ.d/FAQ.Dates.txt
  342. --syncinternaldates : Sets the internal dates on host2 same as host1.
  343. Turned on by default. Internal date is the date
  344. a message arrived on a host (Unix mtime).
  345. --idatefromheader : Sets the internal dates on host2 same as the
  346. ones in "Date:" headers.
  347. =head2 OPTIONS/message selection
  348. --maxsize int : Skip messages larger (or equal) than int bytes
  349. --minsize int : Skip messages smaller (or equal) than int bytes
  350. --maxage int : Skip messages older than int days.
  351. final stats (skipped) don't count older messages
  352. see also --minage
  353. --minage int : Skip messages newer than int days.
  354. final stats (skipped) don't count newer messages
  355. You can do (+ zone are the messages selected):
  356. past|----maxage+++++++++++++++>now
  357. past|+++++++++++++++minage---->now
  358. past|----maxage+++++minage---->now (intersection)
  359. past|++++minage-----maxage++++>now (union)
  360. --search str : Selects only messages returned by this IMAP SEARCH
  361. command. Applied on both sides.
  362. For a complete set of what can be search see
  363. https://imapsync.lamiral.info/FAQ.d/FAQ.Messages_Selection.txt
  364. --search1 str : Same as --search but for selecting host1 messages only.
  365. --search2 str : Same as --search but for selecting host2 messages only.
  366. So --search CRIT equals --search1 CRIT --search2 CRIT
  367. --maxlinelength int : skip messages with a line length longer than int bytes.
  368. RFC 2822 says it must be no more than 1000 bytes but
  369. real life servers and email clients do more.
  370. --useheader str : Use this header to compare messages on both sides.
  371. Ex: Message-ID or Subject or Date.
  372. --useheader str and this one, etc.
  373. --usecache : Use cache to speed up next syncs. Not set by default.
  374. --nousecache : Do not use cache. Caveat: --useuid --nousecache creates
  375. duplicates on multiple runs.
  376. --useuid : Use UIDs instead of headers as a criterion to recognize
  377. messages. Option --usecache is then implied unless
  378. --nousecache is used.
  379. =head2 OPTIONS/miscellaneous
  380. --syncacls : Synchronizes acls (Access Control Lists).
  381. Acls in IMAP are not standardized, be careful
  382. since one acl code on one side may signify something
  383. else on the other one.
  384. --nosyncacls : Does not synchronize acls. This is the default.
  385. --addheader : When a message has no headers to be identified,
  386. --addheader adds a "Message-Id" header,
  387. like "Message-Id: 12345@imapsync", where 12345
  388. is the imap UID of the message on the host1 folder.
  389. =head2 OPTIONS/debugging
  390. --debug : Debug mode.
  391. --debugfolders : Debug mode for the folders part only.
  392. --debugcontent : Debug content of the messages transferred. Huge output.
  393. --debugflags : Debug mode for flags.
  394. --debugimap1 : IMAP debug mode for host1. Very verbose.
  395. --debugimap2 : IMAP debug mode for host2. Very verbose.
  396. --debugimap : IMAP debug mode for host1 and host2. Twice very verbose.
  397. --debugmemory : Debug mode showing memory consumption after each copy.
  398. --errorsmax int : Exit when int number of errors is reached. Default is 50.
  399. --tests : Run local non-regression tests. Exit code 0 means all ok.
  400. --testslive : Run a live test with test1.lamiral.info imap server.
  401. Useful to check the basics. Needs internet connection.
  402. --testslive6 : Run a live test with ks2ipv6.lamiral.info imap server.
  403. Useful to check the ipv6 connectivity. Needs internet.
  404. =head2 OPTIONS/specific
  405. --gmail1 : sets --host1 to Gmail and other options. See FAQ.Gmail.txt
  406. --gmail2 : sets --host2 to Gmail and other options. See FAQ.Gmail.txt
  407. --office1 : sets --host1 to Office365 and other options. See FAQ.Exchange.txt
  408. --office2 : sets --host2 to Office365 and other options. See FAQ.Exchange.txt
  409. --exchange1 : sets options for Exchange. See FAQ.Exchange.txt
  410. --exchange2 : sets options for Exchange. See FAQ.Exchange.txt
  411. --domino1 : sets options for Domino. See FAQ.Domino.txt
  412. --domino2 : sets options for Domino. See FAQ.Domino.txt
  413. =head2 OPTIONS/behavior
  414. --maxmessagespersecond int : limits the number of messages transferred per second.
  415. --maxbytespersecond int : limits the average transfer rate per second.
  416. --maxbytesafter int : starts --maxbytespersecond limitation only after
  417. --maxbytesafter amount of data transferred.
  418. --maxsleep int : do not sleep more than int seconds.
  419. On by default, 2 seconds max, like --maxsleep 2
  420. --abort : terminates a previous call still running.
  421. It uses the pidfile to know what process to abort.
  422. --exitwhenover int : Stop syncing and exits when int total bytes
  423. transferred is reached.
  424. --version : Print only software version.
  425. --noreleasecheck : Do not check for any new imapsync release.
  426. --releasecheck : Check for new imapsync release.
  427. it's an http request to
  428. http://imapsync.lamiral.info/prj/imapsync/VERSION
  429. --noid : Do not send/receive ID command to imap servers.
  430. --justconnect : Just connect to both servers and print useful
  431. information. Need only --host1 and --host2 options.
  432. Obsolete since "imapsync --host1 imaphost" alone
  433. implies --justconnect
  434. --justlogin : Just login to both host1 and host2 with users
  435. credentials, then exit.
  436. --justfolders : Do only things about folders (ignore messages).
  437. --help : print this help.
  438. Example: to synchronize imap account "test1" on "test1.lamiral.info"
  439. to imap account "test2" on "test2.lamiral.info"
  440. with test1 password "secret1"
  441. and test2 password "secret2"
  442. imapsync \
  443. --host1 test1.lamiral.info --user1 test1 --password1 secret1 \
  444. --host2 test2.lamiral.info --user2 test2 --password2 secret2
  445. =cut
  446. # comment
  447. =pod
  448. =head1 SECURITY
  449. You can use --passfile1 instead of --password1 to give the
  450. password since it is safer. With --password1 option, on Linux,
  451. any user on your host can see the password by using the 'ps auxwwww'
  452. command. Using a variable (like IMAPSYNC_PASSWORD1) is also
  453. dangerous because of the 'ps auxwwwwe' command. So, saving
  454. the password in a well protected file (600 or rw-------) is
  455. the best solution.
  456. Imapsync activates ssl or tls encryption by default, if possible.
  457. What detailed behavior is under this "if possible"?
  458. Imapsync activates ssl if the well known port imaps port (993) is open
  459. on the imap servers. If the imaps port is closed then it open a
  460. normal (clear) connection on port 143 but it looks for TLS support
  461. in the CAPABILITY list of the servers. If TLS is supported
  462. then imapsync goes to encryption.
  463. If the automatic ssl and the tls detections fail then imapsync will
  464. not protect against sniffing activities on the network, especially
  465. for passwords.
  466. If you want to force ssl or tls just use --ssl1 --ssl2 or --tls1 --tls2
  467. See also the document FAQ.Security.txt in the FAQ.d/ directory
  468. or at https://imapsync.lamiral.info/FAQ.d/FAQ.Security.txt
  469. =head1 EXIT STATUS
  470. Imapsync will exit with a 0 status (return code) if everything went good.
  471. Otherwise, it exits with a non-zero status. That's classical Unix behavior.
  472. Here is the list of the exit code values (an integer between 0 and 255).
  473. The names reflect their meaning:
  474. =for comment
  475. egrep '^Readonly my.*\$EX' imapsync | egrep -o 'EX.*' | sed 's_^_ _'
  476. EX_OK => 0 ; #/* successful termination */
  477. EX_USAGE => 64 ; #/* command line usage error */
  478. EX_NOINPUT => 66 ; #/* cannot open input */
  479. EX_UNAVAILABLE => 69 ; #/* service unavailable */
  480. EX_SOFTWARE => 70 ; #/* internal software error */
  481. EXIT_CATCH_ALL => 1 ; # Any other error
  482. EXIT_BY_SIGNAL => 6 ; # Should be 128+n where n is the sig_num
  483. EXIT_PID_FILE_ERROR => 8 ;
  484. EXIT_CONNECTION_FAILURE => 10 ;
  485. EXIT_TLS_FAILURE => 12 ;
  486. EXIT_AUTHENTICATION_FAILURE => 16 ;
  487. EXIT_SUBFOLDER1_NO_EXISTS => 21 ;
  488. EXIT_WITH_ERRORS => 111 ;
  489. EXIT_WITH_ERRORS_MAX => 112 ;
  490. EXIT_TESTS_FAILED => 254 ; # Like Test::More API
  491. =head1 LICENSE AND COPYRIGHT
  492. Imapsync is free, open, public but not always gratis software
  493. cover by the NOLIMIT Public License, now called NLPL.
  494. See the LICENSE file included in the distribution or just read this
  495. simple sentence as it IS the licence text:
  496. "No limits to do anything with this work and this license."
  497. In case it is not long enough, I repeat:
  498. "No limits to do anything with this work and this license."
  499. Look at https://imapsync.lamiral.info/LICENSE
  500. =head1 AUTHOR
  501. Gilles LAMIRAL <gilles@lamiral.info>
  502. Good feedback is always welcome.
  503. Bad feedback is very often welcome.
  504. Gilles LAMIRAL earns his living by writing, installing,
  505. configuring and teaching free, open and often gratis
  506. software. Imapsync used to be "always gratis" but now it is
  507. only "often gratis" because imapsync is sold by its author,
  508. a good way to maintain and support free open public
  509. software over decades.
  510. =head1 BUGS AND LIMITATIONS
  511. See https://imapsync.lamiral.info/FAQ.d/FAQ.Reporting_Bugs.txt
  512. =head1 IMAP SERVERS supported
  513. See https://imapsync.lamiral.info/S/imapservers.shtml
  514. =head1 HUGE MIGRATION
  515. If you have many mailboxes to migrate think about a little
  516. shell program. Write a file called file.txt (for example)
  517. containing users and passwords.
  518. The separator used in this example is ';'
  519. The file.txt file contains:
  520. user001_1;password001_1;user001_2;password001_2
  521. user002_1;password002_1;user002_2;password002_2
  522. user003_1;password003_1;user003_2;password003_2
  523. user004_1;password004_1;user004_2;password004_2
  524. user005_1;password005_1;user005_2;password005_2
  525. ...
  526. On Unix the shell program can be:
  527. { while IFS=';' read u1 p1 u2 p2; do
  528. imapsync --host1 imap.side1.org --user1 "$u1" --password1 "$p1" \
  529. --host2 imap.side2.org --user2 "$u2" --password2 "$p2" ...
  530. done ; } < file.txt
  531. On Windows the batch program can be:
  532. FOR /F "tokens=1,2,3,4 delims=; eol=#" %%G IN (file.txt) DO imapsync ^
  533. --host1 imap.side1.org --user1 %%G --password1 %%H ^
  534. --host2 imap.side2.org --user2 %%I --password2 %%J ...
  535. The ... have to be replaced by nothing or any imapsync option.
  536. Welcome in shell or batch programming !
  537. You will find already written scripts at
  538. https://imapsync.lamiral.info/examples/
  539. =head1 INSTALL
  540. Imapsync works under any Unix with Perl.
  541. Imapsync works under most Windows (2000, XP, Vista, Seven, Eight, Ten
  542. and all Server releases 2000, 2003, 2008 and R2, 2012 and R2, 2016)
  543. as a standalone binary software called imapsync.exe,
  544. usually launched from a batch file in order to avoid always typing
  545. the options. There is also a 64bit binary called imapsync_64bit.exe
  546. Imapsync works under OS X as a standalone binary
  547. software called imapsync_bin_Darwin
  548. Purchase latest imapsync at
  549. https://imapsync.lamiral.info/
  550. You'll receive a link to a compressed tarball called imapsync-x.xx.tgz
  551. where x.xx is the version number. Untar the tarball where
  552. you want (on Unix):
  553. tar xzvf imapsync-x.xx.tgz
  554. Go into the directory imapsync-x.xx and read the INSTALL file.
  555. As mentioned at https://imapsync.lamiral.info/#install
  556. the INSTALL file can also be found at
  557. https://imapsync.lamiral.info/INSTALL.d/INSTALL.ANY.txt
  558. It is now split in several files for each system
  559. https://imapsync.lamiral.info/INSTALL.d/
  560. =head1 CONFIGURATION
  561. There is no specific configuration file for imapsync,
  562. everything is specified by the command line parameters
  563. and the default behavior.
  564. =head1 HACKING
  565. Feel free to hack imapsync as the NOLIMIT license permits it.
  566. =head1 SIMILAR SOFTWARE
  567. See also https://imapsync.lamiral.info/S/external.shtml
  568. for a better up to date list.
  569. Last updated and verified on Sun Dec 8, 2019.
  570. imapsync: https://github.com/imapsync/imapsync (this is an imapsync copy, sometimes delayed, with --noreleasecheck by default since release 1.592, 2014/05/22)
  571. 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
  572. imaputils: https://github.com/mtsatsenko/imaputils (very old imap_tools fork)
  573. Doveadm-Sync: https://wiki2.dovecot.org/Tools/Doveadm/Sync ( Dovecot sync tool )
  574. davmail: http://davmail.sourceforge.net/
  575. offlineimap: http://offlineimap.org/
  576. mbsync: http://isync.sourceforge.net/
  577. mailsync: http://mailsync.sourceforge.net/
  578. mailutil: https://www.washington.edu/imap/ part of the UW IMAP toolkit. (well, seems abandoned now)
  579. imaprepl: https://bl0rg.net/software/ http://freecode.com/projects/imap-repl/
  580. imapcopy (Pascal): http://www.ardiehl.de/imapcopy/
  581. imapcopy (Java): https://code.google.com/archive/p/imapcopy/
  582. imapsize: http://www.broobles.com/imapsize/
  583. migrationtool: http://sourceforge.net/projects/migrationtool/
  584. imapmigrate: http://sourceforge.net/projects/cyrus-utils/
  585. larch: https://github.com/rgrove/larch (derived from wonko_imapsync, good at Gmail)
  586. wonko_imapsync: http://wonko.com/article/554 (superseded by larch)
  587. pop2imap: http://www.linux-france.org/prj/pop2imap/ (I wrote that too)
  588. exchange-away: http://exchange-away.sourceforge.net/
  589. SyncBackPro: http://www.2brightsparks.com/syncback/sbpro.html
  590. ImapSyncClient: https://github.com/ridaamirini/ImapSyncClient
  591. MailStore: https://www.mailstore.com/en/products/mailstore-home/
  592. mnIMAPSync: https://github.com/manusa/mnIMAPSync
  593. imap-upload: http://imap-upload.sourceforge.net/ (A tool for uploading a local mbox file to IMAP4 server)
  594. imapbackup: https://github.com/rcarmo/imapbackup (A Python script for incremental backups of IMAP mailboxes)
  595. BitRecover email-backup 99 USD, 299 USD https://www.bitrecover.com/email-backup/.
  596. ImportExportTools: https://addons.thunderbird.net/en-us/thunderbird/addon/importexporttools/ ImportExportTools for Mozilla Thunderbird by Paolo Kaosmos. ImportExportTools does not do IMAP.
  597. =head1 HISTORY
  598. I initially wrote imapsync in July 2001 because an enterprise,
  599. called BaSystemes, paid me to install a new imap server
  600. without losing huge old mailboxes located in a far
  601. away remote imap server, accessible by an
  602. often broken low-bandwidth ISDN link.
  603. I had to verify every mailbox was well transferred, all folders, all messages,
  604. without wasting bandwidth or creating duplicates upon resyncs. The imapsync
  605. design was made with the beautiful rsync command in mind.
  606. Imapsync started its life as a patch of the copy_folder.pl
  607. script. The script copy_folder.pl comes from the Mail-IMAPClient-2.1.3 perl
  608. module tarball source (more precisely in the examples/ directory of the
  609. Mail-IMAPClient tarball).
  610. So many happened since then that I wonder
  611. if it remains any lines of the original
  612. copy_folder.pl in imapsync source code.
  613. =cut
  614. # use pragmas
  615. #
  616. use strict ;
  617. use warnings ;
  618. use Carp ;
  619. use Data::Dumper ;
  620. use Digest::HMAC_SHA1 qw( hmac_sha1 hmac_sha1_hex ) ;
  621. use Digest::MD5 qw( md5 md5_hex md5_base64 ) ;
  622. use English qw( -no_match_vars ) ;
  623. use Errno qw(EAGAIN EPIPE ECONNRESET) ;
  624. use Fcntl ;
  625. use File::Basename ;
  626. use File::Copy::Recursive ;
  627. use File::Glob qw( :glob ) ;
  628. use File::Path qw( mkpath rmtree ) ;
  629. use File::Spec ;
  630. use File::stat ;
  631. use Getopt::Long ( ) ;
  632. use IO::File ;
  633. use IO::Socket qw( :crlf SOL_SOCKET SO_KEEPALIVE ) ;
  634. use IO::Socket::INET6 ;
  635. use IO::Socket::SSL ;
  636. use IO::Tee ;
  637. use IPC::Open3 'open3' ;
  638. use Mail::IMAPClient 3.30 ;
  639. use MIME::Base64 ;
  640. use Pod::Usage qw(pod2usage) ;
  641. use POSIX qw(uname SIGALRM :sys_wait_h) ;
  642. use Sys::Hostname ;
  643. use Term::ReadKey ;
  644. use Test::More ;
  645. use Time::HiRes qw( time sleep ) ;
  646. use Time::Local ;
  647. use Unicode::String ;
  648. use Cwd ;
  649. use Readonly ;
  650. use Sys::MemInfo ;
  651. use Regexp::Common ;
  652. use Text::ParseWords ; # for quotewords()
  653. use File::Tail ;
  654. use Encode ;
  655. use Encode::IMAPUTF7 ;
  656. local $OUTPUT_AUTOFLUSH = 1 ;
  657. # constants
  658. # Let us do like sysexits.h
  659. # /usr/include/sysexits.h
  660. # and https://www.tldp.org/LDP/abs/html/exitcodes.html
  661. # Should avoid 2 126 127 128..128+64=192 255
  662. # Should use 0 1 3..125 193..254
  663. Readonly my $EX_OK => 0 ; #/* successful termination */
  664. Readonly my $EX_USAGE => 64 ; #/* command line usage error */
  665. #Readonly my $EX_DATAERR => 65 ; #/* data format error */
  666. Readonly my $EX_NOINPUT => 66 ; #/* cannot open input */
  667. #Readonly my $EX_NOUSER => 67 ; #/* addressee unknown */
  668. #Readonly my $EX_NOHOST => 68 ; #/* host name unknown */
  669. Readonly my $EX_UNAVAILABLE => 69 ; #/* service unavailable */
  670. Readonly my $EX_SOFTWARE => 70 ; #/* internal software error */
  671. #Readonly my $EX_OSERR => 71 ; #/* system error (e.g., can't fork) */
  672. #Readonly my $EX_OSFILE => 72 ; #/* critical OS file missing */
  673. #Readonly my $EX_CANTCREAT => 73 ; #/* can't create (user) output file */
  674. #Readonly my $EX_IOERR => 74 ; #/* input/output error */
  675. #Readonly my $EX_TEMPFAIL => 75 ; #/* temp failure; user is invited to retry */
  676. #Readonly my $EX_PROTOCOL => 76 ; #/* remote error in protocol */
  677. #Readonly my $EX_NOPERM => 77 ; #/* permission denied */
  678. #Readonly my $EX_CONFIG => 78 ; #/* configuration error */
  679. # Mine
  680. Readonly my $EXIT_CATCH_ALL => 1 ; # Any other error
  681. Readonly my $EXIT_BY_SIGNAL => 6 ; # Should be 128+n where n is the sig_num
  682. Readonly my $EXIT_PID_FILE_ERROR => 8 ;
  683. Readonly my $EXIT_CONNECTION_FAILURE => 10 ;
  684. Readonly my $EXIT_TLS_FAILURE => 12 ;
  685. Readonly my $EXIT_AUTHENTICATION_FAILURE => 16 ;
  686. Readonly my $EXIT_SUBFOLDER1_NO_EXISTS => 21 ;
  687. Readonly my $EXIT_WITH_ERRORS => 111 ;
  688. Readonly my $EXIT_WITH_ERRORS_MAX => 112 ;
  689. Readonly my $EXIT_TESTS_FAILED => 254 ; # Like Test::More API
  690. Readonly my %EXIT_TXT => (
  691. $EX_OK => 'EX_OK: successful termination',
  692. $EX_USAGE => 'EX_USAGE: command line usage error',
  693. $EX_NOINPUT => 'EX_NOINPUT: cannot open input',
  694. $EX_UNAVAILABLE => 'EX_UNAVAILABLE: service unavailable',
  695. $EX_SOFTWARE => 'EX_SOFTWARE: internal software error',
  696. $EXIT_CATCH_ALL => 'EXIT_CATCH_ALL',
  697. $EXIT_BY_SIGNAL => 'EXIT_BY_SIGNAL',
  698. $EXIT_PID_FILE_ERROR => 'EXIT_PID_FILE_ERROR' ,
  699. $EXIT_CONNECTION_FAILURE => 'EXIT_CONNECTION_FAILURE',
  700. $EXIT_TLS_FAILURE => 'EXIT_TLS_FAILURE',
  701. $EXIT_AUTHENTICATION_FAILURE => 'EXIT_AUTHENTICATION_FAILURE',
  702. $EXIT_SUBFOLDER1_NO_EXISTS => 'EXIT_SUBFOLDER1_NO_EXISTS',
  703. $EXIT_WITH_ERRORS => 'EXIT_WITH_ERRORS',
  704. $EXIT_WITH_ERRORS_MAX => 'EXIT_WITH_ERRORS_MAX',
  705. $EXIT_TESTS_FAILED => 'EXIT_TESTS_FAILED',
  706. ) ;
  707. Readonly my $DEFAULT_LOGDIR => 'LOG_imapsync' ;
  708. Readonly my $ERRORS_MAX => 50 ; # exit after 50 errors.
  709. Readonly my $ERRORS_MAX_CGI => 20 ; # exit after 20 errors in CGI context.
  710. Readonly my $INTERVAL_TO_EXIT => 2 ; # interval max to exit instead of reconnect
  711. Readonly my $SPLIT => 100 ; # By default, 100 at a time, not more.
  712. Readonly my $SPLIT_FACTOR => 10 ; # init_imap() calls Maxcommandlength( $SPLIT_FACTOR * $split )
  713. # which means default Maxcommandlength is 10*100 = 1000 characters ;
  714. Readonly my $IMAP_PORT => 143 ; # Well know port for IMAP
  715. Readonly my $IMAP_SSL_PORT => 993 ; # Well know port for IMAP over SSL
  716. Readonly my $LAST => -1 ;
  717. Readonly my $MINUS_ONE => -1 ;
  718. Readonly my $MINUS_TWO => -2 ;
  719. Readonly my $RELEASE_NUMBER_EXAMPLE_1 => '1.351' ;
  720. Readonly my $RELEASE_NUMBER_EXAMPLE_2 => 42.4242 ;
  721. Readonly my $TCP_PING_TIMEOUT => 5 ;
  722. Readonly my $DEFAULT_TIMEOUT => 120 ;
  723. Readonly my $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND => 3 ;
  724. Readonly my $DEFAULT_UIDNEXT => 999_999 ;
  725. Readonly my $DEFAULT_BUFFER_SIZE => 4096 ;
  726. Readonly my $MAX_SLEEP => 2 ; # 2 seconds max for limiting too long sleeps from --maxbytespersecond and --maxmessagespersecond
  727. Readonly my $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12 => 3600 ;
  728. Readonly my $PERMISSION_FILTER => 7777 ;
  729. Readonly my $KIBI => 1024 ;
  730. Readonly my $NUMBER_10 => 10 ;
  731. Readonly my $NUMBER_42 => 42 ;
  732. Readonly my $NUMBER_100 => 100 ;
  733. Readonly my $NUMBER_200 => 200 ;
  734. Readonly my $NUMBER_300 => 300 ;
  735. Readonly my $NUMBER_123456 => 123_456 ;
  736. Readonly my $NUMBER_654321 => 654_321 ;
  737. Readonly my $NUMBER_20_000 => 20_000 ;
  738. Readonly my $QUOTA_PERCENT_LIMIT => 90 ;
  739. Readonly my $NUMBER_104_857_600 => 104_857_600 ;
  740. Readonly my $SIZE_MAX_STR => 64 ;
  741. Readonly my $NB_SECONDS_IN_A_DAY => 86_400 ;
  742. Readonly my $STD_CHAR_PER_LINE => 80 ;
  743. Readonly my $TRUE => 1 ;
  744. Readonly my $FALSE => 0 ;
  745. Readonly my $LAST_RESSORT_SEPARATOR => q{/} ;
  746. Readonly my $CGI_TMPDIR_TOP => '/var/tmp/imapsync_cgi' ;
  747. Readonly my $CGI_HASHFILE => '/var/tmp/imapsync_hash' ;
  748. Readonly my $UMASK_PARANO => '0077' ;
  749. Readonly my $STR_use_releasecheck => q{Check if a new imapsync release is available by adding --releasecheck} ;
  750. Readonly my $GMAIL_MAXSIZE => 35_651_584 ;
  751. Readonly my $FORCE => 1 ;
  752. # if ( 'MSWin32' eq $OSNAME )
  753. # if ( 'darwin' eq $OSNAME )
  754. # if ( 'linux' eq $OSNAME )
  755. # global variables
  756. # Currently working to finish with only $sync
  757. # Not finished yet...
  758. my(
  759. $sync,
  760. $timestart_str,
  761. $debugimap, $debugimap1, $debugimap2, $debugcontent, $debugflags,
  762. $debuglist, $debugdev, $debugmaxlinelength, $debugcgi,
  763. $domain1, $domain2,
  764. @include, @exclude, @folderrec,
  765. @folderfirst, @folderlast,
  766. @h1_folders_all, %h1_folders_all,
  767. @h2_folders_all, %h2_folders_all,
  768. @h2_folders_from_1_wanted, %h2_folders_from_1_all,
  769. %requested_folder,
  770. $h1_folders_wanted_nb, $h1_folders_wanted_ct,
  771. @h2_folders_not_in_1,
  772. %h1_subscribed_folder, %h2_subscribed_folder,
  773. %h2_folders_from_1_wanted,
  774. %h2_folders_from_1_several,
  775. $prefix1, $prefix2,
  776. @regexmess, @regexflag, @skipmess, @pipemess, $pipemesscheck,
  777. $flagscase, $filterflags, $syncflagsaftercopy,
  778. $syncinternaldates,
  779. $idatefromheader,
  780. $syncacls,
  781. $fastio1, $fastio2,
  782. $minsize, $maxage, $minage,
  783. $search,
  784. $skipheader, @useheader, %useheader,
  785. $skipsize, $allowsizemismatch, $buffersize,
  786. $authmd5, $authmd51, $authmd52,
  787. $subscribed, $subscribe, $subscribeall,
  788. $help,
  789. $justbanner,
  790. $fast,
  791. $nb_msg_skipped_dry_mode,
  792. $h1_nb_msg_duplicate,
  793. $h2_nb_msg_duplicate,
  794. $h2_nb_msg_noheader,
  795. $h2_nb_msg_deleted,
  796. $h1_bytes_processed,
  797. $h1_nb_msg_end, $h1_bytes_end,
  798. $h2_nb_msg_end, $h2_bytes_end,
  799. $timeout,
  800. $timestart_int,
  801. $uid1, $uid2,
  802. $authuser1, $authuser2,
  803. $proxyauth1, $proxyauth2,
  804. $authmech1, $authmech2,
  805. $split1, $split2,
  806. $reconnectretry1, $reconnectretry2,
  807. $max_msg_size_in_bytes,
  808. $modulesversion,
  809. $delete2folders, $delete2foldersonly, $delete2foldersbutnot,
  810. $usecache, $debugcache, $cacheaftercopy,
  811. $wholeheaderifneeded, %h1_msgs_copy_by_uid, $useuid, $h2_uidguess,
  812. $checkmessageexists,
  813. $messageidnodomain,
  814. $fixInboxINBOX,
  815. $maxlinelength, $maxlinelengthcmd,
  816. $minmaxlinelength,
  817. $uidnext_default,
  818. $fixcolonbug,
  819. $create_folder_old,
  820. $skipcrossduplicates, $debugcrossduplicates,
  821. $disarmreadreceipts,
  822. $mixfolders,
  823. $fetch_hash_set,
  824. $cgidir,
  825. %month_abrev,
  826. $SSL_VERIFY_POLICY,
  827. $warn_release,
  828. ) ;
  829. single_sync( ) ;
  830. sub single_sync
  831. {
  832. # main program
  833. # global variables initialization
  834. # I'm currently removing all global variables except $sync
  835. # passing each of them under $sync->{variable_name}
  836. $sync->{timestart} = time ; # Is a float because of use Time::HiRres
  837. $sync->{rcs} = q{$Id: imapsync,v 1.977 2019/12/23 20:18:02 gilles Exp gilles $} ;
  838. $sync->{ memory_consumption_at_start } = memory_consumption( ) || 0 ;
  839. my @loadavg = loadavg( ) ;
  840. $sync->{cpu_number} = cpu_number( ) ;
  841. $sync->{loaddelay} = load_and_delay( $sync->{cpu_number}, @loadavg ) ;
  842. $sync->{loadavg} = join( q{ }, $loadavg[ 0 ] )
  843. . " on $sync->{cpu_number} cores and "
  844. . ram_memory_info( ) ;
  845. $sync->{ total_bytes_transferred } = 0 ;
  846. $sync->{ total_bytes_skipped } = 0 ;
  847. $sync->{ nb_msg_transferred } = 0 ;
  848. $sync->{ nb_msg_skipped } = $nb_msg_skipped_dry_mode = 0 ;
  849. $sync->{ h1_nb_msg_deleted } = 0 ;
  850. $h2_nb_msg_deleted = 0 ;
  851. $h1_nb_msg_duplicate = 0 ;
  852. $h2_nb_msg_duplicate = 0 ;
  853. $sync->{ h1_nb_msg_noheader } = 0 ;
  854. $h2_nb_msg_noheader = 0 ;
  855. $sync->{ h1_nb_msg_start } = 0 ;
  856. $sync->{ h1_bytes_start } = 0 ;
  857. $sync->{ h2_nb_msg_start } = 0 ;
  858. $sync->{ h2_bytes_start } = 0 ;
  859. $sync->{ h1_nb_msg_processed } = $h1_bytes_processed = 0 ;
  860. $sync->{ h2_nb_msg_crossdup } = 0 ;
  861. #$h1_nb_msg_end = $h1_bytes_end = 0 ;
  862. #$h2_nb_msg_end = $h2_bytes_end = 0 ;
  863. $sync->{nb_errors} = 0;
  864. $max_msg_size_in_bytes = 0;
  865. %month_abrev = (
  866. Jan => '00',
  867. Feb => '01',
  868. Mar => '02',
  869. Apr => '03',
  870. May => '04',
  871. Jun => '05',
  872. Jul => '06',
  873. Aug => '07',
  874. Sep => '08',
  875. Oct => '09',
  876. Nov => '10',
  877. Dec => '11',
  878. );
  879. # Just create a CGI object if under cgi context only.
  880. # Needed for the get_options() call
  881. cgibegin( $sync ) ;
  882. # In cgi context, printing must start by the header so we delay other prints by using output() storage
  883. my $options_good = get_options( $sync, @ARGV ) ;
  884. # Is it the first myprint?
  885. docker_context( $sync ) ;
  886. cgibuildheader( $sync ) ;
  887. myprint( output( $sync ) ) ;
  888. output_reset_with( $sync ) ;
  889. # Old place for cgiload( $sync ) ;
  890. # don't go on if options are not all known.
  891. if ( ! defined $options_good ) { exit $EX_USAGE ; }
  892. # If you want releasecheck not to be done by default (like the github maintainer),
  893. # then just uncomment the first "$sync->{releasecheck} =" line, the line ending with "0 ;",
  894. # the second line (ending with "1 ;") can then stay active or be commented,
  895. # the result will be the same: no releasecheck by default (because 0 is then the defined value).
  896. #$sync->{releasecheck} = defined $sync->{releasecheck} ? $sync->{releasecheck} : 0 ;
  897. $sync->{releasecheck} = defined $sync->{releasecheck} ? $sync->{releasecheck} : 1 ;
  898. # just the version
  899. if ( $sync->{ version } ) {
  900. myprint( imapsync_version( $sync ), "\n" ) ;
  901. exit 0 ;
  902. }
  903. #$sync->{debugenv} = 1 ;
  904. $sync->{debugenv} and printenv( $sync ) ; # if option --debugenv
  905. load_modules( ) ;
  906. # after_get_options call usage and exit if --help or options were not well got
  907. after_get_options( $sync, $options_good ) ;
  908. # Under CGI environment, fix caveat emptor potential issues
  909. cgisetcontext( $sync ) ;
  910. # --gmail --gmail --exchange --office etc.
  911. easyany( $sync ) ;
  912. $sync->{ sanitize } = defined $sync->{ sanitize } ? $sync->{ sanitize } : 1 ;
  913. sanitize( $sync ) ;
  914. $sync->{ tmpdir } ||= File::Spec->tmpdir( ) ;
  915. # Unit tests
  916. testsexit( $sync ) ;
  917. # init live varaiables
  918. testslive_init( $sync ) if ( $sync->{testslive} ) ;
  919. testslive6_init( $sync ) if ( $sync->{testslive6} ) ;
  920. #
  921. pidfile( $sync ) ;
  922. # old abort place
  923. install_signals( $sync ) ;
  924. $sync->{log} = defined $sync->{log} ? $sync->{log} : 1 ;
  925. $sync->{errorsdump} = defined $sync->{errorsdump} ? $sync->{errorsdump} : 1 ;
  926. $sync->{errorsmax} = defined $sync->{errorsmax} ? $sync->{errorsmax} : $ERRORS_MAX ;
  927. # log and output
  928. binmode STDOUT, ":encoding(UTF-8)" ;
  929. if ( $sync->{log} ) {
  930. setlogfile( $sync ) ;
  931. teelaunch( $sync ) ;
  932. # now $sync->{tee} is a filehandle to STDOUT and the logfile
  933. }
  934. #binmode STDERR, ":encoding(UTF-8)" ;
  935. # STDERR goes to the same place: LOG and STDOUT (if logging is on)
  936. # Useful only for --debugssl
  937. $sync->{tee} and local *STDERR = *${$sync->{tee}}{IO} ;
  938. $timestart_int = int( $sync->{timestart} ) ;
  939. $sync->{timebefore} = $sync->{timestart} ;
  940. $timestart_str = localtime( $sync->{timestart} ) ;
  941. # The prints in the log starts here
  942. myprint( localhost_info( $sync ), "\n" ) ;
  943. myprint( "Transfer started at $timestart_str\n" ) ;
  944. myprint( "PID is $PROCESS_ID my PPID is ", mygetppid( ), "\n" ) ;
  945. myprint( "Log file is $sync->{logfile} ( to change it, use --logfile path ; or use --nolog to turn off logging )\n" ) if ( $sync->{log} ) ;
  946. myprint( "Load is " . ( join( q{ }, loadavg( ) ) || 'unknown' ), " on $sync->{cpu_number} cores\n" ) ;
  947. #myprintf( "Memory consumption so far: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  948. myprint( 'Current directory is ' . getcwd( ) . "\n" ) ;
  949. myprint( 'Real user id is ' . getpwuid_any_os( $REAL_USER_ID ) . " (uid $REAL_USER_ID)\n" ) ;
  950. myprint( 'Effective user id is ' . getpwuid_any_os( $EFFECTIVE_USER_ID ). " (euid $EFFECTIVE_USER_ID)\n" ) ;
  951. $modulesversion = defined $modulesversion ? $modulesversion : 1 ;
  952. $warn_release = ( $sync->{releasecheck} ) ? check_last_release( ) : $STR_use_releasecheck ;
  953. $wholeheaderifneeded = defined $wholeheaderifneeded ? $wholeheaderifneeded : 1;
  954. # Activate --usecache if --useuid is set and no --nousecache
  955. $usecache = 1 if ( $useuid and ( ! defined $usecache ) ) ;
  956. $cacheaftercopy = 1 if ( $usecache and ( ! defined $cacheaftercopy ) ) ;
  957. $sync->{ checkselectable } = defined $sync->{ checkselectable } ? $sync->{ checkselectable } : 1 ;
  958. $sync->{ checkfoldersexist } = defined $sync->{ checkfoldersexist } ? $sync->{ checkfoldersexist } : 1 ;
  959. $checkmessageexists = defined $checkmessageexists ? $checkmessageexists : 0 ;
  960. $sync->{ expungeaftereach } = defined $sync->{ expungeaftereach } ? $sync->{ expungeaftereach } : 1 ;
  961. # abletosearch is on by default
  962. $sync->{abletosearch} = defined $sync->{abletosearch} ? $sync->{abletosearch} : 1 ;
  963. $sync->{abletosearch1} = defined $sync->{abletosearch1} ? $sync->{abletosearch1} : $sync->{abletosearch} ;
  964. $sync->{abletosearch2} = defined $sync->{abletosearch2} ? $sync->{abletosearch2} : $sync->{abletosearch} ;
  965. $checkmessageexists = 0 if ( not $sync->{abletosearch1} ) ;
  966. $sync->{showpasswords} = defined $sync->{showpasswords} ? $sync->{showpasswords} : 0 ;
  967. $sync->{ fixslash2 } = defined $sync->{ fixslash2 } ? $sync->{ fixslash2 } : 1 ;
  968. $fixInboxINBOX = defined $fixInboxINBOX ? $fixInboxINBOX : 1 ;
  969. $create_folder_old = defined $create_folder_old ? $create_folder_old : 0 ;
  970. $mixfolders = defined $mixfolders ? $mixfolders : 1 ;
  971. $sync->{automap} = defined $sync->{automap} ? $sync->{automap} : 0 ;
  972. $sync->{ delete2duplicates } = 1 if ( $sync->{ delete2 } and ( ! defined $sync->{ delete2duplicates } ) ) ;
  973. $sync->{maxmessagespersecond} = defined $sync->{maxmessagespersecond} ? $sync->{maxmessagespersecond} : 0 ;
  974. $sync->{maxbytespersecond} = defined $sync->{maxbytespersecond} ? $sync->{maxbytespersecond} : 0 ;
  975. $sync->{sslcheck} = defined $sync->{sslcheck} ? $sync->{sslcheck} : 1 ;
  976. myprint( banner_imapsync( $sync, @ARGV ) ) ;
  977. myprint( "Temp directory is $sync->{ tmpdir } ( to change it use --tmpdir dirpath )\n" ) ;
  978. myprint( output( $sync ) ) ;
  979. output_reset_with( $sync ) ;
  980. do_valid_directory( $sync->{ tmpdir } ) || croak "Error creating tmpdir $sync->{ tmpdir } : $OS_ERROR" ;
  981. remove_pidfile_not_running( $sync->{pidfile} ) ;
  982. # if another imapsync is running then tail -f its logfile and exit
  983. # useful in cgi context
  984. if ( $sync->{ tail } and tail( $sync ) )
  985. {
  986. $sync->{nb_errors}++ ;
  987. exit_clean( $sync, $EX_OK, "Tail -f finished. Now finishing myself processus $PROCESS_ID\n" ) ;
  988. exit $EX_OK ;
  989. }
  990. if ( ! write_pidfile( $sync ) ) {
  991. myprint( "Exiting with return value $EXIT_PID_FILE_ERROR ($EXIT_TXT{$EXIT_PID_FILE_ERROR}) $sync->{nb_errors}/$sync->{errorsmax} nb_errors/max_errors\n" ) ;
  992. exit $EXIT_PID_FILE_ERROR ;
  993. }
  994. # New place for abort
  995. # abort before simulong in order to be able to abort a simulong sync
  996. if ( $sync->{ abort } )
  997. {
  998. abort( $sync ) ;
  999. }
  1000. # simulong is just a loop printing some lines for xx seconds with option "--simulong xx".
  1001. if ( $sync->{ simulong } )
  1002. {
  1003. simulong( $sync->{ simulong } ) ;
  1004. }
  1005. # New place for cgiload 2019_03_03
  1006. # because I want to log it
  1007. # Can break here if load is too heavy
  1008. cgiload( $sync ) ;
  1009. $fixcolonbug = defined $fixcolonbug ? $fixcolonbug : 1 ;
  1010. if ( $usecache and $fixcolonbug ) { tmpdir_fix_colon_bug( $sync ) } ;
  1011. $modulesversion and myprint( "Modules version list:\n", modulesversion(), "( use --no-modulesversion to turn off printing this Perl modules list )\n" ) ;
  1012. check_lib_version( $sync ) or
  1013. croak "imapsync needs perl lib Mail::IMAPClient release 3.30 or superior.\n";
  1014. exit_clean( $sync, $EX_OK ) if ( $justbanner ) ;
  1015. # turn on RFC standard flags correction like \SEEN -> \Seen
  1016. $flagscase = defined $flagscase ? $flagscase : 1 ;
  1017. # Use PERMANENTFLAGS if available
  1018. $filterflags = defined $filterflags ? $filterflags : 1 ;
  1019. # sync flags just after an APPEND, some servers ignore the flags given in the APPEND
  1020. # like MailEnable IMAP server.
  1021. # Off by default since it takes time.
  1022. $syncflagsaftercopy = defined $syncflagsaftercopy ? $syncflagsaftercopy : 0 ;
  1023. # update flags on host2 for already transferred messages
  1024. $sync->{resyncflags} = defined $sync->{resyncflags} ? $sync->{resyncflags} : 1 ;
  1025. if ( $sync->{resyncflags} ) {
  1026. myprint( "Info: will resync flags for already transferred messages. Use --noresyncflags to not resync flags.\n" ) ;
  1027. }else{
  1028. myprint( "Info: will not resync flags for already transferred messages. Use --resyncflags to resync flags.\n" ) ;
  1029. }
  1030. sslcheck( $sync ) ;
  1031. #print Data::Dumper->Dump( [ \$sync ] ) ;
  1032. $split1 ||= $SPLIT ;
  1033. $split2 ||= $SPLIT ;
  1034. #$sync->{host1} || missing_option( $sync, '--host1' ) ;
  1035. $sync->{port1} ||= ( $sync->{ssl1} ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  1036. #$sync->{host2} || missing_option( $sync, '--host2' ) ;
  1037. $sync->{port2} ||= ( $sync->{ssl2} ) ? $IMAP_SSL_PORT : $IMAP_PORT ;
  1038. $debugimap1 = $debugimap2 = 1 if ( $debugimap ) ;
  1039. $sync->{ debug } = 1 if ( $debugimap1 or $debugimap2 ) ;
  1040. # By default, don't take size to compare
  1041. $skipsize = (defined $skipsize) ? $skipsize : 1;
  1042. $uid1 = defined $uid1 ? $uid1 : 1;
  1043. $uid2 = defined $uid2 ? $uid2 : 1;
  1044. $subscribe = defined $subscribe ? $subscribe : 1;
  1045. # Allow size mismatch by default
  1046. $allowsizemismatch = defined $allowsizemismatch ? $allowsizemismatch : 1;
  1047. if ( defined $delete2foldersbutnot or defined $delete2foldersonly ) {
  1048. $delete2folders = 1 ;
  1049. }
  1050. my %SSL_VERIFY_STR ;
  1051. Readonly $SSL_VERIFY_POLICY => IO::Socket::SSL::SSL_VERIFY_NONE( ) ;
  1052. Readonly %SSL_VERIFY_STR => (
  1053. IO::Socket::SSL::SSL_VERIFY_NONE( ) => 'SSL_VERIFY_NONE, ie, do not check the certificate server.' ,
  1054. IO::Socket::SSL::SSL_VERIFY_PEER( ) => 'SSL_VERIFY_PEER, ie, check the certificate server' ,
  1055. ) ;
  1056. $IO::Socket::SSL::DEBUG = defined( $sync->{debugssl} ) ? $sync->{debugssl} : 1 ;
  1057. if ( $sync->{ssl1} or $sync->{ssl2} or $sync->{tls1} or $sync->{tls2}) {
  1058. 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" ) ;
  1059. }
  1060. if ( $sync->{ssl1} ) {
  1061. 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} ) ;
  1062. 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" ) ;
  1063. }
  1064. if ( $sync->{ssl2} ) {
  1065. 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} ) ;
  1066. 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" ) ;
  1067. }
  1068. # ID on by default since 1.832
  1069. $sync->{id} = defined $sync->{id} ? $sync->{id} : 1 ;
  1070. if ( $sync->{justconnect}
  1071. or not $sync->{user1}
  1072. or not $sync->{user2}
  1073. or not $sync->{host1}
  1074. or not $sync->{host2}
  1075. )
  1076. {
  1077. my $justconnect = justconnect( $sync ) ;
  1078. myprint( debugmemory( $sync, " after justconnect() call" ) ) ;
  1079. exit_clean( $sync, $EX_OK,
  1080. "Exiting after a justconnect on host(s): $justconnect\n"
  1081. ) ;
  1082. }
  1083. #$sync->{user1} || missing_option( $sync, '--user1' ) ;
  1084. #$sync->{user2} || missing_option( $sync, '--user2' ) ;
  1085. $syncinternaldates = defined $syncinternaldates ? $syncinternaldates : 1;
  1086. # Turn on expunge if there is not explicit option --noexpunge1 and option
  1087. # --delete1 is given.
  1088. # Done because --delete1 --noexpunge1 is very dangerous on the second run:
  1089. # the Deleted flag is then synced to all previously transferred messages.
  1090. # So --delete1 implies --expunge1 is a better usability default behavior.
  1091. if ( $sync->{ delete1 } ) {
  1092. if ( ! defined $sync->{ expunge1 } ) {
  1093. myprint( "Info: turning on --expunge1 because --delete1 --noexpunge1 is very dangerous on the second run.\n" ) ;
  1094. $sync->{ expunge1 } = 1 ;
  1095. }
  1096. myprint( "Info: if expunging after each message slows down too much the sync then use --noexpungeaftereach to speed up\n" ) ;
  1097. }
  1098. if ( $sync->{ uidexpunge2 } and not Mail::IMAPClient->can( 'uidexpunge' ) ) {
  1099. myprint( "Failure: uidexpunge not supported (IMAPClient release < 3.17), use nothing or --expunge2 instead\n" ) ;
  1100. $sync->{nb_errors}++ ;
  1101. exit_clean( $sync, $EX_SOFTWARE ) ;
  1102. }
  1103. if ( ( $sync->{ delete2 } or $sync->{ delete2duplicates } ) and not defined $sync->{ uidexpunge2 } ) {
  1104. if ( Mail::IMAPClient->can( 'uidexpunge' ) ) {
  1105. myprint( "Info: will act as --uidexpunge2\n" ) ;
  1106. $sync->{ uidexpunge2 } = 1 ;
  1107. }elsif ( not defined $sync->{ expunge2 } ) {
  1108. myprint( "Info: will act as --expunge2 (no uidexpunge support)\n" ) ;
  1109. $sync->{ expunge2 } = 1 ;
  1110. }
  1111. }
  1112. if ( $sync->{ delete1 } and $sync->{ delete2 } ) {
  1113. myprint( "Warning: using --delete1 and --delete2 together is almost always a bad idea, exiting imapsync\n" ) ;
  1114. $sync->{nb_errors}++ ;
  1115. exit_clean( $sync, $EX_USAGE ) ;
  1116. }
  1117. if ( $idatefromheader ) {
  1118. myprint( 'Turned ON idatefromheader, ',
  1119. "will set the internal dates on host2 from the 'Date:' header line.\n" ) ;
  1120. $syncinternaldates = 0 ;
  1121. }
  1122. if ( $syncinternaldates ) {
  1123. myprint( 'Info: turned ON syncinternaldates, ',
  1124. "will set the internal dates (arrival dates) on host2 same as host1.\n" ) ;
  1125. }else{
  1126. myprint( "Info: turned OFF syncinternaldates\n" ) ;
  1127. }
  1128. if ( defined $authmd5 and $authmd5 ) {
  1129. $authmd51 = 1 ;
  1130. $authmd52 = 1 ;
  1131. }
  1132. if ( defined $authmd51 and $authmd51 ) {
  1133. $authmech1 ||= 'CRAM-MD5';
  1134. }
  1135. else{
  1136. $authmech1 ||= $authuser1 ? 'PLAIN' : 'LOGIN';
  1137. }
  1138. if ( defined $authmd52 and $authmd52 ) {
  1139. $authmech2 ||= 'CRAM-MD5';
  1140. }
  1141. else{
  1142. $authmech2 ||= $authuser2 ? 'PLAIN' : 'LOGIN';
  1143. }
  1144. $authmech1 = uc $authmech1;
  1145. $authmech2 = uc $authmech2;
  1146. if (defined $proxyauth1 && !$authuser1) {
  1147. missing_option( $sync, 'With --proxyauth1, --authuser1' ) ;
  1148. }
  1149. if (defined $proxyauth2 && !$authuser2) {
  1150. missing_option( $sync, 'With --proxyauth2, --authuser2' ) ;
  1151. }
  1152. #$authuser1 ||= $sync->{user1};
  1153. #$authuser2 ||= $sync->{user2};
  1154. myprint( "Host1: will try to use $authmech1 authentication on host1\n") ;
  1155. myprint( "Host2: will try to use $authmech2 authentication on host2\n") ;
  1156. $timeout = defined $timeout ? $timeout : $DEFAULT_TIMEOUT ;
  1157. $sync->{h1}->{timeout} = defined $sync->{h1}->{timeout} ? $sync->{h1}->{timeout} : $timeout ;
  1158. myprint( "Host1: imap connection timeout is $sync->{h1}->{timeout} seconds\n") ;
  1159. $sync->{h2}->{timeout} = defined $sync->{h2}->{timeout} ? $sync->{h2}->{timeout} : $timeout ;
  1160. myprint( "Host2: imap connection timeout is $sync->{h2}->{timeout} seconds\n" ) ;
  1161. $syncacls = defined $syncacls ? $syncacls : 0 ;
  1162. # No folders sizes if --justfolders, unless really wanted.
  1163. if (
  1164. $sync->{ justfolders }
  1165. and not defined $sync->{ foldersizes }
  1166. and not $sync->{ justfoldersizes } )
  1167. {
  1168. $sync->{ foldersizes } = 0 ;
  1169. $sync->{ foldersizesatend } = 1 ;
  1170. }
  1171. $sync->{ foldersizes } = ( defined $sync->{ foldersizes } ) ? $sync->{ foldersizes } : 1 ;
  1172. $sync->{ foldersizesatend } = ( defined $sync->{ foldersizesatend } ) ? $sync->{ foldersizesatend } : $sync->{ foldersizes } ;
  1173. $fastio1 = defined $fastio1 ? $fastio1 : 0 ;
  1174. $fastio2 = defined $fastio2 ? $fastio2 : 0 ;
  1175. $reconnectretry1 = defined $reconnectretry1 ? $reconnectretry1 : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  1176. $reconnectretry2 = defined $reconnectretry2 ? $reconnectretry2 : $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  1177. # Since select_msgs() returns no messages when uidnext does not return something
  1178. # then $uidnext_default is never used. So I have to remove it.
  1179. $uidnext_default = $DEFAULT_UIDNEXT ;
  1180. if ( ! @useheader ) { @useheader = qw( Message-Id Received ) ; }
  1181. # Make a hash %useheader of each --useheader 'key' in uppercase
  1182. for ( @useheader ) { $useheader{ uc $_ } = undef } ;
  1183. #myprint( Data::Dumper->Dump( [ \%useheader ] ) ) ;
  1184. #exit ;
  1185. myprint( "Host1: IMAP server [$sync->{host1}] port [$sync->{port1}] user [$sync->{user1}]\n" ) ;
  1186. myprint( "Host2: IMAP server [$sync->{host2}] port [$sync->{port2}] user [$sync->{user2}]\n" ) ;
  1187. get_password1( $sync ) ;
  1188. get_password2( $sync ) ;
  1189. $sync->{dry_message} = q{} ;
  1190. if( $sync->{dry} ) {
  1191. $sync->{dry_message} = "\t(not really since --dry mode)" ;
  1192. }
  1193. $sync->{ search1 } ||= $search if ( $search ) ;
  1194. $sync->{ search2 } ||= $search if ( $search ) ;
  1195. if ( $disarmreadreceipts ) {
  1196. push @regexmess, q{s{\A((?:[^\n]+\r\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims} ;
  1197. }
  1198. $pipemesscheck = ( defined $pipemesscheck ) ? $pipemesscheck : 1 ;
  1199. if ( @pipemess and $pipemesscheck ) {
  1200. myprint( 'Checking each --pipemess command, '
  1201. . join( q{, }, @pipemess )
  1202. . ", with an space string. ( Can avoid this check with --nopipemesscheck )\n" ) ;
  1203. my $string = pipemess( q{ }, @pipemess ) ;
  1204. # string undef means something was bad.
  1205. if ( not ( defined $string ) ) {
  1206. $sync->{nb_errors}++ ;
  1207. exit_clean( $sync, $EX_USAGE,
  1208. "Error: one of --pipemess command is bad, check it\n"
  1209. ) ;
  1210. }
  1211. myprint( "Ok with each --pipemess @pipemess\n" ) ;
  1212. }
  1213. if ( $maxlinelengthcmd ) {
  1214. myprint( "Checking --maxlinelengthcmd command,
  1215. $maxlinelengthcmd, with an space string.\n"
  1216. ) ;
  1217. my $string = pipemess( q{ }, $maxlinelengthcmd ) ;
  1218. # string undef means something was bad.
  1219. if ( not ( defined $string ) ) {
  1220. $sync->{nb_errors}++ ;
  1221. exit_clean( $sync, $EX_USAGE,
  1222. "Error: --maxlinelengthcmd command is bad, check it\n"
  1223. ) ;
  1224. }
  1225. myprint( "Ok with --maxlinelengthcmd $maxlinelengthcmd\n" ) ;
  1226. }
  1227. if ( @regexmess ) {
  1228. my $string = regexmess( q{ } ) ;
  1229. myprint( "Checking each --regexmess command with an space string.\n" ) ;
  1230. # string undef means one of the eval regex was bad.
  1231. if ( not ( defined $string ) ) {
  1232. #errors_incr( $sync, 'Warning: one of --regexmess option may be bad, check them' ) ;
  1233. exit_clean( $sync, $EX_USAGE,
  1234. "Error: one of --regexmess option is bad, check it\n"
  1235. ) ;
  1236. }
  1237. myprint( "Ok with each --regexmess\n" ) ;
  1238. }
  1239. if ( @skipmess ) {
  1240. myprint( "Checking each --skipmess command with an space string.\n" ) ;
  1241. my $match = skipmess( q{ } ) ;
  1242. # match undef means one of the eval regex was bad.
  1243. if ( not ( defined $match ) ) {
  1244. $sync->{nb_errors}++ ;
  1245. exit_clean( $sync, $EX_USAGE,
  1246. "Error: one of --skipmess option is bad, check it\n"
  1247. ) ;
  1248. }
  1249. myprint( "Ok with each --skipmess\n" ) ;
  1250. }
  1251. if ( @regexflag ) {
  1252. myprint( "Checking each --regexflag command with an space string.\n" ) ;
  1253. my $string = flags_regex( q{ } ) ;
  1254. # string undef means one of the eval regex was bad.
  1255. if ( not ( defined $string ) ) {
  1256. $sync->{nb_errors}++ ;
  1257. exit_clean( $sync, $EX_USAGE,
  1258. "Error: one of --regexflag option is bad, check it\n"
  1259. ) ;
  1260. }
  1261. myprint( "Ok with each --regexflag\n" ) ;
  1262. }
  1263. $sync->{imap1} = login_imap( $sync->{host1}, $sync->{port1}, $sync->{user1}, $domain1, $sync->{password1},
  1264. $debugimap1, $sync->{h1}->{timeout}, $fastio1, $sync->{ssl1}, $sync->{tls1},
  1265. $authmech1, $authuser1, $reconnectretry1,
  1266. $proxyauth1, $uid1, $split1, 'Host1', $sync->{h1}, $sync ) ;
  1267. $sync->{imap2} = login_imap( $sync->{host2}, $sync->{port2}, $sync->{user2}, $domain2, $sync->{password2},
  1268. $debugimap2, $sync->{h2}->{timeout}, $fastio2, $sync->{ssl2}, $sync->{tls2},
  1269. $authmech2, $authuser2, $reconnectretry2,
  1270. $proxyauth2, $uid2, $split2, 'Host2', $sync->{h2}, $sync ) ;
  1271. $sync->{ debug } and myprint( 'Host1 Buffer I/O: ', $sync->{imap1}->Buffer(), "\n" ) ;
  1272. $sync->{ debug } and myprint( 'Host2 Buffer I/O: ', $sync->{imap2}->Buffer(), "\n" ) ;
  1273. if ( ! $sync->{imap1}->IsAuthenticated( ) )
  1274. {
  1275. $sync->{nb_errors}++ ;
  1276. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE, "Not authenticated on host1\n" ) ;
  1277. }
  1278. myprint( "Host1: state Authenticated\n" ) ;
  1279. if ( ! $sync->{imap2}->IsAuthenticated( ) )
  1280. {
  1281. $sync->{nb_errors}++ ;
  1282. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE, "Not authenticated on host2\n" ) ;
  1283. }
  1284. myprint( "Host2: state Authenticated\n" ) ;
  1285. myprint( 'Host1 capability once authenticated: ', join(q{ }, @{ $sync->{imap1}->capability() || [] }), "\n" ) ;
  1286. #myprint( Data::Dumper->Dump( [ $sync->{imap1} ] ) ) ;
  1287. #myprint( "imap4rev1: " . $sync->{imap1}->imap4rev1() . "\n" ) ;
  1288. myprint( 'Host2 capability once authenticated: ', join(q{ }, @{ $sync->{imap2}->capability() || [] }), "\n" ) ;
  1289. imap_id_stuff( $sync ) ;
  1290. #quota( $sync, $sync->{imap1}, 'h1' ) ; # quota on host1 is useless and pollute host2 output.
  1291. quota( $sync, $sync->{imap2}, 'h2' ) ;
  1292. maxsize_setting( $sync ) ;
  1293. if ( $sync->{ justlogin } ) {
  1294. $sync->{imap1}->logout( ) ;
  1295. $sync->{imap2}->logout( ) ;
  1296. exit_clean( $sync, $EX_OK, "Exiting because of --justlogin\n" ) ;
  1297. }
  1298. #
  1299. # Folder stuff
  1300. #
  1301. $h1_folders_wanted_nb = 0 ; # counter of folders to be done.
  1302. $h1_folders_wanted_ct = 0 ; # counter of folders done.
  1303. # All folders on host1 and host2
  1304. @h1_folders_all = sort $sync->{imap1}->folders( ) ;
  1305. @h2_folders_all = sort $sync->{imap2}->folders( ) ;
  1306. myprint( 'Host1: found ', scalar @h1_folders_all , " folders.\n" ) ;
  1307. myprint( 'Host2: found ', scalar @h2_folders_all , " folders.\n" ) ;
  1308. foreach my $f ( @h1_folders_all )
  1309. {
  1310. $h1_folders_all{ $f } = 1
  1311. }
  1312. foreach my $f ( @h2_folders_all )
  1313. {
  1314. $h2_folders_all{ $f } = 1 ;
  1315. $sync->{h2_folders_all_UPPER}{ uc $f } = 1 ;
  1316. }
  1317. $sync->{h1_folders_all} = \%h1_folders_all ;
  1318. $sync->{h2_folders_all} = \%h2_folders_all ;
  1319. private_folders_separators_and_prefixes( ) ;
  1320. # Make a hash of subscribed folders in both servers.
  1321. for ( $sync->{imap1}->subscribed( ) ) { $h1_subscribed_folder{ $_ } = 1 } ;
  1322. for ( $sync->{imap2}->subscribed( ) ) { $h2_subscribed_folder{ $_ } = 1 } ;
  1323. if ( defined $sync->{ subfolder1 } ) {
  1324. subfolder1( $sync ) ;
  1325. }
  1326. if ( defined $sync->{ subfolder2 } ) {
  1327. subfolder2( $sync ) ;
  1328. }
  1329. if ( $fixInboxINBOX and ( my $reg = fix_Inbox_INBOX_mapping( \%h1_folders_all, \%h2_folders_all ) ) ) {
  1330. push @{ $sync->{ regextrans2 } }, $reg ;
  1331. }
  1332. if ( ( $sync->{ folder } and scalar @{ $sync->{ folder } } )
  1333. or $subscribed
  1334. or scalar @folderrec )
  1335. {
  1336. # folders given by option --folder
  1337. if ( $sync->{ folder } and scalar @{ $sync->{ folder } } ) {
  1338. add_to_requested_folders( @{ $sync->{ folder } } ) ;
  1339. }
  1340. # option --subscribed
  1341. if ( $subscribed ) {
  1342. add_to_requested_folders( keys %h1_subscribed_folder ) ;
  1343. }
  1344. # option --folderrec
  1345. if ( scalar @folderrec ) {
  1346. foreach my $folderrec ( @folderrec ) {
  1347. add_to_requested_folders( $sync->{imap1}->folders( $folderrec ) ) ;
  1348. }
  1349. }
  1350. }
  1351. else
  1352. {
  1353. # no include, no folder/subscribed/folderrec options => all folders
  1354. if ( not scalar @include ) {
  1355. 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" ) ;
  1356. add_to_requested_folders( @h1_folders_all ) ;
  1357. }
  1358. }
  1359. # consider (optional) includes and excludes
  1360. if ( scalar @include ) {
  1361. foreach my $include ( @include ) {
  1362. # No, do not add /x after the regex, never.
  1363. # Users would kill you!
  1364. my @included_folders = grep { /$include/ } @h1_folders_all ;
  1365. add_to_requested_folders( @included_folders ) ;
  1366. myprint( "Including folders matching pattern $include\n" . jux_utf8_list( @included_folders ) . "\n" ) ;
  1367. }
  1368. }
  1369. if ( scalar @exclude ) {
  1370. foreach my $exclude ( @exclude ) {
  1371. my @requested_folder = sort keys %requested_folder ;
  1372. # No, do not add /x after the regex, never.
  1373. # Users would kill you!
  1374. my @excluded_folders = grep { /$exclude/ } @requested_folder ;
  1375. remove_from_requested_folders( @excluded_folders ) ;
  1376. myprint( "Excluding folders matching pattern $exclude\n" . jux_utf8_list( @excluded_folders ) . "\n" ) ;
  1377. }
  1378. }
  1379. # sort before is not very powerful
  1380. # it adds --folderfirst and --folderlast even if they don't exist on host1
  1381. #@h1_folders_wanted = sort_requested_folders( ) ;
  1382. $sync->{h1_folders_wanted} = [ sort_requested_folders( ) ] ;
  1383. # Remove no selectable folders
  1384. if ( $sync->{ checkfoldersexist } ) {
  1385. my @h1_folders_wanted_exist ;
  1386. myprint( "Host1: Checking wanted folders exist. Use --nocheckfoldersexist to avoid this check (shared of public namespace targeted).\n" ) ;
  1387. foreach my $folder ( @{ $sync->{h1_folders_wanted} } ) {
  1388. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "Checking $folder exists on host1\n" ) ;
  1389. if ( ! exists $h1_folders_all{ $folder } ) {
  1390. myprint( "Host1: warning! ignoring folder $folder because it is not in host1 whole folders list.\n" ) ;
  1391. next ;
  1392. }else{
  1393. push @h1_folders_wanted_exist, $folder ;
  1394. }
  1395. }
  1396. @{ $sync->{h1_folders_wanted} } = @h1_folders_wanted_exist ;
  1397. }else{
  1398. myprint( "Host1: Not checking that wanted folders exist. Remove --nocheckfoldersexist to get this check.\n" ) ;
  1399. }
  1400. if ( $sync->{ checkselectable } ) {
  1401. my @h1_folders_wanted_selectable ;
  1402. myprint( "Host1: Checking wanted folders are selectable. Use --nocheckselectable to avoid this check.\n" ) ;
  1403. foreach my $folder ( @{ $sync->{h1_folders_wanted} } ) {
  1404. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "Checking $folder is selectable on host1\n" ) ;
  1405. # It does an imap command LIST "" $folder and then search for no \Noselect
  1406. if ( ! $sync->{imap1}->selectable( $folder ) ) {
  1407. myprint( "Host1: warning! ignoring folder $folder because it is not selectable\n" ) ;
  1408. }else{
  1409. push @h1_folders_wanted_selectable, $folder ;
  1410. }
  1411. }
  1412. @{ $sync->{h1_folders_wanted} } = @h1_folders_wanted_selectable ;
  1413. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( 'Host1: checking folders took ', timenext( $sync ), " s\n" ) ;
  1414. }else{
  1415. myprint( "Host1: Not checking that wanted folders are selectable. Remove --nocheckselectable to get this check.\n" ) ;
  1416. }
  1417. # Old place of private_folders_separators_and_prefixes( ) call.
  1418. #private_folders_separators_and_prefixes( ) ;
  1419. # this hack is because LWP post does not pass well a hash in the $form parameter
  1420. # but it does pass well an array
  1421. %{ $sync->{f1f2h} } = split_around_equal( @{ $sync->{f1f2} } ) ;
  1422. automap( $sync ) ;
  1423. foreach my $h1_fold ( @{ $sync->{h1_folders_wanted} } ) {
  1424. my $h2_fold ;
  1425. $h2_fold = imap2_folder_name( $sync, $h1_fold ) ;
  1426. $h2_folders_from_1_wanted{ $h2_fold }++ ;
  1427. if ( 1 < $h2_folders_from_1_wanted{ $h2_fold } ) {
  1428. $h2_folders_from_1_several{ $h2_fold }++ ;
  1429. }
  1430. }
  1431. @h2_folders_from_1_wanted = sort keys %h2_folders_from_1_wanted;
  1432. foreach my $h1_fold ( @h1_folders_all ) {
  1433. my $h2_fold ;
  1434. $h2_fold = imap2_folder_name( $sync, $h1_fold ) ;
  1435. $h2_folders_from_1_all{ $h2_fold }++ ;
  1436. # Follows a fix to avoid deleting folder $sync->{ subfolder2 }
  1437. # because it usually does not exist on host1.
  1438. if ( $sync->{ subfolder2 } )
  1439. {
  1440. $h2_folders_from_1_all{ $sync->{ h2_prefix } . $sync->{ subfolder2 } }++ ;
  1441. $h2_folders_from_1_all{ $sync->{ subfolder2 } }++ ;
  1442. }
  1443. }
  1444. myprint( << 'END_LISTING' ) ;
  1445. ++++ Listing folders
  1446. All foldernames are presented between brackets like [X] where X is the foldername.
  1447. When a foldername contains non-ASCII characters it is presented in the form
  1448. [X] = [Y] where
  1449. X is the imap foldername you have to use in command line options and
  1450. Y is the utf8 output just printed for convenience, to recognize it.
  1451. END_LISTING
  1452. myprint(
  1453. "Host1: folders list (first the raw imap format then the [X] = [Y]):\n",
  1454. $sync->{imap1}->list( ),
  1455. "\n",
  1456. jux_utf8_list( @h1_folders_all ),
  1457. "\n",
  1458. "Host2: folders list (first the raw imap format then the [X] = [Y]):\n",
  1459. $sync->{imap2}->list( ),
  1460. "\n",
  1461. jux_utf8_list( @h2_folders_all ),
  1462. "\n",
  1463. q{}
  1464. ) ;
  1465. if ( $subscribed ) {
  1466. myprint(
  1467. 'Host1 subscribed folders list: ',
  1468. jux_utf8_list( sort keys %h1_subscribed_folder ), "\n",
  1469. ) ;
  1470. }
  1471. @h2_folders_not_in_1 = list_folders_in_2_not_in_1( ) ;
  1472. if ( @h2_folders_not_in_1 ) {
  1473. myprint( "Folders in host2 not in host1:\n",
  1474. jux_utf8_list( @h2_folders_not_in_1 ), "\n" ) ;
  1475. }
  1476. if ( keys %{ $sync->{f1f2auto} } ) {
  1477. myprint( "Folders mapping from --automap feature (use --f1f2 to override any mapping):\n" ) ;
  1478. foreach my $h1_fold ( keys %{ $sync->{f1f2auto} } ) {
  1479. my $h2_fold = $sync->{f1f2auto}{$h1_fold} ;
  1480. myprintf( "%-40s -> %-40s\n",
  1481. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1482. }
  1483. myprint( "\n" ) ;
  1484. }
  1485. if ( keys %{ $sync->{f1f2h} } ) {
  1486. myprint( "Folders mapping from --f1f2 options, it overrides --automap:\n" ) ;
  1487. foreach my $h1_fold ( keys %{ $sync->{f1f2h} } ) {
  1488. my $h2_fold = $sync->{f1f2h}{$h1_fold} ;
  1489. my $warn = q{} ;
  1490. if ( not exists $h1_folders_all{ $h1_fold } ) {
  1491. $warn = "BUT $h1_fold does NOT exist on host1!" ;
  1492. }
  1493. myprintf( "%-40s -> %-40s %s\n",
  1494. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ), $warn ) ;
  1495. }
  1496. myprint( "\n" ) ;
  1497. }
  1498. exit_clean( $sync, $EX_OK, "Exiting because of --justfolderlists\n" ) if ( $sync->{ justfolderlists } ) ;
  1499. exit_clean( $sync, $EX_OK, "Exiting because of --justautomap\n" ) if ( $sync->{ justautomap } ) ;
  1500. debugsleep( $sync ) ;
  1501. if ( $sync->{ skipemptyfolders } )
  1502. {
  1503. myprint( "Host1: will not syncing empty folders on host1. Use --noskipemptyfolders to create them anyway on host2\n") ;
  1504. }
  1505. if ( $sync->{ foldersizes } ) {
  1506. foldersizes_at_the_beggining( $sync ) ;
  1507. #foldersizes_at_the_beggining_old( $sync ) ;
  1508. }
  1509. if ( $sync->{ justfoldersizes } )
  1510. {
  1511. exit_clean( $sync, $EX_OK, "Exiting because of --justfoldersizes\n" ) ;
  1512. }
  1513. $sync->{stats} = 1 ;
  1514. if ( $sync->{ delete1emptyfolders } ) {
  1515. delete1emptyfolders( $sync ) ;
  1516. }
  1517. delete_folders_in_2_not_in_1( ) if $delete2folders ;
  1518. # folder loop
  1519. $h1_folders_wanted_nb = scalar @{ $sync->{h1_folders_wanted} } ;
  1520. myprint( "++++ Looping on each one of $h1_folders_wanted_nb folders to sync\n" ) ;
  1521. $sync->{begin_transfer_time} = time ;
  1522. my %uid_candidate_for_deletion ;
  1523. my %uid_candidate_no_deletion ;
  1524. $sync->{ h2_folders_of_md5 } = { } ;
  1525. FOLDER: foreach my $h1_fold ( @{ $sync->{h1_folders_wanted} } )
  1526. {
  1527. $sync->{ h1_current_folder } = $h1_fold ;
  1528. eta_print( $sync ) ;
  1529. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1530. my $h2_fold = imap2_folder_name( $sync, $h1_fold ) ;
  1531. $sync->{ h2_current_folder } = $h2_fold ;
  1532. $h1_folders_wanted_ct++ ;
  1533. myprintf( "Folder %7s %-35s -> %-35s\n", "$h1_folders_wanted_ct/$h1_folders_wanted_nb",
  1534. jux_utf8( $h1_fold ), jux_utf8( $h2_fold ) ) ;
  1535. myprint( debugmemory( $sync, " at folder loop" ) ) ;
  1536. # host1 can not be fetched read only, select is needed because of expunge.
  1537. select_folder( $sync, $sync->{imap1}, $h1_fold, 'Host1' ) or next FOLDER ;
  1538. debugsleep( $sync ) ;
  1539. my $h1_fold_nb_messages = count_from_select( $sync->{imap1}->History ) ;
  1540. myprint( "Host1: folder [$h1_fold] has $h1_fold_nb_messages messages in total (mentioned by SELECT)\n" ) ;
  1541. if ( $sync->{ skipemptyfolders } and 0 == $h1_fold_nb_messages ) {
  1542. myprint( "Host1: skipping empty host1 folder [$h1_fold]\n" ) ;
  1543. next FOLDER ;
  1544. }
  1545. # Code added from https://github.com/imapsync/imapsync/issues/95
  1546. # Thanks jh1995
  1547. # Goal: do not create folder if --search or --max/minage return 0 message.
  1548. # even if there are messages by SELECT (no not real empty, empty for the user point of vue).
  1549. if ( $sync->{ skipemptyfolders } )
  1550. {
  1551. my $h1_msgs_all_hash_ref_tmp = { } ;
  1552. my @h1_msgs_tmp = select_msgs( $sync->{imap1}, $h1_msgs_all_hash_ref_tmp, $sync->{ search1 }, $h1_fold ) ;
  1553. my $h1_fold_nb_messages_tmp = scalar( @h1_msgs_tmp ) ;
  1554. if ( 0 == $h1_fold_nb_messages_tmp ) {
  1555. myprint( "Host1: skipping empty host1 folder [$h1_fold] (0 message found by SEARCH)\n" ) ;
  1556. next FOLDER ;
  1557. }
  1558. }
  1559. if ( ! exists $h2_folders_all{ $h2_fold } ) {
  1560. create_folder( $sync, $sync->{imap2}, $h2_fold, $h1_fold ) or next FOLDER ;
  1561. }
  1562. acls_sync( $h1_fold, $h2_fold ) ;
  1563. # Sometimes the folder on host2 is listed (it exists) but is
  1564. # not selectable but becomes selectable by a create (Gmail)
  1565. select_folder( $sync, $sync->{imap2}, $h2_fold, 'Host2' )
  1566. or ( create_folder( $sync, $sync->{imap2}, $h2_fold, $h1_fold )
  1567. and select_folder( $sync, $sync->{imap2}, $h2_fold, 'Host2' ) )
  1568. or next FOLDER ;
  1569. my @select_results = $sync->{imap2}->Results( ) ;
  1570. my $h2_fold_nb_messages = count_from_select( @select_results ) ;
  1571. myprint( "Host2: folder [$h2_fold] has $h2_fold_nb_messages messages in total (mentioned by SELECT)\n" ) ;
  1572. my $permanentflags2 = permanentflags( @select_results ) ;
  1573. myprint( "Host2: folder [$h2_fold] permanentflags: $permanentflags2\n" ) ;
  1574. if ( $sync->{ expunge1 } )
  1575. {
  1576. myprint( "Host1: Expunging $h1_fold $sync->{dry_message}\n" ) ;
  1577. if ( ! $sync->{dry} )
  1578. {
  1579. $sync->{imap1}->expunge( ) ;
  1580. }
  1581. }
  1582. if ( ( ( $subscribe and exists $h1_subscribed_folder{ $h1_fold } ) or $subscribeall )
  1583. and not exists $h2_subscribed_folder{ $h2_fold } )
  1584. {
  1585. myprint( "Host2: Subscribing to folder $h2_fold\n" ) ;
  1586. if ( ! $sync->{dry} ) { $sync->{imap2}->subscribe( $h2_fold ) } ;
  1587. }
  1588. next FOLDER if ( $sync->{ justfolders } ) ;
  1589. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1590. my $h1_msgs_all_hash_ref = { } ;
  1591. my @h1_msgs = select_msgs( $sync->{imap1}, $h1_msgs_all_hash_ref, $sync->{ search1 }, $sync->{abletosearch1}, $h1_fold );
  1592. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1593. my $h1_msgs_nb = scalar @h1_msgs ;
  1594. myprint( "Host1: folder [$h1_fold] considering $h1_msgs_nb messages\n" ) ;
  1595. ( $sync->{ debug } or $debuglist ) and myprint( "Host1: folder [$h1_fold] considering $h1_msgs_nb messages, LIST gives: @h1_msgs\n" ) ;
  1596. $sync->{ debug } and myprint( "Host1: selecting messages of folder [$h1_fold] took ", timenext( $sync ), " s\n" ) ;
  1597. my $h2_msgs_all_hash_ref = { } ;
  1598. my @h2_msgs = select_msgs( $sync->{imap2}, $h2_msgs_all_hash_ref, $sync->{ search2 }, $sync->{abletosearch2}, $h2_fold ) ;
  1599. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1600. my $h2_msgs_nb = scalar @h2_msgs ;
  1601. myprint( "Host2: folder [$h2_fold] considering $h2_msgs_nb messages\n" ) ;
  1602. ( $sync->{ debug } or $debuglist ) and myprint( "Host2: folder [$h2_fold] considering $h2_msgs_nb messages, LIST gives: @h2_msgs\n" ) ;
  1603. $sync->{ debug } and myprint( "Host2: selecting messages of folder [$h2_fold] took ", timenext( $sync ), " s\n" ) ;
  1604. my $cache_base = "$sync->{ tmpdir }/imapsync_cache/" ;
  1605. my $cache_dir = cache_folder( $cache_base,
  1606. "$sync->{host1}/$sync->{user1}/$sync->{host2}/$sync->{user2}", $h1_fold, $h2_fold ) ;
  1607. my ( $cache_1_2_ref, $cache_2_1_ref ) = ( {}, {} ) ;
  1608. my $h1_uidvalidity = $sync->{imap1}->uidvalidity( ) || q{} ;
  1609. my $h2_uidvalidity = $sync->{imap2}->uidvalidity( ) || q{} ;
  1610. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1611. if ( $usecache ) {
  1612. myprint( "Local cache directory: $cache_dir ( " . length( $cache_dir ) . " characters long )\n" ) ;
  1613. mkpath( "$cache_dir" ) ;
  1614. ( $cache_1_2_ref, $cache_2_1_ref )
  1615. = get_cache( $cache_dir, \@h1_msgs, \@h2_msgs, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  1616. myprint( 'CACHE h1 h2: ', scalar keys %{ $cache_1_2_ref } , " files\n" ) ;
  1617. $sync->{ debug } and myprint( '[',
  1618. map ( { "$_->$cache_1_2_ref->{$_} " } keys %{ $cache_1_2_ref } ), " ]\n" ) ;
  1619. }
  1620. my %h1_hash = ( ) ;
  1621. my %h2_hash = ( ) ;
  1622. my ( %h1_msgs, %h2_msgs ) ;
  1623. @h1_msgs{ @h1_msgs } = ( ) ;
  1624. @h2_msgs{ @h2_msgs } = ( ) ;
  1625. my @h1_msgs_in_cache = sort { $a <=> $b } keys %{ $cache_1_2_ref } ;
  1626. my @h2_msgs_in_cache = keys %{ $cache_2_1_ref } ;
  1627. my ( %h1_msgs_not_in_cache, %h2_msgs_not_in_cache ) ;
  1628. %h1_msgs_not_in_cache = %h1_msgs ;
  1629. %h2_msgs_not_in_cache = %h2_msgs ;
  1630. delete @h1_msgs_not_in_cache{ @h1_msgs_in_cache } ;
  1631. delete @h2_msgs_not_in_cache{ @h2_msgs_in_cache } ;
  1632. my @h1_msgs_not_in_cache = keys %h1_msgs_not_in_cache ;
  1633. #myprint( "h1_msgs_not_in_cache: [@h1_msgs_not_in_cache]\n" ) ;
  1634. my @h2_msgs_not_in_cache = keys %h2_msgs_not_in_cache ;
  1635. my @h2_msgs_delete2_not_in_cache = () ;
  1636. %h1_msgs_copy_by_uid = ( ) ;
  1637. if ( $useuid ) {
  1638. # use uid so we have to avoid getting header
  1639. @h1_msgs_copy_by_uid{ @h1_msgs_not_in_cache } = ( ) ;
  1640. @h2_msgs_delete2_not_in_cache = @h2_msgs_not_in_cache if $usecache ;
  1641. @h1_msgs_not_in_cache = ( ) ;
  1642. @h2_msgs_not_in_cache = ( ) ;
  1643. #myprint( "delete2: @h2_msgs_delete2_not_in_cache\n" ) ;
  1644. }
  1645. $sync->{ debug } and myprint( "Host1: parsing headers of folder [$h1_fold]\n" ) ;
  1646. my ($h1_heads_ref, $h1_fir_ref) = ({}, {});
  1647. $h1_heads_ref = $sync->{imap1}->parse_headers([@h1_msgs_not_in_cache], @useheader) if (@h1_msgs_not_in_cache);
  1648. $sync->{ debug } and myprint( "Host1: parsing headers of folder [$h1_fold] took ", timenext( $sync ), " s\n" ) ;
  1649. @{ $h1_fir_ref }{@h1_msgs} = ( undef ) ;
  1650. $sync->{ debug } and myprint( "Host1: getting flags idate and sizes of folder [$h1_fold]\n" ) ;
  1651. my @h1_common_fetch_param = ( 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE' ) ;
  1652. if ( $sync->{ synclabels } or $sync->{ resynclabels } ) { push @h1_common_fetch_param, 'X-GM-LABELS' ; }
  1653. if ( $sync->{abletosearch1} )
  1654. {
  1655. $h1_fir_ref = $sync->{imap1}->fetch_hash( \@h1_msgs, @h1_common_fetch_param, $h1_fir_ref )
  1656. if ( @h1_msgs ) ;
  1657. }
  1658. else
  1659. {
  1660. my $uidnext = $sync->{imap1}->uidnext( $h1_fold ) || $uidnext_default ;
  1661. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  1662. $h1_fir_ref = $sync->{imap1}->fetch_hash( $fetch_hash_uids, @h1_common_fetch_param, $h1_fir_ref )
  1663. if ( @h1_msgs ) ;
  1664. }
  1665. $sync->{ debug } and myprint( "Host1: getting flags idate and sizes of folder [$h1_fold] took ", timenext( $sync ), " s\n" ) ;
  1666. if ( ! $h1_fir_ref )
  1667. {
  1668. my $error = join( q{}, "Host1: folder $h1_fold : Could not fetch_hash ",
  1669. scalar @h1_msgs, ' msgs: ', $sync->{imap1}->LastError || q{}, "\n" ) ;
  1670. errors_incr( $sync, $error ) ;
  1671. next FOLDER ;
  1672. }
  1673. my @h1_msgs_duplicate;
  1674. foreach my $m ( @h1_msgs_not_in_cache )
  1675. {
  1676. my $rc = parse_header_msg( $sync, $sync->{imap1}, $m, $h1_heads_ref, $h1_fir_ref, 'Host1', \%h1_hash ) ;
  1677. if ( ! defined $rc )
  1678. {
  1679. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1680. myprint( "Host1: $h1_fold/$m size $h1_size ignored (no wanted headers so we ignore this message. To solve this: use --addheader)\n" ) ;
  1681. $sync->{ total_bytes_skipped } += $h1_size ;
  1682. $sync->{ nb_msg_skipped } += 1 ;
  1683. $sync->{ h1_nb_msg_noheader } +=1 ;
  1684. $sync->{ h1_nb_msg_processed } +=1 ;
  1685. } elsif(0 == $rc)
  1686. {
  1687. # duplicate
  1688. push @h1_msgs_duplicate, $m;
  1689. # duplicate, same id same size?
  1690. my $h1_size = $h1_fir_ref->{$m}->{'RFC822.SIZE'} || 0;
  1691. $sync->{ nb_msg_skipped } += 1;
  1692. $h1_nb_msg_duplicate += 1;
  1693. $sync->{ h1_nb_msg_processed } +=1 ;
  1694. }
  1695. }
  1696. my $h1_msgs_duplicate_nb = scalar @h1_msgs_duplicate ;
  1697. myprint( "Host1: folder [$h1_fold] selected $h1_msgs_nb messages, duplicates $h1_msgs_duplicate_nb\n" ) ;
  1698. $sync->{ debug } and myprint( 'Host1: whole time parsing headers took ', timenext( $sync ), " s\n" ) ;
  1699. # Getting headers and metada can be so long that host2 might be disconnected here
  1700. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1701. $sync->{ debug } and myprint( "Host2: parsing headers of folder [$h2_fold]\n" ) ;
  1702. my ($h2_heads_ref, $h2_fir_ref) = ( {}, {} );
  1703. $h2_heads_ref = $sync->{imap2}->parse_headers([@h2_msgs_not_in_cache], @useheader) if (@h2_msgs_not_in_cache);
  1704. $sync->{ debug } and myprint( "Host2: parsing headers of folder [$h2_fold] took ", timenext( $sync ), " s\n" ) ;
  1705. $sync->{ debug } and myprint( "Host2: getting flags idate and sizes of folder [$h2_fold]\n" ) ;
  1706. @{ $h2_fir_ref }{@h2_msgs} = ( ); # fetch_hash can select by uid with last arg as ref
  1707. my @h2_common_fetch_param = ( 'FLAGS', 'INTERNALDATE', 'RFC822.SIZE' ) ;
  1708. if ( $sync->{ synclabels } or $sync->{ resynclabels } ) { push @h2_common_fetch_param, 'X-GM-LABELS' ; }
  1709. if ( $sync->{abletosearch2} and scalar( @h2_msgs ) ) {
  1710. $h2_fir_ref = $sync->{imap2}->fetch_hash( \@h2_msgs, @h2_common_fetch_param, $h2_fir_ref) ;
  1711. }else{
  1712. my $uidnext = $sync->{imap2}->uidnext( $h2_fold ) || $uidnext_default ;
  1713. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  1714. $h2_fir_ref = $sync->{imap2}->fetch_hash( $fetch_hash_uids, @h2_common_fetch_param, $h2_fir_ref )
  1715. if ( @h2_msgs ) ;
  1716. }
  1717. $sync->{ debug } and myprint( "Host2: getting flags idate and sizes of folder [$h2_fold] took ", timenext( $sync ), " s\n" ) ;
  1718. my @h2_msgs_duplicate;
  1719. foreach my $m (@h2_msgs_not_in_cache) {
  1720. my $rc = parse_header_msg( $sync, $sync->{imap2}, $m, $h2_heads_ref, $h2_fir_ref, 'Host2', \%h2_hash ) ;
  1721. my $h2_size = $h2_fir_ref->{$m}->{'RFC822.SIZE'} || 0 ;
  1722. if (! defined $rc ) {
  1723. myprint( "Host2: $h2_fold/$m size $h2_size ignored (no wanted headers so we ignore this message)\n" ) ;
  1724. $h2_nb_msg_noheader += 1 ;
  1725. } elsif( 0 == $rc ) {
  1726. # duplicate
  1727. $h2_nb_msg_duplicate += 1 ;
  1728. push @h2_msgs_duplicate, $m ;
  1729. }
  1730. }
  1731. # %h2_folders_of_md5
  1732. foreach my $md5 ( keys %h2_hash ) {
  1733. $sync->{ h2_folders_of_md5 }->{ $md5 }->{ $h2_fold } ++ ;
  1734. }
  1735. # %h1_folders_of_md5
  1736. foreach my $md5 ( keys %h1_hash ) {
  1737. $sync->{ h1_folders_of_md5 }->{ $md5 }->{ $h2_fold } ++ ;
  1738. }
  1739. my $h2_msgs_duplicate_nb = scalar @h2_msgs_duplicate ;
  1740. myprint( "Host2: folder [$h2_fold] selected $h2_msgs_nb messages, duplicates $h2_msgs_duplicate_nb\n" ) ;
  1741. $sync->{ debug } and myprint( 'Host2 whole time parsing headers took ', timenext( $sync ), " s\n" ) ;
  1742. $sync->{ debug } and myprint( "++++ Verifying [$h1_fold] -> [$h2_fold]\n" ) ;
  1743. # messages in host1 that are not in host2
  1744. my @h1_hash_keys_sorted_by_uid
  1745. = sort {$h1_hash{$a}{'m'} <=> $h1_hash{$b}{'m'}} keys %h1_hash;
  1746. #myprint( map { $h1_hash{$_}{'m'} . q{ }} @h1_hash_keys_sorted_by_uid ) ;
  1747. my @h2_hash_keys_sorted_by_uid
  1748. = sort {$h2_hash{$a}{'m'} <=> $h2_hash{$b}{'m'}} keys %h2_hash;
  1749. # Deletions on account2.
  1750. if( $sync->{ delete2duplicates } and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  1751. my @h2_expunge ;
  1752. foreach my $h2_msg ( @h2_msgs_duplicate ) {
  1753. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted [duplicate] on host2 $sync->{dry_message}\n" ) ;
  1754. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 } ;
  1755. if ( ! $sync->{dry} ) {
  1756. $sync->{imap2}->delete_message( $h2_msg ) ;
  1757. $h2_nb_msg_deleted += 1 ;
  1758. }
  1759. }
  1760. my $cnt = scalar @h2_expunge ;
  1761. if( @h2_expunge and not $sync->{ expunge2 } ) {
  1762. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  1763. $sync->{imap2}->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  1764. }
  1765. if ( $sync->{ expunge2 } ){
  1766. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  1767. $sync->{imap2}->expunge( ) if ! $sync->{dry} ;
  1768. }
  1769. }
  1770. if( $sync->{ delete2 } and not exists $h2_folders_from_1_several{ $h2_fold } ) {
  1771. # No host1 folders f1a f1b ... going all to same f2 (via --regextrans2)
  1772. my @h2_expunge;
  1773. foreach my $m_id (@h2_hash_keys_sorted_by_uid) {
  1774. #myprint( "$m_id " ) ;
  1775. if ( ! exists $h1_hash{$m_id} ) {
  1776. my $h2_msg = $h2_hash{$m_id}{'m'};
  1777. my $h2_flags = $h2_hash{$m_id}{'F'} || q{};
  1778. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0;
  1779. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted on host2 [$m_id] $sync->{dry_message}\n" )
  1780. if ! $isdel;
  1781. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 };
  1782. if ( ! ( $sync->{dry} or $isdel ) ) {
  1783. $sync->{imap2}->delete_message($h2_msg);
  1784. $h2_nb_msg_deleted += 1;
  1785. }
  1786. }
  1787. }
  1788. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  1789. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted [not in cache] on host2 $sync->{dry_message}\n" ) ;
  1790. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 };
  1791. if ( ! $sync->{dry} ) {
  1792. $sync->{imap2}->delete_message($h2_msg);
  1793. $h2_nb_msg_deleted += 1;
  1794. }
  1795. }
  1796. my $cnt = scalar @h2_expunge ;
  1797. if( @h2_expunge and not $sync->{ expunge2 } ) {
  1798. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  1799. $sync->{imap2}->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  1800. }
  1801. if ( $sync->{ expunge2 } ) {
  1802. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  1803. $sync->{imap2}->expunge( ) if ! $sync->{dry} ;
  1804. }
  1805. }
  1806. if( $sync->{ delete2 } and exists $h2_folders_from_1_several{ $h2_fold } ) {
  1807. myprint( "Host2: folder $h2_fold $h2_folders_from_1_several{ $h2_fold } folders left to sync there\n" ) ;
  1808. my @h2_expunge;
  1809. foreach my $m_id ( @h2_hash_keys_sorted_by_uid ) {
  1810. my $h2_msg = $h2_hash{ $m_id }{ 'm' } ;
  1811. if ( ! exists $h1_hash{ $m_id } ) {
  1812. my $h2_flags = $h2_hash{ $m_id }{ 'F' } || q{} ;
  1813. my $isdel = $h2_flags =~ /\B\\Deleted\b/x ? 1 : 0 ;
  1814. if ( ! $isdel ) {
  1815. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [$m_id]\n" ) ;
  1816. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  1817. }
  1818. }else{
  1819. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [$m_id]\n" ) ;
  1820. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1821. }
  1822. }
  1823. foreach my $h2_msg ( @h2_msgs_delete2_not_in_cache ) {
  1824. myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion [not in cache]\n" ) ;
  1825. $uid_candidate_for_deletion{ $h2_fold }{ $h2_msg }++ ;
  1826. }
  1827. foreach my $h2_msg ( @h2_msgs_in_cache ) {
  1828. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [in cache]\n" ) ;
  1829. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1830. }
  1831. if ( 0 == $h2_folders_from_1_several{ $h2_fold } ) {
  1832. # last host1 folder going to $h2_fold
  1833. myprint( "Last host1 folder going to $h2_fold\n" ) ;
  1834. foreach my $h2_msg ( keys %{ $uid_candidate_for_deletion{ $h2_fold } } ) {
  1835. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg candidate for deletion\n" ) ;
  1836. if ( exists $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg } ) {
  1837. $sync->{ debug } and myprint( "Host2: msg $h2_fold/$h2_msg canceled deletion\n" ) ;
  1838. }else{
  1839. myprint( "Host2: msg $h2_fold/$h2_msg marked \\Deleted $sync->{dry_message}\n" ) ;
  1840. push @h2_expunge, $h2_msg if $sync->{ uidexpunge2 } ;
  1841. if ( ! $sync->{dry} ) {
  1842. $sync->{imap2}->delete_message( $h2_msg ) ;
  1843. $h2_nb_msg_deleted += 1 ;
  1844. }
  1845. }
  1846. }
  1847. }
  1848. my $cnt = scalar @h2_expunge ;
  1849. if( @h2_expunge and not $sync->{ expunge2 } ) {
  1850. myprint( "Host2: UidExpunging $cnt message(s) in folder $h2_fold $sync->{dry_message}\n" ) ;
  1851. $sync->{imap2}->uidexpunge( \@h2_expunge ) if ! $sync->{dry} ;
  1852. }
  1853. if ( $sync->{ expunge2 } ) {
  1854. myprint( "Host2: Expunging host2 folder $h2_fold $sync->{dry_message}\n" ) ;
  1855. $sync->{imap2}->expunge( ) if ! $sync->{dry} ;
  1856. }
  1857. $h2_folders_from_1_several{ $h2_fold }-- ;
  1858. }
  1859. my $h2_uidnext = $sync->{imap2}->uidnext( $h2_fold ) ;
  1860. $sync->{ debug } and myprint( "Host2: uidnext is $h2_uidnext\n" ) ;
  1861. $h2_uidguess = $h2_uidnext ;
  1862. # Getting host2 headers, metada and delete2 stuff can be so long that host1 might be disconnected here
  1863. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1864. my @h1_msgs_to_delete ;
  1865. MESS: foreach my $m_id (@h1_hash_keys_sorted_by_uid) {
  1866. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1867. #myprint( "h1_nb_msg_processed: $sync->{ h1_nb_msg_processed }\n" ) ;
  1868. my $h1_size = $h1_hash{$m_id}{'s'};
  1869. my $h1_msg = $h1_hash{$m_id}{'m'};
  1870. my $h1_idate = $h1_hash{$m_id}{'D'};
  1871. #my $labels = labels( $sync->{imap1}, $h1_msg ) ;
  1872. #print "LABELS: $labels\n" ;
  1873. if ( ( not exists $h2_hash{ $m_id } )
  1874. and ( not ( exists $sync->{ h2_folders_of_md5 }->{ $m_id } )
  1875. or not $skipcrossduplicates ) )
  1876. {
  1877. # copy
  1878. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  1879. if ( $h2_msg and $sync->{ delete1 } and not $sync->{ expungeaftereach } ) {
  1880. # not expunged
  1881. push @h1_msgs_to_delete, $h1_msg ;
  1882. }
  1883. # A bug here with imapsync 1.920, fixed in 1.921
  1884. # Added $h2_msg in the condition. Errors of APPEND were not counted as missing messages on host2!
  1885. if ( $h2_msg and not $sync->{ dry } )
  1886. {
  1887. $sync->{ h2_folders_of_md5 }->{ $m_id }->{ $h2_fold } ++ ;
  1888. }
  1889. #
  1890. if( $sync->{ delete2 } and ( exists $h2_folders_from_1_several{ $h2_fold } ) and $h2_msg ) {
  1891. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  1892. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1893. }
  1894. if ( total_bytes_max_reached( $sync ) ) {
  1895. # a bug when using --delete1 --noexpungeaftereach
  1896. # same thing below on all total_bytes_max_reached!
  1897. last FOLDER ;
  1898. }
  1899. next MESS;
  1900. }
  1901. else
  1902. {
  1903. # already on host2
  1904. if ( exists $h2_hash{ $m_id } )
  1905. {
  1906. my $h2_msg = $h2_hash{$m_id}{'m'} ;
  1907. $sync->{ debug } and myprint( "Host1: found that msg $h1_fold/$h1_msg equals Host2 $h2_fold/$h2_msg\n" ) ;
  1908. if ( $usecache )
  1909. {
  1910. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$h2_msg\n" ) ;
  1911. touch( "$cache_dir/${h1_msg}_$h2_msg" )
  1912. or croak( "Couldn't touch $cache_dir/${h1_msg}_$h2_msg" ) ;
  1913. }
  1914. }
  1915. elsif( exists $sync->{ h2_folders_of_md5 }->{ $m_id } )
  1916. {
  1917. my @folders_dup = keys %{ $sync->{ h2_folders_of_md5 }->{ $m_id } } ;
  1918. ( $sync->{ debug } or $debugcrossduplicates ) and myprint( "Host1: found that msg $h1_fold/$h1_msg is also in Host2 folders @folders_dup\n" ) ;
  1919. $sync->{ h2_nb_msg_crossdup } +=1 ;
  1920. }
  1921. $sync->{ total_bytes_skipped } += $h1_size ;
  1922. $sync->{ nb_msg_skipped } += 1 ;
  1923. $sync->{ h1_nb_msg_processed } +=1 ;
  1924. }
  1925. if ( exists $h2_hash{ $m_id } ) {
  1926. #$debug and myprint( "MESSAGE $m_id\n" ) ;
  1927. my $h2_msg = $h2_hash{$m_id}{'m'};
  1928. if ( $sync->{resyncflags} ) {
  1929. sync_flags_fir( $sync, $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  1930. }
  1931. # Good
  1932. my $h2_size = $h2_hash{$m_id}{'s'};
  1933. $sync->{ debug } and myprint(
  1934. "Host1: size msg $h1_fold/$h1_msg = $h1_size <> $h2_size = Host2 $h2_fold/$h2_msg\n" ) ;
  1935. if ( $sync->{ resynclabels } )
  1936. {
  1937. resynclabels( $sync, $h1_msg, $h2_msg, $h1_fir_ref, $h2_fir_ref, $h1_fold )
  1938. }
  1939. }
  1940. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1941. if ( $sync->{ delete1 } ) {
  1942. push @h1_msgs_to_delete, $h1_msg ;
  1943. }
  1944. }
  1945. # END MESS: loop
  1946. delete_message_on_host1( $sync, $h1_fold, $sync->{ expunge1 }, @h1_msgs_to_delete, @h1_msgs_in_cache ) ;
  1947. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1948. # MESS_IN_CACHE:
  1949. if ( ! $sync->{ delete1 } )
  1950. {
  1951. foreach my $h1_msg ( @h1_msgs_in_cache )
  1952. {
  1953. my $h2_msg = $cache_1_2_ref->{ $h1_msg } ;
  1954. $debugcache and myprint( "cache messages update flags $h1_msg->$h2_msg\n" ) ;
  1955. if ( $sync->{resyncflags} )
  1956. {
  1957. sync_flags_fir( $sync, $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) ;
  1958. }
  1959. my $h1_size = $h1_fir_ref->{ $h1_msg }->{ 'RFC822.SIZE' } || 0 ;
  1960. $sync->{ total_bytes_skipped } += $h1_size;
  1961. $sync->{ nb_msg_skipped } += 1;
  1962. $sync->{ h1_nb_msg_processed } +=1 ;
  1963. }
  1964. }
  1965. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1966. @h1_msgs_to_delete = ( ) ;
  1967. #myprint( "Messages by uid: ", map { "$_ " } keys %h1_msgs_copy_by_uid, "\n" ) ;
  1968. # MESS_BY_UID:
  1969. foreach my $h1_msg ( sort { $a <=> $b } keys %h1_msgs_copy_by_uid )
  1970. {
  1971. $sync->{ debug } and myprint( "Copy by uid $h1_fold/$h1_msg\n" ) ;
  1972. if ( ! reconnect_12_if_needed( $sync ) ) { last FOLDER ; }
  1973. my $h2_msg = copy_message( $sync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) ;
  1974. if( $sync->{ delete2 } and exists $h2_folders_from_1_several{ $h2_fold } and $h2_msg ) {
  1975. myprint( "Host2: msg $h2_fold/$h2_msg will cancel deletion [fresh copy] on host2\n" ) ;
  1976. $uid_candidate_no_deletion{ $h2_fold }{ $h2_msg }++ ;
  1977. }
  1978. last FOLDER if total_bytes_max_reached( $sync ) ;
  1979. }
  1980. if ( $sync->{ expunge1 } ){
  1981. myprint( "Host1: Expunging folder $h1_fold $sync->{dry_message}\n" ) ;
  1982. if ( ! $sync->{dry} ) { $sync->{imap1}->expunge( ) } ;
  1983. }
  1984. if ( $sync->{ expunge2 } ){
  1985. myprint( "Host2: Expunging folder $h2_fold $sync->{dry_message}\n" ) ;
  1986. if ( ! $sync->{dry} ) { $sync->{imap2}->expunge( ) } ;
  1987. }
  1988. $sync->{ debug } and myprint( 'Time: ', timenext( $sync ), " s\n" ) ;
  1989. }
  1990. eta_print( $sync ) ;
  1991. myprint( "++++ End looping on each folder\n" ) ;
  1992. if ( $sync->{ delete1 } and $sync->{ delete1emptyfolders } ) {
  1993. delete1emptyfolders( $sync ) ;
  1994. }
  1995. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( 'Time: ', timenext( $sync ), " s\n" ) ;
  1996. if ( $sync->{ foldersizesatend } ) {
  1997. myprint( << 'END_SIZE' ) ;
  1998. Folders sizes after the synchronization.
  1999. You can remove this foldersizes listing by using "--nofoldersizesatend"
  2000. END_SIZE
  2001. foldersizesatend( $sync ) ;
  2002. }
  2003. if ( ! lost_connection( $sync, $sync->{imap1}, "for host1 [$sync->{host1}]" ) ) { $sync->{imap1}->logout( ) ; }
  2004. if ( ! lost_connection( $sync, $sync->{imap2}, "for host2 [$sync->{host2}]" ) ) { $sync->{imap2}->logout( ) ; }
  2005. stats( $sync ) ;
  2006. myprint( errorsdump( $sync->{nb_errors}, errors_log( $sync ) ) ) if ( $sync->{errorsdump} ) ;
  2007. tests_live_result( $sync->{nb_errors} ) if ( $sync->{testslive} or $sync->{testslive6} ) ;
  2008. if ( $sync->{nb_errors} )
  2009. {
  2010. exit_clean( $sync, $EXIT_WITH_ERRORS ) ;
  2011. }
  2012. else
  2013. {
  2014. exit_clean( $sync, $EX_OK ) ;
  2015. }
  2016. return ;
  2017. }
  2018. # END of sub single_sync
  2019. # subroutines
  2020. sub myprint
  2021. {
  2022. #print @ARG ;
  2023. print { $sync->{ tee } || \*STDOUT } @ARG ;
  2024. return ;
  2025. }
  2026. sub myprintf
  2027. {
  2028. printf { $sync->{ tee } || \*STDOUT } @ARG ;
  2029. return ;
  2030. }
  2031. sub mysprintf
  2032. {
  2033. my( $format, @list ) = @ARG ;
  2034. return sprintf $format, @list ;
  2035. }
  2036. sub output_start
  2037. {
  2038. my $mysync = shift @ARG ;
  2039. if ( not $mysync ) { return ; }
  2040. my @output = @ARG ;
  2041. $mysync->{ output } = join( q{}, @output ) . ( $mysync->{ output } || q{} ) ;
  2042. return $mysync->{ output } ;
  2043. }
  2044. sub tests_output_start
  2045. {
  2046. note( 'Entering tests_output_start()' ) ;
  2047. my $mysync = { } ;
  2048. is( undef, output_start( ), 'output_start: no args => undef' ) ;
  2049. is( q{}, output_start( $mysync ), 'output_start: one arg => ""' ) ;
  2050. is( 'rrrr', output_start( $mysync, 'rrrr' ), 'output_start: rrrr => rrrr' ) ;
  2051. is( 'aaaarrrr', output_start( $mysync, 'aaaa' ), 'output_start: aaaa => aaaarrrr' ) ;
  2052. is( "\naaaarrrr", output_start( $mysync, "\n" ), 'output_start: \n => \naaaarrrr' ) ;
  2053. is( "ABC\naaaarrrr", output_start( $mysync, 'A', 'B', 'C' ), 'output_start: A B C => ABC\naaaarrrr' ) ;
  2054. note( 'Leaving tests_output_start()' ) ;
  2055. return ;
  2056. }
  2057. sub tests_output
  2058. {
  2059. note( 'Entering tests_output()' ) ;
  2060. my $mysync = { } ;
  2061. is( undef, output( ), 'output: no args => undef' ) ;
  2062. is( q{}, output( $mysync ), 'output: one arg => ""' ) ;
  2063. is( 'rrrr', output( $mysync, 'rrrr' ), 'output: rrrr => rrrr' ) ;
  2064. is( 'rrrraaaa', output( $mysync, 'aaaa' ), 'output: aaaa => rrrraaaa' ) ;
  2065. is( "rrrraaaa\n", output( $mysync, "\n" ), 'output: \n => rrrraaaa\n' ) ;
  2066. is( "rrrraaaa\nABC", output( $mysync, 'A', 'B', 'C' ), 'output: A B C => rrrraaaaABC\n' ) ;
  2067. note( 'Leaving tests_output()' ) ;
  2068. return ;
  2069. }
  2070. sub output
  2071. {
  2072. my $mysync = shift @ARG ;
  2073. if ( not $mysync ) { return ; }
  2074. my @output = @ARG ;
  2075. $mysync->{ output } .= join( q{}, @output ) ;
  2076. return $mysync->{ output } ;
  2077. }
  2078. sub tests_output_reset_with
  2079. {
  2080. note( 'Entering tests_output_reset_with()' ) ;
  2081. my $mysync = { } ;
  2082. is( undef, output_reset_with( ), 'output_reset_with: no args => undef' ) ;
  2083. is( q{}, output_reset_with( $mysync ), 'output_reset_with: one arg => ""' ) ;
  2084. is( 'rrrr', output_reset_with( $mysync, 'rrrr' ), 'output_reset_with: rrrr => rrrr' ) ;
  2085. is( 'aaaa', output_reset_with( $mysync, 'aaaa' ), 'output_reset_with: aaaa => aaaa' ) ;
  2086. is( "\n", output_reset_with( $mysync, "\n" ), 'output_reset_with: \n => \n' ) ;
  2087. note( 'Leaving tests_output_reset_with()' ) ;
  2088. return ;
  2089. }
  2090. sub output_reset_with
  2091. {
  2092. my $mysync = shift @ARG ;
  2093. if ( not $mysync ) { return ; }
  2094. my @output = @ARG ;
  2095. $mysync->{ output } = join( q{}, @output ) ;
  2096. return $mysync->{ output } ;
  2097. }
  2098. sub pidfile
  2099. {
  2100. my $mysync = shift ;
  2101. $mysync->{ pidfilelocking } = defined $mysync->{ pidfilelocking } ? $mysync->{ pidfilelocking } : 0 ;
  2102. my $host1 = $mysync->{ host1 } || q{} ;
  2103. my $user1 = $mysync->{ user1 } || q{} ;
  2104. my $host2 = $mysync->{ host2 } || q{} ;
  2105. my $user2 = $mysync->{ user2 } || q{} ;
  2106. my $account1_filtered = filter_forbidden_characters( slash_to_underscore( $host1 . '_' . $user1 ) ) || q{} ;
  2107. my $account2_filtered = filter_forbidden_characters( slash_to_underscore( $host2 . '_' . $user2 ) ) || q{} ;
  2108. my $pidfile_basename ;
  2109. if ( $ENV{ 'NET_SERVER_SOFTWARE' } and ( $ENV{ 'NET_SERVER_SOFTWARE' } =~ /Net::Server::HTTP/ ) )
  2110. {
  2111. # under local webserver
  2112. $pidfile_basename = 'imapsync' . '_' . $account1_filtered . '_' . $account2_filtered . '.pid' ;
  2113. }
  2114. else
  2115. {
  2116. $pidfile_basename = 'imapsync.pid' ;
  2117. }
  2118. $mysync->{ pidfile } = defined $mysync->{ pidfile } ? $mysync-> { pidfile } : $mysync->{ tmpdir } . "/$pidfile_basename" ;
  2119. return ;
  2120. }
  2121. sub tests_kill_zero
  2122. {
  2123. note( 'Entering tests_kill_zero()' ) ;
  2124. SKIP: {
  2125. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests tests_kill_zero avoided on Windows', 8 ) ; }
  2126. is( 1, kill( 'ZERO', $PROCESS_ID ), "kill ZERO : myself $PROCESS_ID => 1" ) ;
  2127. is( 2, kill( 'ZERO', $PROCESS_ID, $PROCESS_ID ), "kill ZERO : myself $PROCESS_ID $PROCESS_ID => 2" ) ;
  2128. if ( (-e '/.dockerenv' ) or ( 0 == $EFFECTIVE_USER_ID) )
  2129. {
  2130. is( 1, kill( 'ZERO', 1 ), "kill ZERO : pid 1 => 1 (docker context or root)" ) ;
  2131. is( 2, kill( 'ZERO', $PROCESS_ID, 1 ), "kill ZERO : myself + pid 1, $PROCESS_ID 1 => 2 (docker context or root)" ) ;
  2132. }
  2133. else
  2134. {
  2135. is( 0, kill( 'ZERO', 1 ), "kill ZERO : pid 1 => 0 (non root)" ) ;
  2136. is( 1, kill( 'ZERO', $PROCESS_ID, 1 ), "kill ZERO : myself + pid 1, $PROCESS_ID 1 => 1 (one is non root)" ) ;
  2137. }
  2138. my $pid_1 = fork( ) ;
  2139. if ( $pid_1 )
  2140. {
  2141. # parent
  2142. }
  2143. else
  2144. {
  2145. # child
  2146. sleep 3 ;
  2147. exit ;
  2148. }
  2149. my $pid_2 ;
  2150. $pid_2 = fork( ) ;
  2151. if ( $pid_2 )
  2152. {
  2153. # I am the parent
  2154. ok( defined( $pid_2 ), "kill_zero: initial fork ok. I am the parent $PROCESS_ID" ) ;
  2155. ok( $pid_2 , "kill_zero: initial fork ok, child pid is $pid_2" ) ;
  2156. is( 3, kill( 'ZERO', $PROCESS_ID, $pid_2, $pid_1 ), "kill ZERO : myself $PROCESS_ID and child $pid_2 and brother $pid_1 => 3" ) ;
  2157. is( $pid_2, waitpid( $pid_2, 0 ), "kill_zero: child $pid_2 no more there => waitpid return $pid_2" ) ;
  2158. }
  2159. else
  2160. {
  2161. # I am the child
  2162. note( 'This one fails under Windows, kill ZERO returns 0 instead of 2' ) ;
  2163. is( 2, kill( 'ZERO', $PROCESS_ID, $pid_1 ), "kill ZERO : myself child $PROCESS_ID brother $pid_1 => 2" ) ;
  2164. myprint( "I am the child pid $PROCESS_ID, Exiting\n" ) ;
  2165. exit ;
  2166. }
  2167. wait( ) ;
  2168. # End of SKIP block
  2169. }
  2170. note( 'Leaving tests_kill_zero()' ) ;
  2171. return ;
  2172. }
  2173. sub tests_killpid_by_parent
  2174. {
  2175. note( 'Entering tests_killpid_by_parent()' ) ;
  2176. SKIP: {
  2177. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests tests_killpid_by_parent avoided on Windows', 7 ) ; }
  2178. is( undef, killpid( ), 'killpid: no args => undef' ) ;
  2179. note( "killpid: trying to kill myself pid $PROCESS_ID, hope I will not succeed" ) ;
  2180. is( undef, killpid( $PROCESS_ID ), 'killpid: myself => undef' ) ;
  2181. local $SIG{'QUIT'} = sub { myprint "GOT SIG QUIT! I am PID $PROCESS_ID. Exiting\n" ; exit ; } ;
  2182. my $pid ;
  2183. $pid = fork( ) ;
  2184. if ( $pid )
  2185. {
  2186. # I am the parent
  2187. ok( defined( $pid ), "killpid: initial fork ok. I am the parent $PROCESS_ID" ) ;
  2188. ok( $pid , "killpid: initial fork ok, child pid is $pid" ) ;
  2189. is( 2, kill( 'ZERO', $PROCESS_ID, $pid ), "kill ZERO : myself $PROCESS_ID and child $pid => 2" ) ;
  2190. is( 1, killpid( $pid ), "killpid: child $pid killed => 1" ) ;
  2191. is( -1, waitpid( $pid, 0 ), "killpid: child $pid no more there => waitpid return -1" ) ;
  2192. }
  2193. else
  2194. {
  2195. # I am the child
  2196. myprint( "I am the child pid $PROCESS_ID, sleeping 1 + 3 seconds then kill myself\n" ) ;
  2197. sleep 1 ;
  2198. myprint( "I am the child pid $PROCESS_ID, slept 1 second, should be killed by my parent now, PPID " . mygetppid( ) . "\n" ) ;
  2199. sleep 3 ;
  2200. # this test should not be run. If it happens => failure.
  2201. ok( 0 == 1, "killpid: child pid $PROCESS_ID not dead => failure" ) ;
  2202. myprint( "I am the child pid $PROCESS_ID, killing myself failure... Exiting\n" ) ;
  2203. exit ;
  2204. }
  2205. # End of SKIP block
  2206. }
  2207. note( 'Leaving tests_killpid_by_parent()' ) ;
  2208. return ;
  2209. }
  2210. sub tests_killpid_by_brother
  2211. {
  2212. note( 'Entering tests_killpid_by_brother()' ) ;
  2213. SKIP: {
  2214. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests tests_killpid_by_brother avoided on Windows', 2 ) ; }
  2215. local $SIG{'QUIT'} = sub { myprint "GOT SIG QUIT! I am PID $PROCESS_ID. Exiting\n" ; exit ; } ;
  2216. my $pid_parent = $PROCESS_ID ;
  2217. myprint( "I am the parent pid $pid_parent\n" ) ;
  2218. my $pid_1 = fork( ) ;
  2219. if ( $pid_1 )
  2220. {
  2221. # parent
  2222. }
  2223. else
  2224. {
  2225. # child
  2226. #while ( 1 ) { } ;
  2227. sleep 2 ;
  2228. sleep 2 ;
  2229. # this test should not be run. If it happens => failure.
  2230. # Well under Windows this always fails, shit!
  2231. ok( 0 == 1 or ( 'MSWin32' eq $OSNAME ) , "killpid: child pid $PROCESS_ID killing by brother but not dead => failure" ) ;
  2232. myprint( "I am the child pid $PROCESS_ID, killing by brother failed... Exiting\n" ) ;
  2233. exit ;
  2234. }
  2235. my $pid_2 ;
  2236. $pid_2 = fork( ) ;
  2237. if ( $pid_2 )
  2238. {
  2239. # parent
  2240. }
  2241. else
  2242. {
  2243. # I am the child
  2244. myprint( "I am the child pid $PROCESS_ID, my brother has pid $pid_1\n" ) ;
  2245. is( 1, killpid( $pid_1 ), "killpid: brother $pid_1 killed => 1" ) ;
  2246. sleep 2 ;
  2247. exit ;
  2248. }
  2249. #sleep 1 ;
  2250. is( $pid_1, waitpid( $pid_1, 0), "I am the parent $PROCESS_ID waitpid _1( $pid_1 )" ) ;
  2251. is( $pid_2, waitpid( $pid_2, 0 ), "I am the parent $PROCESS_ID waitpid _2( $pid_2 )" ) ;
  2252. # End of SKIP block
  2253. }
  2254. note( 'Leaving tests_killpid_by_brother()' ) ;
  2255. return ;
  2256. }
  2257. sub killpid
  2258. {
  2259. my $pidtokill = shift ;
  2260. if ( ! $pidtokill ) {
  2261. myprint( "No process to abort.\n" ) ;
  2262. return ;
  2263. }
  2264. if ( $PROCESS_ID == $pidtokill ) {
  2265. myprint( "I will not kill myself pid $PROCESS_ID via killpid. Sractch it!\n" ) ;
  2266. return ;
  2267. }
  2268. # First ask for suicide
  2269. if ( kill( 'ZERO', $pidtokill ) or ( 'MSWin32' eq $OSNAME ) ) {
  2270. myprint( "Sending signal QUIT to PID $pidtokill \n" ) ;
  2271. kill 'QUIT', $pidtokill ;
  2272. sleep 2 ;
  2273. waitpid( $pidtokill, WNOHANG) ;
  2274. }else{
  2275. myprint( "Can not send signal kill ZERO to PID $pidtokill.\n" ) ;
  2276. return ;
  2277. }
  2278. #while ( waitpid( $pidtokill, WNOHANG) > 0 ) { } ;
  2279. # Then murder
  2280. if ( kill( 'ZERO', $pidtokill ) or ( 'MSWin32' eq $OSNAME ) ) {
  2281. myprint( "Sending signal KILL to PID $pidtokill \n" ) ;
  2282. kill 'KILL', $pidtokill ;
  2283. sleep 1 ;
  2284. waitpid( $pidtokill, WNOHANG) ;
  2285. }else{
  2286. myprint( "Process PID $pidtokill ended.\n" ) ;
  2287. return 1;
  2288. }
  2289. # Well ...
  2290. if ( kill( 'ZERO', $pidtokill ) or ( 'xMSWin32' eq $OSNAME ) ) {
  2291. myprint( "Process PID $pidtokill seems still there. Can not do much.\n" ) ;
  2292. return ;
  2293. }else{
  2294. myprint( "Process PID $pidtokill ended.\n" ) ;
  2295. return 1;
  2296. }
  2297. return ;
  2298. }
  2299. sub tests_abort
  2300. {
  2301. note( 'Entering tests_abort()' ) ;
  2302. is( undef, abort( ), 'abort: no args => undef' ) ;
  2303. note( 'Leaving tests_abort()' ) ;
  2304. return ;
  2305. }
  2306. sub abort
  2307. {
  2308. my $mysync = shift @ARG ;
  2309. if ( not $mysync ) { return ; }
  2310. if ( ! -r $mysync->{pidfile} ) {
  2311. myprint( "Can not read pidfile $mysync->{pidfile}. Exiting.\n" ) ;
  2312. exit $EX_OK ;
  2313. }
  2314. my $pidtokill = firstline( $mysync->{pidfile} ) ;
  2315. if ( ! $pidtokill ) {
  2316. myprint( "No process to abort. Exiting.\n" ) ;
  2317. exit $EX_OK ;
  2318. }
  2319. killpid( $pidtokill ) ;
  2320. # well, the abort job is done anyway, because even when not succeeded
  2321. # in aborting another run, this run has to end without doing any
  2322. # thing else
  2323. exit $EX_OK ;
  2324. }
  2325. sub under_docker_context
  2326. {
  2327. my $mysync = shift ;
  2328. if ( -e '/.dockerenv' )
  2329. {
  2330. return 1 ;
  2331. }
  2332. else
  2333. {
  2334. return 0 ;
  2335. }
  2336. return ;
  2337. }
  2338. sub docker_context
  2339. {
  2340. my $mysync = shift ;
  2341. #-e '/.dockerenv' || return ;
  2342. if ( ! under_docker_context( $mysync ) )
  2343. {
  2344. return ;
  2345. }
  2346. $mysync->{ debug } and myprint( "Docker context detected with /.dockerenv\n" ) ;
  2347. # No pidfile
  2348. $mysync->{pidfile} = q{} ;
  2349. # No log
  2350. $mysync->{log} = 0 ;
  2351. # In case
  2352. $mysync->{ debug } and myprint( "Changing current directory to /var/tmp/\n" ) ;
  2353. chdir '/var/tmp/' ;
  2354. return ;
  2355. }
  2356. sub cgibegin
  2357. {
  2358. my $mysync = shift ;
  2359. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2360. require CGI ;
  2361. CGI->import( qw( -no_debug -utf8 ) ) ;
  2362. require CGI::Carp ;
  2363. CGI::Carp->import( qw( fatalsToBrowser ) ) ;
  2364. $mysync->{cgi} = CGI->new( ) ;
  2365. return ;
  2366. }
  2367. sub tests_under_cgi_context
  2368. {
  2369. note( 'Entering tests_under_cgi_context()' ) ;
  2370. # $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  2371. do {
  2372. # Not in cgi context
  2373. delete local $ENV{SERVER_SOFTWARE} ;
  2374. is( undef, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE unset => not in cgi context' ) ;
  2375. } ;
  2376. do {
  2377. # In cgi context
  2378. local $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  2379. is( 1, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE set => in cgi context' ) ;
  2380. } ;
  2381. do {
  2382. # Not in cgi context
  2383. delete local $ENV{SERVER_SOFTWARE} ;
  2384. is( undef, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE unset => not in cgi context' ) ;
  2385. } ;
  2386. do {
  2387. # In cgi context
  2388. local $ENV{SERVER_SOFTWARE} = 'under imapsync' ;
  2389. is( 1, under_cgi_context( ), 'under_cgi_context: SERVER_SOFTWARE set => in cgi context' ) ;
  2390. } ;
  2391. note( 'Leaving tests_under_cgi_context()' ) ;
  2392. return ;
  2393. }
  2394. sub under_cgi_context
  2395. {
  2396. my $mysync = shift ;
  2397. # Under cgi context
  2398. if ( $ENV{SERVER_SOFTWARE} ) {
  2399. return 1 ;
  2400. }
  2401. # Not in cgi context
  2402. return ;
  2403. }
  2404. sub cgibuildheader
  2405. {
  2406. my $mysync = shift ;
  2407. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2408. my $imapsync_runs = $mysync->{cgi}->cookie( 'imapsync_runs' ) || 0 ;
  2409. my $cookie = $mysync->{cgi}->cookie(
  2410. -name => 'imapsync_runs',
  2411. -value => 1 + $imapsync_runs,
  2412. -expires => '+20y',
  2413. -path => '/cgi-bin/imapsync',
  2414. ) ;
  2415. my $httpheader ;
  2416. if ( $mysync->{ abort } ) {
  2417. $httpheader = $mysync->{cgi}->header(
  2418. -type => 'text/plain',
  2419. -status => '200 OK to abort syncing IMAP boxes' . ". Here is " . hostname(),
  2420. ) ;
  2421. }elsif( $mysync->{ loaddelay } ) {
  2422. # https://tools.ietf.org/html/rfc2616#section-10.5.4
  2423. # 503 Service Unavailable
  2424. # The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
  2425. $httpheader = $mysync->{cgi}->header(
  2426. -type => 'text/plain',
  2427. -status => '503 Service Unavailable' . ". Be back in $mysync->{ loaddelay } min. Load on " . hostname() . " is $mysync->{ loadavg }",
  2428. ) ;
  2429. }else{
  2430. $httpheader = $mysync->{cgi}->header(
  2431. -type => 'text/plain; charset=UTF-8',
  2432. -status => '200 OK to sync IMAP boxes' . ". Load on " . hostname() . " is $mysync->{ loadavg }",
  2433. -cookie => $cookie,
  2434. ) ;
  2435. }
  2436. output_start( $mysync, $httpheader ) ;
  2437. return ;
  2438. }
  2439. sub cgiload
  2440. {
  2441. # Exit on heavy load in CGI context
  2442. my $mysync = shift ;
  2443. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2444. if ( $mysync->{ abort } ) { return ; } # keep going to abort since some ressources will be free soon
  2445. if ( $mysync->{ loaddelay } )
  2446. {
  2447. $mysync->{nb_errors}++ ;
  2448. exit_clean( $mysync, $EX_UNAVAILABLE,
  2449. "Server is on heavy load. Be back in $mysync->{ loaddelay } min. Load is $mysync->{ loadavg }\n"
  2450. ) ;
  2451. }
  2452. return ;
  2453. }
  2454. sub tests_set_umask
  2455. {
  2456. note( 'Entering tests_set_umask()' ) ;
  2457. my $save_umask = umask ;
  2458. my $mysync = {} ;
  2459. if ( 'MSWin32' eq $OSNAME ) {
  2460. is( undef, set_umask( $mysync ), "set_umask: set failure to $UMASK_PARANO on MSWin32" ) ;
  2461. }else{
  2462. is( 1, set_umask( $mysync ), "set_umask: set to $UMASK_PARANO" ) ;
  2463. }
  2464. umask $save_umask ;
  2465. note( 'Leaving tests_set_umask()' ) ;
  2466. return ;
  2467. }
  2468. sub set_umask
  2469. {
  2470. my $mysync = shift ;
  2471. my $previous_umask = umask_str( ) ;
  2472. my $new_umask = umask_str( $UMASK_PARANO ) ;
  2473. output( $mysync, "Umask set with $new_umask (was $previous_umask)\n" ) ;
  2474. if ( $new_umask eq $UMASK_PARANO ) {
  2475. return 1 ;
  2476. }
  2477. return ;
  2478. }
  2479. sub tests_umask_str
  2480. {
  2481. note( 'Entering tests_umask_str()' ) ;
  2482. my $save_umask = umask ;
  2483. is( umask_str( ), umask_str( ), 'umask_str: no parameters => idopotent' ) ;
  2484. is( my $save_umask_str = umask_str( ), umask_str( ), 'umask_str: no parameters => idopotent + save' ) ;
  2485. is( '0000', umask_str( q{ } ), 'umask_str: q{ } => 0000' ) ;
  2486. is( '0000', umask_str( q{} ), 'umask_str: q{} => 0000' ) ;
  2487. is( '0000', umask_str( '0000' ), 'umask_str: 0000 => 0000' ) ;
  2488. is( '0000', umask_str( '0' ), 'umask_str: 0 => 0000' ) ;
  2489. is( '0200', umask_str( '0200' ), 'umask_str: 0200 => 0200' ) ;
  2490. is( '0400', umask_str( '0400' ), 'umask_str: 0400 => 0400' ) ;
  2491. is( '0600', umask_str( '0600' ), 'umask_str: 0600 => 0600' ) ;
  2492. SKIP: {
  2493. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests success only for Unix', 6 ) ; }
  2494. is( '0100', umask_str( '0100' ), 'umask_str: 0100 => 0100' ) ;
  2495. is( '0001', umask_str( '0001' ), 'umask_str: 0001 => 0001' ) ;
  2496. is( '0777', umask_str( '0777' ), 'umask_str: 0777 => 0777' ) ;
  2497. is( '0777', umask_str( '00777' ), 'umask_str: 00777 => 0777' ) ;
  2498. is( '0777', umask_str( ' 777 ' ), 'umask_str: 777 => 0777' ) ;
  2499. is( "$UMASK_PARANO", umask_str( $UMASK_PARANO ), "umask_str: UMASK_PARANO $UMASK_PARANO => $UMASK_PARANO" ) ;
  2500. }
  2501. is( $save_umask_str, umask_str( $save_umask_str ), 'umask_str: restore with str' ) ;
  2502. is( $save_umask, umask, 'umask_str: umask is restored, controlled by direct umask' ) ;
  2503. is( $save_umask, umask $save_umask, 'umask_str: umask is restored by direct umask' ) ;
  2504. is( $save_umask, umask, 'umask_str: umask initial controlled by direct umask' ) ;
  2505. note( 'Leaving tests_umask_str()' ) ;
  2506. return ;
  2507. }
  2508. sub umask_str
  2509. {
  2510. my $value = shift ;
  2511. if ( defined $value ) {
  2512. umask oct( $value ) ;
  2513. }
  2514. my $current = umask ;
  2515. return( sprintf( '%#04o', $current ) ) ;
  2516. }
  2517. sub tests_umask
  2518. {
  2519. note( 'Entering tests_umask()' ) ;
  2520. my $save_umask ;
  2521. is( umask, umask, 'umask: umask is umask' ) ;
  2522. is( $save_umask = umask, umask, "umask: umask is umask again + save it: $save_umask" ) ;
  2523. is( $save_umask, umask oct(0000), 'umask: umask 0000' ) ;
  2524. is( oct(0000), umask, 'umask: umask is now 0000' ) ;
  2525. is( oct(0000), umask oct(777), 'umask: umask 0777 call, previous 0000' ) ;
  2526. SKIP: {
  2527. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests success only for Unix', 2 ) ; }
  2528. is( oct(777), umask, 'umask: umask is now 0777' ) ;
  2529. is( oct(777), umask $save_umask, "umask: umask $save_umask restore inital value, previous 0777" ) ;
  2530. }
  2531. ok( defined umask $save_umask, "umask: umask $save_umask restore inital value, previous defined" ) ;
  2532. is( $save_umask, umask, 'umask: umask is umask restored' ) ;
  2533. note( 'Leaving tests_umask()' ) ;
  2534. return ;
  2535. }
  2536. sub cgisetcontext
  2537. {
  2538. my $mysync = shift ;
  2539. if ( ! under_cgi_context( $mysync ) ) { return ; }
  2540. output( $mysync, "Under cgi context\n" ) ;
  2541. set_umask( $mysync ) ;
  2542. # Remove all content in unsafe evaled options
  2543. @{ $mysync->{ regextrans2 } } = ( ) ;
  2544. @regexflag = ( ) ;
  2545. @regexmess = ( ) ;
  2546. @skipmess = ( ) ;
  2547. @pipemess = ( ) ;
  2548. $delete2foldersonly = undef ;
  2549. $delete2foldersbutnot = undef ;
  2550. $maxlinelengthcmd = undef ;
  2551. # Set safe default values (I hope...)
  2552. #$mysync->{pidfile} = 'imapsync.pid' ;
  2553. $mysync->{pidfilelocking} = 1 ;
  2554. $mysync->{errorsmax} = $ERRORS_MAX_CGI ;
  2555. $modulesversion = 0 ;
  2556. $mysync->{releasecheck} = defined $mysync->{releasecheck} ? $mysync->{releasecheck} : 1 ;
  2557. $usecache = 0 ;
  2558. $mysync->{showpasswords} = 0 ;
  2559. $debugimap1 = $debugimap2 = $debugimap = 0 ;
  2560. $reconnectretry1 = $reconnectretry2 = $DEFAULT_NB_RECONNECT_PER_IMAP_COMMAND ;
  2561. $pipemesscheck = 0 ;
  2562. $mysync->{hashfile} = $CGI_HASHFILE ;
  2563. my $hashsynclocal = hashsynclocal( $mysync ) || die "Can not get hashsynclocal. Exiting\n" ;
  2564. if ( $ENV{ 'NET_SERVER_SOFTWARE' } and ( $ENV{ 'NET_SERVER_SOFTWARE' } =~ /Net::Server::HTTP/ ) )
  2565. {
  2566. # under local webserver
  2567. $cgidir = q{.} ;
  2568. }
  2569. else
  2570. {
  2571. $cgidir = $CGI_TMPDIR_TOP . '/' . $hashsynclocal ;
  2572. }
  2573. -d $cgidir or mkpath $cgidir or die "Can not create $cgidir: $OS_ERROR\n" ;
  2574. $mysync->{ tmpdir } = $cgidir ;
  2575. chdir $cgidir or die "Can not cd to $cgidir: $OS_ERROR\n" ;
  2576. cgioutputenvcontext( $mysync ) ;
  2577. $mysync->{ debug } and output( $mysync, 'Current directory is ' . getcwd( ) . "\n" ) ;
  2578. $mysync->{ debug } and output( $mysync, 'Real user id is ' . getpwuid_any_os( $REAL_USER_ID ) . " (uid $REAL_USER_ID)\n" ) ;
  2579. $mysync->{ debug } and output( $mysync, 'Effective user id is ' . getpwuid_any_os( $EFFECTIVE_USER_ID ). " (euid $EFFECTIVE_USER_ID)\n" ) ;
  2580. $mysync->{ skipemptyfolders } = defined $mysync->{ skipemptyfolders } ? $mysync->{ skipemptyfolders } : 1 ;
  2581. # Out of memory with messages over 1 GB ?
  2582. $mysync->{ maxsize } = defined $mysync->{ maxsize } ? $mysync->{ maxsize } : 1_000_000_000 ;
  2583. # tail -f behaviour on by default
  2584. $mysync->{ tail } = defined $mysync->{ tail } ? $mysync->{ tail } : 1 ;
  2585. # not sure it's for good
  2586. @useheader = qw( Message-Id ) ;
  2587. # addheader on by default
  2588. $mysync->{ addheader } = defined $mysync->{ addheader } ? $mysync->{ addheader } : 1 ;
  2589. return ;
  2590. }
  2591. sub cgioutputenvcontext
  2592. {
  2593. my $mysync = shift @ARG ;
  2594. for my $envvar ( qw( REMOTE_ADDR REMOTE_HOST HTTP_REFERER HTTP_USER_AGENT SERVER_SOFTWARE SERVER_PORT HTTP_COOKIE ) ) {
  2595. my $envval = $ENV{ $envvar } || q{} ;
  2596. if ( $envval ) { output( $mysync, "$envvar is $envval\n" ) } ;
  2597. }
  2598. return ;
  2599. }
  2600. sub debugsleep
  2601. {
  2602. my $mysync = shift @ARG ;
  2603. if ( defined $mysync->{debugsleep} ) {
  2604. myprint( "Info: sleeping $mysync->{debugsleep}s\n" ) ;
  2605. sleep $mysync->{debugsleep} ;
  2606. }
  2607. return ;
  2608. }
  2609. sub tests_foldersize
  2610. {
  2611. note( 'Entering tests_foldersize()' ) ;
  2612. is( undef, foldersize( ), 'foldersize: no args => undef' ) ;
  2613. #is_deeply( {}, {}, 'foldersize: a hash is a hash' ) ;
  2614. #is_deeply( [], [], 'foldersize: an array is an array' ) ;
  2615. note( 'Leaving tests_foldersize()' ) ;
  2616. return ;
  2617. }
  2618. # Globals:
  2619. # $uidnext_default
  2620. # $fetch_hash_set
  2621. #
  2622. sub foldersize
  2623. {
  2624. # size of one folder
  2625. my ( $mysync, $side, $imap, $search_cmd, $abletosearch, $folder ) = @ARG ;
  2626. if ( ! all_defined( $mysync, $side, $imap, $folder ) )
  2627. {
  2628. return ;
  2629. }
  2630. # FTGate is RFC buggy with EXAMINE it does not act as SELECT
  2631. #if ( ! $imap->examine( $folder ) ) {
  2632. if ( ! $imap->select( $folder ) ) {
  2633. my $error = join q{},
  2634. "$side Folder $folder: Could not select: ",
  2635. $imap->LastError, "\n" ;
  2636. errors_incr( $mysync, $error ) ;
  2637. return ;
  2638. }
  2639. if ( $imap->IsUnconnected( ) )
  2640. {
  2641. return ;
  2642. }
  2643. my $hash_ref = { } ;
  2644. my @msgs = select_msgs( $imap, undef, $search_cmd, $abletosearch, $folder ) ;
  2645. my $nb_msgs = scalar @msgs ;
  2646. my $biggest_in_folder = 0 ;
  2647. @{ $hash_ref }{ @msgs } = ( undef ) if @msgs ;
  2648. my $stot = 0 ;
  2649. if ( $imap->IsUnconnected( ) )
  2650. {
  2651. return ;
  2652. }
  2653. if ( $nb_msgs > 0 and @msgs ) {
  2654. if ( $abletosearch ) {
  2655. if ( ! $imap->fetch_hash( \@msgs, 'RFC822.SIZE', $hash_ref) ) {
  2656. my $error = "$side failure with fetch_hash: $EVAL_ERROR\n" ;
  2657. errors_incr( $mysync, $error ) ;
  2658. return ;
  2659. }
  2660. }
  2661. else
  2662. {
  2663. my $uidnext = $imap->uidnext( $folder ) || $uidnext_default ;
  2664. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  2665. if ( ! $imap->fetch_hash( $fetch_hash_uids, 'RFC822.SIZE', $hash_ref ) ) {
  2666. my $error = "$side failure with fetch_hash: $EVAL_ERROR\n" ;
  2667. errors_incr( $mysync, $error ) ;
  2668. return ;
  2669. }
  2670. }
  2671. for ( keys %{ $hash_ref } ) {
  2672. my $size = $hash_ref->{ $_ }->{ 'RFC822.SIZE' } ;
  2673. $stot += $size ;
  2674. $biggest_in_folder = max( $biggest_in_folder, $size ) ;
  2675. }
  2676. }
  2677. return( $stot, $nb_msgs, $biggest_in_folder ) ;
  2678. }
  2679. # The old subroutine that performed just one side at a time.
  2680. # Still here for a while, until confident with sub foldersize_diff_compute()
  2681. sub foldersizes
  2682. {
  2683. my ( $mysync, $side, $imap, $search_cmd, $abletosearch, @folders ) = @_ ;
  2684. my $total_size = 0 ;
  2685. my $total_nb = 0 ;
  2686. my $biggest_in_all = 0 ;
  2687. my $nb_folders = scalar @folders ;
  2688. my $ct_folders = 0 ; # folder counter.
  2689. myprint( "++++ Calculating sizes of $nb_folders folders on $side\n" ) ;
  2690. foreach my $folder ( @folders ) {
  2691. my $stot = 0 ;
  2692. my $nb_msgs = 0 ;
  2693. my $biggest_in_folder = 0 ;
  2694. $ct_folders++ ;
  2695. myprintf( "$side folder %7s %-35s", "$ct_folders/$nb_folders", jux_utf8( $folder ) ) ;
  2696. if ( 'Host2' eq $side and not exists $mysync->{h2_folders_all_UPPER}{ uc $folder } ) {
  2697. myprint( " does not exist yet\n") ;
  2698. next ;
  2699. }
  2700. if ( 'Host1' eq $side and not exists $h1_folders_all{ $folder } ) {
  2701. myprint( " does not exist\n" ) ;
  2702. next ;
  2703. }
  2704. last if $imap->IsUnconnected( ) ;
  2705. ( $stot, $nb_msgs, $biggest_in_folder ) = foldersize( $mysync, $side, $imap, $search_cmd, $abletosearch, $folder ) ;
  2706. myprintf( ' Size: %9s', $stot ) ;
  2707. myprintf( ' Messages: %5s', $nb_msgs ) ;
  2708. myprintf( " Biggest: %9s\n", $biggest_in_folder ) ;
  2709. $total_size += $stot ;
  2710. $total_nb += $nb_msgs ;
  2711. $biggest_in_all = max( $biggest_in_all, $biggest_in_folder ) ;
  2712. }
  2713. myprintf( "%s Nb folders: %11s folders\n", $side, $nb_folders ) ;
  2714. myprintf( "%s Nb messages: %11s messages\n", $side, $total_nb ) ;
  2715. myprintf( "%s Total size: %11s bytes (%s)\n", $side, $total_size, bytes_display_string( $total_size ) ) ;
  2716. myprintf( "%s Biggest message: %11s bytes (%s)\n", $side, $biggest_in_all, bytes_display_string( $biggest_in_all ) ) ;
  2717. myprintf( "%s Time spent on sizing: %11.1f seconds\n", $side, timenext( $mysync ) ) ;
  2718. return( $total_nb, $total_size ) ;
  2719. }
  2720. sub foldersize_diff_present
  2721. {
  2722. my $mysync = shift ;
  2723. my $folder1 = shift ;
  2724. my $folder2 = shift ;
  2725. my $counter_str = shift ;
  2726. my $force = shift ;
  2727. my $values1_str ;
  2728. my $values2_str ;
  2729. if ( ! defined $mysync->{ folder1 }->{ $folder1 }->{ size } || $force )
  2730. {
  2731. foldersize_diff_compute( $mysync, $folder1, $folder2, $force ) ;
  2732. }
  2733. # again, but this time it means no availaible data.
  2734. if ( defined $mysync->{ folder1 }->{ $folder1 }->{ size } )
  2735. {
  2736. $values1_str = sprintf( "Size: %9s Messages: %5s Biggest: %9s\n",
  2737. $mysync->{ folder1 }->{ $folder1 }->{ size },
  2738. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs },
  2739. $mysync->{ folder1 }->{ $folder1 }->{ biggest },
  2740. ) ;
  2741. }
  2742. else
  2743. {
  2744. $values1_str = " does not exist\n" ;
  2745. }
  2746. if ( defined $mysync->{ folder2 }->{ $folder2 }->{ size } )
  2747. {
  2748. $values2_str = sprintf( "Size: %9s Messages: %5s Biggest: %9s\n",
  2749. $mysync->{ folder2 }->{ $folder2 }->{ size },
  2750. $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs },
  2751. $mysync->{ folder2 }->{ $folder2 }->{ biggest },
  2752. ) ;
  2753. }
  2754. else
  2755. {
  2756. $values2_str = " does not exist yet\n" ;
  2757. }
  2758. myprintf( "Host1 folder %7s %-35s %s",
  2759. "$counter_str",
  2760. jux_utf8( $folder1 ),
  2761. $values1_str
  2762. ) ;
  2763. myprintf( "Host2 folder %7s %-35s %s",
  2764. "$counter_str",
  2765. jux_utf8( $folder2 ),
  2766. $values2_str
  2767. ) ;
  2768. myprintf( "Host2-Host1 %7s %-35s %9s %5s %9s\n\n",
  2769. "",
  2770. "",
  2771. $mysync->{ folder1 }->{ $folder1 }->{ size_diff },
  2772. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs_diff },
  2773. $mysync->{ folder1 }->{ $folder1 }->{ biggest_diff },
  2774. ) ;
  2775. return ;
  2776. }
  2777. sub foldersize_diff_compute
  2778. {
  2779. my $mysync = shift ;
  2780. my $folder1 = shift ;
  2781. my $folder2 = shift ;
  2782. my $force = shift ;
  2783. my ( $size_1, $nb_msgs_1, $biggest_1 ) ;
  2784. # memoization
  2785. if (
  2786. exists $h1_folders_all{ $folder1 }
  2787. &&
  2788. (
  2789. ! defined $mysync->{ folder1 }->{ $folder1 }->{ size }
  2790. || $force
  2791. )
  2792. )
  2793. {
  2794. #myprint( "foldersize folder1 $h1_folders_all{ $folder1 }\n" ) ;
  2795. ( $size_1, $nb_msgs_1, $biggest_1 ) =
  2796. foldersize( $mysync,
  2797. 'Host1',
  2798. $mysync->{ imap1 },
  2799. $mysync->{ search1 },
  2800. $mysync->{ abletosearch1 },
  2801. $folder1
  2802. ) ;
  2803. $mysync->{ folder1 }->{ $folder1 }->{ size } = $size_1 ;
  2804. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs } = $nb_msgs_1 ;
  2805. $mysync->{ folder1 }->{ $folder1 }->{ biggest } = $biggest_1 ;
  2806. }
  2807. else
  2808. {
  2809. $size_1 = $mysync->{ folder1 }->{ $folder1 }->{ size } ;
  2810. $nb_msgs_1 = $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs } ;
  2811. $biggest_1 = $mysync->{ folder1 }->{ $folder1 }->{ biggest } ;
  2812. }
  2813. my ( $size_2, $nb_msgs_2, $biggest_2 ) ;
  2814. if (
  2815. exists $mysync->{ h2_folders_all_UPPER }{ uc $folder2 }
  2816. &&
  2817. (
  2818. ! defined $mysync->{ folder2 }->{ $folder2 }->{ size }
  2819. || $force
  2820. )
  2821. )
  2822. {
  2823. #myprint( "foldersize folder2\n" ) ;
  2824. ( $size_2, $nb_msgs_2, $biggest_2 ) =
  2825. foldersize( $mysync,
  2826. 'Host2',
  2827. $mysync->{ imap2 },
  2828. $mysync->{ search2 },
  2829. $mysync->{ abletosearch2 },
  2830. $folder2
  2831. ) ;
  2832. $mysync->{ folder2 }->{ $folder2 }->{ size } = $size_2 ;
  2833. $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs } = $nb_msgs_2 ;
  2834. $mysync->{ folder2 }->{ $folder2 }->{ biggest } = $biggest_2 ;
  2835. }
  2836. else
  2837. {
  2838. $size_2 = $mysync->{ folder2 }->{ $folder2 }->{ size } ;
  2839. $nb_msgs_2 = $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs } ;
  2840. $biggest_2 = $mysync->{ folder2 }->{ $folder2 }->{ biggest } ;
  2841. }
  2842. my $size_diff = diff( $size_2, $size_1 ) ;
  2843. my $nb_msgs_diff = diff( $nb_msgs_2, $nb_msgs_1 ) ;
  2844. my $biggest_diff = diff( $biggest_2, $biggest_1 ) ;
  2845. $mysync->{ folder1 }->{ $folder1 }->{ size_diff } = $size_diff ;
  2846. $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs_diff } = $nb_msgs_diff ;
  2847. $mysync->{ folder1 }->{ $folder1 }->{ biggest_diff } = $biggest_diff ;
  2848. # It's redundant but easier to access later
  2849. $mysync->{ folder2 }->{ $folder2 }->{ size_diff } = $size_diff ;
  2850. $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs_diff } = $nb_msgs_diff ;
  2851. $mysync->{ folder2 }->{ $folder2 }->{ biggest_diff } = $biggest_diff ;
  2852. return ;
  2853. }
  2854. sub diff
  2855. {
  2856. my $x = shift ;
  2857. my $y = shift ;
  2858. $x ||= 0 ;
  2859. $y ||= 0 ;
  2860. return $x - $y ;
  2861. }
  2862. sub add
  2863. {
  2864. my $x = shift ;
  2865. my $y = shift ;
  2866. $x ||= 0 ;
  2867. $y ||= 0 ;
  2868. return $x + $y ;
  2869. }
  2870. sub foldersizes_diff_list
  2871. {
  2872. my $mysync = shift ;
  2873. my $force = shift ;
  2874. my @folders = @{ $mysync->{h1_folders_wanted} } ;
  2875. my $nb_folders = scalar @folders ;
  2876. my $ct_folders = 0 ; # folder counter.
  2877. foreach my $folder1 ( @folders )
  2878. {
  2879. $ct_folders++ ;
  2880. my $counter_str = "$ct_folders/$nb_folders" ;
  2881. my $folder2 = imap2_folder_name( $mysync, $folder1 ) ;
  2882. foldersize_diff_present( $mysync, $folder1, $folder2, $counter_str, $force ) ;
  2883. }
  2884. return ;
  2885. }
  2886. sub foldersizes_total
  2887. {
  2888. my $mysync = shift ;
  2889. my @folders_1 = @{ $mysync->{h1_folders_wanted} } ;
  2890. my @folders_2 = @h2_folders_from_1_wanted ;
  2891. my $nb_folders_1 = scalar( @folders_1 ) ;
  2892. my $nb_folders_2 = scalar( @folders_2 ) ;
  2893. my ( $total_size_1, $total_nb_1, $biggest_in_all_1 ) = ( 0, 0, 0 ) ;
  2894. my ( $total_size_2, $total_nb_2, $biggest_in_all_2 ) = ( 0, 0, 0 ) ;
  2895. foreach my $folder1 ( @folders_1 )
  2896. {
  2897. $total_size_1 = add( $total_size_1, $mysync->{ folder1 }->{ $folder1 }->{ size } ) ;
  2898. $total_nb_1 = add( $total_nb_1, $mysync->{ folder1 }->{ $folder1 }->{ nb_msgs } ) ;
  2899. $biggest_in_all_1 = max( $biggest_in_all_1 , $mysync->{ folder1 }->{ $folder1 }->{ biggest } ) ;
  2900. }
  2901. foreach my $folder2 ( @folders_2 )
  2902. {
  2903. $total_size_2 = add( $total_size_2, $mysync->{ folder2 }->{ $folder2 }->{ size } ) ;
  2904. $total_nb_2 = add( $total_nb_2, $mysync->{ folder2 }->{ $folder2 }->{ nb_msgs } ) ;
  2905. $biggest_in_all_2 = max( $biggest_in_all_2 , $mysync->{ folder2 }->{ $folder2 }->{ biggest } ) ;
  2906. }
  2907. myprintf( "Host1 Nb folders: %11s folders\n", $nb_folders_1 ) ;
  2908. myprintf( "Host2 Nb folders: %11s folders\n", $nb_folders_2 ) ;
  2909. myprint( "\n" ) ;
  2910. myprintf( "Host1 Nb messages: %11s messages\n", $total_nb_1 ) ;
  2911. myprintf( "Host2 Nb messages: %11s messages\n", $total_nb_2 ) ;
  2912. myprint( "\n" ) ;
  2913. myprintf( "Host1 Total size: %11s bytes (%s)\n", $total_size_1, bytes_display_string( $total_size_1 ) ) ;
  2914. myprintf( "Host2 Total size: %11s bytes (%s)\n", $total_size_2, bytes_display_string( $total_size_2 ) ) ;
  2915. myprint( "\n" ) ;
  2916. myprintf( "Host1 Biggest message: %11s bytes (%s)\n", $biggest_in_all_1, bytes_display_string( $biggest_in_all_1 ) ) ;
  2917. myprintf( "Host2 Biggest message: %11s bytes (%s)\n", $biggest_in_all_2, bytes_display_string( $biggest_in_all_2 ) ) ;
  2918. myprint( "\n" ) ;
  2919. myprintf( "Time spent on sizing: %11.1f seconds\n", timenext( $mysync ) ) ;
  2920. my @total_1_2 = ( $total_nb_1, $total_size_1, $total_nb_2, $total_size_2 ) ;
  2921. return @total_1_2 ;
  2922. }
  2923. sub foldersizesatend_old
  2924. {
  2925. my $mysync = shift ;
  2926. timenext( $mysync ) ;
  2927. return if ( $mysync->{imap1}->IsUnconnected( ) ) ;
  2928. return if ( $mysync->{imap2}->IsUnconnected( ) ) ;
  2929. # Get all folders on host2 again since new were created
  2930. @h2_folders_all = sort $mysync->{imap2}->folders();
  2931. for ( @h2_folders_all ) {
  2932. $h2_folders_all{ $_ } = 1 ;
  2933. $mysync->{h2_folders_all_UPPER}{ uc $_ } = 1 ;
  2934. } ;
  2935. ( $h1_nb_msg_end, $h1_bytes_end ) = foldersizes( $mysync, 'Host1', $mysync->{imap1}, $mysync->{ search1 }, $mysync->{abletosearch1}, @{ $mysync->{h1_folders_wanted} } ) ;
  2936. ( $h2_nb_msg_end, $h2_bytes_end ) = foldersizes( $mysync, 'Host2', $mysync->{imap2}, $mysync->{ search2 }, $mysync->{abletosearch2}, @h2_folders_from_1_wanted ) ;
  2937. if ( not all_defined( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end ) ) {
  2938. my $error = "Failure getting foldersizes, final differences will not be calculated\n" ;
  2939. errors_incr( $mysync, $error ) ;
  2940. }
  2941. return ;
  2942. }
  2943. sub foldersizesatend
  2944. {
  2945. my $mysync = shift ;
  2946. timenext( $mysync ) ;
  2947. return if ( $mysync->{imap1}->IsUnconnected( ) ) ;
  2948. return if ( $mysync->{imap2}->IsUnconnected( ) ) ;
  2949. # Get all folders on host2 again since new were created
  2950. @h2_folders_all = sort $mysync->{imap2}->folders();
  2951. for ( @h2_folders_all ) {
  2952. $h2_folders_all{ $_ } = 1 ;
  2953. $mysync->{h2_folders_all_UPPER}{ uc $_ } = 1 ;
  2954. } ;
  2955. foldersizes_diff_list( $mysync, $FORCE ) ;
  2956. ( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end )
  2957. = foldersizes_total( $mysync ) ;
  2958. if ( not all_defined( $h1_nb_msg_end, $h1_bytes_end, $h2_nb_msg_end, $h2_bytes_end ) ) {
  2959. my $error = "Failure getting foldersizes, final differences will not be calculated\n" ;
  2960. errors_incr( $mysync, $error ) ;
  2961. }
  2962. return ;
  2963. }
  2964. sub foldersizes_at_the_beggining
  2965. {
  2966. my $mysync = shift ;
  2967. myprint( << 'END_SIZE' ) ;
  2968. Folders sizes before the synchronization.
  2969. You can remove foldersizes listings by using "--nofoldersizes" and "--nofoldersizesatend"
  2970. but then you will also lose the ETA (Estimation Time of Arrival) given after each message copy.
  2971. END_SIZE
  2972. foldersizes_diff_list( $mysync ) ;
  2973. ( $mysync->{ h1_nb_msg_start }, $mysync->{ h1_bytes_start },
  2974. $mysync->{ h2_nb_msg_start }, $mysync->{ h2_bytes_start } )
  2975. = foldersizes_total( $mysync ) ;
  2976. if ( not all_defined(
  2977. $mysync->{ h1_nb_msg_start },
  2978. $mysync->{ h1_bytes_start },
  2979. $mysync->{ h2_nb_msg_start },
  2980. $mysync->{ h2_bytes_start } ) )
  2981. {
  2982. my $error = "Failure getting foldersizes, ETA and final diff will not be displayed\n" ;
  2983. errors_incr( $mysync, $error ) ;
  2984. $mysync->{ foldersizes } = 0 ;
  2985. $mysync->{ foldersizesatend } = 0 ;
  2986. return ;
  2987. }
  2988. my $h2_bytes_limit = $mysync->{h2}->{quota_limit_bytes} || 0 ;
  2989. if ( $h2_bytes_limit and ( $h2_bytes_limit < $mysync->{ h1_bytes_start } ) )
  2990. {
  2991. my $quota_percent = mysprintf( '%.0f', $NUMBER_100 * $mysync->{ h1_bytes_start } / $h2_bytes_limit ) ;
  2992. my $error = "Host2: Quota limit will be exceeded! Over $quota_percent % ( $mysync->{ h1_bytes_start } bytes / $h2_bytes_limit bytes )\n" ;
  2993. errors_incr( $mysync, $error ) ;
  2994. }
  2995. return ;
  2996. }
  2997. # Globals:
  2998. # @h2_folders_from_1_wanted
  2999. sub foldersizes_at_the_beggining_old
  3000. {
  3001. my $mysync = shift ;
  3002. myprint( << 'END_SIZE' ) ;
  3003. Folders sizes before the synchronization.
  3004. You can remove foldersizes listings by using "--nofoldersizes" and "--nofoldersizesatend"
  3005. but then you will also lose the ETA (Estimation Time of Arrival) given after each message copy.
  3006. END_SIZE
  3007. ( $mysync->{ h1_nb_msg_start }, $mysync->{ h1_bytes_start } ) =
  3008. foldersizes( $mysync, 'Host1', $mysync->{imap1}, $mysync->{ search1 },
  3009. $mysync->{abletosearch1}, @{ $mysync->{h1_folders_wanted} } ) ;
  3010. ( $mysync->{ h2_nb_msg_start }, $mysync->{ h2_bytes_start } ) =
  3011. foldersizes( $mysync, 'Host2', $mysync->{imap2}, $mysync->{ search2 },
  3012. $mysync->{abletosearch2}, @h2_folders_from_1_wanted ) ;
  3013. if ( not all_defined( $mysync->{ h1_nb_msg_start },
  3014. $mysync->{ h1_bytes_start }, $mysync->{ h2_nb_msg_start }, $mysync->{ h2_bytes_start } ) )
  3015. {
  3016. my $error = "Failure getting foldersizes, ETA and final diff will not be displayed\n" ;
  3017. errors_incr( $mysync, $error ) ;
  3018. $mysync->{ foldersizes } = 0 ;
  3019. $mysync->{ foldersizesatend } = 0 ;
  3020. return ;
  3021. }
  3022. my $h2_bytes_limit = $mysync->{h2}->{quota_limit_bytes} || 0 ;
  3023. if ( $h2_bytes_limit and ( $h2_bytes_limit < $mysync->{ h1_bytes_start } ) )
  3024. {
  3025. my $quota_percent = mysprintf( '%.0f', $NUMBER_100 * $mysync->{ h1_bytes_start } / $h2_bytes_limit ) ;
  3026. my $error = "Host2: Quota limit will be exceeded! Over $quota_percent % ( $mysync->{ h1_bytes_start } bytes / $h2_bytes_limit bytes )\n" ;
  3027. errors_incr( $mysync, $error ) ;
  3028. }
  3029. return ;
  3030. }
  3031. sub total_bytes_max_reached
  3032. {
  3033. my $mysync = shift ;
  3034. if ( ! $mysync->{ exitwhenover } ) {
  3035. return( 0 ) ;
  3036. }
  3037. if ( $mysync->{ total_bytes_transferred } >= $mysync->{ exitwhenover } ) {
  3038. myprint( "Maximum bytes transferred reached, $mysync->{total_bytes_transferred} >= $mysync->{ exitwhenover }, ending sync\n" ) ;
  3039. return( 1 ) ;
  3040. }
  3041. return ;
  3042. }
  3043. sub tests_mock_capability
  3044. {
  3045. note( 'Entering tests_mock_capability()' ) ;
  3046. my $myimap ;
  3047. ok( $myimap = mock_capability( ),
  3048. 'mock_capability: (1) no args => a Test::MockObject'
  3049. ) ;
  3050. ok( $myimap->isa( 'Test::MockObject' ),
  3051. 'mock_capability: (2) no args => a Test::MockObject'
  3052. ) ;
  3053. is( undef, $myimap->capability( ),
  3054. 'mock_capability: (3) no args => capability undef'
  3055. ) ;
  3056. ok( mock_capability( $myimap ),
  3057. 'mock_capability: (1) one arg => MockObject'
  3058. ) ;
  3059. is( undef, $myimap->capability( ),
  3060. 'mock_capability: (2) one arg OO style => capability undef'
  3061. ) ;
  3062. ok( mock_capability( $myimap, $NUMBER_123456 ),
  3063. 'mock_capability: (1) two args 123456 => capability 123456'
  3064. ) ;
  3065. is( $NUMBER_123456, $myimap->capability( ),
  3066. 'mock_capability: (2) two args 123456 => capability 123456'
  3067. ) ;
  3068. ok( mock_capability( $myimap, 'ABCD' ),
  3069. 'mock_capability: (1) two args ABCD => capability ABCD'
  3070. ) ;
  3071. is( 'ABCD', $myimap->capability( ),
  3072. 'mock_capability: (2) two args ABCD => capability ABCD'
  3073. ) ;
  3074. ok( mock_capability( $myimap, [ 'ABCD' ] ),
  3075. 'mock_capability: (1) two args [ ABCD ] => capability [ ABCD ]'
  3076. ) ;
  3077. is_deeply( [ 'ABCD' ], $myimap->capability( ),
  3078. 'mock_capability: (2) two args [ ABCD ] => capability [ ABCD ]'
  3079. ) ;
  3080. ok( mock_capability( $myimap, [ 'ABC', 'DEF' ] ),
  3081. 'mock_capability: (1) two args [ ABC, DEF ] => capability [ ABC, DEF ]'
  3082. ) ;
  3083. is_deeply( [ 'ABC', 'DEF' ], $myimap->capability( ),
  3084. 'mock_capability: (2) two args [ ABC, DEF ] => capability capability [ ABC, DEF ]'
  3085. ) ;
  3086. ok( mock_capability( $myimap, 'ABC', 'DEF' ),
  3087. 'mock_capability: (1) two args ABC, DEF => capability [ ABC, DEF ]'
  3088. ) ;
  3089. is_deeply( [ 'ABC', 'DEF' ], [ $myimap->capability( ) ],
  3090. 'mock_capability: (2) two args ABC, DEF => capability capability [ ABC, DEF ]'
  3091. ) ;
  3092. ok( mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ),
  3093. 'mock_capability: (1) two args IMAP4rev1, APPENDLIMIT=123456 => capability [ IMAP4rev1, APPENDLIMIT=123456 ]'
  3094. ) ;
  3095. is_deeply( [ 'IMAP4rev1', 'APPENDLIMIT=123456' ], [ $myimap->capability( ) ],
  3096. 'mock_capability: (2) two args IMAP4rev1, APPENDLIMIT=123456 => capability capability [ IMAP4rev1, APPENDLIMIT=123456 ]'
  3097. ) ;
  3098. note( 'Leaving tests_mock_capability()' ) ;
  3099. return ;
  3100. }
  3101. sub sig_install_toggle_sleep
  3102. {
  3103. my $mysync = shift ;
  3104. if ( 'MSWin32' ne $OSNAME ) {
  3105. #myprint( "sig_install( $mysync, \&toggle_sleep, 'USR1' )\n" ) ;
  3106. sig_install( $mysync, 'toggle_sleep', 'USR1' ) ;
  3107. }
  3108. #myprint( "Leaving sig_install_toggle_sleep\n" ) ;
  3109. return ;
  3110. }
  3111. sub mock_capability
  3112. {
  3113. my $myimap = shift ;
  3114. my @has_capability_value = @ARG ;
  3115. my ( $has_capability_value ) = @has_capability_value ;
  3116. if ( ! $myimap )
  3117. {
  3118. require_ok( "Test::MockObject" ) ;
  3119. $myimap = Test::MockObject->new( ) ;
  3120. }
  3121. $myimap->mock(
  3122. 'capability',
  3123. sub { return wantarray ?
  3124. @has_capability_value
  3125. : $has_capability_value ;
  3126. }
  3127. ) ;
  3128. return $myimap ;
  3129. }
  3130. sub tests_capability_of
  3131. {
  3132. note( 'Entering tests_capability_of()' ) ;
  3133. is( undef, capability_of( ),
  3134. 'capability_of: no args => undef' ) ;
  3135. my $myimap ;
  3136. is( undef, capability_of( $myimap ),
  3137. 'capability_of: undef => undef' ) ;
  3138. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3139. is( undef, capability_of( $myimap, 'CACA' ),
  3140. 'capability_of: two args unknown capability => undef' ) ;
  3141. is( $NUMBER_123456, capability_of( $myimap, 'APPENDLIMIT' ),
  3142. 'capability_of: two args APPENDLIMIT 123456 => 123456 yeah!' ) ;
  3143. note( 'Leaving tests_capability_of()' ) ;
  3144. return ;
  3145. }
  3146. sub capability_of
  3147. {
  3148. my $imap = shift || return ;
  3149. my $capability_keyword = shift || return ;
  3150. my @capability = $imap->capability ;
  3151. if ( ! @capability ) { return ; }
  3152. my $capability_value = search_in_array( $capability_keyword, @capability ) ;
  3153. return $capability_value ;
  3154. }
  3155. sub tests_search_in_array
  3156. {
  3157. note( 'Entering tests_search_in_array()' ) ;
  3158. is( undef, search_in_array( 'KA' ),
  3159. 'search_in_array: no array => undef ' ) ;
  3160. is( 'VA', search_in_array( 'KA', ( 'KA=VA' ) ),
  3161. 'search_in_array: KA KA=VA => VA ' ) ;
  3162. is( 'VA', search_in_array( 'KA', ( 'KA=VA', 'KB=VB' ) ),
  3163. 'search_in_array: KA KA=VA KB=VB => VA ' ) ;
  3164. is( 'VB', search_in_array( 'KB', ( 'KA=VA', 'KB=VB' ) ),
  3165. 'search_in_array: KA=VA KB=VB => VB ' ) ;
  3166. note( 'Leaving tests_search_in_array()' ) ;
  3167. return ;
  3168. }
  3169. sub search_in_array
  3170. {
  3171. my ( $key, @array ) = @ARG ;
  3172. foreach my $item ( @array )
  3173. {
  3174. if ( $item =~ /([^=]+)=(.*)/ )
  3175. {
  3176. if ( $1 eq $key )
  3177. {
  3178. return $2 ;
  3179. }
  3180. }
  3181. }
  3182. return ;
  3183. }
  3184. sub tests_appendlimit_from_capability
  3185. {
  3186. note( 'Entering tests_appendlimit_from_capability()' ) ;
  3187. is( undef, appendlimit_from_capability( ),
  3188. 'appendlimit_from_capability: no args => undef'
  3189. ) ;
  3190. my $myimap ;
  3191. is( undef, appendlimit_from_capability( $myimap ),
  3192. 'appendlimit_from_capability: undef arg => undef'
  3193. ) ;
  3194. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3195. # Normal behavior
  3196. is( $NUMBER_123456, appendlimit_from_capability( $myimap ),
  3197. 'appendlimit_from_capability: APPENDLIMIT=123456 => 123456'
  3198. ) ;
  3199. # Not a number
  3200. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=ABC' ) ;
  3201. is( undef, appendlimit_from_capability( $myimap ),
  3202. 'appendlimit_from_capability: not a number => undef'
  3203. ) ;
  3204. note( 'Leaving tests_appendlimit_from_capability()' ) ;
  3205. return ;
  3206. }
  3207. sub appendlimit_from_capability
  3208. {
  3209. my $myimap = shift ;
  3210. if ( ! $myimap )
  3211. {
  3212. myprint( "Warn: no imap with call to appendlimit_from_capability\n" ) ;
  3213. return ;
  3214. }
  3215. #myprint( Data::Dumper->Dump( [ \$myimap ] ) ) ;
  3216. my $appendlimit = capability_of( $myimap, 'APPENDLIMIT' ) ;
  3217. #myprint( "has_capability APPENDLIMIT $appendlimit\n" ) ;
  3218. if ( is_an_integer( $appendlimit ) )
  3219. {
  3220. return $appendlimit ;
  3221. }
  3222. return ;
  3223. }
  3224. sub tests_appendlimit
  3225. {
  3226. note( 'Entering tests_appendlimit()' ) ;
  3227. is( undef, appendlimit( ),
  3228. 'appendlimit: no args => undef'
  3229. ) ;
  3230. my $mysync = { } ;
  3231. is( undef, appendlimit( $mysync ),
  3232. 'appendlimit: no imap2 => undef'
  3233. ) ;
  3234. my $myimap ;
  3235. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3236. $mysync->{ imap2 } = $myimap ;
  3237. is( 123456, appendlimit( $mysync ),
  3238. 'appendlimit: imap2 with APPENDLIMIT=123456 => 123456'
  3239. ) ;
  3240. note( 'Leaving tests_appendlimit()' ) ;
  3241. return ;
  3242. }
  3243. sub appendlimit
  3244. {
  3245. my $mysync = shift || return ;
  3246. my $myimap = $mysync->{ imap2 } ;
  3247. my $appendlimit = appendlimit_from_capability( $myimap ) ;
  3248. if ( defined $appendlimit )
  3249. {
  3250. myprint( "Host2: found APPENDLIMIT=$appendlimit in CAPABILITY (use --appendlimit xxxx to override this automatic setting)\n" ) ;
  3251. return $appendlimit ;
  3252. }
  3253. return ;
  3254. }
  3255. sub tests_maxsize_setting
  3256. {
  3257. note( 'Entering tests_maxsize_setting()' ) ;
  3258. is( undef, maxsize_setting( ),
  3259. 'maxsize_setting: no args => undef'
  3260. ) ;
  3261. my $mysync ;
  3262. is( undef, maxsize_setting( $mysync ),
  3263. 'maxsize_setting: undef arg => undef'
  3264. ) ;
  3265. $mysync = { } ;
  3266. $mysync->{ maxsize } = $NUMBER_123456 ;
  3267. # --maxsize alone
  3268. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3269. 'maxsize_setting: --maxsize 123456 alone => 123456'
  3270. ) ;
  3271. $mysync = { } ;
  3272. my $myimap ;
  3273. $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=654321' ) ;
  3274. $mysync->{ imap2 } = $myimap ;
  3275. # APPENDLIMIT alone
  3276. is( $NUMBER_654321, maxsize_setting( $mysync ),
  3277. 'maxsize_setting: APPENDLIMIT 654321 alone => 654321'
  3278. ) ;
  3279. is( $NUMBER_654321, $mysync->{ maxsize },
  3280. 'maxsize_setting: APPENDLIMIT 654321 alone => maxsize 654321'
  3281. ) ;
  3282. # APPENDLIMIT with --appendlimit => --appendlimit wins
  3283. $mysync->{ appendlimit } = $NUMBER_123456 ;
  3284. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3285. 'maxsize_setting: APPENDLIMIT 654321 + --appendlimit 123456 => 123456'
  3286. ) ;
  3287. is( $NUMBER_123456, $mysync->{ maxsize },
  3288. 'maxsize_setting: APPENDLIMIT 654321 + --appendlimit 123456 => maxsize 123456'
  3289. ) ;
  3290. # Fresh
  3291. $mysync = { } ;
  3292. $mysync->{ imap2 } = $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=654321' ) ;
  3293. # Case: "APPENDLIMIT >= --maxsize" => maxsize.
  3294. $mysync->{ maxsize } = $NUMBER_123456 ;
  3295. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3296. 'maxsize_setting: APPENDLIMIT 654321 --maxsize 123456 => 123456'
  3297. ) ;
  3298. # Case: "APPENDLIMIT < --maxsize" => APPENDLIMIT.
  3299. # Fresh
  3300. $mysync = { } ;
  3301. $mysync->{ imap2 } = $myimap = mock_capability( $myimap, 'IMAP4rev1', 'APPENDLIMIT=123456' ) ;
  3302. $mysync->{ maxsize } = $NUMBER_654321 ;
  3303. is( $NUMBER_123456, maxsize_setting( $mysync ),
  3304. 'maxsize_setting: APPENDLIMIT 123456 --maxsize 654321 => 123456 '
  3305. ) ;
  3306. # Now --truncmess stuff
  3307. note( 'Leaving tests_maxsize_setting()' ) ;
  3308. return ;
  3309. }
  3310. # Three variables to take account of
  3311. # appendlimit (given by --appendlimit or CAPABILITY...)
  3312. # maxsize
  3313. # truncmess
  3314. sub maxsize_setting
  3315. {
  3316. my $mysync = shift || return ;
  3317. if ( defined $mysync->{ appendlimit } )
  3318. {
  3319. myprint( "Host2: Getting appendlimit from --appendlimit $mysync->{ appendlimit }\n" ) ;
  3320. }
  3321. else
  3322. {
  3323. $mysync->{ appendlimit } = appendlimit( $mysync ) ;
  3324. }
  3325. if ( all_defined( $mysync->{ appendlimit }, $mysync->{ maxsize } ) )
  3326. {
  3327. my $min_maxsize_appendlimit = min( $mysync->{ maxsize }, $mysync->{ appendlimit } ) ;
  3328. myprint( "Host2: Setting maxsize to $min_maxsize_appendlimit (min of --maxsize $mysync->{ maxsize } and appendlimit $mysync->{ appendlimit }\n" ) ;
  3329. $mysync->{ maxsize } = $min_maxsize_appendlimit ;
  3330. return $mysync->{ maxsize } ;
  3331. }
  3332. elsif ( defined $mysync->{ appendlimit } )
  3333. {
  3334. myprint( "Host2: Setting maxsize to appendlimit $mysync->{ appendlimit }\n" ) ;
  3335. $mysync->{ maxsize } = $mysync->{ appendlimit } ;
  3336. return $mysync->{ maxsize } ;
  3337. }elsif ( defined $mysync->{ maxsize } )
  3338. {
  3339. return $mysync->{ maxsize } ;
  3340. }else
  3341. {
  3342. return ;
  3343. }
  3344. }
  3345. sub all_defined
  3346. {
  3347. if ( not @ARG ) {
  3348. return 0 ;
  3349. }
  3350. foreach my $elem ( @ARG ) {
  3351. if ( not defined $elem ) {
  3352. return 0 ;
  3353. }
  3354. }
  3355. return 1 ;
  3356. }
  3357. sub tests_all_defined
  3358. {
  3359. note( 'Entering tests_all_defined()' ) ;
  3360. is( 0, all_defined( ), 'all_defined: no param => 0' ) ;
  3361. is( 0, all_defined( () ), 'all_defined: void list => 0' ) ;
  3362. is( 0, all_defined( undef ), 'all_defined: undef => 0' ) ;
  3363. is( 0, all_defined( undef, undef ), 'all_defined: undef => 0' ) ;
  3364. is( 0, all_defined( 1, undef ), 'all_defined: 1 undef => 0' ) ;
  3365. is( 0, all_defined( undef, 1 ), 'all_defined: undef 1 => 0' ) ;
  3366. is( 1, all_defined( 1, 1 ), 'all_defined: 1 1 => 1' ) ;
  3367. is( 1, all_defined( (1, 1) ), 'all_defined: (1 1) => 1' ) ;
  3368. note( 'Leaving tests_all_defined()' ) ;
  3369. return ;
  3370. }
  3371. sub tests_hashsynclocal
  3372. {
  3373. note( 'Entering tests_hashsynclocal()' ) ;
  3374. my $mysync = {
  3375. host1 => q{},
  3376. user1 => q{},
  3377. password1 => q{},
  3378. host2 => q{},
  3379. user2 => q{},
  3380. password2 => q{},
  3381. } ;
  3382. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: no hashfile name' ) ;
  3383. $mysync->{ hashfile } = q{} ;
  3384. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: empty hashfile name' ) ;
  3385. $mysync->{ hashfile } = './noexist/rrr' ;
  3386. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: no exists hashfile dir' ) ;
  3387. SKIP: {
  3388. if ( 'MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) { skip( 'Tests only for non-root Unix', 1 ) ; }
  3389. $mysync->{ hashfile } = '/rrr' ;
  3390. is( undef, hashsynclocal( $mysync ), 'hashsynclocal: permission denied' ) ;
  3391. }
  3392. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'hashsynclocal: mkpath W/tmp/tests/' ) ;
  3393. $mysync->{ hashfile } = 'W/tmp/tests/imapsync_hash' ;
  3394. ok( ! -e 'W/tmp/tests/imapsync_hash' || unlink 'W/tmp/tests/imapsync_hash', 'hashsynclocal: unlink W/tmp/tests/imapsync_hash' ) ;
  3395. ok( ! -e 'W/tmp/tests/imapsync_hash', 'hashsynclocal: verify there is no W/tmp/tests/imapsync_hash' ) ;
  3396. is( 'ecdeb4ede672794d173da4e08c52b8ee19b7d252', hashsynclocal( $mysync, 'mukksyhpmbixkxkpjlqivmlqsulpictj' ), 'hashsynclocal: creating/reading W/tmp/tests/imapsync_hash' ) ;
  3397. # A second time now
  3398. is( 'ecdeb4ede672794d173da4e08c52b8ee19b7d252', hashsynclocal( $mysync ), 'hashsynclocal: reading W/tmp/tests/imapsync_hash second time => same' ) ;
  3399. note( 'Leaving tests_hashsynclocal()' ) ;
  3400. return ;
  3401. }
  3402. sub hashsynclocal
  3403. {
  3404. my $mysync = shift ;
  3405. my $hashkey = shift ; # Optional, only there for tests
  3406. my $hashfile = $mysync->{ hashfile } ;
  3407. $hashfile = createhashfileifneeded( $hashfile, $hashkey ) ;
  3408. if ( ! $hashfile ) {
  3409. return ;
  3410. }
  3411. $hashkey = firstline( $hashfile ) ;
  3412. if ( ! $hashkey ) {
  3413. myprint( "No hashkey!\n" ) ;
  3414. return ;
  3415. }
  3416. my $hashsynclocal = hashsync( $mysync, $hashkey ) ;
  3417. return( $hashsynclocal ) ;
  3418. }
  3419. sub tests_hashsync
  3420. {
  3421. note( 'Entering tests_hashsync()' ) ;
  3422. is( 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', hashsync( {}, q{} ), 'hashsync: empty args' ) ;
  3423. my $mysync ;
  3424. $mysync->{ host1 } = 'zzz' ;
  3425. is( 'e86a28a3611c1e7bbaf8057cd00ae122781a11fe', hashsync( $mysync, q{} ), 'hashsync: host1 zzz => ' ) ;
  3426. is( 'e86a28a3611c1e7bbaf8057cd00ae122781a11fe', hashsync( $mysync, q{} ), 'hashsync: host1 zzz => ' ) ;
  3427. $mysync->{ host2 } = 'zzz' ;
  3428. is( '15959573e4a86763253a7aedb1a2b0c60d133dc2', hashsync( $mysync, q{} ), 'hashsync: + host2 zzz => ' ) ;
  3429. is( 'b8d4ab541b209c75928528020ca28ee43488bd8f', hashsync( $mysync, 'A' ), 'hashsync: + hashkey A => ' ) ;
  3430. note( 'Leaving tests_hashsync()' ) ;
  3431. return ;
  3432. }
  3433. sub hashsync
  3434. {
  3435. my $mysync = shift ;
  3436. my $hashkey = shift ;
  3437. my $mystring = join( q{},
  3438. $mysync->{ host1 } || q{},
  3439. $mysync->{ user1 } || q{},
  3440. $mysync->{ password1 } || q{},
  3441. $mysync->{ host2 } || q{},
  3442. $mysync->{ user2 } || q{},
  3443. $mysync->{ password2 } || q{},
  3444. ) ;
  3445. my $hashsync = hmac_sha1_hex( $mystring, $hashkey ) ;
  3446. #myprint( "$hashsync\n" ) ;
  3447. return( $hashsync ) ;
  3448. }
  3449. sub tests_createhashfileifneeded
  3450. {
  3451. note( 'Entering tests_createhashfileifneeded()' ) ;
  3452. is( undef, createhashfileifneeded( ), 'createhashfileifneeded: no parameters => undef' ) ;
  3453. note( 'Leaving tests_createhashfileifneeded()' ) ;
  3454. return ;
  3455. }
  3456. sub createhashfileifneeded
  3457. {
  3458. my $hashfile = shift ;
  3459. my $hashkey = shift || rand32( ) ;
  3460. # no name
  3461. if ( ! $hashfile ) {
  3462. return ;
  3463. }
  3464. # already there
  3465. if ( -e -r $hashfile ) {
  3466. return $hashfile ;
  3467. }
  3468. # not creatable
  3469. if ( ! -w dirname( $hashfile ) ) {
  3470. return ;
  3471. }
  3472. # creatable
  3473. open my $FILE_HANDLE, '>', $hashfile
  3474. or do {
  3475. myprint( "Could not open $hashfile for writing. Check permissions or disk space." ) ;
  3476. return ;
  3477. } ;
  3478. myprint( "Writing random hashkey in $hashfile, once for all times\n" ) ;
  3479. print $FILE_HANDLE $hashkey ;
  3480. close $FILE_HANDLE ;
  3481. # Should be there now
  3482. if ( -e -r $hashfile ) {
  3483. return $hashfile ;
  3484. }
  3485. # unknown failure
  3486. return ;
  3487. }
  3488. sub tests_rand32
  3489. {
  3490. note( 'Entering tests_rand32()' ) ;
  3491. my $string = rand32( ) ;
  3492. myprint( "$string\n" ) ;
  3493. is( 32, length( $string ), 'rand32: 32 characters long' ) ;
  3494. is( 32, length( rand32( ) ), 'rand32: 32 characters long, another one' ) ;
  3495. note( 'Leaving tests_rand32()' ) ;
  3496. return ;
  3497. }
  3498. sub rand32
  3499. {
  3500. my @chars = ( "a".."z" ) ;
  3501. my $string;
  3502. $string .= $chars[rand @chars] for 1..32 ;
  3503. return $string ;
  3504. }
  3505. sub imap_id_stuff
  3506. {
  3507. my $mysync = shift ;
  3508. if ( not $mysync->{id} ) { return ; } ;
  3509. $mysync->{h1_imap_id} = imap_id( $mysync, $mysync->{imap1}, 'Host1' ) ;
  3510. #myprint( 'Host1: ' . $mysync->{h1_imap_id} ) ;
  3511. $mysync->{h2_imap_id} = imap_id( $mysync, $mysync->{imap2}, 'Host2' ) ;
  3512. #myprint( 'Host2: ' . $mysync->{h2_imap_id} ) ;
  3513. return ;
  3514. }
  3515. sub imap_id
  3516. {
  3517. my ( $mysync, $imap, $Side ) = @_ ;
  3518. if ( not $mysync->{id} ) { return q{} ; } ;
  3519. $Side ||= q{} ;
  3520. my $imap_id_response = q{} ;
  3521. if ( not $imap->has_capability( 'ID' ) ) {
  3522. $imap_id_response = 'No ID capability' ;
  3523. myprint( "$Side: No ID capability\n" ) ;
  3524. }else{
  3525. my $id_inp = imapsync_id( $mysync, { side => lc $Side } ) ;
  3526. myprint( "\n$Side: found ID capability. Sending/receiving ID, presented in raw IMAP for now.\n"
  3527. . "In order to avoid sending/receiving ID, use option --noid\n" ) ;
  3528. my $debug_before = $imap->Debug( ) ;
  3529. $imap->Debug( 1 ) ;
  3530. my $id_out = $imap->tag_and_run( 'ID ' . $id_inp ) ;
  3531. #my $id_out = $imap->tag_and_run( 'ID NIL' ) ;
  3532. myprint( "\n" ) ;
  3533. $imap->Debug( $debug_before ) ;
  3534. #$imap_id_response = Data::Dumper->Dump( [ $id_out ], [ 'IMAP_ID' ] ) ;
  3535. }
  3536. return( $imap_id_response ) ;
  3537. }
  3538. sub imapsync_id
  3539. {
  3540. my $mysync = shift ;
  3541. my $overhashref = shift ;
  3542. # See http://tools.ietf.org/html/rfc2971.html
  3543. my $imapsync_id = { } ;
  3544. my $imapsync_id_lamiral = {
  3545. name => 'imapsync',
  3546. version => imapsync_version( $mysync ),
  3547. os => $OSNAME,
  3548. vendor => 'Gilles LAMIRAL',
  3549. 'support-url' => 'https://imapsync.lamiral.info/',
  3550. # Example of date-time: 19-Sep-2015 08:56:07
  3551. date => date_from_rcs( q{$Date: 2019/12/23 20:18:02 $ } ),
  3552. } ;
  3553. my $imapsync_id_github = {
  3554. name => 'imapsync',
  3555. version => imapsync_version( $mysync ),
  3556. os => $OSNAME,
  3557. vendor => 'github',
  3558. 'support-url' => 'https://github.com/imapsync/imapsync',
  3559. date => date_from_rcs( q{$Date: 2019/12/23 20:18:02 $ } ),
  3560. } ;
  3561. $imapsync_id = $imapsync_id_lamiral ;
  3562. #$imapsync_id = $imapsync_id_github ;
  3563. my %mix = ( %{ $imapsync_id }, %{ $overhashref } ) ;
  3564. my $imapsync_id_str = format_for_imap_arg( \%mix ) ;
  3565. #myprint( "$imapsync_id_str\n" ) ;
  3566. return( $imapsync_id_str ) ;
  3567. }
  3568. sub tests_imapsync_id
  3569. {
  3570. note( 'Entering tests_imapsync_id()' ) ;
  3571. my $mysync ;
  3572. ok( '("name" "imapsync" "version" "111" "os" "beurk" "vendor" "Gilles LAMIRAL" "support-url" "https://imapsync.lamiral.info/" "date" "22-12-1968" "side" "host1")'
  3573. eq imapsync_id( $mysync,
  3574. {
  3575. version => 111,
  3576. os => 'beurk',
  3577. date => '22-12-1968',
  3578. side => 'host1'
  3579. }
  3580. ),
  3581. 'tests_imapsync_id override'
  3582. ) ;
  3583. note( 'Leaving tests_imapsync_id()' ) ;
  3584. return ;
  3585. }
  3586. sub format_for_imap_arg
  3587. {
  3588. my $ref = shift ;
  3589. my $string = q{} ;
  3590. my %terms = %{ $ref } ;
  3591. my @terms = ( ) ;
  3592. if ( not ( %terms ) ) { return( 'NIL' ) } ;
  3593. # sort like in RFC then add extra key/values
  3594. foreach my $key ( qw( name version os os-version vendor support-url address date command arguments environment) ) {
  3595. if ( $terms{ $key } ) {
  3596. push @terms, $key, $terms{ $key } ;
  3597. delete $terms{ $key } ;
  3598. }
  3599. }
  3600. push @terms, %terms ;
  3601. $string = '(' . ( join q{ }, map { '"' . $_ . '"' } @terms ) . ')' ;
  3602. return( $string ) ;
  3603. }
  3604. sub tests_format_for_imap_arg
  3605. {
  3606. note( 'Entering tests_format_for_imap_arg()' ) ;
  3607. ok( 'NIL' eq format_for_imap_arg( { } ), 'format_for_imap_arg empty hash ref' ) ;
  3608. ok( '("name" "toto")' eq format_for_imap_arg( { name => 'toto' } ), 'format_for_imap_arg { name => toto }' ) ;
  3609. ok( '("name" "toto" "key" "val")' eq format_for_imap_arg( { name => 'toto', key => 'val' } ), 'format_for_imap_arg 2 x key val' ) ;
  3610. note( 'Leaving tests_format_for_imap_arg()' ) ;
  3611. return ;
  3612. }
  3613. sub quota
  3614. {
  3615. my ( $mysync, $imap, $side ) = @_ ;
  3616. my %side = (
  3617. h1 => 'Host1',
  3618. h2 => 'Host2',
  3619. ) ;
  3620. my $Side = $side{ $side } ;
  3621. my $debug_before = $imap->Debug( ) ;
  3622. $imap->Debug( 1 ) ;
  3623. if ( not $imap->has_capability( 'QUOTA' ) ) {
  3624. $imap->Debug( $debug_before ) ;
  3625. return ;
  3626. } ;
  3627. myprint( "\n$Side: found quota, presented in raw IMAP\n" ) ;
  3628. my $getquotaroot = $imap->getquotaroot( 'INBOX' ) ;
  3629. # Gmail INBOX quotaroot is "" but with it Mail::IMAPClient does a literal GETQUOTA {2} \n ""
  3630. #$imap->quota( 'ROOT' ) ;
  3631. #$imap->quota( '""' ) ;
  3632. myprint( "\n" ) ;
  3633. $imap->Debug( $debug_before ) ;
  3634. my $quota_limit_bytes = quota_extract_storage_limit_in_bytes( $mysync, $getquotaroot ) ;
  3635. my $quota_current_bytes = quota_extract_storage_current_in_bytes( $mysync, $getquotaroot ) ;
  3636. $mysync->{$side}->{quota_limit_bytes} = $quota_limit_bytes ;
  3637. $mysync->{$side}->{quota_current_bytes} = $quota_current_bytes ;
  3638. my $quota_percent ;
  3639. if ( $quota_limit_bytes > 0 ) {
  3640. $quota_percent = mysprintf( '%.2f', $NUMBER_100 * $quota_current_bytes / $quota_limit_bytes ) ;
  3641. }else{
  3642. $quota_percent = 0 ;
  3643. }
  3644. myprint( "$Side: Quota current storage is $quota_current_bytes bytes. Limit is $quota_limit_bytes bytes. So $quota_percent % full\n" ) ;
  3645. if ( $QUOTA_PERCENT_LIMIT < $quota_percent ) {
  3646. my $error = "$Side: $quota_percent % full: it is time to find a bigger place! ( $quota_current_bytes bytes / $quota_limit_bytes bytes )\n" ;
  3647. errors_incr( $mysync, $error ) ;
  3648. }
  3649. return ;
  3650. }
  3651. sub tests_quota_extract_storage_limit_in_bytes
  3652. {
  3653. note( 'Entering tests_quota_extract_storage_limit_in_bytes()' ) ;
  3654. my $mysync = {} ;
  3655. my $imap_output = [
  3656. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  3657. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  3658. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  3659. '5 OK Getquotaroot completed.'
  3660. ] ;
  3661. ok( $NUMBER_104_857_600 * $KIBI == quota_extract_storage_limit_in_bytes( $mysync, $imap_output ), 'quota_extract_storage_limit_in_bytes ') ;
  3662. note( 'Leaving tests_quota_extract_storage_limit_in_bytes()' ) ;
  3663. return ;
  3664. }
  3665. sub quota_extract_storage_limit_in_bytes
  3666. {
  3667. my $mysync = shift ;
  3668. my $imap_output = shift ;
  3669. my $limit_kb ;
  3670. $limit_kb = ( map { /.*\(\s*STORAGE\s+\d+\s+(\d+)\s*\)/x ? $1 : () } @{ $imap_output } )[0] ;
  3671. $limit_kb ||= 0 ;
  3672. $mysync->{ debug } and myprint( "storage_limit_kb = $limit_kb\n" ) ;
  3673. return( $KIBI * $limit_kb ) ;
  3674. }
  3675. sub tests_quota_extract_storage_current_in_bytes
  3676. {
  3677. note( 'Entering tests_quota_extract_storage_current_in_bytes()' ) ;
  3678. my $mysync = {} ;
  3679. my $imap_output = [
  3680. '* QUOTAROOT "INBOX" "Storage quota" "Messages quota"',
  3681. '* QUOTA "Storage quota" (STORAGE 1 104857600)',
  3682. '* QUOTA "Messages quota" (MESSAGE 2 100000)',
  3683. '5 OK Getquotaroot completed.'
  3684. ] ;
  3685. ok( 1*$KIBI == quota_extract_storage_current_in_bytes( $mysync, $imap_output ), 'quota_extract_storage_current_in_bytes: 1 => 1024 ') ;
  3686. note( 'Leaving tests_quota_extract_storage_current_in_bytes()' ) ;
  3687. return ;
  3688. }
  3689. sub quota_extract_storage_current_in_bytes
  3690. {
  3691. my $mysync = shift ;
  3692. my $imap_output = shift ;
  3693. my $current_kb ;
  3694. $current_kb = ( map { /.*\(\s*STORAGE\s+(\d+)\s+\d+\s*\)/x ? $1 : () } @{ $imap_output } )[0] ;
  3695. $current_kb ||= 0 ;
  3696. $mysync->{ debug } and myprint( "storage_current_kb = $current_kb\n" ) ;
  3697. return( $KIBI * $current_kb ) ;
  3698. }
  3699. sub automap
  3700. {
  3701. my ( $mysync ) = @_ ;
  3702. if ( $mysync->{automap} ) {
  3703. myprint( "Turned on automapping folders ( use --noautomap to turn off automapping )\n" ) ;
  3704. }else{
  3705. myprint( "Turned off automapping folders ( use --automap to turn on automapping )\n" ) ;
  3706. return ;
  3707. }
  3708. $mysync->{h1_special} = special_from_folders_hash( $mysync, $mysync->{imap1}, 'Host1' ) ;
  3709. $mysync->{h2_special} = special_from_folders_hash( $mysync, $mysync->{imap2}, 'Host2' ) ;
  3710. build_possible_special( $mysync ) ;
  3711. build_guess_special( $mysync ) ;
  3712. build_automap( $mysync ) ;
  3713. return ;
  3714. }
  3715. sub build_guess_special
  3716. {
  3717. my ( $mysync ) = shift ;
  3718. foreach my $h1_fold ( sort keys %{ $mysync->{h1_folders_all} } ) {
  3719. my $special = guess_special( $h1_fold, $mysync->{possible_special}, $mysync->{h1_prefix} ) ;
  3720. if ( $special ) {
  3721. $mysync->{h1_special_guessed}{$h1_fold} = $special ;
  3722. my $already_guessed = $mysync->{h1_special_guessed}{$special} ;
  3723. if ( $already_guessed ) {
  3724. myprint( "Host1: $h1_fold not $special because set to $already_guessed\n" ) ;
  3725. }else{
  3726. $mysync->{h1_special_guessed}{$special} = $h1_fold ;
  3727. }
  3728. }
  3729. }
  3730. foreach my $h2_fold ( sort keys %{ $mysync->{h2_folders_all} } ) {
  3731. my $special = guess_special( $h2_fold, $mysync->{possible_special}, $mysync->{h2_prefix} ) ;
  3732. if ( $special ) {
  3733. $mysync->{h2_special_guessed}{$h2_fold} = $special ;
  3734. my $already_guessed = $mysync->{h2_special_guessed}{$special} ;
  3735. if ( $already_guessed ) {
  3736. myprint( "Host2: $h2_fold not $special because set to $already_guessed\n" ) ;
  3737. }else{
  3738. $mysync->{h2_special_guessed}{$special} = $h2_fold ;
  3739. }
  3740. }
  3741. }
  3742. return ;
  3743. }
  3744. sub guess_special
  3745. {
  3746. my( $folder, $possible_special_ref, $prefix ) = @_ ;
  3747. my $folder_no_prefix = $folder ;
  3748. $folder_no_prefix =~ s/\Q${prefix}\E//xms ;
  3749. #$debug and myprint( "folder_no_prefix: $folder_no_prefix\n" ) ;
  3750. my $guess_special = $possible_special_ref->{ $folder }
  3751. || $possible_special_ref->{ $folder_no_prefix }
  3752. || q{} ;
  3753. return( $guess_special ) ;
  3754. }
  3755. sub tests_guess_special
  3756. {
  3757. note( 'Entering tests_guess_special()' ) ;
  3758. my $possible_special_ref = build_possible_special( my $mysync ) ;
  3759. ok( '\Sent' eq guess_special( 'Sent', $possible_special_ref, q{} ) ,'guess_special: Sent => \Sent' ) ;
  3760. ok( q{} eq guess_special( 'Blabla', $possible_special_ref, q{} ) ,'guess_special: Blabla => q{}' ) ;
  3761. ok( '\Sent' eq guess_special( 'INBOX.Sent', $possible_special_ref, 'INBOX.' ) ,'guess_special: INBOX.Sent => \Sent' ) ;
  3762. ok( '\Sent' eq guess_special( 'IN BOX.Sent', $possible_special_ref, 'IN BOX.' ) ,'guess_special: IN BOX.Sent => \Sent' ) ;
  3763. note( 'Leaving tests_guess_special()' ) ;
  3764. return ;
  3765. }
  3766. sub build_automap
  3767. {
  3768. my $mysync = shift ;
  3769. $mysync->{ debug } and myprint( "Entering build_automap\n" ) ;
  3770. foreach my $h1_fold ( @{ $mysync->{h1_folders_wanted} } ) {
  3771. my $h2_fold ;
  3772. my $h1_special = $mysync->{h1_special}{$h1_fold} ;
  3773. my $h1_special_guessed = $mysync->{h1_special_guessed}{$h1_fold} ;
  3774. # Case 1: special on both sides.
  3775. if ( $h1_special
  3776. and exists $mysync->{h2_special}{$h1_special} ) {
  3777. $h2_fold = $mysync->{h2_special}{$h1_special} ;
  3778. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  3779. next ;
  3780. }
  3781. # Case 2: special on host1, not on host2
  3782. if ( $h1_special
  3783. and ( not exists $mysync->{h2_special}{$h1_special} )
  3784. and ( exists $mysync->{h2_special_guessed}{$h1_special} )
  3785. ) {
  3786. # special_guessed on host2
  3787. $h2_fold = $mysync->{h2_special_guessed}{$h1_special} ;
  3788. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  3789. next ;
  3790. }
  3791. # Case 3: no special on host1, special on host2
  3792. if ( ( not $h1_special )
  3793. and ( $h1_special_guessed )
  3794. and ( exists $mysync->{h2_special}{$h1_special_guessed} )
  3795. ) {
  3796. $h2_fold = $mysync->{h2_special}{$h1_special_guessed} ;
  3797. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  3798. next ;
  3799. }
  3800. # Case 4: no special on both sides.
  3801. if ( ( not $h1_special )
  3802. and ( $h1_special_guessed )
  3803. and ( not exists $mysync->{h2_special}{$h1_special_guessed} )
  3804. and ( exists $mysync->{h2_special_guessed}{$h1_special_guessed} )
  3805. ) {
  3806. $h2_fold = $mysync->{h2_special_guessed}{$h1_special_guessed} ;
  3807. $mysync->{f1f2auto}{ $h1_fold } = $h2_fold ;
  3808. next ;
  3809. }
  3810. }
  3811. return( $mysync->{f1f2auto} ) ;
  3812. }
  3813. # I will not add what there is at:
  3814. # http://stackoverflow.com/questions/2185391/localized-gmail-imap-folders/2185548#2185548
  3815. # because it works well without
  3816. sub build_possible_special
  3817. {
  3818. my $mysync = shift ;
  3819. my $possible_special = { } ;
  3820. # All|Archive|Drafts|Flagged|Junk|Sent|Trash
  3821. $possible_special->{'\All'} = [ 'All', 'All Messages', '&BBIEQQQ1-' ] ;
  3822. $possible_special->{'\Archive'} = [ 'Archive', 'Archives', '&BBAEQARFBDgEMg-' ] ;
  3823. $possible_special->{'\Drafts'} = [ 'Drafts', 'DRAFTS', '&BCcENQRABD0EPgQyBDgEOgQ4-', 'Szkice', 'Wersje robocze' ] ;
  3824. $possible_special->{'\Flagged'} = [ 'Flagged', 'Starred', '&BB8EPgQ8BDUERwQ1BD0EPQRLBDU-' ] ;
  3825. $possible_special->{'\Junk'} = [ 'Junk', 'junk', 'Spam', 'SPAM', '&BCEEPwQwBDw-',
  3826. 'Potwierdzony spam', 'Wiadomo&AVs-ci-&AVs-mieci',
  3827. 'Junk E-Mail', 'Junk Email'] ;
  3828. $possible_special->{'\Sent'} = [ 'Sent', 'Sent Messages', 'Sent Items',
  3829. 'Gesendete Elemente', 'Gesendete Objekte',
  3830. '&AMk-l&AOk-ments envoy&AOk-s', 'Envoy&AOk-', 'Objets envoy&AOk-s',
  3831. 'Elementos enviados',
  3832. '&kAFP4W4IMH8wojCkMMYw4A-',
  3833. '&BB4EQgQ,BEAEMAQyBDsENQQ9BD0ESwQ1-',
  3834. 'Elementy wys&AUI-ane'] ;
  3835. $possible_special->{'\Trash'} = [ 'Trash', 'TRASH',
  3836. '&BCMENAQwBDsENQQ9BD0ESwQ1-', '&BBoEPgRABDcEOAQ9BDA-',
  3837. 'Kosz',
  3838. 'Deleted Items', 'Deleted Messages' ] ;
  3839. foreach my $special ( qw( \All \Archive \Drafts \Flagged \Junk \Sent \Trash ) ){
  3840. foreach my $possible_folder ( @{ $possible_special->{$special} } ) {
  3841. $possible_special->{ $possible_folder } = $special ;
  3842. } ;
  3843. }
  3844. $mysync->{possible_special} = $possible_special ;
  3845. $mysync->{ debug } and myprint( Data::Dumper->Dump( [ $possible_special ], [ 'possible_special' ] ) ) ;
  3846. return( $possible_special ) ;
  3847. }
  3848. sub tests_special_from_folders_hash
  3849. {
  3850. note( 'Entering tests_special_from_folders_hash()' ) ;
  3851. my $mysync = {} ;
  3852. require_ok( "Test::MockObject" ) ;
  3853. my $imapT = Test::MockObject->new( ) ;
  3854. is( undef, special_from_folders_hash( ), 'special_from_folders_hash: no args' ) ;
  3855. is( undef, special_from_folders_hash( $mysync ), 'special_from_folders_hash: undef args' ) ;
  3856. is_deeply( {}, special_from_folders_hash( $mysync, $imapT ), 'special_from_folders_hash: $imap void' ) ;
  3857. $imapT->mock( 'folders_hash', sub { return( [ { name => 'Sent', attrs => [ '\Sent' ] } ] ) } ) ;
  3858. is_deeply( { Sent => '\Sent', '\Sent' => 'Sent' },
  3859. special_from_folders_hash( $mysync, $imapT ), 'special_from_folders_hash: $imap \Sent' ) ;
  3860. note( 'Leaving tests_special_from_folders_hash()' ) ;
  3861. return( ) ;
  3862. }
  3863. sub special_from_folders_hash
  3864. {
  3865. my ( $mysync, $imap, $side ) = @_ ;
  3866. my %special = ( ) ;
  3867. if ( ! defined $imap ) { return ; }
  3868. $side = defined $side ? $side : 'Host?' ;
  3869. if ( ! $imap->can( 'folders_hash' ) ) {
  3870. my $error = "$side: To have automagic rfc6154 folder mapping, upgrade Mail::IMAPClient >= 3.34\n" ;
  3871. errors_incr( $mysync, $error ) ;
  3872. return( \%special ) ; # empty hash ref
  3873. }
  3874. my $folders_hash = $imap->folders_hash( ) ;
  3875. foreach my $fhash (@{ $folders_hash } ) {
  3876. my @special = grep { /\\(?:All|Archive|Drafts|Flagged|Junk|Sent|Trash)/x } @{ $fhash->{attrs} } ;
  3877. if ( @special ) {
  3878. my $special = $special[0] ; # keep first one. Could be not very good.
  3879. if ( exists $special{ $special } ) {
  3880. myprintf( "%s: special %-20s = %s already assigned to %s\n",
  3881. $side, $fhash->{name}, join( q{ }, @special ), $special{ $special } ) ;
  3882. }else{
  3883. myprintf( "%s: special %-20s = %s\n",
  3884. $side, $fhash->{name}, join( q{ }, @special ) ) ;
  3885. $special{ $special } = $fhash->{name} ;
  3886. $special{ $fhash->{name} } = $special ; # double entry value => key
  3887. }
  3888. }
  3889. }
  3890. myprint( "\n" ) if ( %special ) ;
  3891. return( \%special ) ;
  3892. }
  3893. sub errors_incr
  3894. {
  3895. my ( $mysync, @error ) = @ARG ;
  3896. $mysync->{nb_errors}++ ;
  3897. if ( @error ) {
  3898. errors_log( $mysync, @error ) ;
  3899. myprint( @error ) ;
  3900. }
  3901. $mysync->{errorsmax} ||= $ERRORS_MAX ;
  3902. if ( $mysync->{nb_errors} >= $mysync->{errorsmax} ) {
  3903. myprint( "Maximum number of errors $mysync->{errorsmax} reached ( you can change $mysync->{errorsmax} to any value, for example 100 with --errorsmax 100 ). Exiting.\n" ) ;
  3904. if ( $mysync->{errorsdump} ) {
  3905. myprint( errorsdump( $mysync->{nb_errors}, errors_log( $mysync ) ) ) ;
  3906. # again since errorsdump( ) can be very verbose and masquerade previous warning
  3907. myprint( "Maximum number of errors $mysync->{errorsmax} reached ( you can change $mysync->{errorsmax} to any value, for example 100 with --errorsmax 100 ). Exiting.\n" ) ;
  3908. }
  3909. exit_clean( $mysync, $EXIT_WITH_ERRORS_MAX ) ;
  3910. }
  3911. return ;
  3912. }
  3913. sub tests_errors_log
  3914. {
  3915. note( 'Entering tests_errors_log()' ) ;
  3916. is( undef, errors_log( ), 'errors_log: no args => undef' ) ;
  3917. my $mysync = {} ;
  3918. is( undef, errors_log( $mysync ), 'errors_log: empty => undef' ) ;
  3919. is_deeply( [ 'aieaie' ], [ errors_log( $mysync, 'aieaie' ) ], 'errors_log: aieaie => aieaie' ) ;
  3920. # cumulative
  3921. is_deeply( [ 'aieaie' ], [ errors_log( $mysync ) ], 'errors_log: nothing more => aieaie' ) ;
  3922. is_deeply( [ 'aieaie', 'ouille' ], [ errors_log( $mysync, 'ouille' ) ], 'errors_log: ouille => aieaie ouille' ) ;
  3923. is_deeply( [ 'aieaie', 'ouille' ], [ errors_log( $mysync ) ], 'errors_log: nothing more => aieaie ouille' ) ;
  3924. note( 'Leaving tests_errors_log()' ) ;
  3925. return ;
  3926. }
  3927. sub errors_log
  3928. {
  3929. my ( $mysync, @error ) = @ARG ;
  3930. if ( ! $mysync->{errors_log} ) {
  3931. $mysync->{errors_log} = [] ;
  3932. }
  3933. if ( @error ) {
  3934. push @{ $mysync->{errors_log} }, join( q{}, @error ) ;
  3935. }
  3936. if ( @{ $mysync->{errors_log} } ) {
  3937. return @{ $mysync->{errors_log} } ;
  3938. }
  3939. else {
  3940. return ;
  3941. }
  3942. }
  3943. sub errorsdump
  3944. {
  3945. my( $nb_errors, @errors_log ) = @ARG ;
  3946. my $error_num = 0 ;
  3947. my $errors_list = q{} ;
  3948. if ( @errors_log ) {
  3949. $errors_list = "++++ Listing $nb_errors errors encountered during the sync ( avoid this listing with --noerrorsdump ).\n" ;
  3950. foreach my $error ( @errors_log ) {
  3951. $error_num++ ;
  3952. $errors_list .= "Err $error_num/$nb_errors: $error" ;
  3953. }
  3954. }
  3955. return( $errors_list ) ;
  3956. }
  3957. sub tests_live_result
  3958. {
  3959. note( 'Entering tests_live_result()' ) ;
  3960. my $nb_errors = shift ;
  3961. if ( $nb_errors ) {
  3962. myprint( "Live tests failed with $nb_errors errors\n" ) ;
  3963. } else {
  3964. myprint( "Live tests ended successfully\n" ) ;
  3965. }
  3966. note( 'Leaving tests_live_result()' ) ;
  3967. return ;
  3968. }
  3969. sub size_filtered_flag
  3970. {
  3971. my $mysync = shift ;
  3972. my $h1_size = shift ;
  3973. if ( defined $mysync->{ maxsize } and $h1_size >= $mysync->{ maxsize } ) {
  3974. return( 1 ) ;
  3975. }
  3976. if ( defined $minsize and $h1_size <= $minsize ) {
  3977. return( 1 ) ;
  3978. }
  3979. return( 0 ) ;
  3980. }
  3981. sub sync_flags_fir
  3982. {
  3983. my ( $mysync, $h1_fold, $h1_msg, $h2_fold, $h2_msg, $permanentflags2, $h1_fir_ref, $h2_fir_ref ) = @_ ;
  3984. if ( not defined $h1_msg ) { return } ;
  3985. if ( not defined $h2_msg ) { return } ;
  3986. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} ;
  3987. return if size_filtered_flag( $mysync, $h1_size ) ;
  3988. # used cached flag values for efficiency
  3989. my $h1_flags = $h1_fir_ref->{ $h1_msg }->{ 'FLAGS' } || q{} ;
  3990. my $h2_flags = $h2_fir_ref->{ $h2_msg }->{ 'FLAGS' } || q{} ;
  3991. sync_flags( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  3992. return ;
  3993. }
  3994. sub sync_flags_after_copy
  3995. {
  3996. # Activated with option --syncflagsaftercopy
  3997. my( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $permanentflags2 ) = @_ ;
  3998. if ( my @h2_flags = $mysync->{imap2}->flags( $h2_msg ) ) {
  3999. my $h2_flags = "@h2_flags" ;
  4000. ( $mysync->{ debug } or $debugflags ) and myprint( "Host2: msg $h2_fold/$h2_msg flags before sync flags after copy ( $h2_flags )\n" ) ;
  4001. sync_flags( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) ;
  4002. }else{
  4003. myprint( "Host2: msg $h2_fold/$h2_msg could not get its flags for sync flags after copy\n" ) ;
  4004. }
  4005. return ;
  4006. }
  4007. # Globals
  4008. # $debug
  4009. # $debugflags
  4010. # $permanentflags2
  4011. sub sync_flags
  4012. {
  4013. my( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $h2_msg, $h2_flags, $permanentflags2 ) = @_ ;
  4014. ( $mysync->{ debug } or $debugflags ) and
  4015. myprint( "Host1: flags init msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 msg $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  4016. $h1_flags = flags_for_host2( $h1_flags, $permanentflags2 ) ;
  4017. $h2_flags = flagscase( $h2_flags ) ;
  4018. ( $mysync->{ debug } or $debugflags ) and
  4019. myprint( "Host1: flags filt msg $h1_fold/$h1_msg flags( $h1_flags ) Host2 msg $h2_fold/$h2_msg flags( $h2_flags )\n" ) ;
  4020. # compare flags - set flags if there a difference
  4021. my @h1_flags = sort split(q{ }, $h1_flags );
  4022. my @h2_flags = sort split(q{ }, $h2_flags );
  4023. my $diff = compare_lists( \@h1_flags, \@h2_flags );
  4024. $diff and ( $mysync->{ debug } or $debugflags )
  4025. and myprint( "Host2: flags msg $h2_fold/$h2_msg replacing h2 flags( $h2_flags ) with h1 flags( $h1_flags )\n" ) ;
  4026. # This sets flags exactly. So flags can be removed with this.
  4027. # When you remove a \Seen flag on host1 you want it
  4028. # to be removed on host2. Just add flags is not what
  4029. # we need most of the time, so no + like in "+FLAGS.SILENT".
  4030. if ( not $mysync->{dry} and $diff and not $mysync->{imap2}->store( $h2_msg, "FLAGS.SILENT (@h1_flags)" ) ) {
  4031. my $error_msg = join q{}, "Host2: flags msg $h2_fold/$h2_msg could not add flags [@h1_flags]: ",
  4032. $mysync->{imap2}->LastError || q{}, "\n" ;
  4033. errors_incr( $mysync, $error_msg ) ;
  4034. }
  4035. return ;
  4036. }
  4037. sub _filter
  4038. {
  4039. my $mysync = shift ;
  4040. my $str = shift or return q{} ;
  4041. my $sz = $SIZE_MAX_STR ;
  4042. my $len = length $str ;
  4043. if ( not $mysync->{ debug } and $len > $sz*2 ) {
  4044. my $beg = substr $str, 0, $sz ;
  4045. my $end = substr $str, -$sz, $sz ;
  4046. $str = $beg . '...' . $end ;
  4047. }
  4048. $str =~ s/\012?\015$//x ;
  4049. return "(len=$len) " . $str ;
  4050. }
  4051. sub lost_connection
  4052. {
  4053. my( $mysync, $imap, $error_message ) = @_;
  4054. if ( $imap->IsUnconnected( ) ) {
  4055. $mysync->{nb_errors}++ ;
  4056. my $lcomm = $imap->LastIMAPCommand || q{} ;
  4057. my $einfo = $imap->LastError || @{$imap->History}[$LAST] || q{} ;
  4058. # if string is long try reduce to a more reasonable size
  4059. $lcomm = _filter( $mysync, $lcomm ) ;
  4060. $einfo = _filter( $mysync, $einfo ) ;
  4061. myprint( "Failure: last command: $lcomm\n") if ( $mysync->{ debug } && $lcomm) ;
  4062. myprint( "Failure: lost connection $error_message: ", $einfo, "\n") ;
  4063. return( 1 ) ;
  4064. }
  4065. else{
  4066. return( 0 ) ;
  4067. }
  4068. }
  4069. sub tests_max
  4070. {
  4071. note( 'Entering tests_max()' ) ;
  4072. is( 0, max( 0 ), 'max 0 => 0' ) ;
  4073. is( 1, max( 1 ), 'max 1 => 1' ) ;
  4074. is( $MINUS_ONE, max( $MINUS_ONE ), 'max -1 => -1') ;
  4075. is( undef, max( ), 'max no arg => undef' ) ;
  4076. is( undef, max( undef ), 'undef => undef' ) ;
  4077. is( undef, max( undef, undef ), 'undef, undef => undef' ) ;
  4078. is( $NUMBER_100, max( 1, $NUMBER_100 ), 'max 1 100 => 100' ) ;
  4079. is( $NUMBER_100, max( $NUMBER_100, 1 ), 'max 100 1 => 100' ) ;
  4080. is( $NUMBER_100, max( $NUMBER_100, $NUMBER_42, 1 ), 'max 100 42 1 => 100' ) ;
  4081. is( $NUMBER_100, max( $NUMBER_100, '42', 1 ), 'max 100 42 1 => 100' ) ;
  4082. is( $NUMBER_100, max( '100', '42', 1 ), 'max 100 42 1 => 100' ) ;
  4083. is( $NUMBER_100, max( $NUMBER_100, 'haha', 1 ), 'max 100 haha 1 => 100') ;
  4084. is( $NUMBER_100, max( 'bb', $NUMBER_100, 'haha' ), 'max bb 100 haha => 100') ;
  4085. is( $MINUS_ONE, max( q{}, $MINUS_ONE, 'haha' ), 'max "" -1 haha => -1') ;
  4086. is( $MINUS_ONE, max( q{}, $MINUS_ONE, $MINUS_TWO ), 'max "" -1 -2 => -1') ;
  4087. is( $MINUS_ONE, max( 'haha', $MINUS_ONE, $MINUS_TWO ), 'max haha -1 -2 => -1') ;
  4088. is( 1, max( $MINUS_ONE, 1 ), 'max -1 1 => 1') ;
  4089. is( 1, max( undef, 1 ), 'max undef 1 => 1' ) ;
  4090. is( 0, max( undef, 0 ), 'max undef 0 => 0' ) ;
  4091. is( 'haha', max( 'haha' ), 'max haha => haha') ;
  4092. is( 'bb', max( 'aa', 'bb' ), 'max aa bb => bb') ;
  4093. is( 'bb', max( 'bb', 'aa' ), 'max bb aa => bb') ;
  4094. is( 'bb', max( 'bb', 'aa', 'bb' ), 'max bb aa bb => bb') ;
  4095. note( 'Leaving tests_max()' ) ;
  4096. return ;
  4097. }
  4098. sub max
  4099. {
  4100. my @list = @_ ;
  4101. return( undef ) if ( 0 == scalar @list ) ;
  4102. my( @numbers, @notnumbers ) ;
  4103. foreach my $item ( @list )
  4104. {
  4105. if ( is_number( $item ) )
  4106. {
  4107. push @numbers, $item ;
  4108. }
  4109. elsif ( defined $item )
  4110. {
  4111. push @notnumbers, $item ;
  4112. }
  4113. }
  4114. my @sorted ;
  4115. if ( @numbers )
  4116. {
  4117. @sorted = sort { $a <=> $b } @numbers ;
  4118. }
  4119. elsif ( @notnumbers )
  4120. {
  4121. @sorted = sort { $a cmp $b } @notnumbers ;
  4122. }
  4123. else
  4124. {
  4125. return ;
  4126. }
  4127. return( pop @sorted ) ;
  4128. }
  4129. sub tests_is_number
  4130. {
  4131. note( 'Entering tests_is_number()' ) ;
  4132. is( undef, is_number( ), 'is_number: no args => undef ' ) ;
  4133. is( undef, is_number( undef ), 'is_number: undef => undef ' ) ;
  4134. ok( is_number( 1 ), 'is_number: 1 => 1' ) ;
  4135. ok( is_number( 1.1 ), 'is_number: 1.1 => 1' ) ;
  4136. ok( is_number( 0 ), 'is_number: 0 => 1' ) ;
  4137. ok( is_number( -1 ), 'is_number: -1 => 1' ) ;
  4138. ok( ! is_number( 1.1.1 ), 'is_number: 1.1.1 => no' ) ;
  4139. ok( ! is_number( q{} ), 'is_number: q{} => no' ) ;
  4140. ok( ! is_number( 'haha' ), 'is_number: haha => no' ) ;
  4141. ok( ! is_number( '0haha' ), 'is_number: 0haha => no' ) ;
  4142. ok( ! is_number( '2haha' ), 'is_number: 2haha => no' ) ;
  4143. ok( ! is_number( 'haha2' ), 'is_number: haha2 => no' ) ;
  4144. note( 'Leaving tests_is_number()' ) ;
  4145. return ;
  4146. }
  4147. sub is_number
  4148. {
  4149. my $item = shift ;
  4150. if ( ! defined $item ) { return ; }
  4151. if ( $item =~ /\A$RE{num}{real}\Z/ ) {
  4152. return 1 ;
  4153. }
  4154. return ;
  4155. }
  4156. sub tests_min
  4157. {
  4158. note( 'Entering tests_min()' ) ;
  4159. is( 0, min( 0 ), 'min 0 => 0' ) ;
  4160. is( 1, min( 1 ), 'min 1 => 1' ) ;
  4161. is( $MINUS_ONE, min( $MINUS_ONE ), 'min -1 => -1' ) ;
  4162. is( undef, min( ), 'min no arg => undef' ) ;
  4163. is( 1, min( 1, $NUMBER_100 ), 'min 1 100 => 1' ) ;
  4164. is( 1, min( $NUMBER_100, 1 ), 'min 100 1 => 1' ) ;
  4165. is( 1, min( $NUMBER_100, $NUMBER_42, 1 ), 'min 100 42 1 => 1' ) ;
  4166. is( 1, min( $NUMBER_100, '42', 1 ), 'min 100 42 1 => 1' ) ;
  4167. is( 1, min( '100', '42', 1 ), 'min 100 42 1 => 1' ) ;
  4168. is( 1, min( $NUMBER_100, 'haha', 1 ), 'min 100 haha 1 => 1') ;
  4169. is( $MINUS_ONE, min( $MINUS_ONE, 1 ), 'min -1 1 => -1') ;
  4170. is( 1, min( undef, 1 ), 'min undef 1 => 1' ) ;
  4171. is( 0, min( undef, 0 ), 'min undef 0 => 0' ) ;
  4172. is( 1, min( undef, 1 ), 'min undef 1 => 1' ) ;
  4173. is( 0, min( undef, 2, 0, 1 ), 'min undef, 2, 0, 1 => 0' ) ;
  4174. is( 'haha', min( 'haha' ), 'min haha => haha') ;
  4175. is( 'aa', min( 'aa', 'bb' ), 'min aa bb => aa') ;
  4176. is( 'aa', min( 'bb', 'aa' ), 'min bb aa bb => aa') ;
  4177. is( 'aa', min( 'bb', 'aa', 'bb' ), 'min bb aa bb => aa') ;
  4178. note( 'Leaving tests_min()' ) ;
  4179. return ;
  4180. }
  4181. sub min
  4182. {
  4183. my @list = @_ ;
  4184. return( undef ) if ( 0 == scalar @list ) ;
  4185. my( @numbers, @notnumbers ) ;
  4186. foreach my $item ( @list ) {
  4187. if ( is_number( $item ) ) {
  4188. push @numbers, $item ;
  4189. }else{
  4190. push @notnumbers, $item ;
  4191. }
  4192. }
  4193. my @sorted ;
  4194. if ( @numbers ) {
  4195. @sorted = sort { $a <=> $b } @numbers ;
  4196. }elsif( @notnumbers ) {
  4197. @sorted = sort { $a cmp $b } @notnumbers ;
  4198. }else{
  4199. return ;
  4200. }
  4201. return( shift @sorted ) ;
  4202. }
  4203. sub check_lib_version
  4204. {
  4205. my $mysync = shift ;
  4206. $mysync->{ debug } and myprint( "IMAPClient $Mail::IMAPClient::VERSION\n" ) ;
  4207. if ( '2.2.9' eq $Mail::IMAPClient::VERSION ) {
  4208. myprint( "imapsync no longer supports Mail::IMAPClient 2.2.9, upgrade it\n" ) ;
  4209. return 0 ;
  4210. }
  4211. else{
  4212. # 3.x.x is no longer buggy with imapsync.
  4213. # 3.30 or currently superior is imposed in the Perl "use Mail::IMAPClient line".
  4214. return 1 ;
  4215. }
  4216. return ;
  4217. }
  4218. sub module_version_str
  4219. {
  4220. my( $module_name, $module_version ) = @_ ;
  4221. my $str = mysprintf( "%-20s %s\n", $module_name, $module_version ) ;
  4222. return( $str ) ;
  4223. }
  4224. sub modulesversion
  4225. {
  4226. my @list_version;
  4227. my %modulesversion = (
  4228. 'Authen::NTLM' => sub { $Authen::NTLM::VERSION },
  4229. 'CGI' => sub { $CGI::VERSION },
  4230. 'Compress::Zlib' => sub { $Compress::Zlib::VERSION },
  4231. 'Crypt::OpenSSL::RSA' => sub { $Crypt::OpenSSL::RSA::VERSION },
  4232. 'Data::Uniqid' => sub { $Data::Uniqid::VERSION },
  4233. 'Digest::HMAC_MD5' => sub { $Digest::HMAC_MD5::VERSION },
  4234. 'Digest::HMAC_SHA1' => sub { $Digest::HMAC_SHA1::VERSION },
  4235. 'Digest::MD5' => sub { $Digest::MD5::VERSION },
  4236. 'Encode' => sub { $Encode::VERSION },
  4237. 'Encode::IMAPUTF7' => sub { $Encode::IMAPUTF7::VERSION },
  4238. 'File::Copy::Recursive' => sub { $File::Copy::Recursive::VERSION },
  4239. 'File::Spec' => sub { $File::Spec::VERSION },
  4240. 'Getopt::Long' => sub { $Getopt::Long::VERSION },
  4241. 'HTML::Entities' => sub { $HTML::Entities::VERSION },
  4242. 'IO::Socket' => sub { $IO::Socket::VERSION },
  4243. 'IO::Socket::INET' => sub { $IO::Socket::INET::VERSION },
  4244. 'IO::Socket::INET6' => sub { $IO::Socket::INET6::VERSION },
  4245. 'IO::Socket::IP' => sub { $IO::Socket::IP::VERSION },
  4246. 'IO::Socket::SSL' => sub { $IO::Socket::SSL::VERSION },
  4247. 'IO::Tee' => sub { $IO::Tee::VERSION },
  4248. 'JSON' => sub { $JSON::VERSION },
  4249. 'JSON::WebToken' => sub { $JSON::WebToken::VERSION },
  4250. 'LWP' => sub { $LWP::VERSION },
  4251. 'Mail::IMAPClient' => sub { $Mail::IMAPClient::VERSION },
  4252. 'MIME::Base64' => sub { $MIME::Base64::VERSION },
  4253. 'Net::Ping' => sub { $Net::Ping::VERSION },
  4254. 'Net::SSLeay' => sub { $Net::SSLeay::VERSION },
  4255. 'Term::ReadKey' => sub { $Term::ReadKey::VERSION },
  4256. 'Test::MockObject' => sub { $Test::MockObject::VERSION },
  4257. 'Time::HiRes' => sub { $Time::HiRes::VERSION },
  4258. 'Unicode::String' => sub { $Unicode::String::VERSION },
  4259. 'URI::Escape' => sub { $URI::Escape::VERSION },
  4260. #'Lalala' => sub { $Lalala::VERSION },
  4261. ) ;
  4262. foreach my $module_name ( sort keys %modulesversion ) {
  4263. # trick from http://www.perlmonks.org/?node_id=152122
  4264. my $file_name = $module_name . '.pm' ;
  4265. $file_name =~s,::,/,xmgs; # Foo::Bar::Baz => Foo/Bar/Baz.pm
  4266. my $v ;
  4267. eval {
  4268. require $file_name ;
  4269. $v = defined $modulesversion{ $module_name } ? $modulesversion{ $module_name }->() : q{?} ;
  4270. } or $v = q{Not installed} ;
  4271. push @list_version, module_version_str( $module_name, $v ) ;
  4272. }
  4273. return( @list_version ) ;
  4274. }
  4275. sub tests_command_line_nopassword
  4276. {
  4277. note( 'Entering tests_command_line_nopassword()' ) ;
  4278. ok( q{} eq command_line_nopassword(), 'command_line_nopassword void' );
  4279. my $mysync = {} ;
  4280. ok( '--blabla' eq command_line_nopassword( $mysync, '--blabla' ), 'command_line_nopassword --blabla' );
  4281. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  4282. ok( '--password1 MASKED' eq command_line_nopassword( $mysync, qw{ --password1 secret1}), 'command_line_nopassword --password1' );
  4283. ok( '--blabla --password1 MASKED --blibli'
  4284. eq command_line_nopassword( $mysync, qw{ --blabla --password1 secret1 --blibli } ), 'command_line_nopassword --password1 --blibli' );
  4285. $mysync->{showpasswords} = 1 ;
  4286. ok( q{} eq command_line_nopassword(), 'command_line_nopassword void' );
  4287. ok( '--blabla' eq command_line_nopassword( $mysync, '--blabla'), 'command_line_nopassword --blabla' );
  4288. #myprint( command_line_nopassword((qw{ --password1 secret1 })), "\n" ) ;
  4289. ok( '--password1 secret1' eq command_line_nopassword( $mysync, qw{ --password1 secret1} ), 'command_line_nopassword --password1' );
  4290. ok( '--blabla --password1 secret1 --blibli'
  4291. eq command_line_nopassword( $mysync, qw{ --blabla --password1 secret1 --blibli } ), 'command_line_nopassword --password1 --blibli' );
  4292. note( 'Leaving tests_command_line_nopassword()' ) ;
  4293. return ;
  4294. }
  4295. # Construct a command line copy with passwords replaced by MASKED.
  4296. sub command_line_nopassword
  4297. {
  4298. my $mysync = shift @ARG ;
  4299. my @argv = @ARG ;
  4300. my @argv_nopassword ;
  4301. if ( $mysync->{ cmdcgi } ) {
  4302. @argv_nopassword = mask_password_value( @{ $mysync->{ cmdcgi } } ) ;
  4303. return( "@argv_nopassword" ) ;
  4304. }
  4305. if ( $mysync->{showpasswords} )
  4306. {
  4307. return( "@argv" ) ;
  4308. }
  4309. @argv_nopassword = mask_password_value( @argv ) ;
  4310. return("@argv_nopassword") ;
  4311. }
  4312. sub mask_password_value
  4313. {
  4314. my @argv = @ARG ;
  4315. my @argv_nopassword ;
  4316. while ( @argv ) {
  4317. my $arg = shift @argv ; # option name or value
  4318. if ( $arg =~ m/-password[12]/x ) {
  4319. shift @argv ; # password value
  4320. push @argv_nopassword, $arg, 'MASKED' ; # option name and fake value
  4321. }else{
  4322. push @argv_nopassword, $arg ; # same option or value
  4323. }
  4324. }
  4325. return @argv_nopassword ;
  4326. }
  4327. sub tests_get_stdin_masked
  4328. {
  4329. note( 'Entering tests_get_stdin_masked()' ) ;
  4330. is( q{}, get_stdin_masked( ), 'get_stdin_masked: no args' ) ;
  4331. is( q{}, get_stdin_masked( 'Please ENTER: ' ), 'get_stdin_masked: ENTER' ) ;
  4332. note( 'Leaving tests_get_stdin_masked()' ) ;
  4333. return ;
  4334. }
  4335. #######################################################
  4336. # The issue is that prompt() does not prompt the prompt
  4337. # when the program is used like
  4338. # { sleep 2 ; echo blablabla ; } | ./imapsync ...--host1 lo --user1 tata --host2 lo --user2 titi
  4339. # use IO::Prompter ;
  4340. sub get_stdin_masked
  4341. {
  4342. my $prompt = shift || 'Say something: ' ;
  4343. local @ARGV = () ;
  4344. my $input = prompt(
  4345. -prompt => $prompt,
  4346. -echo => '*',
  4347. ) ;
  4348. #myprint( "You said: $input\n" ) ;
  4349. return $input ;
  4350. }
  4351. sub ask_for_password_new
  4352. {
  4353. my $prompt = shift ;
  4354. my $password = get_stdin_masked( $prompt ) ;
  4355. return $password ;
  4356. }
  4357. #########################################################
  4358. sub ask_for_password
  4359. {
  4360. my $prompt = shift ;
  4361. myprint( $prompt ) ;
  4362. Term::ReadKey::ReadMode( 2 ) ;
  4363. ## no critic (InputOutput::ProhibitExplicitStdin)
  4364. my $password = <STDIN> ;
  4365. chomp $password ;
  4366. myprint( "\nGot it\n" ) ;
  4367. Term::ReadKey::ReadMode( 0 ) ;
  4368. return $password ;
  4369. }
  4370. # Have to refactor get_password1() get_password2()
  4371. # to have only get_password() and two calls
  4372. sub get_password1
  4373. {
  4374. my $mysync = shift ;
  4375. $mysync->{password1}
  4376. || $mysync->{ passfile1 }
  4377. || 'PREAUTH' eq $authmech1
  4378. || 'EXTERNAL' eq $authmech1
  4379. || $ENV{IMAPSYNC_PASSWORD1}
  4380. || do
  4381. {
  4382. myprint( << 'FIN_PASSFILE' ) ;
  4383. If you are afraid of giving password on the command line arguments, you can put the
  4384. password of user1 in a file named file1 and use "--passfile1 file1" instead of typing it.
  4385. Then give this file restrictive permissions with the command "chmod 600 file1".
  4386. An other solution is to set the environment variable IMAPSYNC_PASSWORD1
  4387. FIN_PASSFILE
  4388. my $user = $authuser1 || $mysync->{user1} ;
  4389. my $host = $mysync->{host1} ;
  4390. my $prompt = "What's the password for $user" . ' at ' . "$host? (not visible while you type, then enter RETURN) " ;
  4391. $mysync->{password1} = ask_for_password( $prompt ) ;
  4392. } ;
  4393. if ( defined $mysync->{ passfile1 } ) {
  4394. if ( ! -e -r $mysync->{ passfile1 } ) {
  4395. myprint( "Failure: file from parameter --passfile1 $mysync->{ passfile1 } does not exist or is not readable\n" ) ;
  4396. $mysync->{nb_errors}++ ;
  4397. exit_clean( $mysync, $EX_NOINPUT ) ;
  4398. }
  4399. # passfile1 readable
  4400. $mysync->{password1} = firstline ( $mysync->{ passfile1 } ) ;
  4401. return ;
  4402. }
  4403. if ( $ENV{IMAPSYNC_PASSWORD1} ) {
  4404. $mysync->{password1} = $ENV{IMAPSYNC_PASSWORD1} ;
  4405. return ;
  4406. }
  4407. return ;
  4408. }
  4409. sub get_password2
  4410. {
  4411. my $mysync = shift ;
  4412. $mysync->{password2}
  4413. || $mysync->{ passfile2 }
  4414. || 'PREAUTH' eq $authmech2
  4415. || 'EXTERNAL' eq $authmech2
  4416. || $ENV{IMAPSYNC_PASSWORD2}
  4417. || do
  4418. {
  4419. myprint( << 'FIN_PASSFILE' ) ;
  4420. If you are afraid of giving password on the command line arguments, you can put the
  4421. password of user2 in a file named file2 and use "--passfile2 file2" instead of typing it.
  4422. Then give this file restrictive permissions with the command "chmod 600 file2".
  4423. An other solution is to set the environment variable IMAPSYNC_PASSWORD2
  4424. FIN_PASSFILE
  4425. my $user = $authuser2 || $mysync->{user2} ;
  4426. my $host = $mysync->{host2} ;
  4427. my $prompt = "What's the password for $user" . ' at ' . "$host? (not visible while you type, then enter RETURN) " ;
  4428. $mysync->{password2} = ask_for_password( $prompt ) ;
  4429. } ;
  4430. if ( defined $mysync->{ passfile2 } ) {
  4431. if ( ! -e -r $mysync->{ passfile2 } ) {
  4432. myprint( "Failure: file from parameter --passfile2 $mysync->{ passfile2 } does not exist or is not readable\n" ) ;
  4433. $mysync->{nb_errors}++ ;
  4434. exit_clean( $mysync, $EX_NOINPUT ) ;
  4435. }
  4436. # passfile2 readable
  4437. $mysync->{password2} = firstline ( $mysync->{ passfile2 } ) ;
  4438. return ;
  4439. }
  4440. if ( $ENV{IMAPSYNC_PASSWORD2} ) {
  4441. $mysync->{password2} = $ENV{IMAPSYNC_PASSWORD2} ;
  4442. return ;
  4443. }
  4444. return ;
  4445. }
  4446. sub remove_tmp_files
  4447. {
  4448. my $mysync = shift or return ;
  4449. $mysync->{pidfile} or return ;
  4450. if ( -e $mysync->{pidfile} ) {
  4451. unlink $mysync->{pidfile} ;
  4452. }
  4453. return ;
  4454. }
  4455. sub cleanup_before_exit
  4456. {
  4457. my $mysync = shift ;
  4458. remove_tmp_files( $mysync ) ;
  4459. if ( $mysync->{imap1} and $mysync->{imap1}->IsConnected() )
  4460. {
  4461. myprint( "Disconnecting from host1 $mysync->{ host1 } user1 $mysync->{ user1 }\n" ) ;
  4462. $mysync->{imap1}->logout( ) ;
  4463. }
  4464. if ( $mysync->{imap2} and $mysync->{imap2}->IsConnected() )
  4465. {
  4466. myprint( "Disconnecting from host2 $mysync->{ host2 } user2 $mysync->{ user2 }\n" ) ;
  4467. $mysync->{imap2}->logout( ) ;
  4468. }
  4469. if ( $mysync->{log} ) {
  4470. myprint( "Log file is $mysync->{logfile} ( to change it, use --logfile filepath ; or use --nolog to turn off logging )\n" ) ;
  4471. }
  4472. if ( $mysync->{log} and $mysync->{logfile_handle} ) {
  4473. #myprint( "Closing $mysync->{ logfile }\n" ) ;
  4474. close $mysync->{logfile_handle} ;
  4475. }
  4476. return ;
  4477. }
  4478. sub exit_clean
  4479. {
  4480. my $mysync = shift @ARG ;
  4481. my $status = shift @ARG ;
  4482. my @messages = @ARG ;
  4483. if ( @messages )
  4484. {
  4485. myprint( @messages ) ;
  4486. }
  4487. myprint( "Exiting with return value $status ($EXIT_TXT{$status}) $mysync->{nb_errors}/$mysync->{errorsmax} nb_errors/max_errors\n" ) ;
  4488. cleanup_before_exit( $mysync ) ;
  4489. exit $status ;
  4490. }
  4491. sub missing_option
  4492. {
  4493. my $mysync = shift ;
  4494. my $option = shift ;
  4495. $mysync->{nb_errors}++ ;
  4496. exit_clean( $mysync, $EX_USAGE, "$option option is mandatory, for help run $PROGRAM_NAME --help\n" ) ;
  4497. return ;
  4498. }
  4499. sub catch_ignore
  4500. {
  4501. my $mysync = shift ;
  4502. my $signame = shift ;
  4503. my $sigcounter = ++$mysync->{ sigcounter }{ $signame } ;
  4504. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ),
  4505. "). Received $sigcounter $signame signals so far. Thanks!\n" ) ;
  4506. stats( $mysync ) ;
  4507. return ;
  4508. }
  4509. sub catch_exit
  4510. {
  4511. my $mysync = shift ;
  4512. my $signame = shift || q{} ;
  4513. if ( $signame ) {
  4514. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ),
  4515. "). Asked to terminate\n" ) ;
  4516. if ( $mysync->{stats} ) {
  4517. myprint( "Here are the final stats of this sync not completely finished so far\n" ) ;
  4518. stats( $mysync ) ;
  4519. myprint( "Ended by a signal $signame (my PID is $PROCESS_ID my PPID is ",
  4520. getppid( ), "). I am asked to terminate immediately.\n" ) ;
  4521. myprint( "You should resynchronize those accounts by running a sync again,\n",
  4522. "since some messages and entire folders might still be missing on host2.\n" ) ;
  4523. }
  4524. ## no critic (RequireLocalizedPunctuationVars)
  4525. $SIG{ $signame } = 'DEFAULT'; # restore default action
  4526. # kill myself with $signame
  4527. # https://www.cons.org/cracauer/sigint.html
  4528. myprint( "Killing myself with signal $signame\n" ) ;
  4529. cleanup_before_exit( $mysync ) ;
  4530. kill( $signame, $PROCESS_ID ) ;
  4531. sleep 1 ;
  4532. $mysync->{nb_errors}++ ;
  4533. exit_clean( $mysync, $EXIT_BY_SIGNAL,
  4534. "Still there after killing myself with signal $signame...\n"
  4535. ) ;
  4536. }
  4537. else
  4538. {
  4539. $mysync->{nb_errors}++ ;
  4540. exit_clean( $mysync, $EXIT_BY_SIGNAL, "Exiting in catch_exit with no signal...\n" ) ;
  4541. }
  4542. return ;
  4543. }
  4544. sub catch_print
  4545. {
  4546. my $mysync = shift ;
  4547. my $signame = shift ;
  4548. my $sigcounter = ++$mysync->{ sigcounter }{ $signame } ;
  4549. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ),
  4550. "). Received $sigcounter $signame signals so far. Thanks!\n" ) ;
  4551. return ;
  4552. }
  4553. sub here_twice
  4554. {
  4555. my $mysync = shift ;
  4556. my $now = time ;
  4557. my $previous = $mysync->{lastcatch} || 0 ;
  4558. $mysync->{lastcatch} = $now ;
  4559. if ( $INTERVAL_TO_EXIT >= $now - $previous ) {
  4560. return $TRUE ;
  4561. }else{
  4562. return $FALSE ;
  4563. }
  4564. }
  4565. sub catch_reconnect
  4566. {
  4567. my $mysync = shift ;
  4568. my $signame = shift ;
  4569. if ( here_twice( $mysync ) ) {
  4570. myprint( "Got two signals $signame within $INTERVAL_TO_EXIT seconds. Exiting...\n" ) ;
  4571. catch_exit( $mysync, $signame ) ;
  4572. }else{
  4573. myprint( "\nGot a signal $signame (my PID is $PROCESS_ID my PPID is ", getppid( ), ")\n",
  4574. "Hit 2 ctr-c within 2 seconds to exit the program\n",
  4575. "Hit only 1 ctr-c to reconnect to both imap servers\n",
  4576. ) ;
  4577. myprint( "For now only one signal $signame within $INTERVAL_TO_EXIT seconds.\n" ) ;
  4578. if ( ! defined $mysync->{imap1} ) { return ; }
  4579. if ( ! defined $mysync->{imap2} ) { return ; }
  4580. myprint( "Info: reconnecting to host1 imap server $mysync->{host1}\n" ) ;
  4581. $mysync->{imap1}->State( Mail::IMAPClient::Unconnected ) ;
  4582. $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  4583. if ( $mysync->{imap1}->reconnect( ) )
  4584. {
  4585. myprint( "Info: reconnected to host1 imap server $mysync->{host1}\n" ) ;
  4586. }
  4587. else
  4588. {
  4589. $mysync->{nb_errors}++ ;
  4590. exit_clean( $mysync, $EXIT_CONNECTION_FAILURE ) ;
  4591. }
  4592. myprint( "Info: reconnecting to host2 imap server\n" ) ;
  4593. $mysync->{imap2}->State( Mail::IMAPClient::Unconnected ) ;
  4594. $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  4595. if ( $mysync->{imap2}->reconnect( ) )
  4596. {
  4597. myprint( "Info: reconnected to host2 imap server $mysync->{host2}\n" ) ;
  4598. }
  4599. else
  4600. {
  4601. $mysync->{nb_errors}++ ;
  4602. exit_clean( $mysync, $EXIT_CONNECTION_FAILURE ) ;
  4603. }
  4604. myprint( "Info: reconnected to both imap servers\n" ) ;
  4605. }
  4606. return ;
  4607. }
  4608. sub install_signals
  4609. {
  4610. my $mysync = shift ;
  4611. if ( under_docker_context( $mysync ) )
  4612. {
  4613. # output( $mysync, "Under docker context so leaving signals as they are\n" ) ;
  4614. output( $mysync, "Under docker context so installing only signals to exit\n" ) ;
  4615. @{ $mysync->{ sigexit } } = ( defined( $mysync->{ sigexit } ) ) ? @{ $mysync->{ sigexit } } : ( 'INT', 'QUIT', 'TERM' ) ;
  4616. sig_install( $mysync, 'catch_exit', @{ $mysync->{ sigexit } } ) ;
  4617. }
  4618. else
  4619. {
  4620. # Unix signals
  4621. @{ $mysync->{ sigexit } } = ( defined( $mysync->{ sigexit } ) ) ? @{ $mysync->{ sigexit } } : ( 'QUIT', 'TERM' ) ;
  4622. @{ $mysync->{ sigreconnect } } = ( defined( $mysync->{ sigreconnect } ) ) ? @{ $mysync->{ sigreconnect } } : ( 'INT' ) ;
  4623. @{ $mysync->{ sigprint } } = ( defined( $mysync->{ sigprint } ) ) ? @{ $mysync->{ sigprint } } : ( 'HUP' ) ;
  4624. @{ $mysync->{ sigignore } } = ( defined( $mysync->{ sigignore } ) ) ? @{ $mysync->{ sigignore } } : ( ) ;
  4625. #local %SIG = %SIG ;
  4626. sig_install( $mysync, 'catch_exit', @{ $mysync->{ sigexit } } ) ;
  4627. sig_install( $mysync, 'catch_reconnect', @{ $mysync->{ sigreconnect } } ) ;
  4628. sig_install( $mysync, 'catch_print', @{ $mysync->{ sigprint } } ) ;
  4629. # --sigignore can override sigexit, sigreconnect and sigprint (for the same signals only)
  4630. sig_install( $mysync, 'catch_ignore', @{ $mysync->{ sigignore } } ) ;
  4631. sig_install_toggle_sleep( $mysync ) ;
  4632. }
  4633. return ;
  4634. }
  4635. sub tests_reconnect_12_if_needed
  4636. {
  4637. note( 'Entering tests_reconnect_12_if_needed()' ) ;
  4638. my $mysync ;
  4639. $mysync->{imap1} = Mail::IMAPClient->new( ) ;
  4640. $mysync->{imap2} = Mail::IMAPClient->new( ) ;
  4641. $mysync->{imap1}->Server( 'test1.lamiral.info' ) ;
  4642. $mysync->{imap2}->Server( 'test2.lamiral.info' ) ;
  4643. is( 2, reconnect_12_if_needed( $mysync ), 'reconnect_12_if_needed: test1&test2 .lamiral.info => 1' ) ;
  4644. is( 1, $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_12_if_needed: test1.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  4645. is( 1, $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_12_if_needed: test2.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  4646. note( 'Leaving tests_reconnect_12_if_needed()' ) ;
  4647. return ;
  4648. }
  4649. sub reconnect_12_if_needed
  4650. {
  4651. my $mysync = shift ;
  4652. #return 2 ;
  4653. if ( ! reconnect_if_needed( $mysync->{imap1} ) ) {
  4654. return ;
  4655. }
  4656. if ( ! reconnect_if_needed( $mysync->{imap2} ) ) {
  4657. return ;
  4658. }
  4659. # both were good
  4660. return 2 ;
  4661. }
  4662. sub tests_reconnect_if_needed
  4663. {
  4664. note( 'Entering tests_reconnect_if_needed()' ) ;
  4665. my $myimap ;
  4666. is( undef, reconnect_if_needed( ), 'reconnect_if_needed: no args => undef' ) ;
  4667. is( undef, reconnect_if_needed( $myimap ), 'reconnect_if_needed: undef arg => undef' ) ;
  4668. $myimap = Mail::IMAPClient->new( ) ;
  4669. $myimap->Debug( 1 ) ;
  4670. is( undef, reconnect_if_needed( $myimap ), 'reconnect_if_needed: empty new Mail::IMAPClient => undef' ) ;
  4671. $myimap->Server( 'test.lamiral.info' ) ;
  4672. is( 1, reconnect_if_needed( $myimap ), 'reconnect_if_needed: test.lamiral.info => 1' ) ;
  4673. is( 1, $myimap->{IMAPSYNC_RECONNECT_COUNT}, 'reconnect_if_needed: test.lamiral.info IMAPSYNC_RECONNECT_COUNT => 1' ) ;
  4674. note( 'Leaving tests_reconnect_if_needed()' ) ;
  4675. return ;
  4676. }
  4677. sub reconnect_if_needed
  4678. {
  4679. # return undef upon failure.
  4680. # return 1 upon connection success, with or without reconnection.
  4681. my $imap = shift ;
  4682. if ( ! defined $imap ) { return ; }
  4683. if ( ! $imap->Server( ) ) { return ; }
  4684. if ( $imap->IsUnconnected( ) ) {
  4685. $imap->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  4686. if ( $imap->reconnect( ) ) {
  4687. return 1 ;
  4688. }
  4689. }else{
  4690. return 1 ;
  4691. }
  4692. # A last forced one
  4693. $imap->State( Mail::IMAPClient::Unconnected ) ;
  4694. $imap->reconnect( ) ;
  4695. $imap->{IMAPSYNC_RECONNECT_COUNT} += 1 ;
  4696. if ( $imap->noop ) {
  4697. # NOOP is ok
  4698. return 1 ;
  4699. }
  4700. return ;
  4701. }
  4702. # $sync->{id} = defined $sync->{id} ? $sync->{id} : 1 ;
  4703. # imap_id_stuff( $sync ) ;
  4704. sub justconnect
  4705. {
  4706. my $mysync = shift ;
  4707. my $justconnect1 = justconnect1( $sync ) ;
  4708. my $justconnect2 = justconnect2( $sync ) ;
  4709. return "$justconnect1 $justconnect2";
  4710. }
  4711. sub justconnect1
  4712. {
  4713. my $mysync = shift ;
  4714. if ( $mysync->{host1} )
  4715. {
  4716. myprint( "Host1: Will just connect to $mysync->{host1} without login\n" ) ;
  4717. $mysync->{imap1} = connect_imap(
  4718. $mysync->{host1}, $mysync->{port1}, $debugimap1,
  4719. $mysync->{ssl1}, $mysync->{tls1}, 'Host1',
  4720. $mysync->{h1}->{timeout}, $mysync->{h1} ) ;
  4721. imap_id( $mysync, $mysync->{imap1}, 'Host1' ) ;
  4722. $mysync->{imap1}->logout( ) ;
  4723. return $mysync->{host1} ;
  4724. }
  4725. return q{} ;
  4726. }
  4727. sub justconnect2
  4728. {
  4729. my $mysync = shift ;
  4730. if ( $mysync->{host2} )
  4731. {
  4732. myprint( "Host2: Will just connect to $mysync->{host2} without login\n" ) ;
  4733. $mysync->{imap2} = connect_imap(
  4734. $mysync->{host2}, $mysync->{port2}, $debugimap2,
  4735. $mysync->{ssl2}, $mysync->{tls2}, 'Host2',
  4736. $mysync->{h2}->{timeout}, $mysync->{h2} ) ;
  4737. imap_id( $mysync, $mysync->{imap2}, 'Host2' ) ;
  4738. $mysync->{imap2}->logout( ) ;
  4739. return $mysync->{host2} ;
  4740. }
  4741. return q{} ;
  4742. }
  4743. sub skip_macosx
  4744. {
  4745. #return ;
  4746. return( 'macosx.polarhome.com' eq hostname() ) ;
  4747. }
  4748. sub tests_mailimapclient_connect
  4749. {
  4750. note( 'Entering tests_mailimapclient_connect()' ) ;
  4751. my $imap ;
  4752. # ipv4
  4753. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv4: new' ) ;
  4754. is( 'Mail::IMAPClient', ref( $imap ), 'mailimapclient_connect ipv4: ref is Mail::IMAPClient' ) ;
  4755. # Mail::IMAPClient 3.40 die on this... So we skip it, thanks to "mature" IO::Socket::IP
  4756. # Mail::IMAPClient 3.42 is ok so this test is back.
  4757. is( undef, $imap->connect( ), 'mailimapclient_connect ipv4: connect with no server => failure' ) ;
  4758. is( 'test.lamiral.info', $imap->Server( 'test.lamiral.info' ), 'mailimapclient_connect ipv4: setting Server(test.lamiral.info)' ) ;
  4759. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4: setting Debug( 1 )' ) ;
  4760. is( 143, $imap->Port( 143 ), 'mailimapclient_connect ipv4: setting Port( 143 )' ) ;
  4761. is( 3, $imap->Timeout( 3 ), 'mailimapclient_connect ipv4: setting Timout( 3 )' ) ;
  4762. like( ref( $imap->connect( ) ), qr/IO::Socket::INET|IO::Socket::IP/, 'mailimapclient_connect ipv4: connect to test.lamiral.info' ) ;
  4763. like( $imap->logout( ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv4: logout' ) ;
  4764. is( undef, undef $imap, 'mailimapclient_connect ipv4: free variable' ) ;
  4765. # ipv4 + ssl
  4766. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv4 + ssl: new' ) ;
  4767. is( 'test.lamiral.info', $imap->Server( 'test.lamiral.info' ), 'mailimapclient_connect ipv4 + ssl: setting Server(test.lamiral.info)' ) ;
  4768. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4 + ssl: setting Debug( 1 )' ) ;
  4769. ok( $imap->Ssl( [ SSL_verify_mode => SSL_VERIFY_NONE, SSL_cipher_list => 'DEFAULT:!DH' ] ), 'mailimapclient_connect ipv4 + ssl: setting Ssl( SSL_VERIFY_NONE )' ) ;
  4770. is( 993, $imap->Port( 993 ), 'mailimapclient_connect ipv4 + ssl: setting Port( 993 )' ) ;
  4771. like( ref( $imap->connect( ) ), qr/IO::Socket::SSL/, 'mailimapclient_connect ipv4 + ssl: connect to test.lamiral.info' ) ;
  4772. like( $imap->logout( ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv4 + ssl: logout in ssl does not cause failure' ) ;
  4773. is( undef, undef $imap, 'mailimapclient_connect ipv4 + ssl: free variable' ) ;
  4774. # ipv6 + ssl
  4775. # Fails often on ks2ipv6.lamiral.info
  4776. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect ipv6 + ssl: new' ) ;
  4777. is( 'petiteipv6.lamiral.info', $imap->Server( 'petiteipv6.lamiral.info' ), 'mailimapclient_connect ipv6 + ssl: setting Server petiteipv6.lamiral.info' ) ;
  4778. is( 3, $imap->Timeout( 3 ), 'mailimapclient_connect ipv4: setting Timout( 3 )' ) ;
  4779. ok( $imap->Ssl( [ SSL_verify_mode => SSL_VERIFY_NONE, SSL_cipher_list => 'DEFAULT:!DH' ] ), 'mailimapclient_connect ipv6 + ssl: setting Ssl( SSL_VERIFY_NONE )' ) ;
  4780. is( 993, $imap->Port( 993 ), 'mailimapclient_connect ipv6 + ssl: setting Port( 993 )' ) ;
  4781. SKIP: {
  4782. if (
  4783. 'CUILLERE' eq hostname()
  4784. or
  4785. skip_macosx()
  4786. or
  4787. -e '/.dockerenv'
  4788. or
  4789. 'pcHPDV7-HP' eq hostname()
  4790. )
  4791. {
  4792. skip( 'Tests avoided on CUILLERE/pcHPDV7-HP/macosx.polarhome.com/docker cannot do ipv6', 4 ) ;
  4793. }
  4794. is( 1, $imap->Debug( 1 ), 'mailimapclient_connect ipv4 + ssl: setting Debug( 1 )' ) ;
  4795. # It sounds stupid but it avoids failures on the next test about $imap->connect
  4796. is( '2a01:e34:ecde:70d0:223:54ff:fec2:36d7', resolv( 'petiteipv6.lamiral.info' ), 'resolv: petiteipv6.lamiral.info => 2001:41d0:8:bebd::1' ) ;
  4797. like( ref( $imap->connect( ) ), qr/IO::Socket::SSL/, 'mailimapclient_connect ipv6 + ssl: connect to petiteipv6.lamiral.info' ) ;
  4798. # This one is ok on petite, not on ks2, do not know why, so commented.
  4799. like( ref( $imap->logout( ) ), qr/Mail::IMAPClient/, 'mailimapclient_connect ipv6 + ssl: logout in ssl is ok on petiteipv6.lamiral.info' ) ;
  4800. }
  4801. is( undef, undef $imap, 'mailimapclient_connect ipv6 + ssl: free variable' ) ;
  4802. note( 'Leaving tests_mailimapclient_connect()' ) ;
  4803. return ;
  4804. }
  4805. sub tests_mailimapclient_connect_bug
  4806. {
  4807. note( 'Entering tests_mailimapclient_connect_bug()' ) ;
  4808. my $imap ;
  4809. # ipv6
  4810. ok( $imap = Mail::IMAPClient->new( ), 'mailimapclient_connect_bug ipv6: new' ) ;
  4811. is( 'ks2ipv6.lamiral.info', $imap->Server( 'ks2ipv6.lamiral.info' ), 'mailimapclient_connect_bug ipv6: setting Server(ks2ipv6.lamiral.info)' ) ;
  4812. is( 143, $imap->Port( 143 ), 'mailimapclient_connect_bug ipv6: setting Port( 993 )' ) ;
  4813. SKIP: {
  4814. if (
  4815. 'CUILLERE' eq hostname()
  4816. or
  4817. skip_macosx()
  4818. or
  4819. -e '/.dockerenv'
  4820. or
  4821. 'pcHPDV7-HP' eq hostname()
  4822. )
  4823. {
  4824. skip( 'Tests avoided on CUILLERE/pcHPDV7-HP/macosx.polarhome.com/docker cannot do ipv6', 1 ) ;
  4825. }
  4826. like( ref( $imap->connect( ) ), qr/IO::Socket::INET/, 'mailimapclient_connect_bug ipv6: connect to ks2ipv6.lamiral.info' )
  4827. or diag( 'mailimapclient_connect_bug ipv6: ', $imap->LastError( ), $!, ) ;
  4828. }
  4829. #is( $imap->logout( ), undef, 'mailimapclient_connect_bug ipv6: logout in ssl causes failure' ) ;
  4830. is( undef, undef $imap, 'mailimapclient_connect_bug ipv6: free variable' ) ;
  4831. note( 'Leaving tests_mailimapclient_connect_bug()' ) ;
  4832. return ;
  4833. }
  4834. sub tests_connect_socket
  4835. {
  4836. note( 'Entering tests_connect_socket()' ) ;
  4837. is( undef, connect_socket( ), 'connect_socket: no args' ) ;
  4838. my $socket ;
  4839. my $imap ;
  4840. SKIP: {
  4841. if (
  4842. 'CUILLERE' eq hostname()
  4843. or
  4844. skip_macosx()
  4845. or
  4846. -e '/.dockerenv'
  4847. or
  4848. 'pcHPDV7-HP' eq hostname()
  4849. )
  4850. {
  4851. skip( 'Tests avoided on CUILLERE/pcHPDV7-HP/macosx.polarhome.com/docker cannot do ipv6', 2 ) ;
  4852. }
  4853. $socket = IO::Socket::INET6->new(
  4854. PeerAddr => 'ks2ipv6.lamiral.info',
  4855. PeerPort => 143,
  4856. ) ;
  4857. ok( $imap = connect_socket( $socket ), 'connect_socket: ks2ipv6.lamiral.info port 143 IO::Socket::INET6' ) ;
  4858. #$imap->Debug( 1 ) ;
  4859. # myprint( $imap->capability( ) ) ;
  4860. if ( $imap ) {
  4861. $imap->logout( ) ;
  4862. }
  4863. $IO::Socket::SSL::DEBUG = 4 ;
  4864. $socket = IO::Socket::SSL->new(
  4865. PeerHost => 'ks2ipv6.lamiral.info',
  4866. PeerPort => 993,
  4867. SSL_verify_mode => SSL_VERIFY_NONE,
  4868. SSL_cipher_list => 'DEFAULT:!DH',
  4869. ) ;
  4870. # myprint( $socket ) ;
  4871. ok( $imap = connect_socket( $socket ), 'connect_socket: ks2ipv6.lamiral.info port 993 IO::Socket::SSL' ) ;
  4872. #$imap->Debug( 1 ) ;
  4873. # myprint( $imap->capability( ) ) ;
  4874. # $socket->close( ) ;
  4875. if ( $imap ) {
  4876. $socket->close( ) ;
  4877. }
  4878. #$socket->close(SSL_no_shutdown => 1) ;
  4879. #$imap->logout( ) ;
  4880. #myprint( "\n" ) ;
  4881. #$imap->logout( ) ;
  4882. }
  4883. note( 'Leaving tests_connect_socket()' ) ;
  4884. return ;
  4885. }
  4886. sub connect_socket
  4887. {
  4888. my( $socket ) = @ARG ;
  4889. if ( ! defined $socket ) { return ; }
  4890. my $host = $socket->peerhost( ) ;
  4891. my $port = $socket->peerport( ) ;
  4892. #print "socket->peerhost: ", $socket->peerhost( ), "\n" ;
  4893. #print "socket->peerport: ", $socket->peerport( ), "\n" ;
  4894. my $imap = Mail::IMAPClient->new( ) ;
  4895. $imap->Socket( $socket ) ;
  4896. my $banner = $imap->Results()->[0] ;
  4897. #myprint( "banner: $banner" ) ;
  4898. return $imap ;
  4899. }
  4900. sub tests_probe_imapssl
  4901. {
  4902. note( 'Entering tests_probe_imapssl()' ) ;
  4903. is( undef, probe_imapssl( ), 'probe_imapssl: no args => undef' ) ;
  4904. is( undef, probe_imapssl( 'unknown' ), 'probe_imapssl: unknown => undef' ) ;
  4905. note( "hostname is: ", hostname() ) ;
  4906. SKIP: {
  4907. if (
  4908. 'CUILLERE' eq hostname()
  4909. or
  4910. skip_macosx()
  4911. or
  4912. -e '/.dockerenv'
  4913. or
  4914. 'pcHPDV7-HP' eq hostname()
  4915. )
  4916. {
  4917. skip( 'Tests avoided on CUILLERE or pcHPDV7-HP or Mac or docker: cannot do ipv6', 0 ) ;
  4918. }
  4919. # fed up with this one
  4920. #like( probe_imapssl( 'ks2ipv6.lamiral.info' ), qr/^\* OK/, 'probe_imapssl: ks2ipv6.lamiral.info matches "* OK"' ) ;
  4921. } ;
  4922. # It sounds stupid but it avoids failures on the next test about $imap->connect
  4923. ok( resolv( 'imap.gmail.com' ), 'resolv: imap.gmail.com => something' ) ;
  4924. like( probe_imapssl( 'imap.gmail.com' ), qr/^\* OK/, 'probe_imapssl: imap.gmail.com matches "* OK"' ) ;
  4925. like( probe_imapssl( 'test1.lamiral.info' ), qr/^\* OK/, 'probe_imapssl: test1.lamiral.info matches "* OK"' ) ;
  4926. note( 'Leaving tests_probe_imapssl()' ) ;
  4927. return ;
  4928. }
  4929. sub probe_imapssl
  4930. {
  4931. my $host = shift ;
  4932. if ( ! $host ) { return ; }
  4933. $sync->{ debug } and $IO::Socket::SSL::DEBUG = 4 ;
  4934. my $socket = IO::Socket::SSL->new(
  4935. PeerHost => $host,
  4936. PeerPort => $IMAP_SSL_PORT,
  4937. SSL_verifycn_scheme => 'imap',
  4938. SSL_verify_mode => $SSL_VERIFY_POLICY,
  4939. SSL_cipher_list => 'DEFAULT:!DH',
  4940. ) ;
  4941. if ( ! $socket ) { return ; }
  4942. $sync->{ debug } and print "socket: $socket\n" ;
  4943. my $banner ;
  4944. $socket->sysread( $banner, 65_536 ) ;
  4945. $sync->{ debug } and print "banner: $banner" ;
  4946. $socket->close( ) ;
  4947. return $banner ;
  4948. }
  4949. sub connect_imap
  4950. {
  4951. my( $host, $port, $mydebugimap, $ssl, $tls, $Side, $mytimeout, $h ) = @_ ;
  4952. my $imap = Mail::IMAPClient->new( ) ;
  4953. if ( $ssl ) { set_ssl( $imap, $h ) }
  4954. $imap->Server( $host ) ;
  4955. $imap->Port( $port ) ;
  4956. $imap->Debug( $mydebugimap ) ;
  4957. $imap->Timeout( $mytimeout ) ;
  4958. my $side = lc $Side ;
  4959. myprint( "$Side: connecting on $side [$host] port [$port]\n" ) ;
  4960. if ( ! $imap->connect( ) )
  4961. {
  4962. $sync->{nb_errors}++ ;
  4963. exit_clean( $sync, $EXIT_CONNECTION_FAILURE,
  4964. "$Side: Can not open imap connection on [$host]: ",
  4965. $imap->LastError,
  4966. " $OS_ERROR\n"
  4967. ) ;
  4968. }
  4969. myprint( "$Side IP address: ", $imap->Socket->peerhost(), "\n" ) ;
  4970. my $banner = $imap->Results()->[0] ;
  4971. myprint( "$Side banner: $banner" ) ;
  4972. myprint( "$Side capability: ", join(q{ }, @{ $imap->capability() || [] }), "\n" ) ;
  4973. if ( $tls ) {
  4974. set_tls( $imap, $h ) ;
  4975. if ( ! $imap->starttls( ) )
  4976. {
  4977. $sync->{nb_errors}++ ;
  4978. exit_clean( $sync, $EXIT_TLS_FAILURE,
  4979. "$Side: Can not go to tls encryption on $side [$host]:",
  4980. $imap->LastError, "\n"
  4981. ) ;
  4982. }
  4983. myprint( "$Side: Socket successfuly converted to SSL\n" ) ;
  4984. }
  4985. return( $imap ) ;
  4986. }
  4987. sub login_imap
  4988. {
  4989. my @allargs = @_ ;
  4990. my(
  4991. $host, $port, $user, $domain, $password,
  4992. $mydebugimap, $mytimeout, $fastio,
  4993. $ssl, $tls, $authmech, $authuser, $reconnectretry,
  4994. $proxyauth, $uid, $split, $Side, $h, $mysync ) = @allargs ;
  4995. my $side = lc $Side ;
  4996. myprint( "$Side: connecting and login on $side [$host] port [$port] with user [$user]\n" ) ;
  4997. my $imap = init_imap( @allargs ) ;
  4998. if ( ! $imap->connect() )
  4999. {
  5000. $mysync->{nb_errors}++ ;
  5001. exit_clean( $mysync, $EXIT_CONNECTION_FAILURE,
  5002. "$Side failure: can not open imap connection on $side [$host] with user [$user]: ",
  5003. $imap->LastError . " $OS_ERROR\n"
  5004. ) ;
  5005. }
  5006. myprint( "$Side IP address: ", $imap->Socket->peerhost(), "\n" ) ;
  5007. my $banner = $imap->Results()->[0] ;
  5008. myprint( "$Side banner: $banner" ) ;
  5009. myprint( "$Side capability before authentication: ", join(q{ }, @{ $imap->capability() || [] }), "\n" ) ;
  5010. if ( (! $ssl) and (! defined $tls ) and $imap->has_capability( 'STARTTLS' ) ) {
  5011. myprint( "$Side: going to ssl because STARTTLS is in CAPABILITY. Use --notls1 or --notls2 to avoid that behavior\n" ) ;
  5012. $tls = 1 ;
  5013. }
  5014. if ( $authmech eq 'PREAUTH' ) {
  5015. if ( $imap->IsAuthenticated( ) ) {
  5016. $imap->Socket ;
  5017. myprintf("%s: Assuming PREAUTH for %s\n", $Side, $imap->Server ) ;
  5018. }else{
  5019. $mysync->{nb_errors}++ ;
  5020. exit_clean(
  5021. $mysync, $EXIT_AUTHENTICATION_FAILURE,
  5022. "$Side failure: error login on $side [$host] with user [$user] auth [PREAUTH]\n"
  5023. ) ;
  5024. }
  5025. }
  5026. if ( $tls ) {
  5027. set_tls( $imap, $h ) ;
  5028. if ( ! $imap->starttls( ) )
  5029. {
  5030. $mysync->{nb_errors}++ ;
  5031. exit_clean( $mysync, $EXIT_TLS_FAILURE,
  5032. "$Side failure: Can not go to tls encryption on $side [$host]:",
  5033. $imap->LastError, "\n"
  5034. ) ;
  5035. }
  5036. myprint( "$Side: Socket successfuly converted to SSL\n" ) ;
  5037. }
  5038. authenticate_imap( $imap, @allargs ) ;
  5039. myprint( "$Side: success login on [$host] with user [$user] auth [$authmech]\n" ) ;
  5040. return( $imap ) ;
  5041. }
  5042. sub authenticate_imap
  5043. {
  5044. my( $imap,
  5045. $host, $port, $user, $domain, $password,
  5046. $mydebugimap, $mytimeout, $fastio,
  5047. $ssl, $tls, $authmech, $authuser, $reconnectretry,
  5048. $proxyauth, $uid, $split, $Side, $h, $mysync ) = @_ ;
  5049. check_capability( $imap, $authmech, $Side ) ;
  5050. $imap->User( $user ) ;
  5051. $imap->Domain( $domain ) if ( defined $domain ) ;
  5052. $imap->Authuser( $authuser ) ;
  5053. $imap->Password( $password ) ;
  5054. if ( 'X-MASTERAUTH' eq $authmech )
  5055. {
  5056. xmasterauth( $imap ) ;
  5057. return ;
  5058. }
  5059. if ( $proxyauth ) {
  5060. $imap->Authmechanism(q{}) ;
  5061. $imap->User( $authuser ) ;
  5062. } else {
  5063. $imap->Authmechanism( $authmech ) unless ( $authmech eq 'LOGIN' or $authmech eq 'PREAUTH' ) ;
  5064. }
  5065. $imap->Authcallback(\&xoauth) if ( 'XOAUTH' eq $authmech ) ;
  5066. $imap->Authcallback(\&xoauth2) if ( 'XOAUTH2' eq $authmech ) ;
  5067. $imap->Authcallback(\&plainauth) if ( ( 'PLAIN' eq $authmech ) or ( 'EXTERNAL' eq $authmech ) ) ;
  5068. unless ( $authmech eq 'PREAUTH' or $imap->login( ) ) {
  5069. my $info = "$Side failure: Error login on [$host] with user [$user] auth" ;
  5070. my $einfo = $imap->LastError || @{$imap->History}[$LAST] ;
  5071. chomp $einfo ;
  5072. my $error = "$info [$authmech]: $einfo\n" ;
  5073. if ( ( $authmech eq 'LOGIN' ) or $imap->IsUnconnected( ) or $authuser ) {
  5074. $authuser ||= "" ;
  5075. myprint( "$Side info: authmech [$authmech] user [$user] authuser [$authuser] IsUnconnected [", $imap->IsUnconnected( ), "]\n" ) ;
  5076. $mysync->{nb_errors}++ ;
  5077. exit_clean( $mysync, $EXIT_AUTHENTICATION_FAILURE, $error ) ;
  5078. }else{
  5079. myprint( $error ) ;
  5080. }
  5081. # It is not secure to try plain text LOGIN when another authmech failed
  5082. # but I do it.
  5083. # I shell remove this code one day.
  5084. myprint( "$Side info: trying LOGIN Auth mechanism on [$host] with user [$user]\n" ) ;
  5085. $imap->Authmechanism(q{}) ;
  5086. if ( ! $imap->login( ) )
  5087. {
  5088. $mysync->{nb_errors}++ ;
  5089. exit_clean( $mysync, $EXIT_AUTHENTICATION_FAILURE,
  5090. "$info [LOGIN]: ",
  5091. $imap->LastError, "\n"
  5092. ) ;
  5093. }
  5094. }
  5095. if ( $proxyauth ) {
  5096. if ( ! $imap->proxyauth( $user ) ) {
  5097. my $info = "$Side failure: Error doing proxyauth as user [$user] on [$host] using proxy-login as [$authuser]" ;
  5098. my $einfo = $imap->LastError || @{$imap->History}[$LAST] ;
  5099. chomp $einfo ;
  5100. $mysync->{nb_errors}++ ;
  5101. exit_clean( $mysync,
  5102. $EXIT_AUTHENTICATION_FAILURE,
  5103. "$info: $einfo\n"
  5104. ) ;
  5105. }
  5106. }
  5107. return ;
  5108. }
  5109. sub check_capability
  5110. {
  5111. my( $imap, $authmech, $Side ) = @_ ;
  5112. if ( $imap->has_capability( "AUTH=$authmech" )
  5113. or $imap->has_capability( $authmech ) )
  5114. {
  5115. myprintf("%s: %s says it has CAPABILITY for AUTHENTICATE %s\n",
  5116. $Side, $imap->Server, $authmech) ;
  5117. return ;
  5118. }
  5119. if ( $authmech eq 'LOGIN' )
  5120. {
  5121. # Well, the warning is so common and useless that I prefer to remove it
  5122. # No more "... says it has NO CAPABILITY for AUTHENTICATE LOGIN"
  5123. return ;
  5124. }
  5125. myprintf( "%s: %s says it has NO CAPABILITY for AUTHENTICATE %s\n",
  5126. $Side, $imap->Server, $authmech ) ;
  5127. if ( $authmech eq 'PLAIN' )
  5128. {
  5129. myprint( "$Side: frequently PLAIN is only supported with SSL, try --ssl or --tls options\n" ) ;
  5130. }
  5131. return ;
  5132. }
  5133. sub set_ssl
  5134. {
  5135. my ( $imap, $h ) = @_ ;
  5136. # SSL_version can be
  5137. # SSLv3 SSLv2 SSLv23 SSLv23:!SSLv2 (last one is the default in IO-Socket-SSL-1.953)
  5138. #
  5139. my $sslargs_hash = $h->{sslargs} ;
  5140. my $sslargs_default = {
  5141. SSL_verify_mode => $SSL_VERIFY_POLICY,
  5142. SSL_verifycn_scheme => 'imap',
  5143. SSL_cipher_list => 'DEFAULT:!DH',
  5144. } ;
  5145. # initiate with default values
  5146. my %sslargs_mix = %{ $sslargs_default } ;
  5147. # now override with passed values
  5148. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  5149. # remove keys with undef values
  5150. foreach my $key ( keys %sslargs_mix ) {
  5151. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  5152. }
  5153. # back to an ARRAY
  5154. my @sslargs_mix = %sslargs_mix ;
  5155. #myprint( Data::Dumper->Dump( [ $sslargs_hash, $sslargs_default, \%sslargs_mix, \@sslargs_mix ] ) ) ;
  5156. $imap->Ssl( \@sslargs_mix ) ;
  5157. return ;
  5158. }
  5159. sub set_tls
  5160. {
  5161. my ( $imap, $h ) = @_ ;
  5162. my $sslargs_hash = $h->{sslargs} ;
  5163. my $sslargs_default = {
  5164. SSL_verify_mode => $SSL_VERIFY_POLICY,
  5165. SSL_cipher_list => 'DEFAULT:!DH',
  5166. } ;
  5167. # initiate with default values
  5168. my %sslargs_mix = %{ $sslargs_default } ;
  5169. # now override with passed values
  5170. @sslargs_mix{ keys %{ $sslargs_hash } } = values %{ $sslargs_hash } ;
  5171. # remove keys with undef values
  5172. foreach my $key ( keys %sslargs_mix ) {
  5173. delete $sslargs_mix{ $key } if ( not defined $sslargs_mix{ $key } ) ;
  5174. }
  5175. # back to an ARRAY
  5176. my @sslargs_mix = %sslargs_mix ;
  5177. $imap->Starttls( \@sslargs_mix ) ;
  5178. return ;
  5179. }
  5180. sub init_imap
  5181. {
  5182. my(
  5183. $host, $port, $user, $domain, $password,
  5184. $mydebugimap, $mytimeout, $fastio,
  5185. $ssl, $tls, $authmech, $authuser, $reconnectretry,
  5186. $proxyauth, $uid, $split, $Side, $h, $mysync ) = @_ ;
  5187. my ( $imap ) ;
  5188. $imap = Mail::IMAPClient->new() ;
  5189. if ( $mysync->{ tee } )
  5190. {
  5191. # Well, it does not change anything, does it?
  5192. # It does when suppressing the hack with *STDERR
  5193. $imap->Debug_fh( $mysync->{ tee } ) ;
  5194. }
  5195. if ( $ssl ) { set_ssl( $imap, $h ) }
  5196. if ( $tls ) { } # can not do set_tls() here because connect() will directly do a STARTTLS
  5197. $imap->Clear(1);
  5198. $imap->Server($host);
  5199. $imap->Port($port);
  5200. $imap->Fast_io($fastio);
  5201. $imap->Buffer($buffersize || $DEFAULT_BUFFER_SIZE);
  5202. $imap->Uid($uid);
  5203. $imap->Peek(1);
  5204. $imap->Debug($mydebugimap);
  5205. if ( $mysync->{ showpasswords } ) {
  5206. $imap->Showcredentials( 1 ) ;
  5207. }
  5208. defined $mytimeout and $imap->Timeout( $mytimeout ) ;
  5209. $imap->Reconnectretry( $reconnectretry ) if ( $reconnectretry ) ;
  5210. $imap->{IMAPSYNC_RECONNECT_COUNT} = 0 ;
  5211. $imap->Ignoresizeerrors( $allowsizemismatch ) ;
  5212. $split and $imap->Maxcommandlength( $SPLIT_FACTOR * $split ) ;
  5213. return( $imap ) ;
  5214. }
  5215. sub plainauth
  5216. {
  5217. my $code = shift;
  5218. my $imap = shift;
  5219. my $string = mysprintf("%s\x00%s\x00%s", $imap->User,
  5220. $imap->Authuser, $imap->Password);
  5221. return encode_base64("$string", q{});
  5222. }
  5223. # Copy from https://github.com/imapsync/imapsync/pull/25/files
  5224. # Changes "use" pragmas to "require".
  5225. # The openssl system call shall be replaced by pure Perl and
  5226. # https://metacpan.org/pod/Crypt::OpenSSL::PKCS12
  5227. # Now the Joaquin Lopez code:
  5228. #
  5229. # Used this as an example: https://gist.github.com/gsainio/6322375
  5230. #
  5231. # And this as a reference: https://developers.google.com/accounts/docs/OAuth2ServiceAccount
  5232. # (note there is an http/rest tab, where the real info is hidden away... went on a witch hunt
  5233. # until I noticed that...)
  5234. #
  5235. # This is targeted at gmail to maintain compatibility after google's oauth1 service is deactivated
  5236. # on May 5th, 2015: https://developers.google.com/gmail/oauth_protocol
  5237. # If there are other oauth2 implementations out there, this would need to be modified to be
  5238. # compatible
  5239. #
  5240. # This is a good guide on setting up the google api/apps side of the equation:
  5241. # http://www.limilabs.com/blog/oauth2-gmail-imap-service-account
  5242. #
  5243. # 2016/05/27: Updated to support oauth/key data in the .json files Google now defaults to
  5244. # when creating gmail service accounts. They're easier to work with since they neither
  5245. # requiring decrypting nor specifying the oauth2 client id separately.
  5246. #
  5247. # If the password arg ends in .json, it will assume this new json method, otherwise it
  5248. # will fallback to the "oauth client id;.p12" format it was previously using.
  5249. sub xoauth2
  5250. {
  5251. require JSON::WebToken ;
  5252. require LWP::UserAgent ;
  5253. require HTML::Entities ;
  5254. require JSON ;
  5255. require JSON::WebToken::Crypt::RSA ;
  5256. require Crypt::OpenSSL::RSA ;
  5257. require Encode::Byte ;
  5258. require IO::Socket::SSL ;
  5259. my $code = shift;
  5260. my $imap = shift;
  5261. my ($iss,$key);
  5262. if( $imap->Password =~ /^(.*\.json)$/x )
  5263. {
  5264. my $json = JSON->new( ) ;
  5265. my $filename = $1;
  5266. $sync->{ debug } and myprint( "XOAUTH2 json file: $filename\n" ) ;
  5267. my $FILE ;
  5268. if ( ! open( $FILE, '<', $filename ) )
  5269. {
  5270. $sync->{nb_errors}++ ;
  5271. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  5272. "error [$filename]: $OS_ERROR\n"
  5273. ) ;
  5274. }
  5275. my $jsonfile = $json->decode( join q{}, <$FILE> ) ;
  5276. close $FILE ;
  5277. $iss = $jsonfile->{client_id};
  5278. $key = $jsonfile->{private_key};
  5279. $sync->{ debug } and myprint( "Service account: $iss\n");
  5280. $sync->{ debug } and myprint( "Private key:\n$key\n");
  5281. }
  5282. else
  5283. {
  5284. # Get iss (service account address), keyfile name, and keypassword if necessary
  5285. ( $iss, my $keyfile, my $keypass ) = $imap->Password =~ /([\-\d\w\@\.]+);([a-zA-Z0-9 \_\-\.\/]+);?(.*)?/x ;
  5286. # Assume key password is google default if not provided
  5287. $keypass = 'notasecret' if not $keypass;
  5288. $sync->{ debug } and myprint( "Service account: $iss\nKey file: $keyfile\nKey password: $keypass\n");
  5289. # Get private key from p12 file (would be better in perl...)
  5290. $key = `openssl pkcs12 -in "$keyfile" -nodes -nocerts -passin pass:$keypass -nomacver`;
  5291. $sync->{ debug } and myprint( "Private key:\n$key\n");
  5292. }
  5293. # Create jwt of oauth2 request
  5294. my $time = time ;
  5295. my $jwt = JSON::WebToken->encode( {
  5296. 'iss' => $iss, # service account
  5297. 'scope' => 'https://mail.google.com/',
  5298. 'aud' => 'https://www.googleapis.com/oauth2/v3/token',
  5299. 'exp' => $time + $DEFAULT_EXPIRATION_TIME_OAUTH2_PK12,
  5300. 'iat' => $time,
  5301. 'prn' => $imap->User # user to auth as
  5302. },
  5303. $key, 'RS256', {'typ' => 'JWT'} ); # Crypt::OpenSSL::RSA needed here.
  5304. # Post oauth2 request
  5305. my $ua = LWP::UserAgent->new( ) ;
  5306. $ua->env_proxy( ) ;
  5307. my $response = $ua->post('https://www.googleapis.com/oauth2/v3/token',
  5308. { grant_type => HTML::Entities::encode_entities('urn:ietf:params:oauth:grant-type:jwt-bearer'),
  5309. assertion => $jwt } ) ;
  5310. unless( $response->is_success( ) ) {
  5311. $sync->{nb_errors}++ ;
  5312. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  5313. $response->code, "\n", $response->content, "\n"
  5314. ) ;
  5315. }else{
  5316. $sync->{ debug } and myprint( $response->content ) ;
  5317. }
  5318. # access_token in response is what we need
  5319. my $data = JSON::decode_json( $response->content ) ;
  5320. # format as oauth2 auth data
  5321. my $xoauth2_string = encode_base64( 'user=' . $imap->User . "\1auth=Bearer " . $data->{access_token} . "\1\1", q{} ) ;
  5322. $sync->{ debug } and myprint( "XOAUTH2 String: $xoauth2_string\n");
  5323. return($xoauth2_string);
  5324. }
  5325. # xoauth() thanks to Eduardo Bortoluzzi Junior
  5326. sub xoauth
  5327. {
  5328. require URI::Escape ;
  5329. require Data::Uniqid ;
  5330. my $code = shift;
  5331. my $imap = shift;
  5332. # The base information needed to construct the OAUTH authentication
  5333. my $method = 'GET' ;
  5334. my $url = mysprintf( 'https://mail.google.com/mail/b/%s/imap/', $imap->User ) ;
  5335. my $urlparm = mysprintf( 'xoauth_requestor_id=%s', URI::Escape::uri_escape( $imap->User ) ) ;
  5336. # For Google Apps, the consumer key is the primary domain
  5337. # TODO: create a command line argument to define the consumer key
  5338. my @user_parts = split /@/x, $imap->User ;
  5339. $sync->{ debug } and myprint( "XOAUTH: consumer key: $user_parts[1]\n" ) ;
  5340. # All the parameters needed to be signed on the XOAUTH
  5341. my %hash = ();
  5342. $hash { 'xoauth_requestor_id' } = URI::Escape::uri_escape($imap->User);
  5343. $hash { 'oauth_consumer_key' } = $user_parts[1];
  5344. $hash { 'oauth_nonce' } = md5_hex(Data::Uniqid::uniqid(rand(), 1==1));
  5345. $hash { 'oauth_signature_method' } = 'HMAC-SHA1';
  5346. $hash { 'oauth_timestamp' } = time ;
  5347. $hash { 'oauth_version' } = '1.0';
  5348. # Base will hold the string to be signed
  5349. my $base = "$method&" . URI::Escape::uri_escape( $url ) . q{&} ;
  5350. # The parameters must be in dictionary order before signing
  5351. my $baseparms = q{} ;
  5352. foreach my $key ( sort keys %hash ) {
  5353. if ( length( $baseparms ) > 0 ) {
  5354. $baseparms .= q{&} ;
  5355. }
  5356. $baseparms .= "$key=$hash{$key}" ;
  5357. }
  5358. $base .= URI::Escape::uri_escape($baseparms);
  5359. $sync->{ debug } and myprint( "XOAUTH: base request to sign: $base\n" ) ;
  5360. # Sign it with the consumer secret, informed on the command line (password)
  5361. my $digest = hmac_sha1( $base, URI::Escape::uri_escape( $imap->Password ) . q{&} ) ;
  5362. # The parameters signed become a parameter and...
  5363. $hash { 'oauth_signature' } = URI::Escape::uri_escape( substr encode_base64( $digest ), 0, $MINUS_ONE ) ;
  5364. # ... we don't need the requestor_id anymore.
  5365. delete $hash{'xoauth_requestor_id'} ;
  5366. # Create the final authentication string
  5367. my $string = $method . q{ } . $url . q{?} . $urlparm .q{ } ;
  5368. # All the parameters must be sorted
  5369. $baseparms = q{};
  5370. foreach my $key (sort keys %hash) {
  5371. if(length($baseparms)>0) {
  5372. $baseparms .= q{,} ;
  5373. }
  5374. $baseparms .= "$key=\"$hash{$key}\"";
  5375. }
  5376. $string .= $baseparms;
  5377. $sync->{ debug } and myprint( "XOAUTH: authentication string: $string\n" ) ;
  5378. # It must be base64 encoded
  5379. return encode_base64("$string", q{});
  5380. }
  5381. sub xmasterauth
  5382. {
  5383. # This is Kerio auth admin
  5384. # This code comes from
  5385. # https://github.com/imapsync/imapsync/pull/53/files
  5386. my $imap = shift ;
  5387. my $user = $imap->User( ) ;
  5388. my $password = $imap->Password( ) ;
  5389. my $authmech = 'X-MASTERAUTH' ;
  5390. my @challenge = $imap->tag_and_run( $authmech, "+" ) ;
  5391. if ( not defined $challenge[0] )
  5392. {
  5393. $sync->{nb_errors}++ ;
  5394. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  5395. "Failure authenticate with $authmech: ",
  5396. $imap->LastError, "\n"
  5397. ) ;
  5398. return ; # hahaha!
  5399. }
  5400. $sync->{ debug } and myprint( "X-MASTERAUTH challenge: [@challenge]\n" ) ;
  5401. $challenge[1] =~ s/^\+ |^\s+|\s+$//g ;
  5402. if ( ! $imap->_imap_command( { addcrlf => 1, addtag => 0, tag => $imap->Count }, md5_hex( $challenge[1] . $password ) ) )
  5403. {
  5404. $sync->{nb_errors}++ ;
  5405. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  5406. "Failure authenticate with $authmech: ",
  5407. $imap->LastError, "\n"
  5408. ) ;
  5409. }
  5410. if ( ! $imap->tag_and_run( 'X-SETUSER ' . $user ) )
  5411. {
  5412. $sync->{nb_errors}++ ;
  5413. exit_clean( $sync, $EXIT_AUTHENTICATION_FAILURE,
  5414. "Failure authenticate with $authmech: ",
  5415. "X-SETUSER ", $imap->LastError, "\n"
  5416. ) ;
  5417. }
  5418. $imap->State( Mail::IMAPClient::Authenticated ) ;
  5419. # I comment this state because "Selected" state is usually done by SELECT or EXAMINE imap commands
  5420. # $imap->State( Mail::IMAPClient::Selected ) ;
  5421. return ;
  5422. }
  5423. sub tests_do_valid_directory
  5424. {
  5425. note( 'Entering tests_do_valid_directory()' ) ;
  5426. Readonly my $NB_UNIX_tests_do_valid_directory => 2 ;
  5427. SKIP: {
  5428. skip( 'Tests only for Unix', $NB_UNIX_tests_do_valid_directory ) if ( 'MSWin32' eq $OSNAME ) ;
  5429. ok( 1 == do_valid_directory( '.'), 'do_valid_directory: . good' ) ;
  5430. ok( 1 == do_valid_directory( './W/tmp/tests/valid/sub'), 'do_valid_directory: ./W/tmp/tests/valid/sub good' ) ;
  5431. }
  5432. Readonly my $NB_UNIX_tests_do_valid_directory_non_root => 2 ;
  5433. SKIP: {
  5434. skip( 'Tests only for Unix', $NB_UNIX_tests_do_valid_directory_non_root ) if ( 'MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) ;
  5435. diag( 'Error / not writable is on purpose' ) ;
  5436. ok( 0 == do_valid_directory( '/'), 'do_valid_directory: / bad' ) ;
  5437. diag( 'Error permission denied on /noway is on purpose' ) ;
  5438. ok( 0 == do_valid_directory( '/noway'), 'do_valid_directory: /noway bad' ) ;
  5439. }
  5440. note( 'Leaving tests_do_valid_directory()' ) ;
  5441. return ;
  5442. }
  5443. sub banner_imapsync
  5444. {
  5445. my $mysync = shift @ARG ;
  5446. my @argv = @ARG ;
  5447. my $banner_imapsync = join q{},
  5448. q{$RCSfile: imapsync,v $ },
  5449. q{$Revision: 1.977 $ },
  5450. q{$Date: 2019/12/23 20:18:02 $ },
  5451. "\n",
  5452. "Command line used, run by $EXECUTABLE_NAME:\n",
  5453. "$PROGRAM_NAME ", command_line_nopassword( $mysync, @argv ), "\n" ;
  5454. return( $banner_imapsync ) ;
  5455. }
  5456. sub do_valid_directory
  5457. {
  5458. my $dir = shift @ARG ;
  5459. # all good => return ok.
  5460. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  5461. # exist but bad
  5462. if ( -e $dir and not -d _ ) {
  5463. myprint( "Error: $dir exists but is not a directory\n" ) ;
  5464. return( 0 ) ;
  5465. }
  5466. if ( -e $dir and not -w _ ) {
  5467. my $sb = stat $dir ;
  5468. myprintf( "Error: directory %s is not writable for user %s, permissions are %04o and owner is %s ( uid %s )\n",
  5469. $dir, getpwuid_any_os( $EFFECTIVE_USER_ID ), ($sb->mode & oct($PERMISSION_FILTER) ), getpwuid_any_os( $sb->uid ), $sb->uid( ) ) ;
  5470. return( 0 ) ;
  5471. }
  5472. # Trying to create it
  5473. myprint( "Creating directory $dir\n" ) ;
  5474. if ( ! eval { mkpath( $dir ) } ) {
  5475. myprint( "$EVAL_ERROR" ) if ( $EVAL_ERROR ) ;
  5476. }
  5477. return( 1 ) if ( -d $dir and -r _ and -w _ ) ;
  5478. return( 0 ) ;
  5479. }
  5480. sub tests_match_a_pid_number
  5481. {
  5482. note( 'Entering tests_match_a_pid_number()' ) ;
  5483. is( undef, match_a_pid_number( ), 'match_a_pid_number: no args => undef' ) ;
  5484. is( undef, match_a_pid_number( q{} ), 'match_a_pid_number: "" => undef' ) ;
  5485. is( undef, match_a_pid_number( 'lalala' ), 'match_a_pid_number: lalala => undef' ) ;
  5486. is( 1, match_a_pid_number( 1 ), 'match_a_pid_number: 1 => 1' ) ;
  5487. is( 1, match_a_pid_number( 123 ), 'match_a_pid_number: 123 => 1' ) ;
  5488. is( 1, match_a_pid_number( -123 ), 'match_a_pid_number: -123 => 1' ) ;
  5489. is( 1, match_a_pid_number( '123' ), 'match_a_pid_number: "123" => 1' ) ;
  5490. is( 1, match_a_pid_number( '-123' ), 'match_a_pid_number: "-123" => 1' ) ;
  5491. is( undef, match_a_pid_number( 'a123' ), 'match_a_pid_number: a123 => undef' ) ;
  5492. is( undef, match_a_pid_number( '-a123' ), 'match_a_pid_number: -a123 => undef' ) ;
  5493. is( 1, match_a_pid_number( 99999 ), 'match_a_pid_number: 99999 => 1' ) ;
  5494. is( 1, match_a_pid_number( -99999 ), 'match_a_pid_number: -99999 => 1' ) ;
  5495. is( undef, match_a_pid_number( 0 ), 'match_a_pid_number: 0 => undef' ) ;
  5496. is( undef, match_a_pid_number( 100000 ), 'match_a_pid_number: 100000 => undef' ) ;
  5497. is( undef, match_a_pid_number( 123456 ), 'match_a_pid_number: 123456 => undef' ) ;
  5498. is( undef, match_a_pid_number( '-0' ), 'match_a_pid_number: "-0" => undef' ) ;
  5499. is( undef, match_a_pid_number( -100000 ), 'match_a_pid_number: -100000 => undef' ) ;
  5500. is( undef, match_a_pid_number( -123456 ), 'match_a_pid_number: -123456 => undef' ) ;
  5501. note( 'Leaving tests_match_a_pid_number()' ) ;
  5502. return ;
  5503. }
  5504. sub match_a_pid_number
  5505. {
  5506. my $pid = shift @ARG ;
  5507. if ( ! defined $pid ) { return ; }
  5508. #print "$pid\n" ;
  5509. if ( ! match( $pid, '^-?\d+$' ) ) { return ; }
  5510. #print "$pid\n" ;
  5511. # can be negative on Windows
  5512. #if ( 0 > $pid ) { return ; }
  5513. #if ( 65535 < $pid ) { return ; }
  5514. if ( 99999 < abs( $pid ) ) { return ; }
  5515. if ( 0 == abs( $pid ) ) { return ; }
  5516. return 1 ;
  5517. }
  5518. sub tests_remove_pidfile_not_running
  5519. {
  5520. note( 'Entering tests_remove_pidfile_not_running()' ) ;
  5521. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'remove_pidfile_not_running: mkpath W/tmp/tests/' ) ;
  5522. is( undef, remove_pidfile_not_running( ), 'remove_pidfile_not_running: no args => undef' ) ;
  5523. is( undef, remove_pidfile_not_running( './W' ), 'remove_pidfile_not_running: a dir => undef' ) ;
  5524. is( undef, remove_pidfile_not_running( 'noexists' ), 'remove_pidfile_not_running: noexists => undef' ) ;
  5525. is( 1, touch( 'W/tmp/tests/empty.pid' ), 'remove_pidfile_not_running: prepa empty W/tmp/tests/empty.pid' ) ;
  5526. is( undef, remove_pidfile_not_running( 'W/tmp/tests/empty.pid' ), 'remove_pidfile_not_running: W/tmp/tests/empty.pid => undef' ) ;
  5527. is( 'lalala', string_to_file( 'lalala', 'W/tmp/tests/lalala.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/lalala.pid' ) ;
  5528. is( undef, remove_pidfile_not_running( 'W/tmp/tests/lalala.pid' ), 'remove_pidfile_not_running: W/tmp/tests/lalala.pid => undef' ) ;
  5529. is( '55555', string_to_file( '55555', 'W/tmp/tests/notrunning.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/notrunning.pid' ) ;
  5530. is( 1, remove_pidfile_not_running( 'W/tmp/tests/notrunning.pid' ), 'remove_pidfile_not_running: W/tmp/tests/notrunning.pid => 1' ) ;
  5531. is( $PROCESS_ID, string_to_file( $PROCESS_ID, 'W/tmp/tests/running.pid' ), 'remove_pidfile_not_running: prepa W/tmp/tests/running.pid' ) ;
  5532. is( undef, remove_pidfile_not_running( 'W/tmp/tests/running.pid' ), 'remove_pidfile_not_running: W/tmp/tests/running.pid => undef' ) ;
  5533. note( 'Leaving tests_remove_pidfile_not_running()' ) ;
  5534. return ;
  5535. }
  5536. sub remove_pidfile_not_running
  5537. {
  5538. #
  5539. my $pid_filename = shift @ARG ;
  5540. if ( ! $pid_filename ) { myprint( "No variable pid_filename\n" ) ; return } ;
  5541. if ( ! -e $pid_filename ) { myprint( "File $pid_filename does not exist\n" ) ; return } ;
  5542. if ( ! -f $pid_filename ) { myprint( "File $pid_filename is not a file\n" ) ; return } ;
  5543. my $pid = firstline( $pid_filename ) ;
  5544. if ( ! match_a_pid_number( $pid ) ) { myprint( "pid $pid in $pid_filename is not a number\n" ) ; return } ;
  5545. # can't kill myself => do nothing
  5546. if ( ! kill 'ZERO', $PROCESS_ID ) { myprint( "Can not kill ZERO myself $PROCESS_ID\n" ) ; return } ;
  5547. # can't kill ZERO the pid => it is gone or own by another user => remove pidfile
  5548. if ( ! kill 'ZERO', $pid ) {
  5549. myprint( "Removing old $pid_filename since its PID $pid is not running anymore (oo-killed?)\n" ) ;
  5550. if ( unlink $pid_filename ) {
  5551. myprint( "Removed old $pid_filename\n" ) ;
  5552. return 1 ;
  5553. }else{
  5554. myprint( "Could not remove old $pid_filename because $!\n" ) ;
  5555. return ;
  5556. }
  5557. }
  5558. myprint( "Another imapsync process $pid is running as says pidfile $pid_filename\n" ) ;
  5559. return ;
  5560. }
  5561. sub tests_tail
  5562. {
  5563. note( 'Entering tests_tail()' ) ;
  5564. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'tail: mkpath W/tmp/tests/' ) ;
  5565. ok( ( ! -e 'W/tmp/tests/tail.pid' || unlink 'W/tmp/tests/tail.pid' ), 'tail: unlink W/tmp/tests/tail.pid' ) ;
  5566. ok( ( ! -e 'W/tmp/tests/tail.txt' || unlink 'W/tmp/tests/tail.txt' ), 'tail: unlink W/tmp/tests/tail.txt' ) ;
  5567. is( undef, tail( ), 'tail: no args => undef' ) ;
  5568. my $mysync ;
  5569. is( undef, tail( $mysync ), 'tail: no pidfile => undef' ) ;
  5570. $mysync->{pidfile} = 'W/tmp/tests/tail.pid' ;
  5571. is( undef, tail( $mysync ), 'tail: no pidfilelocking => undef' ) ;
  5572. $mysync->{pidfilelocking} = 1 ;
  5573. is( undef, tail( $mysync ), 'tail: pidfile no exists => undef' ) ;
  5574. my $pidandlog = "33333\nW/tmp/tests/tail.txt\n" ;
  5575. is( $pidandlog, string_to_file( $pidandlog, $mysync->{pidfile} ), 'tail: put pid 33333 and tail.txt in pidfile' ) ;
  5576. is( undef, tail( $mysync ), 'tail: logfile to tail no exists => undef' ) ;
  5577. my $tailcontent = "L1\nL2\nL3\nL4\nL5\n" ;
  5578. is( $tailcontent, string_to_file( $tailcontent, 'W/tmp/tests/tail.txt' ),
  5579. 'tail: put L1\nL2\nL3\nL4\nL5\n in W/tmp/tests/tail.txt' ) ;
  5580. is( undef, tail( $mysync ), 'tail: fake pid in pidfile + tail off => 1' ) ;
  5581. $mysync->{ tail } = 1 ;
  5582. is( 1, tail( $mysync ), 'tail: fake pid in pidfile + tail on=> 1' ) ;
  5583. # put my own pid, won't do tail
  5584. $pidandlog = "$PROCESS_ID\nW/tmp/tests/tail.txt\n" ;
  5585. is( $pidandlog, string_to_file( $pidandlog, $mysync->{pidfile} ), 'tail: put my own PID in pidfile' ) ;
  5586. is( undef, tail( $mysync ), 'tail: my own pid in pidfile => undef' ) ;
  5587. note( 'Leaving tests_tail()' ) ;
  5588. return ;
  5589. }
  5590. sub tail
  5591. {
  5592. # return undef on failures
  5593. # return 1 on success
  5594. my $mysync = shift ;
  5595. # no tail when aborting!
  5596. if ( $mysync->{ abort } ) { return ; }
  5597. my $pidfile = $mysync->{pidfile} ;
  5598. my $lock = $mysync->{pidfilelocking} ;
  5599. my $tail = $mysync->{tail} ;
  5600. if ( ! $pidfile ) { return ; }
  5601. if ( ! $lock ) { return ; }
  5602. if ( ! $tail ) { return ; }
  5603. my $pidtotail = firstline( $pidfile ) ;
  5604. if ( ! $pidtotail ) { return ; }
  5605. # It should not happen but who knows...
  5606. if ( $pidtotail eq $PROCESS_ID ) { return ; }
  5607. my $filetotail = secondline( $pidfile ) ;
  5608. if ( ! $filetotail ) { return ; }
  5609. if ( ! -r $filetotail )
  5610. {
  5611. #myprint( "Error: can not read $filetotail\n" ) ;
  5612. return ;
  5613. }
  5614. myprint( "Doing a tail -f on $filetotail for processus pid $pidtotail until it is finished.\n" ) ;
  5615. my $file = File::Tail->new(
  5616. name => $filetotail,
  5617. nowait => 1,
  5618. interval => 1,
  5619. tail => 1,
  5620. adjustafter => 2
  5621. );
  5622. my $moretimes = 200 ;
  5623. # print one line at least
  5624. my $line = $file->read ;
  5625. myprint( $line ) ;
  5626. while ( isrunning( $pidtotail, \$moretimes ) and defined( $line = $file->read ) )
  5627. {
  5628. myprint( $line );
  5629. sleep( 0.02 ) ;
  5630. }
  5631. return 1 ;
  5632. }
  5633. sub isrunning
  5634. {
  5635. my $pidtocheck = shift ;
  5636. my $moretimes_ref = shift ;
  5637. if ( kill 'ZERO', $pidtocheck )
  5638. {
  5639. #myprint( "$pidtocheck running\n" ) ;
  5640. return 1 ;
  5641. }
  5642. elsif ( $$moretimes_ref >= 0 )
  5643. {
  5644. # continue to consider it running
  5645. $$moretimes_ref-- ;
  5646. return 1 ;
  5647. }
  5648. else
  5649. {
  5650. myprint( "Tailed processus $pidtocheck ended\n" ) ;
  5651. return ;
  5652. }
  5653. }
  5654. sub tests_write_pidfile
  5655. {
  5656. note( 'Entering tests_write_pidfile()' ) ;
  5657. my $mysync ;
  5658. is( 1, write_pidfile( ), 'write_pidfile: no args => 1' ) ;
  5659. # no pidfile => ok
  5660. $mysync->{pidfile} = q{} ;
  5661. is( 1, write_pidfile( $mysync ), 'write_pidfile: no pidfile => undef' ) ;
  5662. # The pidfile path is bad => failure
  5663. $mysync->{pidfile} = '/no/no/no.pid' ;
  5664. is( undef, write_pidfile( $mysync ), 'write_pidfile: no permission for /no/no/no.pid, no lock => undef' ) ;
  5665. $mysync->{pidfilelocking} = 1 ;
  5666. is( undef, write_pidfile( $mysync ), 'write_pidfile: no permission for /no/no/no.pid + lock => undef' ) ;
  5667. $mysync->{pidfile} = 'W/tmp/tests/test.pid' ;
  5668. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'write_pidfile: mkpath W/tmp/tests/' ) ;
  5669. is( 1, touch( $mysync->{pidfile} ), 'write_pidfile: lock prepa' ) ;
  5670. $mysync->{pidfilelocking} = 0 ;
  5671. is( 1, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + no lock => 1' ) ;
  5672. is( $PROCESS_ID, firstline( 'W/tmp/tests/test.pid' ), "write_pidfile: W/tmp/tests/test.pid contains $PROCESS_ID" ) ;
  5673. is( q{}, secondline( 'W/tmp/tests/test.pid' ), "write_pidfile: W/tmp/tests/test.pid contains no second line" ) ;
  5674. $mysync->{pidfilelocking} = 1 ;
  5675. is( undef, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + lock => undef' ) ;
  5676. $mysync->{pidfilelocking} = 0 ;
  5677. $mysync->{ logfile } = 'rrrr.txt' ;
  5678. is( 1, write_pidfile( $mysync ), 'write_pidfile: W/tmp/tests/test.pid + no lock + logfile => 1' ) ;
  5679. is( $PROCESS_ID, firstline( 'W/tmp/tests/test.pid' ), "write_pidfile: + no lock + logfile W/tmp/tests/test.pid contains $PROCESS_ID" ) ;
  5680. is( q{rrrr.txt}, secondline( 'W/tmp/tests/test.pid' ), "write_pidfile: + no lock + logfile W/tmp/tests/test.pid contains rrrr.txt" ) ;
  5681. note( 'Leaving tests_write_pidfile()' ) ;
  5682. return ;
  5683. }
  5684. sub write_pidfile
  5685. {
  5686. # returns undef if something is considered fatal
  5687. # returns 1 otherwise
  5688. if ( ! @ARG ) { return 1 ; }
  5689. my $mysync = shift @ARG ;
  5690. # Do not write the pid file if this process goal is to abort the process designed by the pid file
  5691. if ( $mysync->{abort} ) { return 1 ; }
  5692. #
  5693. my $pid_filename = $mysync->{ pidfile } ;
  5694. my $lock = $mysync->{ pidfilelocking } ;
  5695. if ( ! $pid_filename )
  5696. {
  5697. myprint( "PID file is unset ( to set it, use --pidfile filepath ; to avoid it use --pidfile \"\" )\n" ) ;
  5698. return( 1 ) ;
  5699. }
  5700. myprint( "PID file is $pid_filename ( to change it, use --pidfile filepath ; to avoid it use --pidfile \"\" )\n" ) ;
  5701. if ( -e $pid_filename and $lock ) {
  5702. myprint( "$pid_filename already exists, another imapsync may be curently running. Aborting imapsync.\n" ) ;
  5703. return ;
  5704. }
  5705. if ( -e $pid_filename ) {
  5706. myprint( "$pid_filename already exists, overwriting it ( use --pidfilelocking to avoid concurrent runs )\n" ) ;
  5707. }
  5708. my $pid_string = "$PROCESS_ID\n" ;
  5709. my $pid_message = "Writing my PID $PROCESS_ID in $pid_filename\n" ;
  5710. if ( $mysync->{ logfile } )
  5711. {
  5712. $pid_string .= "$mysync->{ logfile }\n" ;
  5713. $pid_message .= "Writing also my logfile name in $pid_filename : $mysync->{ logfile }\n" ;
  5714. }
  5715. if ( open my $FILE_HANDLE, '>', $pid_filename ) {
  5716. myprint( $pid_message ) ;
  5717. print $FILE_HANDLE $pid_string ;
  5718. close $FILE_HANDLE ;
  5719. return( 1 ) ;
  5720. }
  5721. else
  5722. {
  5723. myprint( "Could not open $pid_filename for writing. Check permissions or disk space: $OS_ERROR\n" ) ;
  5724. return ;
  5725. }
  5726. }
  5727. sub fix_Inbox_INBOX_mapping
  5728. {
  5729. my( $h1_all, $h2_all ) = @_ ;
  5730. my $regex = q{} ;
  5731. SWITCH: {
  5732. if ( exists $h1_all->{INBOX} and exists $h2_all->{INBOX} ) { $regex = q{} ; last SWITCH ; } ;
  5733. if ( exists $h1_all->{Inbox} and exists $h2_all->{Inbox} ) { $regex = q{} ; last SWITCH ; } ;
  5734. if ( exists $h1_all->{INBOX} and exists $h2_all->{Inbox} ) { $regex = q{s/^INBOX$/Inbox/x} ; last SWITCH ; } ;
  5735. if ( exists $h1_all->{Inbox} and exists $h2_all->{INBOX} ) { $regex = q{s/^Inbox$/INBOX/x} ; last SWITCH ; } ;
  5736. } ;
  5737. return( $regex ) ;
  5738. }
  5739. sub tests_fix_Inbox_INBOX_mapping
  5740. {
  5741. note( 'Entering tests_fix_Inbox_INBOX_mapping()' ) ;
  5742. my( $h1_all, $h2_all ) ;
  5743. $h1_all = { 'INBOX' => q{} } ;
  5744. $h2_all = { 'INBOX' => q{} } ;
  5745. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX INBOX' ) ;
  5746. $h1_all = { 'Inbox' => q{} } ;
  5747. $h2_all = { 'Inbox' => q{} } ;
  5748. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox Inbox' ) ;
  5749. $h1_all = { 'INBOX' => q{} } ;
  5750. $h2_all = { 'Inbox' => q{} } ;
  5751. ok( q{s/^INBOX$/Inbox/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX Inbox' ) ;
  5752. $h1_all = { 'Inbox' => q{} } ;
  5753. $h2_all = { 'INBOX' => q{} } ;
  5754. ok( q{s/^Inbox$/INBOX/x} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: Inbox INBOX' ) ;
  5755. $h1_all = { 'INBOX' => q{} } ;
  5756. $h2_all = { 'rrrrr' => q{} } ;
  5757. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: INBOX rrrrrr' ) ;
  5758. $h1_all = { 'rrrrr' => q{} } ;
  5759. $h2_all = { 'Inbox' => q{} } ;
  5760. ok( q{} eq fix_Inbox_INBOX_mapping( $h1_all, $h2_all ), 'fix_Inbox_INBOX_mapping: rrrrr Inbox' ) ;
  5761. note( 'Leaving tests_fix_Inbox_INBOX_mapping()' ) ;
  5762. return ;
  5763. }
  5764. sub jux_utf8_list
  5765. {
  5766. my @s_inp = @_ ;
  5767. my $s_out = q{} ;
  5768. foreach my $s ( @s_inp ) {
  5769. $s_out .= jux_utf8( $s ) . "\n" ;
  5770. }
  5771. return( $s_out ) ;
  5772. }
  5773. sub tests_jux_utf8_list
  5774. {
  5775. note( 'Entering tests_jux_utf8_list()' ) ;
  5776. use utf8 ;
  5777. is( q{}, jux_utf8_list( ), 'jux_utf8_list: void' ) ;
  5778. is( "[]\n", jux_utf8_list( q{} ), 'jux_utf8_list: empty string' ) ;
  5779. is( "[INBOX]\n", jux_utf8_list( 'INBOX' ), 'jux_utf8_list: INBOX' ) ;
  5780. is( "[&ANY-] = [Ö]\n", jux_utf8_list( '&ANY-' ), 'jux_utf8_list: [&ANY-] = [Ö]' ) ;
  5781. note( 'Leaving tests_jux_utf8_list()' ) ;
  5782. return( 0 ) ;
  5783. }
  5784. # editing utf8 can be tricky without an utf8 editor
  5785. sub tests_jux_utf8_old
  5786. {
  5787. note( 'Entering tests_jux_utf8_old()' ) ;
  5788. no utf8 ;
  5789. is( '[]', jux_utf8_old( q{} ), 'jux_utf8_old: void => []' ) ;
  5790. is( '[INBOX]', jux_utf8_old( 'INBOX'), 'jux_utf8_old: INBOX => [INBOX]' ) ;
  5791. is( '[&ZTZO9nux-] = [æ”¶ä»¶ç®±]', jux_utf8_old( '&ZTZO9nux-'), 'jux_utf8_old: => [&ZTZO9nux-] = [æ”¶ä»¶ç®±]' ) ;
  5792. is( '[&ANY-] = [Ö]', jux_utf8_old( '&ANY-'), 'jux_utf8_old: &ANY- => [&ANY-] = [Ö]' ) ;
  5793. # +BD8EQAQ1BDQEOwQ+BDM- SHOULD stay as is!
  5794. is( '[+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]', jux_utf8_old( '+BD8EQAQ1BDQEOwQ+BDM-' ), 'jux_utf8_old: => [+BD8EQAQ1BDQEOwQ+BDM-] = [предлог]' ) ;
  5795. is( '[&BB8EQAQ+BDUEOgRC-] = [Проект]', jux_utf8_old( '&BB8EQAQ+BDUEOgRC-' ), 'jux_utf8_old: => [&BB8EQAQ+BDUEOgRC-] = [Проект]' ) ;
  5796. note( 'Leaving tests_jux_utf8_old()' ) ;
  5797. return ;
  5798. }
  5799. sub jux_utf8_old
  5800. {
  5801. # juxtapose utf8 at the right if different
  5802. my ( $s_utf7 ) = shift ;
  5803. my ( $s_utf8 ) = imap_utf7_decode_old( $s_utf7 ) ;
  5804. if ( $s_utf7 eq $s_utf8 ) {
  5805. #myprint( "[$s_utf7]\n" ) ;
  5806. return( "[$s_utf7]" ) ;
  5807. }else{
  5808. #myprint( "[$s_utf7] = [$s_utf8]\n" ) ;
  5809. return( "[$s_utf7] = [$s_utf8]" ) ;
  5810. }
  5811. }
  5812. # Copied from http://cpansearch.perl.org/src/FABPOT/Unicode-IMAPUtf7-2.01/lib/Unicode/IMAPUtf7.pm
  5813. # and then fixed with
  5814. # https://rt.cpan.org/Public/Bug/Display.html?id=11172
  5815. sub imap_utf7_decode_old
  5816. {
  5817. my ( $s ) = shift ;
  5818. # Algorithm
  5819. # On remplace , par / dans les BASE 64 (, entre & et -)
  5820. # On remplace les &, non suivi d'un - par +
  5821. # On remplace les &- par &
  5822. $s =~ s/&([^,&\-]*),([^,\-&]*)\-/&$1\/$2\-/xg ;
  5823. $s =~ s/&(?!\-)/\+/xg ;
  5824. $s =~ s/&\-/&/xg ;
  5825. return( Unicode::String::utf7( $s )->utf8 ) ;
  5826. }
  5827. sub tests_jux_utf8
  5828. {
  5829. note( 'Entering tests_jux_utf8()' ) ;
  5830. #no utf8 ;
  5831. use utf8 ;
  5832. #binmode STDOUT, ":encoding(UTF-8)" ;
  5833. binmode STDERR, ":encoding(UTF-8)" ;
  5834. # This test is because the binary can fail on it, a PAR.pm issue.
  5835. # The failure was with the underlying Encode::IMAPUTF7 module line 66 release 1.05
  5836. # Was solved by including Encode in imapsync and using "pp -x".
  5837. ok( find_encoding( "UTF-16BE"), 'jux_utf8: Encode::find_encoding: UTF-16BE' ) ;
  5838. #
  5839. is( '[]', jux_utf8( q{} ), 'jux_utf8: void => []' ) ;
  5840. is( '[INBOX]', jux_utf8( 'INBOX'), 'jux_utf8: INBOX => [INBOX]' ) ;
  5841. is( '[&ANY-] = [Ö]', jux_utf8( '&ANY-'), 'jux_utf8: &ANY- => [&ANY-] = [Ö]' ) ;
  5842. # +BD8EQAQ1BDQEOwQ+BDM- must stay as is
  5843. is( '[+BD8EQAQ1BDQEOwQ+BDM-]', jux_utf8( '+BD8EQAQ1BDQEOwQ+BDM-' ), 'jux_utf8: => [+BD8EQAQ1BDQEOwQ+BDM-] = [+BD8EQAQ1BDQEOwQ+BDM-]' ) ;
  5844. is( '[&BB8EQAQ+BDUEOgRC-] = [Проект]', jux_utf8( '&BB8EQAQ+BDUEOgRC-' ), 'jux_utf8: => [&BB8EQAQ+BDUEOgRC-] = [Проект]' ) ;
  5845. 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]' ) ;
  5846. my $str = Encode::IMAPUTF7::encode("IMAP-UTF-7", 'Réponses 1200+1201+1202' ) ;
  5847. is( '[R&AOk-ponses 1200+1201+1202] = [Réponses 1200+1201+1202]', jux_utf8( $str ), "jux_utf8: [$str] = [Réponses 1200+1201+1202]" ) ;
  5848. is( '[INBOX.&AOkA4ADnAPk-&-*] = [INBOX.éà çù&*]', jux_utf8( 'INBOX.&AOkA4ADnAPk-&-*' ), "jux_utf8: [INBOX.&AOkA4ADnAPk-&-*] = [INBOX.éà çù&*]" ) ;
  5849. is( '[&ZTZO9nux-] = [æ”¶ä»¶ç®±]', jux_utf8( '&ZTZO9nux-'), 'jux_utf8: => [&ZTZO9nux-] = [æ”¶ä»¶ç®±]' ) ;
  5850. #
  5851. note( 'Leaving tests_jux_utf8()' ) ;
  5852. return ;
  5853. }
  5854. sub jux_utf8
  5855. {
  5856. #use utf8 ;
  5857. # juxtapose utf8 at the right if different
  5858. my ( $s_utf7 ) = shift ;
  5859. my ( $s_utf8 ) = imap_utf7_decode( $s_utf7 ) ;
  5860. if ( $s_utf7 eq $s_utf8 ) {
  5861. #myprint( "[$s_utf7]\n" ) ;
  5862. return( "[$s_utf7]" ) ;
  5863. }else{
  5864. #myprint( "[$s_utf7] = [$s_utf8]\n" ) ;
  5865. return( "[$s_utf7] = [$s_utf8]" ) ;
  5866. }
  5867. }
  5868. sub imap_utf7_decode
  5869. {
  5870. #use utf8 ;
  5871. my ( $s ) = shift ;
  5872. return( Encode::IMAPUTF7::decode("IMAP-UTF-7", $s ) ) ;
  5873. }
  5874. sub imap_utf7_encode
  5875. {
  5876. #use utf8 ;
  5877. my ( $s ) = shift ;
  5878. return( Encode::IMAPUTF7::encode("IMAP-UTF-7", $s ) ) ;
  5879. }
  5880. sub imap_utf7_encode_old
  5881. {
  5882. my ( $s ) = @_ ;
  5883. $s = Unicode::String::utf8( $s )->utf7 ;
  5884. $s =~ s/\+([^\/&\-]*)\/([^\/\-&]*)\-/\+$1,$2\-/xg ;
  5885. $s =~ s/&/&\-/xg ;
  5886. $s =~ s/\+([^+\-]+)?\-/&$1\-/xg ;
  5887. return( $s ) ;
  5888. }
  5889. sub select_folder
  5890. {
  5891. my ( $mysync, $imap, $folder, $hostside ) = @_ ;
  5892. if ( ! $imap->select( $folder ) ) {
  5893. my $error = join q{},
  5894. "$hostside folder $folder: Could not select: ",
  5895. $imap->LastError, "\n" ;
  5896. errors_incr( $mysync, $error ) ;
  5897. return( 0 ) ;
  5898. }else{
  5899. # ok select succeeded
  5900. return( 1 ) ;
  5901. }
  5902. }
  5903. sub examine_folder
  5904. {
  5905. my ( $mysync, $imap, $folder, $hostside ) = @_ ;
  5906. if ( ! $imap->examine( $folder ) ) {
  5907. my $error = join q{},
  5908. "$hostside folder $folder: Could not examine: ",
  5909. $imap->LastError, "\n" ;
  5910. errors_incr( $mysync, $error ) ;
  5911. return( 0 ) ;
  5912. }else{
  5913. # ok select succeeded
  5914. return( 1 ) ;
  5915. }
  5916. }
  5917. sub count_from_select
  5918. {
  5919. my @lines = @ARG ;
  5920. my $count ;
  5921. foreach my $line ( @lines ) {
  5922. #myprint( "line = [$line]\n" ) ;
  5923. if ( $line =~ m/^\*\s+(\d+)\s+EXISTS/x ) {
  5924. $count = $1 ;
  5925. return( $count ) ;
  5926. }
  5927. }
  5928. return( undef ) ;
  5929. }
  5930. sub create_folder_old
  5931. {
  5932. my $mysync = shift @ARG ;
  5933. my( $imap, $h2_fold, $h1_fold ) = @ARG ;
  5934. myprint( "Creating (old way) folder [$h2_fold] on host2\n" ) ;
  5935. if ( ( 'INBOX' eq uc $h2_fold )
  5936. and ( $imap->exists( $h2_fold ) ) ) {
  5937. myprint( "Folder [$h2_fold] already exists\n" ) ;
  5938. return( 1 ) ;
  5939. }
  5940. if ( ! $mysync->{dry} ){
  5941. if ( ! $imap->create( $h2_fold ) ) {
  5942. my $error = join q{},
  5943. "Could not create folder [$h2_fold] from [$h1_fold]: ",
  5944. $imap->LastError( ), "\n" ;
  5945. errors_incr( $mysync, $error ) ;
  5946. # success if folder exists ("already exists" error)
  5947. return( 1 ) if $imap->exists( $h2_fold ) ;
  5948. # failure since create failed
  5949. return( 0 ) ;
  5950. }else{
  5951. #create succeeded
  5952. myprint( "Created ( the old way ) folder [$h2_fold] on host2\n" ) ;
  5953. return( 1 ) ;
  5954. }
  5955. }else{
  5956. # dry mode, no folder so many imap will fail, assuming failure
  5957. myprint( "Created ( the old way ) folder [$h2_fold] on host2 $mysync->{dry_message}\n" ) ;
  5958. return( 0 ) ;
  5959. }
  5960. }
  5961. sub create_folder
  5962. {
  5963. my $mysync = shift @ARG ;
  5964. my( $myimap2 , $h2_fold , $h1_fold ) = @ARG ;
  5965. my( @parts , $parent ) ;
  5966. if ( $myimap2->IsUnconnected( ) ) {
  5967. myprint( "Host2: Unconnected state\n" ) ;
  5968. return( 0 ) ;
  5969. }
  5970. if ( $create_folder_old ) {
  5971. return( create_folder_old( $mysync, $myimap2 , $h2_fold , $h1_fold ) ) ;
  5972. }
  5973. myprint( "Creating folder [$h2_fold] on host2\n" ) ;
  5974. if ( ( 'INBOX' eq uc $h2_fold )
  5975. and ( $myimap2->exists( $h2_fold ) ) ) {
  5976. myprint( "Folder [$h2_fold] already exists\n" ) ;
  5977. return( 1 ) ;
  5978. }
  5979. if ( $mixfolders and $myimap2->exists( $h2_fold ) ) {
  5980. myprint( "Folder [$h2_fold] already exists (--nomixfolders is not set)\n" ) ;
  5981. return( 1 ) ;
  5982. }
  5983. if ( ( not $mixfolders ) and ( $myimap2->exists( $h2_fold ) ) ) {
  5984. myprint( "Folder [$h2_fold] already exists and --nomixfolders is set\n" ) ;
  5985. return( 0 ) ;
  5986. }
  5987. @parts = split /\Q$mysync->{ h2_sep }\E/x, $h2_fold ;
  5988. pop @parts ;
  5989. $parent = join $mysync->{ h2_sep }, @parts ;
  5990. $parent =~ s/^\s+|\s+$//xg ;
  5991. if ( ( $parent ne q{} ) and ( ! $myimap2->exists( $parent ) ) ) {
  5992. create_folder( $mysync, $myimap2 , $parent , $h1_fold ) ;
  5993. }
  5994. if ( ! $mysync->{dry} ) {
  5995. if ( ! $myimap2->create( $h2_fold ) ) {
  5996. my $error = join q{},
  5997. "Could not create folder [$h2_fold] from [$h1_fold]: " ,
  5998. $myimap2->LastError( ), "\n" ;
  5999. errors_incr( $mysync, $error ) ;
  6000. # success if folder exists ("already exists" error)
  6001. return( 1 ) if $myimap2->exists( $h2_fold ) ;
  6002. # failure since create failed
  6003. return( 0 ) ;
  6004. }else{
  6005. #create succeeded
  6006. myprint( "Created folder [$h2_fold] on host2\n" ) ;
  6007. return( 1 ) ;
  6008. }
  6009. }else{
  6010. # dry mode, no folder so many imap will fail, assuming failure
  6011. myprint( "Created folder [$h2_fold] on host2 $mysync->{dry_message}\n" ) ;
  6012. if ( ! $mysync->{ justfolders } ) {
  6013. myprint( "Since --dry mode is on and folder [$h2_fold] on host2 does not exist yet, syncing messages will not be simulated.\n"
  6014. . "To simulate message syncing, use --justfolders without --dry to first create the missing folders then rerun the --dry sync.\n" ) ;
  6015. }
  6016. return( 0 ) ;
  6017. }
  6018. }
  6019. sub tests_folder_routines
  6020. {
  6021. note( 'Entering tests_folder_routines()' ) ;
  6022. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 1' );
  6023. ok( add_to_requested_folders('folder_foo'), 'add_to_requested_folders folder_foo' );
  6024. ok( is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 2' );
  6025. ok( !is_requested_folder('folder_NO_EXIST'), 'is_requested_folder folder_NO_EXIST' );
  6026. is_deeply( [ 'folder_foo' ], [ remove_from_requested_folders( 'folder_foo' ) ], 'removed folder_foo => folder_foo' ) ;
  6027. ok( !is_requested_folder('folder_foo'), 'is_requested_folder folder_foo 3' );
  6028. my @f ;
  6029. ok( @f = add_to_requested_folders('folder_bar', 'folder_toto'), "add result: @f" );
  6030. ok( is_requested_folder('folder_bar'), 'is_requested_folder 4' );
  6031. ok( is_requested_folder('folder_toto'), 'is_requested_folder 5' );
  6032. ok( remove_from_requested_folders('folder_toto'), 'remove_from_requested_folders: ' );
  6033. ok( !is_requested_folder('folder_toto'), 'is_requested_folder 6' );
  6034. is_deeply( [ 'folder_bar' ], [ remove_from_requested_folders('folder_bar') ], 'remove_from_requested_folders: empty' ) ;
  6035. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [] ), 'sort_requested_folders: all empty' ) ;
  6036. ok( add_to_requested_folders( 'A_99', 'M_55', 'Z_11' ), 'add_to_requested_folders M_55 Z_11' );
  6037. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'A_99', 'M_55', 'Z_11' ] ), 'sort_requested_folders: middle' ) ;
  6038. @folderfirst = ( 'Z_11' ) ;
  6039. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'A_99', 'M_55' ] ), 'sort_requested_folders: first+middle' ) ;
  6040. is_deeply( [ 'Z_11', 'A_99', 'M_55' ], [ sort_requested_folders( ) ], 'sort_requested_folders: first+middle is_deeply' ) ;
  6041. @folderlast = ( 'A_99' ) ;
  6042. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_55', 'A_99' ] ), 'sort_requested_folders: first+middle+last 1' ) ;
  6043. ok( add_to_requested_folders('M_55', 'M_44',), 'add_to_requested_folders M_55 M_44' ) ;
  6044. ok( 0 == compare_lists( [ sort_requested_folders( ) ], [ 'Z_11', 'M_44', 'M_55', 'A_99'] ), 'sort_requested_folders: first+middle+last 2' ) ;
  6045. ok( add_to_requested_folders('A_88', 'Z_22',), 'add_to_requested_folders A_88 Z_22' ) ;
  6046. @folderfirst = qw( Z_22 Z_11 ) ;
  6047. @folderlast = qw( A_99 A_88 ) ;
  6048. 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' ) ;
  6049. undef @folderfirst ;
  6050. undef @folderlast ;
  6051. note( 'Leaving tests_folder_routines()' ) ;
  6052. return ;
  6053. }
  6054. sub sort_requested_folders
  6055. {
  6056. my @requested_folders_sorted = () ;
  6057. #myprint "folderfirst: @folderfirst\n" ;
  6058. my @folderfirst_requested = remove_from_requested_folders( @folderfirst ) ;
  6059. #myprint "folderfirst_requested: @folderfirst_requested\n" ;
  6060. my @folderlast_requested = remove_from_requested_folders( @folderlast ) ;
  6061. my @middle = sort keys %requested_folder ;
  6062. @requested_folders_sorted = ( @folderfirst_requested, @middle, @folderlast_requested ) ;
  6063. #myprint "requested_folders_sorted: @requested_folders_sorted\n" ;
  6064. add_to_requested_folders( @requested_folders_sorted ) ;
  6065. return( @requested_folders_sorted ) ;
  6066. }
  6067. sub is_requested_folder
  6068. {
  6069. my ( $folder ) = @_;
  6070. return( defined $requested_folder{ $folder } ) ;
  6071. }
  6072. sub add_to_requested_folders
  6073. {
  6074. my @wanted_folders = @_ ;
  6075. foreach my $folder ( @wanted_folders ) {
  6076. ++$requested_folder{ $folder } ;
  6077. }
  6078. return( keys %requested_folder ) ;
  6079. }
  6080. sub tests_remove_from_requested_folders
  6081. {
  6082. note( 'Entering tests_remove_from_requested_folders()' ) ;
  6083. is( undef, undef, 'remove_from_requested_folders: undef is undef' ) ;
  6084. is_deeply( [], [ remove_from_requested_folders( ) ], 'remove_from_requested_folders: no args' ) ;
  6085. %requested_folder = (
  6086. 'F1' => 1,
  6087. ) ;
  6088. is_deeply( [], [ remove_from_requested_folders( ) ], 'remove_from_requested_folders: remove nothing among F1 => nothing' ) ;
  6089. is_deeply( [], [ remove_from_requested_folders( 'Fno' ) ], 'remove_from_requested_folders: remove Fno among F1 => nothing' ) ;
  6090. is_deeply( [ 'F1' ], [ remove_from_requested_folders( 'F1' ) ], 'remove_from_requested_folders: remove F1 among F1 => F1' ) ;
  6091. is_deeply( { }, { %requested_folder }, 'remove_from_requested_folders: remove F1 among F1 => %requested_folder emptied' ) ;
  6092. %requested_folder = (
  6093. 'F1' => 1,
  6094. 'F2' => 1,
  6095. ) ;
  6096. is_deeply( [], [ remove_from_requested_folders( ) ], 'remove_from_requested_folders: remove nothing among F1 F2 => nothing' ) ;
  6097. is_deeply( [], [ remove_from_requested_folders( 'Fno' ) ], 'remove_from_requested_folders: remove Fno among F1 F2 => nothing' ) ;
  6098. is_deeply( [ 'F1' ], [ remove_from_requested_folders( 'F1' ) ], 'remove_from_requested_folders: remove F1 among F1 F2 => F1' ) ;
  6099. is_deeply( { 'F2' => 1 }, { %requested_folder }, 'remove_from_requested_folders: remove F1 among F1 F2 => %requested_folder F2' ) ;
  6100. is_deeply( [], [ remove_from_requested_folders( 'F1' ) ], 'remove_from_requested_folders: remove F1 among F2 => nothing' ) ;
  6101. is_deeply( [ 'F2' ], [ remove_from_requested_folders( 'F1', 'F2' ) ], 'remove_from_requested_folders: remove F1 F2 among F2 => F2' ) ;
  6102. is_deeply( {}, { %requested_folder }, 'remove_from_requested_folders: remove F1 among F1 F2 => %requested_folder F2' ) ;
  6103. %requested_folder = (
  6104. 'F1' => 1,
  6105. 'F2' => 1,
  6106. 'F3' => 1,
  6107. ) ;
  6108. is_deeply( [ 'F1', 'F2' ], [ remove_from_requested_folders( 'F1', 'F2' ) ], 'remove_from_requested_folders: remove F1 F2 among F1 F2 F3 => F1 F2' ) ;
  6109. is_deeply( { 'F3' => 1 }, { %requested_folder }, 'remove_from_requested_folders: remove F1 F2 among F1 F2 F3 => %requested_folder F3' ) ;
  6110. note( 'Leaving tests_remove_from_requested_folders()' ) ;
  6111. return ;
  6112. }
  6113. sub remove_from_requested_folders
  6114. {
  6115. my @unwanted_folders = @_ ;
  6116. my @removed_folders = () ;
  6117. foreach my $folder ( @unwanted_folders ) {
  6118. if ( exists $requested_folder{ $folder } )
  6119. {
  6120. delete $requested_folder{ $folder } ;
  6121. push @removed_folders, $folder ;
  6122. }
  6123. }
  6124. return( @removed_folders ) ;
  6125. }
  6126. sub compare_lists
  6127. {
  6128. my ($list_1_ref, $list_2_ref) = @_;
  6129. return($MINUS_ONE) if ((not defined $list_1_ref) and defined $list_2_ref);
  6130. return(0) if ((not defined $list_1_ref) and not defined $list_2_ref); # end if no list
  6131. return(1) if (not defined $list_2_ref); # end if only one list
  6132. if (not ref $list_1_ref ) {$list_1_ref = [$list_1_ref]};
  6133. if (not ref $list_2_ref ) {$list_2_ref = [$list_2_ref]};
  6134. my $last_used_indice = $MINUS_ONE;
  6135. ELEMENT:
  6136. foreach my $indice ( 0 .. $#{ $list_1_ref } ) {
  6137. $last_used_indice = $indice ;
  6138. # End of list_2
  6139. return 1 if ($indice > $#{ $list_2_ref } ) ;
  6140. my $element_list_1 = $list_1_ref->[$indice] ;
  6141. my $element_list_2 = $list_2_ref->[$indice] ;
  6142. my $balance = $element_list_1 cmp $element_list_2 ;
  6143. next ELEMENT if ($balance == 0) ;
  6144. return $balance ;
  6145. }
  6146. # each element equal until last indice of list_1
  6147. return $MINUS_ONE if ($last_used_indice < $#{ $list_2_ref } ) ;
  6148. # same size, each element equal
  6149. return 0 ;
  6150. }
  6151. sub tests_compare_lists
  6152. {
  6153. note( 'Entering tests_compare_lists()' ) ;
  6154. my $empty_list_ref = [];
  6155. ok( 0 == compare_lists() , 'compare_lists, no args');
  6156. ok( 0 == compare_lists(undef) , 'compare_lists, undef = nothing');
  6157. ok( 0 == compare_lists(undef, undef) , 'compare_lists, undef = undef');
  6158. ok($MINUS_ONE == compare_lists(undef , []) , 'compare_lists, undef < []');
  6159. ok($MINUS_ONE == compare_lists(undef , [1]) , 'compare_lists, undef < [1]');
  6160. ok($MINUS_ONE == compare_lists(undef , [0]) , 'compare_lists, undef < [0]');
  6161. ok(+1 == compare_lists([]) , 'compare_lists, [] > nothing');
  6162. ok(+1 == compare_lists([], undef) , 'compare_lists, [] > undef');
  6163. ok( 0 == compare_lists([] , []) , 'compare_lists, [] = []');
  6164. ok($MINUS_ONE == compare_lists([] , [1]) , 'compare_lists, [] < [1]');
  6165. ok(+1 == compare_lists([1] , []) , 'compare_lists, [1] > []');
  6166. ok( 0 == compare_lists([1], 1 ) , 'compare_lists, [1] = 1 ') ;
  6167. ok( 0 == compare_lists( 1 , [1]) , 'compare_lists, 1 = [1]') ;
  6168. ok( 0 == compare_lists( 1 , 1 ) , 'compare_lists, 1 = 1 ') ;
  6169. ok($MINUS_ONE == compare_lists( 0 , 1 ) , 'compare_lists, 0 < 1 ') ;
  6170. ok($MINUS_ONE == compare_lists($MINUS_ONE , 0 ) , 'compare_lists, -1 < 0 ') ;
  6171. ok($MINUS_ONE == compare_lists( 1 , 2 ) , 'compare_lists, 1 < 2 ') ;
  6172. ok(+1 == compare_lists( 2 , 1 ) , 'compare_lists, 2 > 1 ') ;
  6173. ok( 0 == compare_lists([1,2], [1,2]) , 'compare_lists, [1,2] = [1,2]' ) ;
  6174. ok($MINUS_ONE == compare_lists([1], [1,2]) , 'compare_lists, [1] < [1,2]' ) ;
  6175. ok(+1 == compare_lists([2], [1,2]) , 'compare_lists, [2] > [1,2]' ) ;
  6176. ok($MINUS_ONE == compare_lists([1], [1,1]) , 'compare_lists, [1] < [1,1]' ) ;
  6177. ok(+1 == compare_lists([1, 1], [1]) , 'compare_lists, [1, 1] > [1]' ) ;
  6178. ok( 0 == compare_lists([1 .. $NUMBER_20_000] , [1 .. $NUMBER_20_000])
  6179. , 'compare_lists, [1..20_000] = [1..20_000]' ) ;
  6180. ok($MINUS_ONE == compare_lists([1], [2]) , 'compare_lists, [1] < [2]') ;
  6181. ok( 0 == compare_lists([2], [2]) , 'compare_lists, [0] = [2]') ;
  6182. ok(+1 == compare_lists([2], [1]) , 'compare_lists, [2] > [1]') ;
  6183. ok($MINUS_ONE == compare_lists(['a'], ['b']) , 'compare_lists, ["a"] < ["b"]') ;
  6184. ok( 0 == compare_lists(['a'], ['a']) , 'compare_lists, ["a"] = ["a"]') ;
  6185. ok( 0 == compare_lists(['ab'], ['ab']) , 'compare_lists, ["ab"] = ["ab"]') ;
  6186. ok(+1 == compare_lists(['b'], ['a']) , 'compare_lists, ["b"] > ["a"]') ;
  6187. ok($MINUS_ONE == compare_lists(['a'], ['aa']) , 'compare_lists, ["a"] < ["aa"]') ;
  6188. ok($MINUS_ONE == compare_lists(['a'], ['a', 'a']), 'compare_lists, ["a"] < ["a", "a"]') ;
  6189. ok( 0 == compare_lists([split q{ }, 'a b' ], ['a', 'b']), 'compare_lists, split') ;
  6190. ok( 0 == compare_lists([sort split q{ }, 'b a' ], ['a', 'b']), 'compare_lists, sort split') ;
  6191. note( 'Leaving tests_compare_lists()' ) ;
  6192. return ;
  6193. }
  6194. sub guess_prefix
  6195. {
  6196. my @foldernames = @_ ;
  6197. my $prefix_guessed = q{} ;
  6198. foreach my $folder ( @foldernames ) {
  6199. next if ( $folder =~ m{^INBOX$}xi ) ; # no guessing from INBOX
  6200. if ( $folder !~ m{^INBOX}xi ) {
  6201. $prefix_guessed = q{} ; # prefix empty guessed
  6202. last ;
  6203. }
  6204. if ( $folder =~ m{^(INBOX(?:\.|\/))}xi ) {
  6205. $prefix_guessed = $1 ; # prefix Inbox/ or INBOX. guessed
  6206. }
  6207. }
  6208. return( $prefix_guessed ) ;
  6209. }
  6210. sub tests_guess_prefix
  6211. {
  6212. note( 'Entering tests_guess_prefix()' ) ;
  6213. is( guess_prefix( ), q{}, 'guess_prefix: no args => empty string' ) ;
  6214. is( q{} , guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  6215. is( q{} , guess_prefix( 'Inbox' ), 'guess_prefix: Inbox alone' ) ;
  6216. is( q{} , guess_prefix( 'INBOX' ), 'guess_prefix: INBOX alone' ) ;
  6217. is( 'INBOX/' , guess_prefix( 'INBOX', 'INBOX/Junk' ), 'guess_prefix: INBOX INBOX/Junk' ) ;
  6218. is( 'INBOX.' , guess_prefix( 'INBOX', 'INBOX.Junk' ), 'guess_prefix: INBOX INBOX.Junk' ) ;
  6219. is( 'Inbox/' , guess_prefix( 'Inbox', 'Inbox/Junk' ), 'guess_prefix: Inbox Inbox/Junk' ) ;
  6220. is( 'Inbox.' , guess_prefix( 'Inbox', 'Inbox.Junk' ), 'guess_prefix: Inbox Inbox.Junk' ) ;
  6221. is( 'INBOX/' , guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr' ) ;
  6222. is( q{} , guess_prefix( 'INBOX', 'INBOX/Junk', 'INBOX/rrr', 'zzz' ), 'guess_prefix: INBOX INBOX/Junk INBOX/rrr zzz' ) ;
  6223. is( q{} , guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  6224. is( q{} , guess_prefix( 'INBOX', 'Junk' ), 'guess_prefix: INBOX Junk' ) ;
  6225. note( 'Leaving tests_guess_prefix()' ) ;
  6226. return ;
  6227. }
  6228. sub get_prefix
  6229. {
  6230. my( $imap, $prefix_in, $prefix_opt, $Side, $folders_ref ) = @_ ;
  6231. my( $prefix_out, $prefix_guessed ) ;
  6232. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: Getting prefix\n" ) ;
  6233. $prefix_guessed = guess_prefix( @{ $folders_ref } ) ;
  6234. myprint( "$Side: guessing prefix from folder listing: [$prefix_guessed]\n" ) ;
  6235. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: Calling namespace capability\n" ) ;
  6236. if ( $imap->has_capability( 'namespace' ) ) {
  6237. my $r_namespace = $imap->namespace( ) ;
  6238. $prefix_out = $r_namespace->[0][0][0] ;
  6239. myprint( "$Side: prefix given by NAMESPACE: [$prefix_out]\n" ) ;
  6240. if ( defined $prefix_in ) {
  6241. myprint( "$Side: but using [$prefix_in] given by $prefix_opt\n" ) ;
  6242. $prefix_out = $prefix_in ;
  6243. return( $prefix_out ) ;
  6244. }else{
  6245. # all good
  6246. return( $prefix_out ) ;
  6247. }
  6248. }
  6249. else{
  6250. if ( defined $prefix_in ) {
  6251. myprint( "$Side: using [$prefix_in] given by $prefix_opt\n" ) ;
  6252. $prefix_out = $prefix_in ;
  6253. return( $prefix_out ) ;
  6254. }else{
  6255. myprint(
  6256. "$Side: No NAMESPACE capability so using guessed prefix [$prefix_guessed]\n",
  6257. help_to_guess_prefix( $imap, $prefix_opt ) ) ;
  6258. return( $prefix_guessed ) ;
  6259. }
  6260. }
  6261. return ;
  6262. }
  6263. sub guess_separator
  6264. {
  6265. my @foldernames = @_ ;
  6266. #return( undef ) unless ( @foldernames ) ;
  6267. my $sep_guessed ;
  6268. my %counter ;
  6269. foreach my $folder ( @foldernames ) {
  6270. $counter{'/'}++ while ( $folder =~ m{/}xg ) ; # count /
  6271. $counter{'.'}++ while ( $folder =~ m{\.}xg ) ; # count .
  6272. $counter{'\\\\'}++ while ( $folder =~ m{(\\){2}}xg ) ; # count \\
  6273. $counter{'\\'}++ while ( $folder =~ m{[^\\](\\){1}(?=[^\\])}xg ) ; # count \
  6274. }
  6275. my @race_sorted = sort { $counter{ $b } <=> $counter{ $a } } keys %counter ;
  6276. $sync->{ debug } and myprint( "@foldernames\n@race_sorted\n", %counter, "\n" ) ;
  6277. $sep_guessed = shift @race_sorted || $LAST_RESSORT_SEPARATOR ; # / when nothing found.
  6278. return( $sep_guessed ) ;
  6279. }
  6280. sub tests_guess_separator
  6281. {
  6282. note( 'Entering tests_guess_separator()' ) ;
  6283. ok( '/' eq guess_separator( ), 'guess_separator: no args' ) ;
  6284. ok( '/' eq guess_separator( 'abcd' ), 'guess_separator: abcd' ) ;
  6285. ok( '/' eq guess_separator( 'a/b/c.d' ), 'guess_separator: a/b/c.d' ) ;
  6286. ok( '.' eq guess_separator( 'a.b/c.d' ), 'guess_separator: a.b/c.d' ) ;
  6287. ok( '\\\\' eq guess_separator( 'a\\\\b\\\\c.c\\\\d/e/f' ), 'guess_separator: a\\\\b\\\\c.c\\\\d/e/f' ) ;
  6288. ok( '\\' eq guess_separator( 'a\\b\\c.c\\d/e/f' ), 'guess_separator: a\\b\\c.c\\d/e/f' ) ;
  6289. ok( '\\' eq guess_separator( 'a\\b' ), 'guess_separator: a\\b' ) ;
  6290. ok( '\\' eq guess_separator( 'a\\b\\c' ), 'guess_separator: a\\b\\c' ) ;
  6291. note( 'Leaving tests_guess_separator()' ) ;
  6292. return ;
  6293. }
  6294. sub get_separator
  6295. {
  6296. my( $imap, $sep_in, $sep_opt, $Side, $folders_ref ) = @_ ;
  6297. my( $sep_out, $sep_guessed ) ;
  6298. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: Getting separator\n" ) ;
  6299. $sep_guessed = guess_separator( @{ $folders_ref } ) ;
  6300. myprint( "$Side: guessing separator from folder listing: [$sep_guessed]\n" ) ;
  6301. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "$Side: calling namespace capability\n" ) ;
  6302. if ( $imap->has_capability( 'namespace' ) )
  6303. {
  6304. $sep_out = $imap->separator( ) ;
  6305. if ( defined $sep_out ) {
  6306. myprint( "$Side: separator given by NAMESPACE: [$sep_out]\n" ) ;
  6307. if ( defined $sep_in ) {
  6308. myprint( "$Side: but using [$sep_in] given by $sep_opt\n" ) ;
  6309. $sep_out = $sep_in ;
  6310. return( $sep_out ) ;
  6311. }else{
  6312. return( $sep_out ) ;
  6313. }
  6314. }else{
  6315. if ( defined $sep_in ) {
  6316. myprint( "$Side: NAMESPACE request failed but using [$sep_in] given by $sep_opt\n" ) ;
  6317. $sep_out = $sep_in ;
  6318. return( $sep_out ) ;
  6319. }else{
  6320. myprint(
  6321. "$Side: NAMESPACE request failed so using guessed separator [$sep_guessed]\n",
  6322. help_to_guess_sep( $imap, $sep_opt ) ) ;
  6323. return( $sep_guessed ) ;
  6324. }
  6325. }
  6326. }
  6327. else
  6328. {
  6329. if ( defined $sep_in ) {
  6330. myprint( "$Side: No NAMESPACE capability but using [$sep_in] given by $sep_opt\n" ) ;
  6331. $sep_out = $sep_in ;
  6332. return( $sep_out ) ;
  6333. }else{
  6334. myprint(
  6335. "$Side: No NAMESPACE capability, so using guessed separator [$sep_guessed]\n",
  6336. help_to_guess_sep( $imap, $sep_opt ) ) ;
  6337. return( $sep_guessed ) ;
  6338. }
  6339. }
  6340. return ;
  6341. }
  6342. sub help_to_guess_sep
  6343. {
  6344. my( $imap, $sep_opt ) = @_ ;
  6345. my $help_to_guess_sep = "You can set the separator character with the $sep_opt option,\n"
  6346. . "the complete listing of folders may help you to find it\n"
  6347. . folders_list_to_help( $imap ) ;
  6348. return( $help_to_guess_sep ) ;
  6349. }
  6350. sub help_to_guess_prefix
  6351. {
  6352. my( $imap, $prefix_opt ) = @_ ;
  6353. my $help_to_guess_prefix = "You can set the prefix namespace with the $prefix_opt option,\n"
  6354. . "the folowing listing of folders may help you to find it:\n"
  6355. . folders_list_to_help( $imap ) ;
  6356. return( $help_to_guess_prefix ) ;
  6357. }
  6358. sub folders_list_to_help
  6359. {
  6360. my( $imap ) = shift ;
  6361. my @folders = $imap->folders ;
  6362. my $listing = join q{}, map { "[$_]\n" } @folders ;
  6363. return( $listing ) ;
  6364. }
  6365. sub private_folders_separators_and_prefixes
  6366. {
  6367. # what are the private folders separators and prefixes for each server ?
  6368. ( $sync->{ debug } or $sync->{debugfolders} ) and myprint( "Getting separators\n" ) ;
  6369. $sync->{ h1_sep } = get_separator( $sync->{imap1}, $sync->{ sep1 }, '--sep1', 'Host1', \@h1_folders_all ) ;
  6370. $sync->{ h2_sep } = get_separator( $sync->{imap2}, $sync->{ sep2 }, '--sep2', 'Host2', \@h2_folders_all ) ;
  6371. $sync->{ h1_prefix } = get_prefix( $sync->{imap1}, $prefix1, '--prefix1', 'Host1', \@h1_folders_all ) ;
  6372. $sync->{ h2_prefix } = get_prefix( $sync->{imap2}, $prefix2, '--prefix2', 'Host2', \@h2_folders_all ) ;
  6373. myprint( "Host1: separator and prefix: [$sync->{ h1_sep }][$sync->{ h1_prefix }]\n" ) ;
  6374. myprint( "Host2: separator and prefix: [$sync->{ h2_sep }][$sync->{ h2_prefix }]\n" ) ;
  6375. return ;
  6376. }
  6377. sub subfolder1
  6378. {
  6379. my $mysync = shift ;
  6380. my $subfolder1 = sanitize_subfolder( $mysync->{ subfolder1 } ) ;
  6381. if ( $subfolder1 )
  6382. {
  6383. # turns off automap
  6384. myprint( "Turning off automapping folders because of --subfolder1\n" ) ;
  6385. $mysync->{ automap } = undef ;
  6386. myprint( "Sanitizing subfolder1: [$mysync->{ subfolder1 }] => [$subfolder1]\n" ) ;
  6387. $mysync->{ subfolder1 } = $subfolder1 ;
  6388. if ( ! add_subfolder1_to_folderrec( $mysync ) )
  6389. {
  6390. $mysync->{nb_errors}++ ;
  6391. exit_clean( $mysync, $EXIT_SUBFOLDER1_NO_EXISTS, "subfolder1 $subfolder1 does not exist\n" ) ;
  6392. }
  6393. }
  6394. else
  6395. {
  6396. $mysync->{ subfolder1 } = undef ;
  6397. }
  6398. return ;
  6399. }
  6400. sub subfolder2
  6401. {
  6402. my $mysync = shift ;
  6403. my $subfolder2 = sanitize_subfolder( $mysync->{ subfolder2 } ) ;
  6404. if ( $subfolder2 )
  6405. {
  6406. # turns off automap
  6407. myprint( "Turning off automapping folders because of --subfolder2\n" ) ;
  6408. $mysync->{ automap } = undef ;
  6409. myprint( "Sanitizing subfolder2: [$mysync->{ subfolder2 }] => [$subfolder2]\n" ) ;
  6410. $mysync->{ subfolder2 } = $subfolder2 ;
  6411. set_regextrans2_for_subfolder2( $mysync ) ;
  6412. }
  6413. else
  6414. {
  6415. $mysync->{ subfolder2 } = undef ;
  6416. }
  6417. return ;
  6418. }
  6419. sub tests_sanitize_subfolder
  6420. {
  6421. note( 'Entering tests_sanitize_subfolder()' ) ;
  6422. is( undef, sanitize_subfolder( ), 'sanitize_subfolder: no args => undef' ) ;
  6423. is( undef, sanitize_subfolder( q{} ), 'sanitize_subfolder: empty => undef' ) ;
  6424. is( undef, sanitize_subfolder( ' ' ), 'sanitize_subfolder: blank => undef' ) ;
  6425. is( undef, sanitize_subfolder( ' ' ), 'sanitize_subfolder: blanks => undef' ) ;
  6426. is( 'abcd', sanitize_subfolder( 'abcd' ), 'sanitize_subfolder: abcd => abcd' ) ;
  6427. is( 'ab cd', sanitize_subfolder( ' ab cd ' ), 'sanitize_subfolder: " ab cd " => "ab cd"' ) ;
  6428. is( 'abcd', sanitize_subfolder( q{a&~b#\\c[]=d;} ), 'sanitize_subfolder: "a&~b#\\c[]=d;" => "abcd"' ) ;
  6429. is( 'aA.b-_ 8c/dD', sanitize_subfolder( 'aA.b-_ 8c/dD' ), 'sanitize_subfolder: aA.b-_ 8c/dD => aA.b-_ 8c/dD' ) ;
  6430. note( 'Leaving tests_sanitize_subfolder()' ) ;
  6431. return ;
  6432. }
  6433. sub sanitize_subfolder
  6434. {
  6435. my $subfolder = shift ;
  6436. if ( ! $subfolder )
  6437. {
  6438. return ;
  6439. }
  6440. # Remove edging blanks
  6441. $subfolder =~ s,^ +| +$,,g ;
  6442. # Keep only abcd...ABCD...0123... and -_./
  6443. $subfolder =~ tr,-_a-zA-Z0-9./ ,,cd ;
  6444. # A blank subfolder is not a subfolder
  6445. if ( ! $subfolder )
  6446. {
  6447. return ;
  6448. }
  6449. else
  6450. {
  6451. return $subfolder ;
  6452. }
  6453. }
  6454. sub tests_add_subfolder1_to_folderrec
  6455. {
  6456. note( 'Entering tests_add_subfolder1_to_folderrec()' ) ;
  6457. is( undef, add_subfolder1_to_folderrec( ), 'add_subfolder1_to_folderrec: undef => undef' ) ;
  6458. is_deeply( [], [ add_subfolder1_to_folderrec( ) ], 'add_subfolder1_to_folderrec: no args => empty array' ) ;
  6459. @folderrec = () ;
  6460. my $mysync = {} ;
  6461. is_deeply( [ ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: empty => empty array' ) ;
  6462. is_deeply( [ ], [ @folderrec ], 'add_subfolder1_to_folderrec: empty => empty folderrec' ) ;
  6463. $mysync->{ subfolder1 } = 'SUBI' ;
  6464. $h1_folders_all{ 'SUBI' } = 1 ;
  6465. $mysync->{ h1_prefix } = 'INBOX/' ;
  6466. is_deeply( [ 'SUBI' ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: SUBI => SUBI' ) ;
  6467. is_deeply( [ 'SUBI' ], [ @folderrec ], 'add_subfolder1_to_folderrec: SUBI => folderrec SUBI ' ) ;
  6468. @folderrec = () ;
  6469. $mysync->{ subfolder1 } = 'SUBO' ;
  6470. is_deeply( [ ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: SUBO no exists => empty array' ) ;
  6471. is_deeply( [ ], [ @folderrec ], 'add_subfolder1_to_folderrec: SUBO no exists => empty folderrec' ) ;
  6472. $h1_folders_all{ 'INBOX/SUBO' } = 1 ;
  6473. is_deeply( [ 'INBOX/SUBO' ], [ add_subfolder1_to_folderrec( $mysync ) ], 'add_subfolder1_to_folderrec: SUBO + INBOX/SUBO exists => INBOX/SUBO' ) ;
  6474. is_deeply( [ 'INBOX/SUBO' ], [ @folderrec ], 'add_subfolder1_to_folderrec: SUBO + INBOX/SUBO exists => INBOX/SUBO folderrec' ) ;
  6475. note( 'Leaving tests_add_subfolder1_to_folderrec()' ) ;
  6476. return ;
  6477. }
  6478. sub add_subfolder1_to_folderrec
  6479. {
  6480. my $mysync = shift ;
  6481. if ( ! $mysync || ! $mysync->{ subfolder1 } )
  6482. {
  6483. return ;
  6484. }
  6485. my $subfolder1 = $mysync->{ subfolder1 } ;
  6486. my $subfolder1_extended = $mysync->{ h1_prefix } . $subfolder1 ;
  6487. if ( exists $h1_folders_all{ $subfolder1 } )
  6488. {
  6489. myprint( qq{Acting like --folderrec "$subfolder1"\n} ) ;
  6490. push @folderrec, $subfolder1 ;
  6491. }
  6492. elsif ( exists $h1_folders_all{ $subfolder1_extended } )
  6493. {
  6494. myprint( qq{Acting like --folderrec "$subfolder1_extended"\n} ) ;
  6495. push @folderrec, $subfolder1_extended ;
  6496. }
  6497. else
  6498. {
  6499. myprint( qq{Nor folder "$subfolder1" nor "$subfolder1_extended" exists on host1\n} ) ;
  6500. }
  6501. return @folderrec ;
  6502. }
  6503. sub set_regextrans2_for_subfolder2
  6504. {
  6505. my $mysync = shift ;
  6506. unshift @{ $mysync->{ regextrans2 } },
  6507. q(s,^$mysync->{ h2_prefix }(.*),$mysync->{ h2_prefix }$mysync->{ subfolder2 }$mysync->{ h2_sep }$1,),
  6508. q(s,^INBOX$,$mysync->{ h2_prefix }$mysync->{ subfolder2 }$mysync->{ h2_sep }INBOX,),
  6509. q(s,^($mysync->{ h2_prefix }){2},$mysync->{ h2_prefix },);
  6510. #myprint( "@{ $mysync->{ regextrans2 } }\n" ) ;
  6511. return ;
  6512. }
  6513. # Looks like no globals here
  6514. sub tests_imap2_folder_name
  6515. {
  6516. note( 'Entering tests_imap2_folder_name()' ) ;
  6517. my $mysync = {} ;
  6518. $mysync->{ h1_prefix } = q{} ;
  6519. $mysync->{ h2_prefix } = q{} ;
  6520. $mysync->{ h1_sep } = '/';
  6521. $mysync->{ h2_sep } = '.';
  6522. $mysync->{ debug } and myprint( <<"EOS"
  6523. prefix1: [$mysync->{ h1_prefix }]
  6524. prefix2: [$mysync->{ h2_prefix }]
  6525. sep1: [$sync->{ h1_sep }]
  6526. sep2: [$sync->{ h2_sep }]
  6527. EOS
  6528. ) ;
  6529. $mysync->{ fixslash2 } = 0 ;
  6530. is( q{INBOX}, imap2_folder_name( $mysync, q{} ), 'imap2_folder_name: empty string' ) ;
  6531. is( 'blabla', imap2_folder_name( $mysync, 'blabla' ), 'imap2_folder_name: blabla' ) ;
  6532. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam' ), 'imap2_folder_name: spam/spam' ) ;
  6533. is( 'spam/spam', imap2_folder_name( $mysync, 'spam.spam' ), 'imap2_folder_name: spam.spam') ;
  6534. is( 'spam.spam/spam', imap2_folder_name( $mysync, 'spam/spam.spam' ), 'imap2_folder_name: spam/spam.spam' ) ;
  6535. is( 's pam.spam/sp am', imap2_folder_name( $mysync, 's pam/spam.sp am' ), 'imap2_folder_name: s pam/spam.sp am' ) ;
  6536. $mysync->{f1f2h}{ 'auto' } = 'moto' ;
  6537. is( 'moto', imap2_folder_name( $mysync, 'auto' ), 'imap2_folder_name: auto' ) ;
  6538. $mysync->{f1f2h}{ 'auto/auto' } = 'moto x 2' ;
  6539. is( 'moto x 2', imap2_folder_name( $mysync, 'auto/auto' ), 'imap2_folder_name: auto/auto' ) ;
  6540. @{ $mysync->{ regextrans2 } } = ( 's,/,X,g' ) ;
  6541. is( q{INBOX}, imap2_folder_name( $mysync, q{} ), 'imap2_folder_name: empty string [s,/,X,g]' ) ;
  6542. is( 'blabla', imap2_folder_name( $mysync, 'blabla' ), 'imap2_folder_name: blabla [s,/,X,g]' ) ;
  6543. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam'), 'imap2_folder_name: spam/spam [s,/,X,g]');
  6544. is('spamXspam', imap2_folder_name( $mysync, 'spam.spam'), 'imap2_folder_name: spam.spam [s,/,X,g]');
  6545. is('spam.spamXspam', imap2_folder_name( $mysync, 'spam/spam.spam'), 'imap2_folder_name: spam/spam.spam [s,/,X,g]');
  6546. @{ $mysync->{ regextrans2 } } = ( 's, ,_,g' ) ;
  6547. is('blabla', imap2_folder_name( $mysync, 'blabla'), 'imap2_folder_name: blabla [s, ,_,g]');
  6548. is('bla_bla', imap2_folder_name( $mysync, 'bla bla'), 'imap2_folder_name: blabla [s, ,_,g]');
  6549. @{ $mysync->{ regextrans2 } } = ( q{s,(.*),\U$1,} ) ;
  6550. is( 'BLABLA', imap2_folder_name( $mysync, 'blabla' ), q{imap2_folder_name: blabla [s,\U(.*)\E,$1,]} ) ;
  6551. $mysync->{ fixslash2 } = 1 ;
  6552. @{ $mysync->{ regextrans2 } } = ( ) ;
  6553. is(q{INBOX}, imap2_folder_name( $mysync, q{}), 'imap2_folder_name: empty string');
  6554. is('blabla', imap2_folder_name( $mysync, 'blabla'), 'imap2_folder_name: blabla');
  6555. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  6556. is('spam_spam', imap2_folder_name( $mysync, 'spam.spam'), 'imap2_folder_name: spam.spam -> spam_spam');
  6557. is('spam.spam_spam', imap2_folder_name( $mysync, 'spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam_spam');
  6558. 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');
  6559. $mysync->{ h1_sep } = '.';
  6560. $mysync->{ h2_sep } = '/';
  6561. is( q{INBOX}, imap2_folder_name( $mysync, q{}), 'imap2_folder_name: empty string');
  6562. is('blabla', imap2_folder_name( $mysync, 'blabla'), 'imap2_folder_name: blabla');
  6563. is('spam.spam', imap2_folder_name( $mysync, 'spam/spam'), 'imap2_folder_name: spam/spam -> spam.spam');
  6564. is('spam/spam', imap2_folder_name( $mysync, 'spam.spam'), 'imap2_folder_name: spam.spam -> spam/spam');
  6565. is('spam.spam/spam', imap2_folder_name( $mysync, 'spam/spam.spam'), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam');
  6566. $mysync->{ fixslash2 } = 0 ;
  6567. $mysync->{ h1_prefix } = q{ };
  6568. is( 'spam.spam/spam', imap2_folder_name( $mysync, 'spam/spam.spam' ), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam' ) ;
  6569. is( 'spam.spam/spam', imap2_folder_name( $mysync, ' spam/spam.spam' ), 'imap2_folder_name: spam/spam.spam -> spam.spam/spam' ) ;
  6570. $mysync->{ h1_sep } = '.' ;
  6571. $mysync->{ h2_sep } = '/' ;
  6572. $mysync->{ h1_prefix } = 'INBOX.' ;
  6573. $mysync->{ h2_prefix } = q{} ;
  6574. @{ $mysync->{ regextrans2 } } = ( q{s,(.*),\U$1,} ) ;
  6575. is( 'BLABLA', imap2_folder_name( $mysync, 'blabla' ), 'imap2_folder_name: blabla' ) ;
  6576. is( 'TEST/TEST/TEST/TEST', imap2_folder_name( $mysync, 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  6577. @{ $mysync->{ regextrans2 } } = ( q{s,(.*),\L$1,} ) ;
  6578. is( 'test/test/test/test', imap2_folder_name( $mysync, 'INBOX.TEST.test.Test.tesT' ), 'imap2_folder_name: INBOX.TEST.test.Test.tesT' ) ;
  6579. # INBOX
  6580. $mysync = {} ;
  6581. $mysync->{ h1_prefix } = q{Pf1.} ;
  6582. $mysync->{ h2_prefix } = q{Pf2/} ;
  6583. $mysync->{ h1_sep } = '.';
  6584. $mysync->{ h2_sep } = '/';
  6585. #
  6586. #$mysync->{ debug } = 1 ;
  6587. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'F1.F2.F3' ), 'imap2_folder_name: F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  6588. is( 'Pf2/F1/INBOX', imap2_folder_name( $mysync, 'F1.INBOX' ), 'imap2_folder_name: F1.INBOX -> Pf2/F1/INBOX' ) ;
  6589. is( 'INBOX', imap2_folder_name( $mysync, 'INBOX' ), 'imap2_folder_name: INBOX -> INBOX' ) ;
  6590. is( 'Pf2/F1/F2/F3', imap2_folder_name( $mysync, 'Pf1.F1.F2.F3' ), 'imap2_folder_name: Pf1.F1.F2.F3 -> Pf2/F1/F2/F3' ) ;
  6591. is( 'Pf2/F1/INBOX', imap2_folder_name( $mysync, 'Pf1.F1.INBOX' ), 'imap2_folder_name: Pf1.F1.INBOX -> Pf2/F1/INBOX' ) ;
  6592. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.INBOX' ), 'imap2_folder_name: Pf1.INBOX -> INBOX' ) ; # not Pf2/INBOX: Yes I can!
  6593. # subfolder2
  6594. $mysync = {} ;
  6595. $mysync->{ h1_prefix } = q{} ;
  6596. $mysync->{ h2_prefix } = q{} ;
  6597. $mysync->{ h1_sep } = '/';
  6598. $mysync->{ h2_sep } = '.';
  6599. set_regextrans2_for_subfolder2( $mysync ) ;
  6600. $mysync->{ subfolder2 } = 'S1.S2' ;
  6601. is( 'S1.S2.F1.F2.F3', imap2_folder_name( $mysync, 'F1/F2/F3' ), 'imap2_folder_name: F1/F2/F3 -> S1.S2.F1.F2.F3' ) ;
  6602. is( 'S1.S2.INBOX', imap2_folder_name( $mysync, 'INBOX' ), 'imap2_folder_name: F1/F2/F3 -> S1.S2.INBOX' ) ;
  6603. $mysync = {} ;
  6604. $mysync->{ h1_prefix } = q{Pf1/} ;
  6605. $mysync->{ h2_prefix } = q{Pf2.} ;
  6606. $mysync->{ h1_sep } = '/';
  6607. $mysync->{ h2_sep } = '.';
  6608. #$mysync->{ debug } = 1 ;
  6609. set_regextrans2_for_subfolder2( $mysync ) ;
  6610. $mysync->{ subfolder2 } = 'Pf2.S1.S2' ;
  6611. 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' ) ;
  6612. is( 'Pf2.S1.S2.INBOX', imap2_folder_name( $mysync, 'INBOX' ), 'imap2_folder_name: INBOX -> Pf2.S1.S2.INBOX' ) ;
  6613. 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' ) ;
  6614. is( 'Pf2.S1.S2.INBOX', imap2_folder_name( $mysync, 'Pf1/INBOX' ), 'imap2_folder_name: INBOX -> Pf2.S1.S2.INBOX' ) ;
  6615. # subfolder1
  6616. # scenario as the reverse of the previous tests, separators point of vue
  6617. $mysync = {} ;
  6618. $mysync->{ h1_prefix } = q{Pf1.} ;
  6619. $mysync->{ h2_prefix } = q{Pf2/} ;
  6620. $mysync->{ h1_sep } = '.';
  6621. $mysync->{ h2_sep } = '/';
  6622. #$mysync->{ debug } = 1 ;
  6623. $mysync->{ subfolder1 } = 'S1.S2' ;
  6624. 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' ) ;
  6625. 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' ) ;
  6626. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.INBOX' ), 'imap2_folder_name: S1.S2.INBOX -> INBOX' ) ;
  6627. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2' ), 'imap2_folder_name: S1.S2 -> INBOX' ) ;
  6628. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.' ), 'imap2_folder_name: S1.S2. -> INBOX' ) ;
  6629. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.INBOX' ), 'imap2_folder_name: Pf1.S1.S2.INBOX -> INBOX' ) ;
  6630. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2' ), 'imap2_folder_name: Pf1.S1.S2 -> INBOX' ) ;
  6631. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.' ), 'imap2_folder_name: Pf1.S1.S2. -> INBOX' ) ;
  6632. $mysync->{ subfolder1 } = 'S1.S2.' ;
  6633. 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' ) ;
  6634. 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' ) ;
  6635. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.INBOX' ), 'imap2_folder_name: S1.S2.INBOX -> INBOX' ) ;
  6636. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2' ), 'imap2_folder_name: S1.S2 -> INBOX' ) ;
  6637. is( 'INBOX', imap2_folder_name( $mysync, 'S1.S2.' ), 'imap2_folder_name: S1.S2. -> INBOX' ) ;
  6638. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.INBOX' ), 'imap2_folder_name: Pf1.S1.S2.INBOX -> INBOX' ) ;
  6639. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2' ), 'imap2_folder_name: Pf1.S1.S2 -> INBOX' ) ;
  6640. is( 'INBOX', imap2_folder_name( $mysync, 'Pf1.S1.S2.' ), 'imap2_folder_name: Pf1.S1.S2. -> INBOX' ) ;
  6641. # subfolder1
  6642. # scenario as Gmail
  6643. $mysync = {} ;
  6644. $mysync->{ h1_prefix } = q{} ;
  6645. $mysync->{ h2_prefix } = q{} ;
  6646. $mysync->{ h1_sep } = '/';
  6647. $mysync->{ h2_sep } = '/';
  6648. #$mysync->{ debug } = 1 ;
  6649. $mysync->{ subfolder1 } = 'S1/S2' ;
  6650. is( 'F1/F2/F3', imap2_folder_name( $mysync, 'S1/S2/F1/F2/F3' ), 'imap2_folder_name: S1/S2/F1/F2/F3 -> F1/F2/F3' ) ;
  6651. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/INBOX' ), 'imap2_folder_name: S1/S2/INBOX -> INBOX' ) ;
  6652. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2' ), 'imap2_folder_name: S1/S2 -> INBOX' ) ;
  6653. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/' ), 'imap2_folder_name: S1/S2/ -> INBOX' ) ;
  6654. $mysync->{ subfolder1 } = 'S1/S2/' ;
  6655. is( 'F1/F2/F3', imap2_folder_name( $mysync, 'S1/S2/F1/F2/F3' ), 'imap2_folder_name: S1/S2/F1/F2/F3 -> F1/F2/F3' ) ;
  6656. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/INBOX' ), 'imap2_folder_name: S1/S2/INBOX -> INBOX' ) ;
  6657. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2' ), 'imap2_folder_name: S1/S2 -> INBOX' ) ;
  6658. is( 'INBOX', imap2_folder_name( $mysync, 'S1/S2/' ), 'imap2_folder_name: S1/S2/ -> INBOX' ) ;
  6659. note( 'Leaving tests_imap2_folder_name()' ) ;
  6660. return ;
  6661. }
  6662. # Global variables to remove:
  6663. # None?
  6664. sub imap2_folder_name
  6665. {
  6666. my $mysync = shift ;
  6667. my ( $h1_fold ) = shift ;
  6668. my ( $h2_fold ) ;
  6669. if ( $mysync->{f1f2h}{ $h1_fold } ) {
  6670. $h2_fold = $mysync->{f1f2h}{ $h1_fold } ;
  6671. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "f1f2 [$h1_fold] -> [$h2_fold]\n" ) ;
  6672. return( $h2_fold ) ;
  6673. }
  6674. if ( $mysync->{f1f2auto}{ $h1_fold } ) {
  6675. $h2_fold = $mysync->{f1f2auto}{ $h1_fold } ;
  6676. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "automap [$h1_fold] -> [$h2_fold]\n" ) ;
  6677. return( $h2_fold ) ;
  6678. }
  6679. if ( $mysync->{ subfolder1 } )
  6680. {
  6681. my $esc_h1_sep = "\\" . $mysync->{ h1_sep } ;
  6682. # case where subfolder1 has the sep1 at the end, then remove it
  6683. my $part_to_removed = remove_last_char_if_is( $mysync->{ subfolder1 }, $mysync->{ h1_sep } ) ;
  6684. # remove the subfolder1 part and the sep1 if present after
  6685. $h1_fold =~ s{$part_to_removed($esc_h1_sep)?}{} ;
  6686. #myprint( "h1_fold=$h1_fold\n" ) ;
  6687. }
  6688. if ( ( q{} eq $h1_fold ) or ( $mysync->{ h1_prefix } eq $h1_fold ) )
  6689. {
  6690. $h1_fold = 'INBOX' ;
  6691. }
  6692. $h2_fold = prefix_seperator_invertion( $mysync, $h1_fold ) ;
  6693. $h2_fold = regextrans2( $mysync, $h2_fold ) ;
  6694. return( $h2_fold ) ;
  6695. }
  6696. sub tests_remove_last_char_if_is
  6697. {
  6698. note( 'Entering tests_remove_last_char_if_is()' ) ;
  6699. is( undef, remove_last_char_if_is( ), 'remove_last_char_if_is: no args => undef' ) ;
  6700. is( q{}, remove_last_char_if_is( q{} ), 'remove_last_char_if_is: empty => empty' ) ;
  6701. is( q{}, remove_last_char_if_is( q{}, 'Z' ), 'remove_last_char_if_is: empty Z => empty' ) ;
  6702. is( q{}, remove_last_char_if_is( 'Z', 'Z' ), 'remove_last_char_if_is: Z Z => empty' ) ;
  6703. is( 'abc', remove_last_char_if_is( 'abcZ', 'Z' ), 'remove_last_char_if_is: abcZ Z => abc' ) ;
  6704. is( 'abcY', remove_last_char_if_is( 'abcY', 'Z' ), 'remove_last_char_if_is: abcY Z => abcY' ) ;
  6705. note( 'Leaving tests_remove_last_char_if_is()' ) ;
  6706. return ;
  6707. }
  6708. sub remove_last_char_if_is
  6709. {
  6710. my $string = shift ;
  6711. my $char = shift ;
  6712. if ( ! defined $string )
  6713. {
  6714. return ;
  6715. }
  6716. if ( ! defined $char )
  6717. {
  6718. return $string ;
  6719. }
  6720. my $last_char = substr $string, -1 ;
  6721. if ( $char eq $last_char )
  6722. {
  6723. chop $string ;
  6724. return $string ;
  6725. }
  6726. else
  6727. {
  6728. return $string ;
  6729. }
  6730. }
  6731. sub tests_prefix_seperator_invertion
  6732. {
  6733. note( 'Entering tests_prefix_seperator_invertion()' ) ;
  6734. is( undef, prefix_seperator_invertion( ), 'prefix_seperator_invertion: no args => undef' ) ;
  6735. is( q{}, prefix_seperator_invertion( undef, q{} ), 'prefix_seperator_invertion: empty string => empty string' ) ;
  6736. is( 'lalala', prefix_seperator_invertion( undef, 'lalala' ), 'prefix_seperator_invertion: lalala => lalala' ) ;
  6737. is( 'lal/ala', prefix_seperator_invertion( undef, 'lal/ala' ), 'prefix_seperator_invertion: lal/ala => lal/ala' ) ;
  6738. is( 'lal.ala', prefix_seperator_invertion( undef, 'lal.ala' ), 'prefix_seperator_invertion: lal.ala => lal.ala' ) ;
  6739. is( '////', prefix_seperator_invertion( undef, '////' ), 'prefix_seperator_invertion: //// => ////' ) ;
  6740. is( '.....', prefix_seperator_invertion( undef, '.....' ), 'prefix_seperator_invertion: ..... => .....' ) ;
  6741. my $mysync = {
  6742. h1_prefix => q{},
  6743. h2_prefix => q{},
  6744. h1_sep => '/',
  6745. h2_sep => '/',
  6746. } ;
  6747. is( q{}, prefix_seperator_invertion( $mysync, q{} ), 'prefix_seperator_invertion: $mysync empty string => empty string' ) ;
  6748. is( 'lalala', prefix_seperator_invertion( $mysync, 'lalala' ), 'prefix_seperator_invertion: $mysync lalala => lalala' ) ;
  6749. is( 'lal/ala', prefix_seperator_invertion( $mysync, 'lal/ala' ), 'prefix_seperator_invertion: $mysync lal/ala => lal/ala' ) ;
  6750. is( 'lal.ala', prefix_seperator_invertion( $mysync, 'lal.ala' ), 'prefix_seperator_invertion: $mysync lal.ala => lal.ala' ) ;
  6751. is( '////', prefix_seperator_invertion( $mysync, '////' ), 'prefix_seperator_invertion: $mysync //// => ////' ) ;
  6752. is( '.....', prefix_seperator_invertion( $mysync, '.....' ), 'prefix_seperator_invertion: $mysync ..... => .....' ) ;
  6753. $mysync = {
  6754. h1_prefix => 'PPP',
  6755. h2_prefix => 'QQQ',
  6756. h1_sep => 's',
  6757. h2_sep => 't',
  6758. } ;
  6759. is( q{QQQ}, prefix_seperator_invertion( $mysync, q{} ), 'prefix_seperator_invertion: PPPQQQst empty string => QQQ' ) ;
  6760. is( 'QQQlalala', prefix_seperator_invertion( $mysync, 'lalala' ), 'prefix_seperator_invertion: PPPQQQst lalala => QQQlalala' ) ;
  6761. is( 'QQQlal/ala', prefix_seperator_invertion( $mysync, 'lal/ala' ), 'prefix_seperator_invertion: PPPQQQst lal/ala => QQQlal/ala' ) ;
  6762. is( 'QQQlal.ala', prefix_seperator_invertion( $mysync, 'lal.ala' ), 'prefix_seperator_invertion: PPPQQQst lal.ala => QQQlal.ala' ) ;
  6763. is( 'QQQ////', prefix_seperator_invertion( $mysync, '////' ), 'prefix_seperator_invertion: PPPQQQst //// => QQQ////' ) ;
  6764. is( 'QQQ.....', prefix_seperator_invertion( $mysync, '.....' ), 'prefix_seperator_invertion: PPPQQQst ..... => QQQ.....' ) ;
  6765. is( 'QQQPlalala', prefix_seperator_invertion( $mysync, 'PPPPlalala' ), 'prefix_seperator_invertion: PPPQQQst PPPPlalala => QQQPlalala' ) ;
  6766. is( 'QQQ', prefix_seperator_invertion( $mysync, 'PPP' ), 'prefix_seperator_invertion: PPPQQQst PPP => QQQ' ) ;
  6767. is( 'QQQttt', prefix_seperator_invertion( $mysync, 'sss' ), 'prefix_seperator_invertion: PPPQQQst sss => QQQttt' ) ;
  6768. is( 'QQQt', prefix_seperator_invertion( $mysync, 's' ), 'prefix_seperator_invertion: PPPQQQst s => QQQt' ) ;
  6769. is( 'QQQtAAAtBBB', prefix_seperator_invertion( $mysync, 'PPPsAAAsBBB' ), 'prefix_seperator_invertion: PPPQQQst PPPsAAAsBBB => QQQtAAAtBBB' ) ;
  6770. note( 'Leaving tests_prefix_seperator_invertion()' ) ;
  6771. return ;
  6772. }
  6773. # Global variables to remove:
  6774. sub prefix_seperator_invertion
  6775. {
  6776. my $mysync = shift ;
  6777. my $h1_fold = shift ;
  6778. my $h2_fold ;
  6779. if ( not defined $h1_fold ) { return ; }
  6780. my $my_h1_prefix = $mysync->{ h1_prefix } || q{} ;
  6781. my $my_h2_prefix = $mysync->{ h2_prefix } || q{} ;
  6782. my $my_h1_sep = $mysync->{ h1_sep } || '/' ;
  6783. my $my_h2_sep = $mysync->{ h2_sep } || '/' ;
  6784. # first we remove the prefix
  6785. $h1_fold =~ s/^\Q$my_h1_prefix\E//x ;
  6786. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "removed host1 prefix: [$h1_fold]\n" ) ;
  6787. $h2_fold = separator_invert( $mysync, $h1_fold, $my_h1_sep, $my_h2_sep ) ;
  6788. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "inverted separators: [$h2_fold]\n" ) ;
  6789. # Adding the prefix supplied by namespace or the --prefix2 option
  6790. # except for INBOX or Inbox
  6791. if ( $h2_fold !~ m/^INBOX$/xi )
  6792. {
  6793. $h2_fold = $my_h2_prefix . $h2_fold ;
  6794. }
  6795. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "added host2 prefix: [$h2_fold]\n" ) ;
  6796. return( $h2_fold ) ;
  6797. }
  6798. sub tests_separator_invert
  6799. {
  6800. note( 'Entering tests_separator_invert()' ) ;
  6801. my $mysync = {} ;
  6802. $mysync->{ fixslash2 } = 0 ;
  6803. ok( not( defined separator_invert( ) ), 'separator_invert: no args' ) ;
  6804. ok( not( defined separator_invert( q{} ) ), 'separator_invert: not enough args' ) ;
  6805. ok( not( defined separator_invert( q{}, q{} ) ), 'separator_invert: not enough args' ) ;
  6806. ok( q{} eq separator_invert( $mysync, q{}, q{}, q{} ), 'separator_invert: 3 empty strings' ) ;
  6807. ok( 'lalala' eq separator_invert( $mysync, 'lalala', q{}, q{} ), 'separator_invert: empty separator' ) ;
  6808. ok( 'lalala' eq separator_invert( $mysync, 'lalala', '/', '/' ), 'separator_invert: same separator /' ) ;
  6809. ok( 'lal/ala' eq separator_invert( $mysync, 'lal/ala', '/', '/' ), 'separator_invert: same separator / 2' ) ;
  6810. ok( 'lal.ala' eq separator_invert( $mysync, 'lal/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  6811. ok( 'lal/ala' eq separator_invert( $mysync, 'lal.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  6812. ok( 'la.l/ala' eq separator_invert( $mysync, 'la/l.ala', '.', '/' ), 'separator_invert: separators ./' ) ;
  6813. ok( 'l/al.ala' eq separator_invert( $mysync, 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  6814. $mysync->{ fixslash2 } = 1 ;
  6815. ok( 'l_al.ala' eq separator_invert( $mysync, 'l.al/ala', '/', '.' ), 'separator_invert: separators /.' ) ;
  6816. note( 'Leaving tests_separator_invert()' ) ;
  6817. return ;
  6818. }
  6819. # Global variables to remove:
  6820. #
  6821. sub separator_invert
  6822. {
  6823. my( $mysync, $h1_fold, $h1_separator, $h2_separator ) = @_ ;
  6824. return( undef ) if ( not all_defined( $mysync, $h1_fold, $h1_separator, $h2_separator ) ) ;
  6825. # The separator we hope we'll never encounter: 00000000 == 0x00
  6826. my $o_sep = "\000" ;
  6827. my $h2_fold = $h1_fold ;
  6828. $h2_fold =~ s,\Q$h2_separator,$o_sep,xg ;
  6829. $h2_fold =~ s,\Q$h1_separator,$h2_separator,xg ;
  6830. $h2_fold =~ s,\Q$o_sep,$h1_separator,xg ;
  6831. $h2_fold =~ s,/,_,xg if( $mysync->{ fixslash2 } and '/' ne $h2_separator and '/' eq $h1_separator ) ;
  6832. return( $h2_fold ) ;
  6833. }
  6834. sub regextrans2
  6835. {
  6836. my( $mysync, $h2_fold ) = @_ ;
  6837. # Transforming the folder name by the --regextrans2 option(s)
  6838. foreach my $regextrans2 ( @{ $mysync->{ regextrans2 } } ) {
  6839. my $h2_fold_before = $h2_fold ;
  6840. my $ret = eval "\$h2_fold =~ $regextrans2 ; 1 " ;
  6841. ( $mysync->{ debug } or $mysync->{debugfolders} ) and myprint( "[$h2_fold_before] -> [$h2_fold] using regextrans2 [$regextrans2]\n" ) ;
  6842. if ( not ( defined $ret ) or $EVAL_ERROR ) {
  6843. $mysync->{nb_errors}++ ;
  6844. exit_clean( $mysync, $EX_USAGE,
  6845. "error: eval regextrans2 '$regextrans2': $EVAL_ERROR\n"
  6846. ) ;
  6847. }
  6848. }
  6849. return( $h2_fold ) ;
  6850. }
  6851. sub tests_decompose_regex
  6852. {
  6853. note( 'Entering tests_decompose_regex()' ) ;
  6854. ok( 1, 'decompose_regex 1' ) ;
  6855. ok( 0 == compare_lists( [ q{}, q{} ], [ decompose_regex( q{} ) ] ), 'decompose_regex empty string' ) ;
  6856. ok( 0 == compare_lists( [ '.*', 'lala' ], [ decompose_regex( 's/.*/lala/' ) ] ), 'decompose_regex s/.*/lala/' ) ;
  6857. note( 'Leaving tests_decompose_regex()' ) ;
  6858. return ;
  6859. }
  6860. sub decompose_regex
  6861. {
  6862. my $regex = shift ;
  6863. my( $left_part, $right_part ) ;
  6864. ( $left_part, $right_part ) = $regex =~ m{^s/((?:[^/]|\\/)+)/((?:[^/]|\\/)+)/}x;
  6865. return( q{}, q{} ) if not $left_part ;
  6866. return( $left_part, $right_part ) ;
  6867. }
  6868. sub tests_timenext
  6869. {
  6870. note( 'Entering tests_timenext()' ) ;
  6871. is( undef, timenext( ), 'timenext: no args => undef' ) ;
  6872. my $mysync ;
  6873. is( undef, timenext( $mysync ), 'timenext: undef => undef' ) ;
  6874. $mysync = {} ;
  6875. ok( time - timenext( $mysync ) <= 1e-02, 'timenext: defined first time => ~ time' ) ;
  6876. ok( timenext( $mysync ) <= 1e-02, 'timenext: second time => less than 1e-02' ) ;
  6877. ok( timenext( $mysync ) <= 1e-02, 'timenext: third time => less than 1e-02' ) ;
  6878. note( 'Leaving tests_timenext()' ) ;
  6879. return ;
  6880. }
  6881. sub timenext
  6882. {
  6883. my $mysync = shift ;
  6884. if ( ! defined $mysync )
  6885. {
  6886. return ;
  6887. }
  6888. my ( $timenow, $timediff ) ;
  6889. $mysync->{ timebefore } ||= 0; # epoch...
  6890. $timenow = time ;
  6891. $timediff = $timenow - $mysync->{ timebefore } ;
  6892. $mysync->{ timebefore } = $timenow ;
  6893. # myprint( "timenext: $timediff\n" ) ;
  6894. return( $timediff ) ;
  6895. }
  6896. sub tests_timesince
  6897. {
  6898. note( 'Entering tests_timesince()' ) ;
  6899. ok( timesince( time - 1 ) - 1 <= 1e-02, 'timesince: time - 1 => <= 1 + 1e-02' ) ;
  6900. ok( timesince( time ) <= 1e-02, 'timesince: time => <= 1e-02' ) ;
  6901. ok( timesince( ) - time <= 1e-02, 'timesince: no args => <= time + 1e-02' ) ;
  6902. note( 'Leaving tests_timesince()' ) ;
  6903. return ;
  6904. }
  6905. sub timesince
  6906. {
  6907. my $timeinit = shift || 0 ;
  6908. my ( $timenow, $timediff ) ;
  6909. $timenow = time ;
  6910. $timediff = $timenow - $timeinit ;
  6911. # Often used in a division so no 0 but a nano seconde.
  6912. return( max( $timediff, min( 1e-09, $timediff ) ) ) ;
  6913. }
  6914. sub tests_flags_regex
  6915. {
  6916. note( 'Entering tests_flags_regex()' ) ;
  6917. ok( q{} eq flags_regex(q{} ), 'flags_regex, null string q{}' ) ;
  6918. ok( q{\Seen NonJunk $Spam} eq flags_regex( q{\Seen NonJunk $Spam} ), q{flags_regex, nothing to do} ) ;
  6919. @regexflag = ('I am BAD' ) ;
  6920. ok( not ( defined flags_regex( q{} ) ), 'flags_regex, bad regex' ) ;
  6921. @regexflag = ( 's/NonJunk//g' ) ;
  6922. ok( q{\Seen $Spam} eq flags_regex( q{\Seen NonJunk $Spam} ), q{flags_regex, remove NonJunk: 's/NonJunk//g'} ) ;
  6923. @regexflag = ( q{s/\$Spam//g} ) ;
  6924. ok( q{\Seen NonJunk } eq flags_regex( q{\Seen NonJunk $Spam} ), q{flags_regex, remove $Spam: 's/\$Spam//g'} ) ;
  6925. @regexflag = ( 's/\\\\Seen//g' ) ;
  6926. ok( q{ NonJunk $Spam} eq flags_regex( q{\Seen NonJunk $Spam} ), q{flags_regex, remove \Seen: 's/\\\\\\\\Seen//g'} ) ;
  6927. @regexflag = ( 's/(\s|^)[^\\\\]\w+//g' ) ;
  6928. ok( q{\Seen \Middle \End} eq flags_regex( q{\Seen NonJunk \Middle $Spam \End} ), q{flags_regex: only \word among \Seen NonJunk \Middle $Spam \End} ) ;
  6929. ok( q{ \Seen \Middle \End1} eq flags_regex( q{Begin \Seen NonJunk \Middle $Spam \End1 End} ),
  6930. q{flags_regex: only \word among Begin \Seen NonJunk \Middle $Spam \End1 End} ) ;
  6931. @regexflag = ( q{s/.*?(Keep1|Keep2|Keep3)/$1 /g} ) ;
  6932. ok( 'Keep1 Keep2 ReB' eq flags_regex('ReA Keep1 REM Keep2 ReB'), 'Keep only regex' ) ;
  6933. ok( 'Keep1 Keep2 ' eq flags_regex( 'REM REM Keep1 Keep2'), 'Keep only regex' ) ;
  6934. ok( 'Keep1 Keep2 ' eq flags_regex( 'Keep1 REM REM Keep2'), 'Keep only regex' ) ;
  6935. ok( 'Keep1 Keep2 ' eq flags_regex( 'REM Keep1 REM REM Keep2'), 'Keep only regex' ) ;
  6936. ok( 'Keep1 Keep2 ' eq flags_regex( 'Keep1 Keep2'), 'Keep only regex' ) ;
  6937. ok( 'Keep1 ' eq flags_regex( 'REM Keep1'), 'Keep only regex' ) ;
  6938. @regexflag = ( q{s/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g} ) ;
  6939. ok( 'Keep1 Keep2 ' eq flags_regex( 'Keep1 Keep2 ReB'), 'Keep only regex' ) ;
  6940. ok( 'Keep1 Keep2 ' eq flags_regex( 'Keep1 Keep2 REM REM REM'), 'Keep only regex' ) ;
  6941. ok( 'Keep2 ' eq flags_regex('Keep2 REM REM REM'), 'Keep only regex' ) ;
  6942. @regexflag = ( q{s/.*?(Keep1|Keep2|Keep3)/$1 /g},
  6943. 's/(Keep1|Keep2|Keep3) (?!(Keep1|Keep2|Keep3)).*/$1 /g' ) ;
  6944. ok( 'Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2 REM'), 'Keep only regex' ) ;
  6945. ok( 'Keep1 Keep2 ' eq flags_regex('Keep1 REM Keep2 REM'), 'Keep only regex' ) ;
  6946. ok( 'Keep1 Keep2 ' eq flags_regex('REM Keep1 Keep2 REM'), 'Keep only regex' ) ;
  6947. ok( 'Keep1 Keep2 ' eq flags_regex('REM Keep1 REM Keep2'), 'Keep only regex' ) ;
  6948. ok( 'Keep1 Keep2 Keep3 ' eq flags_regex('REM Keep1 REM Keep2 REM REM Keep3 REM'), 'Keep only regex' ) ;
  6949. ok( 'Keep1 ' eq flags_regex('REM REM Keep1 REM REM REM '), 'Keep only regex' ) ;
  6950. ok( 'Keep1 Keep3 ' eq flags_regex('RE1 Keep1 RE2 Keep3 RE3 RE4 RE5 '), 'Keep only regex' ) ;
  6951. @regexflag = ( 's/(.*)/$1 jrdH8u/' ) ;
  6952. ok('REM REM REM REM REM jrdH8u' eq flags_regex('REM REM REM REM REM'), q{Add jrdH8u 's/(.*)/\$1 jrdH8u/'} ) ;
  6953. @regexflag = ('s/jrdH8u *//');
  6954. ok('REM REM REM REM REM ' eq flags_regex('REM REM REM REM REM jrdH8u'), q{Remove jrdH8u s/jrdH8u *//} ) ;
  6955. @regexflag = (
  6956. 's/.*?(?:(\\\\(?:Answered|Flagged|Deleted|Seen|Draft)\s?)|$)/defined($1)?$1:q()/eg'
  6957. );
  6958. ok( '\\Deleted \\Answered '
  6959. eq flags_regex('Blabla \$Junk \\Deleted machin \\Answered truc'),
  6960. 'Keep only regex: Exchange case (Phil)' ) ;
  6961. ok( q{} eq flags_regex( q{} ), 'Keep only regex: Exchange case, null string (Phil)' ) ;
  6962. ok( q{}
  6963. eq flags_regex('Blabla $Junk machin truc'),
  6964. 'Keep only regex: Exchange case, no accepted flags (Phil)' ) ;
  6965. ok('\\Deleted \\Answered \\Draft \\Flagged '
  6966. eq flags_regex('\\Deleted \\Answered \\Draft \\Flagged '),
  6967. 'Keep only regex: Exchange case (Phil)' ) ;
  6968. @regexflag = ( 's/\\\\Flagged//g' ) ;
  6969. is('\Deleted \Answered \Draft ',
  6970. flags_regex('\\Deleted \\Answered \\Draft \\Flagged '),
  6971. 'flags_regex: remove \Flagged 1' ) ;
  6972. is('\\Deleted \\Answered \\Draft',
  6973. flags_regex('\\Deleted \\Flagged \\Answered \\Draft'),
  6974. 'flags_regex: remove \Flagged 2' ) ;
  6975. # I didn't understand why it gives \F
  6976. # https://perldoc.perl.org/perlrebackslash.html
  6977. # \F Foldcase till \E. Not in [].
  6978. # https://perldoc.perl.org/functions/fc.html
  6979. # \F Not available in old Perl so I comment the test
  6980. # @regexflag = ( 's/\\Flagged/X/g' ) ;
  6981. #is('\Deleted FX \Answered \FX \Draft \FX',
  6982. #flags_regex( '\Deleted Flagged \Answered \Flagged \Draft \Flagged' ),
  6983. # 'flags_regex: remove \Flagged 3 mistery...' ) ;
  6984. note( 'Leaving tests_flags_regex()' ) ;
  6985. return ;
  6986. }
  6987. sub flags_regex
  6988. {
  6989. my ( $h1_flags ) = @_ ;
  6990. foreach my $regexflag ( @regexflag ) {
  6991. my $h1_flags_orig = $h1_flags ;
  6992. $debugflags and myprint( "eval \$h1_flags =~ $regexflag\n" ) ;
  6993. my $ret = eval "\$h1_flags =~ $regexflag ; 1 " ;
  6994. $debugflags and myprint( "regexflag $regexflag [$h1_flags_orig] -> [$h1_flags]\n" ) ;
  6995. if( not ( defined $ret ) or $EVAL_ERROR ) {
  6996. myprint( "Error: eval regexflag '$regexflag': $EVAL_ERROR\n" ) ;
  6997. return( undef ) ;
  6998. }
  6999. }
  7000. return( $h1_flags ) ;
  7001. }
  7002. sub acls_sync
  7003. {
  7004. my($h1_fold, $h2_fold) = @_ ;
  7005. if ( $syncacls ) {
  7006. my $h1_hash = $sync->{imap1}->getacl($h1_fold)
  7007. or myprint( "Could not getacl for $h1_fold: $EVAL_ERROR\n" ) ;
  7008. my $h2_hash = $sync->{imap2}->getacl($h2_fold)
  7009. or myprint( "Could not getacl for $h2_fold: $EVAL_ERROR\n" ) ;
  7010. my %users = map { ($_, 1) } ( keys %{ $h1_hash} , keys %{ $h2_hash } ) ;
  7011. foreach my $user (sort keys %users ) {
  7012. my $acl = $h1_hash->{$user} || 'none' ;
  7013. myprint( "acl $user: [$acl]\n" ) ;
  7014. next if ($h1_hash->{$user} && $h2_hash->{$user} &&
  7015. $h1_hash->{$user} eq $h2_hash->{$user});
  7016. unless ($sync->{dry}) {
  7017. myprint( "setting acl $h2_fold $user $acl\n" ) ;
  7018. $sync->{imap2}->setacl($h2_fold, $user, $acl)
  7019. or myprint( "Could not set acl: $EVAL_ERROR\n" ) ;
  7020. }
  7021. }
  7022. }
  7023. return ;
  7024. }
  7025. sub tests_permanentflags
  7026. {
  7027. note( 'Entering tests_permanentflags()' ) ;
  7028. my $string;
  7029. ok(q{} eq permanentflags(' * OK [PERMANENTFLAGS (\* \Draft \Answered)] Limited'),
  7030. 'permanentflags \*');
  7031. ok('\Draft \Answered' eq permanentflags(' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited'),
  7032. 'permanentflags \Draft \Answered');
  7033. ok('\Draft \Answered'
  7034. eq permanentflags('Blabla',
  7035. ' * OK [PERMANENTFLAGS (\Draft \Answered)] Limited',
  7036. 'Blabla'),
  7037. 'permanentflags \Draft \Answered'
  7038. );
  7039. ok(q{} eq permanentflags('Blabla'), 'permanentflags nothing');
  7040. note( 'Leaving tests_permanentflags()' ) ;
  7041. return ;
  7042. }
  7043. sub permanentflags
  7044. {
  7045. my @lines = @_ ;
  7046. foreach my $line (@lines) {
  7047. if ( $line =~ m{\[PERMANENTFLAGS\s\(([^)]+?)\)\]}x ) {
  7048. ( $debugflags or $sync->{ debug } ) and myprint( "permanentflags: $line" ) ;
  7049. my $permanentflags = $1 ;
  7050. if ( $permanentflags =~ m{\\\*}x ) {
  7051. $permanentflags = q{} ;
  7052. }
  7053. return($permanentflags) ;
  7054. } ;
  7055. }
  7056. return( q{} ) ;
  7057. }
  7058. sub tests_flags_filter
  7059. {
  7060. note( 'Entering tests_flags_filter()' ) ;
  7061. ok( '\Seen' eq flags_filter('\Seen', '\Draft \Seen \Answered'), 'flags_filter ' );
  7062. ok( q{} eq flags_filter('\Seen', '\Draft \Answered'), 'flags_filter ' );
  7063. ok( '\Seen' eq flags_filter('\Seen', '\Seen'), 'flags_filter ' );
  7064. ok( '\Seen' eq flags_filter('\Seen', ' \Seen '), 'flags_filter ' );
  7065. ok( '\Seen \Draft'
  7066. eq flags_filter('\Seen \Draft', '\Draft \Seen \Answered'), 'flags_filter ' );
  7067. ok( '\Seen \Draft'
  7068. eq flags_filter('\Seen \Draft', ' \Draft \Seen \Answered '), 'flags_filter ' );
  7069. note( 'Leaving tests_flags_filter()' ) ;
  7070. return ;
  7071. }
  7072. sub flags_filter
  7073. {
  7074. my( $flags, $allowed_flags ) = @_ ;
  7075. my @flags = split /\s+/x, $flags ;
  7076. my %allowed_flags = map { $_ => 1 } split q{ }, $allowed_flags ;
  7077. my @flags_out = map { exists $allowed_flags{$_} ? $_ : () } @flags ;
  7078. my $flags_out = join q{ }, @flags_out ;
  7079. return( $flags_out ) ;
  7080. }
  7081. sub flagscase
  7082. {
  7083. my $flags = shift ;
  7084. my @flags = split /\s+/x, $flags ;
  7085. my %rfc_flags = map { $_ => 1 } split q{ }, '\Answered \Flagged \Deleted \Seen \Draft' ;
  7086. my @flags_out = map { exists $rfc_flags{ ucsecond( lc $_ ) } ? ucsecond( lc $_ ) : $_ } @flags ;
  7087. my $flags_out = join q{ }, @flags_out ;
  7088. return( $flags_out ) ;
  7089. }
  7090. sub tests_flagscase
  7091. {
  7092. note( 'Entering tests_flagscase()' ) ;
  7093. ok( '\Seen' eq flagscase( '\Seen' ), 'flagscase: \Seen -> \Seen' ) ;
  7094. ok( '\Seen' eq flagscase( '\SEEN' ), 'flagscase: \SEEN -> \Seen' ) ;
  7095. ok( '\Seen \Draft' eq flagscase( '\SEEN \DRAFT' ), 'flagscase: \SEEN \DRAFT -> \Seen \Draft' ) ;
  7096. ok( '\Draft \Seen' eq flagscase( '\DRAFT \SEEN' ), 'flagscase: \DRAFT \SEEN -> \Draft \Seen' ) ;
  7097. ok( '\Draft LALA \Seen' eq flagscase( '\DRAFT LALA \SEEN' ), 'flagscase: \DRAFT LALA \SEEN -> \Draft LALA \Seen' ) ;
  7098. ok( '\Draft lala \Seen' eq flagscase( '\DRAFT lala \SEEN' ), 'flagscase: \DRAFT lala \SEEN -> \Draft lala \Seen' ) ;
  7099. note( 'Leaving tests_flagscase()' ) ;
  7100. return ;
  7101. }
  7102. sub ucsecond
  7103. {
  7104. my $string = shift ;
  7105. my $output ;
  7106. return( $string ) if ( 1 >= length $string ) ;
  7107. $output = ( substr( $string, 0, 1) ) . ( uc substr $string, 1, 1 ) . ( substr $string, 2 ) ;
  7108. #myprint( "UUU $string -> $output\n" ) ;
  7109. return( $output ) ;
  7110. }
  7111. sub tests_ucsecond
  7112. {
  7113. note( 'Entering tests_ucsecond()' ) ;
  7114. ok( 'aBcde' eq ucsecond( 'abcde' ), 'ucsecond: abcde -> aBcde' ) ;
  7115. ok( 'ABCDE' eq ucsecond( 'ABCDE' ), 'ucsecond: ABCDE -> ABCDE' ) ;
  7116. ok( 'ABCDE' eq ucsecond( 'AbCDE' ), 'ucsecond: AbCDE -> ABCDE' ) ;
  7117. ok( 'ABCde' eq ucsecond( 'AbCde' ), 'ucsecond: AbCde -> ABCde' ) ;
  7118. ok( 'A' eq ucsecond( 'A' ), 'ucsecond: A -> A' ) ;
  7119. ok( 'AB' eq ucsecond( 'Ab' ), 'ucsecond: Ab -> AB' ) ;
  7120. ok( '\B' eq ucsecond( '\b' ), 'ucsecond: \b -> \B' ) ;
  7121. ok( '\Bcde' eq ucsecond( '\bcde' ), 'ucsecond: \bcde -> \Bcde' ) ;
  7122. note( 'Leaving tests_ucsecond()' ) ;
  7123. return ;
  7124. }
  7125. sub select_msgs
  7126. {
  7127. my ( $imap, $msgs_all_hash_ref, $search_cmd, $abletosearch, $folder ) = @_ ;
  7128. my ( @msgs ) ;
  7129. if ( $abletosearch ) {
  7130. @msgs = select_msgs_by_search( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  7131. }else{
  7132. @msgs = select_msgs_by_fetch( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) ;
  7133. }
  7134. return( @msgs ) ;
  7135. }
  7136. sub select_msgs_by_search
  7137. {
  7138. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  7139. my ( @msgs, @msgs_all ) ;
  7140. # Need to have the whole list in msgs_all_hash_ref
  7141. # without calling messages() several times.
  7142. # Need all messages list to avoid deleting useful cache part
  7143. # in case of --search or --minage or --maxage
  7144. if ( ( defined $msgs_all_hash_ref and $usecache )
  7145. or ( not defined $maxage and not defined $minage and not defined $search_cmd )
  7146. ) {
  7147. $debugdev and myprint( "Calling messages()\n" ) ;
  7148. @msgs_all = $imap->messages( ) ;
  7149. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  7150. if ( defined $msgs_all_hash_ref ) {
  7151. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  7152. }
  7153. # return all messages
  7154. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  7155. return( @msgs_all ) ;
  7156. }
  7157. }
  7158. if ( defined $search_cmd ) {
  7159. @msgs = $imap->search( $search_cmd ) ;
  7160. return( @msgs ) ;
  7161. }
  7162. # we are here only if $maxage or $minage is defined
  7163. @msgs = select_msgs_by_age( $imap ) ;
  7164. return( @msgs );
  7165. }
  7166. sub select_msgs_by_fetch
  7167. {
  7168. my ( $imap, $msgs_all_hash_ref, $search_cmd, $folder ) = @_ ;
  7169. my ( @msgs, @msgs_all, %fetch ) ;
  7170. # Need to have the whole list in msgs_all_hash_ref
  7171. # without calling messages() several times.
  7172. # Need all messages list to avoid deleting useful cache part
  7173. # in case of --search or --minage or --maxage
  7174. $debugdev and myprint( "Calling fetch_hash()\n" ) ;
  7175. my $uidnext = $imap->uidnext( $folder ) || $uidnext_default ;
  7176. my $fetch_hash_uids = $fetch_hash_set || "1:$uidnext" ;
  7177. %fetch = %{$imap->fetch_hash( $fetch_hash_uids, 'INTERNALDATE' ) } ;
  7178. @msgs_all = sort { $a <=> $b } keys %fetch ;
  7179. $debugdev and myprint( "Done fetch_hash()\n" ) ;
  7180. return if ( $#msgs_all == 0 && !defined $msgs_all[0] ) ;
  7181. if ( defined $msgs_all_hash_ref ) {
  7182. @{ $msgs_all_hash_ref }{ @msgs_all } = () ;
  7183. }
  7184. # return all messages
  7185. if ( not defined $maxage and not defined $minage and not defined $search_cmd ) {
  7186. return( @msgs_all ) ;
  7187. }
  7188. if ( defined $search_cmd ) {
  7189. myprint( "Warning: strange to see --search with --noabletosearch, an error can happen\n" ) ;
  7190. @msgs = $imap->search( $search_cmd ) ;
  7191. return( @msgs ) ;
  7192. }
  7193. # we are here only if $maxage or $minage is defined
  7194. my( @max, @min, $maxage_epoch, $minage_epoch ) ;
  7195. if ( defined $maxage ) { $maxage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ; }
  7196. if ( defined $minage ) { $minage_epoch = $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ; }
  7197. foreach my $msg ( @msgs_all ) {
  7198. my $idate = $fetch{ $msg }->{'INTERNALDATE'} ;
  7199. #myprint( "$idate\n" ) ;
  7200. if ( defined $maxage and ( epoch( $idate ) >= $maxage_epoch ) ) {
  7201. push @max, $msg ;
  7202. }
  7203. if ( defined $minage and ( epoch( $idate ) <= $minage_epoch ) ) {
  7204. push @min, $msg ;
  7205. }
  7206. }
  7207. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  7208. return( @msgs ) ;
  7209. }
  7210. sub select_msgs_by_age
  7211. {
  7212. my( $imap ) = @_ ;
  7213. my( @max, @min, @msgs, @inter, @union ) ;
  7214. if ( defined $maxage ) {
  7215. @max = $imap->sentsince( $timestart_int - $NB_SECONDS_IN_A_DAY * $maxage ) ;
  7216. }
  7217. if ( defined $minage ) {
  7218. @min = $imap->sentbefore( $timestart_int - $NB_SECONDS_IN_A_DAY * $minage ) ;
  7219. }
  7220. @msgs = msgs_from_maxmin( \@max, \@min ) ;
  7221. return( @msgs ) ;
  7222. }
  7223. sub msgs_from_maxmin
  7224. {
  7225. my( $max_ref, $min_ref ) = @_ ;
  7226. my( @max, @min, @msgs, @inter, @union ) ;
  7227. @max = @{ $max_ref } ;
  7228. @min = @{ $min_ref } ;
  7229. SWITCH: {
  7230. unless( defined $minage ) { @msgs = @max ; last SWITCH } ;
  7231. unless( defined $maxage ) { @msgs = @min ; last SWITCH } ;
  7232. my ( %union, %inter ) ;
  7233. foreach my $m ( @min, @max ) { $union{ $m }++ && $inter{ $m }++ }
  7234. @inter = sort { $a <=> $b } keys %inter ;
  7235. @union = sort { $a <=> $b } keys %union ;
  7236. # normal case
  7237. if ( $minage <= $maxage ) { @msgs = @inter ; last SWITCH } ;
  7238. # just exclude messages between
  7239. if ( $minage > $maxage ) { @msgs = @union ; last SWITCH } ;
  7240. }
  7241. return( @msgs ) ;
  7242. }
  7243. sub tests_msgs_from_maxmin
  7244. {
  7245. note( 'Entering tests_msgs_from_maxmin()' ) ;
  7246. my @msgs ;
  7247. $maxage = $NUMBER_200 ;
  7248. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  7249. ok( 0 == compare_lists( [ '1', '2' ], \@msgs ), 'msgs_from_maxmin: maxage++' ) ;
  7250. $minage = $NUMBER_100 ;
  7251. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  7252. ok( 0 == compare_lists( [ '2' ], \@msgs ), 'msgs_from_maxmin: -maxage++minage-' ) ;
  7253. $minage = $NUMBER_300 ;
  7254. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  7255. ok( 0 == compare_lists( [ '1', '2', '3' ], \@msgs ), 'msgs_from_maxmin: ++maxage-minage++' ) ;
  7256. $maxage = undef ;
  7257. @msgs = msgs_from_maxmin( [ '1', '2' ], [ '2', '3' ] ) ;
  7258. ok( 0 == compare_lists( [ '2', '3' ], \@msgs ), 'msgs_from_maxmin: ++minage-' ) ;
  7259. note( 'Leaving tests_msgs_from_maxmin()' ) ;
  7260. return ;
  7261. }
  7262. sub tests_info_date_from_uid
  7263. {
  7264. note( 'Entering tests_info_date_from_uid()' ) ;
  7265. note( 'Leaving tests_info_date_from_uid()' ) ;
  7266. return ;
  7267. }
  7268. sub info_date_from_uid
  7269. {
  7270. #my $first_uid = $msgs_all[ 0 ] ;
  7271. #my $first_idate = $fetch{ $first_uid }->{'INTERNALDATE'} ;
  7272. #my $first_epoch = epoch( $first_idate ) ;
  7273. #my $first_days = ( $timestart_int - $first_epoch ) / $NB_SECONDS_IN_A_DAY ;
  7274. #myprint( "\nOldest msg has UID $first_uid INTERNALDATE $first_idate EPOCH $first_epoch DAYS AGO $first_days\n" ) ;
  7275. }
  7276. sub lastuid
  7277. {
  7278. my $imap = shift ;
  7279. my $folder = shift ;
  7280. my $lastuid_guess = shift ;
  7281. my $lastuid ;
  7282. # rfc3501: The only reliable way to identify recent messages is to
  7283. # look at message flags to see which have the \Recent flag
  7284. # set, or to do a SEARCH RECENT.
  7285. # SEARCH RECENT doesn't work this way on courrier.
  7286. my @recent_messages ;
  7287. # SEARCH RECENT for each transfer can be expensive with a big folder
  7288. # Call commented for now
  7289. #@recent_messages = $imap->recent( ) ;
  7290. #myprint( "Recent: @recent_messages\n" ) ;
  7291. my $max_recent ;
  7292. $max_recent = max( @recent_messages ) ;
  7293. if ( defined $max_recent and ($lastuid_guess <= $max_recent ) ) {
  7294. $lastuid = $max_recent ;
  7295. }else{
  7296. $lastuid = $lastuid_guess
  7297. }
  7298. return( $lastuid ) ;
  7299. }
  7300. sub size_filtered
  7301. {
  7302. my( $h1_size, $h1_msg, $h1_fold, $h2_fold ) = @_ ;
  7303. $h1_size = 0 if ( ! $h1_size ) ; # null if empty or undef
  7304. if ( defined $sync->{ maxsize } and $h1_size > $sync->{ maxsize } ) {
  7305. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size exceeds maxsize limit $sync->{ maxsize } bytes)\n" ) ;
  7306. $sync->{ total_bytes_skipped } += $h1_size;
  7307. $sync->{ nb_msg_skipped } += 1;
  7308. return( 1 ) ;
  7309. }
  7310. if ( defined $minsize and $h1_size <= $minsize ) {
  7311. myprint( "msg $h1_fold/$h1_msg skipped ($h1_size smaller than minsize $minsize bytes)\n" ) ;
  7312. $sync->{ total_bytes_skipped } += $h1_size;
  7313. $sync->{ nb_msg_skipped } += 1;
  7314. return( 1 ) ;
  7315. }
  7316. return( 0 ) ;
  7317. }
  7318. sub message_exists
  7319. {
  7320. my( $imap, $msg ) = @_ ;
  7321. return( 1 ) if not $imap->Uid( ) ;
  7322. my $search_uid ;
  7323. ( $search_uid ) = $imap->search( "UID $msg" ) ;
  7324. #myprint( "$search ? $msg\n" ) ;
  7325. return( 1 ) if ( $search_uid eq $msg ) ;
  7326. return( 0 ) ;
  7327. }
  7328. # Globals
  7329. # $sync->{ total_bytes_skipped }
  7330. # $sync->{ nb_msg_skipped }
  7331. # $mysync->{ h1_nb_msg_processed }
  7332. sub stats_update_skip_message
  7333. {
  7334. my $mysync = shift ; # to be used
  7335. my $h1_size = shift ;
  7336. $mysync->{ total_bytes_skipped } += $h1_size ;
  7337. $mysync->{ nb_msg_skipped } += 1 ;
  7338. $mysync->{ h1_nb_msg_processed } +=1 ;
  7339. return ;
  7340. }
  7341. sub copy_message
  7342. {
  7343. # copy
  7344. my ( $mysync, $h1_msg, $h1_fold, $h2_fold, $h1_fir_ref, $permanentflags2, $cache_dir ) = @_ ;
  7345. ( $mysync->{ debug } or $mysync->{dry} )
  7346. and myprint( "msg $h1_fold/$h1_msg copying to $h2_fold $mysync->{dry_message} " . eta( $mysync ) . "\n" ) ;
  7347. my $h1_size = $h1_fir_ref->{$h1_msg}->{'RFC822.SIZE'} || 0 ;
  7348. my $h1_flags = $h1_fir_ref->{$h1_msg}->{'FLAGS'} || q{} ;
  7349. my $h1_idate = $h1_fir_ref->{$h1_msg}->{'INTERNALDATE'} || q{} ;
  7350. if ( size_filtered( $h1_size, $h1_msg, $h1_fold, $h2_fold ) ) {
  7351. $mysync->{ h1_nb_msg_processed } +=1 ;
  7352. return ;
  7353. }
  7354. debugsleep( $mysync ) ;
  7355. myprint( "- msg $h1_fold/$h1_msg S[$h1_size] F[$h1_flags] I[$h1_idate] has RFC822.SIZE null!\n" ) if ( ! $h1_size ) ;
  7356. if ( $checkmessageexists and not message_exists( $mysync->{imap1}, $h1_msg ) ) {
  7357. stats_update_skip_message( $mysync, $h1_size ) ;
  7358. return ;
  7359. }
  7360. myprint( debugmemory( $mysync, " at C1" ) ) ;
  7361. my ( $string, $string_len ) ;
  7362. ( $string_len ) = message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, \$string ) ;
  7363. myprint( debugmemory( $mysync, " at C2" ) ) ;
  7364. # not defined or empty $string
  7365. if ( ( not $string ) or ( not $string_len ) ) {
  7366. myprint( "- msg $h1_fold/$h1_msg skipped.\n" ) ;
  7367. stats_update_skip_message( $mysync, $h1_size ) ;
  7368. return ;
  7369. }
  7370. # Lines too long (or not enough) => do no copy or fix
  7371. if ( ( defined $maxlinelength ) or ( defined $minmaxlinelength ) ) {
  7372. $string = linelengthstuff( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) ;
  7373. if ( not defined $string ) {
  7374. stats_update_skip_message( $mysync, $h1_size ) ;
  7375. return ;
  7376. }
  7377. }
  7378. my $h1_date = date_for_host2( $h1_msg, $h1_idate ) ;
  7379. ( $mysync->{ debug } or $debugflags ) and
  7380. myprint( "Host1: flags init msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  7381. $h1_flags = flags_for_host2( $h1_flags, $permanentflags2 ) ;
  7382. ( $mysync->{ debug } or $debugflags ) and
  7383. myprint( "Host1: flags filt msg $h1_fold/$h1_msg date [$h1_date] flags [$h1_flags] size [$h1_size]\n" ) ;
  7384. $h1_date = undef if ( $h1_date eq q{} ) ;
  7385. 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 ) ;
  7386. if ( $new_id and $syncflagsaftercopy ) {
  7387. sync_flags_after_copy( $mysync, $h1_fold, $h1_msg, $h1_flags, $h2_fold, $new_id, $permanentflags2 ) ;
  7388. }
  7389. myprint( debugmemory( $mysync, " at C3" ) ) ;
  7390. return $new_id ;
  7391. }
  7392. sub linelengthstuff
  7393. {
  7394. my( $string, $h1_fold, $h1_msg, $string_len, $h1_size, $h1_flags, $h1_idate ) = @_ ;
  7395. my $maxlinelength_string = max_line_length( $string ) ;
  7396. $debugmaxlinelength and myprint( "msg $h1_fold/$h1_msg maxlinelength: $maxlinelength_string\n" ) ;
  7397. if ( ( defined $minmaxlinelength ) and ( $maxlinelength_string <= $minmaxlinelength ) ) {
  7398. my $subject = subject( $string ) ;
  7399. $debugdev and myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  7400. . "(Subject:[$subject]) (max line length under minmaxlinelength $minmaxlinelength bytes)\n" ) ;
  7401. return ;
  7402. }
  7403. if ( ( defined $maxlinelength ) and ( $maxlinelength_string > $maxlinelength ) ) {
  7404. my $subject = subject( $string ) ;
  7405. if ( $maxlinelengthcmd ) {
  7406. $string = pipemess( $string, $maxlinelengthcmd ) ;
  7407. # string undef means something was bad.
  7408. if ( not ( defined $string ) ) {
  7409. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] "
  7410. . "(Subject:[$subject]) could not be successfully transformed by --maxlinelengthcmd option\n" ) ;
  7411. return ;
  7412. }else{
  7413. return $string ;
  7414. }
  7415. }
  7416. myprint( "- msg $h1_fold/$h1_msg skipped S[$h1_size] F[$h1_flags] I[$h1_idate] "
  7417. . "(Subject:[$subject]) (line length exceeds maxlinelength $maxlinelength bytes)\n" ) ;
  7418. return ;
  7419. }
  7420. return $string ;
  7421. }
  7422. sub message_for_host2
  7423. {
  7424. # global variable list:
  7425. # @skipmess
  7426. # @regexmess
  7427. # @pipemess
  7428. # $debugcontent
  7429. # $debug
  7430. #
  7431. # API current
  7432. #
  7433. # at failure:
  7434. # * return nothing ( will then be undef or () )
  7435. # * $string_ref content is undef or empty
  7436. # at success:
  7437. # * return string length ($string_ref content length)
  7438. # * $string_ref content filled with message
  7439. # API future
  7440. #
  7441. #
  7442. my ( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) = @_ ;
  7443. # abort when missing a parameter
  7444. if ( ( ! $mysync ) or ( ! $h1_msg ) or ( ! $h1_fold ) or ( ! defined $h1_size )
  7445. or ( ! defined $h1_flags) or ( ! defined $h1_idate )
  7446. or ( ! $h1_fir_ref) or ( ! $string_ref ) )
  7447. {
  7448. return ;
  7449. }
  7450. myprint( debugmemory( $mysync, " at M1" ) ) ;
  7451. my $string_ok = $mysync->{imap1}->message_to_file( $string_ref, $h1_msg ) ;
  7452. myprint( debugmemory( $mysync, " at M2" ) ) ;
  7453. my $string_len = length_ref( $string_ref ) ;
  7454. unless ( defined $string_ok and $string_len ) {
  7455. # undef or 0 length
  7456. my $error = join q{},
  7457. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate] could not be fetched: ",
  7458. $mysync->{imap1}->LastError || q{}, "\n" ;
  7459. errors_incr( $mysync, $error ) ;
  7460. $mysync->{ h1_nb_msg_processed } +=1 ;
  7461. return ;
  7462. }
  7463. if ( @skipmess ) {
  7464. my $match = skipmess( ${ $string_ref } ) ;
  7465. # string undef means the eval regex was bad.
  7466. if ( not ( defined $match ) ) {
  7467. myprint(
  7468. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  7469. . " could not be skipped by --skipmess option, bad regex\n" ) ;
  7470. return ;
  7471. }
  7472. if ( $match ) {
  7473. my $subject = subject( ${ $string_ref } ) ;
  7474. myprint( "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  7475. . " (Subject:[$subject]) skipped by --skipmess\n" ) ;
  7476. return ;
  7477. }
  7478. }
  7479. if ( @regexmess ) {
  7480. ${ $string_ref } = regexmess( ${ $string_ref } ) ;
  7481. # string undef means the eval regex was bad.
  7482. if ( not ( defined ${ $string_ref } ) ) {
  7483. myprint(
  7484. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  7485. . " could not be transformed by --regexmess\n" ) ;
  7486. return ;
  7487. }
  7488. }
  7489. if ( @pipemess ) {
  7490. ${ $string_ref } = pipemess( ${ $string_ref }, @pipemess ) ;
  7491. # string undef means something was bad.
  7492. if ( not ( defined ${ $string_ref } ) ) {
  7493. myprint(
  7494. "- msg $h1_fold/$h1_msg {$string_len} S[$h1_size] F[$h1_flags] I[$h1_idate]"
  7495. . " could not be successfully transformed by --pipemess option\n" ) ;
  7496. return ;
  7497. }
  7498. }
  7499. if ( $mysync->{addheader} and defined $h1_fir_ref->{$h1_msg}->{'NO_HEADER'} ) {
  7500. my $header = add_header( $h1_msg ) ;
  7501. $mysync->{ debug } and myprint( "msg $h1_fold/$h1_msg adding custom header [$header]\n" ) ;
  7502. ${ $string_ref } = $header . "\r\n" . ${ $string_ref } ;
  7503. }
  7504. if ( ( defined $mysync->{ truncmess } ) and is_an_integer( $mysync->{ truncmess } ) )
  7505. {
  7506. ${ $string_ref } = truncmess( ${ $string_ref }, $mysync->{ truncmess } ) ;
  7507. }
  7508. $string_len = length_ref( $string_ref ) ;
  7509. $debugcontent and myprint(
  7510. q{=} x $STD_CHAR_PER_LINE, "\n",
  7511. "F message content begin next line ($string_len characters long)\n",
  7512. ${ $string_ref },
  7513. "\nF message content ended on previous line\n", q{=} x $STD_CHAR_PER_LINE, "\n" ) ;
  7514. myprint( debugmemory( $mysync, " at M3" ) ) ;
  7515. return $string_len ;
  7516. }
  7517. sub tests_truncmess
  7518. {
  7519. note( 'Entering tests_truncmess()' ) ;
  7520. is( undef, truncmess( ), 'truncmess: no args => undef' ) ;
  7521. is( 'abc', truncmess( 'abc' ), 'truncmess: abc => abc' ) ;
  7522. is( 'ab', truncmess( 'abc', 2 ), 'truncmess: abc 2 => ab' ) ;
  7523. is( 'abc', truncmess( 'abc', 3 ), 'truncmess: abc 3 => abc' ) ;
  7524. is( 'abc', truncmess( 'abc', 4 ), 'truncmess: abc 4 => abc' ) ;
  7525. is( '12345', truncmess( "123456789\n", 5 ), 'truncmess: "123456789\n", 5 => 12345' ) ;
  7526. is( "123456789\n" x 5000, truncmess( "123456789\n" x 100000, 50000 ), 'truncmess: "123456789\n" x 100000, 50000 => "123456789\n" x 5000' ) ;
  7527. note( 'Leaving tests_truncmess()' ) ;
  7528. return ;
  7529. }
  7530. sub truncmess
  7531. {
  7532. my $string = shift ;
  7533. my $length = shift ;
  7534. if ( not defined $string ) { return ; }
  7535. if ( not defined $length ) { return $string ; }
  7536. $string = substr $string, 0, $length ;
  7537. return $string ;
  7538. }
  7539. sub tests_message_for_host2
  7540. {
  7541. note( 'Entering tests_message_for_host2()' ) ;
  7542. my ( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ) ;
  7543. is( undef, message_for_host2( ), q{message_for_host2: no args} ) ;
  7544. 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} ) ;
  7545. require_ok( "Test::MockObject" ) ;
  7546. my $imapT = Test::MockObject->new( ) ;
  7547. $mysync->{imap1} = $imapT ;
  7548. my $string ;
  7549. $h1_msg = 1 ;
  7550. $h1_fold = 'FoldFoo';
  7551. $h1_size = 9 ;
  7552. $h1_flags = q{} ;
  7553. $h1_idate = '10-Jul-2015 09:00:00 +0200' ;
  7554. $h1_fir_ref = {} ;
  7555. $string_ref = \$string ;
  7556. $imapT->mock( 'message_to_file',
  7557. sub {
  7558. my ( $imap, $mystring_ref, $msg ) = @_ ;
  7559. ${$mystring_ref} = 'blablabla' ;
  7560. return length ${$mystring_ref} ;
  7561. }
  7562. ) ;
  7563. is( 9, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  7564. q{message_for_host2: msg 1 == "blablabla", length} ) ;
  7565. is( 'blablabla', $string, q{message_for_host2: msg 1 == "blablabla", value} ) ;
  7566. # so far so good
  7567. # now the --pipemess stuff
  7568. SKIP: {
  7569. Readonly my $NB_WIN_tests_message_for_host2 => 0 ;
  7570. skip( 'Not on MSWin32', $NB_WIN_tests_message_for_host2 ) if ('MSWin32' ne $OSNAME) ;
  7571. # Windows
  7572. # "type" command does not accept redirection of STDIN with <
  7573. # "sort" does
  7574. } ;
  7575. SKIP: {
  7576. Readonly my $NB_UNX_tests_message_for_host2 => 6 ;
  7577. skip( 'Not on Unix', $NB_UNX_tests_message_for_host2 ) if ('MSWin32' eq $OSNAME) ;
  7578. # Unix
  7579. # no change by cat
  7580. @pipemess = ( 'cat' ) ;
  7581. is( 9, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  7582. q{message_for_host2: --pipemess 'cat', length} ) ;
  7583. is( 'blablabla', $string, q{message_for_host2: --pipemess 'cat', value} ) ;
  7584. # failure by false
  7585. @pipemess = ( 'false' ) ;
  7586. is( undef, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  7587. q{message_for_host2: --pipemess 'false', length} ) ;
  7588. is( undef, $string, q{message_for_host2: --pipemess 'false', value} ) ;
  7589. # failure by true since no output
  7590. @pipemess = ( 'true' ) ;
  7591. is( undef, message_for_host2( $mysync, $h1_msg, $h1_fold, $h1_size, $h1_flags, $h1_idate, $h1_fir_ref, $string_ref ),
  7592. q{message_for_host2: --pipemess 'true', length} ) ;
  7593. is( undef, $string, q{message_for_host2: --pipemess 'true', value} ) ;
  7594. }
  7595. note( 'Leaving tests_message_for_host2()' ) ;
  7596. return ;
  7597. }
  7598. sub tests_labels_remove_subfolder1
  7599. {
  7600. note( 'Entering tests_labels_remove_subfolder1()' ) ;
  7601. is( undef, labels_remove_subfolder1( ), 'labels_remove_subfolder1: no parameters => undef' ) ;
  7602. is( 'Blabla', labels_remove_subfolder1( 'Blabla' ), 'labels_remove_subfolder1: one parameter Blabla => Blabla' ) ;
  7603. is( 'Blan blue', labels_remove_subfolder1( 'Blan blue' ), 'labels_remove_subfolder1: one parameter Blan blue => Blan blue' ) ;
  7604. is( '\Bla "Blan blan" Blabla', labels_remove_subfolder1( '\Bla "Blan blan" Blabla' ),
  7605. 'labels_remove_subfolder1: one parameter \Bla "Blan blan" Blabla => \Bla "Blan blan" Blabla' ) ;
  7606. is( 'Bla', labels_remove_subfolder1( 'Subf/Bla', 'Subf' ), 'labels_remove_subfolder1: Subf/Bla Subf => "Bla"' ) ;
  7607. is( '"\\\\Bla"', labels_remove_subfolder1( '"\\\\Bla"', 'Subf' ), 'labels_remove_subfolder1: "\\\\Bla" Subf => "\\\\Bla"' ) ;
  7608. is( 'Bla Kii', labels_remove_subfolder1( 'Subf/Bla Subf/Kii', 'Subf' ),
  7609. 'labels_remove_subfolder1: Subf/Bla Subf/Kii, Subf => "Bla" "Kii"' ) ;
  7610. is( '"\\\\Bla" Kii', labels_remove_subfolder1( '"\\\\Bla" Subf/Kii', 'Subf' ),
  7611. 'labels_remove_subfolder1: "\\\\Bla" Subf/Kii Subf => "\\\\Bla" Kii' ) ;
  7612. is( '"Blan blan"', labels_remove_subfolder1( '"Subf/Blan blan"', 'Subf' ),
  7613. 'labels_remove_subfolder1: "Subf/Blan blan" Subf => "Blan blan"' ) ;
  7614. is( '"\\\\Loo" "Blan blan" Kii', labels_remove_subfolder1( '"\\\\Loo" "Subf/Blan blan" Subf/Kii', 'Subf' ),
  7615. 'labels_remove_subfolder1: "\\\\Loo" "Subf/Blan blan" Subf/Kii + Subf => "\\\\Loo" "Blan blan" Kii' ) ;
  7616. is( '"\\\\Inbox"', labels_remove_subfolder1( 'Subf/INBOX', 'Subf' ),
  7617. 'labels_remove_subfolder1: Subf/INBOX + Subf => "\\\\Inbox"' ) ;
  7618. is( '"\\\\Loo" "Blan blan" Kii "\\\\Inbox"', labels_remove_subfolder1( '"\\\\Loo" "Subf/Blan blan" Subf/Kii Subf/INBOX', 'Subf' ),
  7619. 'labels_remove_subfolder1: "\\\\Loo" "Subf/Blan blan" Subf/Kii Subf/INBOX + Subf => "\\\\Loo" "Blan blan" Kii "\\\\Inbox"' ) ;
  7620. note( 'Leaving tests_labels_remove_subfolder1()' ) ;
  7621. return ;
  7622. }
  7623. sub labels_remove_subfolder1
  7624. {
  7625. my $labels = shift ;
  7626. my $subfolder1 = shift ;
  7627. if ( not defined $labels ) { return ; }
  7628. if ( not defined $subfolder1 ) { return $labels ; }
  7629. my @labels = quotewords('\s+', 1, $labels ) ;
  7630. #myprint( "@labels\n" ) ;
  7631. my @labels_subfolder2 ;
  7632. foreach my $label ( @labels )
  7633. {
  7634. if ( $label =~ m{zzzzzzzzzz} )
  7635. {
  7636. # \Seen \Deleted ... stay the same
  7637. push @labels_subfolder2, $label ;
  7638. }
  7639. else
  7640. {
  7641. # Remove surrounding quotes if any, to add them again in case of space
  7642. $label = join( q{}, quotewords('\s+', 0, $label ) ) ;
  7643. $label =~ s{$subfolder1/?}{} ;
  7644. if ( 'INBOX' eq $label )
  7645. {
  7646. push @labels_subfolder2, q{"\\\\Inbox"} ;
  7647. }
  7648. elsif ( $label =~ m{\\} )
  7649. {
  7650. push @labels_subfolder2, qq{"\\$label"} ;
  7651. }
  7652. elsif ( $label =~ m{ } )
  7653. {
  7654. push @labels_subfolder2, qq{"$label"} ;
  7655. }
  7656. else
  7657. {
  7658. push @labels_subfolder2, $label ;
  7659. }
  7660. }
  7661. }
  7662. my $labels_subfolder2 = join( ' ', sort uniq( @labels_subfolder2 ) ) ;
  7663. return $labels_subfolder2 ;
  7664. }
  7665. sub tests_labels_remove_special
  7666. {
  7667. note( 'Entering tests_labels_remove_special()' ) ;
  7668. is( undef, labels_remove_special( ), 'labels_remove_special: no parameters => undef' ) ;
  7669. is( q{}, labels_remove_special( q{} ), 'labels_remove_special: empty string => empty string' ) ;
  7670. is( q{}, labels_remove_special( '"\\\\Inbox"' ), 'labels_remove_special:"\\\\Inbox" => empty string' ) ;
  7671. is( q{}, labels_remove_special( '"\\\\Inbox" "\\\\Starred"' ), 'labels_remove_special:"\\\\Inbox" "\\\\Starred" => empty string' ) ;
  7672. is( 'Bar Foo', labels_remove_special( 'Foo Bar' ), 'labels_remove_special:Foo Bar => Bar Foo' ) ;
  7673. is( 'Bar Foo', labels_remove_special( 'Foo Bar "\\\\Inbox"' ), 'labels_remove_special:Foo Bar "\\\\Inbox" => Bar Foo' ) ;
  7674. note( 'Leaving tests_labels_remove_special()' ) ;
  7675. return ;
  7676. }
  7677. sub labels_remove_special
  7678. {
  7679. my $labels = shift ;
  7680. if ( not defined $labels ) { return ; }
  7681. my @labels = quotewords('\s+', 1, $labels ) ;
  7682. myprint( "labels before remove_non_folded: @labels\n" ) ;
  7683. my @labels_remove_special ;
  7684. foreach my $label ( @labels )
  7685. {
  7686. if ( $label =~ m{^\"\\\\} )
  7687. {
  7688. # not kept
  7689. }
  7690. else
  7691. {
  7692. push @labels_remove_special, $label ;
  7693. }
  7694. }
  7695. my $labels_remove_special = join( ' ', sort @labels_remove_special ) ;
  7696. return $labels_remove_special ;
  7697. }
  7698. sub tests_labels_add_subfolder2
  7699. {
  7700. note( 'Entering tests_labels_add_subfolder2()' ) ;
  7701. is( undef, labels_add_subfolder2( ), 'labels_add_subfolder2: no parameters => undef' ) ;
  7702. is( 'Blabla', labels_add_subfolder2( 'Blabla' ), 'labels_add_subfolder2: one parameter Blabla => Blabla' ) ;
  7703. is( 'Blan blue', labels_add_subfolder2( 'Blan blue' ), 'labels_add_subfolder2: one parameter Blan blue => Blan blue' ) ;
  7704. is( '\Bla "Blan blan" Blabla', labels_add_subfolder2( '\Bla "Blan blan" Blabla' ),
  7705. 'labels_add_subfolder2: one parameter \Bla "Blan blan" Blabla => \Bla "Blan blan" Blabla' ) ;
  7706. is( 'Subf/Bla', labels_add_subfolder2( 'Bla', 'Subf' ), 'labels_add_subfolder2: Bla Subf => "Subf/Bla"' ) ;
  7707. is( 'Subf/\Bla', labels_add_subfolder2( '\\\\Bla', 'Subf' ), 'labels_add_subfolder2: \Bla Subf => \Bla' ) ;
  7708. is( 'Subf/Bla Subf/Kii', labels_add_subfolder2( 'Bla Kii', 'Subf' ),
  7709. 'labels_add_subfolder2: Bla Kii Subf => "Subf/Bla" "Subf/Kii"' ) ;
  7710. is( 'Subf/Kii Subf/\Bla', labels_add_subfolder2( '\\\\Bla Kii', 'Subf' ),
  7711. 'labels_add_subfolder2: \Bla Kii Subf => \Bla Subf/Kii' ) ;
  7712. is( '"Subf/Blan blan"', labels_add_subfolder2( '"Blan blan"', 'Subf' ),
  7713. 'labels_add_subfolder2: "Blan blan" Subf => "Subf/Blan blan"' ) ;
  7714. is( '"Subf/Blan blan" Subf/Kii Subf/\Loo', labels_add_subfolder2( '\\\\Loo "Blan blan" Kii', 'Subf' ),
  7715. 'labels_add_subfolder2: \Loo "Blan blan" Kii + Subf => "Subf/Blan blan" Subf/Kii Subf/\Loo' ) ;
  7716. # "\\Inbox" is special, add to subfolder INBOX also because Gmail will but ...
  7717. is( '"Subf/\\\\Inbox" Subf/INBOX', labels_add_subfolder2( '"\\\\Inbox"', 'Subf' ),
  7718. 'labels_add_subfolder2: "\\\\Inbox" Subf => "Subf/\\\\Inbox" Subf/INBOX' ) ;
  7719. # but not with INBOX folder
  7720. is( '"Subf/\\\\Inbox"', labels_add_subfolder2( '"\\\\Inbox"', 'Subf', 'INBOX' ),
  7721. 'labels_add_subfolder2: "\\\\Inbox" Subf INBOX => "Subf/\\\\Inbox"' ) ;
  7722. # two times => one time
  7723. is( '"Subf/\\\\Inbox" Subf/INBOX', labels_add_subfolder2( '"\\\\Inbox" "\\\\Inbox"', 'Subf' ),
  7724. 'labels_add_subfolder2: "\\\\Inbox" "\\\\Inbox" Subf => "Subf/\\\\Inbox"' ) ;
  7725. is( '"Subf/\\\\Starred"', labels_add_subfolder2( '"\\\\Starred"', 'Subf' ),
  7726. 'labels_add_subfolder2: "\\\\Starred" Subf => "Subf/\\\\Starred"' ) ;
  7727. note( 'Leaving tests_labels_add_subfolder2()' ) ;
  7728. return ;
  7729. }
  7730. sub labels_add_subfolder2
  7731. {
  7732. my $labels = shift ;
  7733. my $subfolder2 = shift ;
  7734. my $h1_folder = shift || q{} ;
  7735. if ( not defined $labels ) { return ; }
  7736. if ( not defined $subfolder2 ) { return $labels ; }
  7737. # Isn't it messy?
  7738. if ( 'INBOX' eq $h1_folder )
  7739. {
  7740. $labels .= ' "\\\\Inbox"' ;
  7741. }
  7742. my @labels = uniq( quotewords('\s+', 1, $labels ) ) ;
  7743. myprint( "labels before subfolder2: @labels\n" ) ;
  7744. my @labels_subfolder2 ;
  7745. foreach my $label ( @labels )
  7746. {
  7747. # Isn't it more messy?
  7748. if ( ( q{"\\\\Inbox"} eq $label ) and ( 'INBOX' ne $h1_folder ) )
  7749. {
  7750. if ( $subfolder2 =~ m{ } )
  7751. {
  7752. push @labels_subfolder2, qq{"$subfolder2/INBOX"} ;
  7753. }
  7754. else
  7755. {
  7756. push @labels_subfolder2, "$subfolder2/INBOX" ;
  7757. }
  7758. }
  7759. if ( $label =~ m{^\"\\\\} )
  7760. {
  7761. # \Seen \Deleted ... stay the same
  7762. #push @labels_subfolder2, $label ;
  7763. # Remove surrounding quotes if any, to add them again
  7764. $label = join( q{}, quotewords('\s+', 0, $label ) ) ;
  7765. push @labels_subfolder2, qq{"$subfolder2/\\$label"} ;
  7766. }
  7767. else
  7768. {
  7769. # Remove surrounding quotes if any, to add them again in case of space
  7770. $label = join( q{}, quotewords('\s+', 0, $label ) ) ;
  7771. if ( $label =~ m{ } )
  7772. {
  7773. push @labels_subfolder2, qq{"$subfolder2/$label"} ;
  7774. }
  7775. else
  7776. {
  7777. push @labels_subfolder2, "$subfolder2/$label" ;
  7778. }
  7779. }
  7780. }
  7781. my $labels_subfolder2 = join( ' ', sort @labels_subfolder2 ) ;
  7782. return $labels_subfolder2 ;
  7783. }
  7784. sub tests_labels
  7785. {
  7786. note( 'Entering tests_labels()' ) ;
  7787. is( undef, labels( ), 'labels: no parameters => undef' ) ;
  7788. is( undef, labels( undef ), 'labels: undef => undef' ) ;
  7789. require_ok( "Test::MockObject" ) ;
  7790. my $myimap = Test::MockObject->new( ) ;
  7791. $myimap->mock( 'fetch_hash',
  7792. sub {
  7793. return(
  7794. { '1' => {
  7795. 'X-GM-LABELS' => '\Seen Blabla'
  7796. }
  7797. }
  7798. ) ;
  7799. }
  7800. ) ;
  7801. $myimap->mock( 'Debug' , sub { } ) ;
  7802. $myimap->mock( 'Unescape', sub { return Mail::IMAPClient::Unescape( @_ ) } ) ; # real one
  7803. is( undef, labels( $myimap ), 'labels: one parameter => undef' ) ;
  7804. is( '\Seen Blabla', labels( $myimap, '1' ), 'labels: $mysync UID_1 => \Seen Blabla' ) ;
  7805. note( 'Leaving tests_labels()' ) ;
  7806. return ;
  7807. }
  7808. sub labels
  7809. {
  7810. my ( $myimap, $uid ) = @ARG ;
  7811. if ( not all_defined( $myimap, $uid ) ) {
  7812. return ;
  7813. }
  7814. my $hash = $myimap->fetch_hash( [ $uid ], 'X-GM-LABELS' ) ;
  7815. my $labels = $hash->{ $uid }->{ 'X-GM-LABELS' } ;
  7816. #$labels = $myimap->Unescape( $labels ) ;
  7817. return $labels ;
  7818. }
  7819. sub tests_synclabels
  7820. {
  7821. note( 'Entering tests_synclabels()' ) ;
  7822. is( undef, synclabels( ), 'synclabels: no parameters => undef' ) ;
  7823. is( undef, synclabels( undef ), 'synclabels: undef => undef' ) ;
  7824. my $mysync ;
  7825. is( undef, synclabels( $mysync ), 'synclabels: var undef => undef' ) ;
  7826. require_ok( "Test::MockObject" ) ;
  7827. $mysync = {} ;
  7828. my $myimap1 = Test::MockObject->new( ) ;
  7829. $myimap1->mock( 'fetch_hash',
  7830. sub {
  7831. return(
  7832. { '1' => {
  7833. 'X-GM-LABELS' => '\Seen Blabla'
  7834. }
  7835. }
  7836. ) ;
  7837. }
  7838. ) ;
  7839. $myimap1->mock( 'Debug', sub { } ) ;
  7840. $myimap1->mock( 'Unescape', sub { return Mail::IMAPClient::Unescape( @_ ) } ) ; # real one
  7841. my $myimap2 = Test::MockObject->new( ) ;
  7842. $myimap2->mock( 'store',
  7843. sub {
  7844. return 1 ;
  7845. }
  7846. ) ;
  7847. $mysync->{imap1} = $myimap1 ;
  7848. $mysync->{imap2} = $myimap2 ;
  7849. is( undef, synclabels( $mysync ), 'synclabels: fresh $mysync => undef' ) ;
  7850. is( undef, synclabels( $mysync, '1' ), 'synclabels: $mysync UID_1 alone => undef' ) ;
  7851. is( 1, synclabels( $mysync, '1', '2' ), 'synclabels: $mysync UID_1 UID_2 => 1' ) ;
  7852. note( 'Leaving tests_synclabels()' ) ;
  7853. return ;
  7854. }
  7855. sub synclabels
  7856. {
  7857. my( $mysync, $uid1, $uid2 ) = @ARG ;
  7858. if ( not all_defined( $mysync, $uid1, $uid2 ) ) {
  7859. return ;
  7860. }
  7861. my $myimap1 = $mysync->{ 'imap1' } || return ;
  7862. my $myimap2 = $mysync->{ 'imap2' } || return ;
  7863. $mysync->{debuglabels} and $myimap1->Debug( 1 ) ;
  7864. my $labels1 = labels( $myimap1, $uid1 ) ;
  7865. $mysync->{debuglabels} and $myimap1->Debug( 0 ) ;
  7866. $mysync->{debuglabels} and myprint( "Host1 labels: $labels1\n" ) ;
  7867. if ( $mysync->{ subfolder1 } and $labels1 )
  7868. {
  7869. $labels1 = labels_remove_subfolder1( $labels1, $mysync->{ subfolder1 } ) ;
  7870. $mysync->{debuglabels} and myprint( "Host1 labels with subfolder1: $labels1\n" ) ;
  7871. }
  7872. if ( $mysync->{ subfolder2 } and $labels1 )
  7873. {
  7874. $labels1 = labels_add_subfolder2( $labels1, $mysync->{ subfolder2 } ) ;
  7875. $mysync->{debuglabels} and myprint( "Host1 labels with subfolder2: $labels1\n" ) ;
  7876. }
  7877. my $store ;
  7878. if ( $labels1 and not $mysync->{ dry } )
  7879. {
  7880. $mysync->{ debuglabels } and $myimap2->Debug( 1 ) ;
  7881. $store = $myimap2->store( $uid2, "X-GM-LABELS ($labels1)" ) ;
  7882. $mysync->{ debuglabels } and $myimap2->Debug( 0 ) ;
  7883. }
  7884. return $store ;
  7885. }
  7886. sub tests_resynclabels
  7887. {
  7888. note( 'Entering tests_resynclabels()' ) ;
  7889. is( undef, resynclabels( ), 'resynclabels: no parameters => undef' ) ;
  7890. is( undef, resynclabels( undef ), 'resynclabels: undef => undef' ) ;
  7891. my $mysync ;
  7892. is( undef, resynclabels( $mysync ), 'resynclabels: var undef => undef' ) ;
  7893. my ( $h1_fir_ref, $h2_fir_ref ) ;
  7894. $mysync->{ debuglabels } = 1 ;
  7895. $h1_fir_ref->{ 11 }->{ 'X-GM-LABELS' } = '\Seen Baa Kii' ;
  7896. $h2_fir_ref->{ 22 }->{ 'X-GM-LABELS' } = '\Seen Baa Kii' ;
  7897. # labels are equal
  7898. is( 1, resynclabels( $mysync, 11, 22, $h1_fir_ref, $h2_fir_ref ),
  7899. 'resynclabels: $mysync UID_1 UID_2 labels are equal => 1' ) ;
  7900. # labels are different
  7901. $h2_fir_ref->{ 22 }->{ 'X-GM-LABELS' } = '\Seen Zuu' ;
  7902. require_ok( "Test::MockObject" ) ;
  7903. my $myimap2 = Test::MockObject->new( ) ;
  7904. $myimap2->mock( 'store',
  7905. sub {
  7906. return 1 ;
  7907. }
  7908. ) ;
  7909. $myimap2->mock( 'Debug', sub { } ) ;
  7910. $mysync->{imap2} = $myimap2 ;
  7911. is( 1, resynclabels( $mysync, 11, 22, $h1_fir_ref, $h2_fir_ref ),
  7912. 'resynclabels: $mysync UID_1 UID_2 labels are not equal => store => 1' ) ;
  7913. note( 'Leaving tests_resynclabels()' ) ;
  7914. return ;
  7915. }
  7916. sub resynclabels
  7917. {
  7918. my( $mysync, $uid1, $uid2, $h1_fir_ref, $h2_fir_ref, $h1_folder ) = @ARG ;
  7919. if ( not all_defined( $mysync, $uid1, $uid2, $h1_fir_ref, $h2_fir_ref ) ) {
  7920. return ;
  7921. }
  7922. my $labels1 = $h1_fir_ref->{ $uid1 }->{ 'X-GM-LABELS' } || q{} ;
  7923. my $labels2 = $h2_fir_ref->{ $uid2 }->{ 'X-GM-LABELS' } || q{} ;
  7924. if ( $mysync->{ subfolder1 } and $labels1 )
  7925. {
  7926. $labels1 = labels_remove_subfolder1( $labels1, $mysync->{ subfolder1 } ) ;
  7927. }
  7928. if ( $mysync->{ subfolder2 } and $labels1 )
  7929. {
  7930. $labels1 = labels_add_subfolder2( $labels1, $mysync->{ subfolder2 }, $h1_folder ) ;
  7931. $labels2 = labels_remove_special( $labels2 ) ;
  7932. }
  7933. $mysync->{ debuglabels } and myprint( "Host1 labels fixed: $labels1\n" ) ;
  7934. $mysync->{ debuglabels } and myprint( "Host2 labels : $labels2\n" ) ;
  7935. my $store ;
  7936. if ( $labels1 eq $labels2 )
  7937. {
  7938. # no sync needed
  7939. $mysync->{ debuglabels } and myprint( "Labels are already equal\n" ) ;
  7940. return 1 ;
  7941. }
  7942. elsif ( not $mysync->{ dry } )
  7943. {
  7944. # sync needed
  7945. $mysync->{debuglabels} and $mysync->{imap2}->Debug( 1 ) ;
  7946. $store = $mysync->{imap2}->store( $uid2, "X-GM-LABELS ($labels1)" ) ;
  7947. $mysync->{debuglabels} and $mysync->{imap2}->Debug( 0 ) ;
  7948. }
  7949. return $store ;
  7950. }
  7951. sub tests_uniq
  7952. {
  7953. note( 'Entering tests_uniq()' ) ;
  7954. is( 0, uniq( ), 'uniq: undef => 0' ) ;
  7955. is_deeply( [ 'one' ], [ uniq( 'one' ) ], 'uniq: one => one' ) ;
  7956. is_deeply( [ 'one' ], [ uniq( 'one', 'one' ) ], 'uniq: one one => one' ) ;
  7957. is_deeply( [ 'one', 'two' ], [ uniq( 'one', 'one', 'two', 'one', 'two' ) ], 'uniq: one one two one two => one two' ) ;
  7958. note( 'Leaving tests_uniq()' ) ;
  7959. return ;
  7960. }
  7961. sub uniq
  7962. {
  7963. my @list = @ARG ;
  7964. my %seen = ( ) ;
  7965. my @uniq = ( ) ;
  7966. foreach my $item ( @list ) {
  7967. if ( ! $seen{ $item } ) {
  7968. $seen{ $item } = 1 ;
  7969. push( @uniq, $item ) ;
  7970. }
  7971. }
  7972. return @uniq ;
  7973. }
  7974. sub length_ref
  7975. {
  7976. my $string_ref = shift ;
  7977. my $string_len = defined ${ $string_ref } ? length( ${ $string_ref } ) : q{} ; # length or empty string
  7978. return $string_len ;
  7979. }
  7980. sub tests_length_ref
  7981. {
  7982. note( 'Entering tests_length_ref()' ) ;
  7983. my $notdefined ;
  7984. is( q{}, length_ref( \$notdefined ), q{length_ref: value not defined} ) ;
  7985. my $notref ;
  7986. is( q{}, length_ref( $notref ), q{length_ref: param not a ref} ) ;
  7987. my $lala = 'lala' ;
  7988. is( 4, length_ref( \$lala ), q{length_ref: lala length == 4} ) ;
  7989. is( 4, length_ref( \'lili' ), q{length_ref: lili length == 4} ) ;
  7990. note( 'Leaving tests_length_ref()' ) ;
  7991. return ;
  7992. }
  7993. sub date_for_host2
  7994. {
  7995. my( $h1_msg, $h1_idate ) = @_ ;
  7996. my $h1_date = q{} ;
  7997. if ( $syncinternaldates ) {
  7998. $h1_date = $h1_idate ;
  7999. $sync->{ debug } and myprint( "internal date from host1: [$h1_date]\n" ) ;
  8000. $h1_date = good_date( $h1_date ) ;
  8001. $sync->{ debug } and myprint( "internal date from host1: [$h1_date] (fixed)\n" ) ;
  8002. }
  8003. if ( $idatefromheader ) {
  8004. $h1_date = $sync->{imap1}->get_header( $h1_msg, 'Date' ) ;
  8005. $sync->{ debug } and myprint( "header date from host1: [$h1_date]\n" ) ;
  8006. $h1_date = good_date( $h1_date ) ;
  8007. $sync->{ debug } and myprint( "header date from host1: [$h1_date] (fixed)\n" ) ;
  8008. }
  8009. return( $h1_date ) ;
  8010. }
  8011. sub flags_for_host2
  8012. {
  8013. my( $h1_flags, $permanentflags2 ) = @_ ;
  8014. # RFC 2060: This flag can not be altered by any client
  8015. $h1_flags =~ s@\\Recent\s?@@xgi ;
  8016. my $h1_flags_re ;
  8017. if ( @regexflag and defined( $h1_flags_re = flags_regex( $h1_flags ) ) ) {
  8018. $h1_flags = $h1_flags_re ;
  8019. }
  8020. $h1_flags = flagscase( $h1_flags ) if $flagscase ;
  8021. $h1_flags = flags_filter( $h1_flags, $permanentflags2) if ( $permanentflags2 and $filterflags ) ;
  8022. return( $h1_flags ) ;
  8023. }
  8024. sub subject
  8025. {
  8026. my $string = shift ;
  8027. my $subject = q{} ;
  8028. my $header = extract_header( $string ) ;
  8029. if( $header =~ m/^Subject:\s*([^\n\r]*)\r?$/msx ) {
  8030. #myprint( "MMM[$1]\n" ) ;
  8031. $subject = $1 ;
  8032. }
  8033. return( $subject ) ;
  8034. }
  8035. sub tests_subject
  8036. {
  8037. note( 'Entering tests_subject()' ) ;
  8038. ok( q{} eq subject( q{} ), 'subject: null') ;
  8039. ok( 'toto le hero' eq subject( 'Subject: toto le hero' ), 'subject: toto le hero') ;
  8040. ok( 'toto le hero' eq subject( 'Subject:toto le hero' ), 'subject: toto le hero blank') ;
  8041. ok( 'toto le hero' eq subject( "Subject:toto le hero\r\n" ), 'subject: toto le hero\r\n') ;
  8042. my $MESS ;
  8043. $MESS = <<'EOF';
  8044. From: lalala
  8045. Subject: toto le hero
  8046. Date: zzzzzz
  8047. Boogie boogie
  8048. EOF
  8049. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 2') ;
  8050. $MESS = <<'EOF';
  8051. Subject: toto le hero
  8052. From: lalala
  8053. Date: zzzzzz
  8054. Boogie boogie
  8055. EOF
  8056. ok( 'toto le hero' eq subject( $MESS ), 'subject: toto le hero 3') ;
  8057. $MESS = <<'EOF';
  8058. From: lalala
  8059. Subject: cuicui
  8060. Date: zzzzzz
  8061. Subject: toto le hero
  8062. EOF
  8063. ok( 'cuicui' eq subject( $MESS ), 'subject: cuicui') ;
  8064. $MESS = <<'EOF';
  8065. From: lalala
  8066. Date: zzzzzz
  8067. Subject: toto le hero
  8068. EOF
  8069. ok( q{} eq subject( $MESS ), 'subject: null but body could') ;
  8070. note( 'Leaving tests_subject()' ) ;
  8071. return ;
  8072. }
  8073. # GlobVar
  8074. # $max_msg_size_in_bytes
  8075. # $h2_uidguess
  8076. # ...
  8077. #
  8078. #
  8079. sub append_message_on_host2
  8080. {
  8081. my( $mysync, $string_ref, $h1_fold, $h1_msg, $string_len, $h2_fold, $h1_size, $h1_flags, $h1_date, $cache_dir ) = @_ ;
  8082. myprint( debugmemory( $mysync, " at A1" ) ) ;
  8083. my $new_id ;
  8084. if ( ! $mysync->{dry} ) {
  8085. $max_msg_size_in_bytes = max( $string_len, $max_msg_size_in_bytes ) ;
  8086. $new_id = $mysync->{imap2}->append_string( $h2_fold, ${ $string_ref }, $h1_flags, $h1_date ) ;
  8087. myprint( debugmemory( $mysync, " at A2" ) ) ;
  8088. if ( ! $new_id){
  8089. my $subject = subject( ${ $string_ref } ) ;
  8090. my $error_imap = $mysync->{imap2}->LastError || q{} ;
  8091. 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" ;
  8092. errors_incr( $mysync, $error ) ;
  8093. $mysync->{ h1_nb_msg_processed } +=1 ;
  8094. return ;
  8095. }
  8096. else{
  8097. # good
  8098. # $new_id is an id if the IMAP server has the
  8099. # UIDPLUS capability else just a ref
  8100. if ( $new_id !~ m{^\d+$}x ) {
  8101. $new_id = lastuid( $mysync->{imap2}, $h2_fold, $h2_uidguess ) ;
  8102. }
  8103. if ( $mysync->{ synclabels } ) { synclabels( $mysync, $h1_msg, $new_id ) }
  8104. $h2_uidguess += 1 ;
  8105. $mysync->{ total_bytes_transferred } += $string_len ;
  8106. $mysync->{ nb_msg_transferred } += 1 ;
  8107. $mysync->{ h1_nb_msg_processed } +=1 ;
  8108. my $time_spent = timesince( $mysync->{begin_transfer_time} ) ;
  8109. my $rate = bytes_display_string( $mysync->{total_bytes_transferred} / $time_spent ) ;
  8110. my $eta = eta( $mysync ) ;
  8111. my $amount_transferred = bytes_display_string( $mysync->{total_bytes_transferred} ) ;
  8112. myprintf( "msg %s/%-19s copied to %s/%-10s %.2f msgs/s %s/s %s copied %s\n",
  8113. $h1_fold, "$h1_msg {$string_len}", $h2_fold, $new_id, $mysync->{nb_msg_transferred}/$time_spent, $rate,
  8114. $amount_transferred,
  8115. $eta );
  8116. sleep_if_needed( $mysync ) ;
  8117. if ( $usecache and $cacheaftercopy and $new_id =~ m{^\d+$}x ) {
  8118. $debugcache and myprint( "touch $cache_dir/${h1_msg}_$new_id\n" ) ;
  8119. touch( "$cache_dir/${h1_msg}_$new_id" )
  8120. or croak( "Couldn't touch $cache_dir/${h1_msg}_$new_id" ) ;
  8121. }
  8122. if ( $mysync->{ delete1 } ) {
  8123. delete_message_on_host1( $mysync, $h1_fold, $mysync->{ expungeaftereach }, $h1_msg ) ;
  8124. }
  8125. #myprint( "PRESS ENTER" ) and my $a = <> ;
  8126. return( $new_id ) ;
  8127. }
  8128. }
  8129. else{
  8130. $nb_msg_skipped_dry_mode += 1 ;
  8131. $mysync->{ h1_nb_msg_processed } += 1 ;
  8132. }
  8133. return ;
  8134. }
  8135. sub tests_sleep_if_needed
  8136. {
  8137. note( 'Entering tests_sleep_if_needed()' ) ;
  8138. is( undef, sleep_if_needed( ), 'sleep_if_needed: no args => undef' ) ;
  8139. my $mysync ;
  8140. is( undef, sleep_if_needed( $mysync ), 'sleep_if_needed: arg undef => undef' ) ;
  8141. $mysync->{maxbytespersecond} = 1000 ;
  8142. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: maxbytespersecond only => no sleep => 0' ) ;
  8143. $mysync->{begin_transfer_time} = time ; # now
  8144. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: begin_transfer_time now => no sleep => 0' ) ;
  8145. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before
  8146. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 0 => no sleep => 0' ) ;
  8147. $mysync->{total_bytes_transferred} = 2200 ;
  8148. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before
  8149. is( '0.20', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 2200 since 2s => sleep 0.2s' ) ;
  8150. is( '0', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 2200 since 2+2 == 4s => no sleep' ) ;
  8151. $mysync->{maxsleep} = 0.1 ;
  8152. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before again
  8153. is( '0.10', sleep_if_needed( $mysync ), 'sleep_if_needed: total_bytes_transferred == 4000 since 2s but maxsleep 0.1s => sleep 0.1s' ) ;
  8154. $mysync->{maxbytesafter} = 4000 ;
  8155. $mysync->{begin_transfer_time} = time - 2 ; # 2 s before again
  8156. is( 0, sleep_if_needed( $mysync ), 'sleep_if_needed: maxbytesafter == total_bytes_transferred => no sleep => 0' ) ;
  8157. note( 'Leaving tests_sleep_if_needed()' ) ;
  8158. return ;
  8159. }
  8160. sub sleep_if_needed
  8161. {
  8162. my( $mysync ) = shift ;
  8163. if ( ! $mysync ) {
  8164. return ;
  8165. }
  8166. # No need to go further if there is no limit set
  8167. if ( not ( $mysync->{maxmessagespersecond}
  8168. or $mysync->{maxbytespersecond} )
  8169. ) {
  8170. return ;
  8171. }
  8172. $mysync->{maxsleep} = defined $mysync->{maxsleep} ? $mysync->{maxsleep} : $MAX_SLEEP ;
  8173. # Must be positive
  8174. $mysync->{maxsleep} = max( 0, $mysync->{maxsleep} ) ;
  8175. my $time_spent = timesince( $mysync->{begin_transfer_time} ) ;
  8176. my $sleep_max_messages = sleep_max_messages( $mysync->{nb_msg_transferred}, $time_spent, $mysync->{maxmessagespersecond} ) ;
  8177. my $maxbytesafter = $mysync->{maxbytesafter} || 0 ;
  8178. my $total_bytes_transferred = $mysync->{total_bytes_transferred} || 0 ;
  8179. my $total_bytes_to_consider = $total_bytes_transferred - $maxbytesafter ;
  8180. #myprint( "maxbytesafter:$maxbytesafter\n" ) ;
  8181. #myprint( "total_bytes_to_consider:$total_bytes_to_consider\n" ) ;
  8182. my $sleep_max_bytes = sleep_max_bytes( $total_bytes_to_consider, $time_spent, $mysync->{maxbytespersecond} ) ;
  8183. my $sleep_max = min( $mysync->{maxsleep}, max( $sleep_max_messages, $sleep_max_bytes ) ) ;
  8184. $sleep_max = mysprintf( "%.2f", $sleep_max ) ; # round with 2 decimals.
  8185. if ( $sleep_max > 0 ) {
  8186. myprint( "sleeping $sleep_max s\n" ) ;
  8187. sleep $sleep_max ;
  8188. # Slept
  8189. return $sleep_max ;
  8190. }
  8191. # No sleep
  8192. return 0 ;
  8193. }
  8194. sub sleep_max_messages
  8195. {
  8196. # how long we have to sleep to go under max_messages_per_second
  8197. my( $nb_msg_transferred, $time_spent, $maxmessagespersecond ) = @_ ;
  8198. if ( ( not defined $maxmessagespersecond ) or $maxmessagespersecond <= 0 ) { return( 0 ) } ;
  8199. my $sleep = ( $nb_msg_transferred / $maxmessagespersecond ) - $time_spent ;
  8200. # the sleep must be positive
  8201. return( max( 0, $sleep ) ) ;
  8202. }
  8203. sub tests_sleep_max_messages
  8204. {
  8205. note( 'Entering tests_sleep_max_messages()' ) ;
  8206. ok( 0 == sleep_max_messages( 4, 2, undef ), 'sleep_max_messages: maxmessagespersecond = undef') ;
  8207. ok( 0 == sleep_max_messages( 4, 2, 0 ), 'sleep_max_messages: maxmessagespersecond = 0') ;
  8208. ok( 0 == sleep_max_messages( 4, 2, $MINUS_ONE ), 'sleep_max_messages: maxmessagespersecond = -1') ;
  8209. ok( 0 == sleep_max_messages( 4, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max reached') ;
  8210. ok( 2 == sleep_max_messages( 8, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max over') ;
  8211. ok( 0 == sleep_max_messages( 2, 2, 2 ), 'sleep_max_messages: maxmessagespersecond = 2 max not reached') ;
  8212. note( 'Leaving tests_sleep_max_messages()' ) ;
  8213. return ;
  8214. }
  8215. sub sleep_max_bytes
  8216. {
  8217. # how long we have to sleep to go under max_bytes_per_second
  8218. my( $total_bytes_to_consider, $time_spent, $maxbytespersecond ) = @_ ;
  8219. $total_bytes_to_consider ||= 0 ;
  8220. $time_spent ||= 0 ;
  8221. if ( ( not defined $maxbytespersecond ) or $maxbytespersecond <= 0 ) { return( 0 ) } ;
  8222. #myprint( "total_bytes_to_consider:$total_bytes_to_consider\n" ) ;
  8223. my $sleep = ( $total_bytes_to_consider / $maxbytespersecond ) - $time_spent ;
  8224. # the sleep must be positive
  8225. return( max( 0, $sleep ) ) ;
  8226. }
  8227. sub tests_sleep_max_bytes
  8228. {
  8229. note( 'Entering tests_sleep_max_bytes()' ) ;
  8230. ok( 0 == sleep_max_bytes( 4000, 2, undef ), 'sleep_max_bytes: maxbytespersecond == undef => sleep 0' ) ;
  8231. ok( 0 == sleep_max_bytes( 4000, 2, 0 ), 'sleep_max_bytes: maxbytespersecond = 0 => sleep 0') ;
  8232. ok( 0 == sleep_max_bytes( 4000, 2, $MINUS_ONE ), 'sleep_max_bytes: maxbytespersecond = -1 => sleep 0') ;
  8233. ok( 0 == sleep_max_bytes( 4000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max reached sharp => sleep 0') ;
  8234. ok( 2 == sleep_max_bytes( 8000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max over => sleep a little') ;
  8235. ok( 0 == sleep_max_bytes( -8000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max not reached => sleep 0') ;
  8236. ok( 0 == sleep_max_bytes( 2000, 2, 2000 ), 'sleep_max_bytes: maxbytespersecond = 2k max not reached => sleep 0') ;
  8237. ok( 0 == sleep_max_bytes( -2000, 2, 1000 ), 'sleep_max_bytes: maxbytespersecond = 1k max not reached => sleep 0') ;
  8238. note( 'Leaving tests_sleep_max_bytes()' ) ;
  8239. return ;
  8240. }
  8241. sub delete_message_on_host1
  8242. {
  8243. my( $mysync, $h1_fold, $expunge, @h1_msg ) = @_ ;
  8244. if ( ! $mysync->{ delete1 } ) { return ; }
  8245. if ( ! @h1_msg ) { return ; }
  8246. delete_messages_on_any(
  8247. $mysync,
  8248. $mysync->{imap1},
  8249. "Host1: $h1_fold",
  8250. $expunge,
  8251. $split1,
  8252. @h1_msg ) ;
  8253. return ;
  8254. }
  8255. sub tests_operators_and_exclam_precedence
  8256. {
  8257. note( 'Entering tests_operators_and_exclam_precedence()' ) ;
  8258. is( 1, ! 0, 'tests_operators_and_exclam_precedence: ! 0 => 1' ) ;
  8259. is( "", ! 1, 'tests_operators_and_exclam_precedence: ! 1 => ""' ) ;
  8260. is( 1, not( 0 ), 'tests_operators_and_exclam_precedence: not( 0 ) => 1' ) ;
  8261. is( "", not( 1 ), 'tests_operators_and_exclam_precedence: not( 1 ) => ""' ) ;
  8262. # I wrote those tests to avoid perlcrit "Mixed high and low-precedence booleans"
  8263. # and change sub delete_messages_on_any() but got 4 more warnings... So now commented.
  8264. #is( 0, ( ! 0 and 0 ), 'tests_operators_and_exclam_precedence: ! 0 and 0 ) => 0' ) ;
  8265. #is( 1, ( ! 0 and 1 ), 'tests_operators_and_exclam_precedence: ! 0 and 1 ) => 1' ) ;
  8266. #is( "", ( ! 1 and 0 ), 'tests_operators_and_exclam_precedence: ! 1 and 0 ) => ""' ) ;
  8267. #is( "", ( ! 1 and 1 ), 'tests_operators_and_exclam_precedence: ! 1 and 1 ) => ""' ) ;
  8268. is( 0, ( ! 0 && 0 ), 'tests_operators_and_exclam_precedence: ! 0 && 0 ) => 0' ) ;
  8269. is( 1, ( ! 0 && 1 ), 'tests_operators_and_exclam_precedence: ! 0 && 1 ) => 1' ) ;
  8270. is( "", ( ! 1 && 0 ), 'tests_operators_and_exclam_precedence: ! 1 && 0 ) => ""' ) ;
  8271. is( "", ( ! 1 && 1 ), 'tests_operators_and_exclam_precedence: ! 1 && 1 ) => ""' ) ;
  8272. is( 2, ( ! 0 && 2 ), 'tests_operators_and_exclam_precedence: ! 0 && 2 ) => 1' ) ;
  8273. note( 'Leaving tests_operators_and_exclam_precedence()' ) ;
  8274. return ;
  8275. }
  8276. sub delete_messages_on_any
  8277. {
  8278. my( $mysync, $imap, $hostX_folder, $expunge, $split, @messages ) = @_ ;
  8279. my $expunge_message = q{} ;
  8280. my $dry_message = $mysync->{ dry_message } ;
  8281. $expunge_message = 'and expunged' if ( $expunge ) ;
  8282. # "Host1: msg "
  8283. $imap->Debug( 1 ) ;
  8284. while ( my @messages_part = splice @messages, 0, $split )
  8285. {
  8286. foreach my $message ( @messages_part )
  8287. {
  8288. myprint( "$hostX_folder/$message marking deleted $expunge_message $dry_message\n" ) ;
  8289. }
  8290. if ( ! $mysync->{dry} && @messages_part )
  8291. {
  8292. my $nb_deleted = $imap->delete_message( $imap->Range( @messages_part ) ) ;
  8293. if ( defined $nb_deleted )
  8294. {
  8295. # $nb_deleted is not accurate
  8296. $mysync->{ h1_nb_msg_deleted } += scalar @messages_part ;
  8297. }
  8298. else
  8299. {
  8300. my $error_imap = $imap->LastError || q{} ;
  8301. my $error = join( q{}, "$hostX_folder folder, could not delete ",
  8302. scalar @messages_part, ' messages: ', $error_imap, "\n" ) ;
  8303. errors_incr( $mysync, $error ) ;
  8304. }
  8305. }
  8306. }
  8307. if ( $expunge ) {
  8308. uidexpunge_or_expunge( $mysync, $imap, @messages ) ;
  8309. }
  8310. $imap->Debug( 0 ) ;
  8311. return ;
  8312. }
  8313. sub tests_uidexpunge_or_expunge
  8314. {
  8315. note( 'Entering tests_uidexpunge_or_expunge()' ) ;
  8316. is( undef, uidexpunge_or_expunge( ), 'uidexpunge_or_expunge: no args => undef' ) ;
  8317. my $mysync ;
  8318. is( undef, uidexpunge_or_expunge( $mysync ), 'uidexpunge_or_expunge: undef args => undef' ) ;
  8319. $mysync = {} ;
  8320. is( undef, uidexpunge_or_expunge( $mysync ), 'uidexpunge_or_expunge: arg empty => undef' ) ;
  8321. my $imap ;
  8322. is( undef, uidexpunge_or_expunge( $mysync, $imap ), 'uidexpunge_or_expunge: undef Mail-IMAPClient instance => undef' ) ;
  8323. require_ok( "Test::MockObject" ) ;
  8324. $imap = Test::MockObject->new( ) ;
  8325. is( undef, uidexpunge_or_expunge( $mysync, $imap ), 'uidexpunge_or_expunge: no message (1) to uidexpunge => undef' ) ;
  8326. my @messages = ( ) ;
  8327. is( undef, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: no message (2) to uidexpunge => undef' ) ;
  8328. @messages = ( '2', '1' ) ;
  8329. $imap->mock( 'uidexpunge', sub { return ; } ) ;
  8330. $imap->mock( 'expunge', sub { return ; } ) ;
  8331. is( undef, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: uidexpunge failure => expunge failure => undef' ) ;
  8332. $imap->mock( 'expunge', sub { return 1 ; } ) ;
  8333. is( 1, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: uidexpunge failure => expunge ok => 1' ) ;
  8334. $imap->mock( 'uidexpunge', sub { return 1 ; } ) ;
  8335. is( 1, uidexpunge_or_expunge( $mysync, $imap, @messages ), 'uidexpunge_or_expunge: messages to uidexpunge ok => 1' ) ;
  8336. note( 'Leaving tests_uidexpunge_or_expunge()' ) ;
  8337. return ;
  8338. }
  8339. sub uidexpunge_or_expunge
  8340. {
  8341. my $mysync = shift ;
  8342. my $imap = shift ;
  8343. my @messages = @ARG ;
  8344. if ( ! $imap ) { return ; } ;
  8345. if ( ! @messages ) { return ; } ;
  8346. # Doing uidexpunge
  8347. my @uidexpunge_result = $imap->uidexpunge( @messages ) ;
  8348. if ( @uidexpunge_result ) {
  8349. return 1 ;
  8350. }
  8351. # Failure so doing expunge
  8352. my $expunge_result = $imap->expunge( ) ;
  8353. if ( $expunge_result ) {
  8354. return 1 ;
  8355. }
  8356. # bad trip
  8357. return ;
  8358. }
  8359. sub eta_print
  8360. {
  8361. my $mysync = shift ;
  8362. if ( my $eta = eta( $mysync ) )
  8363. {
  8364. myprint( "$eta\n" ) ;
  8365. }
  8366. return ;
  8367. }
  8368. sub tests_eta
  8369. {
  8370. note( 'Entering tests_eta()' ) ;
  8371. is( q{}, eta( ), 'eta: no args => ""' ) ;
  8372. is( q{}, eta( undef ), 'eta: undef => ""' ) ;
  8373. my $mysync = {} ;
  8374. # No foldersizes
  8375. is( q{}, eta( $mysync ), 'eta: No foldersizes => ""' ) ;
  8376. $mysync->{ foldersizes } = 1 ;
  8377. $mysync->{ begin_transfer_time } = time ; # Now
  8378. $mysync->{ h1_nb_msg_processed } = 0 ;
  8379. is( "ETA: " . localtime( time ) . " 0 s 0/0 msgs left",
  8380. eta( $mysync ),
  8381. 'eta: no args => ETA: "Now" 0 s 0/0 msgs left' ) ;
  8382. $mysync->{ h1_nb_msg_processed } = 1 ;
  8383. $mysync->{ h1_nb_msg_start } = 2 ;
  8384. is( "ETA: " . localtime( time ) . " 0 s 1/2 msgs left",
  8385. eta( $mysync ),
  8386. 'eta: 1, 1, 2 => ETA: "Now" 0 s 1/2 msgs left' ) ;
  8387. note( 'Leaving tests_eta()' ) ;
  8388. return ;
  8389. }
  8390. sub eta
  8391. {
  8392. my( $mysync ) = shift ;
  8393. if ( ! $mysync )
  8394. {
  8395. return q{} ;
  8396. }
  8397. return( q{} ) if not $mysync->{ foldersizes } ;
  8398. my $h1_nb_msg_start = $mysync->{ h1_nb_msg_start } ;
  8399. my $h1_nb_processed = $mysync->{ h1_nb_msg_processed } ;
  8400. my $nb_msg_transferred = ( $mysync->{dry} ) ? $mysync->{ h1_nb_msg_processed } : $mysync->{ nb_msg_transferred } ;
  8401. my $time_spent = timesince( $mysync->{ begin_transfer_time } ) ;
  8402. $h1_nb_processed ||= 0 ;
  8403. $h1_nb_msg_start ||= 0 ;
  8404. $time_spent ||= 0 ;
  8405. my $time_remaining = time_remaining( $time_spent, $h1_nb_processed, $h1_nb_msg_start, $nb_msg_transferred ) ;
  8406. $mysync->{ debug } and myprint( "time_spent: $time_spent time_remaining: $time_remaining\n" ) ;
  8407. my $nb_msg_remaining = $h1_nb_msg_start - $h1_nb_processed ;
  8408. my $eta_date = localtime( time + $time_remaining ) ;
  8409. return( mysprintf( 'ETA: %s %1.0f s %s/%s msgs left',
  8410. $eta_date, $time_remaining, $nb_msg_remaining, $h1_nb_msg_start ) ) ;
  8411. }
  8412. sub time_remaining
  8413. {
  8414. my( $my_time_spent, $h1_nb_processed, $h1_nb_msg_start, $nb_transferred ) = @_ ;
  8415. $nb_transferred ||= 1 ; # At least one is done (no division by zero)
  8416. $h1_nb_processed ||= 0 ;
  8417. $h1_nb_msg_start ||= $h1_nb_processed ;
  8418. $my_time_spent ||= 0 ;
  8419. my $time_remaining = ( $my_time_spent / $nb_transferred ) * ( $h1_nb_msg_start - $h1_nb_processed ) ;
  8420. return( $time_remaining ) ;
  8421. }
  8422. sub tests_time_remaining
  8423. {
  8424. note( 'Entering tests_time_remaining()' ) ;
  8425. # time_spent, nb_processed, nb_to_do_total, nb_transferred
  8426. is( 0, time_remaining( ), 'time_remaining: no args -> 0' ) ;
  8427. is( 0, time_remaining( 0, 0, 0, 0 ), 'time_remaining: 0, 0, 0, 0 -> 0' ) ;
  8428. is( 1, time_remaining( 1, 1, 2, 1 ), 'time_remaining: 1, 1, 2, 1 -> 1' ) ;
  8429. is( 1, time_remaining( 9, 9, 10, 9 ), 'time_remaining: 9, 9, 10, 9 -> 1' ) ;
  8430. is( 9, time_remaining( 1, 1, 10, 1 ), 'time_remaining: 1, 1, 10, 1 -> 9' ) ;
  8431. is( 5, time_remaining( 5, 5, 10, 5 ), 'time_remaining: 5, 5, 10, 5 -> 5' ) ;
  8432. is( 25, time_remaining( 5, 5, 10, 0 ), 'time_remaining: 5, 5, 10, 0 -> ( 5 / 1 ) * ( 10 - 5) = 25' ) ;
  8433. is( 25, time_remaining( 5, 5, 10, 1 ), 'time_remaining: 5, 5, 10, 1 -> ( 5 / 1 ) * ( 10 - 5) = 25' ) ;
  8434. note( 'Leaving tests_time_remaining()' ) ;
  8435. return ;
  8436. }
  8437. sub cache_map
  8438. {
  8439. my ( $cache_files_ref, $h1_msgs_ref, $h2_msgs_ref ) = @_;
  8440. my ( %map1_2, %map2_1, %done2 ) ;
  8441. my $h1_msgs_hash_ref = { } ;
  8442. my $h2_msgs_hash_ref = { } ;
  8443. @{ $h1_msgs_hash_ref }{ @{ $h1_msgs_ref } } = ( ) ;
  8444. @{ $h2_msgs_hash_ref }{ @{ $h2_msgs_ref } } = ( ) ;
  8445. foreach my $file ( sort @{ $cache_files_ref } ) {
  8446. $debugcache and myprint( "C12: $file\n" ) ;
  8447. ( $uid1, $uid2 ) = match_a_cache_file( $file ) ;
  8448. if ( exists( $h1_msgs_hash_ref->{ defined $uid1 ? $uid1 : q{} } )
  8449. and exists( $h2_msgs_hash_ref->{ defined $uid2 ? $uid2 : q{} } ) ) {
  8450. # keep only the greatest uid2
  8451. # 130_2301 and
  8452. # 130_231 => keep only 130 -> 2301
  8453. # keep only the greatest uid1
  8454. # 1601_260 and
  8455. # 161_260 => keep only 1601 -> 260
  8456. my $max_uid2 = max( $uid2, $map1_2{ $uid1 } || $MINUS_ONE ) ;
  8457. if ( exists $done2{ $max_uid2 } ) {
  8458. if ( $done2{ $max_uid2 } < $uid1 ) {
  8459. $map1_2{ $uid1 } = $max_uid2 ;
  8460. delete $map1_2{ $done2{ $max_uid2 } } ;
  8461. $done2{ $max_uid2 } = $uid1 ;
  8462. }
  8463. }else{
  8464. $map1_2{ $uid1 } = $max_uid2 ;
  8465. $done2{ $max_uid2 } = $uid1 ;
  8466. }
  8467. };
  8468. }
  8469. %map2_1 = reverse %map1_2 ;
  8470. return( \%map1_2, \%map2_1) ;
  8471. }
  8472. sub tests_cache_map
  8473. {
  8474. note( 'Entering tests_cache_map()' ) ;
  8475. #$debugcache = 1 ;
  8476. my @cache_files = qw (
  8477. 100_200
  8478. 101_201
  8479. 120_220
  8480. 142_242
  8481. 143_243
  8482. 177_277
  8483. 177_278
  8484. 177_279
  8485. 155_255
  8486. 180_280
  8487. 181_280
  8488. 182_280
  8489. 130_231
  8490. 130_2301
  8491. 161_260
  8492. 1601_260
  8493. ) ;
  8494. my $msgs_1 = [120, 142, 143, 144, 161, 1601, 177, 182, 130 ];
  8495. my $msgs_2 = [ 242, 243, 260, 299, 377, 279, 255, 280, 231, 2301 ];
  8496. my( $c12, $c21 ) ;
  8497. ok( ( $c12, $c21 ) = cache_map( \@cache_files, $msgs_1, $msgs_2 ), 'cache_map: 02' );
  8498. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  8499. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  8500. ok( 0 == compare_lists( [ 130, 142, 143, 177, 182, 1601 ], $a1 ), 'cache_map: 03' );
  8501. ok( 0 == compare_lists( [ 242, 243, 260, 279, 280, 2301 ], $a2 ), 'cache_map: 04' );
  8502. ok( ! $c12->{161}, 'cache_map: ! 161 -> 260' );
  8503. ok( 260 == $c12->{1601}, 'cache_map: 1601 -> 260' );
  8504. ok( 2301 == $c12->{130}, 'cache_map: 130 -> 2301' );
  8505. #myprint( $c12->{1601}, "\n" ) ;
  8506. note( 'Leaving tests_cache_map()' ) ;
  8507. return ;
  8508. }
  8509. sub cache_dir_fix
  8510. {
  8511. my $cache_dir = shift ;
  8512. $cache_dir =~ s/([;<>\*\|`&\$!#\(\)\[\]\{\}:'"\\])/\\$1/xg ;
  8513. #myprint( "cache_dir_fix: $cache_dir\n" ) ;
  8514. return( $cache_dir ) ;
  8515. }
  8516. sub tests_cache_dir_fix
  8517. {
  8518. note( 'Entering tests_cache_dir_fix()' ) ;
  8519. ok( 'lalala' eq cache_dir_fix('lalala'), 'cache_dir_fix: lalala -> lalala' );
  8520. ok( 'ii\\\\ii' eq cache_dir_fix('ii\ii'), 'cache_dir_fix: ii\ii -> ii\\\\ii' );
  8521. ok( 'ii@ii' eq cache_dir_fix('ii@ii'), 'cache_dir_fix: ii@ii -> ii@ii' );
  8522. ok( 'ii@ii\\:ii' eq cache_dir_fix('ii@ii:ii'), 'cache_dir_fix: ii@ii:ii -> ii@ii\\:ii' );
  8523. ok( 'i\\\\i\\\\ii' eq cache_dir_fix('i\i\ii'), 'cache_dir_fix: i\i\ii -> i\\\\i\\\\ii' );
  8524. ok( 'i\\\\ii' eq cache_dir_fix('i\\ii'), 'cache_dir_fix: i\\ii -> i\\\\\\\\ii' );
  8525. ok( '\\\\ ' eq cache_dir_fix('\\ '), 'cache_dir_fix: \\ -> \\\\\ ' );
  8526. ok( '\\\\ ' eq cache_dir_fix('\ '), 'cache_dir_fix: \ -> \\\\\ ' );
  8527. ok( '\[bracket\]' eq cache_dir_fix('[bracket]'), 'cache_dir_fix: [bracket] -> \[bracket\]' );
  8528. note( 'Leaving tests_cache_dir_fix()' ) ;
  8529. return ;
  8530. }
  8531. sub cache_dir_fix_win
  8532. {
  8533. my $cache_dir = shift ;
  8534. $cache_dir =~ s/(\[|\])/[$1]/xg ;
  8535. #myprint( "cache_dir_fix_win: $cache_dir\n" ) ;
  8536. return( $cache_dir ) ;
  8537. }
  8538. sub tests_cache_dir_fix_win
  8539. {
  8540. note( 'Entering tests_cache_dir_fix_win()' ) ;
  8541. ok( 'lalala' eq cache_dir_fix_win('lalala'), 'cache_dir_fix_win: lalala -> lalala' );
  8542. ok( '[[]bracket[]]' eq cache_dir_fix_win('[bracket]'), 'cache_dir_fix_win: [bracket] -> [[]bracket[]]' );
  8543. note( 'Leaving tests_cache_dir_fix_win()' ) ;
  8544. return ;
  8545. }
  8546. sub get_cache
  8547. {
  8548. my ( $cache_dir, $h1_msgs_ref, $h2_msgs_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_;
  8549. $debugcache and myprint( "Entering get_cache\n" ) ;
  8550. -d $cache_dir or return( undef ); # exit if cache directory doesn't exist
  8551. $debugcache and myprint( "cache_dir : $cache_dir\n" ) ;
  8552. if ( 'MSWin32' ne $OSNAME ) {
  8553. $cache_dir = cache_dir_fix( $cache_dir ) ;
  8554. }else{
  8555. $cache_dir = cache_dir_fix_win( $cache_dir ) ;
  8556. }
  8557. $debugcache and myprint( "cache_dir_fix: $cache_dir\n" ) ;
  8558. my @cache_files = bsd_glob( "$cache_dir/*" ) ;
  8559. #$debugcache and myprint( "cache_files: [@cache_files]\n" ) ;
  8560. $debugcache and myprint( 'cache_files: ', scalar @cache_files , " files found\n" ) ;
  8561. my( $cache_1_2_ref, $cache_2_1_ref )
  8562. = cache_map( \@cache_files, $h1_msgs_ref, $h2_msgs_ref ) ;
  8563. clean_cache( \@cache_files, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) ;
  8564. $debugcache and myprint( "Exiting get_cache\n" ) ;
  8565. return( $cache_1_2_ref, $cache_2_1_ref ) ;
  8566. }
  8567. sub tests_get_cache
  8568. {
  8569. note( 'Entering tests_get_cache()' ) ;
  8570. ok( not( get_cache('/cache_no_exist') ), 'get_cache: /cache_no_exist' );
  8571. ok( ( not -d 'W/tmp/cache/F1/F2' or rmtree( 'W/tmp/cache/F1/F2' ) ), 'get_cache: rmtree W/tmp/cache/F1/F2' ) ;
  8572. ok( mkpath( 'W/tmp/cache/F1/F2' ), 'get_cache: mkpath W/tmp/cache/F1/F2' ) ;
  8573. my @test_files_cache = ( qw(
  8574. W/tmp/cache/F1/F2/100_200
  8575. W/tmp/cache/F1/F2/101_201
  8576. W/tmp/cache/F1/F2/120_220
  8577. W/tmp/cache/F1/F2/142_242
  8578. W/tmp/cache/F1/F2/143_243
  8579. W/tmp/cache/F1/F2/177_277
  8580. W/tmp/cache/F1/F2/177_377
  8581. W/tmp/cache/F1/F2/177_777
  8582. W/tmp/cache/F1/F2/155_255
  8583. ) ) ;
  8584. ok( touch( @test_files_cache ), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  8585. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  8586. # on live:
  8587. my $msgs_1 = [120, 142, 143, 144, 177 ];
  8588. my $msgs_2 = [ 242, 243, 299, 377, 777, 255 ];
  8589. my $msgs_all_1 = { 120 => 0, 142 => 0, 143 => 0, 144 => 0, 177 => 0 } ;
  8590. my $msgs_all_2 = { 242 => 0, 243 => 0, 299 => 0, 377 => 0, 777 => 0, 255 => 0 } ;
  8591. my( $c12, $c21 ) ;
  8592. ok( ( $c12, $c21 ) = get_cache( 'W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  8593. my $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  8594. my $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  8595. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: 03' );
  8596. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: 04' );
  8597. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  8598. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  8599. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file removed 100_200');
  8600. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file removed 101_201');
  8601. # test clean_cache executed
  8602. $maxage = 2 ;
  8603. ok( touch(@test_files_cache), 'get_cache: touch W/tmp/cache/F1/F2/...' ) ;
  8604. ok( ( $c12, $c21 ) = get_cache('W/tmp/cache/F1/F2', $msgs_1, $msgs_2, $msgs_all_1, $msgs_all_2 ), 'get_cache: 02' );
  8605. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 142_242');
  8606. ok( -f 'W/tmp/cache/F1/F2/142_242', 'get_cache: file kept 143_243');
  8607. ok( ! -f 'W/tmp/cache/F1/F2/100_200', 'get_cache: file NOT removed 100_200');
  8608. ok( ! -f 'W/tmp/cache/F1/F2/101_201', 'get_cache: file NOT removed 101_201');
  8609. # strange files
  8610. #$debugcache = 1 ;
  8611. $maxage = undef ;
  8612. ok( ( not -d 'W/tmp/cache/rr\uee' or rmtree( 'W/tmp/cache/rr\uee' )), 'get_cache: rmtree W/tmp/cache/rr\uee' ) ;
  8613. ok( mkpath( 'W/tmp/cache/rr\uee' ), 'get_cache: mkpath W/tmp/cache/rr\uee' ) ;
  8614. @test_files_cache = ( qw(
  8615. W/tmp/cache/rr\uee/100_200
  8616. W/tmp/cache/rr\uee/101_201
  8617. W/tmp/cache/rr\uee/120_220
  8618. W/tmp/cache/rr\uee/142_242
  8619. W/tmp/cache/rr\uee/143_243
  8620. W/tmp/cache/rr\uee/177_277
  8621. W/tmp/cache/rr\uee/177_377
  8622. W/tmp/cache/rr\uee/177_777
  8623. W/tmp/cache/rr\uee/155_255
  8624. ) ) ;
  8625. ok( touch(@test_files_cache), 'get_cache: touch strange W/tmp/cache/...' ) ;
  8626. # on cache: 100_200 101_201 142_242 143_243 177_277 177_377 177_777 155_255
  8627. # on live:
  8628. $msgs_1 = [120, 142, 143, 144, 177 ] ;
  8629. $msgs_2 = [ 242, 243, 299, 377, 777, 255 ] ;
  8630. $msgs_all_1 = { 120 => q{}, 142 => q{}, 143 => q{}, 144 => q{}, 177 => q{} } ;
  8631. $msgs_all_2 = { 242 => q{}, 243 => q{}, 299 => q{}, 377 => q{}, 777 => q{}, 255 => q{} } ;
  8632. 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' );
  8633. $a1 = [ sort { $a <=> $b } keys %{ $c12 } ] ;
  8634. $a2 = [ sort { $a <=> $b } keys %{ $c21 } ] ;
  8635. ok( 0 == compare_lists( [ 142, 143, 177 ], $a1 ), 'get_cache: strange path 03' );
  8636. ok( 0 == compare_lists( [ 242, 243, 777 ], $a2 ), 'get_cache: strange path 04' );
  8637. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 142_242');
  8638. ok( -f 'W/tmp/cache/rr\uee/142_242', 'get_cache: strange path file kept 143_243');
  8639. ok( ! -f 'W/tmp/cache/rr\uee/100_200', 'get_cache: strange path file removed 100_200');
  8640. ok( ! -f 'W/tmp/cache/rr\uee/101_201', 'get_cache: strange path file removed 101_201');
  8641. note( 'Leaving tests_get_cache()' ) ;
  8642. return ;
  8643. }
  8644. sub match_a_cache_file
  8645. {
  8646. my $file = shift ;
  8647. my ( $cache_uid1, $cache_uid2 ) ;
  8648. return( ( undef, undef ) ) if ( ! $file ) ;
  8649. if ( $file =~ m{(?:^|/)(\d+)_(\d+)$}x ) {
  8650. $cache_uid1 = $1 ;
  8651. $cache_uid2 = $2 ;
  8652. }
  8653. return( $cache_uid1, $cache_uid2 ) ;
  8654. }
  8655. sub tests_match_a_cache_file
  8656. {
  8657. note( 'Entering tests_match_a_cache_file()' ) ;
  8658. my ( $tuid1, $tuid2 ) ;
  8659. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( ), 'match_a_cache_file: no arg' ) ;
  8660. ok( ! defined $tuid1 , 'match_a_cache_file: no arg 1' ) ;
  8661. ok( ! defined $tuid2 , 'match_a_cache_file: no arg 2' ) ;
  8662. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( q{} ), 'match_a_cache_file: empty arg' ) ;
  8663. ok( ! defined $tuid1 , 'match_a_cache_file: empty arg 1' ) ;
  8664. ok( ! defined $tuid2 , 'match_a_cache_file: empty arg 2' ) ;
  8665. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '000_000' ), 'match_a_cache_file: 000_000' ) ;
  8666. ok( '000' eq $tuid1, 'match_a_cache_file: 000_000 1' ) ;
  8667. ok( '000' eq $tuid2, 'match_a_cache_file: 000_000 2' ) ;
  8668. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '123_456' ), 'match_a_cache_file: 123_456' ) ;
  8669. ok( '123' eq $tuid1, 'match_a_cache_file: 123_456 1' ) ;
  8670. ok( '456' eq $tuid2, 'match_a_cache_file: 123_456 2' ) ;
  8671. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/tmp/truc/123_456' ), 'match_a_cache_file: /tmp/truc/123_456' ) ;
  8672. ok( '123' eq $tuid1, 'match_a_cache_file: /tmp/truc/123_456 1' ) ;
  8673. ok( '456' eq $tuid2, 'match_a_cache_file: /tmp/truc/123_456 2' ) ;
  8674. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( '/lala123_456' ), 'match_a_cache_file: NO /lala123_456' ) ;
  8675. ok( ! $tuid1, 'match_a_cache_file: /lala123_456 1' ) ;
  8676. ok( ! $tuid2, 'match_a_cache_file: /lala123_456 2' ) ;
  8677. ok( ( $tuid1, $tuid2 ) = match_a_cache_file( 'la123_456' ), 'match_a_cache_file: NO la123_456' ) ;
  8678. ok( ! $tuid1, 'match_a_cache_file: la123_456 1' ) ;
  8679. ok( ! $tuid2, 'match_a_cache_file: la123_456 2' ) ;
  8680. note( 'Leaving tests_match_a_cache_file()' ) ;
  8681. return ;
  8682. }
  8683. sub clean_cache
  8684. {
  8685. my ( $cache_files_ref, $cache_1_2_ref, $h1_msgs_all_hash_ref, $h2_msgs_all_hash_ref ) = @_ ;
  8686. $debugcache and myprint( "Entering clean_cache\n" ) ;
  8687. $debugcache and myprint( map { "$_ -> " . $cache_1_2_ref->{ $_ } . "\n" } keys %{ $cache_1_2_ref } ) ;
  8688. foreach my $file ( @{ $cache_files_ref } ) {
  8689. $debugcache and myprint( "$file\n" ) ;
  8690. my ( $cache_uid1, $cache_uid2 ) = match_a_cache_file( $file ) ;
  8691. $debugcache and myprint( "u1: $cache_uid1 u2: $cache_uid2 c12: ", $cache_1_2_ref->{ $cache_uid1 } || q{}, "\n") ;
  8692. # or ( ! exists( $cache_1_2_ref->{ $cache_uid1 } ) )
  8693. # or ( ! ( $cache_uid2 == $cache_1_2_ref->{ $cache_uid1 } ) )
  8694. if ( ( not defined $cache_uid1 )
  8695. or ( not defined $cache_uid2 )
  8696. or ( not exists $h1_msgs_all_hash_ref->{ $cache_uid1 } )
  8697. or ( not exists $h2_msgs_all_hash_ref->{ $cache_uid2 } )
  8698. ) {
  8699. $debugcache and myprint( "remove $file\n" ) ;
  8700. unlink $file or myprint( "$OS_ERROR" ) ;
  8701. }
  8702. }
  8703. $debugcache and myprint( "Exiting clean_cache\n" ) ;
  8704. return( 1 ) ;
  8705. }
  8706. sub tests_clean_cache
  8707. {
  8708. note( 'Entering tests_clean_cache()' ) ;
  8709. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache: rmtree W/tmp/cache/G1/G2' ) ;
  8710. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache: mkpath W/tmp/cache/G1/G2' ) ;
  8711. my @test_files_cache = ( qw(
  8712. W/tmp/cache/G1/G2/100_200
  8713. W/tmp/cache/G1/G2/101_201
  8714. W/tmp/cache/G1/G2/120_220
  8715. W/tmp/cache/G1/G2/142_242
  8716. W/tmp/cache/G1/G2/143_243
  8717. W/tmp/cache/G1/G2/177_277
  8718. W/tmp/cache/G1/G2/177_377
  8719. W/tmp/cache/G1/G2/177_777
  8720. W/tmp/cache/G1/G2/155_255
  8721. ) ) ;
  8722. ok( touch(@test_files_cache), 'clean_cache: touch W/tmp/cache/G1/G2/...' ) ;
  8723. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 before' );
  8724. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 before' );
  8725. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 before' );
  8726. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 before' );
  8727. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 before' );
  8728. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 before' );
  8729. my $cache = {
  8730. 142 => 242,
  8731. 177 => 777,
  8732. } ;
  8733. my $all_1 = {
  8734. 142 => q{},
  8735. 177 => q{},
  8736. } ;
  8737. my $all_2 = {
  8738. 200 => q{},
  8739. 242 => q{},
  8740. 777 => q{},
  8741. } ;
  8742. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache: ' ) ;
  8743. ok( ! -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache: 100_200 after' );
  8744. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache: 142_242 after' );
  8745. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache: 177_277 after' );
  8746. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache: 177_377 after' );
  8747. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache: 177_777 after' );
  8748. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache: 155_255 after' );
  8749. note( 'Leaving tests_clean_cache()' ) ;
  8750. return ;
  8751. }
  8752. sub tests_clean_cache_2
  8753. {
  8754. note( 'Entering tests_clean_cache_2()' ) ;
  8755. ok( ( not -d 'W/tmp/cache/G1/G2' or rmtree( 'W/tmp/cache/G1/G2' )), 'clean_cache_2: rmtree W/tmp/cache/G1/G2' ) ;
  8756. ok( mkpath( 'W/tmp/cache/G1/G2' ), 'clean_cache_2: mkpath W/tmp/cache/G1/G2' ) ;
  8757. my @test_files_cache = ( qw(
  8758. W/tmp/cache/G1/G2/100_200
  8759. W/tmp/cache/G1/G2/101_201
  8760. W/tmp/cache/G1/G2/120_220
  8761. W/tmp/cache/G1/G2/142_242
  8762. W/tmp/cache/G1/G2/143_243
  8763. W/tmp/cache/G1/G2/177_277
  8764. W/tmp/cache/G1/G2/177_377
  8765. W/tmp/cache/G1/G2/177_777
  8766. W/tmp/cache/G1/G2/155_255
  8767. ) ) ;
  8768. ok( touch(@test_files_cache), 'clean_cache_2: touch W/tmp/cache/G1/G2/...' ) ;
  8769. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 before' );
  8770. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 before' );
  8771. ok( -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 before' );
  8772. ok( -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 before' );
  8773. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 before' );
  8774. ok( -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 before' );
  8775. my $cache = {
  8776. 142 => 242,
  8777. 177 => 777,
  8778. } ;
  8779. my $all_1 = {
  8780. $NUMBER_100 => q{},
  8781. 142 => q{},
  8782. 177 => q{},
  8783. } ;
  8784. my $all_2 = {
  8785. 200 => q{},
  8786. 242 => q{},
  8787. 777 => q{},
  8788. } ;
  8789. ok( clean_cache( \@test_files_cache, $cache, $all_1, $all_2 ), 'clean_cache_2: ' ) ;
  8790. ok( -f 'W/tmp/cache/G1/G2/100_200', 'clean_cache_2: 100_200 after' );
  8791. ok( -f 'W/tmp/cache/G1/G2/142_242', 'clean_cache_2: 142_242 after' );
  8792. ok( ! -f 'W/tmp/cache/G1/G2/177_277', 'clean_cache_2: 177_277 after' );
  8793. ok( ! -f 'W/tmp/cache/G1/G2/177_377', 'clean_cache_2: 177_377 after' );
  8794. ok( -f 'W/tmp/cache/G1/G2/177_777', 'clean_cache_2: 177_777 after' );
  8795. ok( ! -f 'W/tmp/cache/G1/G2/155_255', 'clean_cache_2: 155_255 after' );
  8796. note( 'Leaving tests_clean_cache_2()' ) ;
  8797. return ;
  8798. }
  8799. sub tests_mkpath
  8800. {
  8801. note( 'Entering tests_mkpath()' ) ;
  8802. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' )), 'mkpath: mkpath W/tmp/tests/' ) ;
  8803. SKIP: {
  8804. skip( 'Tests only for Unix', 10 ) if ( 'MSWin32' eq $OSNAME ) ;
  8805. my $long_path_unix = '123456789/' x 30 ;
  8806. ok( ( -d "W/tmp/tests/long/$long_path_unix" or mkpath( "W/tmp/tests/long/$long_path_unix" ) ), 'mkpath: mkpath 300 char' ) ;
  8807. ok( -d "W/tmp/tests/long/$long_path_unix", 'mkpath: mkpath > 300 char verified' ) ;
  8808. ok( ( -d "W/tmp/tests/long/$long_path_unix" and rmtree( 'W/tmp/tests/long/' ) ), 'mkpath: rmtree 300 char' ) ;
  8809. ok( ! -d "W/tmp/tests/long/$long_path_unix", 'mkpath: rmtree 300 char verified' ) ;
  8810. ok( ( -d 'W/tmp/tests/trailing_dots...' or mkpath( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: mkpath trailing_dots...' ) ;
  8811. ok( -d 'W/tmp/tests/trailing_dots...', 'mkpath: mkpath trailing_dots... verified' ) ;
  8812. ok( ( -d 'W/tmp/tests/trailing_dots...' and rmtree( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: rmtree trailing_dots...' ) ;
  8813. ok( ! -d 'W/tmp/tests/trailing_dots...', 'mkpath: rmtree trailing_dots... verified' ) ;
  8814. eval { ok( 1 / 0, 'mkpath: divide by 0' ) ; } or ok( 1, 'mkpath: can not divide by 0' ) ;
  8815. ok( 1, 'mkpath: still alive' ) ;
  8816. } ;
  8817. SKIP: {
  8818. skip( 'Tests only for MSWin32', 13 ) if ( 'MSWin32' ne $OSNAME ) ;
  8819. my $long_path_2_prefix = ".\\imapsync_tests" || '\\\?\\E:\\TEMP\\imapsync_tests' ;
  8820. myprint( "long_path_2_prefix: $long_path_2_prefix\n" ) ;
  8821. my $long_path_100 = $long_path_2_prefix . '\\' . '123456789\\' x 10 . 'END' ;
  8822. my $long_path_300 = $long_path_2_prefix . '\\' . '123456789\\' x 30 . 'END' ;
  8823. #myprint( "$long_path_100\n" ) ;
  8824. ok( ( -d $long_path_2_prefix or mkpath( $long_path_2_prefix ) ), 'mkpath: -d mkpath small path' ) ;
  8825. ok( ( -d $long_path_2_prefix ), 'mkpath: -d mkpath small path done' ) ;
  8826. ok( ( -d $long_path_100 or mkpath( $long_path_100 ) ), 'mkpath: mkpath > 100 char' ) ;
  8827. ok( ( -d $long_path_100 ), 'mkpath: -d mkpath > 200 char done' ) ;
  8828. ok( ( -d $long_path_2_prefix and rmtree( $long_path_2_prefix ) ), 'mkpath: rmtree > 100 char' ) ;
  8829. ok( (! -d $long_path_2_prefix ), 'mkpath: ! -d rmtree done' ) ;
  8830. # Without the eval the following mkpath 300 just kill the whole process without a whisper
  8831. #myprint( "$long_path_300\n" ) ;
  8832. eval { ok( ( -d $long_path_300 or mkpath( $long_path_300 ) ), 'mkpath: create a path with 300 characters' ) ; }
  8833. or ok( 1, 'mkpath: can not create a path with 300 characters' ) ;
  8834. ok( ( ( ! -d $long_path_300 ) or -d $long_path_300 and rmtree( $long_path_300 ) ), 'mkpath: rmtree the 300 character path' ) ;
  8835. ok( 1, 'mkpath: still alive' ) ;
  8836. ok( ( -d 'W/tmp/tests/trailing_dots...' or mkpath( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: mkpath trailing_dots...' ) ;
  8837. ok( -d 'W/tmp/tests/trailing_dots...', 'mkpath: mkpath trailing_dots... verified' ) ;
  8838. ok( ( -d 'W/tmp/tests/trailing_dots...' and rmtree( 'W/tmp/tests/trailing_dots...' ) ), 'mkpath: rmtree trailing_dots...' ) ;
  8839. ok( ! -d 'W/tmp/tests/trailing_dots...', 'mkpath: rmtree trailing_dots... verified' ) ;
  8840. } ;
  8841. note( 'Leaving tests_mkpath()' ) ;
  8842. # Keep this because of the eval used by the caller (failed badly?)
  8843. return 1 ;
  8844. }
  8845. sub tests_touch
  8846. {
  8847. note( 'Entering tests_touch()' ) ;
  8848. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' )), 'touch: mkpath W/tmp/tests/' ) ;
  8849. ok( 1 == touch( 'W/tmp/tests/lala'), 'touch: W/tmp/tests/lala') ;
  8850. ok( 1 == touch( 'W/tmp/tests/\y'), 'touch: W/tmp/tests/\y') ;
  8851. ok( 0 == touch( '/no/no/no/aaa'), 'touch: not /aaa') ;
  8852. ok( 1 == touch( 'W/tmp/tests/lili', 'W/tmp/tests/lolo'), 'touch: 2 files') ;
  8853. ok( 0 == touch( 'W/tmp/tests/\y', '/no/no/aaa'), 'touch: 2 files, 1 fails' ) ;
  8854. note( 'Leaving tests_touch()' ) ;
  8855. return ;
  8856. }
  8857. sub touch
  8858. {
  8859. my @files = @_ ;
  8860. my $failures = 0 ;
  8861. foreach my $file ( @files ) {
  8862. my $fh = IO::File->new ;
  8863. if ( $fh->open(">> $file" ) ) {
  8864. $fh->close ;
  8865. }else{
  8866. myprint( "Could not open file $file in write/append mode\n" ) ;
  8867. $failures++ ;
  8868. }
  8869. }
  8870. return( ! $failures );
  8871. }
  8872. sub tests_tmpdir_has_colon_bug
  8873. {
  8874. note( 'Entering tests_tmpdir_has_colon_bug()' ) ;
  8875. ok( 0 == tmpdir_has_colon_bug( q{} ), 'tmpdir_has_colon_bug: ' ) ;
  8876. ok( 0 == tmpdir_has_colon_bug( '/tmp' ), 'tmpdir_has_colon_bug: /tmp' ) ;
  8877. ok( 1 == tmpdir_has_colon_bug( 'C:' ), 'tmpdir_has_colon_bug: C:' ) ;
  8878. ok( 1 == tmpdir_has_colon_bug( 'C:\temp' ), 'tmpdir_has_colon_bug: C:\temp' ) ;
  8879. note( 'Leaving tests_tmpdir_has_colon_bug()' ) ;
  8880. return ;
  8881. }
  8882. sub tmpdir_has_colon_bug
  8883. {
  8884. my $path = shift ;
  8885. my $path_filtered = filter_forbidden_characters( $path ) ;
  8886. if ( $path_filtered ne $path ) {
  8887. ( -d $path_filtered ) and myprint( "Path $path was previously mistakely changed to $path_filtered\n" ) ;
  8888. return( 1 ) ;
  8889. }
  8890. return( 0 ) ;
  8891. }
  8892. sub tmpdir_fix_colon_bug
  8893. {
  8894. my $mysync = shift ;
  8895. my $err = 0 ;
  8896. if ( not (-d $mysync->{ tmpdir } and -r _ and -w _) ) {
  8897. myprint( "tmpdir $mysync->{ tmpdir } is not valid\n" ) ;
  8898. return( 0 ) ;
  8899. }
  8900. my $cachedir_new = "$mysync->{ tmpdir }/imapsync_cache" ;
  8901. if ( not tmpdir_has_colon_bug( $cachedir_new ) ) { return( 0 ) } ;
  8902. # check if old cache directory already exists
  8903. my $cachedir_old = filter_forbidden_characters( $cachedir_new ) ;
  8904. if ( not ( -d $cachedir_old ) ) {
  8905. myprint( "Old cache directory $cachedir_new no exists, nothing to do\n" ) ;
  8906. return( 1 ) ;
  8907. }
  8908. # check if new cache directory already exists
  8909. if ( -d $cachedir_new ) {
  8910. myprint( "New fixed cache directory $cachedir_new already exists, not moving the old one $cachedir_old. Fix this manually.\n" ) ;
  8911. return( 0 ) ;
  8912. }else{
  8913. # move the old one to the new place
  8914. myprint( "Moving $cachedir_old to $cachedir_new Do not interrupt this task.\n" ) ;
  8915. File::Copy::Recursive::rmove( $cachedir_old, $cachedir_new )
  8916. or do {
  8917. myprint( "Could not move $cachedir_old to $cachedir_new\n" ) ;
  8918. $err++ ;
  8919. } ;
  8920. # check it succeeded
  8921. if ( -d $cachedir_new and -r _ and -w _ ) {
  8922. myprint( "New fixed cache directory $cachedir_new ok\n" ) ;
  8923. }else{
  8924. myprint( "New fixed cache directory $cachedir_new does not exist\n" ) ;
  8925. $err++ ;
  8926. }
  8927. if ( -d $cachedir_old ) {
  8928. myprint( "Old cache directory $cachedir_old still exists\n" ) ;
  8929. $err++ ;
  8930. }else{
  8931. myprint( "Old cache directory $cachedir_old successfuly moved\n" ) ;
  8932. }
  8933. }
  8934. return( not $err ) ;
  8935. }
  8936. sub tests_cache_folder
  8937. {
  8938. note( 'Entering tests_cache_folder()' ) ;
  8939. ok( '/path/fold1/fold2' eq cache_folder( q{}, '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  8940. ok( '/pa_th/fold1/fold2' eq cache_folder( q{}, '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  8941. 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' ) ;
  8942. ok( 'D:/path/fold1/fold2' eq cache_folder( 'D:', '/path', 'fold1', 'fold2'), 'cache_folder: /path, fold1, fold2 -> /path/fold1/fold2' ) ;
  8943. ok( 'D:/pa_th/fold1/fold2' eq cache_folder( 'D:', '/pa*th', 'fold1', 'fold2'), 'cache_folder: /pa*th, fold1, fold2 -> /path/fold1/fold2' ) ;
  8944. 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' ) ;
  8945. ok( '//' eq cache_folder( q{}, q{}, q{}, q{}), 'cache_folder: -> //' ) ;
  8946. ok( '//_______' eq cache_folder( q{}, q{}, q{}, '*|?:"<>'), 'cache_folder: *|?:"<> -> //_______' ) ;
  8947. note( 'Leaving tests_cache_folder()' ) ;
  8948. return ;
  8949. }
  8950. sub cache_folder
  8951. {
  8952. my( $cache_base, $cache_dir, $h1_fold, $h2_fold ) = @_ ;
  8953. my $sep_1 = $sync->{ h1_sep } || '/';
  8954. my $sep_2 = $sync->{ h2_sep } || '/';
  8955. #myprint( "$cache_dir h1_fold $h1_fold sep1 $sep_1 h2_fold $h2_fold sep2 $sep_2\n" ) ;
  8956. $h1_fold = convert_sep_to_slash( $h1_fold, $sep_1 ) ;
  8957. $h2_fold = convert_sep_to_slash( $h2_fold, $sep_2 ) ;
  8958. my $cache_folder = "$cache_base" . filter_forbidden_characters( "$cache_dir/$h1_fold/$h2_fold" ) ;
  8959. #myprint( "cache_folder [$cache_folder]\n" ) ;
  8960. return( $cache_folder ) ;
  8961. }
  8962. sub tests_filter_forbidden_characters
  8963. {
  8964. note( 'Entering tests_filter_forbidden_characters()' ) ;
  8965. ok( 'a_b' eq filter_forbidden_characters( 'a_b' ), 'filter_forbidden_characters: a_b -> a_b' ) ;
  8966. ok( 'a_b' eq filter_forbidden_characters( 'a*b' ), 'filter_forbidden_characters: a*b -> a_b' ) ;
  8967. ok( 'a_b' eq filter_forbidden_characters( 'a|b' ), 'filter_forbidden_characters: a|b -> a_b' ) ;
  8968. ok( 'a_b' eq filter_forbidden_characters( 'a?b' ), 'filter_forbidden_characters: a?b -> a_b' ) ;
  8969. ok( 'a_______b' eq filter_forbidden_characters( 'a*|?:"<>b' ), 'filter_forbidden_characters: a*|?:"<>b -> a_______b' ) ;
  8970. SKIP: {
  8971. skip( 'Not on MSWin32', 1 ) if ( 'MSWin32' eq $OSNAME ) ;
  8972. ok( ( 'a b ' eq filter_forbidden_characters( 'a b ' ) ), 'filter_forbidden_characters: "a b " -> "a b "' ) ;
  8973. } ;
  8974. SKIP: {
  8975. skip( 'Only on MSWin32', 2 ) if ( 'MSWin32' ne $OSNAME ) ;
  8976. ok( ( ' a b_' eq filter_forbidden_characters( ' a b ' ) ), 'filter_forbidden_characters: "a b " -> "a b_"' ) ;
  8977. ok( ( ' a b_/ c d_' eq filter_forbidden_characters( ' a b / c d ' ) ), 'filter_forbidden_characters: " a b / c d " -> "a b_/ c d_"' ) ;
  8978. } ;
  8979. ok( 'a_b' eq filter_forbidden_characters( "a\tb" ), 'filter_forbidden_characters: a\tb -> a_b' ) ;
  8980. ok( "a_b" eq filter_forbidden_characters( "a\rb" ), 'filter_forbidden_characters: a\rb -> a_b' ) ;
  8981. ok( "a_b" eq filter_forbidden_characters( "a\nb" ), 'filter_forbidden_characters: a\nb -> a_b' ) ;
  8982. ok( "a_b" eq filter_forbidden_characters( "a\\b" ), 'filter_forbidden_characters: a\b -> a_b' ) ;
  8983. note( 'Leaving tests_filter_forbidden_characters()' ) ;
  8984. return ;
  8985. }
  8986. sub filter_forbidden_characters
  8987. {
  8988. my $string = shift ;
  8989. if ( ! defined $string ) { return ; }
  8990. if ( 'MSWin32' eq $OSNAME ) {
  8991. # Move trailing whitespace to _ " a b /c d " -> " a b_/c d_"
  8992. $string =~ s{\ (/|$)}{_$1}xg ;
  8993. }
  8994. $string =~ s{[\Q*|?:"<>\E\t\r\n\\]}{_}xg ;
  8995. #myprint( "[$string]\n" ) ;
  8996. return( $string ) ;
  8997. }
  8998. sub tests_convert_sep_to_slash
  8999. {
  9000. note( 'Entering tests_convert_sep_to_slash()' ) ;
  9001. ok(q{} eq convert_sep_to_slash(q{}, '/'), 'convert_sep_to_slash: no folder');
  9002. ok('INBOX' eq convert_sep_to_slash('INBOX', '/'), 'convert_sep_to_slash: INBOX');
  9003. ok('INBOX/foo' eq convert_sep_to_slash('INBOX/foo', '/'), 'convert_sep_to_slash: INBOX/foo');
  9004. ok('INBOX/foo' eq convert_sep_to_slash('INBOX_foo', '_'), 'convert_sep_to_slash: INBOX_foo');
  9005. ok('INBOX/foo/zob' eq convert_sep_to_slash('INBOX_foo_zob', '_'), 'convert_sep_to_slash: INBOX_foo_zob');
  9006. ok('INBOX/foo' eq convert_sep_to_slash('INBOX.foo', '.'), 'convert_sep_to_slash: INBOX.foo');
  9007. ok('INBOX/foo/hi' eq convert_sep_to_slash('INBOX.foo.hi', '.'), 'convert_sep_to_slash: INBOX.foo.hi');
  9008. note( 'Leaving tests_convert_sep_to_slash()' ) ;
  9009. return ;
  9010. }
  9011. sub convert_sep_to_slash
  9012. {
  9013. my ( $folder, $sep ) = @_ ;
  9014. $folder =~ s{\Q$sep\E}{/}xg ;
  9015. return( $folder ) ;
  9016. }
  9017. sub tests_regexmess
  9018. {
  9019. note( 'Entering tests_regexmess()' ) ;
  9020. ok( 'blabla' eq regexmess( 'blabla' ), 'regexmess, no regexmess, nothing to do' ) ;
  9021. @regexmess = ( 'lalala' ) ;
  9022. ok( not( defined regexmess( 'popopo' ) ), 'regexmess, bad regex lalala' ) ;
  9023. @regexmess = ( 's/p/Z/g' ) ;
  9024. ok( 'ZoZoZo' eq regexmess( 'popopo' ), 'regexmess, s/p/Z/g' ) ;
  9025. @regexmess = ( 's{c}{C}gxms' ) ;
  9026. ok("H1: abC\nH2: Cde\n\nBody abC"
  9027. eq regexmess( "H1: abc\nH2: cde\n\nBody abc"),
  9028. 'regexmess, c->C');
  9029. @regexmess = ( 's{\AFrom\ }{From:}gxms' ) ;
  9030. ok( q{}
  9031. eq regexmess(q{}),
  9032. 'From mbox 1 add colon blank');
  9033. ok( 'From:<tartanpion@machin.truc>'
  9034. eq regexmess('From <tartanpion@machin.truc>'),
  9035. 'From mbox 2 add colo');
  9036. ok( "\n" . 'From <tartanpion@machin.truc>'
  9037. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  9038. 'From mbox 3 add colo') ;
  9039. ok( "From: zzz\n" . 'From <tartanpion@machin.truc>'
  9040. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  9041. 'From mbox 4 add colo') ;
  9042. @regexmess = ( 's{\AFrom\ [^\n]*(\n)?}{}gxms' ) ;
  9043. ok( q{}
  9044. eq regexmess(q{}),
  9045. 'From mbox 1 remove, blank');
  9046. ok( q{}
  9047. eq regexmess('From <tartanpion@machin.truc>'),
  9048. 'From mbox 2 remove');
  9049. ok( "\n" . 'From <tartanpion@machin.truc>'
  9050. eq regexmess("\n" . 'From <tartanpion@machin.truc>'),
  9051. 'From mbox 3 remove');
  9052. #myprint( "[", regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'), "]" ) ;
  9053. ok( q{} . 'From <tartanpion@machin.truc>'
  9054. eq regexmess("From zzz\n" . 'From <tartanpion@machin.truc>'),
  9055. 'From mbox 4 remove');
  9056. ok(
  9057. <<'EOM'
  9058. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9059. From:<tartanpion@machin.truc>
  9060. Hello,
  9061. Bye.
  9062. EOM
  9063. eq regexmess(
  9064. <<'EOM'
  9065. From zzz
  9066. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9067. From:<tartanpion@machin.truc>
  9068. Hello,
  9069. Bye.
  9070. EOM
  9071. ), 'From mbox 5 remove');
  9072. @regexmess = ( 's{\A((?:[^\n]+\n)+|)^Disposition-Notification-To:[^\n]*\n(\r?\n|.*\n\r?\n)}{$1$2}xms' ) ; # SUPER SUPER BEST!
  9073. ok(
  9074. <<'EOM'
  9075. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9076. From:<tartanpion@machin.truc>
  9077. Hello,
  9078. Bye.
  9079. EOM
  9080. eq regexmess(
  9081. <<'EOM'
  9082. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9083. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9084. From:<tartanpion@machin.truc>
  9085. Hello,
  9086. Bye.
  9087. EOM
  9088. ),
  9089. 'regexmess: 1 Delete header Disposition-Notification-To:');
  9090. ok(
  9091. <<'EOM'
  9092. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9093. From:<tartanpion@machin.truc>
  9094. Hello,
  9095. Bye.
  9096. EOM
  9097. eq regexmess(
  9098. <<'EOM'
  9099. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9100. From:<tartanpion@machin.truc>
  9101. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9102. Hello,
  9103. Bye.
  9104. EOM
  9105. ),
  9106. 'regexmess: 2 Delete header Disposition-Notification-To:');
  9107. ok(
  9108. <<'EOM'
  9109. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9110. From:<tartanpion@machin.truc>
  9111. Hello,
  9112. Bye.
  9113. EOM
  9114. eq regexmess(
  9115. <<'EOM'
  9116. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9117. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9118. From:<tartanpion@machin.truc>
  9119. Hello,
  9120. Bye.
  9121. EOM
  9122. ),
  9123. 'regexmess: 3 Delete header Disposition-Notification-To:');
  9124. ok(
  9125. <<'EOM'
  9126. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9127. From:<tartanpion@machin.truc>
  9128. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9129. Bye.
  9130. EOM
  9131. eq regexmess(
  9132. <<'EOM'
  9133. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9134. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9135. From:<tartanpion@machin.truc>
  9136. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9137. Bye.
  9138. EOM
  9139. ),
  9140. 'regexmess: 4 Delete header Disposition-Notification-To:');
  9141. ok(
  9142. <<'EOM'
  9143. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9144. From:<tartanpion@machin.truc>
  9145. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9146. Bye.
  9147. EOM
  9148. eq regexmess(
  9149. <<'EOM'
  9150. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9151. From:<tartanpion@machin.truc>
  9152. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9153. Bye.
  9154. EOM
  9155. ),
  9156. 'regexmess: 5 Delete header Disposition-Notification-To:');
  9157. ok(
  9158. <<'EOM'
  9159. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9160. From:<tartanpion@machin.truc>
  9161. Hello,
  9162. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9163. Bye.
  9164. EOM
  9165. eq regexmess(
  9166. <<'EOM'
  9167. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9168. From:<tartanpion@machin.truc>
  9169. Hello,
  9170. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9171. Bye.
  9172. EOM
  9173. ),
  9174. 'regexmess: 6 Delete header Disposition-Notification-To:');
  9175. ok(
  9176. <<'EOM'
  9177. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9178. From:<tartanpion@machin.truc>
  9179. Hello,
  9180. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9181. Bye.
  9182. EOM
  9183. eq regexmess(
  9184. <<'EOM'
  9185. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9186. From:<tartanpion@machin.truc>
  9187. Hello,
  9188. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9189. Bye.
  9190. EOM
  9191. ),
  9192. 'regexmess: 7 Delete header Disposition-Notification-To:');
  9193. ok(
  9194. <<'EOM'
  9195. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9196. From:<tartanpion@machin.truc>
  9197. Hello,
  9198. Bye.
  9199. EOM
  9200. eq regexmess(
  9201. <<'EOM'
  9202. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9203. From:<tartanpion@machin.truc>
  9204. Hello,
  9205. Bye.
  9206. EOM
  9207. ),
  9208. 'regexmess: 8 Delete header Disposition-Notification-To:');
  9209. ok(
  9210. <<'EOM'
  9211. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9212. From:<tartanpion@machin.truc>
  9213. Hello,
  9214. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9215. Bye.
  9216. EOM
  9217. eq regexmess(
  9218. <<'EOM'
  9219. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9220. From:<tartanpion@machin.truc>
  9221. Hello,
  9222. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9223. Bye.
  9224. EOM
  9225. ),
  9226. 'regexmess: 9 Delete header Disposition-Notification-To:');
  9227. ok(
  9228. <<'EOM'
  9229. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9230. From:<tartanpion@machin.truc>
  9231. Hello,
  9232. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9233. Bye.
  9234. EOM
  9235. eq regexmess(
  9236. <<'EOM'
  9237. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9238. From:<tartanpion@machin.truc>
  9239. Hello,
  9240. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9241. Bye.
  9242. EOM
  9243. ),
  9244. 'regexmess: 10 Delete header Disposition-Notification-To:');
  9245. ok(
  9246. <<'EOM'
  9247. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9248. From:<tartanpion@machin.truc>
  9249. Hello,
  9250. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9251. Bye.
  9252. EOM
  9253. eq regexmess(
  9254. <<'EOM'
  9255. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9256. From:<tartanpion@machin.truc>
  9257. Hello,
  9258. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9259. Bye.
  9260. EOM
  9261. ),
  9262. 'regexmess: 11 Delete header Disposition-Notification-To:');
  9263. ok(
  9264. <<'EOM'
  9265. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9266. From:<tartanpion@machin.truc>
  9267. Hello,
  9268. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9269. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9270. Bye.
  9271. EOM
  9272. eq regexmess(
  9273. <<'EOM'
  9274. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9275. From:<tartanpion@machin.truc>
  9276. Hello,
  9277. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9278. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9279. Bye.
  9280. EOM
  9281. ),
  9282. 'regexmess: 12 Delete header Disposition-Notification-To:');
  9283. @regexmess = ( 's{\A(.*?(?! ^$))^Disposition-Notification-To:(.*?)$}{$1X-Disposition-Notification-To:$2}igxms' ) ; # BAD!
  9284. @regexmess = ( 's{\A((?:[^\n]+\n)+|)(^Disposition-Notification-To:[^\n]*\n)(\r?\n|.*\n\r?\n)}{$1X-$2$3}ims' ) ;
  9285. ok(
  9286. <<'EOM'
  9287. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9288. From:<tartanpion@machin.truc>
  9289. Hello,
  9290. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9291. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9292. Bye.
  9293. EOM
  9294. eq regexmess(
  9295. <<'EOM'
  9296. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9297. From:<tartanpion@machin.truc>
  9298. Hello,
  9299. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9300. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9301. Bye.
  9302. EOM
  9303. ),
  9304. 'regexmess: 13 Delete header Disposition-Notification-To:');
  9305. ok(
  9306. <<'EOM'
  9307. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9308. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9309. From:<tartanpion@machin.truc>
  9310. Hello,
  9311. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9312. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9313. Bye.
  9314. EOM
  9315. eq regexmess(
  9316. <<'EOM'
  9317. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9318. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9319. From:<tartanpion@machin.truc>
  9320. Hello,
  9321. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9322. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9323. Bye.
  9324. EOM
  9325. ),
  9326. 'regexmess: 14 Delete header Disposition-Notification-To:');
  9327. ok(
  9328. <<'EOM'
  9329. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9330. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9331. From:<tartanpion@machin.truc>
  9332. Hello,
  9333. Bye.
  9334. EOM
  9335. eq regexmess(
  9336. <<'EOM'
  9337. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9338. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9339. From:<tartanpion@machin.truc>
  9340. Hello,
  9341. Bye.
  9342. EOM
  9343. ),
  9344. 'regexmess: 15 Delete header Disposition-Notification-To:');
  9345. ok(
  9346. <<'EOM'
  9347. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9348. From:<tartanpion@machin.truc>
  9349. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9350. Hello,
  9351. Bye.
  9352. EOM
  9353. eq regexmess(
  9354. <<'EOM'
  9355. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9356. From:<tartanpion@machin.truc>
  9357. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9358. Hello,
  9359. Bye.
  9360. EOM
  9361. ),
  9362. 'regexmess: 16 Delete header Disposition-Notification-To:');
  9363. ok(
  9364. <<'EOM'
  9365. X-Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9366. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9367. From:<tartanpion@machin.truc>
  9368. Hello,
  9369. Bye.
  9370. EOM
  9371. eq regexmess(
  9372. <<'EOM'
  9373. Disposition-Notification-To: Gilles LAMIRAL <gilles@lamiral.info>
  9374. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9375. From:<tartanpion@machin.truc>
  9376. Hello,
  9377. Bye.
  9378. EOM
  9379. ),
  9380. 'regexmess: 17 Delete header Disposition-Notification-To:');
  9381. @regexmess = ( 's/.{11}\K.*//gs' ) ;
  9382. is( "0123456789\n", regexmess( "0123456789\n" x 100 ), 'regexmess, truncate whole message after 11 characters' ) ;
  9383. is( "0123456789\n", regexmess( "0123456789\n" x 100_000 ), 'regexmess, truncate whole message after 11 characters ~ 1MB' ) ;
  9384. @regexmess = ( 's/.{10000}\K.*//gs' ) ;
  9385. is( "123456789\n" x 1000, regexmess( "123456789\n" x 100_000 ), 'regexmess, truncate whole message after 10000 characters ~ 1MB' ) ;
  9386. @regexmess = ( 's/^(X-Ham-Report.*?\n)^X-/X-/sm' ) ;
  9387. is(
  9388. <<'EOM'
  9389. X-Spam-Score: -1
  9390. X-Spam-Bar: /
  9391. X-Spam-Flag: NO
  9392. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9393. From:<tartanpion@machin.truc>
  9394. Hello,
  9395. Bye.
  9396. EOM
  9397. ,
  9398. regexmess(
  9399. <<'EOM'
  9400. X-Spam-Score: -1
  9401. X-Spam-Bar: /
  9402. X-Ham-Report: =?utf-8?Q?Spam_detection_software=2C_running?=
  9403. =?utf-8?Q?_on_the_system_=22ohp-ag006.int200?=
  9404. _has_NOT_identified_thi?=
  9405. =?utf-8?Q?s_incoming_email_as_spam.__The_o?=
  9406. _message_has_been_attac?=
  9407. =?utf-8?Q?hed_to_this_so_you_can_view_it_o?=
  9408. ___________________________?=
  9409. =?utf-8?Q?__author's_domain
  9410. X-Spam-Flag: NO
  9411. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9412. From:<tartanpion@machin.truc>
  9413. Hello,
  9414. Bye.
  9415. EOM
  9416. ),
  9417. 'regexmess: 1 Delete header X-Ham-Report:');
  9418. # regex to play with Date: from the FAQ
  9419. #@regexmess = 's{\A(.*?(?! ^$))^Date:(.*?)$}{$1Date:$2\nX-Date:$2}gxms'
  9420. note( 'Leaving tests_regexmess()' ) ;
  9421. return ;
  9422. }
  9423. sub regexmess
  9424. {
  9425. my ( $string ) = @_ ;
  9426. foreach my $regexmess ( @regexmess ) {
  9427. $sync->{ debug } and myprint( "eval \$string =~ $regexmess\n" ) ;
  9428. my $ret = eval "\$string =~ $regexmess ; 1" ;
  9429. #myprint( "eval [$ret]\n" ) ;
  9430. if ( ( not $ret ) or $EVAL_ERROR ) {
  9431. myprint( "Error: eval regexmess '$regexmess': $EVAL_ERROR" ) ;
  9432. return( undef ) ;
  9433. }
  9434. }
  9435. $sync->{ debug } and myprint( "$string\n" ) ;
  9436. return( $string ) ;
  9437. }
  9438. sub tests_skipmess
  9439. {
  9440. note( 'Entering tests_skipmess()' ) ;
  9441. ok( not( defined skipmess( 'blabla' ) ), 'skipmess, no skipmess, no skip' ) ;
  9442. @skipmess = ('[') ;
  9443. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex [' ) ;
  9444. @skipmess = ('lalala') ;
  9445. ok( not( defined skipmess( 'popopo' ) ), 'skipmess, bad regex lalala' ) ;
  9446. @skipmess = ('/popopo/') ;
  9447. ok( 1 == skipmess( 'popopo' ), 'skipmess, popopo match regex /popopo/' ) ;
  9448. @skipmess = ('/popopo/') ;
  9449. ok( 0 == skipmess( 'rrrrrr' ), 'skipmess, rrrrrr does not match regex /popopo/' ) ;
  9450. @skipmess = ('m{^$}') ;
  9451. ok( 1 == skipmess( q{} ), 'skipmess: empty string yes' ) ;
  9452. ok( 0 == skipmess( 'Hi!' ), 'skipmess: empty string no' ) ;
  9453. @skipmess = ('m{i}') ;
  9454. ok( 1 == skipmess( 'Hi!' ), 'skipmess: i string yes' ) ;
  9455. ok( 0 == skipmess( 'Bye!' ), 'skipmess: i string no' ) ;
  9456. @skipmess = ('m{[\x80-\xff]}') ;
  9457. ok( 0 == skipmess( 'Hi!' ), 'skipmess: i 8bit no' ) ;
  9458. ok( 1 == skipmess( "\xff" ), 'skipmess: \xff 8bit yes' ) ;
  9459. @skipmess = ('m{A}', 'm{B}') ;
  9460. ok( 0 == skipmess( 'Hi!' ), 'skipmess: A or B no' ) ;
  9461. ok( 0 == skipmess( 'lala' ), 'skipmess: A or B no' ) ;
  9462. ok( 0 == skipmess( "\xff" ), 'skipmess: A or B no' ) ;
  9463. ok( 1 == skipmess( 'AB' ), 'skipmess: A or B yes' ) ;
  9464. ok( 1 == skipmess( 'BA' ), 'skipmess: A or B yes' ) ;
  9465. ok( 1 == skipmess( 'AA' ), 'skipmess: A or B yes' ) ;
  9466. ok( 1 == skipmess( 'Ok Bye' ), 'skipmess: A or B yes' ) ;
  9467. @skipmess = ( 'm#\A((?:[^\n]+\n)+|)^Content-Type: Message/Partial;[^\n]*\n(?:\n|.*\n\n)#ism' ) ; # SUPER BEST!
  9468. ok( 1 == skipmess(
  9469. <<'EOM'
  9470. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9471. Content-Type: Message/Partial; blabla
  9472. From:<tartanpion@machin.truc>
  9473. Hello!
  9474. Bye.
  9475. EOM
  9476. ),
  9477. 'skipmess: 1 match Content-Type: Message/Partial' ) ;
  9478. ok( 0 == skipmess(
  9479. <<'EOM'
  9480. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9481. From:<tartanpion@machin.truc>
  9482. Hello!
  9483. Bye.
  9484. EOM
  9485. ),
  9486. 'skipmess: 2 not match Content-Type: Message/Partial' ) ;
  9487. ok( 1 == skipmess(
  9488. <<'EOM'
  9489. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9490. From:<tartanpion@machin.truc>
  9491. Content-Type: Message/Partial; blabla
  9492. Hello!
  9493. Bye.
  9494. EOM
  9495. ),
  9496. 'skipmess: 3 match Content-Type: Message/Partial' ) ;
  9497. ok( 0 == skipmess(
  9498. <<'EOM'
  9499. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9500. From:<tartanpion@machin.truc>
  9501. Hello!
  9502. Content-Type: Message/Partial; blabla
  9503. Bye.
  9504. EOM
  9505. ),
  9506. 'skipmess: 4 not match Content-Type: Message/Partial' ) ;
  9507. ok( 0 == skipmess(
  9508. <<'EOM'
  9509. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9510. From:<tartanpion@machin.truc>
  9511. Hello!
  9512. Content-Type: Message/Partial; blabla
  9513. Bye.
  9514. EOM
  9515. ),
  9516. 'skipmess: 5 not match Content-Type: Message/Partial' ) ;
  9517. ok( 1 == skipmess(
  9518. <<'EOM'
  9519. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9520. Content-Type: Message/Partial; blabla
  9521. From:<tartanpion@machin.truc>
  9522. Hello!
  9523. Content-Type: Message/Partial; blabla
  9524. Bye.
  9525. EOM
  9526. ),
  9527. 'skipmess: 6 match Content-Type: Message/Partial' ) ;
  9528. ok( 1 == skipmess(
  9529. <<'EOM'
  9530. Date: Sat, 10 Jul 2010 05:34:45 -0700
  9531. Content-Type: Message/Partial;
  9532. From:<tartanpion@machin.truc>
  9533. Hello!
  9534. Bye.
  9535. EOM
  9536. ),
  9537. 'skipmess: 7 match Content-Type: Message/Partial' ) ;
  9538. ok( 1 == skipmess(
  9539. <<'EOM'
  9540. Date: Wed, 2 Jul 2014 02:26:40 +0000
  9541. MIME-Version: 1.0
  9542. Content-Type: message/partial;
  9543. id="TAN_U_P<1404267997.00007489ed17>";
  9544. number=3;
  9545. total=3
  9546. 6HQ6Hh3CdXj77qEGixerQ6zHx0OnQ/Cf5On4W0Y6vtU2crABZQtD46Hx1EOh8dDz4+OnTr1G
  9547. Hello!
  9548. Bye.
  9549. EOM
  9550. ),
  9551. 'skipmess: 8 match Content-Type: Message/Partial' ) ;
  9552. ok( 1 == skipmess(
  9553. <<'EOM'
  9554. Return-Path: <gilles@lamiral.info>
  9555. Received: by lamiral.info (Postfix, from userid 1000)
  9556. id 21EB12443BF; Mon, 2 Mar 2015 15:38:35 +0100 (CET)
  9557. Subject: test: aethaecohngiexao
  9558. To: <tata@petite.lamiral.info>
  9559. X-Mailer: mail (GNU Mailutils 2.2)
  9560. Message-Id: <20150302143835.21EB12443BF@lamiral.info>
  9561. Content-Type: message/partial;
  9562. id="TAN_U_P<1404267997.00007489ed17>";
  9563. number=3;
  9564. total=3
  9565. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  9566. From: gilles@lamiral.info (Gilles LAMIRAL)
  9567. test: aethaecohngiexao
  9568. EOM
  9569. ),
  9570. 'skipmess: 9 match Content-Type: Message/Partial' ) ;
  9571. ok( 1 == skipmess(
  9572. <<'EOM'
  9573. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  9574. From: gilles@lamiral.info (Gilles LAMIRAL)
  9575. Content-Type: message/partial;
  9576. id="TAN_U_P<1404267997.00007489ed17>";
  9577. number=3;
  9578. total=3
  9579. test: aethaecohngiexao
  9580. EOM
  9581. . "lalala\n" x 3_000_000
  9582. ),
  9583. 'skipmess: 10 match Content-Type: Message/Partial' ) ;
  9584. ok( 0 == skipmess(
  9585. <<'EOM'
  9586. Date: Mon, 2 Mar 2015 15:38:34 +0100 (CET)
  9587. From: gilles@lamiral.info (Gilles LAMIRAL)
  9588. test: aethaecohngiexao
  9589. EOM
  9590. . "lalala\n" x 3_000_000
  9591. ),
  9592. 'skipmess: 11 match Content-Type: Message/Partial' ) ;
  9593. ok( 0 == skipmess(
  9594. <<"EOM"
  9595. From: fff\r
  9596. To: fff\r
  9597. Subject: Testing imapsync --skipmess\r
  9598. Date: Mon, 22 Aug 2011 08:40:20 +0800\r
  9599. Mime-Version: 1.0\r
  9600. Content-Type: text/plain; charset=iso-8859-1\r
  9601. Content-Transfer-Encoding: 7bit\r
  9602. \r
  9603. EOM
  9604. . qq{!#"d%&'()*+,-./0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg\r\n } x 32_730
  9605. ),
  9606. 'skipmess: 12 not match Content-Type: Message/Partial' ) ;
  9607. # Complex regular subexpression recursion limit (32766) exceeded with more lines
  9608. # exit;
  9609. note( 'Leaving tests_skipmess()' ) ;
  9610. return ;
  9611. }
  9612. sub skipmess
  9613. {
  9614. my ( $string ) = @_ ;
  9615. my $match ;
  9616. #myprint( "$string\n" ) ;
  9617. foreach my $skipmess ( @skipmess ) {
  9618. $sync->{ debug } and myprint( "eval \$match = \$string =~ $skipmess\n" ) ;
  9619. my $ret = eval "\$match = \$string =~ $skipmess ; 1" ;
  9620. #myprint( "eval [$ret]\n" ) ;
  9621. $sync->{ debug } and myprint( "match [$match]\n" ) ;
  9622. if ( ( not $ret ) or $EVAL_ERROR ) {
  9623. myprint( "Error: eval skipmess '$skipmess': $EVAL_ERROR" ) ;
  9624. return( undef ) ;
  9625. }
  9626. return( $match ) if ( $match ) ;
  9627. }
  9628. return( $match ) ;
  9629. }
  9630. sub tests_bytes_display_string
  9631. {
  9632. note( 'Entering tests_bytes_display_string()' ) ;
  9633. is( 'NA', bytes_display_string( ), 'bytes_display_string: no args => NA' ) ;
  9634. is( 'NA', bytes_display_string( undef ), 'bytes_display_string: undef => NA' ) ;
  9635. is( 'NA', bytes_display_string( 'blabla' ), 'bytes_display_string: blabla => NA' ) ;
  9636. ok( '0.000 KiB' eq bytes_display_string( 0 ), 'bytes_display_string: 0' ) ;
  9637. ok( '0.001 KiB' eq bytes_display_string( 1 ), 'bytes_display_string: 1' ) ;
  9638. ok( '0.010 KiB' eq bytes_display_string( 10 ), 'bytes_display_string: 10' ) ;
  9639. ok( '1.000 MiB' eq bytes_display_string( 1_048_575 ), 'bytes_display_string: 1_048_575' ) ;
  9640. ok( '1.000 MiB' eq bytes_display_string( 1_048_576 ), 'bytes_display_string: 1_048_576' ) ;
  9641. ok( '1.000 GiB' eq bytes_display_string( 1_073_741_823 ), 'bytes_display_string: 1_073_741_823 ' ) ;
  9642. ok( '1.000 GiB' eq bytes_display_string( 1_073_741_824 ), 'bytes_display_string: 1_073_741_824 ' ) ;
  9643. ok( '1.000 TiB' eq bytes_display_string( 1_099_511_627_775 ), 'bytes_display_string: 1_099_511_627_775' ) ;
  9644. ok( '1.000 TiB' eq bytes_display_string( 1_099_511_627_776 ), 'bytes_display_string: 1_099_511_627_776' ) ;
  9645. ok( '1.000 PiB' eq bytes_display_string( 1_125_899_906_842_623 ), 'bytes_display_string: 1_125_899_906_842_623' ) ;
  9646. ok( '1.000 PiB' eq bytes_display_string( 1_125_899_906_842_624 ), 'bytes_display_string: 1_125_899_906_842_624' ) ;
  9647. ok( '1024.000 PiB' eq bytes_display_string( 1_152_921_504_606_846_975 ), 'bytes_display_string: 1_152_921_504_606_846_975' ) ;
  9648. ok( '1024.000 PiB' eq bytes_display_string( 1_152_921_504_606_846_976 ), 'bytes_display_string: 1_152_921_504_606_846_976' ) ;
  9649. ok( '1048576.000 PiB' eq bytes_display_string( 1_180_591_620_717_411_303_424 ), 'bytes_display_string: 1_180_591_620_717_411_303_424' ) ;
  9650. #myprint( bytes_display_string( 1_180_591_620_717_411_303_424 ), "\n" ) ;
  9651. note( 'Leaving tests_bytes_display_string()' ) ;
  9652. return ;
  9653. }
  9654. sub bytes_display_string
  9655. {
  9656. my ( $bytes ) = @_ ;
  9657. my $readable_value = q{} ;
  9658. if ( ! defined( $bytes ) ) {
  9659. return( 'NA' ) ;
  9660. }
  9661. if ( not match_number( $bytes ) ) {
  9662. return( 'NA' ) ;
  9663. }
  9664. SWITCH: {
  9665. if ( abs( $bytes ) < ( 1000 * $KIBI ) ) {
  9666. $readable_value = mysprintf( '%.3f KiB', $bytes / $KIBI) ;
  9667. last SWITCH ;
  9668. }
  9669. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI ) ) {
  9670. $readable_value = mysprintf( '%.3f MiB', $bytes / ($KIBI * $KIBI) ) ;
  9671. last SWITCH ;
  9672. }
  9673. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI) ) {
  9674. $readable_value = mysprintf( '%.3f GiB', $bytes / ($KIBI * $KIBI * $KIBI) ) ;
  9675. last SWITCH ;
  9676. }
  9677. if ( abs( $bytes ) < ( 1000 * $KIBI * $KIBI * $KIBI * $KIBI) ) {
  9678. $readable_value = mysprintf( '%.3f TiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI) ) ;
  9679. last SWITCH ;
  9680. } else {
  9681. $readable_value = mysprintf( '%.3f PiB', $bytes / ($KIBI * $KIBI * $KIBI * $KIBI * $KIBI) ) ;
  9682. }
  9683. # if you have exabytes (EiB) of email to transfer, you have too much email!
  9684. }
  9685. #myprint( "$bytes = $readable_value\n" ) ;
  9686. return( $readable_value ) ;
  9687. }
  9688. sub tests_useheader_suggestion
  9689. {
  9690. note( 'Entering tests_useheader_suggestion()' ) ;
  9691. is( undef, useheader_suggestion( ), 'useheader_suggestion: no args => undef' ) ;
  9692. my $mysync = {} ;
  9693. $mysync->{ h1_nb_msg_noheader } = 0 ;
  9694. is( q{}, useheader_suggestion( $mysync ), 'useheader_suggestion: h1_nb_msg_noheader count null => no suggestion' ) ;
  9695. $mysync->{ h1_nb_msg_noheader } = 2 ;
  9696. is( q{in order to sync those 2 unidentified messages, add option --addheader}, useheader_suggestion( $mysync ),
  9697. 'useheader_suggestion: h1_nb_msg_noheader count 2 => suggestion of --addheader' ) ;
  9698. note( 'Leaving tests_useheader_suggestion()' ) ;
  9699. return ;
  9700. }
  9701. sub useheader_suggestion
  9702. {
  9703. my $mysync = shift ;
  9704. if ( ! defined $mysync->{ h1_nb_msg_noheader } )
  9705. {
  9706. return ;
  9707. }
  9708. elsif ( 1 <= $mysync->{ h1_nb_msg_noheader } )
  9709. {
  9710. return qq{in order to sync those $mysync->{ h1_nb_msg_noheader } unidentified messages, add option --addheader} ;
  9711. }
  9712. else
  9713. {
  9714. return q{} ;
  9715. }
  9716. return ;
  9717. }
  9718. sub stats
  9719. {
  9720. my $mysync = shift ;
  9721. if ( ! $mysync->{stats} ) {
  9722. return ;
  9723. }
  9724. my $timeend = time ;
  9725. my $timediff = $timeend - $mysync->{timestart} ;
  9726. my $timeend_str = localtime $timeend ;
  9727. my $memory_consumption_at_end = memory_consumption( ) || 0 ;
  9728. my $memory_consumption_at_start = $mysync->{ memory_consumption_at_start } || 0 ;
  9729. my $memory_ratio = ($max_msg_size_in_bytes) ?
  9730. mysprintf('%.1f', $memory_consumption_at_end / $max_msg_size_in_bytes) : 'NA' ;
  9731. # my $useheader_suggestion = useheader_suggestion( $mysync ) ;
  9732. myprint( "++++ Statistics\n" ) ;
  9733. myprint( "Transfer started on : $timestart_str\n" ) ;
  9734. myprint( "Transfer ended on : $timeend_str\n" ) ;
  9735. myprintf( "Transfer time : %.1f sec\n", $timediff ) ;
  9736. myprint( "Folders synced : $h1_folders_wanted_ct/$h1_folders_wanted_nb synced\n" ) ;
  9737. myprint( "Messages transferred : $mysync->{ nb_msg_transferred } " ) ;
  9738. myprint( "(could be $nb_msg_skipped_dry_mode without dry mode)" ) if ( $mysync->{dry} ) ;
  9739. myprint( "\n" ) ;
  9740. myprint( "Messages skipped : $mysync->{ nb_msg_skipped }\n" ) ;
  9741. myprint( "Messages found duplicate on host1 : $h1_nb_msg_duplicate\n" ) ;
  9742. myprint( "Messages found duplicate on host2 : $h2_nb_msg_duplicate\n" ) ;
  9743. myprint( "Messages found crossduplicate on host2 : $mysync->{ h2_nb_msg_crossdup }\n" ) ;
  9744. myprint( "Messages void (noheader) on host1 : $mysync->{ h1_nb_msg_noheader } ", useheader_suggestion( $mysync ), "\n" ) ;
  9745. myprint( "Messages void (noheader) on host2 : $h2_nb_msg_noheader\n" ) ;
  9746. nb_messages_in_1_not_in_2( $mysync ) ;
  9747. nb_messages_in_2_not_in_1( $mysync ) ;
  9748. myprintf( "Messages found in host1 not in host2 : %s messages\n", $mysync->{ nb_messages_in_1_not_in_2 } ) ;
  9749. myprintf( "Messages found in host2 not in host1 : %s messages\n", $mysync->{ nb_messages_in_2_not_in_1 } ) ;
  9750. myprint( "Messages deleted on host1 : $mysync->{ h1_nb_msg_deleted }\n" ) ;
  9751. myprint( "Messages deleted on host2 : $h2_nb_msg_deleted\n" ) ;
  9752. myprintf( "Total bytes transferred : %s (%s)\n",
  9753. $mysync->{total_bytes_transferred},
  9754. bytes_display_string( $mysync->{total_bytes_transferred} ) ) ;
  9755. myprintf( "Total bytes skipped : %s (%s)\n",
  9756. $mysync->{ total_bytes_skipped },
  9757. bytes_display_string( $mysync->{ total_bytes_skipped } ) ) ;
  9758. $timediff ||= 1 ; # No division per 0
  9759. myprintf("Message rate : %.1f messages/s\n", $mysync->{nb_msg_transferred} / $timediff ) ;
  9760. myprintf("Average bandwidth rate : %.1f KiB/s\n", $mysync->{total_bytes_transferred} / $KIBI / $timediff ) ;
  9761. myprint( "Reconnections to host1 : $mysync->{imap1}->{IMAPSYNC_RECONNECT_COUNT}\n" ) ;
  9762. myprint( "Reconnections to host2 : $mysync->{imap2}->{IMAPSYNC_RECONNECT_COUNT}\n" ) ;
  9763. myprintf("Memory consumption at the end : %.1f MiB (started with %.1f MiB)\n",
  9764. $memory_consumption_at_end / $KIBI / $KIBI,
  9765. $memory_consumption_at_start / $KIBI / $KIBI ) ;
  9766. myprint( "Load end is : " . ( join( q{ }, loadavg( ) ) || 'unknown' ), " on $mysync->{cpu_number} cores\n" ) ;
  9767. myprintf("Biggest message : %s bytes (%s)\n",
  9768. $max_msg_size_in_bytes,
  9769. bytes_display_string( $max_msg_size_in_bytes) ) ;
  9770. myprint( "Memory/biggest message ratio : $memory_ratio\n" ) ;
  9771. if ( $mysync->{ foldersizesatend } and $mysync->{ foldersizes } ) {
  9772. my $nb_msg_start_diff = diff_or_NA( $mysync->{ h2_nb_msg_start }, $mysync->{ h1_nb_msg_start } ) ;
  9773. my $bytes_start_diff = diff_or_NA( $mysync->{ h2_bytes_start }, $mysync->{ h1_bytes_start } ) ;
  9774. myprintf("Start difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_start_diff,
  9775. $bytes_start_diff,
  9776. bytes_display_string( $bytes_start_diff ) ) ;
  9777. my $nb_msg_end_diff = diff_or_NA( $h2_nb_msg_end, $h1_nb_msg_end ) ;
  9778. my $bytes_end_diff = diff_or_NA( $h2_bytes_end, $h1_bytes_end ) ;
  9779. myprintf("Final difference host2 - host1 : %s messages, %s bytes (%s)\n", $nb_msg_end_diff,
  9780. $bytes_end_diff,
  9781. bytes_display_string( $bytes_end_diff ) ) ;
  9782. }
  9783. comment_on_final_diff_in_1_not_in_2( $mysync ) ;
  9784. comment_on_final_diff_in_2_not_in_1( $mysync ) ;
  9785. myprint( "Detected $mysync->{nb_errors} errors\n\n" ) ;
  9786. myprint( $warn_release, "\n" ) ;
  9787. myprint( homepage( ), "\n" ) ;
  9788. return ;
  9789. }
  9790. sub diff_or_NA
  9791. {
  9792. my( $n1, $n2 ) = @ARG ;
  9793. if ( not defined $n1 or not defined $n2 ) {
  9794. return 'NA' ;
  9795. }
  9796. if ( not match_number( $n1 )
  9797. or not match_number( $n2 ) ) {
  9798. return 'NA' ;
  9799. }
  9800. return( $n1 - $n2 ) ;
  9801. }
  9802. sub match_number
  9803. {
  9804. my $n = shift @ARG ;
  9805. if ( not defined $n ) {
  9806. return 0 ;
  9807. }
  9808. if ( $n =~ /[0-9]+\.?[0-9]?/x ) {
  9809. return 1 ;
  9810. }
  9811. else {
  9812. return 0 ;
  9813. }
  9814. }
  9815. sub tests_match_number
  9816. {
  9817. note( 'Entering tests_match_number()' ) ;
  9818. is( 0, match_number( ), 'match_number: no parameters => 0' ) ;
  9819. is( 0, match_number( undef ), 'match_number: undef => 0' ) ;
  9820. is( 0, match_number( 'blabla' ), 'match_number: blabla => 0' ) ;
  9821. is( 1, match_number( 0 ), 'match_number: 0 => 1' ) ;
  9822. is( 1, match_number( 1 ), 'match_number: 1 => 1' ) ;
  9823. is( 1, match_number( 1.0 ), 'match_number: 1.0 => 1' ) ;
  9824. is( 1, match_number( 0.0 ), 'match_number: 0.0 => 1' ) ;
  9825. note( 'Leaving tests_match_number()' ) ;
  9826. return ;
  9827. }
  9828. sub tests_diff_or_NA
  9829. {
  9830. note( 'Entering tests_diff_or_NA()' ) ;
  9831. is( 'NA', diff_or_NA( ), 'diff_or_NA: no parameters => NA' ) ;
  9832. is( 'NA', diff_or_NA( undef ), 'diff_or_NA: undef => NA' ) ;
  9833. is( 'NA', diff_or_NA( undef, undef ), 'diff_or_NA: undef undef => NA' ) ;
  9834. is( 'NA', diff_or_NA( undef, 1 ), 'diff_or_NA: undef 1 => NA' ) ;
  9835. is( 'NA', diff_or_NA( 1, undef ), 'diff_or_NA: 1 undef => NA' ) ;
  9836. is( 'NA', diff_or_NA( 'blabla', 1 ), 'diff_or_NA: blabla 1 => NA' ) ;
  9837. is( 'NA', diff_or_NA( 1, 'blabla' ), 'diff_or_NA: 1 blabla => NA' ) ;
  9838. is( 0, diff_or_NA( 1, 1 ), 'diff_or_NA: 1 1 => 0' ) ;
  9839. is( 1, diff_or_NA( 1, 0 ), 'diff_or_NA: 1 0 => 1' ) ;
  9840. is( -1, diff_or_NA( 0, 1 ), 'diff_or_NA: 0 1 => -1' ) ;
  9841. is( 0, diff_or_NA( 1.0, 1 ), 'diff_or_NA: 1.0 1 => 0' ) ;
  9842. is( 1, diff_or_NA( 1.0, 0 ), 'diff_or_NA: 1.0 0 => 1' ) ;
  9843. is( -1, diff_or_NA( 0, 1.0 ), 'diff_or_NA: 0 1.0 => -1' ) ;
  9844. note( 'Leaving tests_diff_or_NA()' ) ;
  9845. return ;
  9846. }
  9847. sub homepage
  9848. {
  9849. return( 'Homepage: https://imapsync.lamiral.info/' ) ;
  9850. }
  9851. sub load_modules
  9852. {
  9853. if ( $sync->{ssl1}
  9854. or $sync->{ssl2}
  9855. or $sync->{tls1}
  9856. or $sync->{tls2}) {
  9857. if ( $sync->{inet4} ) {
  9858. IO::Socket::SSL->import( 'inet4' ) ;
  9859. }
  9860. if ( $sync->{inet6} ) {
  9861. IO::Socket::SSL->import( 'inet6' ) ;
  9862. }
  9863. }
  9864. return ;
  9865. }
  9866. sub parse_header_msg
  9867. {
  9868. my ( $mysync, $imap, $m_uid, $s_heads, $s_fir, $side, $s_hash ) = @_ ;
  9869. my $head = $s_heads->{$m_uid} ;
  9870. my $headnum = scalar keys %{ $head } ;
  9871. $mysync->{ debug } and myprint( "$side: uid $m_uid number of headers, pass one: ", $headnum, "\n" ) ;
  9872. if ( ( ! $headnum ) and ( $wholeheaderifneeded ) ){
  9873. $mysync->{ debug } and myprint( "$side: uid $m_uid no header by parse_headers so taking whole header with BODY.PEEK[HEADER]\n" ) ;
  9874. $imap->fetch($m_uid, 'BODY.PEEK[HEADER]' ) ;
  9875. my $whole_header = $imap->_transaction_literals ;
  9876. #myprint( $whole_header ) ;
  9877. $head = decompose_header( $whole_header ) ;
  9878. $headnum = scalar keys %{ $head } ;
  9879. $mysync->{ debug } and myprint( "$side: uid $m_uid number of headers, pass two: ", $headnum, "\n" ) ;
  9880. }
  9881. #myprint( Data::Dumper->Dump( [ $head, \%useheader ] ) ) ;
  9882. my $headstr ;
  9883. $headstr = header_construct( $head, $side, $m_uid ) ;
  9884. if ( ( ! $headstr ) and ( $mysync->{addheader} ) and ( $side eq 'Host1' ) ) {
  9885. my $header = add_header( $m_uid ) ;
  9886. $mysync->{ debug } and myprint( "$side: uid $m_uid no header found so adding our own [$header]\n" ) ;
  9887. $headstr .= uc $header ;
  9888. $s_fir->{$m_uid}->{NO_HEADER} = 1;
  9889. }
  9890. return if ( ! $headstr ) ;
  9891. my $size = $s_fir->{$m_uid}->{'RFC822.SIZE'} ;
  9892. my $flags = $s_fir->{$m_uid}->{'FLAGS'} ;
  9893. my $idate = $s_fir->{$m_uid}->{'INTERNALDATE'} ;
  9894. $size = length $headstr unless ( $size ) ;
  9895. my $m_md5 = md5_base64( $headstr ) ;
  9896. $mysync->{ debug } and myprint( "$side: uid $m_uid sig $m_md5 size $size idate $idate\n" ) ;
  9897. my $key ;
  9898. if ($skipsize) {
  9899. $key = "$m_md5";
  9900. }
  9901. else {
  9902. $key = "$m_md5:$size";
  9903. }
  9904. # 0 return code is used to identify duplicate message hash
  9905. return 0 if exists $s_hash->{"$key"};
  9906. $s_hash->{"$key"}{'5'} = $m_md5;
  9907. $s_hash->{"$key"}{'s'} = $size;
  9908. $s_hash->{"$key"}{'D'} = $idate;
  9909. $s_hash->{"$key"}{'F'} = $flags;
  9910. $s_hash->{"$key"}{'m'} = $m_uid;
  9911. return( 1 ) ;
  9912. }
  9913. sub header_construct
  9914. {
  9915. my( $head, $side, $m_uid ) = @_ ;
  9916. my $headstr ;
  9917. foreach my $h ( sort keys %{ $head } ) {
  9918. next if ( not ( exists $useheader{ uc $h } )
  9919. and ( not exists $useheader{ 'ALL' } )
  9920. ) ;
  9921. foreach my $val ( sort @{$head->{$h}} ) {
  9922. my $H = header_line_normalize( $h, $val ) ;
  9923. # show stuff in debug mode
  9924. $sync->{ debug } and myprint( "$side uid $m_uid header [$H]", "\n" ) ;
  9925. if ($skipheader and $H =~ m/$skipheader/xi) {
  9926. $sync->{ debug } and myprint( "$side uid $m_uid skipping header [$H]\n" ) ;
  9927. next ;
  9928. }
  9929. $headstr .= "$H" ;
  9930. }
  9931. }
  9932. return( $headstr ) ;
  9933. }
  9934. sub header_line_normalize
  9935. {
  9936. my( $header_key, $header_val ) = @_ ;
  9937. # no 8-bit data in headers !
  9938. $header_val =~ s/[\x80-\xff]/X/xog;
  9939. # change tabulations to space (Gmail bug on with "Received:" on multilines)
  9940. $header_val =~ s/\t/\ /xgo ;
  9941. # remove the first blanks ( dbmail bug? )
  9942. $header_val =~ s/^\s*//xo;
  9943. # remove the last blanks ( Gmail bug )
  9944. $header_val =~ s/\s*$//xo;
  9945. # remove successive blanks ( Mailenable does it )
  9946. $header_val =~ s/\s+/ /xgo;
  9947. # remove Message-Id value domain part ( Mailenable changes it )
  9948. if ( ( $messageidnodomain ) and ( 'MESSAGE-ID' eq uc $header_key ) ) { $header_val =~ s/^([^@]+).*$/$1/xo ; }
  9949. # and uppercase header line
  9950. # (dbmail and dovecot)
  9951. my $header_line = uc "$header_key: $header_val" ;
  9952. return( $header_line ) ;
  9953. }
  9954. sub tests_header_line_normalize
  9955. {
  9956. note( 'Entering tests_header_line_normalize()' ) ;
  9957. ok( ': ' eq header_line_normalize( q{}, q{} ), 'header_line_normalize: empty args' ) ;
  9958. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', 'vvv' ), 'header_line_normalize: hhh vvv ' ) ;
  9959. ok( 'HHH: VVV' eq header_line_normalize( 'hhh', ' vvv' ), 'header_line_normalize: remove first blancs' ) ;
  9960. ok( 'HHH: AA BB CCC D' eq header_line_normalize( 'hhh', 'aa bb ccc d' ), 'header_line_normalize: remove succesive blanks' ) ;
  9961. ok( 'HHH: AA BB CCC' eq header_line_normalize( 'hhh', 'aa bb ccc ' ), 'header_line_normalize: remove last blanks' ) ;
  9962. ok( 'HHH: VVV XX YY' eq header_line_normalize( 'hhh', "vvv\t\txx\tyy" ), 'header_line_normalize: tabs' ) ;
  9963. ok( 'HHH: XABX' eq header_line_normalize( 'hhh', "\x80AB\xff" ), 'header_line_normalize: 8bit' ) ;
  9964. note( 'Leaving tests_header_line_normalize()' ) ;
  9965. return ;
  9966. }
  9967. sub tests_firstline
  9968. {
  9969. note( 'Entering tests_firstline()' ) ;
  9970. is( q{}, firstline( 'W/tmp/tests/noexist.txt' ), 'firstline: getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  9971. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'firstline: mkpath W/tmp/tests/' ) ;
  9972. is( "blabla\n" , string_to_file( "blabla\n", 'W/tmp/tests/firstline.txt' ), 'firstline: put blabla in W/tmp/tests/firstline.txt' ) ;
  9973. is( 'blabla' , firstline( 'W/tmp/tests/firstline.txt' ), 'firstline: get blabla from W/tmp/tests/firstline.txt' ) ;
  9974. is( q{} , string_to_file( q{}, 'W/tmp/tests/firstline2.txt' ), 'firstline: put empty string in W/tmp/tests/firstline2.txt' ) ;
  9975. is( q{} , firstline( 'W/tmp/tests/firstline2.txt' ), 'firstline: get empty string from W/tmp/tests/firstline2.txt' ) ;
  9976. is( "\n" , string_to_file( "\n", 'W/tmp/tests/firstline3.txt' ), 'firstline: put CR in W/tmp/tests/firstline3.txt' ) ;
  9977. is( q{} , firstline( 'W/tmp/tests/firstline3.txt' ), 'firstline: get empty string from W/tmp/tests/firstline3.txt' ) ;
  9978. 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' ) ;
  9979. is( 'blabla' , firstline( 'W/tmp/tests/firstline4.txt' ), 'firstline: get blabla from W/tmp/tests/firstline4.txt' ) ;
  9980. note( 'Leaving tests_firstline()' ) ;
  9981. return ;
  9982. }
  9983. sub firstline
  9984. {
  9985. # extract the first line of a file (without \n)
  9986. # return empty string if error or empty string
  9987. my $file = shift ;
  9988. my $line ;
  9989. $line = nthline( $file, 1 ) ;
  9990. return $line ;
  9991. }
  9992. sub tests_secondline
  9993. {
  9994. note( 'Entering tests_secondline()' ) ;
  9995. is( q{}, secondline( 'W/tmp/tests/noexist.txt' ), 'secondline: getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  9996. is( q{}, secondline( 'W/tmp/tests/noexist.txt', 2 ), 'secondline: 2nd getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  9997. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'secondline: mkpath W/tmp/tests/' ) ;
  9998. 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' ) ;
  9999. is( 'L2' , secondline( 'W/tmp/tests/secondline.txt' ), 'secondline: get L2 from W/tmp/tests/secondline.txt' ) ;
  10000. note( 'Leaving tests_secondline()' ) ;
  10001. return ;
  10002. }
  10003. sub secondline
  10004. {
  10005. # extract the second line of a file (without \n)
  10006. # return empty string if error or empty string
  10007. my $file = shift ;
  10008. my $line ;
  10009. $line = nthline( $file, 2 ) ;
  10010. return $line ;
  10011. }
  10012. sub tests_nthline
  10013. {
  10014. note( 'Entering tests_nthline()' ) ;
  10015. is( q{}, nthline( 'W/tmp/tests/noexist.txt' ), 'nthline: getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  10016. is( q{}, nthline( 'W/tmp/tests/noexist.txt', 2 ), 'nthline: 2nd getting empty string from inexisting W/tmp/tests/noexist.txt' ) ;
  10017. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'nthline: mkpath W/tmp/tests/' ) ;
  10018. 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' ) ;
  10019. is( 'L3' , nthline( 'W/tmp/tests/nthline.txt', 3 ), 'nthline: get L3 from W/tmp/tests/nthline.txt' ) ;
  10020. note( 'Leaving tests_nthline()' ) ;
  10021. return ;
  10022. }
  10023. sub nthline
  10024. {
  10025. # extract the nth line of a file (without \n)
  10026. # return empty string if error or empty string
  10027. my $file = shift ;
  10028. my $num = shift ;
  10029. if ( ! all_defined( $file, $num ) ) { return q{} ; }
  10030. my $line ;
  10031. $line = ( file_to_array( $file ) )[$num - 1] ;
  10032. if ( ! defined $line )
  10033. {
  10034. return q{} ;
  10035. }
  10036. else
  10037. {
  10038. chomp $line ;
  10039. return $line ;
  10040. }
  10041. }
  10042. # Should be unit tested and then be used by file_to_string, refactoring file_to_string
  10043. sub file_to_array
  10044. {
  10045. my( $file ) = shift ;
  10046. my @string ;
  10047. open my $FILE, '<', $file or do {
  10048. myprint( "Error reading file $file : $OS_ERROR\n" ) ;
  10049. return ;
  10050. } ;
  10051. @string = <$FILE> ;
  10052. close $FILE ;
  10053. return( @string ) ;
  10054. }
  10055. sub tests_file_to_string
  10056. {
  10057. note( 'Entering tests_file_to_string()' ) ;
  10058. is( undef, file_to_string( ), 'file_to_string: no args => undef' ) ;
  10059. is( undef, file_to_string( '/noexist' ), 'file_to_string: /noexist => undef' ) ;
  10060. is( undef, file_to_string( '/' ), 'file_to_string: reading a directory => undef' ) ;
  10061. ok( file_to_string( $PROGRAM_NAME ), 'file_to_string: reading myself' ) ;
  10062. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'file_to_string: mkpath W/tmp/tests/' ) ;
  10063. is( 'lilili', string_to_file( 'lilili', 'W/tmp/tests/canbewritten' ), 'file_to_string: string_to_file filling W/tmp/tests/canbewritten with lilili' ) ;
  10064. is( 'lilili', file_to_string( 'W/tmp/tests/canbewritten' ), 'file_to_string: reading W/tmp/tests/canbewritten is lilili' ) ;
  10065. is( q{}, string_to_file( q{}, 'W/tmp/tests/empty' ), 'file_to_string: string_to_file filling W/tmp/tests/empty with empty string' ) ;
  10066. is( q{}, file_to_string( 'W/tmp/tests/empty' ), 'file_to_string: reading W/tmp/tests/empty is empty' ) ;
  10067. note( 'Leaving tests_file_to_string()' ) ;
  10068. return ;
  10069. }
  10070. sub file_to_string
  10071. {
  10072. my $file = shift ;
  10073. if ( ! $file ) { return ; }
  10074. if ( ! -e $file ) { return ; }
  10075. if ( ! -f $file ) { return ; }
  10076. if ( ! -r $file ) { return ; }
  10077. my @string ;
  10078. if ( open my $FILE, '<', $file ) {
  10079. @string = <$FILE> ;
  10080. close $FILE ;
  10081. return( join q{}, @string ) ;
  10082. }else{
  10083. myprint( "Error reading file $file : $OS_ERROR\n" ) ;
  10084. return ;
  10085. }
  10086. }
  10087. sub tests_string_to_file
  10088. {
  10089. note( 'Entering tests_string_to_file()' ) ;
  10090. is( undef, string_to_file( ), 'string_to_file: no args => undef' ) ;
  10091. is( undef, string_to_file( 'lalala' ), 'string_to_file: one arg => undef' ) ;
  10092. is( undef, string_to_file( 'lalala', '.' ), 'string_to_file: writing a directory => undef' ) ;
  10093. ok( (-d 'W/tmp/tests/' or mkpath( 'W/tmp/tests/' ) ), 'string_to_file: mkpath W/tmp/tests/' ) ;
  10094. is( 'lalala', string_to_file( 'lalala', 'W/tmp/tests/canbewritten' ), 'string_to_file: W/tmp/tests/canbewritten with lalala' ) ;
  10095. is( q{}, string_to_file( q{}, 'W/tmp/tests/empty' ), 'string_to_file: W/tmp/tests/empty with empty string' ) ;
  10096. SKIP: {
  10097. Readonly my $NB_UNX_tests_string_to_file => 1 ;
  10098. skip( 'Not on Unix non-root', $NB_UNX_tests_string_to_file ) if ('MSWin32' eq $OSNAME or '0' eq $EFFECTIVE_USER_ID ) ;
  10099. is( undef, string_to_file( 'lalala', '/cantouch' ), 'string_to_file: /cantouch denied => undef' ) ;
  10100. }
  10101. note( 'Leaving tests_string_to_file()' ) ;
  10102. return ;
  10103. }
  10104. sub string_to_file
  10105. {
  10106. my( $string, $file ) = @_ ;
  10107. if( ! defined $string ) { return ; }
  10108. if( ! defined $file ) { return ; }
  10109. if ( ! -e $file && ! -w dirname( $file ) ) {
  10110. myprint( "string_to_file: directory of $file is not writable\n" ) ;
  10111. return ;
  10112. }
  10113. if ( ! sysopen( FILE, $file, O_WRONLY|O_TRUNC|O_CREAT, 0600) ) {
  10114. myprint( "string_to_file: failure writing to $file with error: $OS_ERROR\n" ) ;
  10115. return ;
  10116. }
  10117. print FILE $string ;
  10118. close FILE ;
  10119. return $string ;
  10120. }
  10121. 0 and <<'MULTILINE_COMMENT' ;
  10122. This is a multiline comment.
  10123. Based on David Carter discussion, to do:
  10124. * Call parameters stay the same.
  10125. * Now always "return( $string, $error )". Descriptions below.
  10126. OK * Still capture STDOUT via "1> $output_tmpfile" to finish in $string and "return( $string, $error )"
  10127. OK * Now also capture STDERR via "2> $error_tmpfile" to finish in $error and "return( $string, $error )"
  10128. OK * in case of CHILD_ERROR, return( undef, $error )
  10129. and print $error, with folder/UID/maybeSubject context,
  10130. on console and at the end with the final error listing. Count this as a sync error.
  10131. * in case of good command, take final $string as is, unless void. In case $error with value then print it.
  10132. * in case of good command and final $string empty, consider it like CHILD_ERROR =>
  10133. return( undef, $error ) and print $error, with folder/UID/maybeSubject context,
  10134. on console and at the end with the final error listing. Count this as a sync error.
  10135. MULTILINE_COMMENT
  10136. # End of multiline comment.
  10137. sub pipemess
  10138. {
  10139. my ( $string, @commands ) = @_ ;
  10140. my $error = q{} ;
  10141. foreach my $command ( @commands ) {
  10142. my $input_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.inp.txt" ;
  10143. my $output_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.out.txt" ;
  10144. my $error_tmpfile = "$sync->{ tmpdir }/imapsync_tmp_file.$PROCESS_ID.err.txt" ;
  10145. string_to_file( $string, $input_tmpfile ) ;
  10146. ` $command < $input_tmpfile 1> $output_tmpfile 2> $error_tmpfile ` ;
  10147. my $is_command_ko = $CHILD_ERROR ;
  10148. my $error_cmd = file_to_string( $error_tmpfile ) ;
  10149. chomp( $error_cmd ) ;
  10150. $string = file_to_string( $output_tmpfile ) ;
  10151. my $string_len = length( $string ) ;
  10152. unlink $input_tmpfile, $output_tmpfile, $error_tmpfile ;
  10153. if ( $is_command_ko or ( ! $string_len ) ) {
  10154. my $cmd_exit_value = $CHILD_ERROR >> 8 ;
  10155. my $cmd_end_signal = $CHILD_ERROR & 127 ;
  10156. my $signal_log = ( $cmd_end_signal ) ? " signal $cmd_end_signal and" : q{} ;
  10157. 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} ;
  10158. myprint( $error_log ) ;
  10159. if ( wantarray ) {
  10160. return @{ [ undef, $error_log ] }
  10161. }else{
  10162. return ;
  10163. }
  10164. }
  10165. if ( $error_cmd ) {
  10166. $error .= qq{STDERR of --pipemess "$command": $error_cmd\n} ;
  10167. myprint( qq{STDERR of --pipemess "$command": $error_cmd\n} ) ;
  10168. }
  10169. }
  10170. #myprint( "[$string]\n" ) ;
  10171. if ( wantarray ) {
  10172. return ( $string, $error ) ;
  10173. }else{
  10174. return $string ;
  10175. }
  10176. }
  10177. sub tests_pipemess
  10178. {
  10179. note( 'Entering tests_pipemess()' ) ;
  10180. SKIP: {
  10181. Readonly my $NB_WIN_tests_pipemess => 3 ;
  10182. skip( 'Not on MSWin32', $NB_WIN_tests_pipemess ) if ('MSWin32' ne $OSNAME) ;
  10183. # Windows
  10184. # "type" command does not accept redirection of STDIN with <
  10185. # "sort" does
  10186. ok( "nochange\n" eq pipemess( 'nochange', 'sort' ), 'pipemess: nearly no change by sort' ) ;
  10187. ok( "nochange2\n" eq pipemess( 'nochange2', qw( sort sort ) ), 'pipemess: nearly no change by sort,sort' ) ;
  10188. # command not found
  10189. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  10190. ok( ! defined( pipemess( q{}, 'cacaprout' ) ), 'pipemess: command not found' ) ;
  10191. } ;
  10192. my ( $stringT, $errorT ) ;
  10193. SKIP: {
  10194. Readonly my $NB_UNX_tests_pipemess => 25 ;
  10195. skip( 'Not on Unix', $NB_UNX_tests_pipemess ) if ('MSWin32' eq $OSNAME) ;
  10196. # Unix
  10197. ok( 'nochange' eq pipemess( 'nochange', 'cat' ), 'pipemess: no change by cat' ) ;
  10198. ok( 'nochange2' eq pipemess( 'nochange2', 'cat', 'cat' ), 'pipemess: no change by cat,cat' ) ;
  10199. ok( " 1\tnumberize\n" eq pipemess( "numberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  10200. ok( " 1\tnumberize\n 2\tnumberize\n" eq pipemess( "numberize\nnumberize\n", 'cat -n' ), 'pipemess: numberize by cat -n' ) ;
  10201. ok( "A\nB\nC\n" eq pipemess( "A\nC\nB\n", 'sort' ), 'pipemess: sort' ) ;
  10202. # command not found
  10203. #diag( 'Warning and failure about cacaprout are on purpose' ) ;
  10204. is( undef, pipemess( q{}, 'cacaprout' ), 'pipemess: command not found' ) ;
  10205. # success with true but no output at all
  10206. is( undef, pipemess( q{blabla}, 'true' ), 'pipemess: true but no output' ) ;
  10207. # failure with false and no output at all
  10208. is( undef, pipemess( q{blabla}, 'false' ), 'pipemess: false and no output' ) ;
  10209. # Failure since pipemess is not a real pipe, so first cat wait for standard input
  10210. is( q{blabla}, pipemess( q{blabla}, '( cat|cat ) ' ), 'pipemess: ok by ( cat|cat )' ) ;
  10211. ( $stringT, $errorT ) = pipemess( 'nochange', 'cat' ) ;
  10212. is( $stringT, 'nochange', 'pipemess: list context, no change by cat, string' ) ;
  10213. is( $errorT, q{}, 'pipemess: list context, no change by cat, no error' ) ;
  10214. ( $stringT, $errorT ) = pipemess( 'dontcare', 'true' ) ;
  10215. is( $stringT, undef, 'pipemess: list context, true but no output, string' ) ;
  10216. 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' ) ;
  10217. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false' ) ;
  10218. is( $stringT, undef, 'pipemess: list context, false and no output, string' ) ;
  10219. like( $errorT, qr{\QFailure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""\E}xm,
  10220. 'pipemess: list context, false and no output, error' ) ;
  10221. ( $stringT, $errorT ) = pipemess( 'dontcare', '/bin/echo -n blablabla' ) ;
  10222. is( $stringT, q{blablabla}, 'pipemess: list context, "echo -n blablabla", string' ) ;
  10223. is( $errorT, q{}, 'pipemess: list context, "echo blablabla", error' ) ;
  10224. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  10225. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla", string' ) ;
  10226. like( $errorT, qr{blablabla"}xm, 'pipemess: list context, "no output STDERR blablabla", error' ) ;
  10227. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo -n blablabla 3>&1 1>&2 2>&3 )', 'false' ) ;
  10228. is( $stringT, undef, 'pipemess: list context, "no output STDERR blablabla then false", string' ) ;
  10229. like( $errorT, qr{blablabla"}xm, 'pipemess: list context, "no output STDERR blablabla then false", error' ) ;
  10230. ( $stringT, $errorT ) = pipemess( 'dontcare', 'false', '( echo -n blablabla 3>&1 1>&2 2>&3 )' ) ;
  10231. is( $stringT, undef, 'pipemess: list context, "false then STDERR blablabla", string' ) ;
  10232. like( $errorT, qr{\QFailure: --pipemess command "false" ended with "0" characters exit value "1" and STDERR ""\E}xm,
  10233. 'pipemess: list context, "false then STDERR blablabla", error' ) ;
  10234. ( $stringT, $errorT ) = pipemess( 'dontcare', '( echo rrrrr ; echo -n error_blablabla 3>&1 1>&2 2>&3 )' ) ;
  10235. like( $stringT, qr{rrrrr}xm, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", string' ) ;
  10236. like( $errorT, qr{STDERR.*error_blablabla}xm, 'pipemess: list context, "STDOUT rrrrr STDERR error_blablabla", error' ) ;
  10237. }
  10238. ( $stringT, $errorT ) = pipemess( 'dontcare', 'cacaprout' ) ;
  10239. is( $stringT, undef, 'pipemess: list context, cacaprout not found, string' ) ;
  10240. like( $errorT, qr{\QFailure: --pipemess command "cacaprout" ended with "0" characters exit value\E}xm,
  10241. 'pipemess: list context, cacaprout not found, error' ) ;
  10242. note( 'Leaving tests_pipemess()' ) ;
  10243. return ;
  10244. }
  10245. sub tests_is_a_release_number
  10246. {
  10247. note( 'Entering tests_is_a_release_number()' ) ;
  10248. is( undef, is_a_release_number( ), 'is_a_release_number: no args => undef' ) ;
  10249. ok( is_a_release_number( $RELEASE_NUMBER_EXAMPLE_1 ), 'is_a_release_number 1.351' ) ;
  10250. ok( is_a_release_number( $RELEASE_NUMBER_EXAMPLE_2 ), 'is_a_release_number 42.4242' ) ;
  10251. ok( is_a_release_number( imapsync_version( $sync ) ), 'is_a_release_number imapsync_version( )' ) ;
  10252. ok( ! is_a_release_number( 'blabla' ), '! is_a_release_number blabla' ) ;
  10253. note( 'Leaving tests_is_a_release_number()' ) ;
  10254. return ;
  10255. }
  10256. sub is_a_release_number
  10257. {
  10258. my $number = shift ;
  10259. if ( ! defined $number ) { return ; }
  10260. return( $number =~ m{^\d+\.\d+$}xo ) ;
  10261. }
  10262. sub imapsync_version_public
  10263. {
  10264. my $local_version = imapsync_version( $sync ) ;
  10265. my $imapsync_basename = imapsync_basename( ) ;
  10266. my $context = imapsync_context( ) ;
  10267. my $agent_info = "$OSNAME system, perl "
  10268. . mysprintf( '%vd', $PERL_VERSION)
  10269. . ", Mail::IMAPClient $Mail::IMAPClient::VERSION"
  10270. . " $imapsync_basename"
  10271. . " $context" ;
  10272. my $sock = IO::Socket::INET->new(
  10273. PeerAddr => 'imapsync.lamiral.info',
  10274. PeerPort => 80,
  10275. Proto => 'tcp',
  10276. ) ;
  10277. return( 'unknown' ) if not $sock ;
  10278. print $sock
  10279. "GET /prj/imapsync/VERSION HTTP/1.0\r\n",
  10280. "User-Agent: imapsync/$local_version ($agent_info)\r\n",
  10281. "Host: ks.lamiral.info\r\n\r\n" ;
  10282. my @line = <$sock> ;
  10283. close $sock ;
  10284. my $last_release = $line[$LAST] ;
  10285. chomp $last_release ;
  10286. return( $last_release ) ;
  10287. }
  10288. sub not_long_imapsync_version_public
  10289. {
  10290. #myprint( "Entering not_long_imapsync_version_public\n" ) ;
  10291. my $fake = shift ;
  10292. if ( $fake ) { return $fake }
  10293. my $val ;
  10294. # Doesn't work with gethostbyname (see perlipc)
  10295. #local $SIG{ALRM} = sub { die "alarm\n" } ;
  10296. if ('MSWin32' eq $OSNAME) {
  10297. local $SIG{ALRM} = sub { die "alarm\n" } ;
  10298. }else{
  10299. POSIX::sigaction(SIGALRM,
  10300. POSIX::SigAction->new(sub { croak 'alarm' } ) )
  10301. or myprint( "Error setting SIGALRM handler: $OS_ERROR\n" ) ;
  10302. }
  10303. my $ret = eval {
  10304. alarm 3 ;
  10305. {
  10306. $val = imapsync_version_public( ) ;
  10307. #sleep 4 ;
  10308. #myprint( "End of imapsync_version_public\n" ) ;
  10309. }
  10310. alarm 0 ;
  10311. 1 ;
  10312. } ;
  10313. #myprint( "eval [$ret]\n" ) ;
  10314. if ( ( not $ret ) or $EVAL_ERROR ) {
  10315. #myprint( "$EVAL_ERROR" ) ;
  10316. if ($EVAL_ERROR =~ /alarm/) {
  10317. # timed out
  10318. return('timeout') ;
  10319. }else{
  10320. alarm 0 ;
  10321. return( 'unknown' ) ; # propagate unexpected errors
  10322. }
  10323. }else {
  10324. # Good!
  10325. return( $val ) ;
  10326. }
  10327. }
  10328. sub tests_not_long_imapsync_version_public
  10329. {
  10330. note( 'Entering tests_not_long_imapsync_version_public()' ) ;
  10331. is( 1, is_a_release_number( not_long_imapsync_version_public( ) ),
  10332. 'not_long_imapsync_version_public: public release is a number' ) ;
  10333. note( 'Leaving tests_not_long_imapsync_version_public()' ) ;
  10334. return ;
  10335. }
  10336. sub check_last_release
  10337. {
  10338. my $fake = shift ;
  10339. my $public_release = not_long_imapsync_version_public( $fake ) ;
  10340. $sync->{ debug } and myprint( "check_last_release: [$public_release]\n" ) ;
  10341. my $inline_help_when_on = '( Use --noreleasecheck to avoid this release check. )' ;
  10342. if ( $public_release eq 'unknown' ) {
  10343. return( 'Imapsync public release is unknown.' . $inline_help_when_on ) ;
  10344. }
  10345. if ( $public_release eq 'timeout' ) {
  10346. return( 'Imapsync public release is unknown (timeout).' . $inline_help_when_on ) ;
  10347. }
  10348. if ( ! is_a_release_number( $public_release ) ) {
  10349. return( "Imapsync public release is unknown ($public_release)." . $inline_help_when_on ) ;
  10350. }
  10351. my $imapsync_here = imapsync_version( $sync ) ;
  10352. if ( $public_release > $imapsync_here ) {
  10353. return( 'This imapsync is not up to date. ' . "( local $imapsync_here < official $public_release )" . $inline_help_when_on ) ;
  10354. }else{
  10355. return( 'This imapsync is up to date. ' . "( local $imapsync_here >= official $public_release )" . $inline_help_when_on ) ;
  10356. }
  10357. return( 'really unknown' ) ; # Should never arrive here
  10358. }
  10359. sub tests_check_last_release
  10360. {
  10361. note( 'Entering tests_check_last_release()' ) ;
  10362. diag( check_last_release( 1.1 ) ) ;
  10363. # \Q \E here to avoid putting \ before each space
  10364. like( check_last_release( 1.1 ), qr/\Qis up to date\E/mxs, 'check_last_release: up to date' ) ;
  10365. like( check_last_release( 1.1 ), qr/1\.1/mxs, 'check_last_release: up to date, include number' ) ;
  10366. diag( check_last_release( 999.999 ) ) ;
  10367. like( check_last_release( 999.999 ), qr/\Qnot up to date\E/mxs, 'check_last_release: not up to date' ) ;
  10368. like( check_last_release( 999.999 ), qr/999\.999/mxs, 'check_last_release: not up to date, include number' ) ;
  10369. like( check_last_release( 'unknown' ), qr/\QImapsync public release is unknown\E/mxs, 'check_last_release: unknown' ) ;
  10370. like( check_last_release( 'timeout' ), qr/\QImapsync public release is unknown (timeout)\E/mxs, 'check_last_release: timeout' ) ;
  10371. like( check_last_release( 'lalala' ), qr/\QImapsync public release is unknown (lalala)\E/mxs, 'check_last_release: lalala' ) ;
  10372. diag( check_last_release( ) ) ;
  10373. note( 'Leaving tests_check_last_release()' ) ;
  10374. return ;
  10375. }
  10376. sub tests_imapsync_context
  10377. {
  10378. note( 'Entering tests_imapsync_context()' ) ;
  10379. like( imapsync_context( ), qr/^CGI|^Docker|^DockerCGI|^Standard/, 'imapsync_context: CGI or Docker or DockerCGI or Standard' ) ;
  10380. note( 'Leaving tests_imapsync_context()' ) ;
  10381. return ;
  10382. }
  10383. sub imapsync_context
  10384. {
  10385. my $mysync = shift ;
  10386. my $context = q{} ;
  10387. if ( under_docker_context( $mysync ) && under_cgi_context( $mysync ) )
  10388. {
  10389. $context = 'DockerCGI' ;
  10390. }
  10391. elsif ( under_docker_context( $mysync ) )
  10392. {
  10393. $context = 'Docker' ;
  10394. }
  10395. elsif ( under_cgi_context( $mysync ) )
  10396. {
  10397. $context = 'CGI' ;
  10398. }
  10399. else
  10400. {
  10401. $context = 'Standard' ;
  10402. }
  10403. return $context ;
  10404. }
  10405. sub imapsync_version
  10406. {
  10407. my $mysync = shift ;
  10408. my $rcs = $mysync->{rcs} ;
  10409. my $version ;
  10410. $version = version_from_rcs( $rcs ) ;
  10411. return( $version ) ;
  10412. }
  10413. sub tests_version_from_rcs
  10414. {
  10415. note( 'Entering tests_version_from_rcs()' ) ;
  10416. is( undef, version_from_rcs( ), 'version_from_rcs: no args => UNKNOWN' ) ;
  10417. 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' ) ;
  10418. is( 'UNKNOWN', version_from_rcs( 1.831 ), 'version_from_rcs: 1.831 => UNKNOWN' ) ;
  10419. note( 'Leaving tests_version_from_rcs()' ) ;
  10420. return ;
  10421. }
  10422. sub version_from_rcs
  10423. {
  10424. my $rcs = shift ;
  10425. if ( ! $rcs ) { return ; }
  10426. my $version = 'UNKNOWN' ;
  10427. if ( $rcs =~ m{,v\s+(\d+\.\d+)}mxso ) {
  10428. $version = $1
  10429. }
  10430. return( $version ) ;
  10431. }
  10432. sub tests_imapsync_basename
  10433. {
  10434. note( 'Entering tests_imapsync_basename()' ) ;
  10435. ok( imapsync_basename() =~ m/imapsync/, 'imapsync_basename: match imapsync');
  10436. ok( 'blabla' ne imapsync_basename(), 'imapsync_basename: do not equal blabla');
  10437. note( 'Leaving tests_imapsync_basename()' ) ;
  10438. return ;
  10439. }
  10440. sub imapsync_basename
  10441. {
  10442. return basename( $PROGRAM_NAME ) ;
  10443. }
  10444. sub localhost_info
  10445. {
  10446. my $mysync = shift ;
  10447. my( $infos ) = join( q{},
  10448. "Here is imapsync ", imapsync_version( $mysync ),
  10449. " on host " . hostname(),
  10450. ", a $OSNAME system with ",
  10451. ram_memory_info( ),
  10452. "\n",
  10453. 'with Perl ',
  10454. mysprintf( '%vd ', $PERL_VERSION),
  10455. "and Mail::IMAPClient $Mail::IMAPClient::VERSION",
  10456. ) ;
  10457. return( $infos ) ;
  10458. }
  10459. sub tests_cpu_number
  10460. {
  10461. note( 'Entering tests_cpu_number()' ) ;
  10462. is( 1, is_an_integer( cpu_number( ) ), "cpu_number: is_an_integer" ) ;
  10463. ok( 1 <= cpu_number( ), "cpu_number: 1 or more" ) ;
  10464. is( 1, cpu_number( 1 ), "cpu_number: 1 => 1" ) ;
  10465. is( 1, cpu_number( $MINUS_ONE ), "cpu_number: -1 => 1" ) ;
  10466. is( 1, cpu_number( 'lalala' ), "cpu_number: lalala => 1" ) ;
  10467. is( $NUMBER_42, cpu_number( $NUMBER_42 ), "cpu_number: $NUMBER_42 => $NUMBER_42" ) ;
  10468. note( 'Leaving tests_cpu_number()' ) ;
  10469. return ;
  10470. }
  10471. sub cpu_number
  10472. {
  10473. my $cpu_number_forced = shift ;
  10474. # Well, here 1 is better than 0 or undef
  10475. my $cpu_number = 1 ; # Default value, erased if better found
  10476. my @cpuinfo ;
  10477. if ( $ENV{"NUMBER_OF_PROCESSORS"} ) {
  10478. # might be under a Windows system
  10479. $cpu_number = $ENV{"NUMBER_OF_PROCESSORS"} ;
  10480. $sync->{ debug } and myprint( "Number of processors found by env var NUMBER_OF_PROCESSORS: $cpu_number\n" ) ;
  10481. }elsif ( 'darwin' eq $OSNAME or 'freebsd' eq $OSNAME ) {
  10482. $cpu_number = backtick( "sysctl -n hw.ncpu" ) ;
  10483. chomp( $cpu_number ) ;
  10484. $sync->{ debug } and myprint( "Number of processors found by cmd 'sysctl -n hw.ncpu': $cpu_number\n" ) ;
  10485. }elsif ( ! -e '/proc/cpuinfo' ) {
  10486. $sync->{ debug } and myprint( "Number of processors not found so I might assume there is only 1\n" ) ;
  10487. $cpu_number = 1 ;
  10488. }elsif( @cpuinfo = file_to_array( '/proc/cpuinfo' ) ) {
  10489. $cpu_number = grep { /^processor/mxs } @cpuinfo ;
  10490. $sync->{ debug } and myprint( "Number of processors found via /proc/cpuinfo: $cpu_number\n" ) ;
  10491. }
  10492. if ( defined $cpu_number_forced ) {
  10493. $cpu_number = $cpu_number_forced ;
  10494. }
  10495. return( integer_or_1( $cpu_number ) ) ;
  10496. }
  10497. sub tests_integer_or_1
  10498. {
  10499. note( 'Entering tests_integer_or_1()' ) ;
  10500. is( 1, integer_or_1( ), 'integer_or_1: no args => 1' ) ;
  10501. is( 1, integer_or_1( undef ), 'integer_or_1: undef => 1' ) ;
  10502. is( $NUMBER_10, integer_or_1( $NUMBER_10 ), 'integer_or_1: 10 => 10' ) ;
  10503. is( 1, integer_or_1( q{} ), 'integer_or_1: empty string => 1' ) ;
  10504. is( 1, integer_or_1( 'lalala' ), 'integer_or_1: lalala => 1' ) ;
  10505. note( 'Leaving tests_integer_or_1()' ) ;
  10506. return ;
  10507. }
  10508. sub integer_or_1
  10509. {
  10510. my $number = shift ;
  10511. if ( is_an_integer( $number ) ) {
  10512. return $number ;
  10513. }
  10514. # else
  10515. return 1 ;
  10516. }
  10517. sub tests_is_an_integer
  10518. {
  10519. note( 'Entering tests_is_an_integer()' ) ;
  10520. is( undef, is_an_integer( ), 'is_an_integer: no args => undef ' ) ;
  10521. ok( is_an_integer( 1 ), 'is_an_integer: 1 => yes ') ;
  10522. ok( is_an_integer( $NUMBER_42 ), 'is_an_integer: 42 => yes ') ;
  10523. ok( is_an_integer( "$NUMBER_42" ), 'is_an_integer: "$NUMBER_42" => yes ') ;
  10524. ok( is_an_integer( '42' ), 'is_an_integer: "42" => yes ') ;
  10525. ok( is_an_integer( $NUMBER_104_857_600 ), 'is_an_integer: 104_857_600 => yes') ;
  10526. ok( is_an_integer( "$NUMBER_104_857_600" ), 'is_an_integer: "$NUMBER_104_857_600" => yes') ;
  10527. ok( is_an_integer( '104857600' ), 'is_an_integer: 104857600 => yes') ;
  10528. ok( ! is_an_integer( 'blabla' ), 'is_an_integer: blabla => no' ) ;
  10529. ok( ! is_an_integer( q{} ), 'is_an_integer: empty string => no' ) ;
  10530. note( 'Leaving tests_is_an_integer()' ) ;
  10531. return ;
  10532. }
  10533. sub is_an_integer
  10534. {
  10535. my $number = shift ;
  10536. if ( ! defined $number ) { return ; }
  10537. return( $number =~ m{^\d+$}xo ) ;
  10538. }
  10539. sub tests_loadavg
  10540. {
  10541. note( 'Entering tests_loadavg()' ) ;
  10542. SKIP: {
  10543. skip( 'Tests for darwin', 2 ) if ('darwin' ne $OSNAME) ;
  10544. is( undef, loadavg( '/noexist' ), 'loadavg: /noexist => undef' ) ;
  10545. is_deeply( [ '0.11', '0.22', '0.33' ],
  10546. [ loadavg( 'W/t/loadavg.out' ) ],
  10547. 'loadavg W/t/loadavg.out => 0.11 0.22 0.33' ) ;
  10548. } ;
  10549. SKIP: {
  10550. skip( 'Tests for linux', 3 ) if ('linux' ne $OSNAME) ;
  10551. is( undef, loadavg( '/noexist' ), 'loadavg: /noexist => undef' ) ;
  10552. ok( loadavg( ), 'loadavg: no args' ) ;
  10553. is_deeply( [ '0.39', '0.30', '0.37', '1/602' ],
  10554. [ loadavg( '0.39 0.30 0.37 1/602 6073' ) ],
  10555. 'loadavg 0.39 0.30 0.37 1/602 6073 => [0.39, 0.30, 0.37, 1/602]' ) ;
  10556. } ;
  10557. SKIP: {
  10558. skip( 'Tests for Windows', 1 ) if ('MSWin32' ne $OSNAME) ;
  10559. is_deeply( [ 0 ],
  10560. [ loadavg( ) ],
  10561. 'loadavg on MSWin32 => 0' ) ;
  10562. } ;
  10563. note( 'Leaving tests_loadavg()' ) ;
  10564. return ;
  10565. }
  10566. sub loadavg
  10567. {
  10568. if ( 'linux' eq $OSNAME ) {
  10569. return ( loadavg_linux( @ARG ) ) ;
  10570. }
  10571. if ( 'freebsd' eq $OSNAME ) {
  10572. return ( loadavg_freebsd( @ARG ) ) ;
  10573. }
  10574. if ( 'darwin' eq $OSNAME ) {
  10575. return ( loadavg_darwin( @ARG ) ) ;
  10576. }
  10577. if ( 'MSWin32' eq $OSNAME ) {
  10578. return ( loadavg_windows( @ARG ) ) ;
  10579. }
  10580. return( 'unknown' ) ;
  10581. }
  10582. sub loadavg_linux
  10583. {
  10584. my $line = shift ;
  10585. if ( ! $line ) {
  10586. $line = firstline( '/proc/loadavg' ) or return ;
  10587. }
  10588. my ( $avg_1_min, $avg_5_min, $avg_15_min, $current_runs ) = split /\s/mxs, $line ;
  10589. if ( all_defined( $avg_1_min, $avg_5_min, $avg_15_min ) ) {
  10590. $sync->{ debug } and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min $current_runs\n" ) ;
  10591. return ( $avg_1_min, $avg_5_min, $avg_15_min, $current_runs ) ;
  10592. }
  10593. return ;
  10594. }
  10595. sub loadavg_freebsd
  10596. {
  10597. my $file = shift ;
  10598. # Example of output of command "sysctl vm.loadavg":
  10599. # vm.loadavg: { 0.15 0.08 0.08 }
  10600. my $loadavg ;
  10601. if ( ! defined $file ) {
  10602. eval {
  10603. $loadavg = `/sbin/sysctl vm.loadavg` ;
  10604. #myprint( "LOADAVG FREEBSD: $loadavg\n" ) ;
  10605. } ;
  10606. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  10607. }else{
  10608. $loadavg = firstline( $file ) or return ;
  10609. }
  10610. my ( $avg_1_min, $avg_5_min, $avg_15_min )
  10611. = $loadavg =~ /vm\.loadavg\s*[:=]\s*\{?\s*(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)/mxs ;
  10612. $sync->{ debug } and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min\n" ) ;
  10613. return ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  10614. }
  10615. sub loadavg_darwin
  10616. {
  10617. my $file = shift ;
  10618. # Example of output of command "sysctl vm.loadavg":
  10619. # vm.loadavg: { 0.15 0.08 0.08 }
  10620. my $loadavg ;
  10621. if ( ! defined $file ) {
  10622. eval {
  10623. $loadavg = `/usr/sbin/sysctl vm.loadavg` ;
  10624. #myprint( "LOADAVG DARWIN: $loadavg\n" ) ;
  10625. } ;
  10626. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  10627. }else{
  10628. $loadavg = firstline( $file ) or return ;
  10629. }
  10630. my ( $avg_1_min, $avg_5_min, $avg_15_min )
  10631. = $loadavg =~ /vm\.loadavg\s*[:=]\s*\{?\s*(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)/mxs ;
  10632. $sync->{ debug } and myprint( "System load: $avg_1_min $avg_5_min $avg_15_min\n" ) ;
  10633. return ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  10634. }
  10635. sub loadavg_windows
  10636. {
  10637. my $file = shift ;
  10638. # Example of output of command "wmic cpu get loadpercentage":
  10639. # LoadPercentage
  10640. # 12
  10641. my $loadavg ;
  10642. if ( ! defined $file ) {
  10643. eval {
  10644. #$loadavg = `CMD wmic cpu get loadpercentage` ;
  10645. $loadavg = "LoadPercentage\n0\n" ;
  10646. #myprint( "LOADAVG WIN: $loadavg\n" ) ;
  10647. } ;
  10648. if ( $EVAL_ERROR ) { myprint( "[$EVAL_ERROR]\n" ) ; return ; }
  10649. }else{
  10650. $loadavg = file_to_string( $file ) or return ;
  10651. #myprint( "$loadavg" ) ;
  10652. }
  10653. $loadavg =~ /LoadPercentage\n(\d+)/xms ;
  10654. my $num = $1 ;
  10655. $num /= 100 ;
  10656. $sync->{ debug } and myprint( "System load: $num\n" ) ;
  10657. return ( $num ) ;
  10658. }
  10659. sub tests_load_and_delay
  10660. {
  10661. note( 'Entering tests_load_and_delay()' ) ;
  10662. is( undef, load_and_delay( ), 'load_and_delay: no args => undef ' ) ;
  10663. is( undef, load_and_delay( 1 ), 'load_and_delay: not 4 args => undef ' ) ;
  10664. is( undef, load_and_delay( 0, 1, 1, 1 ), 'load_and_delay: division per 0 => undef ' ) ;
  10665. is( 0, load_and_delay( 1, 1, 1, 1 ), 'load_and_delay: one core, loads are all 1 => ok ' ) ;
  10666. is( 0, load_and_delay( 1, 1, 1, 1, 'lalala' ), 'load_and_delay: five arguments is ok' ) ;
  10667. is( 0, load_and_delay( 2, 2, 2, 2 ), 'load_and_delay: two core, loads are all 2 => ok ' ) ;
  10668. is( 0, load_and_delay( 2, 2, 4, 5 ), 'load_and_delay: two core, load1m is 2 => ok ' ) ;
  10669. # Old behavior, rather strict
  10670. # is( 0, load_and_delay( 1, 0, 0, 0 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=0 => 0 ' ) ;
  10671. # is( 0, load_and_delay( 1, 0, 0, 2 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=2 => 0 ' ) ;
  10672. # is( 0, load_and_delay( 1, 0, 2, 0 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=0 => 0 ' ) ;
  10673. # is( 0, load_and_delay( 1, 0, 2, 2 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=2 => 0 ' ) ;
  10674. # is( 1, load_and_delay( 1, 2, 0, 0 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=0 => 1 ' ) ;
  10675. # is( 1, load_and_delay( 1, 2, 0, 2 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=2 => 1 ' ) ;
  10676. # is( 5, load_and_delay( 1, 2, 2, 0 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=0 => 5 ' ) ;
  10677. # is( 15, load_and_delay( 1, 2, 2, 2 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=2 => 15 ' ) ;
  10678. # is( 0, load_and_delay( 4, 0, 2, 2 ), 'load_and_delay: four core, load1m=0 load5m=2 load15m=2 => 0 ' ) ;
  10679. # is( 1, load_and_delay( 4, 8, 0, 0 ), 'load_and_delay: four core, load1m=2 load5m=0 load15m=0 => 1 ' ) ;
  10680. # is( 1, load_and_delay( 4, 8, 0, 2 ), 'load_and_delay: four core, load1m=2 load5m=0 load15m=2 => 1 ' ) ;
  10681. # is( 5, load_and_delay( 4, 8, 8, 0 ), 'load_and_delay: four core, load1m=2 load5m=2 load15m=0 => 5 ' ) ;
  10682. # is( 15, load_and_delay( 4, 8, 8, 8 ), 'load_and_delay: four core, load1m=2 load5m=2 load15m=2 => 15 ' ) ;
  10683. # New behavior, tolerate more load
  10684. is( 0, load_and_delay( 1, 0, 0, 0 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=0 => 0 ' ) ;
  10685. is( 0, load_and_delay( 1, 0, 0, 2 ), 'load_and_delay: one core, load1m=0 load5m=0 load15m=2 => 0 ' ) ;
  10686. is( 0, load_and_delay( 1, 0, 2, 0 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=0 => 0 ' ) ;
  10687. is( 0, load_and_delay( 1, 0, 2, 2 ), 'load_and_delay: one core, load1m=0 load5m=2 load15m=2 => 0 ' ) ;
  10688. is( 0, load_and_delay( 1, 2, 0, 0 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=0 => 1 ' ) ;
  10689. is( 0, load_and_delay( 1, 2, 0, 2 ), 'load_and_delay: one core, load1m=2 load5m=0 load15m=2 => 1 ' ) ;
  10690. is( 0, load_and_delay( 1, 2, 2, 0 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=0 => 5 ' ) ;
  10691. is( 0, load_and_delay( 1, 2, 2, 2 ), 'load_and_delay: one core, load1m=2 load5m=2 load15m=2 => 15 ' ) ;
  10692. is( 1, load_and_delay( 1, 4, 0, 0 ), 'load_and_delay: one core, load1m=4 load5m=0 load15m=0 => 1 ' ) ;
  10693. is( 1, load_and_delay( 1, 4, 0, 4 ), 'load_and_delay: one core, load1m=4 load5m=0 load15m=4 => 1 ' ) ;
  10694. is( 5, load_and_delay( 1, 4, 4, 0 ), 'load_and_delay: one core, load1m=4 load5m=4 load15m=0 => 5 ' ) ;
  10695. is( 15, load_and_delay( 1, 4, 4, 4 ), 'load_and_delay: one core, load1m=4 load5m=4 load15m=4 => 15 ' ) ;
  10696. is( 0, load_and_delay( 4, 0, 9, 9 ), 'load_and_delay: four core, load1m=0 load5m=9 load15m=9 => 0 ' ) ;
  10697. is( 1, load_and_delay( 4, 9, 0, 0 ), 'load_and_delay: four core, load1m=9 load5m=0 load15m=0 => 1 ' ) ;
  10698. is( 1, load_and_delay( 4, 9, 0, 9 ), 'load_and_delay: four core, load1m=9 load5m=0 load15m=9 => 1 ' ) ;
  10699. is( 5, load_and_delay( 4, 9, 9, 0 ), 'load_and_delay: four core, load1m=9 load5m=9 load15m=0 => 5 ' ) ;
  10700. is( 15, load_and_delay( 4, 9, 9, 9 ), 'load_and_delay: four core, load1m=9 load5m=9 load15m=9 => 15 ' ) ;
  10701. note( 'Leaving tests_load_and_delay()' ) ;
  10702. return ;
  10703. }
  10704. sub load_and_delay
  10705. {
  10706. # Basically return 0 if load is not heavy, ie <= 1 per processor
  10707. # Not enough arguments
  10708. if ( 4 > scalar @ARG ) { return ; }
  10709. my ( $cpu_num, $avg_1_min, $avg_5_min, $avg_15_min ) = @ARG ;
  10710. if ( 0 == $cpu_num ) { return ; }
  10711. # Let divide by number of cores
  10712. ( $avg_1_min, $avg_5_min, $avg_15_min ) = map { $_ / $cpu_num } ( $avg_1_min, $avg_5_min, $avg_15_min ) ;
  10713. # One of avg ok => ok, for now it is a OR
  10714. if ( $avg_1_min <= 2 ) { return 0 ; }
  10715. if ( $avg_5_min <= 2 ) { return 1 ; } # Retry in 1 minute
  10716. if ( $avg_15_min <= 2 ) { return 5 ; } # Retry in 5 minutes
  10717. return 15 ; # Retry in 15 minutes
  10718. }
  10719. sub ram_memory_info
  10720. {
  10721. # In GigaBytes so division by 1024 * 1024 * 1024
  10722. #
  10723. return(
  10724. sprintf( "%.1f/%.1f free GiB of RAM",
  10725. Sys::MemInfo::get("freemem") / ( $KIBI ** 3 ),
  10726. Sys::MemInfo::get("totalmem") / ( $KIBI ** 3 ),
  10727. )
  10728. ) ;
  10729. }
  10730. sub tests_memory_stress
  10731. {
  10732. note( 'Entering tests_memory_stress()' ) ;
  10733. is( undef, memory_stress( ), 'memory_stress: => undef' ) ;
  10734. note( 'Leaving tests_memory_stress()' ) ;
  10735. return ;
  10736. }
  10737. sub memory_stress
  10738. {
  10739. my $total_ram_in_MB = Sys::MemInfo::get("totalmem") / ( $KIBI * $KIBI ) ;
  10740. my $i = 1 ;
  10741. myprintf("Stress memory consumption before: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  10742. while ( $i < $total_ram_in_MB / 1.7 ) { $a .= "A" x 1000_000; $i++ } ;
  10743. myprintf("Stress memory consumption after: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ;
  10744. return ;
  10745. }
  10746. sub tests_memory_consumption
  10747. {
  10748. note( 'Entering tests_memory_consumption()' ) ;
  10749. like( memory_consumption( ), qr{\d+}xms,'memory_consumption no args') ;
  10750. like( memory_consumption( 1 ), qr{\d+}xms,'memory_consumption 1') ;
  10751. like( memory_consumption( $PROCESS_ID ), qr{\d+}xms,"memory_consumption_of_pids $PROCESS_ID") ;
  10752. like( memory_consumption_ratio(), qr{\d+}xms, 'memory_consumption_ratio' ) ;
  10753. like( memory_consumption_ratio(1), qr{\d+}xms, 'memory_consumption_ratio 1' ) ;
  10754. like( memory_consumption_ratio(10), qr{\d+}xms, 'memory_consumption_ratio 10' ) ;
  10755. like( memory_consumption(), qr{\d+}xms, "memory_consumption\n" ) ;
  10756. note( 'Leaving tests_memory_consumption()' ) ;
  10757. return ;
  10758. }
  10759. sub memory_consumption
  10760. {
  10761. # memory consumed by imapsync until now in bytes
  10762. return( ( memory_consumption_of_pids( ) )[0] );
  10763. }
  10764. sub debugmemory
  10765. {
  10766. my $mysync = shift ;
  10767. if ( ! $mysync->{debugmemory} ) { return q{} ; }
  10768. my $precision = shift ;
  10769. return( mysprintf( "Memory consumption$precision: %.1f MiB\n", memory_consumption( ) / $KIBI / $KIBI ) ) ;
  10770. }
  10771. sub memory_consumption_of_pids
  10772. {
  10773. my @pid = @_;
  10774. @pid = ( @pid ) ? @pid : ( $PROCESS_ID ) ;
  10775. $sync->{ debug } and myprint( "memory_consumption_of_pids PIDs: @pid\n" ) ;
  10776. my @val ;
  10777. if ( ( 'MSWin32' eq $OSNAME ) or ( 'cygwin' eq $OSNAME ) ) {
  10778. @val = memory_consumption_of_pids_win32( @pid ) ;
  10779. }else{
  10780. # Unix
  10781. my @ps = qx{ ps -o vsz -p @pid } ;
  10782. #myprint( "ps: @ps" ) ;
  10783. # Use IPC::Open3 from perlcrit -3
  10784. # It stalls on Darwin, don't understand why!
  10785. #my @ps = backtick( "ps -o vsz -p @pid" ) ;
  10786. #myprint( "ps: @ps" ) ;
  10787. shift @ps; # First line is column name "VSZ"
  10788. chomp @ps;
  10789. # convert to octets
  10790. @val = map { $_ * $KIBI } @ps ;
  10791. }
  10792. $sync->{ debug } and myprint( "@val\n" ) ;
  10793. return( @val ) ;
  10794. }
  10795. sub memory_consumption_of_pids_win32
  10796. {
  10797. # Windows
  10798. my @PID = @_;
  10799. my %PID;
  10800. # hash of pids as key values
  10801. map { $PID{$_}++ } @PID;
  10802. # Does not work but should work reading the tasklist documentation
  10803. #@ps = qx{ tasklist /FI "PID eq @PID" };
  10804. my @ps = qx{ tasklist /NH /FO CSV } ;
  10805. #my @ps = backtick( 'tasklist /NH /FO CSV' ) ;
  10806. #myprint( "-" x $STD_CHAR_PER_LINE, "\n", @ps, "-" x $STD_CHAR_PER_LINE, "\n" ) ;
  10807. my @val;
  10808. foreach my $line (@ps) {
  10809. my($name, $pid, $mem) = (split ',', $line )[0,1,4];
  10810. next if (! $pid);
  10811. #myprint( "[$name][$pid][$mem]" ) ;
  10812. if ($PID{remove_qq($pid)}) {
  10813. #myprint( "MATCH !\n" ) ;
  10814. chomp $mem ;
  10815. $mem = remove_qq($mem);
  10816. $mem = remove_Ko($mem);
  10817. $mem = remove_not_num($mem);
  10818. #myprint( "[$mem]\n" ) ;
  10819. push @val, $mem * $KIBI;
  10820. }
  10821. }
  10822. return(@val);
  10823. }
  10824. sub tests_backtick
  10825. {
  10826. note( 'Entering tests_backtick()' ) ;
  10827. is( undef, backtick( ), 'backtick: no args' ) ;
  10828. is( undef, backtick( q{} ), 'backtick: empty command' ) ;
  10829. SKIP: {
  10830. skip( 'test for MSWin32', 5 ) if ('MSWin32' ne $OSNAME) ;
  10831. my @output ;
  10832. @output = backtick( 'echo Hello World!' ) ;
  10833. # Add \r on Windows.
  10834. ok( "Hello World!\r\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  10835. $sync->{ debug } and myprint( "[@output]" ) ;
  10836. @output = backtick( 'echo Hello & echo World!' ) ;
  10837. ok( "Hello \r\n" eq $output[0], 'backtick: echo Hello & echo World! line 1' ) ;
  10838. ok( "World!\r\n" eq $output[1], 'backtick: echo Hello & echo World! line 2' ) ;
  10839. $sync->{ debug } and myprint( "[@output][$output[0]][$output[1]]" ) ;
  10840. # Scalar context
  10841. ok( "Hello World!\r\n" eq backtick( 'echo Hello World!' ),
  10842. 'backtick: echo Hello World! scalar' ) ;
  10843. ok( "Hello \r\nWorld!\r\n" eq backtick( 'echo Hello & echo World!' ),
  10844. 'backtick: echo Hello & echo World! scalar 2 lines' ) ;
  10845. } ;
  10846. SKIP: {
  10847. skip( 'test for Unix', 7 ) if ('MSWin32' eq $OSNAME) ;
  10848. is( undef, backtick( 'aaaarrrg' ), 'backtick: aaaarrrg command not found' ) ;
  10849. # Array context
  10850. my @output ;
  10851. @output = backtick( 'echo Hello World!' ) ;
  10852. ok( "Hello World!\n" eq $output[0], 'backtick: echo Hello World!' ) ;
  10853. $sync->{ debug } and myprint( "[@output]" ) ;
  10854. @output = backtick( "echo Hello\necho World!" ) ;
  10855. ok( "Hello\n" eq $output[0], 'backtick: echo Hello; echo World! line 1' ) ;
  10856. ok( "World!\n" eq $output[1], 'backtick: echo Hello; echo World! line 2' ) ;
  10857. $sync->{ debug } and myprint( "[@output]" ) ;
  10858. # Scalar context
  10859. ok( "Hello World!\n" eq backtick( 'echo Hello World!' ),
  10860. 'backtick: echo Hello World! scalar' ) ;
  10861. ok( "Hello\nWorld!\n" eq backtick( "echo Hello\necho World!" ),
  10862. 'backtick: echo Hello; echo World! scalar 2 lines' ) ;
  10863. # Return error positive value, that's ok
  10864. is( undef, backtick( 'false' ), 'backtick: false returns no output' ) ;
  10865. my $mem = backtick( "ps -o vsz -p $PROCESS_ID" ) ;
  10866. $sync->{ debug } and myprint( "MEM=$mem\n" ) ;
  10867. }
  10868. note( 'Leaving tests_backtick()' ) ;
  10869. return ;
  10870. }
  10871. sub backtick
  10872. {
  10873. my $command = shift ;
  10874. if ( ! $command ) { return ; }
  10875. my ( $writer, $reader, $err ) ;
  10876. my @output ;
  10877. my $pid ;
  10878. my $eval = eval {
  10879. $pid = IPC::Open3::open3( $writer, $reader, $err, $command ) ;
  10880. } ;
  10881. if ( $EVAL_ERROR ) {
  10882. myprint( $EVAL_ERROR ) ;
  10883. return ;
  10884. }
  10885. if ( ! $eval ) { return ; }
  10886. if ( ! $pid ) { return ; }
  10887. waitpid( $pid, 0 ) ;
  10888. @output = <$reader>; # Output here
  10889. #
  10890. #my @errors = <$err>; #Errors here, instead of the console
  10891. if ( not @output ) { return ; }
  10892. #myprint( @output ) ;
  10893. if ( $output[0] =~ /\Qopen3: exec of $command failed\E/mxs ) { return ; }
  10894. if ( wantarray ) {
  10895. return( @output ) ;
  10896. } else {
  10897. return( join( q{}, @output) ) ;
  10898. }
  10899. }
  10900. sub tests_check_binary_embed_all_dyn_libs
  10901. {
  10902. note( 'Entering tests_check_binary_embed_all_dyn_libs()' ) ;
  10903. is( 1, check_binary_embed_all_dyn_libs( ), 'check_binary_embed_all_dyn_libs: no args => 1' ) ;
  10904. note( 'Leaving tests_check_binary_embed_all_dyn_libs()' ) ;
  10905. return ;
  10906. }
  10907. sub check_binary_embed_all_dyn_libs
  10908. {
  10909. my @search_dyn_lib_locale = search_dyn_lib_locale( ) ;
  10910. if ( @search_dyn_lib_locale )
  10911. {
  10912. myprint( "Found myself $PROGRAM_NAME pid $PROCESS_ID using locale dynamic libraries that seems out of myself:\n" ) ;
  10913. myprint( @search_dyn_lib_locale ) ;
  10914. if ( $PROGRAM_NAME =~ m{imapsync_bin_Darwin} )
  10915. {
  10916. return 0 ;
  10917. }
  10918. elsif ( $PROGRAM_NAME =~ m{imapsync.*\.exe} )
  10919. {
  10920. return 0 ;
  10921. }
  10922. else
  10923. {
  10924. # is always ok for non binary
  10925. return 1 ;
  10926. }
  10927. }
  10928. else
  10929. {
  10930. # Found only embedded dynamic lib
  10931. myprint( "Found nothing\n" ) ;
  10932. return 1 ;
  10933. }
  10934. }
  10935. sub search_dyn_lib_locale
  10936. {
  10937. if ( 'darwin' eq $OSNAME )
  10938. {
  10939. return search_dyn_lib_locale_darwin( ) ;
  10940. }
  10941. if ( 'linux' eq $OSNAME )
  10942. {
  10943. return search_dyn_lib_locale_linux( ) ;
  10944. }
  10945. if ( 'MSWin32' eq $OSNAME )
  10946. {
  10947. return search_dyn_lib_locale_MSWin32( ) ;
  10948. }
  10949. }
  10950. sub search_dyn_lib_locale_darwin
  10951. {
  10952. my $command = qq{ lsof -p $PID | grep ' REG ' | grep .dylib | grep -v '/par-' } ;
  10953. myprint( "Search non embeded dynamic libs with the command: $command\n" ) ;
  10954. return backtick( $command ) ;
  10955. }
  10956. sub search_dyn_lib_locale_linux
  10957. {
  10958. my $command = qq{ lsof -p $PID | grep ' REG ' | grep -v '/tmp/par-' | grep '\.so' } ;
  10959. myprint( "Search non embeded dynamic libs with the command: $command\n" ) ;
  10960. return backtick( $command ) ;
  10961. }
  10962. sub search_dyn_lib_locale_MSWin32
  10963. {
  10964. my $command = qq{ Listdlls.exe $PID|findstr Strawberry } ;
  10965. # $command = qq{ Listdlls.exe $PID|findstr Strawberry } ;
  10966. myprint( "Search non embeded dynamic libs with the command: $command\n" ) ;
  10967. return qx( $command ) ;
  10968. }
  10969. sub remove_not_num
  10970. {
  10971. my $string = shift ;
  10972. $string =~ tr/0-9//cd ;
  10973. #myprint( "tr [$string]\n" ) ;
  10974. return( $string ) ;
  10975. }
  10976. sub tests_remove_not_num
  10977. {
  10978. note( 'Entering tests_remove_not_num()' ) ;
  10979. ok( '123' eq remove_not_num( 123 ), 'remove_not_num( 123 )' ) ;
  10980. ok( '123' eq remove_not_num( '123' ), q{remove_not_num( '123' )} ) ;
  10981. ok( '123' eq remove_not_num( '12 3' ), q{remove_not_num( '12 3' )} ) ;
  10982. ok( '123' eq remove_not_num( 'a 12 3 Ko' ), q{remove_not_num( 'a 12 3 Ko' )} ) ;
  10983. note( 'Leaving tests_remove_not_num()' ) ;
  10984. return ;
  10985. }
  10986. sub remove_Ko
  10987. {
  10988. my $string = shift;
  10989. if ($string =~ /^(.*)\sKo$/xo) {
  10990. return($1);
  10991. }else{
  10992. return($string);
  10993. }
  10994. }
  10995. sub remove_qq
  10996. {
  10997. my $string = shift;
  10998. if ($string =~ /^"(.*)"$/xo) {
  10999. return($1);
  11000. }else{
  11001. return($string);
  11002. }
  11003. }
  11004. sub memory_consumption_ratio
  11005. {
  11006. my ($base) = @_;
  11007. $base ||= 1;
  11008. my $consu = memory_consumption();
  11009. return($consu / $base);
  11010. }
  11011. sub date_from_rcs
  11012. {
  11013. my $d = shift ;
  11014. 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 ) ;
  11015. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  11016. # Handles the following format
  11017. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  11018. #myprint( "$d\n" ) ;
  11019. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  11020. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  11021. $month = $num2mon{$month} ;
  11022. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  11023. #myprint( "$d\n" ) ;
  11024. }
  11025. return( $d ) ;
  11026. }
  11027. sub tests_date_from_rcs
  11028. {
  11029. note( 'Entering tests_date_from_rcs()' ) ;
  11030. ok('19-Sep-2015 16:11:07 +0000'
  11031. eq date_from_rcs('Date: 2015/09/19 16:11:07 '), 'date_from_rcs from RCS date' ) ;
  11032. note( 'Leaving tests_date_from_rcs()' ) ;
  11033. return ;
  11034. }
  11035. sub good_date
  11036. {
  11037. # two incoming formats:
  11038. # header Tue, 24 Aug 2010 16:00:00 +0200
  11039. # internal 24-Aug-2010 16:00:00 +0200
  11040. # outgoing format: internal date format
  11041. # 24-Aug-2010 16:00:00 +0200
  11042. my $d = shift ;
  11043. return(q{}) if not defined $d;
  11044. SWITCH: {
  11045. if ( $d =~ m{(\d?)(\d-...-\d{4})(\s\d{2}:\d{2}:\d{2})(\s(?:\+|-)\d{4})?}xo ) {
  11046. #myprint( "internal: [$1][$2][$3][$4]\n" ) ;
  11047. my ($day_1, $date_rest, $hour, $zone) = ($1,$2,$3,$4) ;
  11048. $day_1 = '0' if ($day_1 eq q{}) ;
  11049. $zone = ' +0000' if not defined $zone ;
  11050. $d = $day_1 . $date_rest . $hour . $zone ;
  11051. last SWITCH ;
  11052. }
  11053. 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 ) {
  11054. # Handles any combination of following formats
  11055. # Tue, 24 Aug 2010 16:00:00 +0200 -- Standard
  11056. # 24 Aug 2010 16:00:00 +0200 -- Missing Day of Week
  11057. # Tue, 24 Aug 97 16:00:00 +0200 -- Two digit year
  11058. # Tue, 24 Aug 1997 16.00.00 +0200 -- Periods instead of colons
  11059. # Tue, 24 Aug 1997 16:00:00 +0200 -- Extra whitespace between year and hour
  11060. # Tue, 24 Aug 1997 6:5:2 +0200 -- Single digit hour, min, or second
  11061. # Tue, 24, Aug 1997 16:00:00 +0200 -- Extra comma
  11062. #myprint( "header: [$1][$2][$3][$4][$5][$6][$7][$8]\n" ) ;
  11063. my ($day, $month, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7,$8);
  11064. $year = '19' . $year if length($year) == 2 && $year =~ m/^[789]/xo;
  11065. $year = '20' . $year if length($year) == 2;
  11066. $month = substr $month, 0, 3 if length($month) > 4;
  11067. $day = mysprintf( '%02d', $day);
  11068. $hour = mysprintf( '%02d', $hour);
  11069. $min = mysprintf( '%02d', $min);
  11070. $sec = '00' if not defined $sec ;
  11071. $sec = mysprintf( '%02d', $sec ) ;
  11072. $zone = '+0000' if not defined $zone ;
  11073. $d = "$day-$month-$year $hour:$min:$sec $zone" ;
  11074. last SWITCH ;
  11075. }
  11076. 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 ) {
  11077. # Handles any combination of following formats
  11078. # Sun Aug 20 11:55:09 2006
  11079. # Wed Jan 24 11:58:38 MST 2007
  11080. # Wed Jan 2 08:40:57 2008
  11081. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  11082. my ($month, $day, $hour, $min, $sec, $year) = ($1,$2,$3,$4,$5,$6);
  11083. $day = mysprintf( '%02d', $day ) ;
  11084. $hour = mysprintf( '%02d', $hour ) ;
  11085. $min = mysprintf( '%02d', $min ) ;
  11086. $sec = mysprintf( '%02d', $sec ) ;
  11087. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  11088. last SWITCH ;
  11089. }
  11090. 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 ) ;
  11091. if ($d =~ m{(\d{4})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  11092. # Handles the following format
  11093. # 2015/07/10 11:05:59 -- Generated by RCS Date tag.
  11094. #myprint( "$d\n" ) ;
  11095. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  11096. my ($year, $month, $day, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6) ;
  11097. $month = $num2mon{$month} ;
  11098. $d = "$day-$month-$year $hour:$min:$sec +0000" ;
  11099. #myprint( "$d\n" ) ;
  11100. last SWITCH ;
  11101. }
  11102. if ($d =~ m{(\d{2})/(\d{2})/(\d{2})\s(\d{2}):(\d{2}):(\d{2})}xo ) {
  11103. # Handles the following format
  11104. # 02/06/09 22:18:08 -- Generated by AVTECH TemPageR devices
  11105. #myprint( "header: [$1][$2][$3][$4][$5][$6]\n" ) ;
  11106. my ($month, $day, $year, $hour, $min, $sec) = ($1,$2,$3,$4,$5,$6);
  11107. $year = '20' . $year;
  11108. $month = $num2mon{$month};
  11109. $d = "$day-$month-$year $hour:$min:$sec +0000";
  11110. last SWITCH ;
  11111. }
  11112. 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 ) {
  11113. # Handles the following format
  11114. # Saturday, December 14, 2002 05:00 PM - KBtoys.com order confirmations
  11115. my ($month, $day, $year, $hour, $min, $apm) = ($1,$2,$3,$4,$5,$6);
  11116. $hour += 12 if $apm eq 'PM' ;
  11117. $day = mysprintf( '%02d', $day ) ;
  11118. $d = "$day-$month-$year $hour:$min:00 +0000" ;
  11119. last SWITCH ;
  11120. }
  11121. if ($d =~ m{(\w{3})\s(\d{1,2})\s(\d{4})\s(\d{2}):(\d{2}):(\d{2})\s((?:\+|-)\d{4})}xo ) {
  11122. # Handles the following format
  11123. # Saturday, December 14, 2002 05:00 PM - jr.com order confirmations
  11124. my ($month, $day, $year, $hour, $min, $sec, $zone) = ($1,$2,$3,$4,$5,$6,$7);
  11125. $day = mysprintf( '%02d', $day ) ;
  11126. $d = "$day-$month-$year $hour:$min:$sec $zone";
  11127. last SWITCH ;
  11128. }
  11129. if ($d =~ m{(\d{1,2})-(\w{3})-(\d{4})}xo ) {
  11130. # Handles the following format
  11131. # 21-Jun-2001 - register.com domain transfer email circa 2001
  11132. my ($day, $month, $year) = ($1,$2,$3);
  11133. $day = mysprintf( '%02d', $day);
  11134. $d = "$day-$month-$year 11:11:11 +0000";
  11135. last SWITCH ;
  11136. }
  11137. # unknown or unmatch => return same string
  11138. return($d);
  11139. }
  11140. $d = qq("$d") ;
  11141. return( $d ) ;
  11142. }
  11143. sub tests_good_date
  11144. {
  11145. note( 'Entering tests_good_date()' ) ;
  11146. ok(q{} eq good_date(), 'good_date no arg');
  11147. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('24-Aug-2010 16:00:00 +0200'), 'good_date internal 2digit zone');
  11148. ok('"24-Aug-2010 16:00:00 +0000"' eq good_date('24-Aug-2010 16:00:00'), 'good_date internal 2digit no zone');
  11149. ok('"01-Sep-2010 16:00:00 +0200"' eq good_date( '1-Sep-2010 16:00:00 +0200'), 'good_date internal SP 1digit');
  11150. ok('"24-Aug-2010 16:00:00 +0200"' eq good_date('Tue, 24 Aug 2010 16:00:00 +0200'), 'good_date header 2digit zone');
  11151. ok('"01-Sep-2010 16:00:00 +0000"' eq good_date('Wed, 1 Sep 2010 16:00:00'), 'good_date header SP 1digit zone');
  11152. 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');
  11153. 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');
  11154. ok('"06-Feb-2009 22:18:08 +0000"' eq good_date('02/06/09 22:18:08'), 'good_date header TemPageR');
  11155. 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');
  11156. 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');
  11157. 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');
  11158. 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');
  11159. ok('"24-Aug-2067 16:00:00 +0200"' eq good_date('Tue, 24 Aug 67 16:00:00 +0200'), 'good_date header 2digit year');
  11160. ok('"24-Aug-1977 16:00:00 +0200"' eq good_date('Tue, 24 Aug 77 16:00:00 +0200'), 'good_date header 2digit year');
  11161. ok('"24-Aug-1987 16:00:00 +0200"' eq good_date('Tue, 24 Aug 87 16:00:00 +0200'), 'good_date header 2digit year');
  11162. ok('"24-Aug-1997 16:00:00 +0200"' eq good_date('Tue, 24 Aug 97 16:00:00 +0200'), 'good_date header 2digit year');
  11163. ok('"24-Aug-2004 16:00:00 +0200"' eq good_date('Tue, 24 Aug 04 16:00:00 +0200'), 'good_date header 2digit year');
  11164. 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');
  11165. 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');
  11166. 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');
  11167. ok('"24-Aug-1997 05:06:02 +0200"' eq good_date('Tue, 24, Aug 1997 05:06:02 +0200'), 'good_date header extra commas');
  11168. ok('"01-Oct-2003 12:45:24 +0000"' eq good_date('Wednesday, 01 October 2003 12:45:24 CDT'), 'good_date header no abbrev');
  11169. ok('"11-Jan-2005 17:58:27 -0500"' eq good_date('Tue, 11 Jan 2005 17:58:27 -0500'), 'good_date extra white space');
  11170. ok('"18-Dec-2002 15:07:00 +0000"' eq good_date('Wednesday, December 18, 2002 03:07 PM'), 'good_date kbtoys.com orders');
  11171. ok('"16-Dec-2004 02:01:49 -0500"' eq good_date('Dec 16 2004 02:01:49 -0500'), 'good_date jr.com orders');
  11172. ok('"21-Jun-2001 11:11:11 +0000"' eq good_date('21-Jun-2001'), 'good_date register.com domain transfer');
  11173. 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)');
  11174. ok('"19-Sep-2015 16:11:07 +0000"' eq good_date('Date: 2015/09/19 16:11:07 '), 'good_date from RCS date' ) ;
  11175. note( 'Leaving tests_good_date()' ) ;
  11176. return ;
  11177. }
  11178. sub tests_list_keys_in_2_not_in_1
  11179. {
  11180. note( 'Entering tests_list_keys_in_2_not_in_1()' ) ;
  11181. my @list;
  11182. ok( ! list_keys_in_2_not_in_1( {}, {}), 'list_keys_in_2_not_in_1: {} {}');
  11183. ok( 0 == compare_lists( [], [ list_keys_in_2_not_in_1( {}, {} ) ] ), 'list_keys_in_2_not_in_1: {} {}');
  11184. 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}');
  11185. 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}');
  11186. 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}');
  11187. 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}');
  11188. 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}');
  11189. note( 'Leaving tests_list_keys_in_2_not_in_1()' ) ;
  11190. return ;
  11191. }
  11192. sub list_keys_in_2_not_in_1
  11193. {
  11194. my $hash_1_ref = shift;
  11195. my $hash_2_ref = shift;
  11196. my @list;
  11197. foreach my $key ( sort keys %{ $hash_2_ref } ) {
  11198. #$sync->{ debug } and print "$key\n" ;
  11199. if ( exists $hash_1_ref->{$key} )
  11200. {
  11201. next ;
  11202. }
  11203. #$sync->{ debug } and print "list_keys_in_2_not_in_1: $key\n" ;
  11204. push @list, $key ;
  11205. }
  11206. #$sync->{ debug } and print "@list\n" ;
  11207. return( @list ) ;
  11208. }
  11209. sub list_folders_in_2_not_in_1
  11210. {
  11211. my ( @h2_folders_not_in_h1, %h2_folders_not_in_h1 ) ;
  11212. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h1_folders_all, \%h2_folders_all ) ;
  11213. map { $h2_folders_not_in_h1{$_} = 1} @h2_folders_not_in_h1 ;
  11214. @h2_folders_not_in_h1 = list_keys_in_2_not_in_1( \%h2_folders_from_1_all, \%h2_folders_not_in_h1 ) ;
  11215. #$sync->{ debug } and print "h2_folders_not_in_h1: @h2_folders_not_in_h1\n" ;
  11216. return( reverse @h2_folders_not_in_h1 ) ;
  11217. }
  11218. sub tests_nb_messages_in_2_not_in_1
  11219. {
  11220. note( 'Entering tests_stats_across_folders()' ) ;
  11221. is( undef, nb_messages_in_2_not_in_1( ), 'nb_messages_in_2_not_in_1: no args => undef' ) ;
  11222. my $mysync->{ h1_folders_of_md5 }->{ 'some_id_01' }->{ 'some_folder_01' } = 1 ;
  11223. is( 0, nb_messages_in_2_not_in_1( $mysync ), 'nb_messages_in_2_not_in_1: no messages in 2 => 0' ) ;
  11224. $mysync->{ h1_folders_of_md5 }->{ 'some_id_in_1_and_2' }->{ 'some_folder_01' } = 2 ;
  11225. $mysync->{ h2_folders_of_md5 }->{ 'some_id_in_1_and_2' }->{ 'some_folder_02' } = 4 ;
  11226. is( 0, nb_messages_in_2_not_in_1( $mysync ), 'nb_messages_in_2_not_in_1: a common message => 0' ) ;
  11227. $mysync->{ h2_folders_of_md5 }->{ 'some_id_in_2_not_in_1' }->{ 'some_folder_02' } = 1 ;
  11228. 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' ) ;
  11229. $mysync->{ h2_folders_of_md5 }->{ 'some_other_id_in_2_not_in_1' }->{ 'some_folder_02' } = 3 ;
  11230. 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' ) ;
  11231. note( 'Leaving tests_stats_across_folders()' ) ;
  11232. return ;
  11233. }
  11234. sub nb_messages_in_2_not_in_1
  11235. {
  11236. my $mysync = shift ;
  11237. if ( not defined $mysync ) { return ; }
  11238. $mysync->{ nb_messages_in_2_not_in_1 } = scalar(
  11239. list_keys_in_2_not_in_1(
  11240. $mysync->{ h1_folders_of_md5 },
  11241. $mysync->{ h2_folders_of_md5 } ) ) ;
  11242. return $mysync->{ nb_messages_in_2_not_in_1 } ;
  11243. }
  11244. sub nb_messages_in_1_not_in_2
  11245. {
  11246. my $mysync = shift ;
  11247. if ( not defined $mysync ) { return ; }
  11248. $mysync->{ nb_messages_in_1_not_in_2 } = scalar(
  11249. list_keys_in_2_not_in_1(
  11250. $mysync->{ h2_folders_of_md5 },
  11251. $mysync->{ h1_folders_of_md5 } ) ) ;
  11252. return $mysync->{ nb_messages_in_1_not_in_2 } ;
  11253. }
  11254. sub comment_on_final_diff_in_1_not_in_2
  11255. {
  11256. my $mysync = shift ;
  11257. if ( not defined $mysync
  11258. or $mysync->{ justfolders }
  11259. or $mysync->{ useuid }
  11260. )
  11261. {
  11262. return ;
  11263. }
  11264. my $nb_identified_h1_messages = scalar( keys %{ $mysync->{ h1_folders_of_md5 } } ) ;
  11265. my $nb_identified_h2_messages = scalar( keys %{ $mysync->{ h2_folders_of_md5 } } ) ;
  11266. $mysync->{ debug } and myprint( "nb_keys h1_folders_of_md5 $nb_identified_h1_messages\n" ) ;
  11267. $mysync->{ debug } and myprint( "nb_keys h2_folders_of_md5 $nb_identified_h2_messages\n" ) ;
  11268. if ( 0 == $nb_identified_h1_messages ) { return ; }
  11269. # Calculate if not yet done
  11270. if ( not defined $mysync->{ nb_messages_in_1_not_in_2 } )
  11271. {
  11272. nb_messages_in_1_not_in_2( $mysync ) ;
  11273. }
  11274. if ( 0 == $mysync->{ nb_messages_in_1_not_in_2 } )
  11275. {
  11276. myprint( "The sync looks good, all ",
  11277. $nb_identified_h1_messages,
  11278. " identified messages in host1 are on host2.\n" ) ;
  11279. }
  11280. else
  11281. {
  11282. myprint( "The sync is not finished, there are ",
  11283. $mysync->{ nb_messages_in_1_not_in_2 },
  11284. " identified messages in host1 that are not on host2.\n" ) ;
  11285. }
  11286. if ( 1 <= $mysync->{ h1_nb_msg_noheader } )
  11287. {
  11288. myprint( "There are ",
  11289. $mysync->{ h1_nb_msg_noheader },
  11290. " unidentified messages (usually Sent or Draft messages).",
  11291. " To sync them add option --addheader\n" ) ;
  11292. }
  11293. else
  11294. {
  11295. myprint( "There is no unidentified message\n" ) ;
  11296. }
  11297. return ;
  11298. }
  11299. sub comment_on_final_diff_in_2_not_in_1
  11300. {
  11301. my $mysync = shift ;
  11302. if ( not defined $mysync
  11303. or $mysync->{ justfolders }
  11304. or $mysync->{ useuid }
  11305. )
  11306. {
  11307. return ;
  11308. }
  11309. my $nb_identified_h2_messages = scalar( keys %{ $mysync->{ h2_folders_of_md5 } } ) ;
  11310. # Calculate if not done yet
  11311. if ( not defined $mysync->{ nb_messages_in_2_not_in_1 } )
  11312. {
  11313. nb_messages_in_2_not_in_1( $mysync ) ;
  11314. }
  11315. if ( 0 == $mysync->{ nb_messages_in_2_not_in_1 } )
  11316. {
  11317. myprint( "The sync is strict, all ",
  11318. $nb_identified_h2_messages,
  11319. " identified messages in host2 are on host1.\n" ) ;
  11320. }
  11321. else
  11322. {
  11323. myprint( "The sync is not strict, there are ",
  11324. $mysync->{ nb_messages_in_2_not_in_1 },
  11325. " messages in host2 that are not on host1.",
  11326. " Use --delete2 to delete them and have a strict sync.",
  11327. " ($nb_identified_h2_messages identified messages in host2)\n" ) ;
  11328. }
  11329. return ;
  11330. }
  11331. sub tests_match
  11332. {
  11333. note( 'Entering tests_match()' ) ;
  11334. # undef serie
  11335. is( undef, match( ), 'match: no args => undef' ) ;
  11336. is( undef, match( 'lalala' ), 'match: one args => undef' ) ;
  11337. # This one gives 0 under a binary made by pp
  11338. # but 1 under "normal" Perl interpreter. So a PAR bug?
  11339. #is( 1, match( q{}, q{} ), 'match: q{} =~ q{} => 1' ) ;
  11340. is( 'lalala', match( 'lalala', 'lalala' ), 'match: lalala =~ lalala => lalala' ) ;
  11341. is( 'lalala', match( 'lalala', '^lalala' ), 'match: lalala =~ ^lalala => lalala' ) ;
  11342. is( 'lalala', match( 'lalala', 'lalala$' ), 'match: lalala =~ lalala$ => lalala' ) ;
  11343. is( 'lalala', match( 'lalala', '^lalala$' ), 'match: lalala =~ ^lalala$ => lalala' ) ;
  11344. is( '_lalala_', match( '_lalala_', 'lalala' ), 'match: _lalala_ =~ lalala => _lalala_' ) ;
  11345. is( 'lalala', match( 'lalala', '.*' ), 'match: lalala =~ .* => lalala' ) ;
  11346. is( 'lalala', match( 'lalala', '.' ), 'match: lalala =~ . => lalala' ) ;
  11347. is( '/lalala/', match( '/lalala/', '/lalala/' ), 'match: /lalala/ =~ /lalala/ => /lalala/' ) ;
  11348. is( 0, match( 'foo', 's/foo/bar/g' ), 'match: foo =~ s/foo/bar/g => 0' ) ;
  11349. 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' ) ;
  11350. is( 0, match( 'lalala', 'ooo' ), 'match: lalala =~ ooo => 0' ) ;
  11351. is( 0, match( 'lalala', 'lal_ala' ), 'match: lalala =~ lal_ala => 0' ) ;
  11352. is( 0, match( 'lalala', '\.' ), 'match: lalala =~ \. => 0' ) ;
  11353. is( 0, match( 'lalalaX', '^lalala$' ), 'match: lalalaX =~ ^lalala$ => 0' ) ;
  11354. is( 0, match( 'lalala', '/lalala/' ), 'match: lalala =~ /lalala/ => 0' ) ;
  11355. is( 'LALALA', match( 'LALALA', '(?i:lalala)' ), 'match: LALALA =~ (?i:lalala) => 1' ) ;
  11356. is( undef, match( 'LALALA', '(?{`ls /`})' ), 'match: LALALA =~ (?{`ls /`}) => undef' ) ;
  11357. is( undef, match( 'LALALA', '(?{print "CACA"})' ), 'match: LALALA =~ (?{print "CACA"}) => undef' ) ;
  11358. is( undef, match( 'CACA', '(??{print "CACA"})' ), 'match: CACA =~ (??{print "CACA"}) => undef' ) ;
  11359. note( 'Leaving tests_match()' ) ;
  11360. return ;
  11361. }
  11362. sub match
  11363. {
  11364. my( $var, $regex ) = @ARG ;
  11365. # undef cases
  11366. if ( ( ! defined $var ) or ( ! defined $regex ) ) { return ; }
  11367. # normal cases
  11368. if ( eval { $var =~ qr{$regex} } ) {
  11369. return $var ;
  11370. }elsif ( $EVAL_ERROR ) {
  11371. myprint( "Fatal regex $regex\n" ) ;
  11372. return ;
  11373. } else {
  11374. return 0 ;
  11375. }
  11376. return ;
  11377. }
  11378. sub tests_notmatch
  11379. {
  11380. note( 'Entering tests_notmatch()' ) ;
  11381. # undef serie
  11382. is( undef, notmatch( ), 'notmatch: no args => undef' ) ;
  11383. is( undef, notmatch( 'lalala' ), 'notmatch: one args => undef' ) ;
  11384. is( 1, notmatch( 'lalala', '/lalala/' ), 'notmatch: lalala !~ /lalala/ => 1' ) ;
  11385. is( 0, notmatch( '/lalala/', '/lalala/' ), 'notmatch: /lalala/ !~ /lalala/ => 0' ) ;
  11386. is( 1, notmatch( 'lalala', '/ooo/' ), 'notmatch: lalala !~ /ooo/ => 1' ) ;
  11387. # This one gives 1 under a binary made by pp
  11388. # but 0 under "normal" Perl interpreter. So a PAR bug, same in tests_match .
  11389. #is( 0, notmatch( q{}, q{} ), 'notmatch: q{} !~ q{} => 0' ) ;
  11390. is( 0, notmatch( 'lalala', 'lalala' ), 'notmatch: lalala !~ lalala => 0' ) ;
  11391. is( 0, notmatch( 'lalala', '^lalala' ), 'notmatch: lalala !~ ^lalala => 0' ) ;
  11392. is( 0, notmatch( 'lalala', 'lalala$' ), 'notmatch: lalala !~ lalala$ => 0' ) ;
  11393. is( 0, notmatch( 'lalala', '^lalala$' ), 'notmatch: lalala !~ ^lalala$ => 0' ) ;
  11394. is( 0, notmatch( '_lalala_', 'lalala' ), 'notmatch: _lalala_ !~ lalala => 0' ) ;
  11395. is( 0, notmatch( 'lalala', '.*' ), 'notmatch: lalala !~ .* => 0' ) ;
  11396. is( 0, notmatch( 'lalala', '.' ), 'notmatch: lalala !~ . => 0' ) ;
  11397. is( 1, notmatch( 'lalala', 'ooo' ), 'notmatch: does not match regex => 1' ) ;
  11398. is( 1, notmatch( 'lalala', 'lal_ala' ), 'notmatch: does not match regex => 1' ) ;
  11399. is( 1, notmatch( 'lalala', '\.' ), 'notmatch: matches regex => 0' ) ;
  11400. is( 1, notmatch( 'lalalaX', '^lalala$' ), 'notmatch: does not match regex => 1' ) ;
  11401. note( 'Leaving tests_notmatch()' ) ;
  11402. return ;
  11403. }
  11404. sub notmatch
  11405. {
  11406. my( $var, $regex ) = @ARG ;
  11407. # undef cases
  11408. if ( ( ! defined $var ) or ( ! defined $regex ) ) { return ; }
  11409. # normal cases
  11410. if ( eval { $var !~ $regex } ) {
  11411. return 1 ;
  11412. }elsif ( $EVAL_ERROR ) {
  11413. myprint( "Fatal regex $regex\n" ) ;
  11414. return ;
  11415. }else{
  11416. return 0 ;
  11417. }
  11418. return ;
  11419. }
  11420. sub delete_folders_in_2_not_in_1
  11421. {
  11422. foreach my $folder ( @h2_folders_not_in_1 ) {
  11423. if ( defined $delete2foldersonly and eval "\$folder !~ $delete2foldersonly" ) {
  11424. myprint( "Not deleting $folder because of --delete2foldersonly $delete2foldersonly\n" ) ;
  11425. next ;
  11426. }
  11427. if ( defined $delete2foldersbutnot and eval "\$folder =~ $delete2foldersbutnot" ) {
  11428. myprint( "Not deleting $folder because of --delete2foldersbutnot $delete2foldersbutnot\n" ) ;
  11429. next ;
  11430. }
  11431. my $res = $sync->{dry} ; # always success in dry mode!
  11432. $sync->{imap2}->unsubscribe( $folder ) if ( ! $sync->{dry} ) ;
  11433. $res = $sync->{imap2}->delete( $folder ) if ( ! $sync->{dry} ) ;
  11434. if ( $res ) {
  11435. myprint( "Deleted $folder", "$sync->{dry_message}", "\n" ) ;
  11436. }else{
  11437. myprint( "Deleting $folder failed", "\n" ) ;
  11438. }
  11439. }
  11440. return ;
  11441. }
  11442. sub delete_folder
  11443. {
  11444. my ( $mysync, $imap, $folder, $Side ) = @_ ;
  11445. if ( ! $mysync ) { return ; }
  11446. if ( ! $imap ) { return ; }
  11447. if ( ! $folder ) { return ; }
  11448. $Side ||= 'HostX' ;
  11449. my $res = $mysync->{dry} ; # always success in dry mode!
  11450. if ( ! $mysync->{dry} ) {
  11451. $imap->unsubscribe( $folder ) ;
  11452. $res = $imap->delete( $folder ) ;
  11453. }
  11454. if ( $res ) {
  11455. myprint( "$Side deleted $folder", $mysync->{dry_message}, "\n" ) ;
  11456. return 1 ;
  11457. }else{
  11458. myprint( "$Side deleting $folder failed", "\n" ) ;
  11459. return ;
  11460. }
  11461. }
  11462. sub delete1emptyfolders
  11463. {
  11464. my $mysync = shift ;
  11465. if ( ! $mysync ) { return ; } # abort if no parameter
  11466. if ( ! $mysync->{delete1emptyfolders} ) { return ; } # abort if --delete1emptyfolders off
  11467. my $imap = $mysync->{imap1} ;
  11468. if ( ! $imap ) { return ; } # abort if no imap
  11469. if ( $imap->IsUnconnected( ) ) { return ; } # abort if disconnected
  11470. my %folders_kept ;
  11471. myprint( qq{Host1 deleting empty folders\n} ) ;
  11472. foreach my $folder ( reverse sort @{ $mysync->{h1_folders_wanted} } ) {
  11473. my $parenthood = $imap->is_parent( $folder ) ;
  11474. if ( defined $parenthood and $parenthood ) {
  11475. myprint( "Host1: folder $folder has subfolders\n" ) ;
  11476. $folders_kept{ $folder }++ ;
  11477. next ;
  11478. }
  11479. my $nb_messages_select = examine_folder_and_count( $mysync, $imap, $folder, 'Host1' ) ;
  11480. if ( ! defined $nb_messages_select ) { next ; } # Select failed => Neither continue nor keep this folder }
  11481. my $nb_messages_search = scalar( @{ $imap->messages( ) } ) ;
  11482. if ( 0 != $nb_messages_select and 0 != $nb_messages_search ) {
  11483. myprint( "Host1: folder $folder has messages: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  11484. $folders_kept{ $folder }++ ;
  11485. next ;
  11486. }
  11487. if ( 0 != $nb_messages_select + $nb_messages_search ) {
  11488. myprint( "Host1: folder $folder odd messages count: $nb_messages_search (search) $nb_messages_select (select)\n" ) ;
  11489. $folders_kept{ $folder }++ ;
  11490. next ;
  11491. }
  11492. # Here we must have 0 messages by messages() aka "SEARCH ALL" and also "EXAMINE"
  11493. if ( uc $folder eq 'INBOX' ) {
  11494. myprint( "Host1: Not deleting $folder\n" ) ;
  11495. $folders_kept{ $folder }++ ;
  11496. next ;
  11497. }
  11498. myprint( "Host1: deleting empty folder $folder\n" ) ;
  11499. # can not delete a SELECTed or EXAMINEd folder so closing it
  11500. # could changed be SELECT INBOX
  11501. $imap->close( ) ; # close after examine does not expunge; anyway expunging an empty folder...
  11502. if ( delete_folder( $mysync, $imap, $folder, 'Host1' ) ) {
  11503. next ; # Deleted, good!
  11504. }else{
  11505. $folders_kept{ $folder }++ ;
  11506. next ; # Not deleted, bad!
  11507. }
  11508. }
  11509. remove_deleted_folders_from_wanted_list( $mysync, %folders_kept ) ;
  11510. myprint( qq{Host1 ended deleting empty folders\n} ) ;
  11511. return ;
  11512. }
  11513. sub remove_deleted_folders_from_wanted_list
  11514. {
  11515. my ( $mysync, %folders_kept ) = @ARG ;
  11516. my @h1_folders_wanted_init = @{ $mysync->{h1_folders_wanted} } ;
  11517. my @h1_folders_wanted_last ;
  11518. foreach my $folder ( @h1_folders_wanted_init ) {
  11519. if ( $folders_kept{ $folder } ) {
  11520. push @h1_folders_wanted_last, $folder ;
  11521. }
  11522. }
  11523. @{ $mysync->{h1_folders_wanted} } = @h1_folders_wanted_last ;
  11524. return ;
  11525. }
  11526. sub examine_folder_and_count
  11527. {
  11528. my ( $mysync, $imap, $folder, $Side ) = @_ ;
  11529. $Side ||= 'HostX' ;
  11530. if ( ! examine_folder( $mysync, $imap, $folder, $Side ) ) {
  11531. return ;
  11532. }
  11533. my $nb_messages_select = count_from_select( $imap->History ) ;
  11534. return $nb_messages_select ;
  11535. }
  11536. sub tests_delete1emptyfolders
  11537. {
  11538. note( 'Entering tests_delete1emptyfolders()' ) ;
  11539. is( undef, delete1emptyfolders( ), q{delete1emptyfolders: undef} ) ;
  11540. my $syncT ;
  11541. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef 2} ) ;
  11542. my $imapT ;
  11543. $syncT->{imap1} = $imapT ;
  11544. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: undef imap} ) ;
  11545. require_ok( "Test::MockObject" ) ;
  11546. $imapT = Test::MockObject->new( ) ;
  11547. $syncT->{imap1} = $imapT ;
  11548. $imapT->set_true( 'IsUnconnected' ) ;
  11549. is( undef, delete1emptyfolders( $syncT ), q{delete1emptyfolders: Unconnected imap} ) ;
  11550. # Now connected tests
  11551. $imapT->set_false( 'IsUnconnected' ) ;
  11552. $imapT->mock( 'LastError', sub { q{LastError mocked} } ) ;
  11553. $syncT->{delete1emptyfolders} = 0 ;
  11554. tests_delete1emptyfolders_unit(
  11555. $syncT,
  11556. [ qw{ INBOX DELME1 DELME2 } ],
  11557. [ qw{ INBOX DELME1 DELME2 } ],
  11558. q{tests_delete1emptyfolders: --delete1emptyfolders OFF}
  11559. ) ;
  11560. # All are parents => no deletion at all
  11561. $imapT->set_true( 'is_parent' ) ;
  11562. $syncT->{delete1emptyfolders} = 1 ;
  11563. tests_delete1emptyfolders_unit(
  11564. $syncT,
  11565. [ qw{ INBOX DELME1 DELME2 } ],
  11566. [ qw{ INBOX DELME1 DELME2 } ],
  11567. q{tests_delete1emptyfolders: --delete1emptyfolders ON}
  11568. ) ;
  11569. # No parents but examine false for all => skip all
  11570. $imapT->set_false( 'is_parent', 'examine' ) ;
  11571. tests_delete1emptyfolders_unit(
  11572. $syncT,
  11573. [ qw{ INBOX DELME1 DELME2 } ],
  11574. [ ],
  11575. q{tests_delete1emptyfolders: EXAMINE fails}
  11576. ) ;
  11577. # examine ok for all but History bad => skip all
  11578. $imapT->set_true( 'examine' ) ;
  11579. $imapT->mock( 'History', sub { ( q{History badly mocked} ) } ) ;
  11580. tests_delete1emptyfolders_unit(
  11581. $syncT,
  11582. [ qw{ INBOX DELME1 DELME2 } ],
  11583. [ ],
  11584. q{tests_delete1emptyfolders: examine ok but History badly mocked so count messages fails}
  11585. ) ;
  11586. # History good but some messages EXISTS == messages() => no deletion
  11587. $imapT->mock( 'History', sub { ( q{* 2 EXISTS} ) } ) ;
  11588. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  11589. tests_delete1emptyfolders_unit(
  11590. $syncT,
  11591. [ qw{ INBOX DELME1 DELME2 } ],
  11592. [ qw{ INBOX DELME1 DELME2 } ],
  11593. q{tests_delete1emptyfolders: History EXAMINE ok, several messages}
  11594. ) ;
  11595. # 0 EXISTS but != messages() => no deletion
  11596. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  11597. $imapT->mock( 'messages', sub { [ qw{ UID_1 UID_2 } ] } ) ;
  11598. tests_delete1emptyfolders_unit(
  11599. $syncT,
  11600. [ qw{ INBOX DELME1 DELME2 } ],
  11601. [ qw{ INBOX DELME1 DELME2 } ],
  11602. q{tests_delete1emptyfolders: 0 EXISTS but 2 by messages()}
  11603. ) ;
  11604. # 1 EXISTS but != 0 == messages() => no deletion
  11605. $imapT->mock( 'History', sub { ( q{* 1 EXISTS} ) } ) ;
  11606. $imapT->mock( 'messages', sub { [ ] } ) ;
  11607. tests_delete1emptyfolders_unit(
  11608. $syncT,
  11609. [ qw{ INBOX DELME1 DELME2 } ],
  11610. [ qw{ INBOX DELME1 DELME2 } ],
  11611. q{tests_delete1emptyfolders: 1 EXISTS but 0 by messages()}
  11612. ) ;
  11613. # 0 EXISTS and 0 == messages() => deletion except INBOX
  11614. $imapT->mock( 'History', sub { ( q{* 0 EXISTS} ) } ) ;
  11615. $imapT->mock( 'messages', sub { [ ] } ) ;
  11616. $imapT->set_true( qw{ delete close unsubscribe } ) ;
  11617. $syncT->{dry_message} = q{ (not really since in a mocked test)} ;
  11618. tests_delete1emptyfolders_unit(
  11619. $syncT,
  11620. [ qw{ INBOX DELME1 DELME2 } ],
  11621. [ qw{ INBOX } ],
  11622. q{tests_delete1emptyfolders: 0 EXISTS 0 by messages() delete folders, keep INBOX}
  11623. ) ;
  11624. note( 'Leaving tests_delete1emptyfolders()' ) ;
  11625. return ;
  11626. }
  11627. sub tests_delete1emptyfolders_unit
  11628. {
  11629. note( 'Entering tests_delete1emptyfolders_unit()' ) ;
  11630. my $syncT = shift ;
  11631. my $folders1wanted_init_ref = shift ;
  11632. my $folders1wanted_after_ref = shift ;
  11633. my $comment = shift || q{delete1emptyfolders:} ;
  11634. my @folders1wanted_init = @{ $folders1wanted_init_ref } ;
  11635. my @folders1wanted_after = @{ $folders1wanted_after_ref } ;
  11636. @{ $syncT->{h1_folders_wanted} } = @folders1wanted_init ;
  11637. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_init, qq{$comment, init check} ) ;
  11638. delete1emptyfolders( $syncT ) ;
  11639. is_deeply( $syncT->{h1_folders_wanted}, \@folders1wanted_after, qq{$comment, after check} ) ;
  11640. note( 'Leaving tests_delete1emptyfolders_unit()' ) ;
  11641. return ;
  11642. }
  11643. sub extract_header
  11644. {
  11645. my $string = shift ;
  11646. my ( $header ) = split /\n\n/x, $string ;
  11647. if ( ! $header ) { return( q{} ) ; }
  11648. #myprint( "[$header]\n" ) ;
  11649. return( $header ) ;
  11650. }
  11651. sub tests_extract_header
  11652. {
  11653. note( 'Entering tests_extract_header()' ) ;
  11654. my $h = <<'EOM';
  11655. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  11656. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  11657. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  11658. EOM
  11659. chomp $h ;
  11660. ok( $h eq extract_header(
  11661. <<'EOM'
  11662. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  11663. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  11664. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  11665. body
  11666. lalala
  11667. EOM
  11668. ), 'extract_header: 1') ;
  11669. note( 'Leaving tests_extract_header()' ) ;
  11670. return ;
  11671. }
  11672. sub decompose_header{
  11673. my $string = shift ;
  11674. # a hash, for a keyword header KEY value are list of strings [VAL1, VAL1_other, etc]
  11675. # Think of multiple "Received:" header lines.
  11676. my $header = { } ;
  11677. my ($key, $val ) ;
  11678. my @line = split /\n|\r\n/x, $string ;
  11679. foreach my $line ( @line ) {
  11680. #myprint( "DDD $line\n" ) ;
  11681. # End of header
  11682. last if ( $line =~ m{^$}xo ) ;
  11683. # Key: value
  11684. if ( $line =~ m/(^[^:]+):\s(.*)/xo ) {
  11685. $key = $1 ;
  11686. $val = $2 ;
  11687. $debugdev and myprint( "DDD KV [$key] [$val]\n" ) ;
  11688. push @{ $header->{ $key } }, $val ;
  11689. # blanc and value => value from previous line continues
  11690. }elsif( $line =~ m/^(\s+)(.*)/xo ) {
  11691. $val = $2 ;
  11692. $debugdev and myprint( "DDD V [$val]\n" ) ;
  11693. @{ $header->{ $key } }[ $LAST ] .= " $val" if $key ;
  11694. # dirty line?
  11695. }else{
  11696. next ;
  11697. }
  11698. }
  11699. #myprint( Data::Dumper->Dump( [ $header ] ) ) ;
  11700. return( $header ) ;
  11701. }
  11702. sub tests_decompose_header{
  11703. note( 'Entering tests_decompose_header()' ) ;
  11704. my $header_dec ;
  11705. $header_dec = decompose_header(
  11706. <<'EOH'
  11707. KEY_1: VAL_1
  11708. KEY_2: VAL_2
  11709. VAL_2_+
  11710. VAL_2_++
  11711. KEY_3: VAL_3
  11712. KEY_1: VAL_1_other
  11713. KEY_4: VAL_4
  11714. VAL_4_+
  11715. KEY_5 BLANC: VAL_5
  11716. KEY_6_BAD_BODY: VAL_6
  11717. EOH
  11718. ) ;
  11719. ok( 'VAL_3'
  11720. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: VAL_3' ) ;
  11721. ok( 'VAL_1'
  11722. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: VAL_1' ) ;
  11723. ok( 'VAL_1_other'
  11724. eq $header_dec->{ 'KEY_1' }[1], 'decompose_header: VAL_1_other' ) ;
  11725. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  11726. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: VAL_2 VAL_2_+ VAL_2_++' ) ;
  11727. ok( 'VAL_4 VAL_4_+'
  11728. eq $header_dec->{ 'KEY_4' }[0], 'decompose_header: VAL_4 VAL_4_+' ) ;
  11729. ok( ' VAL_5'
  11730. eq $header_dec->{ 'KEY_5 BLANC' }[0], 'decompose_header: KEY_5 BLANC' ) ;
  11731. ok( not( defined $header_dec->{ 'KEY_6_BAD_BODY' }[0] ), 'decompose_header: KEY_6_BAD_BODY' ) ;
  11732. $header_dec = decompose_header(
  11733. <<'EOH'
  11734. Message-Id: <20100428101817.A66CB162474E@plume.est.belle>
  11735. Date: Wed, 28 Apr 2010 12:18:17 +0200 (CEST)
  11736. From: gilles@louloutte.dyndns.org (Gilles LAMIRAL)
  11737. EOH
  11738. ) ;
  11739. ok( '<20100428101817.A66CB162474E@plume.est.belle>'
  11740. eq $header_dec->{ 'Message-Id' }[0], 'decompose_header: 1' ) ;
  11741. $header_dec = decompose_header(
  11742. <<'EOH'
  11743. Return-Path: <gilles@louloutte.dyndns.org>
  11744. Received: by plume.est.belle (Postfix, from userid 1000)
  11745. id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)
  11746. Subject: test:eekahceishukohpe
  11747. EOH
  11748. ) ;
  11749. ok(
  11750. 'by plume.est.belle (Postfix, from userid 1000) id 120A71624742; Wed, 28 Apr 2010 01:46:40 +0200 (CEST)'
  11751. eq $header_dec->{ 'Received' }[0], 'decompose_header: 2' ) ;
  11752. $header_dec = decompose_header(
  11753. <<'EOH'
  11754. Received: from plume (localhost [127.0.0.1])
  11755. by plume.est.belle (Postfix) with ESMTP id C6EB73F6C9
  11756. for <gilles@localhost>; Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  11757. Received: from plume [192.168.68.7]
  11758. by plume with POP3 (fetchmail-6.3.6)
  11759. for <gilles@localhost> (single-drop); Mon, 26 Nov 2007 10:39:06 +0100 (CET)
  11760. EOH
  11761. ) ;
  11762. ok(
  11763. '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)'
  11764. eq $header_dec->{ 'Received' }[0], 'decompose_header: 3' ) ;
  11765. ok(
  11766. '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)'
  11767. eq $header_dec->{ 'Received' }[1], 'decompose_header: 3' ) ;
  11768. # Bad header beginning with a blank character
  11769. $header_dec = decompose_header(
  11770. <<'EOH'
  11771. KEY_1: VAL_1
  11772. KEY_2: VAL_2
  11773. VAL_2_+
  11774. VAL_2_++
  11775. KEY_3: VAL_3
  11776. KEY_1: VAL_1_other
  11777. EOH
  11778. ) ;
  11779. ok( 'VAL_3'
  11780. eq $header_dec->{ 'KEY_3' }[0], 'decompose_header: Bad header VAL_3' ) ;
  11781. ok( 'VAL_1_other'
  11782. eq $header_dec->{ 'KEY_1' }[0], 'decompose_header: Bad header VAL_1_other' ) ;
  11783. ok( 'VAL_2 VAL_2_+ VAL_2_++'
  11784. eq $header_dec->{ 'KEY_2' }[0], 'decompose_header: Bad header VAL_2 VAL_2_+ VAL_2_++' ) ;
  11785. note( 'Leaving tests_decompose_header()' ) ;
  11786. return ;
  11787. }
  11788. sub tests_epoch
  11789. {
  11790. note( 'Entering tests_epoch()' ) ;
  11791. ok( '1282658400' eq epoch( '24-Aug-2010 16:00:00 +0200' ), 'epoch 24-Aug-2010 16:00:00 +0200 -> 1282658400' ) ;
  11792. ok( '1282658400' eq epoch( '24-Aug-2010 14:00:00 +0000' ), 'epoch 24-Aug-2010 14:00:00 +0000 -> 1282658400' ) ;
  11793. ok( '1282658400' eq epoch( '24-Aug-2010 12:00:00 -0200' ), 'epoch 24-Aug-2010 12:00:00 -0200 -> 1282658400' ) ;
  11794. ok( '1282658400' eq epoch( '24-Aug-2010 16:01:00 +0201' ), 'epoch 24-Aug-2010 16:01:00 +0201 -> 1282658400' ) ;
  11795. ok( '1282658400' eq epoch( '24-Aug-2010 14:01:00 +0001' ), 'epoch 24-Aug-2010 14:01:00 +0001 -> 1282658400' ) ;
  11796. ok( '1280671200' eq epoch( '1-Aug-2010 16:00:00 +0200' ), 'epoch 1-Aug-2010 16:00:00 +0200 -> 1280671200' ) ;
  11797. ok( '1280671200' eq epoch( '1-Aug-2010 14:00:00 +0000' ), 'epoch 1-Aug-2010 14:00:00 +0000 -> 1280671200' ) ;
  11798. ok( '1280671200' eq epoch( '1-Aug-2010 12:00:00 -0200' ), 'epoch 1-Aug-2010 12:00:00 -0200 -> 1280671200' ) ;
  11799. ok( '1280671200' eq epoch( '1-Aug-2010 16:01:00 +0201' ), 'epoch 1-Aug-2010 16:01:00 +0201 -> 1280671200' ) ;
  11800. ok( '1280671200' eq epoch( '1-Aug-2010 14:01:00 +0001' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  11801. is( '1280671200', epoch( '1-Aug-2010 14:01:00 +0001' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  11802. is( '946684800', epoch( '00-Jan-0000 00:00:00 +0000' ), 'epoch 1-Aug-2010 14:01:00 +0001 -> 1280671200' ) ;
  11803. note( 'Leaving tests_epoch()' ) ;
  11804. return ;
  11805. }
  11806. sub epoch
  11807. {
  11808. # incoming format:
  11809. # internal date 24-Aug-2010 16:00:00 +0200
  11810. # outgoing format: epoch
  11811. my $d = shift ;
  11812. return(q{}) if not defined $d;
  11813. my ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m ) ;
  11814. my $time ;
  11815. 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 ) {
  11816. #myprint( "internal: [$1][$2][$3][$4][$5][$6][$7][$8][$9]\n" ) ;
  11817. ( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )
  11818. = ( $1, $2, $3, $4, $5, $6, $7, $8, $9 ) ;
  11819. #myprint( "( $mday, $month, $year, $hour, $min, $sec, $sign, $zone_h, $zone_m )\n" ) ;
  11820. $sign = +1 if ( '+' eq $sign ) ;
  11821. $sign = $MINUS_ONE if ( '-' eq $sign ) ;
  11822. if ( 0 == $mday ) {
  11823. myprint( "buggy day in $d. Fixed to 01\n" ) ;
  11824. $mday = '01' ;
  11825. }
  11826. $time = timegm( $sec, $min, $hour, $mday, $month_abrev{$month}, $year )
  11827. - $sign * ( 3600 * $zone_h + 60 * $zone_m ) ;
  11828. #myprint( "$time ", scalar localtime($time), "\n");
  11829. }
  11830. return( $time ) ;
  11831. }
  11832. sub tests_add_header
  11833. {
  11834. note( 'Entering tests_add_header()' ) ;
  11835. ok( 'Message-Id: <mistake@imapsync>' eq add_header(), 'add_header no arg' ) ;
  11836. ok( 'Message-Id: <123456789@imapsync>' eq add_header( '123456789' ), 'add_header 123456789' ) ;
  11837. note( 'Leaving tests_add_header()' ) ;
  11838. return ;
  11839. }
  11840. sub add_header
  11841. {
  11842. my $header_uid = shift || 'mistake' ;
  11843. my $header_Message_Id = 'Message-Id: <' . $header_uid . '@imapsync>' ;
  11844. return( $header_Message_Id ) ;
  11845. }
  11846. sub tests_max_line_length
  11847. {
  11848. note( 'Entering tests_max_line_length()' ) ;
  11849. ok( 0 == max_line_length( q{} ), 'max_line_length: 0 == null string' ) ;
  11850. ok( 1 == max_line_length( "\n" ), 'max_line_length: 1 == \n' ) ;
  11851. ok( 1 == max_line_length( "\n\n" ), 'max_line_length: 1 == \n\n' ) ;
  11852. ok( 1 == max_line_length( "\n" x 500 ), 'max_line_length: 1 == 500 \n' ) ;
  11853. ok( 1 == max_line_length( 'a' ), 'max_line_length: 1 == a' ) ;
  11854. ok( 2 == max_line_length( "a\na" ), 'max_line_length: 2 == a\na' ) ;
  11855. ok( 2 == max_line_length( "a\na\n" ), 'max_line_length: 2 == a\na\n' ) ;
  11856. ok( 3 == max_line_length( "a\nab\n" ), 'max_line_length: 3 == a\nab\n' ) ;
  11857. ok( 3 == max_line_length( "a\nab\n" x 1_000 ), 'max_line_length: 3 == 1_000 a\nab\n' ) ;
  11858. ok( 3 == max_line_length( "a\nab\nabc" ), 'max_line_length: 3 == a\nab\nabc' ) ;
  11859. ok( 4 == max_line_length( "a\nab\nabc\n" ), 'max_line_length: 4 == a\nab\nabc\n' ) ;
  11860. ok( 5 == max_line_length( "a\nabcd\nabc\n" ), 'max_line_length: 5 == a\nabcd\nabc\n' ) ;
  11861. 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' ) ;
  11862. note( 'Leaving tests_max_line_length()' ) ;
  11863. return ;
  11864. }
  11865. sub max_line_length
  11866. {
  11867. my $string = shift ;
  11868. my $max = 0 ;
  11869. while ( $string =~ m/([^\n]*\n?)/msxg ) {
  11870. $max = max( $max, length $1 ) ;
  11871. }
  11872. return( $max ) ;
  11873. }
  11874. sub tests_setlogfile
  11875. {
  11876. note( 'Entering tests_setlogfile()' ) ;
  11877. my $mysync = {} ;
  11878. $mysync->{logdir} = 'vallogdir' ;
  11879. $mysync->{logfile} = 'vallogfile.txt' ;
  11880. is( 'vallogdir/vallogfile.txt', setlogfile( $mysync ),
  11881. 'setlogfile: logdir vallogdir, logfile vallogfile.txt, vallogdir/vallogfile.txt' ) ;
  11882. SKIP: {
  11883. skip( 'Too hard to have a well known timezone on Windows', 9 ) if ( 'MSWin32' eq $OSNAME ) ;
  11884. local $ENV{TZ} = 'GMT' ;
  11885. $mysync = {
  11886. timestart => 2,
  11887. } ;
  11888. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000__.txt", setlogfile( $mysync ),
  11889. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000__.txt" ) ;
  11890. $mysync = {
  11891. timestart => 2,
  11892. user1 => 'user1',
  11893. user2 => 'user2',
  11894. abort => 1,
  11895. } ;
  11896. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_abort.txt", setlogfile( $mysync ),
  11897. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_abort.txt" ) ;
  11898. $mysync = {
  11899. timestart => 2,
  11900. user1 => 'user1',
  11901. user2 => 'user2',
  11902. remote => 'zzz',
  11903. } ;
  11904. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote.txt", setlogfile( $mysync ),
  11905. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote.txt" ) ;
  11906. $mysync = {
  11907. timestart => 2,
  11908. user1 => 'user1',
  11909. user2 => 'user2',
  11910. remote => 'zzz',
  11911. abort => 1,
  11912. } ;
  11913. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote_abort.txt", setlogfile( $mysync ),
  11914. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2_remote_abort.txt" ) ;
  11915. $mysync = {
  11916. timestart => 2,
  11917. user1 => 'user1',
  11918. user2 => 'user2',
  11919. } ;
  11920. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt", setlogfile( $mysync ),
  11921. "setlogfile: default is like $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt" ) ;
  11922. $mysync->{logdir} = undef ;
  11923. $mysync->{logfile} = undef ;
  11924. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt", setlogfile( $mysync ),
  11925. "setlogfile: logdir undef, $DEFAULT_LOGDIR/1970_01_01_00_00_02_000_user1_user2.txt" ) ;
  11926. $mysync->{logdir} = q{} ;
  11927. $mysync->{logfile} = undef ;
  11928. is( '1970_01_01_00_00_02_000_user1_user2.txt', setlogfile( $mysync ),
  11929. 'setlogfile: logdir empty, 1970_01_01_00_00_02_000_user1_user2.txt' ) ;
  11930. $mysync->{logdir} = 'vallogdir' ;
  11931. $mysync->{logfile} = undef ;
  11932. is( 'vallogdir/1970_01_01_00_00_02_000_user1_user2.txt', setlogfile( $mysync ),
  11933. 'setlogfile: logdir vallogdir, vallogdir/1970_01_01_00_00_02_000_user1_user2.txt' ) ;
  11934. $mysync = {
  11935. user1 => 'us/er1a*|?:"<>b',
  11936. user2 => 'u/ser2a*|?:"<>b',
  11937. } ;
  11938. is( "$DEFAULT_LOGDIR/1970_01_01_00_00_00_000_us_er1a_______b_u_ser2a_______b.txt", setlogfile( $mysync ),
  11939. "setlogfile: logdir undef, $DEFAULT_LOGDIR/1970_01_01_00_00_00_000_us_er1a_______b_u_ser2a_______b.txt" ) ;
  11940. } ;
  11941. note( 'Leaving tests_setlogfile()' ) ;
  11942. return ;
  11943. }
  11944. sub setlogfile
  11945. {
  11946. my( $mysync ) = shift ;
  11947. # When aborting another process the log file name finishes with "_abort.txt"
  11948. my $abort_suffix = ( $mysync->{abort} ) ? '_abort' : q{} ;
  11949. # When acting as a proxy the log file name finishes with "_remote.txt"
  11950. # proxy mode is not done yet
  11951. my $remote_suffix = ( $mysync->{remote} ) ? '_remote' : q{} ;
  11952. my $suffix = (
  11953. filter_forbidden_characters( slash_to_underscore( $mysync->{user1} ) ) || q{} )
  11954. . '_'
  11955. . ( filter_forbidden_characters( slash_to_underscore( $mysync->{user2} ) ) || q{} )
  11956. . $remote_suffix . $abort_suffix ;
  11957. $mysync->{logdir} = defined $mysync->{logdir} ? $mysync->{logdir} : $DEFAULT_LOGDIR ;
  11958. $mysync->{logfile} = defined $mysync->{logfile}
  11959. ? "$mysync->{logdir}/$mysync->{logfile}"
  11960. : logfile( $mysync->{timestart}, $suffix, $mysync->{logdir} ) ;
  11961. return( $mysync->{logfile} ) ;
  11962. }
  11963. sub tests_logfile
  11964. {
  11965. note( 'Entering tests_logfile()' ) ;
  11966. SKIP: {
  11967. # Too hard to have a well known timezone on Windows
  11968. skip( 'Too hard to have a well known timezone on Windows', 10 ) if ( 'MSWin32' eq $OSNAME ) ;
  11969. local $ENV{TZ} = 'GMT' ;
  11970. { POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  11971. is( '1970_01_01_00_00_00_000.txt', logfile( ), 'logfile: no args => 1970_01_01_00_00_00.txt' ) ;
  11972. is( '1970_01_01_00_00_00_000.txt', logfile( 0 ), 'logfile: 0 => 1970_01_01_00_00_00.txt' ) ;
  11973. is( '1970_01_01_00_01_01_000.txt', logfile( 61 ), 'logfile: 0 => 1970_01_01_00_01_01.txt' ) ;
  11974. is( '1970_01_01_00_01_01_234.txt', logfile( 61.234 ), 'logfile: 0 => 1970_01_01_00_01_01.txt' ) ;
  11975. 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' ) ;
  11976. 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' ) ;
  11977. 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' ) ;
  11978. 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' ) ;
  11979. is( '2010_08_24_14_01_01_234_poup.txt', logfile( 1_282_658_461.2347, 'poup' ),
  11980. 'logfile: 1_282_658_461.2347 poup => 2010_08_24_14_01_01_234_poup.txt' ) ;
  11981. is( 'dirdir/2010_08_24_14_01_01_234_poup.txt', logfile( 1_282_658_461.2347, 'poup', 'dirdir' ),
  11982. 'logfile: 1_282_658_461.2347 poup dirdir => dirdir/2010_08_24_14_01_01_234_poup.txt' ) ;
  11983. }
  11984. POSIX::tzset unless ('MSWin32' eq $OSNAME) ;
  11985. } ;
  11986. note( 'Leaving tests_logfile()' ) ;
  11987. return ;
  11988. }
  11989. sub logfile
  11990. {
  11991. my ( $time, $suffix, $dir ) = @_ ;
  11992. $time ||= 0 ;
  11993. $suffix ||= q{} ;
  11994. $suffix =~ tr/ //ds ;
  11995. my $sep_suffix = ( $suffix ) ? '_' : q{} ;
  11996. $dir ||= q{} ;
  11997. my $sep_dir = ( $dir ) ? '/' : q{} ;
  11998. my $date_str = POSIX::strftime( '%Y_%m_%d_%H_%M_%S', localtime $time ) ;
  11999. # Because of ab tests or web accesses, more than one sync withing one second is possible
  12000. # so we add also milliseconds
  12001. $date_str .= sprintf "_%03d", ($time - int( $time ) ) * 1000 ; # without rounding
  12002. my $logfile = "${dir}${sep_dir}${date_str}${sep_suffix}${suffix}.txt" ;
  12003. return( $logfile ) ;
  12004. }
  12005. sub tests_slash_to_underscore
  12006. {
  12007. note( 'Entering tests_slash_to_underscore()' ) ;
  12008. is( undef, slash_to_underscore( ), 'slash_to_underscore: no parameters => undef' ) ;
  12009. is( '_', slash_to_underscore( '/' ), 'slash_to_underscore: / => _' ) ;
  12010. is( '_abc_def_', slash_to_underscore( '/abc/def/' ), 'slash_to_underscore: /abc/def/ => _abc_def_' ) ;
  12011. note( 'Leaving tests_slash_to_underscore()' ) ;
  12012. return ;
  12013. }
  12014. sub slash_to_underscore
  12015. {
  12016. my $string = shift ;
  12017. if ( ! defined $string ) { return ; }
  12018. $string =~ tr{/}{_} ;
  12019. return( $string ) ;
  12020. }
  12021. sub tests_million_folders_baby_2
  12022. {
  12023. note( 'Entering tests_million_folders_baby_2()' ) ;
  12024. my %long ;
  12025. @long{ 1 .. 900_000 } = (1) x 900_000 ;
  12026. #myprint( %long, "\n" ) ;
  12027. my $pasglop = 0 ;
  12028. foreach my $elem ( 1 .. 900_000 ) {
  12029. #$debug and myprint( "$elem " ) ;
  12030. if ( not exists $long{ $elem } ) {
  12031. $pasglop++ ;
  12032. }
  12033. }
  12034. ok( 0 == $pasglop, 'tests_million_folders_baby_2: search among 900_000' ) ;
  12035. # myprint( "$pasglop\n" ) ;
  12036. note( 'Leaving tests_million_folders_baby_2()' ) ;
  12037. return ;
  12038. }
  12039. sub tests_always_fail
  12040. {
  12041. note( 'Entering tests_always_fail()' ) ;
  12042. is( 0, 1, 'always_fail: 0 is 1' ) ;
  12043. note( 'Leaving tests_always_fail()' ) ;
  12044. return ;
  12045. }
  12046. sub tests_logfileprepa
  12047. {
  12048. note( 'Entering tests_logfileprepa()' ) ;
  12049. is( undef, logfileprepa( ), 'logfileprepa: no args => undef' ) ;
  12050. my $logfile = 'W/tmp/tests/tests_logfileprepa.txt' ;
  12051. is( 1, logfileprepa( $logfile ), 'logfileprepa: W/tmp/tests/tests_logfileprepa.txt => 1' ) ;
  12052. note( 'Leaving tests_logfileprepa()' ) ;
  12053. return ;
  12054. }
  12055. sub logfileprepa
  12056. {
  12057. my $logfile = shift ;
  12058. if ( ! defined( $logfile ) )
  12059. {
  12060. return ;
  12061. }else
  12062. {
  12063. #myprint( "[$logfile]\n" ) ;
  12064. my $dirname = dirname( $logfile ) ;
  12065. do_valid_directory( $dirname ) || return( 0 ) ;
  12066. return( 1 ) ;
  12067. }
  12068. }
  12069. sub tests_teelaunch
  12070. {
  12071. note( 'Entering tests_teelaunch()' ) ;
  12072. is( undef, teelaunch( ), 'teelaunch: no args => undef' ) ;
  12073. my $mysync = {} ;
  12074. is( undef, teelaunch( $mysync ), 'teelaunch: arg empty {} => undef' ) ;
  12075. $mysync->{logfile} = q{} ;
  12076. is( undef, teelaunch( $mysync ), 'teelaunch: logfile empty string => undef' ) ;
  12077. $mysync->{logfile} = 'W/tmp/tests/tests_teelaunch.txt' ;
  12078. isa_ok( my $tee = teelaunch( $mysync ), 'IO::Tee' , 'teelaunch: logfile W/tmp/tests/tests_teelaunch.txt' ) ;
  12079. is( 1, print( $tee "Hi!\n" ), 'teelaunch: write Hi!') ;
  12080. is( "Hi!\n", file_to_string( 'W/tmp/tests/tests_teelaunch.txt' ), 'teelaunch: reading W/tmp/tests/tests_teelaunch.txt is Hi!\n' ) ;
  12081. is( 1, print( $tee "Hoo\n" ), 'teelaunch: write Hoo') ;
  12082. 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' ) ;
  12083. note( 'Leaving tests_teelaunch()' ) ;
  12084. return ;
  12085. }
  12086. sub teelaunch
  12087. {
  12088. my $mysync = shift ;
  12089. if ( ! defined( $mysync ) )
  12090. {
  12091. return ;
  12092. }
  12093. my $logfile = $mysync->{logfile} ;
  12094. if ( ! $logfile )
  12095. {
  12096. return ;
  12097. }
  12098. logfileprepa( $logfile ) || croak "Error no valid directory to write log file $logfile : $OS_ERROR" ;
  12099. # This is a log file opened during the whole sync
  12100. ## no critic (InputOutput::RequireBriefOpen)
  12101. open my $logfile_handle, '>', $logfile
  12102. or croak( "Can not open $logfile for write: $OS_ERROR" ) ;
  12103. binmode $logfile_handle, ":encoding(UTF-8)" ;
  12104. my $tee = IO::Tee->new( $logfile_handle, \*STDOUT ) ;
  12105. $tee->autoflush( 1 ) ;
  12106. $mysync->{logfile_handle} = $logfile_handle ;
  12107. $mysync->{tee} = $tee ;
  12108. return $tee ;
  12109. }
  12110. sub getpwuid_any_os
  12111. {
  12112. my $uid = shift ;
  12113. return( scalar getlogin ) if ( 'MSWin32' eq $OSNAME ) ; # Windows system
  12114. return( scalar getpwuid $uid ) ; # Unix system
  12115. }
  12116. sub simulong
  12117. {
  12118. my $max_seconds = shift ;
  12119. my $division = 5 ;
  12120. my $last_count = $division * $max_seconds ;
  12121. foreach my $i ( 1 .. ( $last_count ) ) {
  12122. myprint( "Are you still here ETA: " . ($last_count - $i) . "/$last_count msgs left\n" ) ;
  12123. #myprint( "Are you still here ETA: " . ($last_count - $i) . "/$last_count msgs left\n" . ( "Ah" x 40 . "\n") x 4000 ) ;
  12124. sleep( 1 / $division ) ;
  12125. }
  12126. return ;
  12127. }
  12128. sub printenv
  12129. {
  12130. myprint( "Environment variables listing:\n",
  12131. ( map { "$_ => $ENV{$_}\n" } sort keys %ENV),
  12132. "Environment variables listing end\n" ) ;
  12133. return ;
  12134. }
  12135. sub testsexit
  12136. {
  12137. my $mysync = shift ;
  12138. if ( ! ( $mysync->{ tests } or $mysync->{ testsdebug } or $mysync->{ testsunit } ) ) {
  12139. return ;
  12140. }
  12141. my $test_builder = Test::More->builder ;
  12142. tests( $mysync ) ;
  12143. testsdebug( $mysync ) ;
  12144. testunitsession( $mysync ) ;
  12145. my @summary = $test_builder->summary() ;
  12146. my @details = $test_builder->details() ;
  12147. my $nb_tests_run = scalar( @summary ) ;
  12148. my $nb_tests_expected = $test_builder->expected_tests() ;
  12149. my $nb_tests_failed = count_0s( @summary ) ;
  12150. my $tests_failed = report_failures( @details ) ;
  12151. if ( $nb_tests_failed or ( $nb_tests_run != $nb_tests_expected ) ) {
  12152. #$test_builder->reset( ) ;
  12153. myprint( "Summary of tests: failed $nb_tests_failed tests, run $nb_tests_run tests, expected to run $nb_tests_expected tests.\n",
  12154. "List of failed tests:\n", $tests_failed ) ;
  12155. exit $EXIT_TESTS_FAILED ;
  12156. }
  12157. cleanup_mess_from_tests( ) ;
  12158. # Cover is larger with --tests --testslive
  12159. if ( ! $mysync->{ testslive } )
  12160. {
  12161. exit ;
  12162. }
  12163. return ;
  12164. }
  12165. sub cleanup_mess_from_tests
  12166. {
  12167. undef @pipemess ;
  12168. return ;
  12169. }
  12170. sub after_get_options
  12171. {
  12172. my $mysync = shift ;
  12173. my $numopt = shift ;
  12174. # exit with --help option or no option at all
  12175. $mysync->{ debug } and myprint( "numopt:$numopt\n" ) ;
  12176. if ( $help or not $numopt ) {
  12177. myprint( usage( $mysync ) ) ;
  12178. exit ;
  12179. }
  12180. return ;
  12181. }
  12182. sub tests_remove_edging_blanks
  12183. {
  12184. note( 'Entering tests_remove_edging_blanks()' ) ;
  12185. is( undef, remove_edging_blanks( ), 'remove_edging_blanks: no args => undef' ) ;
  12186. is( 'abcd', remove_edging_blanks( 'abcd' ), 'remove_edging_blanks: abcd => abcd' ) ;
  12187. is( 'ab cd', remove_edging_blanks( ' ab cd ' ), 'remove_edging_blanks: " ab cd " => "ab cd"' ) ;
  12188. note( 'Leaving tests_remove_edging_blanks()' ) ;
  12189. return ;
  12190. }
  12191. sub remove_edging_blanks
  12192. {
  12193. my $string = shift ;
  12194. if ( ! defined $string )
  12195. {
  12196. return ;
  12197. }
  12198. $string =~ s,^ +| +$,,g ;
  12199. return $string ;
  12200. }
  12201. sub tests_sanitize
  12202. {
  12203. note( 'Entering tests_remove_edging_blanks()' ) ;
  12204. is( undef, sanitize( ), 'sanitize: no args => undef' ) ;
  12205. my $mysync = {} ;
  12206. $mysync->{ host1 } = ' example.com ' ;
  12207. $mysync->{ user1 } = ' to to ' ;
  12208. $mysync->{ password1 } = ' sex is good! ' ;
  12209. is( undef, sanitize( $mysync ), 'sanitize: => undef' ) ;
  12210. is( 'example.com', $mysync->{ host1 }, 'sanitize: host1 " example.com " => "example.com"' ) ;
  12211. is( 'to to', $mysync->{ user1 }, 'sanitize: user1 " to to " => "to to"' ) ;
  12212. is( 'sex is good!', $mysync->{ password1 }, 'sanitize: password1 " sex is good! " => "sex is good!"' ) ;
  12213. note( 'Leaving tests_remove_edging_blanks()' ) ;
  12214. return ;
  12215. }
  12216. sub sanitize
  12217. {
  12218. my $mysync = shift ;
  12219. if ( ! defined $mysync )
  12220. {
  12221. return ;
  12222. }
  12223. foreach my $parameter ( qw( host1 host2 user1 user2 password1 password2 ) )
  12224. {
  12225. $mysync->{ $parameter } = remove_edging_blanks( $mysync->{ $parameter } ) ;
  12226. }
  12227. return ;
  12228. }
  12229. sub easyany
  12230. {
  12231. my $mysync = shift ;
  12232. # Gmail
  12233. if ( $mysync->{gmail1} and $mysync->{gmail2} ) {
  12234. $mysync->{ debug } and myprint( "gmail1 gmail2\n") ;
  12235. gmail12( $mysync ) ;
  12236. return ;
  12237. }
  12238. if ( $mysync->{gmail1} ) {
  12239. $mysync->{ debug } and myprint( "gmail1\n" ) ;
  12240. gmail1( $mysync ) ;
  12241. }
  12242. if ( $mysync->{gmail2} ) {
  12243. $mysync->{ debug } and myprint( "gmail2\n" ) ;
  12244. gmail2( $mysync ) ;
  12245. }
  12246. # Office 365
  12247. if ( $mysync->{office1} ) {
  12248. office1( $mysync ) ;
  12249. }
  12250. if ( $mysync->{office2} ) {
  12251. office2( $mysync ) ;
  12252. }
  12253. # Exchange
  12254. if ( $mysync->{exchange1} ) {
  12255. exchange1( $mysync ) ;
  12256. }
  12257. if ( $mysync->{exchange2} ) {
  12258. exchange2( $mysync ) ;
  12259. }
  12260. # Domino
  12261. if ( $mysync->{domino1} ) {
  12262. domino1( $mysync ) ;
  12263. }
  12264. if ( $mysync->{domino2} ) {
  12265. domino2( $mysync ) ;
  12266. }
  12267. return ;
  12268. }
  12269. # From and for https://imapsync.lamiral.info/FAQ.d/FAQ.Gmail.txt
  12270. sub gmail12
  12271. {
  12272. my $mysync = shift ;
  12273. # Gmail at host1 and host2
  12274. $mysync->{host1} ||= 'imap.gmail.com' ;
  12275. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  12276. $mysync->{host2} ||= 'imap.gmail.com' ;
  12277. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  12278. $mysync->{maxbytespersecond} ||= 20_000 ; # should be 10_000 when computed from Gmail documentation
  12279. $mysync->{maxbytesafter} ||= 1_000_000_000 ;
  12280. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  12281. $mysync->{maxsleep} = ( defined $mysync->{maxsleep} ) ? $mysync->{maxsleep} : $MAX_SLEEP ; ;
  12282. $skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 0 ;
  12283. $mysync->{ synclabels } = ( defined $mysync->{ synclabels } ) ? $mysync->{ synclabels } : 1 ;
  12284. $mysync->{ resynclabels } = ( defined $mysync->{ resynclabels } ) ? $mysync->{ resynclabels } : 1 ;
  12285. push @exclude, '\[Gmail\]$' ;
  12286. push @folderlast, '[Gmail]/All Mail' ;
  12287. return ;
  12288. }
  12289. sub gmail1
  12290. {
  12291. my $mysync = shift ;
  12292. # Gmail at host2
  12293. $mysync->{host1} ||= 'imap.gmail.com' ;
  12294. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  12295. $mysync->{maxbytespersecond} ||= 40_000 ; # should be 20_000 computed from by Gmail documentation
  12296. $mysync->{maxbytesafter} ||= 2_500_000_000 ;
  12297. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  12298. $mysync->{maxsleep} = ( defined $mysync->{maxsleep} ) ? $mysync->{maxsleep} : $MAX_SLEEP ; ;
  12299. $skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 1 ;
  12300. push @useheader, 'X-Gmail-Received', 'Message-Id' ;
  12301. push @{ $mysync->{ regextrans2 } }, 's,\[Gmail\].,,' ;
  12302. push @folderlast, '[Gmail]/All Mail' ;
  12303. return ;
  12304. }
  12305. sub gmail2
  12306. {
  12307. my $mysync = shift ;
  12308. # Gmail at host2
  12309. $mysync->{host2} ||= 'imap.gmail.com' ;
  12310. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  12311. $mysync->{maxbytespersecond} ||= 20_000 ; # should be 10_000 computed from by Gmail documentation
  12312. $mysync->{maxbytesafter} ||= 1_000_000_000 ; # In fact it is documented as half: 500_000_000
  12313. $mysync->{automap} = ( defined $mysync->{automap} ) ? $mysync->{automap} : 1 ;
  12314. #$skipcrossduplicates = ( defined $skipcrossduplicates ) ? $skipcrossduplicates : 1 ;
  12315. $mysync->{ expunge1 } = ( defined $mysync->{ expunge1 } ) ? $mysync->{ expunge1 } : 1 ;
  12316. $mysync->{addheader} = ( defined $mysync->{addheader} ) ? $mysync->{addheader} : 1 ;
  12317. $mysync->{maxsleep} = ( defined $mysync->{maxsleep} ) ? $mysync->{maxsleep} : $MAX_SLEEP ; ;
  12318. $mysync->{maxsize} = ( defined $mysync->{maxsize} ) ? $mysync->{maxsize} : $GMAIL_MAXSIZE ;
  12319. if ( ! $mysync->{noexclude} ) {
  12320. push @exclude, '\[Gmail\]$' ;
  12321. }
  12322. push @useheader, 'Message-Id' ;
  12323. push @{ $mysync->{ regextrans2 } }, 's,\[Gmail\].,,' ;
  12324. # push @{ $mysync->{ regextrans2 } }, 's/[ ]+/_/g' ; # is now replaced
  12325. # by the two more specific following regexes,
  12326. # they remove just the beginning and trailing blanks, not all.
  12327. push @{ $mysync->{ regextrans2 } }, 's,^ +| +$,,g' ;
  12328. push @{ $mysync->{ regextrans2 } }, 's,/ +| +/,/,g' ;
  12329. #
  12330. push @{ $mysync->{ regextrans2 } }, q{s/['\\^"]/_/g} ; # Verified this
  12331. push @folderlast, '[Gmail]/All Mail' ;
  12332. return ;
  12333. }
  12334. # From https://imapsync.lamiral.info/FAQ.d/FAQ.Exchange.txt
  12335. sub office1
  12336. {
  12337. # Office 365 at host1
  12338. my $mysync = shift ;
  12339. output( $mysync, q{Option --office1 is like: --host1 outlook.office365.com --ssl1 --exclude "^Files$"} . "\n" ) ;
  12340. output( $mysync, "Option --office1 (cont) : unless overrided with --host1 otherhost --nossl1 --noexclude\n" ) ;
  12341. $mysync->{host1} ||= 'outlook.office365.com' ;
  12342. $mysync->{ssl1} = ( defined $mysync->{ssl1} ) ? $mysync->{ssl1} : 1 ;
  12343. if ( ! $mysync->{noexclude} ) {
  12344. push @exclude, '^Files$' ;
  12345. }
  12346. return ;
  12347. }
  12348. sub office2
  12349. {
  12350. # Office 365 at host2
  12351. my $mysync = shift ;
  12352. output( $mysync, qq{Option --office2 is like: --host2 outlook.office365.com --ssl2 --maxsize 45_000_000 --maxmessagespersecond 4\n} ) ;
  12353. output( $mysync, qq{Option --office2 (cont) : --disarmreadreceipts --regexmess "wrap 10500" --f1f2 "Files=Files_renamed_by_imapsync"\n} ) ;
  12354. output( $mysync, qq{Option --office2 (cont) : unless overrided with --host2 otherhost --nossl2 ... --nodisarmreadreceipts --noregexmess\n} ) ;
  12355. output( $mysync, qq{Option --office2 (cont) : and --nof1f2 to avoid Files folder renamed to Files_renamed_by_imapsync\n} ) ;
  12356. $mysync->{host2} ||= 'outlook.office365.com' ;
  12357. $mysync->{ssl2} = ( defined $mysync->{ssl2} ) ? $mysync->{ssl2} : 1 ;
  12358. $mysync->{ maxsize } ||= 45_000_000 ;
  12359. $mysync->{maxmessagespersecond} ||= 4 ;
  12360. #push @regexflag, 's/\\\\Flagged//g' ; # No problem without! tested 2018_09_10
  12361. $disarmreadreceipts = ( defined $disarmreadreceipts ) ? $disarmreadreceipts : 1 ;
  12362. # I dislike double negation but here is one
  12363. if ( ! $mysync->{noregexmess} )
  12364. {
  12365. push @regexmess, 's,(.{10239}),$1\r\n,g' ;
  12366. }
  12367. # and another...
  12368. if ( ! $mysync->{nof1f2} )
  12369. {
  12370. push @{ $mysync->{f1f2} }, 'Files=Files_renamed_by_imapsync' ;
  12371. }
  12372. return ;
  12373. }
  12374. sub exchange1
  12375. {
  12376. # Exchange 2010/2013 at host1
  12377. my $mysync = shift ;
  12378. output( $mysync, "Option --exchange1 does nothing (except printing this line...)\n" ) ;
  12379. # Well nothing to do so far
  12380. return ;
  12381. }
  12382. sub exchange2
  12383. {
  12384. # Exchange 2010/2013 at host2
  12385. my $mysync = shift ;
  12386. output( $mysync, "Option --exchange2 is like: --maxsize 10_000_000 --maxmessagespersecond 4 --disarmreadreceipts\n" ) ;
  12387. output( $mysync, "Option --exchange2 (cont) : --regexflag del Flagged --regexmess wrap 10500\n" ) ;
  12388. output( $mysync, "Option --exchange2 (cont) : unless overrided with --maxsize xxx --nodisarmreadreceipts --noregexflag --noregexmess\n" ) ;
  12389. $mysync->{ maxsize } ||= 10_000_000 ;
  12390. $mysync->{maxmessagespersecond} ||= 4 ;
  12391. $disarmreadreceipts = ( defined $disarmreadreceipts ) ? $disarmreadreceipts : 1 ;
  12392. # I dislike double negation but here are two
  12393. if ( ! $mysync->{noregexflag} ) {
  12394. push @regexflag, 's/\\\\Flagged//g' ;
  12395. }
  12396. if ( ! $mysync->{noregexmess} ) {
  12397. push @regexmess, 's,(.{10239}),$1\r\n,g' ;
  12398. }
  12399. return ;
  12400. }
  12401. sub domino1
  12402. {
  12403. # Domino at host1
  12404. my $mysync = shift ;
  12405. $mysync->{ sep1 } = q{\\} ;
  12406. $prefix1 = q{} ;
  12407. $messageidnodomain = ( defined $messageidnodomain ) ? $messageidnodomain : 1 ;
  12408. return ;
  12409. }
  12410. sub domino2
  12411. {
  12412. # Domino at host1
  12413. my $mysync = shift ;
  12414. $mysync->{ sep2 } = q{\\} ;
  12415. $prefix2 = q{} ;
  12416. $messageidnodomain = ( defined $messageidnodomain ) ? $messageidnodomain : 1 ;
  12417. push @{ $mysync->{ regextrans2 } }, 's,^Inbox\\\\(.*),$1,i' ;
  12418. return ;
  12419. }
  12420. sub tests_resolv
  12421. {
  12422. note( 'Entering tests_resolv()' ) ;
  12423. # is( , resolv( ), 'resolv: => ' ) ;
  12424. is( undef, resolv( ), 'resolv: no args => undef' ) ;
  12425. is( undef, resolv( q{} ), 'resolv: empty string => undef' ) ;
  12426. is( undef, resolv( 'hostnotexist' ), 'resolv: hostnotexist => undef' ) ;
  12427. is( '127.0.0.1', resolv( '127.0.0.1' ), 'resolv: 127.0.0.1 => 127.0.0.1' ) ;
  12428. is( '127.0.0.1', resolv( 'localhost' ), 'resolv: localhost => 127.0.0.1' ) ;
  12429. is( '5.135.158.182', resolv( 'imapsync.lamiral.info' ), 'resolv: imapsync.lamiral.info => 5.135.158.182' ) ;
  12430. # ip6-localhost ( in /etc/hosts )
  12431. is( '::1', resolv( 'ip6-localhost' ), 'resolv: ip6-localhost => ::1' ) ;
  12432. is( '::1', resolv( '::1' ), 'resolv: ::1 => ::1' ) ;
  12433. # ks2
  12434. is( '2001:41d0:8:d8b6::1', resolv( '2001:41d0:8:d8b6::1' ), 'resolv: 2001:41d0:8:d8b6::1 => 2001:41d0:8:d8b6::1' ) ;
  12435. is( '2001:41d0:8:d8b6::1', resolv( 'ks2ipv6.lamiral.info' ), 'resolv: ks2ipv6.lamiral.info => 2001:41d0:8:d8b6::1' ) ;
  12436. # ks3
  12437. is( '2001:41d0:8:bebd::1', resolv( '2001:41d0:8:bebd::1' ), 'resolv: 2001:41d0:8:bebd::1 => 2001:41d0:8:bebd::1' ) ;
  12438. is( '2001:41d0:8:bebd::1', resolv( 'ks3ipv6.lamiral.info' ), 'resolv: ks3ipv6.lamiral.info => 2001:41d0:8:bebd::1' ) ;
  12439. note( 'Leaving tests_resolv()' ) ;
  12440. return ;
  12441. }
  12442. sub resolv
  12443. {
  12444. my $host = shift @ARG ;
  12445. if ( ! $host ) { return ; }
  12446. my $addr ;
  12447. if ( defined &Socket::getaddrinfo ) {
  12448. $addr = resolv_with_getaddrinfo( $host ) ;
  12449. return( $addr ) ;
  12450. }
  12451. my $iaddr = inet_aton( $host ) ;
  12452. if ( ! $iaddr ) { return ; }
  12453. $addr = inet_ntoa( $iaddr ) ;
  12454. return $addr ;
  12455. }
  12456. sub resolv_with_getaddrinfo
  12457. {
  12458. my $host = shift @ARG ;
  12459. if ( ! $host ) { return ; }
  12460. my ( $err_getaddrinfo, @res ) = Socket::getaddrinfo( $host, "", { socktype => Socket::SOCK_RAW } ) ;
  12461. if ( $err_getaddrinfo ) {
  12462. myprint( "Cannot getaddrinfo of $host: $err_getaddrinfo\n" ) ;
  12463. return ;
  12464. }
  12465. my @addr ;
  12466. while( my $ai = shift @res ) {
  12467. my ( $err_getnameinfo, $ipaddr ) = Socket::getnameinfo( $ai->{addr}, Socket::NI_NUMERICHOST(), Socket::NIx_NOSERV() ) ;
  12468. if ( $err_getnameinfo ) {
  12469. myprint( "Cannot getnameinfo of $host: $err_getnameinfo\n" ) ;
  12470. return ;
  12471. }
  12472. $sync->{ debug } and myprint( "$host => $ipaddr\n" ) ;
  12473. push @addr, $ipaddr ;
  12474. my $reverse ;
  12475. ( $err_getnameinfo, $reverse ) = Socket::getnameinfo( $ai->{addr}, 0, Socket::NIx_NOSERV() ) ;
  12476. $sync->{ debug } and myprint( "$host => $ipaddr => $reverse\n" ) ;
  12477. }
  12478. return $addr[0] ;
  12479. }
  12480. sub tests_resolvrev
  12481. {
  12482. note( 'Entering tests_resolvrev()' ) ;
  12483. # is( , resolvrev( ), 'resolvrev: => ' ) ;
  12484. is( undef, resolvrev( ), 'resolvrev: no args => undef' ) ;
  12485. is( undef, resolvrev( q{} ), 'resolvrev: empty string => undef' ) ;
  12486. is( undef, resolvrev( 'hostnotexist' ), 'resolvrev: hostnotexist => undef' ) ;
  12487. is( 'localhost', resolvrev( '127.0.0.1' ), 'resolvrev: 127.0.0.1 => localhost' ) ;
  12488. is( 'localhost', resolvrev( 'localhost' ), 'resolvrev: localhost => localhost' ) ;
  12489. is( 'ks.lamiral.info', resolvrev( 'imapsync.lamiral.info' ), 'resolvrev: imapsync.lamiral.info => ks.lamiral.info' ) ;
  12490. # ip6-localhost ( in /etc/hosts )
  12491. is( 'ip6-localhost', resolvrev( 'ip6-localhost' ), 'resolvrev: ip6-localhost => ip6-localhost' ) ;
  12492. is( 'ip6-localhost', resolvrev( '::1' ), 'resolvrev: ::1 => ip6-localhost' ) ;
  12493. # ks2
  12494. is( 'ks2ipv6.lamiral.info', resolvrev( '2001:41d0:8:d8b6::1' ), 'resolvrev: 2001:41d0:8:d8b6::1 => ks2ipv6.lamiral.info' ) ;
  12495. is( 'ks2ipv6.lamiral.info', resolvrev( 'ks2ipv6.lamiral.info' ), 'resolvrev: ks2ipv6.lamiral.info => ks2ipv6.lamiral.info' ) ;
  12496. # ks3
  12497. is( 'ks3ipv6.lamiral.info', resolvrev( '2001:41d0:8:bebd::1' ), 'resolvrev: 2001:41d0:8:bebd::1 => ks3ipv6.lamiral.info' ) ;
  12498. is( 'ks3ipv6.lamiral.info', resolvrev( 'ks3ipv6.lamiral.info' ), 'resolvrev: ks3ipv6.lamiral.info => ks3ipv6.lamiral.info' ) ;
  12499. note( 'Leaving tests_resolvrev()' ) ;
  12500. return ;
  12501. }
  12502. sub resolvrev
  12503. {
  12504. my $host = shift @ARG ;
  12505. if ( ! $host ) { return ; }
  12506. if ( defined &Socket::getaddrinfo ) {
  12507. my $name = resolvrev_with_getaddrinfo( $host ) ;
  12508. return( $name ) ;
  12509. }
  12510. return ;
  12511. }
  12512. sub resolvrev_with_getaddrinfo
  12513. {
  12514. my $host = shift @ARG ;
  12515. if ( ! $host ) { return ; }
  12516. my ( $err, @res ) = Socket::getaddrinfo( $host, "", { socktype => Socket::SOCK_RAW } ) ;
  12517. if ( $err ) {
  12518. myprint( "Cannot getaddrinfo of $host: $err\n" ) ;
  12519. return ;
  12520. }
  12521. my @name ;
  12522. while( my $ai = shift @res ) {
  12523. my ( $err, $reverse ) = Socket::getnameinfo( $ai->{addr}, 0, Socket::NIx_NOSERV() ) ;
  12524. if ( $err ) {
  12525. myprint( "Cannot getnameinfo of $host: $err\n" ) ;
  12526. return ;
  12527. }
  12528. $sync->{ debug } and myprint( "$host => $reverse\n" ) ;
  12529. push @name, $reverse ;
  12530. }
  12531. return $name[0] ;
  12532. }
  12533. sub tests_imapsping
  12534. {
  12535. note( 'Entering tests_imapsping()' ) ;
  12536. is( undef, imapsping( ), 'imapsping: no args => undef' ) ;
  12537. is( undef, imapsping( 'hostnotexist' ), 'imapsping: hostnotexist => undef' ) ;
  12538. is( 1, imapsping( 'imapsync.lamiral.info' ), 'imapsping: imapsync.lamiral.info => 1' ) ;
  12539. is( 1, imapsping( 'ks2ipv6.lamiral.info' ), 'imapsping: ks2ipv6.lamiral.info => 1' ) ;
  12540. note( 'Leaving tests_imapsping()' ) ;
  12541. return ;
  12542. }
  12543. sub imapsping
  12544. {
  12545. my $host = shift ;
  12546. return tcpping( $host, $IMAP_SSL_PORT ) ;
  12547. }
  12548. sub tests_tcpping
  12549. {
  12550. note( 'Entering tests_tcpping()' ) ;
  12551. is( undef, tcpping( ), 'tcpping: no args => undef' ) ;
  12552. is( undef, tcpping( 'hostnotexist' ), 'tcpping: one arg => undef' ) ;
  12553. is( undef, tcpping( undef, 888 ), 'tcpping: arg undef, port => undef' ) ;
  12554. is( undef, tcpping( 'hostnotexist', 993 ), 'tcpping: hostnotexist 993 => undef' ) ;
  12555. is( undef, tcpping( 'hostnotexist', 888 ), 'tcpping: hostnotexist 888 => undef' ) ;
  12556. is( 1, tcpping( 'imapsync.lamiral.info', 993 ), 'tcpping: imapsync.lamiral.info 993 => 1' ) ;
  12557. is( 0, tcpping( 'imapsync.lamiral.info', 888 ), 'tcpping: imapsync.lamiral.info 888 => 0' ) ;
  12558. is( 1, tcpping( '5.135.158.182', 993 ), 'tcpping: 5.135.158.182 993 => 1' ) ;
  12559. is( 0, tcpping( '5.135.158.182', 888 ), 'tcpping: 5.135.158.182 888 => 0' ) ;
  12560. # Net::Ping supports ipv6 only after release 1.50
  12561. # http://cpansearch.perl.org/src/RURBAN/Net-Ping-2.59/Changes
  12562. # Anyway I plan to avoid Net-Ping for that too long standing feature
  12563. # Net-Ping is integrated in Perl itself, who knows ipv6 for a long time
  12564. is( 1, tcpping( '2001:41d0:8:d8b6::1', 993 ), 'tcpping: 2001:41d0:8:d8b6::1 993 => 1' ) ;
  12565. is( 0, tcpping( '2001:41d0:8:d8b6::1', 888 ), 'tcpping: 2001:41d0:8:d8b6::1 888 => 0' ) ;
  12566. note( 'Leaving tests_tcpping()' ) ;
  12567. return ;
  12568. }
  12569. sub tcpping
  12570. {
  12571. if ( 2 != scalar( @ARG ) ) {
  12572. return ;
  12573. }
  12574. my ( $host, $port ) = @ARG ;
  12575. if ( ! $host ) { return ; }
  12576. if ( ! $port ) { return ; }
  12577. my $mytimeout = $TCP_PING_TIMEOUT ;
  12578. require Net::Ping ;
  12579. #my $p = Net::Ping->new( 'tcp' ) ;
  12580. my $p = Net::Ping->new( ) ;
  12581. $p->{port_num} = $port ;
  12582. $p->service_check( 1 ) ;
  12583. $p->hires( 1 ) ;
  12584. my ($ping_ok, $rtt, $ip ) = $p->ping( $host, $mytimeout ) ;
  12585. if ( ! defined $ping_ok ) { return ; }
  12586. my $rtt_approx = sprintf( "%.3f", $rtt ) ;
  12587. $sync->{ debug } and myprint( "Host $host timeout $mytimeout port $port ok $ping_ok ip $ip acked in $rtt_approx s\n" ) ;
  12588. $p->close( ) ;
  12589. if( $ping_ok ) {
  12590. return 1 ;
  12591. }else{
  12592. return 0 ;
  12593. }
  12594. }
  12595. sub tests_sslcheck
  12596. {
  12597. note( 'Entering tests_sslcheck()' ) ;
  12598. my $mysync ;
  12599. is( undef, sslcheck( $mysync ), 'sslcheck: no sslcheck => undef' ) ;
  12600. $mysync = {
  12601. sslcheck => 1,
  12602. } ;
  12603. is( 0, sslcheck( $mysync ), 'sslcheck: no host => 0' ) ;
  12604. $mysync = {
  12605. sslcheck => 1,
  12606. host1 => 'imapsync.lamiral.info',
  12607. tls1 => 1,
  12608. } ;
  12609. is( 0, sslcheck( $mysync ), 'sslcheck: tls1 => 0' ) ;
  12610. $mysync = {
  12611. sslcheck => 1,
  12612. host1 => 'imapsync.lamiral.info',
  12613. } ;
  12614. is( 1, sslcheck( $mysync ), 'sslcheck: imapsync.lamiral.info => 1' ) ;
  12615. is( 1, $mysync->{ssl1}, 'sslcheck: imapsync.lamiral.info => ssl1 1' ) ;
  12616. $mysync->{sslcheck} = 0 ;
  12617. is( undef, sslcheck( $mysync ), 'sslcheck: sslcheck off => undef' ) ;
  12618. $mysync = {
  12619. sslcheck => 1,
  12620. host1 => 'imapsync.lamiral.info',
  12621. host2 => 'test2.lamiral.info',
  12622. } ;
  12623. is( 2, sslcheck( $mysync ), 'sslcheck: imapsync.lamiral.info + test2.lamiral.info => 2' ) ;
  12624. $mysync = {
  12625. sslcheck => 1,
  12626. host1 => 'imapsync.lamiral.info',
  12627. host2 => 'test2.lamiral.info',
  12628. tls1 => 1,
  12629. } ;
  12630. is( 1, sslcheck( $mysync ), 'sslcheck: imapsync.lamiral.info + test2.lamiral.info + tls1 => 1' ) ;
  12631. note( 'Leaving tests_sslcheck()' ) ;
  12632. return ;
  12633. }
  12634. sub sslcheck
  12635. {
  12636. my $mysync = shift ;
  12637. if ( ! $mysync->{sslcheck} ) {
  12638. return ;
  12639. }
  12640. my $nb_on = 0 ;
  12641. $mysync->{ debug } and myprint( "sslcheck\n" ) ;
  12642. if (
  12643. ( ! defined $mysync->{port1} )
  12644. and
  12645. ( ! defined $mysync->{tls1} )
  12646. and
  12647. ( ! defined $mysync->{ssl1} )
  12648. and
  12649. ( defined $mysync->{host1} )
  12650. ) {
  12651. myprint( "Host1: probing ssl on port $IMAP_SSL_PORT ( use --nosslcheck to avoid this ssl probe ) \n" ) ;
  12652. if ( probe_imapssl( $mysync->{host1} ) ) {
  12653. $mysync->{ssl1} = 1 ;
  12654. 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" ) ;
  12655. $nb_on++ ;
  12656. }else{
  12657. myprint( "Host1: sslcheck did not detected open ssl port $IMAP_SSL_PORT. Will use standard $IMAP_PORT port.\n" ) ;
  12658. }
  12659. }
  12660. if (
  12661. ( ! defined $mysync->{port2} )
  12662. and
  12663. ( ! defined $mysync->{tls2} )
  12664. and
  12665. ( ! defined $mysync->{ssl2} )
  12666. and
  12667. ( defined $mysync->{host2} )
  12668. ) {
  12669. myprint( "Host2: probing ssl on port $IMAP_SSL_PORT ( use --nosslcheck to avoid this ssl probe ) \n" ) ;
  12670. if ( probe_imapssl( $mysync->{host2} ) ) {
  12671. $mysync->{ssl2} = 1 ;
  12672. 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" ) ;
  12673. $nb_on++ ;
  12674. }else{
  12675. myprint( "Host2: sslcheck did not detected open ssl port $IMAP_SSL_PORT. Will use standard $IMAP_PORT port.\n" ) ;
  12676. }
  12677. }
  12678. return $nb_on ;
  12679. }
  12680. sub testslive_init
  12681. {
  12682. my $mysync = shift ;
  12683. $mysync->{host1} ||= 'test1.lamiral.info' ;
  12684. $mysync->{user1} ||= 'test1' ;
  12685. $mysync->{password1} ||= 'secret1' ;
  12686. $mysync->{host2} ||= 'test2.lamiral.info' ;
  12687. $mysync->{user2} ||= 'test2' ;
  12688. $mysync->{password2} ||= 'secret2' ;
  12689. return ;
  12690. }
  12691. sub testslive6_init
  12692. {
  12693. my $mysync = shift ;
  12694. $mysync->{host1} ||= 'ks2ipv6.lamiral.info' ;
  12695. $mysync->{user1} ||= 'test1' ;
  12696. $mysync->{password1} ||= 'secret1' ;
  12697. $mysync->{host2} ||= 'ks2ipv6.lamiral.info' ;
  12698. $mysync->{user2} ||= 'test2' ;
  12699. $mysync->{password2} ||= 'secret2' ;
  12700. return ;
  12701. }
  12702. sub tests_backslash_caret
  12703. {
  12704. note( 'Entering tests_backslash_caret()' ) ;
  12705. is( "lalala", backslash_caret( "lalala" ), 'backslash_caret: lalala => lalala' ) ;
  12706. is( "lalala\n", backslash_caret( "lalala\n" ), 'backslash_caret: lalala => lalala 2nd' ) ;
  12707. is( '^', backslash_caret( '\\' ), 'backslash_caret: \\ => ^' ) ;
  12708. is( "^\n", backslash_caret( "\\\n" ), 'backslash_caret: \\ => ^' ) ;
  12709. is( "\\lalala", backslash_caret( "\\lalala" ), 'backslash_caret: \\lalala => \\lalala' ) ;
  12710. is( "\\lal\\ala", backslash_caret( "\\lal\\ala" ), 'backslash_caret: \\lal\\ala => \\lal\\ala' ) ;
  12711. is( "\\lalala\n", backslash_caret( "\\lalala\n" ), 'backslash_caret: \\lalala => \\lalala 2nd' ) ;
  12712. is( "lalala^\n", backslash_caret( "lalala\\\n" ), 'backslash_caret: lalala\\\n => lalala^\n' ) ;
  12713. is( "lalala^\nlalala^\n", backslash_caret( "lalala\\\nlalala\\\n" ), 'backslash_caret: lalala\\\nlalala\\\n => lalala^\nlalala^\n' ) ;
  12714. is( "lal\\ala^\nlalala^\n", backslash_caret( "lal\\ala\\\nlalala\\\n" ), 'backslash_caret: lal\\ala\\\nlalala\\\n => lal\\ala^\nlalala^\n' ) ;
  12715. note( 'Leaving tests_backslash_caret()' ) ;
  12716. return ;
  12717. }
  12718. sub backslash_caret
  12719. {
  12720. my $string = shift ;
  12721. $string =~ s{\\ $ }{^}gxms ;
  12722. return $string ;
  12723. }
  12724. sub tests_split_around_equal
  12725. {
  12726. note( 'Entering tests_split_around_equal()' ) ;
  12727. is( undef, split_around_equal( ), 'split_around_equal: no args => undef' ) ;
  12728. is_deeply( { toto => 'titi' }, { split_around_equal( 'toto=titi' ) }, 'split_around_equal: toto=titi => toto => titi' ) ;
  12729. is_deeply( { A => 'B', C => 'D' }, { split_around_equal( 'A=B=C=D' ) }, 'split_around_equal: toto=titi => toto => titi' ) ;
  12730. is_deeply( { A => 'B', C => 'D' }, { split_around_equal( 'A=B', 'C=D' ) }, 'split_around_equal: A=B C=D => A => B, C=>D' ) ;
  12731. note( 'Leaving tests_split_around_equal()' ) ;
  12732. return ;
  12733. }
  12734. sub split_around_equal
  12735. {
  12736. if ( ! @ARG ) { return ; } ;
  12737. return map { split /=/mxs, $_ } @ARG ;
  12738. }
  12739. sub tests_sig_install
  12740. {
  12741. note( 'Entering tests_sig_install()' ) ;
  12742. my $mysync ;
  12743. is( undef, sig_install( ), 'sig_install: no args => undef' ) ;
  12744. is( undef, sig_install( $mysync ), 'sig_install: arg undef => undef' ) ;
  12745. $mysync = { } ;
  12746. is( undef, sig_install( $mysync ), 'sig_install: empty hash => undef' ) ;
  12747. SKIP: {
  12748. Readonly my $SKIP_15 => 15 ;
  12749. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests only for Unix', $SKIP_15 ) ; }
  12750. # Default to ignore USR1 USR2 in case future install fails
  12751. local $SIG{ USR1 } = local $SIG{ USR2 } = sub { } ;
  12752. kill( 'USR1', $PROCESS_ID ) ;
  12753. $mysync->{ debugsig } = 1 ;
  12754. # Assign USR1 to call sub tototo
  12755. # Surely a better value than undef should be returned when doing real signal stuff
  12756. is( undef, sig_install( $mysync, 'tototo', 'USR1' ), 'sig_install: USR1 tototo' ) ;
  12757. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 1' ) ;
  12758. is( 1, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 1' ) ;
  12759. #return ;
  12760. # Assign USR2 to call sub tototo
  12761. is( undef, sig_install( $mysync, 'tototo', 'USR2' ), 'sig_install: USR2 tototo' ) ;
  12762. is( 1, kill( 'USR2', $PROCESS_ID ), 'sig_install: kill USR2 myself 1' ) ;
  12763. is( 2, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 2' ) ;
  12764. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 2' ) ;
  12765. is( 3, $mysync->{ tototo_calls }, 'sig_install: tototo call nb 3' ) ;
  12766. local $SIG{ USR1 } = local $SIG{ USR2 } = sub { } ;
  12767. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 3' ) ;
  12768. is( 3, $mysync->{ tototo_calls }, 'sig_install: tototo call still nb 3' ) ;
  12769. # Assign USR1 + USR2 to call sub tototo
  12770. is( undef, sig_install( $mysync, 'tototo', 'USR1', 'USR2' ), 'sig_install: USR1 USR2 tototo' ) ;
  12771. is( 1, kill( 'USR1', $PROCESS_ID ), 'sig_install: kill USR1 myself 4' ) ;
  12772. is( 4, $mysync->{ tototo_calls }, 'sig_install: tototo call now nb 4' ) ;
  12773. is( 1, kill( 'USR2', $PROCESS_ID ), 'sig_install: kill USR1 myself 2' ) ;
  12774. is( 5, $mysync->{ tototo_calls }, 'sig_install: tototo call now nb 5' ) ;
  12775. }
  12776. note( 'Leaving tests_sig_install()' ) ;
  12777. return ;
  12778. }
  12779. #
  12780. sub sig_install
  12781. {
  12782. my $mysync = shift ;
  12783. if ( ! $mysync ) { return ; }
  12784. my $mysubname = shift ;
  12785. if ( ! $mysubname ) { return ; }
  12786. if ( ! @ARG ) { return ; }
  12787. my @signals = @ARG ;
  12788. my $mysub = \&$mysubname ;
  12789. #$mysync->{ debugsig } = 1 ;
  12790. $mysync->{ debugsig } and myprint( "In sig_install with sub $mysubname and signal @ARG\n" ) ;
  12791. my $subsignal = sub {
  12792. my $signame = shift ;
  12793. $mysync->{ debugsig } and myprint( "In subsignal with $signame and $mysubname\n" ) ;
  12794. &$mysub( $mysync, $signame ) ;
  12795. } ;
  12796. foreach my $signal ( @signals ) {
  12797. $mysync->{ debugsig } and myprint( "Installing signal $signal to call sub $mysubname\n") ;
  12798. output( $mysync, "kill -$signal $PROCESS_ID # special behavior: call to sub $mysubname\n" ) ;
  12799. ## no critic (RequireLocalizedPunctuationVars)
  12800. $SIG{ $signal } = $subsignal ;
  12801. }
  12802. return ;
  12803. }
  12804. sub tototo
  12805. {
  12806. my $mysync = shift ;
  12807. myprint("In tototo with @ARG\n" ) ;
  12808. $mysync->{ tototo_calls } += 1 ;
  12809. return ;
  12810. }
  12811. sub mygetppid
  12812. {
  12813. if ( 'MSWin32' eq $OSNAME ) {
  12814. return( 'unknown under MSWin32 (too complicated)' ) ;
  12815. } else {
  12816. # Unix
  12817. return( getppid( ) ) ;
  12818. }
  12819. }
  12820. sub tests_toggle_sleep
  12821. {
  12822. note( 'Entering tests_toggle_sleep()' ) ;
  12823. is( undef, toggle_sleep( ), 'toggle_sleep: no args => undef' ) ;
  12824. my $mysync ;
  12825. is( undef, toggle_sleep( $mysync ), 'toggle_sleep: undef => undef' ) ;
  12826. $mysync = { } ;
  12827. is( undef, toggle_sleep( $mysync ), 'toggle_sleep: no maxsleep => undef' ) ;
  12828. $mysync->{maxsleep} = 3 ;
  12829. is( 0, toggle_sleep( $mysync ), 'toggle_sleep: 3 => 0' ) ;
  12830. is( $MAX_SLEEP, toggle_sleep( $mysync ), "toggle_sleep: 0 => $MAX_SLEEP" ) ;
  12831. is( 0, toggle_sleep( $mysync ), "toggle_sleep: $MAX_SLEEP => 0" ) ;
  12832. is( $MAX_SLEEP, toggle_sleep( $mysync ), "toggle_sleep: 0 => $MAX_SLEEP" ) ;
  12833. is( 0, toggle_sleep( $mysync ), "toggle_sleep: $MAX_SLEEP => 0" ) ;
  12834. SKIP: {
  12835. Readonly my $SKIP_9 => 9 ;
  12836. if ( 'MSWin32' eq $OSNAME ) { skip( 'Tests only for Unix', $SKIP_9 ) ; }
  12837. # Default to ignore USR1 USR2 in case future install fails
  12838. local $SIG{ USR1 } = sub { } ;
  12839. kill( 'USR1', $PROCESS_ID ) ;
  12840. $mysync->{ debugsig } = 1 ;
  12841. # Assign USR1 to call sub toggle_sleep
  12842. is( undef, sig_install( $mysync, \&toggle_sleep, 'USR1' ), 'toggle_sleep: install USR1 toggle_sleep' ) ;
  12843. $mysync->{maxsleep} = 4 ;
  12844. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself' ) ;
  12845. is( 0, $mysync->{ maxsleep }, 'toggle_sleep: toggle_sleep called => sleeps are 0s' ) ;
  12846. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself again' ) ;
  12847. is( $MAX_SLEEP, $mysync->{ maxsleep }, "toggle_sleep: toggle_sleep called => sleeps are ${MAX_SLEEP}s" ) ;
  12848. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself' ) ;
  12849. is( 0, $mysync->{ maxsleep }, 'toggle_sleep: toggle_sleep called => sleeps are 0s' ) ;
  12850. is( 1, kill( 'USR1', $PROCESS_ID ), 'toggle_sleep: kill USR1 myself again' ) ;
  12851. is( $MAX_SLEEP, $mysync->{ maxsleep }, "toggle_sleep: toggle_sleep called => sleeps are ${MAX_SLEEP}s" ) ;
  12852. }
  12853. note( 'Leaving tests_toggle_sleep()' ) ;
  12854. return ;
  12855. }
  12856. sub toggle_sleep
  12857. {
  12858. my $mysync = shift ;
  12859. myprint("In toggle_sleep with @ARG\n" ) ;
  12860. if ( !defined( $mysync ) ) { return ; }
  12861. if ( !defined( $mysync->{maxsleep} ) ) { return ; }
  12862. $mysync->{ maxsleep } = max( 0, $MAX_SLEEP - $mysync->{maxsleep} ) ;
  12863. myprint("Resetting maxsleep to ", $mysync->{maxsleep}, "s\n" ) ;
  12864. return $mysync->{maxsleep} ;
  12865. }
  12866. sub mypod2usage
  12867. {
  12868. my $fh_pod2usage = shift ;
  12869. pod2usage(
  12870. -exitval => 'NOEXIT',
  12871. -noperldoc => 1,
  12872. -verbose => 99,
  12873. -sections => [ qw(NAME VERSION USAGE OPTIONS) ],
  12874. -indent => 1,
  12875. -loose => 1,
  12876. -output => $fh_pod2usage,
  12877. ) ;
  12878. return ;
  12879. }
  12880. sub usage
  12881. {
  12882. my $mysync = shift ;
  12883. if ( ! defined $mysync ) { return ; }
  12884. my $usage = q{} ;
  12885. my $usage_from_pod ;
  12886. my $usage_footer = usage_footer( $mysync ) ;
  12887. # pod2usage writes on a filehandle only and I want a variable
  12888. open my $fh_pod2usage, ">", \$usage_from_pod
  12889. or do { warn $OS_ERROR ; return ; } ;
  12890. mypod2usage( $fh_pod2usage ) ;
  12891. close $fh_pod2usage ;
  12892. if ( 'MSWin32' eq $OSNAME ) {
  12893. $usage_from_pod = backslash_caret( $usage_from_pod ) ;
  12894. }
  12895. $usage = join( q{}, $usage_from_pod, $usage_footer ) ;
  12896. return( $usage ) ;
  12897. }
  12898. sub tests_usage
  12899. {
  12900. note( 'Entering tests_usage()' ) ;
  12901. my $usage ;
  12902. like( $usage = usage( $sync ), qr/Name:/, 'usage: contains Name:' ) ;
  12903. myprint( $usage ) ;
  12904. like( $usage, qr/Version:/, 'usage: contains Version:' ) ;
  12905. like( $usage, qr/Usage:/, 'usage: contains Usage:' ) ;
  12906. like( $usage, qr/imapsync/, 'usage: contains imapsync' ) ;
  12907. is( undef, usage( ), 'usage: no args => undef' ) ;
  12908. note( 'Leaving tests_usage()' ) ;
  12909. return ;
  12910. }
  12911. sub usage_footer
  12912. {
  12913. my $mysync = shift ;
  12914. my $footer = q{} ;
  12915. my $localhost_info = localhost_info( $mysync ) ;
  12916. my $rcs = $mysync->{rcs} ;
  12917. my $homepage = homepage( ) ;
  12918. my $imapsync_release = $STR_use_releasecheck ;
  12919. if ( $mysync->{releasecheck} ) {
  12920. $imapsync_release = check_last_release( ) ;
  12921. }
  12922. $footer = qq{$localhost_info
  12923. $rcs
  12924. $imapsync_release
  12925. $homepage
  12926. } ;
  12927. return( $footer ) ;
  12928. }
  12929. sub usage_complete
  12930. {
  12931. # Unused, I guess this function could be deleted
  12932. my $usage = <<'EOF' ;
  12933. --skipheader reg : Don't take into account header keyword
  12934. matching reg ex: --skipheader 'X.*'
  12935. --skipsize : Don't take message size into account to compare
  12936. messages on both sides. On by default.
  12937. Use --no-skipsize for using size comparaison.
  12938. --allowsizemismatch : allow RFC822.SIZE != fetched msg size
  12939. consider also --skipsize to avoid duplicate messages
  12940. when running syncs more than one time per mailbox
  12941. --reconnectretry1 int : reconnect to host1 if connection is lost up to
  12942. int times per imap command (default is 3)
  12943. --reconnectretry2 int : same as --reconnectretry1 but for host2
  12944. --split1 int : split the requests in several parts on host1.
  12945. int is the number of messages handled per request.
  12946. default is like --split1 100.
  12947. --split2 int : same thing on host2.
  12948. --nofixInboxINBOX : Don't fix Inbox INBOX mapping.
  12949. EOF
  12950. return( $usage ) ;
  12951. }
  12952. sub myGetOptions
  12953. {
  12954. # Started as a copy of Luke Ross Getopt::Long::CGI
  12955. # https://metacpan.org/release/Getopt-Long-CGI
  12956. # So this sub function is under the same license as Getopt-Long-CGI Luke Ross wants it,
  12957. # which was Perl 5.6 or later licenses at the date of the copy.
  12958. my $mysync = shift @ARG ;
  12959. my $arguments_ref = shift @ARG ;
  12960. my %options = @ARG ;
  12961. my $mycgi = $mysync->{cgi} ;
  12962. if ( not under_cgi_context() ) {
  12963. # Not CGI - pass upstream for normal command line handling
  12964. return Getopt::Long::GetOptionsFromArray( $arguments_ref, %options ) ;
  12965. }
  12966. # We must be in CGI context now
  12967. if ( ! defined( $mycgi ) ) { return ; }
  12968. my $badthings = 0 ;
  12969. foreach my $key ( sort keys %options ) {
  12970. my $val = $options{$key} ;
  12971. if ( $key !~ m/^([\w\d\|]+)([=:][isf])?([\+!\@\%])?$/mxs ) {
  12972. $badthings++ ;
  12973. next ; # Unknown item
  12974. }
  12975. my $name = [ split '|', $1, 1 ]->[0] ;
  12976. if ( ( $3 || q{} ) eq '+' ) {
  12977. ${$val} = $mycgi->param( $name ) ; # "Incremental" integer
  12978. }
  12979. elsif ( $2 ) {
  12980. my @values = $mycgi->multi_param( $name ) ;
  12981. my $type = $2 ;
  12982. #myprint( "type[$type]values[@values]\$3[", $3 || q{}, "]val[$val]ref(val)[", ref($val), "]\n" ) ;
  12983. if ( ( $3 || q{} ) eq '%' or ref( $val ) eq 'HASH' ) {
  12984. my %values = map { split /=/mxs, $_ } @values ;
  12985. if ( $type =~ m/i$/mxs ) {
  12986. foreach my $k ( keys %values ) {
  12987. $values{$k} = int $values{$k} ;
  12988. }
  12989. }
  12990. elsif ( $type =~ m/f$/mxs ) {
  12991. foreach my $k ( keys %values ) {
  12992. $values{$k} = 0 + $values{$k};
  12993. }
  12994. }
  12995. if ( 'REF' eq ref $val ) {
  12996. %{ ${$val} } = %values ;
  12997. }
  12998. else {
  12999. %{$val} = %values ;
  13000. }
  13001. }
  13002. else {
  13003. if ( $type =~ m/i$/mxs ) {
  13004. @values = map { q{} ne $_ ? int $_ : undef } @values ;
  13005. }
  13006. elsif ( $type =~ m/f$/mxs ) {
  13007. @values = map { 0 + $_ } @values ;
  13008. }
  13009. if ( ( $3 || q{} ) eq '@' ) {
  13010. @{ ${$val} } = @values ;
  13011. my @option = map { +( "--$name", "$_" ) } @values ;
  13012. push @{ $mysync->{ cmdcgi } }, @option ;
  13013. }
  13014. elsif ( ref( $val ) eq 'ARRAY' ) {
  13015. @{$val} = @values ;
  13016. }
  13017. elsif ( my $value = $values[0] )
  13018. {
  13019. ${$val} = $value ;
  13020. push @{ $mysync->{ cmdcgi } }, "--$name", $value ;
  13021. }
  13022. else
  13023. {
  13024. }
  13025. }
  13026. }
  13027. else
  13028. {
  13029. # Checkbox
  13030. # Considers only --name
  13031. # Should consider also --no-name and --noname
  13032. my $value = $mycgi->param( $name ) ;
  13033. if ( $value )
  13034. {
  13035. ${$val} = 1 ;
  13036. push @{ $mysync->{ cmdcgi } }, "--$name" ;
  13037. }
  13038. else
  13039. {
  13040. ${$val} = undef ;
  13041. }
  13042. }
  13043. }
  13044. if ( $badthings ) {
  13045. return ; # undef or ()
  13046. }
  13047. else {
  13048. return ( 1 ) ;
  13049. }
  13050. }
  13051. my @blabla ; # just used to check get_options_cgi() with an array
  13052. sub tests_get_options_cgi_context
  13053. {
  13054. note( 'Entering tests_get_options_cgi()' ) ;
  13055. # Temporary, have to think harder about testing CGI context in command line --tests
  13056. # API:
  13057. # * input arguments: two ways, command line or CGI
  13058. # * the program arguments
  13059. # * QUERY_STRING env variable
  13060. # * return
  13061. # * QUERY_STRING length
  13062. # CGI context
  13063. local $ENV{SERVER_SOFTWARE} = 'Votre serviteur' ;
  13064. # Real full test
  13065. # = 'host1=test1.lamiral.info&user1=test1&password1=secret1&host2=test2.lamiral.info&user2=test2&password2=secret2&debugenv=on'
  13066. my $mysync ;
  13067. is( undef, get_options( $mysync ), 'get_options cgi context: no CGI module => undef' ) ;
  13068. require CGI ;
  13069. CGI->import( qw( -no_debug -utf8 ) ) ;
  13070. is( undef, get_options( $mysync ), 'get_options cgi context: no CGI param => undef' ) ;
  13071. # Testing boolean
  13072. $mysync->{cgi} = CGI->new( 'version=on&debugenv=on' ) ;
  13073. local $ENV{'QUERY_STRING'} = 'version=on&debugenv=on' ;
  13074. is( 22, get_options( $mysync ), 'get_options cgi context: QUERY_STRING => 22' ) ;
  13075. is( 1, $mysync->{ version }, 'get_options cgi context: --version => 1' ) ;
  13076. # debugenv is not allowed in cgi context
  13077. is( undef, $mysync->{debugenv}, 'get_options cgi context: $mysync->{debugenv} => undef' ) ;
  13078. # QUERY_STRING in this test is only for return value of get_options
  13079. # Have to think harder, GET/POST context, is this return value a good thing?
  13080. local $ENV{'QUERY_STRING'} = 'host1=test1.lamiral.info&user1=test1' ;
  13081. $mysync->{cgi} = CGI->new( 'host1=test1.lamiral.info&user1=test1' ) ;
  13082. is( 36, get_options( $mysync, ), 'get_options cgi context: QUERY_STRING => 36' ) ;
  13083. is( 'test1', $mysync->{user1}, 'get_options cgi context: $mysync->{user1} => test1' ) ;
  13084. #local $ENV{'QUERY_STRING'} = undef ;
  13085. # Testing @
  13086. $mysync->{cgi} = CGI->new( 'blabla=fd1' ) ;
  13087. get_options( $mysync ) ;
  13088. is_deeply( [ 'fd1' ], [ @blabla ], 'get_options cgi context: @blabla => fd1' ) ;
  13089. $mysync->{cgi} = CGI->new( 'blabla=fd1&blabla=fd2' ) ;
  13090. get_options( $mysync ) ;
  13091. is_deeply( [ 'fd1', 'fd2' ], [ @blabla ], 'get_options cgi context: @blabla => fd1, fd2' ) ;
  13092. # Testing s@ as ref
  13093. $mysync->{cgi} = CGI->new( 'folder=fd1' ) ;
  13094. get_options( $mysync ) ;
  13095. is_deeply( [ 'fd1' ], $mysync->{ folder }, 'get_options cgi context: $mysync->{ folder } => fd1' ) ;
  13096. $mysync->{cgi} = CGI->new( 'folder=fd1&folder=fd2' ) ;
  13097. get_options( $mysync ) ;
  13098. is_deeply( [ 'fd1', 'fd2' ], $mysync->{ folder }, 'get_options cgi context: $mysync->{ folder } => fd1, fd2' ) ;
  13099. # Testing %
  13100. $mysync->{cgi} = CGI->new( 'f1f2h=s1=d1&f1f2h=s2=d2&f1f2h=s3=d3' ) ;
  13101. get_options( $mysync ) ;
  13102. is_deeply( { 's1' => 'd1', 's2' => 'd2', 's3' => 'd3' },
  13103. $mysync->{f1f2h}, 'get_options cgi context: f1f2h => s1=d1 s2=d2 s3=d3' ) ;
  13104. # Testing boolean ! with --noxxx, doesnot work
  13105. $mysync->{cgi} = CGI->new( 'nodry=on' ) ;
  13106. get_options( $mysync ) ;
  13107. is( undef, $mysync->{dry}, 'get_options cgi context: --nodry => $mysync->{dry} => undef' ) ;
  13108. $mysync->{cgi} = CGI->new( 'host1=example.com' ) ;
  13109. get_options( $mysync ) ;
  13110. is( 'example.com', $mysync->{host1}, 'get_options cgi context: --host1=example.com => $mysync->{host1} => example.com' ) ;
  13111. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  13112. $mysync->{cgi} = CGI->new( 'simulong=' ) ;
  13113. get_options( $mysync ) ;
  13114. is( undef, $mysync->{simulong}, 'get_options cgi context: --simulong= => $mysync->{simulong} => undef' ) ;
  13115. $mysync->{cgi} = CGI->new( 'simulong' ) ;
  13116. get_options( $mysync ) ;
  13117. is( undef, $mysync->{simulong}, 'get_options cgi context: --simulong => $mysync->{simulong} => undef' ) ;
  13118. $mysync->{cgi} = CGI->new( 'simulong=4' ) ;
  13119. get_options( $mysync ) ;
  13120. is( 4, $mysync->{simulong}, 'get_options cgi context: --simulong=4 => $mysync->{simulong} => 4' ) ;
  13121. is( undef, $mysync->{ folder }, 'get_options cgi context: --simulong=4 => $mysync->{ folder } => undef' ) ;
  13122. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  13123. $mysync ={} ;
  13124. $mysync->{cgi} = CGI->new( 'justfoldersizes=on' ) ;
  13125. get_options( $mysync ) ;
  13126. is( 1, $mysync->{ justfoldersizes }, 'get_options cgi context: --justfoldersizes=1 => justfoldersizes => 1' ) ;
  13127. myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  13128. note( 'Leaving tests_get_options_cgi_context()' ) ;
  13129. return ;
  13130. }
  13131. sub get_options_cgi
  13132. {
  13133. # In CGI context arguments are not in @ARGV but in QUERY_STRING variable (with GET).
  13134. my $mysync = shift @ARG ;
  13135. $mysync->{cgi} || return ;
  13136. my @arguments = @ARG ;
  13137. # final 0 is used to print usage when no option is given
  13138. my $numopt = length $ENV{'QUERY_STRING'} || 1 ;
  13139. $mysync->{f1f2h} = {} ;
  13140. my $opt_ret = myGetOptions(
  13141. $mysync,
  13142. \@arguments,
  13143. 'abort' => \$mysync->{abort},
  13144. 'host1=s' => \$mysync->{ host1 },
  13145. 'host2=s' => \$mysync->{ host2 },
  13146. 'user1=s' => \$mysync->{ user1 },
  13147. 'user2=s' => \$mysync->{ user2 },
  13148. 'password1=s' => \$mysync->{password1},
  13149. 'password2=s' => \$mysync->{password2},
  13150. 'dry!' => \$mysync->{dry},
  13151. 'version' => \$mysync->{version},
  13152. 'ssl1!' => \$mysync->{ssl1},
  13153. 'ssl2!' => \$mysync->{ssl2},
  13154. 'tls1!' => \$mysync->{tls1},
  13155. 'tls2!' => \$mysync->{tls2},
  13156. 'justlogin!' => \$mysync->{justlogin},
  13157. 'justconnect!' => \$mysync->{justconnect},
  13158. 'addheader!' => \$mysync->{addheader},
  13159. 'automap!' => \$mysync->{automap},
  13160. 'justautomap!' => \$mysync->{justautomap},
  13161. 'gmail1' => \$mysync->{gmail1},
  13162. 'gmail2' => \$mysync->{gmail2},
  13163. 'office1' => \$mysync->{office1},
  13164. 'office2' => \$mysync->{office2},
  13165. 'exchange1' => \$mysync->{exchange1},
  13166. 'exchange2' => \$mysync->{exchange2},
  13167. 'domino1' => \$mysync->{domino1},
  13168. 'domino2' => \$mysync->{domino2},
  13169. 'f1f2=s@' => \$mysync->{f1f2},
  13170. 'f1f2h=s%' => \$mysync->{f1f2h},
  13171. 'folder=s@' => \$mysync->{ folder },
  13172. 'blabla=s' => \@blabla,
  13173. 'testslive!' => \$mysync->{testslive},
  13174. 'testslive6!' => \$mysync->{testslive6},
  13175. 'releasecheck!' => \$mysync->{releasecheck},
  13176. 'simulong=i' => \$mysync->{simulong},
  13177. 'debugsleep=f' => \$mysync->{debugsleep},
  13178. 'subfolder1=s' => \$mysync->{ subfolder1 },
  13179. 'subfolder2=s' => \$mysync->{ subfolder2 },
  13180. 'justfolders!' => \$mysync->{ justfolders },
  13181. 'justfoldersizes!' => \$mysync->{ justfoldersizes },
  13182. 'delete1!' => \$mysync->{ delete1 },
  13183. 'delete2!' => \$mysync->{ delete2 },
  13184. 'delete2duplicates!' => \$mysync->{ delete2duplicates },
  13185. 'tail!' => \$mysync->{tail},
  13186. # blabla and f1f2h=s% could be removed but
  13187. # tests_get_options_cgi() should be split before
  13188. # with a sub tests_myGetOptions()
  13189. ) ;
  13190. $mysync->{ debug } and output( $mysync, "get options: [$opt_ret][$numopt]\n" ) ;
  13191. if ( ! $opt_ret ) {
  13192. return ;
  13193. }
  13194. return $numopt ;
  13195. }
  13196. sub get_options_cmd
  13197. {
  13198. my $mysync = shift @ARG ;
  13199. my @arguments = @ARG ;
  13200. my $mycgi = $mysync->{cgi} ;
  13201. # final 0 is used to print usage when no option is given on command line
  13202. my $numopt = scalar @arguments || 0 ;
  13203. my $argv = join "\x00", @arguments ;
  13204. if ( $argv =~ m/-delete\x002/x ) {
  13205. output( $mysync, "May be you mean --delete2 instead of --delete 2\n" ) ;
  13206. return ;
  13207. }
  13208. $mysync->{f1f2h} = {} ;
  13209. my $opt_ret = myGetOptions(
  13210. $mysync,
  13211. \@arguments,
  13212. 'debug!' => \$mysync->{ debug },
  13213. 'debuglist!' => \$debuglist,
  13214. 'debugcontent!' => \$debugcontent,
  13215. 'debugsleep=f' => \$mysync->{debugsleep},
  13216. 'debugflags!' => \$debugflags,
  13217. 'debugimap!' => \$debugimap,
  13218. 'debugimap1!' => \$debugimap1,
  13219. 'debugimap2!' => \$debugimap2,
  13220. 'debugdev!' => \$debugdev,
  13221. 'debugmemory!' => \$mysync->{debugmemory},
  13222. 'debugfolders!' => \$mysync->{debugfolders},
  13223. 'debugssl=i' => \$mysync->{debugssl},
  13224. 'debugcgi!' => \$debugcgi,
  13225. 'debugenv!' => \$mysync->{debugenv},
  13226. 'debugsig!' => \$mysync->{debugsig},
  13227. 'debuglabels!' => \$mysync->{debuglabels},
  13228. 'simulong=i' => \$mysync->{simulong},
  13229. 'abort' => \$mysync->{abort},
  13230. 'host1=s' => \$mysync->{ host1 },
  13231. 'host2=s' => \$mysync->{ host2 },
  13232. 'port1=i' => \$mysync->{port1},
  13233. 'port2=i' => \$mysync->{port2},
  13234. 'inet4|ipv4' => \$mysync->{inet4},
  13235. 'inet6|ipv6' => \$mysync->{inet6},
  13236. 'user1=s' => \$mysync->{ user1 },
  13237. 'user2=s' => \$mysync->{ user2 },
  13238. 'gmail1' => \$mysync->{gmail1},
  13239. 'gmail2' => \$mysync->{gmail2},
  13240. 'office1' => \$mysync->{office1},
  13241. 'office2' => \$mysync->{office2},
  13242. 'exchange1' => \$mysync->{exchange1},
  13243. 'exchange2' => \$mysync->{exchange2},
  13244. 'domino1' => \$mysync->{domino1},
  13245. 'domino2' => \$mysync->{domino2},
  13246. 'domain1=s' => \$domain1,
  13247. 'domain2=s' => \$domain2,
  13248. 'password1=s' => \$mysync->{password1},
  13249. 'password2=s' => \$mysync->{password2},
  13250. 'passfile1=s' => \$mysync->{ passfile1 },
  13251. 'passfile2=s' => \$mysync->{ passfile2 },
  13252. 'authmd5!' => \$authmd5,
  13253. 'authmd51!' => \$authmd51,
  13254. 'authmd52!' => \$authmd52,
  13255. 'sep1=s' => \$mysync->{ sep1 },
  13256. 'sep2=s' => \$mysync->{ sep2 },
  13257. 'sanitize!' => \$mysync->{ sanitize },
  13258. 'folder=s@' => \$mysync->{ folder },
  13259. 'folderrec=s' => \@folderrec,
  13260. 'include=s' => \@include,
  13261. 'exclude=s' => \@exclude,
  13262. 'noexclude' => \$mysync->{noexclude},
  13263. 'folderfirst=s' => \@folderfirst,
  13264. 'folderlast=s' => \@folderlast,
  13265. 'prefix1=s' => \$prefix1,
  13266. 'prefix2=s' => \$prefix2,
  13267. 'subfolder1=s' => \$mysync->{ subfolder1 },
  13268. 'subfolder2=s' => \$mysync->{ subfolder2 },
  13269. 'fixslash2!' => \$mysync->{ fixslash2 },
  13270. 'fixInboxINBOX!' => \$fixInboxINBOX,
  13271. 'regextrans2=s@' => \$mysync->{ regextrans2 },
  13272. 'mixfolders!' => \$mixfolders,
  13273. 'skipemptyfolders!' => \$mysync->{ skipemptyfolders },
  13274. 'regexmess=s' => \@regexmess,
  13275. 'noregexmess' => \$mysync->{noregexmess},
  13276. 'skipmess=s' => \@skipmess,
  13277. 'pipemess=s' => \@pipemess,
  13278. 'pipemesscheck!' => \$pipemesscheck,
  13279. 'disarmreadreceipts!' => \$disarmreadreceipts,
  13280. 'regexflag=s' => \@regexflag,
  13281. 'noregexflag' => \$mysync->{noregexflag},
  13282. 'filterflags!' => \$filterflags,
  13283. 'flagscase!' => \$flagscase,
  13284. 'syncflagsaftercopy!' => \$syncflagsaftercopy,
  13285. 'resyncflags!' => \$mysync->{ resyncflags },
  13286. 'synclabels!' => \$mysync->{ synclabels },
  13287. 'resynclabels!' => \$mysync->{ resynclabels },
  13288. 'delete|delete1!' => \$mysync->{ delete1 },
  13289. 'delete2!' => \$mysync->{ delete2 },
  13290. 'delete2duplicates!' => \$mysync->{ delete2duplicates },
  13291. 'delete2folders!' => \$delete2folders,
  13292. 'delete2foldersonly=s' => \$delete2foldersonly,
  13293. 'delete2foldersbutnot=s' => \$delete2foldersbutnot,
  13294. 'syncinternaldates!' => \$syncinternaldates,
  13295. 'idatefromheader!' => \$idatefromheader,
  13296. 'syncacls!' => \$syncacls,
  13297. 'maxsize=i' => \$mysync->{ maxsize },
  13298. 'appendlimit=i' => \$mysync->{ appendlimit },
  13299. 'truncmess=i' => \$mysync->{ truncmess },
  13300. 'minsize=i' => \$minsize,
  13301. 'maxage=f' => \$maxage,
  13302. 'minage=f' => \$minage,
  13303. 'search=s' => \$search,
  13304. 'search1=s' => \$mysync->{ search1 },
  13305. 'search2=s' => \$mysync->{ search2 },
  13306. 'foldersizes!' => \$mysync->{ foldersizes },
  13307. 'foldersizesatend!' => \$mysync->{ foldersizesatend },
  13308. 'dry!' => \$mysync->{dry},
  13309. 'expunge1|expunge!' => \$mysync->{ expunge1 },
  13310. 'expunge2!' => \$mysync->{ expunge2 },
  13311. 'uidexpunge2!' => \$mysync->{ uidexpunge2 },
  13312. 'subscribed' => \$subscribed,
  13313. 'subscribe!' => \$subscribe,
  13314. 'subscribeall|subscribe_all!' => \$subscribeall,
  13315. 'justbanner!' => \$justbanner,
  13316. 'justfolders!'=> \$mysync->{ justfolders },
  13317. 'justfoldersizes!' => \$mysync->{ justfoldersizes },
  13318. 'fast!' => \$fast,
  13319. 'version' => \$mysync->{version},
  13320. 'help' => \$help,
  13321. 'timeout=i' => \$timeout,
  13322. 'timeout1=i' => \$mysync->{h1}->{timeout},
  13323. 'timeout2=i' => \$mysync->{h2}->{timeout},
  13324. 'skipheader=s' => \$skipheader,
  13325. 'useheader=s' => \@useheader,
  13326. 'wholeheaderifneeded!' => \$wholeheaderifneeded,
  13327. 'messageidnodomain!' => \$messageidnodomain,
  13328. 'skipsize!' => \$skipsize,
  13329. 'allowsizemismatch!' => \$allowsizemismatch,
  13330. 'fastio1!' => \$fastio1,
  13331. 'fastio2!' => \$fastio2,
  13332. 'sslcheck!' => \$mysync->{sslcheck},
  13333. 'ssl1!' => \$mysync->{ssl1},
  13334. 'ssl2!' => \$mysync->{ssl2},
  13335. 'ssl1_ssl_version=s' => \$mysync->{h1}->{sslargs}->{SSL_version},
  13336. 'ssl2_ssl_version=s' => \$mysync->{h2}->{sslargs}->{SSL_version},
  13337. 'sslargs1=s%' => \$mysync->{h1}->{sslargs},
  13338. 'sslargs2=s%' => \$mysync->{h2}->{sslargs},
  13339. 'tls1!' => \$mysync->{tls1},
  13340. 'tls2!' => \$mysync->{tls2},
  13341. 'uid1!' => \$uid1,
  13342. 'uid2!' => \$uid2,
  13343. 'authmech1=s' => \$authmech1,
  13344. 'authmech2=s' => \$authmech2,
  13345. 'authuser1=s' => \$authuser1,
  13346. 'authuser2=s' => \$authuser2,
  13347. 'proxyauth1' => \$proxyauth1,
  13348. 'proxyauth2' => \$proxyauth2,
  13349. 'split1=i' => \$split1,
  13350. 'split2=i' => \$split2,
  13351. 'buffersize=i' => \$buffersize,
  13352. 'reconnectretry1=i' => \$reconnectretry1,
  13353. 'reconnectretry2=i' => \$reconnectretry2,
  13354. 'tests!' => \$mysync->{ tests },
  13355. 'testsdebug|tests_debug!' => \$mysync->{ testsdebug },
  13356. 'testsunit=s@' => \$mysync->{testsunit},
  13357. 'testslive!' => \$mysync->{testslive},
  13358. 'testslive6!' => \$mysync->{testslive6},
  13359. 'justlogin!' => \$mysync->{justlogin},
  13360. 'justconnect!' => \$mysync->{justconnect},
  13361. 'tmpdir=s' => \$mysync->{ tmpdir },
  13362. 'pidfile=s' => \$mysync->{pidfile},
  13363. 'pidfilelocking!' => \$mysync->{pidfilelocking},
  13364. 'sigexit=s@' => \$mysync->{ sigexit },
  13365. 'sigreconnect=s@' => \$mysync->{ sigreconnect },
  13366. 'sigignore=s@' => \$mysync->{ sigignore },
  13367. 'releasecheck!' => \$mysync->{releasecheck},
  13368. 'modulesversion|modules_version!' => \$modulesversion,
  13369. 'usecache!' => \$usecache,
  13370. 'cacheaftercopy!' => \$cacheaftercopy,
  13371. 'debugcache!' => \$debugcache,
  13372. 'useuid!' => \$useuid,
  13373. 'addheader!' => \$mysync->{addheader},
  13374. 'exitwhenover=i' => \$mysync->{ exitwhenover },
  13375. 'checkselectable!' => \$mysync->{ checkselectable },
  13376. 'checkfoldersexist!' => \$mysync->{ checkfoldersexist },
  13377. 'checkmessageexists!' => \$checkmessageexists,
  13378. 'expungeaftereach!' => \$mysync->{ expungeaftereach },
  13379. 'abletosearch!' => \$mysync->{abletosearch},
  13380. 'abletosearch1!' => \$mysync->{abletosearch1},
  13381. 'abletosearch2!' => \$mysync->{abletosearch2},
  13382. 'showpasswords!' => \$mysync->{showpasswords},
  13383. 'maxlinelength=i' => \$maxlinelength,
  13384. 'maxlinelengthcmd=s' => \$maxlinelengthcmd,
  13385. 'minmaxlinelength=i' => \$minmaxlinelength,
  13386. 'debugmaxlinelength!' => \$debugmaxlinelength,
  13387. 'fixcolonbug!' => \$fixcolonbug,
  13388. 'create_folder_old!' => \$create_folder_old,
  13389. 'maxmessagespersecond=f' => \$mysync->{maxmessagespersecond},
  13390. 'maxbytespersecond=i' => \$mysync->{maxbytespersecond},
  13391. 'maxbytesafter=i' => \$mysync->{maxbytesafter},
  13392. 'maxsleep=f' => \$mysync->{maxsleep},
  13393. 'skipcrossduplicates!' => \$skipcrossduplicates,
  13394. 'debugcrossduplicates!' => \$debugcrossduplicates,
  13395. 'log!' => \$mysync->{log},
  13396. 'tail!' => \$mysync->{tail},
  13397. 'logfile=s' => \$mysync->{logfile},
  13398. 'logdir=s' => \$mysync->{logdir},
  13399. 'errorsmax=i' => \$mysync->{errorsmax},
  13400. 'errorsdump!' => \$mysync->{errorsdump},
  13401. 'fetch_hash_set=s' => \$fetch_hash_set,
  13402. 'automap!' => \$mysync->{automap},
  13403. 'justautomap!' => \$mysync->{justautomap},
  13404. 'id!' => \$mysync->{id},
  13405. 'f1f2=s@' => \$mysync->{f1f2},
  13406. 'nof1f2' => \$mysync->{nof1f2},
  13407. 'f1f2h=s%' => \$mysync->{f1f2h},
  13408. 'justfolderlists!' => \$mysync->{justfolderlists},
  13409. 'delete1emptyfolders' => \$mysync->{delete1emptyfolders},
  13410. ) ;
  13411. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  13412. $mysync->{ debug } and output( $mysync, "get options: [$opt_ret][$numopt]\n" ) ;
  13413. my $numopt_after = scalar @arguments ;
  13414. #myprint( "get options: [$opt_ret][$numopt][$numopt_after]\n" ) ;
  13415. if ( $numopt_after ) {
  13416. myprint(
  13417. "Extra arguments found: @arguments\n",
  13418. "It usually means a quoting issue in the command line ",
  13419. "or some misspelling options.\n",
  13420. ) ;
  13421. return ;
  13422. }
  13423. if ( ! $opt_ret ) {
  13424. return ;
  13425. }
  13426. return $numopt ;
  13427. }
  13428. sub tests_get_options
  13429. {
  13430. note( 'Entering tests_get_options()' ) ;
  13431. # CAVEAT: still setting global variables, be careful
  13432. # with tests, the context increases! $debug stays on for example.
  13433. # API:
  13434. # * input arguments: two ways, command line or CGI
  13435. # * the program arguments
  13436. # * QUERY_STRING env variable
  13437. # * return
  13438. # * undef if bad things happened like
  13439. # * options not known
  13440. # * --delete 2 input
  13441. # * number of arguments or QUERY_STRING length
  13442. my $mysync = { } ;
  13443. is( undef, get_options( $mysync, qw( --noexist ) ), 'get_options: --noexist => undef' ) ;
  13444. is( undef, $mysync->{ noexist }, 'get_options: --noexist => undef' ) ;
  13445. $mysync = { } ;
  13446. is( undef, get_options( $mysync, qw( --lalala --noexist --version ) ), 'get_options: --lalala --noexist --version => undef' ) ;
  13447. is( 1, $mysync->{ version }, 'get_options: --version => 1' ) ;
  13448. is( undef, $mysync->{ noexist }, 'get_options: --noexist => undef' ) ;
  13449. $mysync = { } ;
  13450. is( 1, get_options( $mysync, qw( --delete2 ) ), 'get_options: --delete2 => 1' ) ;
  13451. is( 1, $mysync->{ delete2 }, 'get_options: --delete2 => var delete2 = 1' ) ;
  13452. $mysync = { } ;
  13453. is( undef, get_options( $mysync, qw( --delete 2 ) ), 'get_options: --delete 2 => var undef' ) ;
  13454. is( undef, $mysync->{ delete1 }, 'get_options: --delete 2 => var still undef ; good!' ) ;
  13455. $mysync = { } ;
  13456. is( undef, get_options( $mysync, "--delete 2" ), 'get_options: --delete 2 => undef' ) ;
  13457. is( 1, get_options( $mysync, "--version" ), 'get_options: --version => 1' ) ;
  13458. is( 1, get_options( $mysync, "--help" ), 'get_options: --help => 1' ) ;
  13459. is( undef, get_options( $mysync, qw( --noexist --version ) ), 'get_options: --debug --noexist --version => undef' ) ;
  13460. is( 1, get_options( $mysync, qw( --version ) ), 'get_options: --version => 1' ) ;
  13461. is( undef, get_options( $mysync, qw( extra ) ), 'get_options: extra => undef' ) ;
  13462. is( undef, get_options( $mysync, qw( extra1 --version extra2 ) ), 'get_options: extra1 --version extra2 => undef' ) ;
  13463. $mysync = { } ;
  13464. is( 2, get_options( $mysync, qw( --host1 HOST_01) ), 'get_options: --host1 HOST_01 => 1' ) ;
  13465. is( 'HOST_01', $mysync->{ host1 }, 'get_options: --host1 HOST_01 => HOST_01' ) ;
  13466. #myprint( Data::Dumper->Dump( [ $mysync ] ) ) ;
  13467. note( 'Leaving tests_get_options()' ) ;
  13468. return ;
  13469. }
  13470. sub get_options
  13471. {
  13472. my $mysync = shift @ARG ;
  13473. my @arguments = @ARG ;
  13474. #myprint( "1 mysync: ", Data::Dumper->Dump( [ $mysync ] ) ) ;
  13475. my $ret ;
  13476. if ( under_cgi_context( ) ) {
  13477. # CGI context
  13478. $ret = get_options_cgi( $mysync, @arguments ) ;
  13479. }else{
  13480. # Command line context ;
  13481. $ret = get_options_cmd( $mysync, @arguments ) ;
  13482. } ;
  13483. #myprint( "2 mysync: ", Data::Dumper->Dump( [ $mysync ] ) ) ;
  13484. foreach my $key ( sort keys %{ $mysync } ) {
  13485. if ( ! defined $mysync->{$key} ) {
  13486. delete $mysync->{$key} ;
  13487. next ;
  13488. }
  13489. if ( 'ARRAY' eq ref( $mysync->{$key} )
  13490. and 0 == scalar( @{ $mysync->{$key} } ) ) {
  13491. delete $mysync->{$key} ;
  13492. }
  13493. }
  13494. return $ret ;
  13495. }
  13496. sub testunitsession
  13497. {
  13498. my $mysync = shift ;
  13499. if ( ! $mysync ) { return ; }
  13500. if ( ! $mysync->{ testsunit } ) { return ; }
  13501. my @functions = @{ $mysync->{ testsunit } } ;
  13502. if ( ! @functions ) { return ; }
  13503. SKIP: {
  13504. if ( ! @functions ) { skip 'No test in normal run' ; }
  13505. testsunit( @functions ) ;
  13506. done_testing( ) ;
  13507. }
  13508. return ;
  13509. }
  13510. sub tests_count_0s
  13511. {
  13512. note( 'Entering tests_count_zeros()' ) ;
  13513. is( 0, count_0s( ), 'count_0s: no parameters => 0' ) ;
  13514. is( 1, count_0s( 0 ), 'count_0s: 0 => 1' ) ;
  13515. is( 0, count_0s( 1 ), 'count_0s: 1 => 0' ) ;
  13516. is( 1, count_0s( 1, 0, 1 ), 'count_0s: 1, 0, 1 => 1' ) ;
  13517. is( 2, count_0s( 1, 0, 1, 0 ), 'count_0s: 1, 0, 1, 0 => 2' ) ;
  13518. note( 'Leaving tests_count_zeros()' ) ;
  13519. return ;
  13520. }
  13521. sub count_0s
  13522. {
  13523. my @array = @ARG ;
  13524. if ( ! @array ) { return 0 ; }
  13525. my $nb_zeros = 0 ;
  13526. map { $_ == 0 and $nb_zeros += 1 } @array ;
  13527. return $nb_zeros ;
  13528. }
  13529. sub tests_report_failures
  13530. {
  13531. note( 'Entering tests_report_failures()' ) ;
  13532. is( undef, report_failures( ), 'report_failures: no parameters => undef' ) ;
  13533. is( "nb 1 - first\n", report_failures( ({'ok' => 0, name => 'first'}) ), 'report_failures: "first" failed => nb 1 - first' ) ;
  13534. is( q{}, report_failures( ( {'ok' => 1, name => 'first'} ) ), 'report_failures: "first" success =>' ) ;
  13535. is( "nb 2 - second\n", report_failures( ( {'ok' => 1, name => 'second'}, {'ok' => 0, name => 'second'} ) ), 'report_failures: "second" failed => nb 2 - second' ) ;
  13536. 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' ) ;
  13537. note( 'Leaving tests_report_failures()' ) ;
  13538. return ;
  13539. }
  13540. sub report_failures
  13541. {
  13542. my @details = @ARG ;
  13543. if ( ! @details ) { return ; }
  13544. my $counter = 1 ;
  13545. my $report = q{} ;
  13546. foreach my $details ( @details ) {
  13547. if ( ! $details->{ 'ok' } ) {
  13548. my $name = $details->{ 'name' } || 'NONAME' ;
  13549. $report .= "nb $counter - $name\n" ;
  13550. }
  13551. $counter += 1 ;
  13552. }
  13553. return $report ;
  13554. }
  13555. sub tests_true
  13556. {
  13557. note( 'Entering tests_true()' ) ;
  13558. is( 1, 1, 'true: 1 is 1' ) ;
  13559. note( 'Leaving tests_true()' ) ;
  13560. return ;
  13561. }
  13562. sub tests_testsunit
  13563. {
  13564. note( 'Entering tests_testunit()' ) ;
  13565. is( undef, testsunit( ), 'testsunit: no parameters => undef' ) ;
  13566. is( undef, testsunit( undef ), 'testsunit: an undef parameter => undef' ) ;
  13567. is( undef, testsunit( q{} ), 'testsunit: an empty parameter => undef' ) ;
  13568. is( undef, testsunit( 'idonotexist' ), 'testsunit: a do not exist function as parameter => undef' ) ;
  13569. is( undef, testsunit( 'tests_true' ), 'testsunit: tests_true => undef' ) ;
  13570. note( 'Leaving tests_testunit()' ) ;
  13571. return ;
  13572. }
  13573. sub testsunit
  13574. {
  13575. my @functions = @ARG ;
  13576. if ( ! @functions ) { #
  13577. myprint( "testsunit warning: no argument given\n" ) ;
  13578. return ;
  13579. }
  13580. foreach my $function ( @functions ) {
  13581. if ( ! $function ) {
  13582. myprint( "testsunit warning: argument is empty\n" ) ;
  13583. next ;
  13584. }
  13585. if ( ! exists &$function ) {
  13586. myprint( "testsunit warning: function $function does not exist\n" ) ;
  13587. next ;
  13588. }
  13589. if ( ! defined &$function ) {
  13590. myprint( "testsunit warning: function $function is not defined\n" ) ;
  13591. next ;
  13592. }
  13593. my $function_ref = \&{ $function } ;
  13594. &$function_ref() ;
  13595. }
  13596. return ;
  13597. }
  13598. sub testsdebug
  13599. {
  13600. # Now a little obsolete since there is
  13601. # imapsync ... --testsunit "anyfunction"
  13602. my $mysync = shift ;
  13603. if ( ! $mysync->{ testsdebug } ) { return ; }
  13604. SKIP: {
  13605. if ( ! $mysync->{ testsdebug } ) {
  13606. skip 'No test in normal run' ;
  13607. }
  13608. note( 'Entering testsdebug()' ) ;
  13609. #ok( ( ( not -d 'W/tmp/tests' ) or rmtree( 'W/tmp/tests/' ) ), 'testsdebug: rmtree W/tmp/tests' ) ;
  13610. #tests_check_binary_embed_all_dyn_libs( ) ;
  13611. #tests_killpid_by_parent( ) ;
  13612. #tests_killpid_by_brother( ) ;
  13613. #tests_kill_zero( ) ;
  13614. #tests_connect_socket( ) ;
  13615. tests_probe_imapssl( ) ;
  13616. #tests_always_fail( ) ;
  13617. note( 'Leaving testsdebug()' ) ;
  13618. done_testing( ) ;
  13619. }
  13620. return ;
  13621. }
  13622. sub tests
  13623. {
  13624. my $mysync = shift ;
  13625. if ( ! $mysync->{ tests } ) { return ; }
  13626. SKIP: {
  13627. skip 'No test in normal run' if ( ! $mysync->{ tests } ) ;
  13628. note( 'Entering tests()' ) ;
  13629. tests_folder_routines( ) ;
  13630. tests_compare_lists( ) ;
  13631. tests_regexmess( ) ;
  13632. tests_skipmess( ) ;
  13633. tests_flags_regex();
  13634. tests_ucsecond( ) ;
  13635. tests_permanentflags();
  13636. tests_flags_filter( ) ;
  13637. tests_separator_invert( ) ;
  13638. tests_imap2_folder_name( ) ;
  13639. tests_command_line_nopassword( ) ;
  13640. tests_good_date( ) ;
  13641. tests_max( ) ;
  13642. tests_remove_not_num();
  13643. tests_memory_consumption( ) ;
  13644. tests_is_a_release_number();
  13645. tests_imapsync_basename();
  13646. tests_list_keys_in_2_not_in_1();
  13647. tests_convert_sep_to_slash( ) ;
  13648. tests_match_a_cache_file( ) ;
  13649. tests_cache_map( ) ;
  13650. tests_get_cache( ) ;
  13651. tests_clean_cache( ) ;
  13652. tests_clean_cache_2( ) ;
  13653. tests_touch( ) ;
  13654. tests_flagscase( ) ;
  13655. tests_mkpath( ) ;
  13656. tests_extract_header( ) ;
  13657. tests_decompose_header( ) ;
  13658. tests_epoch( ) ;
  13659. tests_add_header( ) ;
  13660. tests_cache_dir_fix( ) ;
  13661. tests_cache_dir_fix_win( ) ;
  13662. tests_filter_forbidden_characters( ) ;
  13663. tests_cache_folder( ) ;
  13664. tests_time_remaining( ) ;
  13665. tests_decompose_regex( ) ;
  13666. tests_backtick( ) ;
  13667. tests_bytes_display_string( ) ;
  13668. tests_header_line_normalize( ) ;
  13669. tests_fix_Inbox_INBOX_mapping( ) ;
  13670. tests_max_line_length( ) ;
  13671. tests_subject( ) ;
  13672. tests_msgs_from_maxmin( ) ;
  13673. tests_tmpdir_has_colon_bug( ) ;
  13674. tests_sleep_max_messages( ) ;
  13675. tests_sleep_max_bytes( ) ;
  13676. tests_logfile( ) ;
  13677. tests_setlogfile( ) ;
  13678. tests_jux_utf8_old( ) ;
  13679. tests_jux_utf8( ) ;
  13680. tests_pipemess( ) ;
  13681. tests_jux_utf8_list( ) ;
  13682. tests_guess_prefix( ) ;
  13683. tests_guess_separator( ) ;
  13684. tests_format_for_imap_arg( ) ;
  13685. tests_imapsync_id( ) ;
  13686. tests_date_from_rcs( ) ;
  13687. tests_quota_extract_storage_limit_in_bytes( ) ;
  13688. tests_quota_extract_storage_current_in_bytes( ) ;
  13689. tests_guess_special( ) ;
  13690. tests_do_valid_directory( ) ;
  13691. tests_delete1emptyfolders( ) ;
  13692. tests_message_for_host2( ) ;
  13693. tests_length_ref( ) ;
  13694. tests_firstline( ) ;
  13695. tests_diff_or_NA( ) ;
  13696. tests_match_number( ) ;
  13697. tests_all_defined( ) ;
  13698. tests_special_from_folders_hash( ) ;
  13699. tests_notmatch( ) ;
  13700. tests_match( ) ;
  13701. tests_get_options( ) ;
  13702. tests_get_options_cgi_context( ) ;
  13703. tests_rand32( ) ;
  13704. tests_hashsynclocal( ) ;
  13705. tests_hashsync( ) ;
  13706. tests_output( ) ;
  13707. tests_output_reset_with( ) ;
  13708. tests_output_start( ) ;
  13709. tests_check_last_release( ) ;
  13710. tests_loadavg( ) ;
  13711. tests_cpu_number( ) ;
  13712. tests_load_and_delay( ) ;
  13713. #tests_imapsping( ) ;
  13714. #tests_tcpping( ) ;
  13715. tests_sslcheck( ) ;
  13716. tests_not_long_imapsync_version_public( ) ;
  13717. tests_reconnect_if_needed( ) ;
  13718. tests_reconnect_12_if_needed( ) ;
  13719. tests_sleep_if_needed( ) ;
  13720. tests_string_to_file( ) ;
  13721. tests_file_to_string( ) ;
  13722. tests_under_cgi_context( ) ;
  13723. tests_umask( ) ;
  13724. tests_umask_str( ) ;
  13725. tests_set_umask( ) ;
  13726. tests_createhashfileifneeded( ) ;
  13727. tests_slash_to_underscore( ) ;
  13728. tests_testsunit( ) ;
  13729. tests_count_0s( ) ;
  13730. tests_report_failures( ) ;
  13731. tests_min( ) ;
  13732. #tests_connect_socket( ) ;
  13733. #tests_resolvrev( ) ;
  13734. tests_usage( ) ;
  13735. tests_version_from_rcs( ) ;
  13736. tests_backslash_caret( ) ;
  13737. #tests_mailimapclient_connect_bug( ) ; # it fails with Mail-IMAPClient <= 3.39
  13738. tests_write_pidfile( ) ;
  13739. tests_remove_pidfile_not_running( ) ;
  13740. tests_match_a_pid_number( ) ;
  13741. tests_prefix_seperator_invertion( ) ;
  13742. tests_is_an_integer( ) ;
  13743. tests_integer_or_1( ) ;
  13744. tests_is_number( ) ;
  13745. tests_sig_install( ) ;
  13746. tests_template( ) ;
  13747. tests_split_around_equal( ) ;
  13748. tests_toggle_sleep( ) ;
  13749. tests_labels( ) ;
  13750. tests_synclabels( ) ;
  13751. tests_uidexpunge_or_expunge( ) ;
  13752. tests_appendlimit_from_capability( ) ;
  13753. tests_maxsize_setting( ) ;
  13754. tests_mock_capability( ) ;
  13755. tests_appendlimit( ) ;
  13756. tests_capability_of( ) ;
  13757. tests_search_in_array( ) ;
  13758. tests_operators_and_exclam_precedence( ) ;
  13759. tests_teelaunch( ) ;
  13760. tests_logfileprepa( ) ;
  13761. tests_useheader_suggestion( ) ;
  13762. tests_nb_messages_in_2_not_in_1( ) ;
  13763. tests_labels_add_subfolder2( ) ;
  13764. tests_labels_remove_subfolder1( ) ;
  13765. tests_resynclabels( ) ;
  13766. tests_labels_remove_special( ) ;
  13767. tests_uniq( ) ;
  13768. tests_remove_from_requested_folders( ) ;
  13769. tests_errors_log( ) ;
  13770. tests_add_subfolder1_to_folderrec( ) ;
  13771. tests_sanitize_subfolder( ) ;
  13772. tests_remove_edging_blanks( ) ;
  13773. tests_sanitize( ) ;
  13774. tests_remove_last_char_if_is( ) ;
  13775. tests_check_binary_embed_all_dyn_libs( ) ;
  13776. tests_nthline( ) ;
  13777. tests_secondline( ) ;
  13778. tests_tail( ) ;
  13779. tests_truncmess( ) ;
  13780. tests_eta( ) ;
  13781. tests_timesince( ) ;
  13782. tests_timenext( ) ;
  13783. tests_foldersize( ) ;
  13784. tests_imapsync_context( ) ;
  13785. tests_abort( ) ;
  13786. tests_probe_imapssl( ) ;
  13787. tests_mailimapclient_connect( ) ;
  13788. #tests_resolv( ) ;
  13789. # Those three are for later use, when webserver will be inside imapsync
  13790. # or will be deleted them if I abandon the project.
  13791. #tests_killpid_by_parent( ) ;
  13792. #tests_killpid_by_brother( ) ;
  13793. #tests_kill_zero( ) ;
  13794. #tests_always_fail( ) ;
  13795. done_testing( 1496 ) ;
  13796. note( 'Leaving tests()' ) ;
  13797. }
  13798. return ;
  13799. }
  13800. sub tests_template
  13801. {
  13802. note( 'Entering tests_template()' ) ;
  13803. is( undef, undef, 'template: no args => undef' ) ;
  13804. is_deeply( {}, {}, 'template: a hash is a hash' ) ;
  13805. is_deeply( [], [], 'template: an array is an array' ) ;
  13806. note( 'Leaving tests_template()' ) ;
  13807. return ;
  13808. }