imap4.py 206 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404
  1. # -*- test-case-name: twisted.mail.test.test_imap.IMAP4HelperTests -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. An IMAP4 protocol implementation
  6. @author: Jp Calderone
  7. To do::
  8. Suspend idle timeout while server is processing
  9. Use an async message parser instead of buffering in memory
  10. Figure out a way to not queue multi-message client requests (Flow? A simple callback?)
  11. Clarify some API docs (Query, etc)
  12. Make APPEND recognize (again) non-existent mailboxes before accepting the literal
  13. """
  14. import binascii
  15. import codecs
  16. import copy
  17. import functools
  18. import re
  19. import string
  20. import tempfile
  21. import time
  22. import uuid
  23. import email.utils
  24. from itertools import chain
  25. from io import BytesIO
  26. from zope.interface import implementer
  27. from twisted.protocols import basic
  28. from twisted.protocols import policies
  29. from twisted.internet import defer
  30. from twisted.internet import error
  31. from twisted.internet.defer import maybeDeferred
  32. from twisted.python import log, text
  33. from twisted.python.compat import (
  34. _bytesChr, unichr as chr, _b64decodebytes as decodebytes,
  35. _b64encodebytes as encodebytes,
  36. intToBytes, iterbytes, long, nativeString, networkString, unicode,
  37. _matchingString, _PY3, _get_async_param,
  38. )
  39. from twisted.internet import interfaces
  40. from twisted.cred import credentials
  41. from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
  42. # Re-exported for compatibility reasons
  43. from twisted.mail.interfaces import (
  44. IClientAuthentication, INamespacePresenter,
  45. IAccountIMAP as IAccount,
  46. IMessageIMAPPart as IMessagePart,
  47. IMessageIMAP as IMessage,
  48. IMessageIMAPFile as IMessageFile,
  49. ISearchableIMAPMailbox as ISearchableMailbox,
  50. IMessageIMAPCopier as IMessageCopier,
  51. IMailboxIMAPInfo as IMailboxInfo,
  52. IMailboxIMAP as IMailbox,
  53. ICloseableMailboxIMAP as ICloseableMailbox,
  54. IMailboxIMAPListener as IMailboxListener
  55. )
  56. from twisted.mail._cred import (
  57. CramMD5ClientAuthenticator,
  58. LOGINAuthenticator, LOGINCredentials,
  59. PLAINAuthenticator, PLAINCredentials)
  60. from twisted.mail._except import (
  61. IMAP4Exception, IllegalClientResponse, IllegalOperation, MailboxException,
  62. IllegalMailboxEncoding, MailboxCollision, NoSuchMailbox, ReadOnlyMailbox,
  63. UnhandledResponse, NegativeResponse, NoSupportedAuthentication,
  64. IllegalIdentifierError, IllegalQueryError, MismatchedNesting,
  65. MismatchedQuoting, IllegalServerResponse,
  66. )
  67. # locale-independent month names to use instead of strftime's
  68. _MONTH_NAMES = dict(zip(
  69. range(1, 13),
  70. "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()))
  71. def _swap(this, that, ifIs):
  72. """
  73. Swap C{this} with C{that} if C{this} is C{ifIs}.
  74. @param this: The object that may be replaced.
  75. @param that: The object that may replace C{this}.
  76. @param ifIs: An object whose identity will be compared to
  77. C{this}.
  78. """
  79. return that if this is ifIs else this
  80. def _swapAllPairs(of, that, ifIs):
  81. """
  82. Swap each element in each pair in C{of} with C{that} it is
  83. C{ifIs}.
  84. @param of: A list of 2-L{tuple}s, whose members may be the object
  85. C{that}
  86. @type of: L{list} of 2-L{tuple}s
  87. @param ifIs: An object whose identity will be compared to members
  88. of each pair in C{of}
  89. @return: A L{list} of 2-L{tuple}s with all occurences of C{ifIs}
  90. replaced with C{that}
  91. """
  92. return [(_swap(first, that, ifIs), _swap(second, that, ifIs))
  93. for first, second in of]
  94. class MessageSet(object):
  95. """
  96. A set of message identifiers usable by both L{IMAP4Client} and
  97. L{IMAP4Server} via L{IMailboxIMAP.store} and
  98. L{IMailboxIMAP.fetch}.
  99. These identifiers can be either message sequence numbers or unique
  100. identifiers. See Section 2.3.1, "Message Numbers", RFC 3501.
  101. This represents the C{sequence-set} described in Section 9,
  102. "Formal Syntax" of RFC 3501:
  103. - A L{MessageSet} can describe a single identifier, e.g.
  104. C{MessageSet(1)}
  105. - A L{MessageSet} can describe C{*} via L{None}, e.g.
  106. C{MessageSet(None)}
  107. - A L{MessageSet} can describe a range of identifiers, e.g.
  108. C{MessageSet(1, 2)}. The range is inclusive and unordered
  109. (see C{seq-range} in RFC 3501, Section 9), so that
  110. C{Message(2, 1)} is equivalent to C{MessageSet(1, 2)}, and
  111. both describe messages 1 and 2. Ranges can include C{*} by
  112. specifying L{None}, e.g. C{MessageSet(None, 1)}. In all
  113. cases ranges are normalized so that the smallest identifier
  114. comes first, and L{None} always comes last; C{Message(2, 1)}
  115. becomes C{MessageSet(1, 2)} and C{MessageSet(None, 1)}
  116. becomes C{MessageSet(1, None)}
  117. - A L{MessageSet} can describe a sequence of single
  118. identifiers and ranges, constructed by addition.
  119. C{MessageSet(1) + MessageSet(5, 10)} refers the message
  120. identified by C{1} and the messages identified by C{5}
  121. through C{10}.
  122. B{NB: The meaning of * varies, but it always represents the
  123. largest number in use}.
  124. B{For servers}: Your L{IMailboxIMAP} provider must set
  125. L{MessageSet.last} to the highest-valued identifier (unique or
  126. message sequence) before iterating over it.
  127. B{For clients}: C{*} consumes ranges smaller than it, e.g.
  128. C{MessageSet(1, 100) + MessageSet(50, None)} is equivalent to
  129. C{1:*}.
  130. @type getnext: Function taking L{int} returning L{int}
  131. @ivar getnext: A function that returns the next message number,
  132. used when iterating through the L{MessageSet}. By default, a
  133. function returning the next integer is supplied, but as this
  134. can be rather inefficient for sparse UID iterations, it is
  135. recommended to supply one when messages are requested by UID.
  136. The argument is provided as a hint to the implementation and
  137. may be ignored if it makes sense to do so (eg, if an iterator
  138. is being used that maintains its own state, it is guaranteed
  139. that it will not be called out-of-order).
  140. """
  141. _empty = []
  142. _infinity = float('inf')
  143. def __init__(self, start=_empty, end=_empty):
  144. """
  145. Create a new MessageSet()
  146. @type start: Optional L{int}
  147. @param start: Start of range, or only message number
  148. @type end: Optional L{int}
  149. @param end: End of range.
  150. """
  151. self._last = self._empty # Last message/UID in use
  152. self.ranges = [] # List of ranges included
  153. self.getnext = lambda x: x+1 # A function which will return the next
  154. # message id. Handy for UID requests.
  155. if start is self._empty:
  156. return
  157. if isinstance(start, list):
  158. self.ranges = start[:]
  159. self.clean()
  160. else:
  161. self.add(start,end)
  162. # Ooo. A property.
  163. def last():
  164. def _setLast(self, value):
  165. if self._last is not self._empty:
  166. raise ValueError("last already set")
  167. self._last = value
  168. for i, (l, h) in enumerate(self.ranges):
  169. if l is None:
  170. l = value
  171. if h is None:
  172. h = value
  173. if l > h:
  174. l, h = h, l
  175. self.ranges[i] = (l, h)
  176. self.clean()
  177. def _getLast(self):
  178. return self._last
  179. doc = '''
  180. Replaces all occurrences of "*". This should be the
  181. largest number in use. Must be set before attempting to
  182. use the MessageSet as a container.
  183. @raises: L{ValueError} if a largest value has already
  184. been set.
  185. '''
  186. return _getLast, _setLast, None, doc
  187. last = property(*last())
  188. def add(self, start, end=_empty):
  189. """
  190. Add another range
  191. @type start: L{int}
  192. @param start: Start of range, or only message number
  193. @type end: Optional L{int}
  194. @param end: End of range.
  195. """
  196. if end is self._empty:
  197. end = start
  198. if self._last is not self._empty:
  199. if start is None:
  200. start = self.last
  201. if end is None:
  202. end = self.last
  203. start, end = sorted(
  204. [start, end],
  205. key=functools.partial(_swap, that=self._infinity, ifIs=None))
  206. self.ranges.append((start, end))
  207. self.clean()
  208. def __add__(self, other):
  209. if isinstance(other, MessageSet):
  210. ranges = self.ranges + other.ranges
  211. return MessageSet(ranges)
  212. else:
  213. res = MessageSet(self.ranges)
  214. if self.last is not self._empty:
  215. res.last = self.last
  216. try:
  217. res.add(*other)
  218. except TypeError:
  219. res.add(other)
  220. return res
  221. def extend(self, other):
  222. """
  223. Extend our messages with another message or set of messages.
  224. @param other: The messages to include.
  225. @type other: L{MessageSet}, L{tuple} of two L{int}s, or a
  226. single L{int}
  227. """
  228. if isinstance(other, MessageSet):
  229. self.ranges.extend(other.ranges)
  230. self.clean()
  231. else:
  232. try:
  233. self.add(*other)
  234. except TypeError:
  235. self.add(other)
  236. return self
  237. def clean(self):
  238. """
  239. Clean ranges list, combining adjacent ranges
  240. """
  241. ranges = sorted(_swapAllPairs(self.ranges,
  242. that=self._infinity,
  243. ifIs=None))
  244. mergedRanges = [(float('-inf'), float('-inf'))]
  245. for low, high in ranges:
  246. previousLow, previousHigh = mergedRanges[-1]
  247. if previousHigh < low - 1:
  248. mergedRanges.append((low, high))
  249. continue
  250. mergedRanges[-1] = (min(previousLow, low),
  251. max(previousHigh, high))
  252. self.ranges = _swapAllPairs(mergedRanges[1:],
  253. that=None,
  254. ifIs=self._infinity)
  255. def _noneInRanges(self):
  256. """
  257. Is there a L{None} in our ranges?
  258. L{MessageSet.clean} merges overlapping or consecutive ranges.
  259. None is represents a value larger than any number. There are
  260. thus two cases:
  261. 1. C{(x, *) + (y, z)} such that C{x} is smaller than C{y}
  262. 2. C{(z, *) + (x, y)} such that C{z} is larger than C{y}
  263. (Other cases, such as C{y < x < z}, can be split into these
  264. two cases; for example C{(y - 1, y)} + C{(x, x) + (z, z + 1)})
  265. In case 1, C{* > y} and C{* > z}, so C{(x, *) + (y, z) = (x,
  266. *)}
  267. In case 2, C{z > x and z > y}, so the intervals do not merge,
  268. and the ranges are sorted as C{[(x, y), (z, *)]}. C{*} is
  269. represented as C{(*, *)}, so this is the same as 2. but with
  270. a C{z} that is greater than everything.
  271. The result is that there is a maximum of two L{None}s, and one
  272. of them has to be the high element in the last tuple in
  273. C{self.ranges}. That means checking if C{self.ranges[-1][-1]}
  274. is L{None} suffices to check if I{any} element is L{None}.
  275. @return: L{True} if L{None} is in some range in ranges and
  276. L{False} if otherwise.
  277. """
  278. return self.ranges[-1][-1] is None
  279. def __contains__(self, value):
  280. """
  281. May raise TypeError if we encounter an open-ended range
  282. @param value: Is this in our ranges?
  283. @type value: L{int}
  284. """
  285. if self._noneInRanges():
  286. raise TypeError(
  287. "Can't determine membership; last value not set")
  288. for low, high in self.ranges:
  289. if low <= value <= high:
  290. return True
  291. return False
  292. def _iterator(self):
  293. for l, h in self.ranges:
  294. l = self.getnext(l-1)
  295. while l <= h:
  296. yield l
  297. l = self.getnext(l)
  298. def __iter__(self):
  299. if self._noneInRanges():
  300. raise TypeError("Can't iterate; last value not set")
  301. return self._iterator()
  302. def __len__(self):
  303. res = 0
  304. for l, h in self.ranges:
  305. if l is None:
  306. res += 1
  307. elif h is None:
  308. raise TypeError("Can't size object; last value not set")
  309. else:
  310. res += (h - l) + 1
  311. return res
  312. def __str__(self):
  313. p = []
  314. for low, high in self.ranges:
  315. if low == high:
  316. if low is None:
  317. p.append('*')
  318. else:
  319. p.append(str(low))
  320. elif high is None:
  321. p.append('%d:*' % (low,))
  322. else:
  323. p.append('%d:%d' % (low, high))
  324. return ','.join(p)
  325. def __repr__(self):
  326. return '<MessageSet %s>' % (str(self),)
  327. def __eq__(self, other):
  328. if isinstance(other, MessageSet):
  329. return self.ranges == other.ranges
  330. return False
  331. def __ne__(self, other):
  332. return not self.__eq__(other)
  333. class LiteralString:
  334. def __init__(self, size, defered):
  335. self.size = size
  336. self.data = []
  337. self.defer = defered
  338. def write(self, data):
  339. self.size -= len(data)
  340. passon = None
  341. if self.size > 0:
  342. self.data.append(data)
  343. else:
  344. if self.size:
  345. data, passon = data[:self.size], data[self.size:]
  346. else:
  347. passon = b''
  348. if data:
  349. self.data.append(data)
  350. return passon
  351. def callback(self, line):
  352. """
  353. Call deferred with data and rest of line
  354. """
  355. self.defer.callback((b''.join(self.data), line))
  356. class LiteralFile:
  357. _memoryFileLimit = 1024 * 1024 * 10
  358. def __init__(self, size, defered):
  359. self.size = size
  360. self.defer = defered
  361. if size > self._memoryFileLimit:
  362. self.data = tempfile.TemporaryFile()
  363. else:
  364. self.data = BytesIO()
  365. def write(self, data):
  366. self.size -= len(data)
  367. passon = None
  368. if self.size > 0:
  369. self.data.write(data)
  370. else:
  371. if self.size:
  372. data, passon = data[:self.size], data[self.size:]
  373. else:
  374. passon = b''
  375. if data:
  376. self.data.write(data)
  377. return passon
  378. def callback(self, line):
  379. """
  380. Call deferred with data and rest of line
  381. """
  382. self.data.seek(0,0)
  383. self.defer.callback((self.data, line))
  384. class WriteBuffer:
  385. """
  386. Buffer up a bunch of writes before sending them all to a transport at once.
  387. """
  388. def __init__(self, transport, size=8192):
  389. self.bufferSize = size
  390. self.transport = transport
  391. self._length = 0
  392. self._writes = []
  393. def write(self, s):
  394. self._length += len(s)
  395. self._writes.append(s)
  396. if self._length > self.bufferSize:
  397. self.flush()
  398. def flush(self):
  399. if self._writes:
  400. self.transport.writeSequence(self._writes)
  401. self._writes = []
  402. self._length = 0
  403. class Command:
  404. _1_RESPONSES = (b'CAPABILITY', b'FLAGS', b'LIST', b'LSUB', b'STATUS', b'SEARCH', b'NAMESPACE')
  405. _2_RESPONSES = (b'EXISTS', b'EXPUNGE', b'FETCH', b'RECENT')
  406. _OK_RESPONSES = (b'UIDVALIDITY', b'UNSEEN', b'READ-WRITE', b'READ-ONLY', b'UIDNEXT', b'PERMANENTFLAGS')
  407. defer = None
  408. def __init__(self, command, args=None, wantResponse=(),
  409. continuation=None, *contArgs, **contKw):
  410. self.command = command
  411. self.args = args
  412. self.wantResponse = wantResponse
  413. self.continuation = lambda x: continuation(x, *contArgs, **contKw)
  414. self.lines = []
  415. def __repr__(self):
  416. return "<imap4.Command {!r} {!r} {!r} {!r} {!r}>".format(
  417. self.command, self.args, self.wantResponse, self.continuation,
  418. self.lines
  419. )
  420. def format(self, tag):
  421. if self.args is None:
  422. return b' '.join((tag, self.command))
  423. return b' '.join((tag, self.command, self.args))
  424. def finish(self, lastLine, unusedCallback):
  425. send = []
  426. unuse = []
  427. for L in self.lines:
  428. names = parseNestedParens(L)
  429. N = len(names)
  430. if (N >= 1 and names[0] in self._1_RESPONSES or
  431. N >= 2 and names[1] in self._2_RESPONSES or
  432. N >= 2 and names[0] == b'OK' and isinstance(names[1], list)
  433. and names[1][0] in self._OK_RESPONSES):
  434. send.append(names)
  435. else:
  436. unuse.append(names)
  437. d, self.defer = self.defer, None
  438. d.callback((send, lastLine))
  439. if unuse:
  440. unusedCallback(unuse)
  441. # Some constants to help define what an atom is and is not - see the grammar
  442. # section of the IMAP4 RFC - <https://tools.ietf.org/html/rfc3501#section-9>.
  443. # Some definitions (SP, CTL, DQUOTE) are also from the ABNF RFC -
  444. # <https://tools.ietf.org/html/rfc2234>.
  445. _SP = b' '
  446. _CTL = b''.join(_bytesChr(ch) for ch in chain(range(0x21), range(0x80, 0x100)))
  447. # It is easier to define ATOM-CHAR in terms of what it does not match than in
  448. # terms of what it does match.
  449. _nonAtomChars = b']\\\\(){%*"' + _SP + _CTL
  450. # _nonAtomRE is only used in Query, so it uses native strings.
  451. if _PY3:
  452. #
  453. _nativeNonAtomChars = _nonAtomChars.decode('charmap')
  454. else:
  455. _nativeNonAtomChars = _nonAtomChars
  456. _nonAtomRE = re.compile('[' + _nativeNonAtomChars + ']')
  457. # This is all the bytes that match the ATOM-CHAR from the grammar in the RFC.
  458. _atomChars = b''.join(_bytesChr(ch) for ch in list(range(0x100)) if _bytesChr(ch) not in _nonAtomChars)
  459. @implementer(IMailboxListener)
  460. class IMAP4Server(basic.LineReceiver, policies.TimeoutMixin):
  461. """
  462. Protocol implementation for an IMAP4rev1 server.
  463. The server can be in any of four states:
  464. - Non-authenticated
  465. - Authenticated
  466. - Selected
  467. - Logout
  468. """
  469. # Identifier for this server software
  470. IDENT = b'Twisted IMAP4rev1 Ready'
  471. # Number of seconds before idle timeout
  472. # Initially 1 minute. Raised to 30 minutes after login.
  473. timeOut = 60
  474. POSTAUTH_TIMEOUT = 60 * 30
  475. # Whether STARTTLS has been issued successfully yet or not.
  476. startedTLS = False
  477. # Whether our transport supports TLS
  478. canStartTLS = False
  479. # Mapping of tags to commands we have received
  480. tags = None
  481. # The object which will handle logins for us
  482. portal = None
  483. # The account object for this connection
  484. account = None
  485. # Logout callback
  486. _onLogout = None
  487. # The currently selected mailbox
  488. mbox = None
  489. # Command data to be processed when literal data is received
  490. _pendingLiteral = None
  491. # Maximum length to accept for a "short" string literal
  492. _literalStringLimit = 4096
  493. # IChallengeResponse factories for AUTHENTICATE command
  494. challengers = None
  495. # Search terms the implementation of which needs to be passed both the last
  496. # message identifier (UID) and the last sequence id.
  497. _requiresLastMessageInfo = set([b"OR", b"NOT", b"UID"])
  498. state = 'unauth'
  499. parseState = 'command'
  500. def __init__(self, chal = None, contextFactory = None, scheduler = None):
  501. if chal is None:
  502. chal = {}
  503. self.challengers = chal
  504. self.ctx = contextFactory
  505. if scheduler is None:
  506. scheduler = iterateInReactor
  507. self._scheduler = scheduler
  508. self._queuedAsync = []
  509. def capabilities(self):
  510. cap = {b'AUTH': list(self.challengers.keys())}
  511. if self.ctx and self.canStartTLS:
  512. if not self.startedTLS and interfaces.ISSLTransport(self.transport, None) is None:
  513. cap[b'LOGINDISABLED'] = None
  514. cap[b'STARTTLS'] = None
  515. cap[b'NAMESPACE'] = None
  516. cap[b'IDLE'] = None
  517. return cap
  518. def connectionMade(self):
  519. self.tags = {}
  520. self.canStartTLS = interfaces.ITLSTransport(self.transport, None) is not None
  521. self.setTimeout(self.timeOut)
  522. self.sendServerGreeting()
  523. def connectionLost(self, reason):
  524. self.setTimeout(None)
  525. if self._onLogout:
  526. self._onLogout()
  527. self._onLogout = None
  528. def timeoutConnection(self):
  529. self.sendLine(b'* BYE Autologout; connection idle too long')
  530. self.transport.loseConnection()
  531. if self.mbox:
  532. self.mbox.removeListener(self)
  533. cmbx = ICloseableMailbox(self.mbox, None)
  534. if cmbx is not None:
  535. maybeDeferred(cmbx.close).addErrback(log.err)
  536. self.mbox = None
  537. self.state = 'timeout'
  538. def rawDataReceived(self, data):
  539. self.resetTimeout()
  540. passon = self._pendingLiteral.write(data)
  541. if passon is not None:
  542. self.setLineMode(passon)
  543. # Avoid processing commands while buffers are being dumped to
  544. # our transport
  545. blocked = None
  546. def _unblock(self):
  547. commands = self.blocked
  548. self.blocked = None
  549. while commands and self.blocked is None:
  550. self.lineReceived(commands.pop(0))
  551. if self.blocked is not None:
  552. self.blocked.extend(commands)
  553. def lineReceived(self, line):
  554. if self.blocked is not None:
  555. self.blocked.append(line)
  556. return
  557. self.resetTimeout()
  558. f = getattr(self, 'parse_' + self.parseState)
  559. try:
  560. f(line)
  561. except Exception as e:
  562. self.sendUntaggedResponse(b'BAD Server error: ' + networkString(str(e)))
  563. log.err()
  564. def parse_command(self, line):
  565. args = line.split(None, 2)
  566. rest = None
  567. if len(args) == 3:
  568. tag, cmd, rest = args
  569. elif len(args) == 2:
  570. tag, cmd = args
  571. elif len(args) == 1:
  572. tag = args[0]
  573. self.sendBadResponse(tag, b'Missing command')
  574. return None
  575. else:
  576. self.sendBadResponse(None, b'Null command')
  577. return None
  578. cmd = cmd.upper()
  579. try:
  580. return self.dispatchCommand(tag, cmd, rest)
  581. except IllegalClientResponse as e:
  582. self.sendBadResponse(tag, b'Illegal syntax: ' + networkString(str(e)))
  583. except IllegalOperation as e:
  584. self.sendNegativeResponse(tag, b'Illegal operation: ' + networkString(str(e)))
  585. except IllegalMailboxEncoding as e:
  586. self.sendNegativeResponse(tag, b'Illegal mailbox name: ' + networkString(str(e)))
  587. def parse_pending(self, line):
  588. d = self._pendingLiteral
  589. self._pendingLiteral = None
  590. self.parseState = 'command'
  591. d.callback(line)
  592. def dispatchCommand(self, tag, cmd, rest, uid=None):
  593. f = self.lookupCommand(cmd)
  594. if f:
  595. fn = f[0]
  596. parseargs = f[1:]
  597. self.__doCommand(tag, fn, [self, tag], parseargs, rest, uid)
  598. else:
  599. self.sendBadResponse(tag, b'Unsupported command')
  600. def lookupCommand(self, cmd):
  601. return getattr(self, '_'.join((self.state, nativeString(cmd.upper()))), None)
  602. def __doCommand(self, tag, handler, args, parseargs, line, uid):
  603. for (i, arg) in enumerate(parseargs):
  604. if callable(arg):
  605. parseargs = parseargs[i+1:]
  606. maybeDeferred(arg, self, line).addCallback(
  607. self.__cbDispatch, tag, handler, args,
  608. parseargs, uid).addErrback(self.__ebDispatch, tag)
  609. return
  610. else:
  611. args.append(arg)
  612. if line:
  613. # Too many arguments
  614. raise IllegalClientResponse("Too many arguments for command: " + repr(line))
  615. if uid is not None:
  616. handler(uid=uid, *args)
  617. else:
  618. handler(*args)
  619. def __cbDispatch(self, result, tag, fn, args, parseargs, uid):
  620. (arg, rest) = result
  621. args.append(arg)
  622. self.__doCommand(tag, fn, args, parseargs, rest, uid)
  623. def __ebDispatch(self, failure, tag):
  624. if failure.check(IllegalClientResponse):
  625. self.sendBadResponse(tag, b'Illegal syntax: ' + networkString(str(failure.value)))
  626. elif failure.check(IllegalOperation):
  627. self.sendNegativeResponse(tag, b'Illegal operation: ' +
  628. networkString(str(failure.value)))
  629. elif failure.check(IllegalMailboxEncoding):
  630. self.sendNegativeResponse(tag, b'Illegal mailbox name: ' +
  631. networkString(str(failure.value)))
  632. else:
  633. self.sendBadResponse(tag, b'Server error: ' + networkString(str(failure.value)))
  634. log.err(failure)
  635. def _stringLiteral(self, size):
  636. if size > self._literalStringLimit:
  637. raise IllegalClientResponse(
  638. "Literal too long! I accept at most %d octets" %
  639. (self._literalStringLimit,))
  640. d = defer.Deferred()
  641. self.parseState = 'pending'
  642. self._pendingLiteral = LiteralString(size, d)
  643. self.sendContinuationRequest(
  644. networkString('Ready for %d octets of text' % size))
  645. self.setRawMode()
  646. return d
  647. def _fileLiteral(self, size):
  648. d = defer.Deferred()
  649. self.parseState = 'pending'
  650. self._pendingLiteral = LiteralFile(size, d)
  651. self.sendContinuationRequest(
  652. networkString('Ready for %d octets of data' % size))
  653. self.setRawMode()
  654. return d
  655. def arg_finalastring(self, line):
  656. """
  657. Parse an astring from line that represents a command's final
  658. argument. This special case exists to enable parsing empty
  659. string literals.
  660. @param line: A line that contains a string literal.
  661. @type line: L{bytes}
  662. @return: A 2-tuple containing the parsed argument and any
  663. trailing data, or a L{Deferred} that fires with that
  664. 2-tuple
  665. @rtype: L{tuple} of (L{bytes}, L{bytes}) or a L{Deferred}
  666. @see: https://twistedmatrix.com/trac/ticket/9207
  667. """
  668. return self.arg_astring(line, final=True)
  669. def arg_astring(self, line, final=False):
  670. """
  671. Parse an astring from the line, return (arg, rest), possibly
  672. via a deferred (to handle literals)
  673. @param line: A line that contains a string literal.
  674. @type line: L{bytes}
  675. @param final: Is this the final argument?
  676. @type final L{bool}
  677. @return: A 2-tuple containing the parsed argument and any
  678. trailing data, or a L{Deferred} that fires with that
  679. 2-tuple
  680. @rtype: L{tuple} of (L{bytes}, L{bytes}) or a L{Deferred}
  681. """
  682. line = line.strip()
  683. if not line:
  684. raise IllegalClientResponse("Missing argument")
  685. d = None
  686. arg, rest = None, None
  687. if line[0:1] == b'"':
  688. try:
  689. spam, arg, rest = line.split(b'"',2)
  690. rest = rest[1:] # Strip space
  691. except ValueError:
  692. raise IllegalClientResponse("Unmatched quotes")
  693. elif line[0:1] == b'{':
  694. # literal
  695. if line[-1:] != b'}':
  696. raise IllegalClientResponse("Malformed literal")
  697. try:
  698. size = int(line[1:-1])
  699. except ValueError:
  700. raise IllegalClientResponse(
  701. "Bad literal size: " + repr(line[1:-1]))
  702. if final and not size:
  703. return (b'', b'')
  704. d = self._stringLiteral(size)
  705. else:
  706. arg = line.split(b' ',1)
  707. if len(arg) == 1:
  708. arg.append(b'')
  709. arg, rest = arg
  710. return d or (arg, rest)
  711. # ATOM: Any CHAR except ( ) { % * " \ ] CTL SP (CHAR is 7bit)
  712. atomre = re.compile(b'(?P<atom>[' + re.escape(_atomChars) + b']+)( (?P<rest>.*$)|$)')
  713. def arg_atom(self, line):
  714. """
  715. Parse an atom from the line
  716. """
  717. if not line:
  718. raise IllegalClientResponse("Missing argument")
  719. m = self.atomre.match(line)
  720. if m:
  721. return m.group('atom'), m.group('rest')
  722. else:
  723. raise IllegalClientResponse("Malformed ATOM")
  724. def arg_plist(self, line):
  725. """
  726. Parse a (non-nested) parenthesised list from the line
  727. """
  728. if not line:
  729. raise IllegalClientResponse("Missing argument")
  730. if line[:1] != b"(":
  731. raise IllegalClientResponse("Missing parenthesis")
  732. i = line.find(b")")
  733. if i == -1:
  734. raise IllegalClientResponse("Mismatched parenthesis")
  735. return (parseNestedParens(line[1:i],0), line[i+2:])
  736. def arg_literal(self, line):
  737. """
  738. Parse a literal from the line
  739. """
  740. if not line:
  741. raise IllegalClientResponse("Missing argument")
  742. if line[:1] != b'{':
  743. raise IllegalClientResponse("Missing literal")
  744. if line[-1:] != b'}':
  745. raise IllegalClientResponse("Malformed literal")
  746. try:
  747. size = int(line[1:-1])
  748. except ValueError:
  749. raise IllegalClientResponse(
  750. "Bad literal size: {!r}".format(line[1:-1]))
  751. return self._fileLiteral(size)
  752. def arg_searchkeys(self, line):
  753. """
  754. searchkeys
  755. """
  756. query = parseNestedParens(line)
  757. # XXX Should really use list of search terms and parse into
  758. # a proper tree
  759. return (query, b'')
  760. def arg_seqset(self, line):
  761. """
  762. sequence-set
  763. """
  764. rest = b''
  765. arg = line.split(b' ',1)
  766. if len(arg) == 2:
  767. rest = arg[1]
  768. arg = arg[0]
  769. try:
  770. return (parseIdList(arg), rest)
  771. except IllegalIdentifierError as e:
  772. raise IllegalClientResponse("Bad message number " + str(e))
  773. def arg_fetchatt(self, line):
  774. """
  775. fetch-att
  776. """
  777. p = _FetchParser()
  778. p.parseString(line)
  779. return (p.result, b'')
  780. def arg_flaglist(self, line):
  781. """
  782. Flag part of store-att-flag
  783. """
  784. flags = []
  785. if line[0:1] == b'(':
  786. if line[-1:] != b')':
  787. raise IllegalClientResponse("Mismatched parenthesis")
  788. line = line[1:-1]
  789. while line:
  790. m = self.atomre.search(line)
  791. if not m:
  792. raise IllegalClientResponse("Malformed flag")
  793. if line[0:1] == b'\\' and m.start() == 1:
  794. flags.append(b'\\' + m.group('atom'))
  795. elif m.start() == 0:
  796. flags.append(m.group('atom'))
  797. else:
  798. raise IllegalClientResponse("Malformed flag")
  799. line = m.group('rest')
  800. return (flags, b'')
  801. def arg_line(self, line):
  802. """
  803. Command line of UID command
  804. """
  805. return (line, b'')
  806. def opt_plist(self, line):
  807. """
  808. Optional parenthesised list
  809. """
  810. if line.startswith(b'('):
  811. return self.arg_plist(line)
  812. else:
  813. return (None, line)
  814. def opt_datetime(self, line):
  815. """
  816. Optional date-time string
  817. """
  818. if line.startswith(b'"'):
  819. try:
  820. spam, date, rest = line.split(b'"',2)
  821. except ValueError:
  822. raise IllegalClientResponse("Malformed date-time")
  823. return (date, rest[1:])
  824. else:
  825. return (None, line)
  826. def opt_charset(self, line):
  827. """
  828. Optional charset of SEARCH command
  829. """
  830. if line[:7].upper() == b'CHARSET':
  831. arg = line.split(b' ',2)
  832. if len(arg) == 1:
  833. raise IllegalClientResponse("Missing charset identifier")
  834. if len(arg) == 2:
  835. arg.append(b'')
  836. spam, arg, rest = arg
  837. return (arg, rest)
  838. else:
  839. return (None, line)
  840. def sendServerGreeting(self):
  841. msg = (b'[CAPABILITY ' + b' '.join(self.listCapabilities()) + b'] ' +
  842. self.IDENT)
  843. self.sendPositiveResponse(message=msg)
  844. def sendBadResponse(self, tag = None, message = b''):
  845. self._respond(b'BAD', tag, message)
  846. def sendPositiveResponse(self, tag = None, message = b''):
  847. self._respond(b'OK', tag, message)
  848. def sendNegativeResponse(self, tag = None, message = b''):
  849. self._respond(b'NO', tag, message)
  850. def sendUntaggedResponse(self, message, isAsync=None, **kwargs):
  851. isAsync = _get_async_param(isAsync, **kwargs)
  852. if not isAsync or (self.blocked is None):
  853. self._respond(message, None, None)
  854. else:
  855. self._queuedAsync.append(message)
  856. def sendContinuationRequest(self, msg = b'Ready for additional command text'):
  857. if msg:
  858. self.sendLine(b'+ ' + msg)
  859. else:
  860. self.sendLine(b'+')
  861. def _respond(self, state, tag, message):
  862. if state in (b'OK', b'NO', b'BAD') and self._queuedAsync:
  863. lines = self._queuedAsync
  864. self._queuedAsync = []
  865. for msg in lines:
  866. self._respond(msg, None, None)
  867. if not tag:
  868. tag = b'*'
  869. if message:
  870. self.sendLine(b' '.join((tag, state, message)))
  871. else:
  872. self.sendLine(b' '.join((tag, state)))
  873. def listCapabilities(self):
  874. caps = [b'IMAP4rev1']
  875. for c, v in self.capabilities().items():
  876. if v is None:
  877. caps.append(c)
  878. elif len(v):
  879. caps.extend([(c + b'=' + cap) for cap in v])
  880. return caps
  881. def do_CAPABILITY(self, tag):
  882. self.sendUntaggedResponse(b'CAPABILITY ' + b' '.join(self.listCapabilities()))
  883. self.sendPositiveResponse(tag, b'CAPABILITY completed')
  884. unauth_CAPABILITY = (do_CAPABILITY,)
  885. auth_CAPABILITY = unauth_CAPABILITY
  886. select_CAPABILITY = unauth_CAPABILITY
  887. logout_CAPABILITY = unauth_CAPABILITY
  888. def do_LOGOUT(self, tag):
  889. self.sendUntaggedResponse(b'BYE Nice talking to you')
  890. self.sendPositiveResponse(tag, b'LOGOUT successful')
  891. self.transport.loseConnection()
  892. unauth_LOGOUT = (do_LOGOUT,)
  893. auth_LOGOUT = unauth_LOGOUT
  894. select_LOGOUT = unauth_LOGOUT
  895. logout_LOGOUT = unauth_LOGOUT
  896. def do_NOOP(self, tag):
  897. self.sendPositiveResponse(tag, b'NOOP No operation performed')
  898. unauth_NOOP = (do_NOOP,)
  899. auth_NOOP = unauth_NOOP
  900. select_NOOP = unauth_NOOP
  901. logout_NOOP = unauth_NOOP
  902. def do_AUTHENTICATE(self, tag, args):
  903. args = args.upper().strip()
  904. if args not in self.challengers:
  905. self.sendNegativeResponse(tag, b'AUTHENTICATE method unsupported')
  906. else:
  907. self.authenticate(self.challengers[args](), tag)
  908. unauth_AUTHENTICATE = (do_AUTHENTICATE, arg_atom)
  909. def authenticate(self, chal, tag):
  910. if self.portal is None:
  911. self.sendNegativeResponse(tag, b'Temporary authentication failure')
  912. return
  913. self._setupChallenge(chal, tag)
  914. def _setupChallenge(self, chal, tag):
  915. try:
  916. challenge = chal.getChallenge()
  917. except Exception as e:
  918. self.sendBadResponse(tag, b'Server error: ' + networkString(str(e)))
  919. else:
  920. coded = encodebytes(challenge)[:-1]
  921. self.parseState = 'pending'
  922. self._pendingLiteral = defer.Deferred()
  923. self.sendContinuationRequest(coded)
  924. self._pendingLiteral.addCallback(self.__cbAuthChunk, chal, tag)
  925. self._pendingLiteral.addErrback(self.__ebAuthChunk, tag)
  926. def __cbAuthChunk(self, result, chal, tag):
  927. try:
  928. uncoded = decodebytes(result)
  929. except binascii.Error:
  930. raise IllegalClientResponse("Malformed Response - not base64")
  931. chal.setResponse(uncoded)
  932. if chal.moreChallenges():
  933. self._setupChallenge(chal, tag)
  934. else:
  935. self.portal.login(chal, None, IAccount).addCallbacks(
  936. self.__cbAuthResp,
  937. self.__ebAuthResp,
  938. (tag,), None, (tag,), None
  939. )
  940. def __cbAuthResp(self, result, tag):
  941. (iface, avatar, logout) = result
  942. assert iface is IAccount, "IAccount is the only supported interface"
  943. self.account = avatar
  944. self.state = 'auth'
  945. self._onLogout = logout
  946. self.sendPositiveResponse(tag, b'Authentication successful')
  947. self.setTimeout(self.POSTAUTH_TIMEOUT)
  948. def __ebAuthResp(self, failure, tag):
  949. if failure.check(UnauthorizedLogin):
  950. self.sendNegativeResponse(tag, b'Authentication failed: unauthorized')
  951. elif failure.check(UnhandledCredentials):
  952. self.sendNegativeResponse(tag, b'Authentication failed: server misconfigured')
  953. else:
  954. self.sendBadResponse(tag, b'Server error: login failed unexpectedly')
  955. log.err(failure)
  956. def __ebAuthChunk(self, failure, tag):
  957. self.sendNegativeResponse(tag, b'Authentication failed: ' + networkString(str(failure.value)))
  958. def do_STARTTLS(self, tag):
  959. if self.startedTLS:
  960. self.sendNegativeResponse(tag, b'TLS already negotiated')
  961. elif self.ctx and self.canStartTLS:
  962. self.sendPositiveResponse(tag, b'Begin TLS negotiation now')
  963. self.transport.startTLS(self.ctx)
  964. self.startedTLS = True
  965. self.challengers = self.challengers.copy()
  966. if b'LOGIN' not in self.challengers:
  967. self.challengers[b'LOGIN'] = LOGINCredentials
  968. if b'PLAIN' not in self.challengers:
  969. self.challengers[b'PLAIN'] = PLAINCredentials
  970. else:
  971. self.sendNegativeResponse(tag, b'TLS not available')
  972. unauth_STARTTLS = (do_STARTTLS,)
  973. def do_LOGIN(self, tag, user, passwd):
  974. if b'LOGINDISABLED' in self.capabilities():
  975. self.sendBadResponse(tag, b'LOGIN is disabled before STARTTLS')
  976. return
  977. maybeDeferred(self.authenticateLogin, user, passwd
  978. ).addCallback(self.__cbLogin, tag
  979. ).addErrback(self.__ebLogin, tag
  980. )
  981. unauth_LOGIN = (do_LOGIN, arg_astring, arg_finalastring)
  982. def authenticateLogin(self, user, passwd):
  983. """
  984. Lookup the account associated with the given parameters
  985. Override this method to define the desired authentication behavior.
  986. The default behavior is to defer authentication to C{self.portal}
  987. if it is not None, or to deny the login otherwise.
  988. @type user: L{str}
  989. @param user: The username to lookup
  990. @type passwd: L{str}
  991. @param passwd: The password to login with
  992. """
  993. if self.portal:
  994. return self.portal.login(
  995. credentials.UsernamePassword(user, passwd),
  996. None, IAccount
  997. )
  998. raise UnauthorizedLogin()
  999. def __cbLogin(self, result, tag):
  1000. (iface, avatar, logout) = result
  1001. if iface is not IAccount:
  1002. self.sendBadResponse(tag, b'Server error: login returned unexpected value')
  1003. log.err("__cbLogin called with %r, IAccount expected" % (iface,))
  1004. else:
  1005. self.account = avatar
  1006. self._onLogout = logout
  1007. self.sendPositiveResponse(tag, b'LOGIN succeeded')
  1008. self.state = 'auth'
  1009. self.setTimeout(self.POSTAUTH_TIMEOUT)
  1010. def __ebLogin(self, failure, tag):
  1011. if failure.check(UnauthorizedLogin):
  1012. self.sendNegativeResponse(tag, b'LOGIN failed')
  1013. else:
  1014. self.sendBadResponse(tag, b'Server error: ' + networkString(str(failure.value)))
  1015. log.err(failure)
  1016. def do_NAMESPACE(self, tag):
  1017. personal = public = shared = None
  1018. np = INamespacePresenter(self.account, None)
  1019. if np is not None:
  1020. personal = np.getPersonalNamespaces()
  1021. public = np.getSharedNamespaces()
  1022. shared = np.getSharedNamespaces()
  1023. self.sendUntaggedResponse(b'NAMESPACE ' + collapseNestedLists([personal, public, shared]))
  1024. self.sendPositiveResponse(tag, b"NAMESPACE command completed")
  1025. auth_NAMESPACE = (do_NAMESPACE,)
  1026. select_NAMESPACE = auth_NAMESPACE
  1027. def _selectWork(self, tag, name, rw, cmdName):
  1028. if self.mbox:
  1029. self.mbox.removeListener(self)
  1030. cmbx = ICloseableMailbox(self.mbox, None)
  1031. if cmbx is not None:
  1032. maybeDeferred(cmbx.close).addErrback(log.err)
  1033. self.mbox = None
  1034. self.state = 'auth'
  1035. name = _parseMbox(name)
  1036. maybeDeferred(self.account.select, _parseMbox(name), rw
  1037. ).addCallback(self._cbSelectWork, cmdName, tag
  1038. ).addErrback(self._ebSelectWork, cmdName, tag
  1039. )
  1040. def _ebSelectWork(self, failure, cmdName, tag):
  1041. self.sendBadResponse(tag, cmdName + b" failed: Server error")
  1042. log.err(failure)
  1043. def _cbSelectWork(self, mbox, cmdName, tag):
  1044. if mbox is None:
  1045. self.sendNegativeResponse(tag, b'No such mailbox')
  1046. return
  1047. if '\\noselect' in [s.lower() for s in mbox.getFlags()]:
  1048. self.sendNegativeResponse(tag, 'Mailbox cannot be selected')
  1049. return
  1050. flags = [networkString(flag) for flag in mbox.getFlags()]
  1051. self.sendUntaggedResponse(intToBytes(mbox.getMessageCount()) + b' EXISTS')
  1052. self.sendUntaggedResponse(intToBytes(mbox.getRecentCount()) + b' RECENT')
  1053. self.sendUntaggedResponse(b'FLAGS (' + b' '.join(flags) + b')')
  1054. self.sendPositiveResponse(None, b'[UIDVALIDITY ' + intToBytes(mbox.getUIDValidity()) + b']')
  1055. s = mbox.isWriteable() and b'READ-WRITE' or b'READ-ONLY'
  1056. mbox.addListener(self)
  1057. self.sendPositiveResponse(tag, b'[' + s + b'] ' + cmdName + b' successful')
  1058. self.state = 'select'
  1059. self.mbox = mbox
  1060. auth_SELECT = ( _selectWork, arg_astring, 1, b'SELECT' )
  1061. select_SELECT = auth_SELECT
  1062. auth_EXAMINE = ( _selectWork, arg_astring, 0, b'EXAMINE' )
  1063. select_EXAMINE = auth_EXAMINE
  1064. def do_IDLE(self, tag):
  1065. self.sendContinuationRequest(None)
  1066. self.parseTag = tag
  1067. self.lastState = self.parseState
  1068. self.parseState = 'idle'
  1069. def parse_idle(self, *args):
  1070. self.parseState = self.lastState
  1071. del self.lastState
  1072. self.sendPositiveResponse(self.parseTag, b"IDLE terminated")
  1073. del self.parseTag
  1074. select_IDLE = ( do_IDLE, )
  1075. auth_IDLE = select_IDLE
  1076. def do_CREATE(self, tag, name):
  1077. name = _parseMbox(name)
  1078. try:
  1079. result = self.account.create(name)
  1080. except MailboxException as c:
  1081. self.sendNegativeResponse(tag, networkString(str(c)))
  1082. except:
  1083. self.sendBadResponse(tag, b"Server error encountered while creating mailbox")
  1084. log.err()
  1085. else:
  1086. if result:
  1087. self.sendPositiveResponse(tag, b'Mailbox created')
  1088. else:
  1089. self.sendNegativeResponse(tag, b'Mailbox not created')
  1090. auth_CREATE = (do_CREATE, arg_finalastring)
  1091. select_CREATE = auth_CREATE
  1092. def do_DELETE(self, tag, name):
  1093. name = _parseMbox(name)
  1094. if name.lower() == 'inbox':
  1095. self.sendNegativeResponse(tag, b'You cannot delete the inbox')
  1096. return
  1097. try:
  1098. self.account.delete(name)
  1099. except MailboxException as m:
  1100. self.sendNegativeResponse(tag, str(m).encode("imap4-utf-7"))
  1101. except:
  1102. self.sendBadResponse(tag, b"Server error encountered while deleting mailbox")
  1103. log.err()
  1104. else:
  1105. self.sendPositiveResponse(tag, b'Mailbox deleted')
  1106. auth_DELETE = (do_DELETE, arg_finalastring)
  1107. select_DELETE = auth_DELETE
  1108. def do_RENAME(self, tag, oldname, newname):
  1109. oldname, newname = [_parseMbox(n) for n in (oldname, newname)]
  1110. if oldname.lower() == 'inbox' or newname.lower() == 'inbox':
  1111. self.sendNegativeResponse(tag, b'You cannot rename the inbox, or rename another mailbox to inbox.')
  1112. return
  1113. try:
  1114. self.account.rename(oldname, newname)
  1115. except TypeError:
  1116. self.sendBadResponse(tag, b'Invalid command syntax')
  1117. except MailboxException as m:
  1118. self.sendNegativeResponse(tag, networkString(str(m)))
  1119. except:
  1120. self.sendBadResponse(tag, b"Server error encountered while renaming mailbox")
  1121. log.err()
  1122. else:
  1123. self.sendPositiveResponse(tag, b'Mailbox renamed')
  1124. auth_RENAME = (do_RENAME, arg_astring, arg_finalastring)
  1125. select_RENAME = auth_RENAME
  1126. def do_SUBSCRIBE(self, tag, name):
  1127. name = _parseMbox(name)
  1128. try:
  1129. self.account.subscribe(name)
  1130. except MailboxException as m:
  1131. self.sendNegativeResponse(tag, networkString(str(m)))
  1132. except:
  1133. self.sendBadResponse(tag, b"Server error encountered while subscribing to mailbox")
  1134. log.err()
  1135. else:
  1136. self.sendPositiveResponse(tag, b'Subscribed')
  1137. auth_SUBSCRIBE = (do_SUBSCRIBE, arg_finalastring)
  1138. select_SUBSCRIBE = auth_SUBSCRIBE
  1139. def do_UNSUBSCRIBE(self, tag, name):
  1140. name = _parseMbox(name)
  1141. try:
  1142. self.account.unsubscribe(name)
  1143. except MailboxException as m:
  1144. self.sendNegativeResponse(tag, networkString(str(m)))
  1145. except:
  1146. self.sendBadResponse(tag, b"Server error encountered while unsubscribing from mailbox")
  1147. log.err()
  1148. else:
  1149. self.sendPositiveResponse(tag, b'Unsubscribed')
  1150. auth_UNSUBSCRIBE = (do_UNSUBSCRIBE, arg_finalastring)
  1151. select_UNSUBSCRIBE = auth_UNSUBSCRIBE
  1152. def _listWork(self, tag, ref, mbox, sub, cmdName):
  1153. mbox = _parseMbox(mbox)
  1154. ref = _parseMbox(ref)
  1155. maybeDeferred(self.account.listMailboxes, ref, mbox
  1156. ).addCallback(self._cbListWork, tag, sub, cmdName
  1157. ).addErrback(self._ebListWork, tag
  1158. )
  1159. def _cbListWork(self, mailboxes, tag, sub, cmdName):
  1160. for (name, box) in mailboxes:
  1161. if not sub or self.account.isSubscribed(name):
  1162. flags = [networkString(flag) for flag in box.getFlags()]
  1163. delim = box.getHierarchicalDelimiter().encode('imap4-utf-7')
  1164. resp = (DontQuoteMe(cmdName), map(DontQuoteMe, flags), delim, name.encode('imap4-utf-7'))
  1165. self.sendUntaggedResponse(collapseNestedLists(resp))
  1166. self.sendPositiveResponse(tag, cmdName + b' completed')
  1167. def _ebListWork(self, failure, tag):
  1168. self.sendBadResponse(tag, b"Server error encountered while listing mailboxes.")
  1169. log.err(failure)
  1170. auth_LIST = (_listWork, arg_astring, arg_astring, 0, b'LIST')
  1171. select_LIST = auth_LIST
  1172. auth_LSUB = (_listWork, arg_astring, arg_astring, 1, b'LSUB')
  1173. select_LSUB = auth_LSUB
  1174. def do_STATUS(self, tag, mailbox, names):
  1175. nativeNames = []
  1176. for name in names:
  1177. nativeNames.append(nativeString(name))
  1178. mailbox = _parseMbox(mailbox)
  1179. maybeDeferred(self.account.select, mailbox, 0
  1180. ).addCallback(self._cbStatusGotMailbox, tag, mailbox, nativeNames
  1181. ).addErrback(self._ebStatusGotMailbox, tag
  1182. )
  1183. def _cbStatusGotMailbox(self, mbox, tag, mailbox, names):
  1184. if mbox:
  1185. maybeDeferred(mbox.requestStatus, names).addCallbacks(
  1186. self.__cbStatus, self.__ebStatus,
  1187. (tag, mailbox), None, (tag, mailbox), None
  1188. )
  1189. else:
  1190. self.sendNegativeResponse(tag, b"Could not open mailbox")
  1191. def _ebStatusGotMailbox(self, failure, tag):
  1192. self.sendBadResponse(tag, b"Server error encountered while opening mailbox.")
  1193. log.err(failure)
  1194. auth_STATUS = (do_STATUS, arg_astring, arg_plist)
  1195. select_STATUS = auth_STATUS
  1196. def __cbStatus(self, status, tag, box):
  1197. # STATUS names should only be ASCII
  1198. line = networkString(' '.join(['%s %s' % x for x in status.items()]))
  1199. self.sendUntaggedResponse(b'STATUS ' + box.encode('imap4-utf-7') + b' ('+ line + b')')
  1200. self.sendPositiveResponse(tag, b'STATUS complete')
  1201. def __ebStatus(self, failure, tag, box):
  1202. self.sendBadResponse(tag, b'STATUS '+ box + b' failed: ' +
  1203. networkString(str(failure.value)))
  1204. def do_APPEND(self, tag, mailbox, flags, date, message):
  1205. mailbox = _parseMbox(mailbox)
  1206. maybeDeferred(self.account.select, mailbox
  1207. ).addCallback(self._cbAppendGotMailbox, tag, flags, date, message
  1208. ).addErrback(self._ebAppendGotMailbox, tag
  1209. )
  1210. def _cbAppendGotMailbox(self, mbox, tag, flags, date, message):
  1211. if not mbox:
  1212. self.sendNegativeResponse(tag, '[TRYCREATE] No such mailbox')
  1213. return
  1214. decodedFlags = [nativeString(flag) for flag in flags]
  1215. d = mbox.addMessage(message, decodedFlags, date)
  1216. d.addCallback(self.__cbAppend, tag, mbox)
  1217. d.addErrback(self.__ebAppend, tag)
  1218. def _ebAppendGotMailbox(self, failure, tag):
  1219. self.sendBadResponse(tag, b"Server error encountered while opening mailbox.")
  1220. log.err(failure)
  1221. auth_APPEND = (do_APPEND, arg_astring, opt_plist, opt_datetime,
  1222. arg_literal)
  1223. select_APPEND = auth_APPEND
  1224. def __cbAppend(self, result, tag, mbox):
  1225. self.sendUntaggedResponse(intToBytes(mbox.getMessageCount()) + b' EXISTS')
  1226. self.sendPositiveResponse(tag, b'APPEND complete')
  1227. def __ebAppend(self, failure, tag):
  1228. self.sendBadResponse(tag, b'APPEND failed: ' +
  1229. networkString(str(failure.value)))
  1230. def do_CHECK(self, tag):
  1231. d = self.checkpoint()
  1232. if d is None:
  1233. self.__cbCheck(None, tag)
  1234. else:
  1235. d.addCallbacks(
  1236. self.__cbCheck,
  1237. self.__ebCheck,
  1238. callbackArgs=(tag,),
  1239. errbackArgs=(tag,)
  1240. )
  1241. select_CHECK = (do_CHECK,)
  1242. def __cbCheck(self, result, tag):
  1243. self.sendPositiveResponse(tag, b'CHECK completed')
  1244. def __ebCheck(self, failure, tag):
  1245. self.sendBadResponse(tag, b'CHECK failed: ' +
  1246. networkString(str(failure.value)))
  1247. def checkpoint(self):
  1248. """
  1249. Called when the client issues a CHECK command.
  1250. This should perform any checkpoint operations required by the server.
  1251. It may be a long running operation, but may not block. If it returns
  1252. a deferred, the client will only be informed of success (or failure)
  1253. when the deferred's callback (or errback) is invoked.
  1254. """
  1255. return None
  1256. def do_CLOSE(self, tag):
  1257. d = None
  1258. if self.mbox.isWriteable():
  1259. d = maybeDeferred(self.mbox.expunge)
  1260. cmbx = ICloseableMailbox(self.mbox, None)
  1261. if cmbx is not None:
  1262. if d is not None:
  1263. d.addCallback(lambda result: cmbx.close())
  1264. else:
  1265. d = maybeDeferred(cmbx.close)
  1266. if d is not None:
  1267. d.addCallbacks(self.__cbClose, self.__ebClose, (tag,), None, (tag,), None)
  1268. else:
  1269. self.__cbClose(None, tag)
  1270. select_CLOSE = (do_CLOSE,)
  1271. def __cbClose(self, result, tag):
  1272. self.sendPositiveResponse(tag, b'CLOSE completed')
  1273. self.mbox.removeListener(self)
  1274. self.mbox = None
  1275. self.state = 'auth'
  1276. def __ebClose(self, failure, tag):
  1277. self.sendBadResponse(tag, b'CLOSE failed: ' +
  1278. networkString(str(failure.value)))
  1279. def do_EXPUNGE(self, tag):
  1280. if self.mbox.isWriteable():
  1281. maybeDeferred(self.mbox.expunge).addCallbacks(
  1282. self.__cbExpunge, self.__ebExpunge, (tag,), None, (tag,), None
  1283. )
  1284. else:
  1285. self.sendNegativeResponse(tag, b'EXPUNGE ignored on read-only mailbox')
  1286. select_EXPUNGE = (do_EXPUNGE,)
  1287. def __cbExpunge(self, result, tag):
  1288. for e in result:
  1289. self.sendUntaggedResponse(intToBytes(e) + b' EXPUNGE')
  1290. self.sendPositiveResponse(tag, b'EXPUNGE completed')
  1291. def __ebExpunge(self, failure, tag):
  1292. self.sendBadResponse(tag, b'EXPUNGE failed: ' +
  1293. networkString(str(failure.value)))
  1294. log.err(failure)
  1295. def do_SEARCH(self, tag, charset, query, uid=0):
  1296. sm = ISearchableMailbox(self.mbox, None)
  1297. if sm is not None:
  1298. maybeDeferred(sm.search, query, uid=uid
  1299. ).addCallback(self.__cbSearch, tag, self.mbox, uid
  1300. ).addErrback(self.__ebSearch, tag)
  1301. else:
  1302. # that's not the ideal way to get all messages, there should be a
  1303. # method on mailboxes that gives you all of them
  1304. s = parseIdList(b'1:*')
  1305. maybeDeferred(self.mbox.fetch, s, uid=uid
  1306. ).addCallback(self.__cbManualSearch,
  1307. tag, self.mbox, query, uid
  1308. ).addErrback(self.__ebSearch, tag)
  1309. select_SEARCH = (do_SEARCH, opt_charset, arg_searchkeys)
  1310. def __cbSearch(self, result, tag, mbox, uid):
  1311. if uid:
  1312. result = map(mbox.getUID, result)
  1313. ids = networkString(' '.join([str(i) for i in result]))
  1314. self.sendUntaggedResponse(b'SEARCH ' + ids)
  1315. self.sendPositiveResponse(tag, b'SEARCH completed')
  1316. def __cbManualSearch(self, result, tag, mbox, query, uid,
  1317. searchResults=None):
  1318. """
  1319. Apply the search filter to a set of messages. Send the response to the
  1320. client.
  1321. @type result: L{list} of L{tuple} of (L{int}, provider of
  1322. L{imap4.IMessage})
  1323. @param result: A list two tuples of messages with their sequence ids,
  1324. sorted by the ids in descending order.
  1325. @type tag: L{str}
  1326. @param tag: A command tag.
  1327. @type mbox: Provider of L{imap4.IMailbox}
  1328. @param mbox: The searched mailbox.
  1329. @type query: L{list}
  1330. @param query: A list representing the parsed form of the search query.
  1331. @param uid: A flag indicating whether the search is over message
  1332. sequence numbers or UIDs.
  1333. @type searchResults: L{list}
  1334. @param searchResults: The search results so far or L{None} if no
  1335. results yet.
  1336. """
  1337. if searchResults is None:
  1338. searchResults = []
  1339. i = 0
  1340. # result is a list of tuples (sequenceId, Message)
  1341. lastSequenceId = result and result[-1][0]
  1342. lastMessageId = result and result[-1][1].getUID()
  1343. for (i, (msgId, msg)) in list(zip(range(5), result)):
  1344. # searchFilter and singleSearchStep will mutate the query. Dang.
  1345. # Copy it here or else things will go poorly for subsequent
  1346. # messages.
  1347. if self._searchFilter(copy.deepcopy(query), msgId, msg,
  1348. lastSequenceId, lastMessageId):
  1349. if uid:
  1350. searchResults.append(intToBytes(msg.getUID()))
  1351. else:
  1352. searchResults.append(intToBytes(msgId))
  1353. if i == 4:
  1354. from twisted.internet import reactor
  1355. reactor.callLater(
  1356. 0, self.__cbManualSearch, list(result[5:]), tag, mbox, query, uid,
  1357. searchResults)
  1358. else:
  1359. if searchResults:
  1360. self.sendUntaggedResponse(b'SEARCH ' + b' '.join(searchResults))
  1361. self.sendPositiveResponse(tag, b'SEARCH completed')
  1362. def _searchFilter(self, query, id, msg, lastSequenceId, lastMessageId):
  1363. """
  1364. Pop search terms from the beginning of C{query} until there are none
  1365. left and apply them to the given message.
  1366. @param query: A list representing the parsed form of the search query.
  1367. @param id: The sequence number of the message being checked.
  1368. @param msg: The message being checked.
  1369. @type lastSequenceId: L{int}
  1370. @param lastSequenceId: The highest sequence number of any message in
  1371. the mailbox being searched.
  1372. @type lastMessageId: L{int}
  1373. @param lastMessageId: The highest UID of any message in the mailbox
  1374. being searched.
  1375. @return: Boolean indicating whether all of the query terms match the
  1376. message.
  1377. """
  1378. while query:
  1379. if not self._singleSearchStep(query, id, msg,
  1380. lastSequenceId, lastMessageId):
  1381. return False
  1382. return True
  1383. def _singleSearchStep(self, query, msgId, msg, lastSequenceId, lastMessageId):
  1384. """
  1385. Pop one search term from the beginning of C{query} (possibly more than
  1386. one element) and return whether it matches the given message.
  1387. @param query: A list representing the parsed form of the search query.
  1388. @param msgId: The sequence number of the message being checked.
  1389. @param msg: The message being checked.
  1390. @param lastSequenceId: The highest sequence number of any message in
  1391. the mailbox being searched.
  1392. @param lastMessageId: The highest UID of any message in the mailbox
  1393. being searched.
  1394. @return: Boolean indicating whether the query term matched the message.
  1395. """
  1396. q = query.pop(0)
  1397. if isinstance(q, list):
  1398. if not self._searchFilter(q, msgId, msg,
  1399. lastSequenceId, lastMessageId):
  1400. return False
  1401. else:
  1402. c = q.upper()
  1403. if not c[:1].isalpha():
  1404. # A search term may be a word like ALL, ANSWERED, BCC, etc (see
  1405. # below) or it may be a message sequence set. Here we
  1406. # recognize a message sequence set "N:M".
  1407. messageSet = parseIdList(c, lastSequenceId)
  1408. return msgId in messageSet
  1409. else:
  1410. f = getattr(self, 'search_' + nativeString(c), None)
  1411. if f is None:
  1412. raise IllegalQueryError("Invalid search command %s" % nativeString(c))
  1413. if c in self._requiresLastMessageInfo:
  1414. result = f(query, msgId, msg, (lastSequenceId,
  1415. lastMessageId))
  1416. else:
  1417. result = f(query, msgId, msg)
  1418. if not result:
  1419. return False
  1420. return True
  1421. def search_ALL(self, query, id, msg):
  1422. """
  1423. Returns C{True} if the message matches the ALL search key (always).
  1424. @type query: A L{list} of L{str}
  1425. @param query: A list representing the parsed query string.
  1426. @type id: L{int}
  1427. @param id: The sequence number of the message being checked.
  1428. @type msg: Provider of L{imap4.IMessage}
  1429. """
  1430. return True
  1431. def search_ANSWERED(self, query, id, msg):
  1432. """
  1433. Returns C{True} if the message has been answered.
  1434. @type query: A L{list} of L{str}
  1435. @param query: A list representing the parsed query string.
  1436. @type id: L{int}
  1437. @param id: The sequence number of the message being checked.
  1438. @type msg: Provider of L{imap4.IMessage}
  1439. """
  1440. return '\\Answered' in msg.getFlags()
  1441. def search_BCC(self, query, id, msg):
  1442. """
  1443. Returns C{True} if the message has a BCC address matching the query.
  1444. @type query: A L{list} of L{str}
  1445. @param query: A list whose first element is a BCC L{str}
  1446. @type id: L{int}
  1447. @param id: The sequence number of the message being checked.
  1448. @type msg: Provider of L{imap4.IMessage}
  1449. """
  1450. bcc = msg.getHeaders(False, 'bcc').get('bcc', '')
  1451. return bcc.lower().find(query.pop(0).lower()) != -1
  1452. def search_BEFORE(self, query, id, msg):
  1453. date = parseTime(query.pop(0))
  1454. return email.utils.parsedate(nativeString(msg.getInternalDate())) < date
  1455. def search_BODY(self, query, id, msg):
  1456. body = query.pop(0).lower()
  1457. return text.strFile(body, msg.getBodyFile(), False)
  1458. def search_CC(self, query, id, msg):
  1459. cc = msg.getHeaders(False, 'cc').get('cc', '')
  1460. return cc.lower().find(query.pop(0).lower()) != -1
  1461. def search_DELETED(self, query, id, msg):
  1462. return '\\Deleted' in msg.getFlags()
  1463. def search_DRAFT(self, query, id, msg):
  1464. return '\\Draft' in msg.getFlags()
  1465. def search_FLAGGED(self, query, id, msg):
  1466. return '\\Flagged' in msg.getFlags()
  1467. def search_FROM(self, query, id, msg):
  1468. fm = msg.getHeaders(False, 'from').get('from', '')
  1469. return fm.lower().find(query.pop(0).lower()) != -1
  1470. def search_HEADER(self, query, id, msg):
  1471. hdr = query.pop(0).lower()
  1472. hdr = msg.getHeaders(False, hdr).get(hdr, '')
  1473. return hdr.lower().find(query.pop(0).lower()) != -1
  1474. def search_KEYWORD(self, query, id, msg):
  1475. query.pop(0)
  1476. return False
  1477. def search_LARGER(self, query, id, msg):
  1478. return int(query.pop(0)) < msg.getSize()
  1479. def search_NEW(self, query, id, msg):
  1480. return '\\Recent' in msg.getFlags() and '\\Seen' not in msg.getFlags()
  1481. def search_NOT(self, query, id, msg, lastIDs):
  1482. """
  1483. Returns C{True} if the message does not match the query.
  1484. @type query: A L{list} of L{str}
  1485. @param query: A list representing the parsed form of the search query.
  1486. @type id: L{int}
  1487. @param id: The sequence number of the message being checked.
  1488. @type msg: Provider of L{imap4.IMessage}
  1489. @param msg: The message being checked.
  1490. @type lastIDs: L{tuple}
  1491. @param lastIDs: A tuple of (last sequence id, last message id).
  1492. The I{last sequence id} is an L{int} containing the highest sequence
  1493. number of a message in the mailbox. The I{last message id} is an
  1494. L{int} containing the highest UID of a message in the mailbox.
  1495. """
  1496. (lastSequenceId, lastMessageId) = lastIDs
  1497. return not self._singleSearchStep(query, id, msg,
  1498. lastSequenceId, lastMessageId)
  1499. def search_OLD(self, query, id, msg):
  1500. return '\\Recent' not in msg.getFlags()
  1501. def search_ON(self, query, id, msg):
  1502. date = parseTime(query.pop(0))
  1503. return email.utils.parsedate(msg.getInternalDate()) == date
  1504. def search_OR(self, query, id, msg, lastIDs):
  1505. """
  1506. Returns C{True} if the message matches any of the first two query
  1507. items.
  1508. @type query: A L{list} of L{str}
  1509. @param query: A list representing the parsed form of the search query.
  1510. @type id: L{int}
  1511. @param id: The sequence number of the message being checked.
  1512. @type msg: Provider of L{imap4.IMessage}
  1513. @param msg: The message being checked.
  1514. @type lastIDs: L{tuple}
  1515. @param lastIDs: A tuple of (last sequence id, last message id).
  1516. The I{last sequence id} is an L{int} containing the highest sequence
  1517. number of a message in the mailbox. The I{last message id} is an
  1518. L{int} containing the highest UID of a message in the mailbox.
  1519. """
  1520. (lastSequenceId, lastMessageId) = lastIDs
  1521. a = self._singleSearchStep(query, id, msg,
  1522. lastSequenceId, lastMessageId)
  1523. b = self._singleSearchStep(query, id, msg,
  1524. lastSequenceId, lastMessageId)
  1525. return a or b
  1526. def search_RECENT(self, query, id, msg):
  1527. return '\\Recent' in msg.getFlags()
  1528. def search_SEEN(self, query, id, msg):
  1529. return '\\Seen' in msg.getFlags()
  1530. def search_SENTBEFORE(self, query, id, msg):
  1531. """
  1532. Returns C{True} if the message date is earlier than the query date.
  1533. @type query: A L{list} of L{str}
  1534. @param query: A list whose first element starts with a stringified date
  1535. that is a fragment of an L{imap4.Query()}. The date must be in the
  1536. format 'DD-Mon-YYYY', for example '03-March-2003' or '03-Mar-2003'.
  1537. @type id: L{int}
  1538. @param id: The sequence number of the message being checked.
  1539. @type msg: Provider of L{imap4.IMessage}
  1540. """
  1541. date = msg.getHeaders(False, 'date').get('date', '')
  1542. date = email.utils.parsedate(date)
  1543. return date < parseTime(query.pop(0))
  1544. def search_SENTON(self, query, id, msg):
  1545. """
  1546. Returns C{True} if the message date is the same as the query date.
  1547. @type query: A L{list} of L{str}
  1548. @param query: A list whose first element starts with a stringified date
  1549. that is a fragment of an L{imap4.Query()}. The date must be in the
  1550. format 'DD-Mon-YYYY', for example '03-March-2003' or '03-Mar-2003'.
  1551. @type msg: Provider of L{imap4.IMessage}
  1552. """
  1553. date = msg.getHeaders(False, 'date').get('date', '')
  1554. date = email.utils.parsedate(date)
  1555. return date[:3] == parseTime(query.pop(0))[:3]
  1556. def search_SENTSINCE(self, query, id, msg):
  1557. """
  1558. Returns C{True} if the message date is later than the query date.
  1559. @type query: A L{list} of L{str}
  1560. @param query: A list whose first element starts with a stringified date
  1561. that is a fragment of an L{imap4.Query()}. The date must be in the
  1562. format 'DD-Mon-YYYY', for example '03-March-2003' or '03-Mar-2003'.
  1563. @type msg: Provider of L{imap4.IMessage}
  1564. """
  1565. date = msg.getHeaders(False, 'date').get('date', '')
  1566. date = email.utils.parsedate(date)
  1567. return date > parseTime(query.pop(0))
  1568. def search_SINCE(self, query, id, msg):
  1569. date = parseTime(query.pop(0))
  1570. return email.utils.parsedate(msg.getInternalDate()) > date
  1571. def search_SMALLER(self, query, id, msg):
  1572. return int(query.pop(0)) > msg.getSize()
  1573. def search_SUBJECT(self, query, id, msg):
  1574. subj = msg.getHeaders(False, 'subject').get('subject', '')
  1575. return subj.lower().find(query.pop(0).lower()) != -1
  1576. def search_TEXT(self, query, id, msg):
  1577. # XXX - This must search headers too
  1578. body = query.pop(0).lower()
  1579. return text.strFile(body, msg.getBodyFile(), False)
  1580. def search_TO(self, query, id, msg):
  1581. to = msg.getHeaders(False, 'to').get('to', '')
  1582. return to.lower().find(query.pop(0).lower()) != -1
  1583. def search_UID(self, query, id, msg, lastIDs):
  1584. """
  1585. Returns C{True} if the message UID is in the range defined by the
  1586. search query.
  1587. @type query: A L{list} of L{bytes}
  1588. @param query: A list representing the parsed form of the search
  1589. query. Its first element should be a L{str} that can be interpreted
  1590. as a sequence range, for example '2:4,5:*'.
  1591. @type id: L{int}
  1592. @param id: The sequence number of the message being checked.
  1593. @type msg: Provider of L{imap4.IMessage}
  1594. @param msg: The message being checked.
  1595. @type lastIDs: L{tuple}
  1596. @param lastIDs: A tuple of (last sequence id, last message id).
  1597. The I{last sequence id} is an L{int} containing the highest sequence
  1598. number of a message in the mailbox. The I{last message id} is an
  1599. L{int} containing the highest UID of a message in the mailbox.
  1600. """
  1601. (lastSequenceId, lastMessageId) = lastIDs
  1602. c = query.pop(0)
  1603. m = parseIdList(c, lastMessageId)
  1604. return msg.getUID() in m
  1605. def search_UNANSWERED(self, query, id, msg):
  1606. return '\\Answered' not in msg.getFlags()
  1607. def search_UNDELETED(self, query, id, msg):
  1608. return '\\Deleted' not in msg.getFlags()
  1609. def search_UNDRAFT(self, query, id, msg):
  1610. return '\\Draft' not in msg.getFlags()
  1611. def search_UNFLAGGED(self, query, id, msg):
  1612. return '\\Flagged' not in msg.getFlags()
  1613. def search_UNKEYWORD(self, query, id, msg):
  1614. query.pop(0)
  1615. return False
  1616. def search_UNSEEN(self, query, id, msg):
  1617. return '\\Seen' not in msg.getFlags()
  1618. def __ebSearch(self, failure, tag):
  1619. self.sendBadResponse(tag, b'SEARCH failed: ' +
  1620. networkString(str(failure.value)))
  1621. log.err(failure)
  1622. def do_FETCH(self, tag, messages, query, uid=0):
  1623. if query:
  1624. self._oldTimeout = self.setTimeout(None)
  1625. maybeDeferred(self.mbox.fetch, messages, uid=uid
  1626. ).addCallback(iter
  1627. ).addCallback(self.__cbFetch, tag, query, uid
  1628. ).addErrback(self.__ebFetch, tag
  1629. )
  1630. else:
  1631. self.sendPositiveResponse(tag, b'FETCH complete')
  1632. select_FETCH = (do_FETCH, arg_seqset, arg_fetchatt)
  1633. def __cbFetch(self, results, tag, query, uid):
  1634. if self.blocked is None:
  1635. self.blocked = []
  1636. try:
  1637. id, msg = next(results)
  1638. except StopIteration:
  1639. # The idle timeout was suspended while we delivered results,
  1640. # restore it now.
  1641. self.setTimeout(self._oldTimeout)
  1642. del self._oldTimeout
  1643. # All results have been processed, deliver completion notification.
  1644. # It's important to run this *after* resetting the timeout to "rig
  1645. # a race" in some test code. writing to the transport will
  1646. # synchronously call test code, which synchronously loses the
  1647. # connection, calling our connectionLost method, which cancels the
  1648. # timeout. We want to make sure that timeout is cancelled *after*
  1649. # we reset it above, so that the final state is no timed
  1650. # calls. This avoids reactor uncleanliness errors in the test
  1651. # suite.
  1652. # XXX: Perhaps loopback should be fixed to not call the user code
  1653. # synchronously in transport.write?
  1654. self.sendPositiveResponse(tag, b'FETCH completed')
  1655. # Instance state is now consistent again (ie, it is as though
  1656. # the fetch command never ran), so allow any pending blocked
  1657. # commands to execute.
  1658. self._unblock()
  1659. else:
  1660. self.spewMessage(id, msg, query, uid
  1661. ).addCallback(lambda _: self.__cbFetch(results, tag, query, uid)
  1662. ).addErrback(self.__ebSpewMessage
  1663. )
  1664. def __ebSpewMessage(self, failure):
  1665. # This indicates a programming error.
  1666. # There's no reliable way to indicate anything to the client, since we
  1667. # may have already written an arbitrary amount of data in response to
  1668. # the command.
  1669. log.err(failure)
  1670. self.transport.loseConnection()
  1671. def spew_envelope(self, id, msg, _w=None, _f=None):
  1672. if _w is None:
  1673. _w = self.transport.write
  1674. _w(b'ENVELOPE ' + collapseNestedLists([getEnvelope(msg)]))
  1675. def spew_flags(self, id, msg, _w=None, _f=None):
  1676. if _w is None:
  1677. _w = self.transport.writen
  1678. encodedFlags = [networkString(flag) for flag in msg.getFlags()]
  1679. _w(b'FLAGS ' + b'(' + b' '.join(encodedFlags) + b')')
  1680. def spew_internaldate(self, id, msg, _w=None, _f=None):
  1681. if _w is None:
  1682. _w = self.transport.write
  1683. idate = msg.getInternalDate()
  1684. ttup = email.utils.parsedate_tz(nativeString(idate))
  1685. if ttup is None:
  1686. log.msg("%d:%r: unpareseable internaldate: %r" % (id, msg, idate))
  1687. raise IMAP4Exception("Internal failure generating INTERNALDATE")
  1688. # need to specify the month manually, as strftime depends on locale
  1689. strdate = time.strftime("%d-%%s-%Y %H:%M:%S ", ttup[:9])
  1690. odate = networkString(strdate % (_MONTH_NAMES[ttup[1]],))
  1691. if ttup[9] is None:
  1692. odate = odate + b"+0000"
  1693. else:
  1694. if ttup[9] >= 0:
  1695. sign = b"+"
  1696. else:
  1697. sign = b"-"
  1698. odate = odate + sign + intToBytes(
  1699. ((abs(ttup[9]) // 3600) * 100 +
  1700. (abs(ttup[9]) % 3600) // 60)
  1701. ).zfill(4)
  1702. _w(b'INTERNALDATE ' + _quote(odate))
  1703. def spew_rfc822header(self, id, msg, _w=None, _f=None):
  1704. if _w is None:
  1705. _w = self.transport.write
  1706. hdrs = _formatHeaders(msg.getHeaders(True))
  1707. _w(b'RFC822.HEADER ' + _literal(hdrs))
  1708. def spew_rfc822text(self, id, msg, _w=None, _f=None):
  1709. if _w is None:
  1710. _w = self.transport.write
  1711. _w(b'RFC822.TEXT ')
  1712. _f()
  1713. return FileProducer(msg.getBodyFile()
  1714. ).beginProducing(self.transport
  1715. )
  1716. def spew_rfc822size(self, id, msg, _w=None, _f=None):
  1717. if _w is None:
  1718. _w = self.transport.write
  1719. _w(b'RFC822.SIZE ' + intToBytes(msg.getSize()))
  1720. def spew_rfc822(self, id, msg, _w=None, _f=None):
  1721. if _w is None:
  1722. _w = self.transport.write
  1723. _w(b'RFC822 ')
  1724. _f()
  1725. mf = IMessageFile(msg, None)
  1726. if mf is not None:
  1727. return FileProducer(mf.open()
  1728. ).beginProducing(self.transport
  1729. )
  1730. return MessageProducer(msg, None, self._scheduler
  1731. ).beginProducing(self.transport
  1732. )
  1733. def spew_uid(self, id, msg, _w=None, _f=None):
  1734. if _w is None:
  1735. _w = self.transport.write
  1736. _w(b'UID ' + intToBytes(msg.getUID()))
  1737. def spew_bodystructure(self, id, msg, _w=None, _f=None):
  1738. _w(b'BODYSTRUCTURE ' + collapseNestedLists([getBodyStructure(msg, True)]))
  1739. def spew_body(self, part, id, msg, _w=None, _f=None):
  1740. if _w is None:
  1741. _w = self.transport.write
  1742. for p in part.part:
  1743. if msg.isMultipart():
  1744. msg = msg.getSubPart(p)
  1745. elif p > 0:
  1746. # Non-multipart messages have an implicit first part but no
  1747. # other parts - reject any request for any other part.
  1748. raise TypeError("Requested subpart of non-multipart message")
  1749. if part.header:
  1750. hdrs = msg.getHeaders(part.header.negate, *part.header.fields)
  1751. hdrs = _formatHeaders(hdrs)
  1752. _w(part.__bytes__() + b' ' + _literal(hdrs))
  1753. elif part.text:
  1754. _w(part.__bytes__() + b' ')
  1755. _f()
  1756. return FileProducer(msg.getBodyFile()
  1757. ).beginProducing(self.transport
  1758. )
  1759. elif part.mime:
  1760. hdrs = _formatHeaders(msg.getHeaders(True))
  1761. _w(part.__bytes__() + b' ' + _literal(hdrs))
  1762. elif part.empty:
  1763. _w(part.__bytes__() + b' ')
  1764. _f()
  1765. if part.part:
  1766. return FileProducer(msg.getBodyFile()
  1767. ).beginProducing(self.transport
  1768. )
  1769. else:
  1770. mf = IMessageFile(msg, None)
  1771. if mf is not None:
  1772. return FileProducer(mf.open()).beginProducing(self.transport)
  1773. return MessageProducer(msg, None, self._scheduler).beginProducing(self.transport)
  1774. else:
  1775. _w(b'BODY ' + collapseNestedLists([getBodyStructure(msg)]))
  1776. def spewMessage(self, id, msg, query, uid):
  1777. wbuf = WriteBuffer(self.transport)
  1778. write = wbuf.write
  1779. flush = wbuf.flush
  1780. def start():
  1781. write(b'* ' + intToBytes(id) + b' FETCH (')
  1782. def finish():
  1783. write(b')\r\n')
  1784. def space():
  1785. write(b' ')
  1786. def spew():
  1787. seenUID = False
  1788. start()
  1789. for part in query:
  1790. if part.type == 'uid':
  1791. seenUID = True
  1792. if part.type == 'body':
  1793. yield self.spew_body(part, id, msg, write, flush)
  1794. else:
  1795. f = getattr(self, 'spew_' + part.type)
  1796. yield f(id, msg, write, flush)
  1797. if part is not query[-1]:
  1798. space()
  1799. if uid and not seenUID:
  1800. space()
  1801. yield self.spew_uid(id, msg, write, flush)
  1802. finish()
  1803. flush()
  1804. return self._scheduler(spew())
  1805. def __ebFetch(self, failure, tag):
  1806. self.setTimeout(self._oldTimeout)
  1807. del self._oldTimeout
  1808. log.err(failure)
  1809. self.sendBadResponse(tag, b'FETCH failed: ' +
  1810. networkString(str(failure.value)))
  1811. def do_STORE(self, tag, messages, mode, flags, uid=0):
  1812. mode = mode.upper()
  1813. silent = mode.endswith(b'SILENT')
  1814. if mode.startswith(b'+'):
  1815. mode = 1
  1816. elif mode.startswith(b'-'):
  1817. mode = -1
  1818. else:
  1819. mode = 0
  1820. flags = [nativeString(flag) for flag in flags]
  1821. maybeDeferred(self.mbox.store, messages, flags, mode, uid=uid).addCallbacks(
  1822. self.__cbStore, self.__ebStore, (tag, self.mbox, uid, silent), None, (tag,), None
  1823. )
  1824. select_STORE = (do_STORE, arg_seqset, arg_atom, arg_flaglist)
  1825. def __cbStore(self, result, tag, mbox, uid, silent):
  1826. if result and not silent:
  1827. for (k, v) in result.items():
  1828. if uid:
  1829. uidstr = b' UID ' + intToBytes(mbox.getUID(k))
  1830. else:
  1831. uidstr = b''
  1832. flags = [networkString(flag) for flag in v]
  1833. self.sendUntaggedResponse(
  1834. intToBytes(k) +
  1835. b' FETCH (FLAGS ('+ b' '.join(flags) + b')' +
  1836. uidstr + b')')
  1837. self.sendPositiveResponse(tag, b'STORE completed')
  1838. def __ebStore(self, failure, tag):
  1839. self.sendBadResponse(tag, b'Server error: ' +
  1840. networkString(str(failure.value)))
  1841. def do_COPY(self, tag, messages, mailbox, uid=0):
  1842. mailbox = self._parseMbox(mailbox)
  1843. maybeDeferred(self.account.select, mailbox
  1844. ).addCallback(self._cbCopySelectedMailbox, tag, messages, mailbox, uid
  1845. ).addErrback(self._ebCopySelectedMailbox, tag
  1846. )
  1847. select_COPY = (do_COPY, arg_seqset, arg_finalastring)
  1848. def _cbCopySelectedMailbox(self, mbox, tag, messages, mailbox, uid):
  1849. if not mbox:
  1850. self.sendNegativeResponse(tag, 'No such mailbox: ' + mailbox)
  1851. else:
  1852. maybeDeferred(self.mbox.fetch, messages, uid
  1853. ).addCallback(self.__cbCopy, tag, mbox
  1854. ).addCallback(self.__cbCopied, tag, mbox
  1855. ).addErrback(self.__ebCopy, tag
  1856. )
  1857. def _ebCopySelectedMailbox(self, failure, tag):
  1858. self.sendBadResponse(tag, b'Server error: ' +
  1859. networkString(str(failure.value)))
  1860. def __cbCopy(self, messages, tag, mbox):
  1861. # XXX - This should handle failures with a rollback or something
  1862. addedDeferreds = []
  1863. fastCopyMbox = IMessageCopier(mbox, None)
  1864. for (id, msg) in messages:
  1865. if fastCopyMbox is not None:
  1866. d = maybeDeferred(fastCopyMbox.copy, msg)
  1867. addedDeferreds.append(d)
  1868. continue
  1869. # XXX - The following should be an implementation of IMessageCopier.copy
  1870. # on an IMailbox->IMessageCopier adapter.
  1871. flags = msg.getFlags()
  1872. date = msg.getInternalDate()
  1873. body = IMessageFile(msg, None)
  1874. if body is not None:
  1875. bodyFile = body.open()
  1876. d = maybeDeferred(mbox.addMessage, bodyFile, flags, date)
  1877. else:
  1878. def rewind(f):
  1879. f.seek(0)
  1880. return f
  1881. buffer = tempfile.TemporaryFile()
  1882. d = MessageProducer(msg, buffer, self._scheduler
  1883. ).beginProducing(None
  1884. ).addCallback(lambda _, b=buffer, f=flags, d=date: mbox.addMessage(rewind(b), f, d)
  1885. )
  1886. addedDeferreds.append(d)
  1887. return defer.DeferredList(addedDeferreds)
  1888. def __cbCopied(self, deferredIds, tag, mbox):
  1889. ids = []
  1890. failures = []
  1891. for (status, result) in deferredIds:
  1892. if status:
  1893. ids.append(result)
  1894. else:
  1895. failures.append(result.value)
  1896. if failures:
  1897. self.sendNegativeResponse(tag, '[ALERT] Some messages were not copied')
  1898. else:
  1899. self.sendPositiveResponse(tag, b'COPY completed')
  1900. def __ebCopy(self, failure, tag):
  1901. self.sendBadResponse(tag, b'COPY failed:' +
  1902. networkString(str(failure.value)))
  1903. log.err(failure)
  1904. def do_UID(self, tag, command, line):
  1905. command = command.upper()
  1906. if command not in (b'COPY', b'FETCH', b'STORE', b'SEARCH'):
  1907. raise IllegalClientResponse(command)
  1908. self.dispatchCommand(tag, command, line, uid=1)
  1909. select_UID = (do_UID, arg_atom, arg_line)
  1910. #
  1911. # IMailboxListener implementation
  1912. #
  1913. def modeChanged(self, writeable):
  1914. if writeable:
  1915. self.sendUntaggedResponse(message=b'[READ-WRITE]', isAsync=True)
  1916. else:
  1917. self.sendUntaggedResponse(message=b'[READ-ONLY]', isAsync=True)
  1918. def flagsChanged(self, newFlags):
  1919. for (mId, flags) in newFlags.items():
  1920. encodedFlags = [networkString(flag) for flag in flags]
  1921. msg = intToBytes(mId) + (
  1922. b' FETCH (FLAGS (' + b' '.join(encodedFlags) + b'))'
  1923. )
  1924. self.sendUntaggedResponse(msg, isAsync=True)
  1925. def newMessages(self, exists, recent):
  1926. if exists is not None:
  1927. self.sendUntaggedResponse(
  1928. intToBytes(exists) + b' EXISTS', isAsync=True)
  1929. if recent is not None:
  1930. self.sendUntaggedResponse(
  1931. intToBytes(recent) + b' RECENT', isAsync=True)
  1932. TIMEOUT_ERROR = error.TimeoutError()
  1933. @implementer(IMailboxListener)
  1934. class IMAP4Client(basic.LineReceiver, policies.TimeoutMixin):
  1935. """IMAP4 client protocol implementation
  1936. @ivar state: A string representing the state the connection is currently
  1937. in.
  1938. """
  1939. tags = None
  1940. waiting = None
  1941. queued = None
  1942. tagID = 1
  1943. state = None
  1944. startedTLS = False
  1945. # Number of seconds to wait before timing out a connection.
  1946. # If the number is <= 0 no timeout checking will be performed.
  1947. timeout = 0
  1948. # Capabilities are not allowed to change during the session
  1949. # So cache the first response and use that for all later
  1950. # lookups
  1951. _capCache = None
  1952. _memoryFileLimit = 1024 * 1024 * 10
  1953. # Authentication is pluggable. This maps names to IClientAuthentication
  1954. # objects.
  1955. authenticators = None
  1956. STATUS_CODES = ('OK', 'NO', 'BAD', 'PREAUTH', 'BYE')
  1957. STATUS_TRANSFORMATIONS = {
  1958. 'MESSAGES': int, 'RECENT': int, 'UNSEEN': int
  1959. }
  1960. context = None
  1961. def __init__(self, contextFactory = None):
  1962. self.tags = {}
  1963. self.queued = []
  1964. self.authenticators = {}
  1965. self.context = contextFactory
  1966. self._tag = None
  1967. self._parts = None
  1968. self._lastCmd = None
  1969. def registerAuthenticator(self, auth):
  1970. """
  1971. Register a new form of authentication
  1972. When invoking the authenticate() method of IMAP4Client, the first
  1973. matching authentication scheme found will be used. The ordering is
  1974. that in which the server lists support authentication schemes.
  1975. @type auth: Implementor of C{IClientAuthentication}
  1976. @param auth: The object to use to perform the client
  1977. side of this authentication scheme.
  1978. """
  1979. self.authenticators[auth.getName().upper()] = auth
  1980. def rawDataReceived(self, data):
  1981. if self.timeout > 0:
  1982. self.resetTimeout()
  1983. self._pendingSize -= len(data)
  1984. if self._pendingSize > 0:
  1985. self._pendingBuffer.write(data)
  1986. else:
  1987. passon = b''
  1988. if self._pendingSize < 0:
  1989. data, passon = data[:self._pendingSize], data[self._pendingSize:]
  1990. self._pendingBuffer.write(data)
  1991. rest = self._pendingBuffer
  1992. self._pendingBuffer = None
  1993. self._pendingSize = None
  1994. rest.seek(0, 0)
  1995. self._parts.append(rest.read())
  1996. self.setLineMode(passon.lstrip(b'\r\n'))
  1997. # def sendLine(self, line):
  1998. # print 'S:', repr(line)
  1999. # return basic.LineReceiver.sendLine(self, line)
  2000. def _setupForLiteral(self, rest, octets):
  2001. self._pendingBuffer = self.messageFile(octets)
  2002. self._pendingSize = octets
  2003. if self._parts is None:
  2004. self._parts = [rest, b'\r\n']
  2005. else:
  2006. self._parts.extend([rest, b'\r\n'])
  2007. self.setRawMode()
  2008. def connectionMade(self):
  2009. if self.timeout > 0:
  2010. self.setTimeout(self.timeout)
  2011. def connectionLost(self, reason):
  2012. """
  2013. We are no longer connected
  2014. """
  2015. if self.timeout > 0:
  2016. self.setTimeout(None)
  2017. if self.queued is not None:
  2018. queued = self.queued
  2019. self.queued = None
  2020. for cmd in queued:
  2021. cmd.defer.errback(reason)
  2022. if self.tags is not None:
  2023. tags = self.tags
  2024. self.tags = None
  2025. for cmd in tags.values():
  2026. if cmd is not None and cmd.defer is not None:
  2027. cmd.defer.errback(reason)
  2028. def lineReceived(self, line):
  2029. """
  2030. Attempt to parse a single line from the server.
  2031. @type line: L{bytes}
  2032. @param line: The line from the server, without the line delimiter.
  2033. @raise IllegalServerResponse: If the line or some part of the line
  2034. does not represent an allowed message from the server at this time.
  2035. """
  2036. # print('C: ' + repr(line))
  2037. if self.timeout > 0:
  2038. self.resetTimeout()
  2039. lastPart = line.rfind(b'{')
  2040. if lastPart != -1:
  2041. lastPart = line[lastPart + 1:]
  2042. if lastPart.endswith(b'}'):
  2043. # It's a literal a-comin' in
  2044. try:
  2045. octets = int(lastPart[:-1])
  2046. except ValueError:
  2047. raise IllegalServerResponse(line)
  2048. if self._parts is None:
  2049. self._tag, parts = line.split(None, 1)
  2050. else:
  2051. parts = line
  2052. self._setupForLiteral(parts, octets)
  2053. return
  2054. if self._parts is None:
  2055. # It isn't a literal at all
  2056. self._regularDispatch(line)
  2057. else:
  2058. # If an expression is in progress, no tag is required here
  2059. # Since we didn't find a literal indicator, this expression
  2060. # is done.
  2061. self._parts.append(line)
  2062. tag, rest = self._tag, b''.join(self._parts)
  2063. self._tag = self._parts = None
  2064. self.dispatchCommand(tag, rest)
  2065. def timeoutConnection(self):
  2066. if self._lastCmd and self._lastCmd.defer is not None:
  2067. d, self._lastCmd.defer = self._lastCmd.defer, None
  2068. d.errback(TIMEOUT_ERROR)
  2069. if self.queued:
  2070. for cmd in self.queued:
  2071. if cmd.defer is not None:
  2072. d, cmd.defer = cmd.defer, d
  2073. d.errback(TIMEOUT_ERROR)
  2074. self.transport.loseConnection()
  2075. def _regularDispatch(self, line):
  2076. parts = line.split(None, 1)
  2077. if len(parts) != 2:
  2078. parts.append(b'')
  2079. tag, rest = parts
  2080. self.dispatchCommand(tag, rest)
  2081. def messageFile(self, octets):
  2082. """
  2083. Create a file to which an incoming message may be written.
  2084. @type octets: L{int}
  2085. @param octets: The number of octets which will be written to the file
  2086. @rtype: Any object which implements C{write(string)} and
  2087. C{seek(int, int)}
  2088. @return: A file-like object
  2089. """
  2090. if octets > self._memoryFileLimit:
  2091. return tempfile.TemporaryFile()
  2092. else:
  2093. return BytesIO()
  2094. def makeTag(self):
  2095. tag = (u'%0.4X' % self.tagID).encode("ascii")
  2096. self.tagID += 1
  2097. return tag
  2098. def dispatchCommand(self, tag, rest):
  2099. if self.state is None:
  2100. f = self.response_UNAUTH
  2101. else:
  2102. f = getattr(self, 'response_' + self.state.upper(), None)
  2103. if f:
  2104. try:
  2105. f(tag, rest)
  2106. except:
  2107. log.err()
  2108. self.transport.loseConnection()
  2109. else:
  2110. log.err("Cannot dispatch: %s, %r, %r" % (self.state, tag, rest))
  2111. self.transport.loseConnection()
  2112. def response_UNAUTH(self, tag, rest):
  2113. if self.state is None:
  2114. # Server greeting, this is
  2115. status, rest = rest.split(None, 1)
  2116. if status.upper() == b'OK':
  2117. self.state = 'unauth'
  2118. elif status.upper() == b'PREAUTH':
  2119. self.state = 'auth'
  2120. else:
  2121. # XXX - This is rude.
  2122. self.transport.loseConnection()
  2123. raise IllegalServerResponse(tag + b' ' + rest)
  2124. b, e = rest.find(b'['), rest.find(b']')
  2125. if b != -1 and e != -1:
  2126. self.serverGreeting(
  2127. self.__cbCapabilities(
  2128. ([parseNestedParens(rest[b + 1:e])], None)))
  2129. else:
  2130. self.serverGreeting(None)
  2131. else:
  2132. self._defaultHandler(tag, rest)
  2133. def response_AUTH(self, tag, rest):
  2134. self._defaultHandler(tag, rest)
  2135. def _defaultHandler(self, tag, rest):
  2136. if tag == b'*' or tag == b'+':
  2137. if not self.waiting:
  2138. self._extraInfo([parseNestedParens(rest)])
  2139. else:
  2140. cmd = self.tags[self.waiting]
  2141. if tag == b'+':
  2142. cmd.continuation(rest)
  2143. else:
  2144. cmd.lines.append(rest)
  2145. else:
  2146. try:
  2147. cmd = self.tags[tag]
  2148. except KeyError:
  2149. # XXX - This is rude.
  2150. self.transport.loseConnection()
  2151. raise IllegalServerResponse(tag + b' ' + rest)
  2152. else:
  2153. status, line = rest.split(None, 1)
  2154. if status == b'OK':
  2155. # Give them this last line, too
  2156. cmd.finish(rest, self._extraInfo)
  2157. else:
  2158. cmd.defer.errback(IMAP4Exception(line))
  2159. del self.tags[tag]
  2160. self.waiting = None
  2161. self._flushQueue()
  2162. def _flushQueue(self):
  2163. if self.queued:
  2164. cmd = self.queued.pop(0)
  2165. t = self.makeTag()
  2166. self.tags[t] = cmd
  2167. self.sendLine(cmd.format(t))
  2168. self.waiting = t
  2169. def _extraInfo(self, lines):
  2170. # XXX - This is terrible.
  2171. # XXX - Also, this should collapse temporally proximate calls into single
  2172. # invocations of IMailboxListener methods, where possible.
  2173. flags = {}
  2174. recent = exists = None
  2175. for response in lines:
  2176. elements = len(response)
  2177. if elements == 1 and response[0] == [b'READ-ONLY']:
  2178. self.modeChanged(False)
  2179. elif elements == 1 and response[0] == [b'READ-WRITE']:
  2180. self.modeChanged(True)
  2181. elif elements == 2 and response[1] == b'EXISTS':
  2182. exists = int(response[0])
  2183. elif elements == 2 and response[1] == b'RECENT':
  2184. recent = int(response[0])
  2185. elif elements == 3 and response[1] == b'FETCH':
  2186. mId = int(response[0])
  2187. values, _ = self._parseFetchPairs(response[2])
  2188. flags.setdefault(mId, []).extend(values.get('FLAGS', ()))
  2189. else:
  2190. log.msg('Unhandled unsolicited response: %s' % (response,))
  2191. if flags:
  2192. self.flagsChanged(flags)
  2193. if recent is not None or exists is not None:
  2194. self.newMessages(exists, recent)
  2195. def sendCommand(self, cmd):
  2196. cmd.defer = defer.Deferred()
  2197. if self.waiting:
  2198. self.queued.append(cmd)
  2199. return cmd.defer
  2200. t = self.makeTag()
  2201. self.tags[t] = cmd
  2202. self.sendLine(cmd.format(t))
  2203. self.waiting = t
  2204. self._lastCmd = cmd
  2205. return cmd.defer
  2206. def getCapabilities(self, useCache=1):
  2207. """
  2208. Request the capabilities available on this server.
  2209. This command is allowed in any state of connection.
  2210. @type useCache: C{bool}
  2211. @param useCache: Specify whether to use the capability-cache or to
  2212. re-retrieve the capabilities from the server. Server capabilities
  2213. should never change, so for normal use, this flag should never be
  2214. false.
  2215. @rtype: L{Deferred}
  2216. @return: A deferred whose callback will be invoked with a
  2217. dictionary mapping capability types to lists of supported
  2218. mechanisms, or to None if a support list is not applicable.
  2219. """
  2220. if useCache and self._capCache is not None:
  2221. return defer.succeed(self._capCache)
  2222. cmd = b'CAPABILITY'
  2223. resp = (b'CAPABILITY',)
  2224. d = self.sendCommand(Command(cmd, wantResponse=resp))
  2225. d.addCallback(self.__cbCapabilities)
  2226. return d
  2227. def __cbCapabilities(self, result):
  2228. (lines, tagline) = result
  2229. caps = {}
  2230. for rest in lines:
  2231. for cap in rest[1:]:
  2232. parts = cap.split(b'=', 1)
  2233. if len(parts) == 1:
  2234. category, value = parts[0], None
  2235. else:
  2236. category, value = parts
  2237. caps.setdefault(category, []).append(value)
  2238. # Preserve a non-ideal API for backwards compatibility. It would
  2239. # probably be entirely sensible to have an object with a wider API than
  2240. # dict here so this could be presented less insanely.
  2241. for category in caps:
  2242. if caps[category] == [None]:
  2243. caps[category] = None
  2244. self._capCache = caps
  2245. return caps
  2246. def logout(self):
  2247. """
  2248. Inform the server that we are done with the connection.
  2249. This command is allowed in any state of connection.
  2250. @rtype: L{Deferred}
  2251. @return: A deferred whose callback will be invoked with None
  2252. when the proper server acknowledgement has been received.
  2253. """
  2254. d = self.sendCommand(Command(b'LOGOUT', wantResponse=(b'BYE',)))
  2255. d.addCallback(self.__cbLogout)
  2256. return d
  2257. def __cbLogout(self, result):
  2258. (lines, tagline) = result
  2259. self.transport.loseConnection()
  2260. # We don't particularly care what the server said
  2261. return None
  2262. def noop(self):
  2263. """
  2264. Perform no operation.
  2265. This command is allowed in any state of connection.
  2266. @rtype: L{Deferred}
  2267. @return: A deferred whose callback will be invoked with a list
  2268. of untagged status updates the server responds with.
  2269. """
  2270. d = self.sendCommand(Command(b'NOOP'))
  2271. d.addCallback(self.__cbNoop)
  2272. return d
  2273. def __cbNoop(self, result):
  2274. # Conceivable, this is elidable.
  2275. # It is, afterall, a no-op.
  2276. (lines, tagline) = result
  2277. return lines
  2278. def startTLS(self, contextFactory=None):
  2279. """
  2280. Initiates a 'STARTTLS' request and negotiates the TLS / SSL
  2281. Handshake.
  2282. @param contextFactory: The TLS / SSL Context Factory to
  2283. leverage. If the contextFactory is None the IMAP4Client will
  2284. either use the current TLS / SSL Context Factory or attempt to
  2285. create a new one.
  2286. @type contextFactory: C{ssl.ClientContextFactory}
  2287. @return: A Deferred which fires when the transport has been
  2288. secured according to the given contextFactory, or which fails
  2289. if the transport cannot be secured.
  2290. """
  2291. assert not self.startedTLS, "Client and Server are currently communicating via TLS"
  2292. if contextFactory is None:
  2293. contextFactory = self._getContextFactory()
  2294. if contextFactory is None:
  2295. return defer.fail(IMAP4Exception(
  2296. "IMAP4Client requires a TLS context to "
  2297. "initiate the STARTTLS handshake"))
  2298. if b'STARTTLS' not in self._capCache:
  2299. return defer.fail(IMAP4Exception(
  2300. "Server does not support secure communication "
  2301. "via TLS / SSL"))
  2302. tls = interfaces.ITLSTransport(self.transport, None)
  2303. if tls is None:
  2304. return defer.fail(IMAP4Exception(
  2305. "IMAP4Client transport does not implement "
  2306. "interfaces.ITLSTransport"))
  2307. d = self.sendCommand(Command(b'STARTTLS'))
  2308. d.addCallback(self._startedTLS, contextFactory)
  2309. d.addCallback(lambda _: self.getCapabilities())
  2310. return d
  2311. def authenticate(self, secret):
  2312. """
  2313. Attempt to enter the authenticated state with the server
  2314. This command is allowed in the Non-Authenticated state.
  2315. @rtype: L{Deferred}
  2316. @return: A deferred whose callback is invoked if the authentication
  2317. succeeds and whose errback will be invoked otherwise.
  2318. """
  2319. if self._capCache is None:
  2320. d = self.getCapabilities()
  2321. else:
  2322. d = defer.succeed(self._capCache)
  2323. d.addCallback(self.__cbAuthenticate, secret)
  2324. return d
  2325. def __cbAuthenticate(self, caps, secret):
  2326. auths = caps.get(b'AUTH', ())
  2327. for scheme in auths:
  2328. if scheme.upper() in self.authenticators:
  2329. cmd = Command(b'AUTHENTICATE', scheme, (),
  2330. self.__cbContinueAuth, scheme,
  2331. secret)
  2332. return self.sendCommand(cmd)
  2333. if self.startedTLS:
  2334. return defer.fail(NoSupportedAuthentication(
  2335. auths, self.authenticators.keys()))
  2336. else:
  2337. def ebStartTLS(err):
  2338. err.trap(IMAP4Exception)
  2339. # We couldn't negotiate TLS for some reason
  2340. return defer.fail(NoSupportedAuthentication(
  2341. auths, self.authenticators.keys()))
  2342. d = self.startTLS()
  2343. d.addErrback(ebStartTLS)
  2344. d.addCallback(lambda _: self.getCapabilities())
  2345. d.addCallback(self.__cbAuthTLS, secret)
  2346. return d
  2347. def __cbContinueAuth(self, rest, scheme, secret):
  2348. try:
  2349. chal = decodebytes(rest + b'\n')
  2350. except binascii.Error:
  2351. self.sendLine(b'*')
  2352. raise IllegalServerResponse(rest)
  2353. else:
  2354. auth = self.authenticators[scheme]
  2355. chal = auth.challengeResponse(secret, chal)
  2356. self.sendLine(encodebytes(chal).strip())
  2357. def __cbAuthTLS(self, caps, secret):
  2358. auths = caps.get(b'AUTH', ())
  2359. for scheme in auths:
  2360. if scheme.upper() in self.authenticators:
  2361. cmd = Command(b'AUTHENTICATE', scheme, (),
  2362. self.__cbContinueAuth, scheme,
  2363. secret)
  2364. return self.sendCommand(cmd)
  2365. raise NoSupportedAuthentication(auths, self.authenticators.keys())
  2366. def login(self, username, password):
  2367. """
  2368. Authenticate with the server using a username and password
  2369. This command is allowed in the Non-Authenticated state. If the
  2370. server supports the STARTTLS capability and our transport supports
  2371. TLS, TLS is negotiated before the login command is issued.
  2372. A more secure way to log in is to use C{startTLS} or
  2373. C{authenticate} or both.
  2374. @type username: L{str}
  2375. @param username: The username to log in with
  2376. @type password: L{str}
  2377. @param password: The password to log in with
  2378. @rtype: L{Deferred}
  2379. @return: A deferred whose callback is invoked if login is successful
  2380. and whose errback is invoked otherwise.
  2381. """
  2382. d = maybeDeferred(self.getCapabilities)
  2383. d.addCallback(self.__cbLoginCaps, username, password)
  2384. return d
  2385. def serverGreeting(self, caps):
  2386. """
  2387. Called when the server has sent us a greeting.
  2388. @type caps: C{dict}
  2389. @param caps: Capabilities the server advertised in its greeting.
  2390. """
  2391. def _getContextFactory(self):
  2392. if self.context is not None:
  2393. return self.context
  2394. try:
  2395. from twisted.internet import ssl
  2396. except ImportError:
  2397. return None
  2398. else:
  2399. context = ssl.ClientContextFactory()
  2400. context.method = ssl.SSL.TLSv1_METHOD
  2401. return context
  2402. def __cbLoginCaps(self, capabilities, username, password):
  2403. # If the server advertises STARTTLS, we might want to try to switch to TLS
  2404. tryTLS = b'STARTTLS' in capabilities
  2405. # If our transport supports switching to TLS, we might want to try to switch to TLS.
  2406. tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None
  2407. # If our transport is not already using TLS, we might want to try to switch to TLS.
  2408. nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None
  2409. if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
  2410. d = self.startTLS()
  2411. d.addCallbacks(
  2412. self.__cbLoginTLS,
  2413. self.__ebLoginTLS,
  2414. callbackArgs=(username, password),
  2415. )
  2416. return d
  2417. else:
  2418. if nontlsTransport:
  2419. log.msg("Server has no TLS support. logging in over cleartext!")
  2420. args = b' '.join((_quote(username), _quote(password)))
  2421. return self.sendCommand(Command(b'LOGIN', args))
  2422. def _startedTLS(self, result, context):
  2423. self.transport.startTLS(context)
  2424. self._capCache = None
  2425. self.startedTLS = True
  2426. return result
  2427. def __cbLoginTLS(self, result, username, password):
  2428. args = b' '.join((_quote(username), _quote(password)))
  2429. return self.sendCommand(Command(b'LOGIN', args))
  2430. def __ebLoginTLS(self, failure):
  2431. log.err(failure)
  2432. return failure
  2433. def namespace(self):
  2434. """
  2435. Retrieve information about the namespaces available to this account
  2436. This command is allowed in the Authenticated and Selected states.
  2437. @rtype: L{Deferred}
  2438. @return: A deferred whose callback is invoked with namespace
  2439. information. An example of this information is::
  2440. [[['', '/']], [], []]
  2441. which indicates a single personal namespace called '' with '/'
  2442. as its hierarchical delimiter, and no shared or user namespaces.
  2443. """
  2444. cmd = b'NAMESPACE'
  2445. resp = (b'NAMESPACE',)
  2446. d = self.sendCommand(Command(cmd, wantResponse=resp))
  2447. d.addCallback(self.__cbNamespace)
  2448. return d
  2449. def __cbNamespace(self, result):
  2450. (lines, last) = result
  2451. # Namespaces and their delimiters qualify and delimit
  2452. # mailboxes, so they should be native strings
  2453. #
  2454. # On Python 2, no decoding is necessary to maintain
  2455. # the API contract.
  2456. #
  2457. # On Python 3, users specify mailboxes with native strings, so
  2458. # they should receive namespaces and delimiters as native
  2459. # strings. Both cases are possible because of the imap4-utf-7
  2460. # encoding.
  2461. if _PY3:
  2462. def _prepareNamespaceOrDelimiter(namespaceList):
  2463. return [
  2464. element.decode('imap4-utf-7') for element in namespaceList
  2465. ]
  2466. else:
  2467. def _prepareNamespaceOrDelimiter(element):
  2468. return element
  2469. for parts in lines:
  2470. if len(parts) == 4 and parts[0] == b'NAMESPACE':
  2471. return [
  2472. []
  2473. if pairOrNone is None else
  2474. [
  2475. _prepareNamespaceOrDelimiter(value)
  2476. for value in pairOrNone
  2477. ]
  2478. for pairOrNone in parts[1:]
  2479. ]
  2480. log.err("No NAMESPACE response to NAMESPACE command")
  2481. return [[], [], []]
  2482. def select(self, mailbox):
  2483. """
  2484. Select a mailbox
  2485. This command is allowed in the Authenticated and Selected states.
  2486. @type mailbox: L{str}
  2487. @param mailbox: The name of the mailbox to select
  2488. @rtype: L{Deferred}
  2489. @return: A deferred whose callback is invoked with mailbox
  2490. information if the select is successful and whose errback is
  2491. invoked otherwise. Mailbox information consists of a dictionary
  2492. with the following L{str} keys and values::
  2493. FLAGS: A list of strings containing the flags settable on
  2494. messages in this mailbox.
  2495. EXISTS: An integer indicating the number of messages in this
  2496. mailbox.
  2497. RECENT: An integer indicating the number of "recent"
  2498. messages in this mailbox.
  2499. UNSEEN: The message sequence number (an integer) of the
  2500. first unseen message in the mailbox.
  2501. PERMANENTFLAGS: A list of strings containing the flags that
  2502. can be permanently set on messages in this mailbox.
  2503. UIDVALIDITY: An integer uniquely identifying this mailbox.
  2504. """
  2505. cmd = b'SELECT'
  2506. args = _prepareMailboxName(mailbox)
  2507. # This appears not to be used, so we can use native strings to
  2508. # indicate that the return type is native strings.
  2509. resp = ('FLAGS', 'EXISTS', 'RECENT',
  2510. 'UNSEEN', 'PERMANENTFLAGS', 'UIDVALIDITY')
  2511. d = self.sendCommand(Command(cmd, args, wantResponse=resp))
  2512. d.addCallback(self.__cbSelect, 1)
  2513. return d
  2514. def examine(self, mailbox):
  2515. """
  2516. Select a mailbox in read-only mode
  2517. This command is allowed in the Authenticated and Selected states.
  2518. @type mailbox: L{str}
  2519. @param mailbox: The name of the mailbox to examine
  2520. @rtype: L{Deferred}
  2521. @return: A deferred whose callback is invoked with mailbox
  2522. information if the examine is successful and whose errback
  2523. is invoked otherwise. Mailbox information consists of a dictionary
  2524. with the following keys and values::
  2525. 'FLAGS': A list of strings containing the flags settable on
  2526. messages in this mailbox.
  2527. 'EXISTS': An integer indicating the number of messages in this
  2528. mailbox.
  2529. 'RECENT': An integer indicating the number of \"recent\"
  2530. messages in this mailbox.
  2531. 'UNSEEN': An integer indicating the number of messages not
  2532. flagged \\Seen in this mailbox.
  2533. 'PERMANENTFLAGS': A list of strings containing the flags that
  2534. can be permanently set on messages in this mailbox.
  2535. 'UIDVALIDITY': An integer uniquely identifying this mailbox.
  2536. """
  2537. cmd = b'EXAMINE'
  2538. args = _prepareMailboxName(mailbox)
  2539. resp = (b'FLAGS', b'EXISTS', b'RECENT', b'UNSEEN', b'PERMANENTFLAGS', b'UIDVALIDITY')
  2540. d = self.sendCommand(Command(cmd, args, wantResponse=resp))
  2541. d.addCallback(self.__cbSelect, 0)
  2542. return d
  2543. def _intOrRaise(self, value, phrase):
  2544. """
  2545. Parse C{value} as an integer and return the result or raise
  2546. L{IllegalServerResponse} with C{phrase} as an argument if C{value}
  2547. cannot be parsed as an integer.
  2548. """
  2549. try:
  2550. return int(value)
  2551. except ValueError:
  2552. raise IllegalServerResponse(phrase)
  2553. def __cbSelect(self, result, rw):
  2554. """
  2555. Handle lines received in response to a SELECT or EXAMINE command.
  2556. See RFC 3501, section 6.3.1.
  2557. """
  2558. (lines, tagline) = result
  2559. # In the absence of specification, we are free to assume:
  2560. # READ-WRITE access
  2561. datum = {'READ-WRITE': rw}
  2562. lines.append(parseNestedParens(tagline))
  2563. for split in lines:
  2564. if len(split) > 0 and split[0].upper() == b'OK':
  2565. # Handle all the kinds of OK response.
  2566. content = split[1]
  2567. if isinstance(content, list):
  2568. key = content[0]
  2569. else:
  2570. # not multi-valued, like OK LOGIN
  2571. key = content
  2572. key = key.upper()
  2573. if key == b'READ-ONLY':
  2574. datum['READ-WRITE'] = False
  2575. elif key == b'READ-WRITE':
  2576. datum['READ-WRITE'] = True
  2577. elif key == b'UIDVALIDITY':
  2578. datum['UIDVALIDITY'] = self._intOrRaise(content[1], split)
  2579. elif key == b'UNSEEN':
  2580. datum['UNSEEN'] = self._intOrRaise(content[1], split)
  2581. elif key == b'UIDNEXT':
  2582. datum['UIDNEXT'] = self._intOrRaise(content[1], split)
  2583. elif key == b'PERMANENTFLAGS':
  2584. datum['PERMANENTFLAGS'] = tuple(
  2585. nativeString(flag) for flag in content[1])
  2586. else:
  2587. log.err('Unhandled SELECT response (2): %s' % (split,))
  2588. elif len(split) == 2:
  2589. # Handle FLAGS, EXISTS, and RECENT
  2590. if split[0].upper() == b'FLAGS':
  2591. datum['FLAGS'] = tuple(
  2592. nativeString(flag) for flag in split[1])
  2593. elif isinstance(split[1], bytes):
  2594. # Must make sure things are strings before treating them as
  2595. # strings since some other forms of response have nesting in
  2596. # places which results in lists instead.
  2597. if split[1].upper() == b'EXISTS':
  2598. datum['EXISTS'] = self._intOrRaise(split[0], split)
  2599. elif split[1].upper() == b'RECENT':
  2600. datum['RECENT'] = self._intOrRaise(split[0], split)
  2601. else:
  2602. log.err('Unhandled SELECT response (0): %s' % (split,))
  2603. else:
  2604. log.err('Unhandled SELECT response (1): %s' % (split,))
  2605. else:
  2606. log.err('Unhandled SELECT response (4): %s' % (split,))
  2607. return datum
  2608. def create(self, name):
  2609. """
  2610. Create a new mailbox on the server
  2611. This command is allowed in the Authenticated and Selected states.
  2612. @type name: L{str}
  2613. @param name: The name of the mailbox to create.
  2614. @rtype: L{Deferred}
  2615. @return: A deferred whose callback is invoked if the mailbox creation
  2616. is successful and whose errback is invoked otherwise.
  2617. """
  2618. return self.sendCommand(Command(b'CREATE', _prepareMailboxName(name)))
  2619. def delete(self, name):
  2620. """
  2621. Delete a mailbox
  2622. This command is allowed in the Authenticated and Selected states.
  2623. @type name: L{str}
  2624. @param name: The name of the mailbox to delete.
  2625. @rtype: L{Deferred}
  2626. @return: A deferred whose calblack is invoked if the mailbox is
  2627. deleted successfully and whose errback is invoked otherwise.
  2628. """
  2629. return self.sendCommand(Command(b'DELETE', _prepareMailboxName(name)))
  2630. def rename(self, oldname, newname):
  2631. """
  2632. Rename a mailbox
  2633. This command is allowed in the Authenticated and Selected states.
  2634. @type oldname: L{str}
  2635. @param oldname: The current name of the mailbox to rename.
  2636. @type newname: L{str}
  2637. @param newname: The new name to give the mailbox.
  2638. @rtype: L{Deferred}
  2639. @return: A deferred whose callback is invoked if the rename is
  2640. successful and whose errback is invoked otherwise.
  2641. """
  2642. oldname = _prepareMailboxName(oldname)
  2643. newname = _prepareMailboxName(newname)
  2644. return self.sendCommand(Command(b'RENAME', b' '.join((oldname, newname))))
  2645. def subscribe(self, name):
  2646. """
  2647. Add a mailbox to the subscription list
  2648. This command is allowed in the Authenticated and Selected states.
  2649. @type name: L{str}
  2650. @param name: The mailbox to mark as 'active' or 'subscribed'
  2651. @rtype: L{Deferred}
  2652. @return: A deferred whose callback is invoked if the subscription
  2653. is successful and whose errback is invoked otherwise.
  2654. """
  2655. return self.sendCommand(Command(b'SUBSCRIBE', _prepareMailboxName(name)))
  2656. def unsubscribe(self, name):
  2657. """
  2658. Remove a mailbox from the subscription list
  2659. This command is allowed in the Authenticated and Selected states.
  2660. @type name: L{str}
  2661. @param name: The mailbox to unsubscribe
  2662. @rtype: L{Deferred}
  2663. @return: A deferred whose callback is invoked if the unsubscription
  2664. is successful and whose errback is invoked otherwise.
  2665. """
  2666. return self.sendCommand(Command(b'UNSUBSCRIBE', _prepareMailboxName(name)))
  2667. def list(self, reference, wildcard):
  2668. """
  2669. List a subset of the available mailboxes
  2670. This command is allowed in the Authenticated and Selected
  2671. states.
  2672. @type reference: L{str}
  2673. @param reference: The context in which to interpret
  2674. C{wildcard}
  2675. @type wildcard: L{str}
  2676. @param wildcard: The pattern of mailbox names to match,
  2677. optionally including either or both of the '*' and '%'
  2678. wildcards. '*' will match zero or more characters and
  2679. cross hierarchical boundaries. '%' will also match zero
  2680. or more characters, but is limited to a single
  2681. hierarchical level.
  2682. @rtype: L{Deferred}
  2683. @return: A deferred whose callback is invoked with a list of
  2684. L{tuple}s, the first element of which is a L{tuple} of
  2685. mailbox flags, the second element of which is the
  2686. hierarchy delimiter for this mailbox, and the third of
  2687. which is the mailbox name; if the command is unsuccessful,
  2688. the deferred's errback is invoked instead. B{NB}: the
  2689. delimiter and the mailbox name are L{str}s.
  2690. """
  2691. cmd = b'LIST'
  2692. args = ('"%s" "%s"' % (reference, wildcard)).encode("imap4-utf-7")
  2693. resp = (b'LIST',)
  2694. d = self.sendCommand(Command(cmd, args, wantResponse=resp))
  2695. d.addCallback(self.__cbList, b'LIST')
  2696. return d
  2697. def lsub(self, reference, wildcard):
  2698. """
  2699. List a subset of the subscribed available mailboxes
  2700. This command is allowed in the Authenticated and Selected states.
  2701. The parameters and returned object are the same as for the L{list}
  2702. method, with one slight difference: Only mailboxes which have been
  2703. subscribed can be included in the resulting list.
  2704. """
  2705. cmd = b'LSUB'
  2706. encodedReference = reference.encode('ascii')
  2707. encodedWildcard = wildcard.encode('imap4-utf-7')
  2708. args = b"".join([
  2709. b'"', encodedReference, b'"'
  2710. b' "', encodedWildcard, b'"',
  2711. ])
  2712. resp = (b'LSUB',)
  2713. d = self.sendCommand(Command(cmd, args, wantResponse=resp))
  2714. d.addCallback(self.__cbList, b'LSUB')
  2715. return d
  2716. def __cbList(self, result, command):
  2717. (lines, last) = result
  2718. results = []
  2719. for parts in lines:
  2720. if len(parts) == 4 and parts[0] == command:
  2721. # flags
  2722. parts[1] = tuple(nativeString(flag) for flag in parts[1])
  2723. # The mailbox should be a native string.
  2724. # On Python 2, this maintains the API's contract.
  2725. #
  2726. # On Python 3, users specify mailboxes with native
  2727. # strings, so they should receive mailboxes as native
  2728. # strings. Both cases are possible because of the
  2729. # imap4-utf-7 encoding.
  2730. #
  2731. # Mailbox names contain the hierarchical delimiter, so
  2732. # it too should be a native string.
  2733. if _PY3:
  2734. # delimiter
  2735. parts[2] = parts[2].decode('imap4-utf-7')
  2736. # mailbox
  2737. parts[3] = parts[3].decode('imap4-utf-7')
  2738. results.append(tuple(parts[1:]))
  2739. return results
  2740. _statusNames = {
  2741. name: name.encode('ascii') for name in (
  2742. 'MESSAGES',
  2743. 'RECENT',
  2744. 'UIDNEXT',
  2745. 'UIDVALIDITY',
  2746. 'UNSEEN',
  2747. )
  2748. }
  2749. def status(self, mailbox, *names):
  2750. """
  2751. Retrieve the status of the given mailbox
  2752. This command is allowed in the Authenticated and Selected states.
  2753. @type mailbox: L{str}
  2754. @param mailbox: The name of the mailbox to query
  2755. @type *names: L{bytes}
  2756. @param *names: The status names to query. These may be any number of:
  2757. C{'MESSAGES'}, C{'RECENT'}, C{'UIDNEXT'}, C{'UIDVALIDITY'}, and
  2758. C{'UNSEEN'}.
  2759. @rtype: L{Deferred}
  2760. @return: A deferred which fires with the status information if the
  2761. command is successful and whose errback is invoked otherwise. The
  2762. status information is in the form of a C{dict}. Each element of
  2763. C{names} is a key in the dictionary. The value for each key is the
  2764. corresponding response from the server.
  2765. """
  2766. cmd = b'STATUS'
  2767. preparedMailbox = _prepareMailboxName(mailbox)
  2768. try:
  2769. names = b' '.join(self._statusNames[name] for name in names)
  2770. except KeyError:
  2771. raise ValueError("Unknown names: {!r}".format(
  2772. set(names) - set(self._statusNames)
  2773. ))
  2774. args = b''.join([preparedMailbox,
  2775. b" (", names, b")"])
  2776. resp = (b'STATUS',)
  2777. d = self.sendCommand(Command(cmd, args, wantResponse=resp))
  2778. d.addCallback(self.__cbStatus)
  2779. return d
  2780. def __cbStatus(self, result):
  2781. (lines, last) = result
  2782. status = {}
  2783. for parts in lines:
  2784. if parts[0] == b'STATUS':
  2785. items = parts[2]
  2786. items = [items[i:i+2] for i in range(0, len(items), 2)]
  2787. for k, v in items:
  2788. try:
  2789. status[nativeString(k)] = v
  2790. except UnicodeDecodeError:
  2791. raise IllegalServerResponse(repr(items))
  2792. for k in status.keys():
  2793. t = self.STATUS_TRANSFORMATIONS.get(k)
  2794. if t:
  2795. try:
  2796. status[k] = t(status[k])
  2797. except Exception as e:
  2798. raise IllegalServerResponse('(' + k + ' '+ status[k] + '): ' + str(e))
  2799. return status
  2800. def append(self, mailbox, message, flags = (), date = None):
  2801. """
  2802. Add the given message to the given mailbox.
  2803. This command is allowed in the Authenticated and Selected states.
  2804. @type mailbox: L{str}
  2805. @param mailbox: The mailbox to which to add this message.
  2806. @type message: Any file-like object opened in B{binary mode}.
  2807. @param message: The message to add, in RFC822 format. Newlines
  2808. in this file should be \\r\\n-style.
  2809. @type flags: Any iterable of L{str}
  2810. @param flags: The flags to associated with this message.
  2811. @type date: L{str}
  2812. @param date: The date to associate with this message. This should
  2813. be of the format DD-MM-YYYY HH:MM:SS +/-HHMM. For example, in
  2814. Eastern Standard Time, on July 1st 2004 at half past 1 PM,
  2815. \"01-07-2004 13:30:00 -0500\".
  2816. @rtype: L{Deferred}
  2817. @return: A deferred whose callback is invoked when this command
  2818. succeeds or whose errback is invoked if it fails.
  2819. """
  2820. message.seek(0, 2)
  2821. L = message.tell()
  2822. message.seek(0, 0)
  2823. if date:
  2824. date = networkString(' "%s"' % nativeString(date))
  2825. else:
  2826. date = b''
  2827. encodedFlags = [networkString(flag) for flag in flags]
  2828. cmd = b''.join([
  2829. _prepareMailboxName(mailbox),
  2830. b" (", b" ".join(encodedFlags), b")",
  2831. date,
  2832. b" {", intToBytes(L), b"}",
  2833. ])
  2834. d = self.sendCommand(Command(b'APPEND', cmd, (), self.__cbContinueAppend, message))
  2835. return d
  2836. def __cbContinueAppend(self, lines, message):
  2837. s = basic.FileSender()
  2838. return s.beginFileTransfer(message, self.transport, None
  2839. ).addCallback(self.__cbFinishAppend)
  2840. def __cbFinishAppend(self, foo):
  2841. self.sendLine(b'')
  2842. def check(self):
  2843. """
  2844. Tell the server to perform a checkpoint
  2845. This command is allowed in the Selected state.
  2846. @rtype: L{Deferred}
  2847. @return: A deferred whose callback is invoked when this command
  2848. succeeds or whose errback is invoked if it fails.
  2849. """
  2850. return self.sendCommand(Command(b'CHECK'))
  2851. def close(self):
  2852. """
  2853. Return the connection to the Authenticated state.
  2854. This command is allowed in the Selected state.
  2855. Issuing this command will also remove all messages flagged \\Deleted
  2856. from the selected mailbox if it is opened in read-write mode,
  2857. otherwise it indicates success by no messages are removed.
  2858. @rtype: L{Deferred}
  2859. @return: A deferred whose callback is invoked when the command
  2860. completes successfully or whose errback is invoked if it fails.
  2861. """
  2862. return self.sendCommand(Command(b'CLOSE'))
  2863. def expunge(self):
  2864. """
  2865. Return the connection to the Authenticate state.
  2866. This command is allowed in the Selected state.
  2867. Issuing this command will perform the same actions as issuing the
  2868. close command, but will also generate an 'expunge' response for
  2869. every message deleted.
  2870. @rtype: L{Deferred}
  2871. @return: A deferred whose callback is invoked with a list of the
  2872. 'expunge' responses when this command is successful or whose errback
  2873. is invoked otherwise.
  2874. """
  2875. cmd = b'EXPUNGE'
  2876. resp = (b'EXPUNGE',)
  2877. d = self.sendCommand(Command(cmd, wantResponse=resp))
  2878. d.addCallback(self.__cbExpunge)
  2879. return d
  2880. def __cbExpunge(self, result):
  2881. (lines, last) = result
  2882. ids = []
  2883. for parts in lines:
  2884. if len(parts) == 2 and parts[1] == b'EXPUNGE':
  2885. ids.append(self._intOrRaise(parts[0], parts))
  2886. return ids
  2887. def search(self, *queries, **kwarg):
  2888. """
  2889. Search messages in the currently selected mailbox
  2890. This command is allowed in the Selected state.
  2891. Any non-zero number of queries are accepted by this method, as returned
  2892. by the C{Query}, C{Or}, and C{Not} functions.
  2893. @param uid: if true, the server is asked to return message UIDs instead
  2894. of message sequence numbers. (This is a keyword-only argument.)
  2895. @type uid: L{bool}
  2896. @rtype: L{Deferred}
  2897. @return: A deferred whose callback will be invoked with a list of all
  2898. the message sequence numbers return by the search, or whose errback
  2899. will be invoked if there is an error.
  2900. """
  2901. # Queries should be encoded as ASCII unless a charset
  2902. # identifier is provided. See #9201.
  2903. if _PY3:
  2904. queries = [query.encode('charmap') for query in queries]
  2905. if kwarg.get('uid'):
  2906. cmd = b'UID SEARCH'
  2907. else:
  2908. cmd = b'SEARCH'
  2909. args = b' '.join(queries)
  2910. d = self.sendCommand(Command(cmd, args, wantResponse=(cmd,)))
  2911. d.addCallback(self.__cbSearch)
  2912. return d
  2913. def __cbSearch(self, result):
  2914. (lines, end) = result
  2915. ids = []
  2916. for parts in lines:
  2917. if len(parts) > 0 and parts[0] == b'SEARCH':
  2918. ids.extend([self._intOrRaise(p, parts) for p in parts[1:]])
  2919. return ids
  2920. def fetchUID(self, messages, uid=0):
  2921. """
  2922. Retrieve the unique identifier for one or more messages
  2923. This command is allowed in the Selected state.
  2924. @type messages: L{MessageSet} or L{str}
  2925. @param messages: A message sequence set
  2926. @type uid: L{bool}
  2927. @param uid: Indicates whether the message sequence set is of message
  2928. numbers or of unique message IDs.
  2929. @rtype: L{Deferred}
  2930. @return: A deferred whose callback is invoked with a dict mapping
  2931. message sequence numbers to unique message identifiers, or whose
  2932. errback is invoked if there is an error.
  2933. """
  2934. return self._fetch(messages, useUID=uid, uid=1)
  2935. def fetchFlags(self, messages, uid=0):
  2936. """
  2937. Retrieve the flags for one or more messages
  2938. This command is allowed in the Selected state.
  2939. @type messages: L{MessageSet} or L{str}
  2940. @param messages: The messages for which to retrieve flags.
  2941. @type uid: L{bool}
  2942. @param uid: Indicates whether the message sequence set is of message
  2943. numbers or of unique message IDs.
  2944. @rtype: L{Deferred}
  2945. @return: A deferred whose callback is invoked with a dict mapping
  2946. message numbers to lists of flags, or whose errback is invoked if
  2947. there is an error.
  2948. """
  2949. return self._fetch(messages, useUID=uid, flags=1)
  2950. def fetchInternalDate(self, messages, uid=0):
  2951. """
  2952. Retrieve the internal date associated with one or more messages
  2953. This command is allowed in the Selected state.
  2954. @type messages: L{MessageSet} or L{str}
  2955. @param messages: The messages for which to retrieve the internal date.
  2956. @type uid: L{bool}
  2957. @param uid: Indicates whether the message sequence set is of message
  2958. numbers or of unique message IDs.
  2959. @rtype: L{Deferred}
  2960. @return: A deferred whose callback is invoked with a dict mapping
  2961. message numbers to date strings, or whose errback is invoked
  2962. if there is an error. Date strings take the format of
  2963. \"day-month-year time timezone\".
  2964. """
  2965. return self._fetch(messages, useUID=uid, internaldate=1)
  2966. def fetchEnvelope(self, messages, uid=0):
  2967. """
  2968. Retrieve the envelope data for one or more messages
  2969. This command is allowed in the Selected state.
  2970. @type messages: L{MessageSet} or L{str}
  2971. @param messages: The messages for which to retrieve envelope
  2972. data.
  2973. @type uid: L{bool}
  2974. @param uid: Indicates whether the message sequence set is of
  2975. message numbers or of unique message IDs.
  2976. @rtype: L{Deferred}
  2977. @return: A deferred whose callback is invoked with a dict
  2978. mapping message numbers to envelope data, or whose errback
  2979. is invoked if there is an error. Envelope data consists
  2980. of a sequence of the date, subject, from, sender,
  2981. reply-to, to, cc, bcc, in-reply-to, and message-id header
  2982. fields. The date, subject, in-reply-to, and message-id
  2983. fields are L{str}, while the from, sender, reply-to, to,
  2984. cc, and bcc fields contain address data as L{str}s.
  2985. Address data consists of a sequence of name, source route,
  2986. mailbox name, and hostname. Fields which are not present
  2987. for a particular address may be L{None}.
  2988. """
  2989. return self._fetch(messages, useUID=uid, envelope=1)
  2990. def fetchBodyStructure(self, messages, uid=0):
  2991. """
  2992. Retrieve the structure of the body of one or more messages
  2993. This command is allowed in the Selected state.
  2994. @type messages: L{MessageSet} or L{str}
  2995. @param messages: The messages for which to retrieve body structure
  2996. data.
  2997. @type uid: L{bool}
  2998. @param uid: Indicates whether the message sequence set is of message
  2999. numbers or of unique message IDs.
  3000. @rtype: L{Deferred}
  3001. @return: A deferred whose callback is invoked with a dict mapping
  3002. message numbers to body structure data, or whose errback is invoked
  3003. if there is an error. Body structure data describes the MIME-IMB
  3004. format of a message and consists of a sequence of mime type, mime
  3005. subtype, parameters, content id, description, encoding, and size.
  3006. The fields following the size field are variable: if the mime
  3007. type/subtype is message/rfc822, the contained message's envelope
  3008. information, body structure data, and number of lines of text; if
  3009. the mime type is text, the number of lines of text. Extension fields
  3010. may also be included; if present, they are: the MD5 hash of the body,
  3011. body disposition, body language.
  3012. """
  3013. return self._fetch(messages, useUID=uid, bodystructure=1)
  3014. def fetchSimplifiedBody(self, messages, uid=0):
  3015. """
  3016. Retrieve the simplified body structure of one or more messages
  3017. This command is allowed in the Selected state.
  3018. @type messages: L{MessageSet} or L{str}
  3019. @param messages: A message sequence set
  3020. @type uid: C{bool}
  3021. @param uid: Indicates whether the message sequence set is of message
  3022. numbers or of unique message IDs.
  3023. @rtype: L{Deferred}
  3024. @return: A deferred whose callback is invoked with a dict mapping
  3025. message numbers to body data, or whose errback is invoked
  3026. if there is an error. The simplified body structure is the same
  3027. as the body structure, except that extension fields will never be
  3028. present.
  3029. """
  3030. return self._fetch(messages, useUID=uid, body=1)
  3031. def fetchMessage(self, messages, uid=0):
  3032. """
  3033. Retrieve one or more entire messages
  3034. This command is allowed in the Selected state.
  3035. @type messages: L{MessageSet} or L{str}
  3036. @param messages: A message sequence set
  3037. @type uid: C{bool}
  3038. @param uid: Indicates whether the message sequence set is of message
  3039. numbers or of unique message IDs.
  3040. @rtype: L{Deferred}
  3041. @return: A L{Deferred} which will fire with a C{dict} mapping message
  3042. sequence numbers to C{dict}s giving message data for the
  3043. corresponding message. If C{uid} is true, the inner dictionaries
  3044. have a C{'UID'} key mapped to a L{str} giving the UID for the
  3045. message. The text of the message is a L{str} associated with the
  3046. C{'RFC822'} key in each dictionary.
  3047. """
  3048. return self._fetch(messages, useUID=uid, rfc822=1)
  3049. def fetchHeaders(self, messages, uid=0):
  3050. """
  3051. Retrieve headers of one or more messages
  3052. This command is allowed in the Selected state.
  3053. @type messages: L{MessageSet} or L{str}
  3054. @param messages: A message sequence set
  3055. @type uid: L{bool}
  3056. @param uid: Indicates whether the message sequence set is of message
  3057. numbers or of unique message IDs.
  3058. @rtype: L{Deferred}
  3059. @return: A deferred whose callback is invoked with a dict mapping
  3060. message numbers to dicts of message headers, or whose errback is
  3061. invoked if there is an error.
  3062. """
  3063. return self._fetch(messages, useUID=uid, rfc822header=1)
  3064. def fetchBody(self, messages, uid=0):
  3065. """
  3066. Retrieve body text of one or more messages
  3067. This command is allowed in the Selected state.
  3068. @type messages: L{MessageSet} or L{str}
  3069. @param messages: A message sequence set
  3070. @type uid: L{bool}
  3071. @param uid: Indicates whether the message sequence set is of message
  3072. numbers or of unique message IDs.
  3073. @rtype: L{Deferred}
  3074. @return: A deferred whose callback is invoked with a dict mapping
  3075. message numbers to file-like objects containing body text, or whose
  3076. errback is invoked if there is an error.
  3077. """
  3078. return self._fetch(messages, useUID=uid, rfc822text=1)
  3079. def fetchSize(self, messages, uid=0):
  3080. """
  3081. Retrieve the size, in octets, of one or more messages
  3082. This command is allowed in the Selected state.
  3083. @type messages: L{MessageSet} or L{str}
  3084. @param messages: A message sequence set
  3085. @type uid: L{bool}
  3086. @param uid: Indicates whether the message sequence set is of message
  3087. numbers or of unique message IDs.
  3088. @rtype: L{Deferred}
  3089. @return: A deferred whose callback is invoked with a dict mapping
  3090. message numbers to sizes, or whose errback is invoked if there is
  3091. an error.
  3092. """
  3093. return self._fetch(messages, useUID=uid, rfc822size=1)
  3094. def fetchFull(self, messages, uid=0):
  3095. """
  3096. Retrieve several different fields of one or more messages
  3097. This command is allowed in the Selected state. This is equivalent
  3098. to issuing all of the C{fetchFlags}, C{fetchInternalDate},
  3099. C{fetchSize}, C{fetchEnvelope}, and C{fetchSimplifiedBody}
  3100. functions.
  3101. @type messages: L{MessageSet} or L{str}
  3102. @param messages: A message sequence set
  3103. @type uid: L{bool}
  3104. @param uid: Indicates whether the message sequence set is of message
  3105. numbers or of unique message IDs.
  3106. @rtype: L{Deferred}
  3107. @return: A deferred whose callback is invoked with a dict mapping
  3108. message numbers to dict of the retrieved data values, or whose
  3109. errback is invoked if there is an error. They dictionary keys
  3110. are "flags", "date", "size", "envelope", and "body".
  3111. """
  3112. return self._fetch(
  3113. messages, useUID=uid, flags=1, internaldate=1,
  3114. rfc822size=1, envelope=1, body=1)
  3115. def fetchAll(self, messages, uid=0):
  3116. """
  3117. Retrieve several different fields of one or more messages
  3118. This command is allowed in the Selected state. This is equivalent
  3119. to issuing all of the C{fetchFlags}, C{fetchInternalDate},
  3120. C{fetchSize}, and C{fetchEnvelope} functions.
  3121. @type messages: L{MessageSet} or L{str}
  3122. @param messages: A message sequence set
  3123. @type uid: L{bool}
  3124. @param uid: Indicates whether the message sequence set is of message
  3125. numbers or of unique message IDs.
  3126. @rtype: L{Deferred}
  3127. @return: A deferred whose callback is invoked with a dict mapping
  3128. message numbers to dict of the retrieved data values, or whose
  3129. errback is invoked if there is an error. They dictionary keys
  3130. are "flags", "date", "size", and "envelope".
  3131. """
  3132. return self._fetch(
  3133. messages, useUID=uid, flags=1, internaldate=1,
  3134. rfc822size=1, envelope=1)
  3135. def fetchFast(self, messages, uid=0):
  3136. """
  3137. Retrieve several different fields of one or more messages
  3138. This command is allowed in the Selected state. This is equivalent
  3139. to issuing all of the C{fetchFlags}, C{fetchInternalDate}, and
  3140. C{fetchSize} functions.
  3141. @type messages: L{MessageSet} or L{str}
  3142. @param messages: A message sequence set
  3143. @type uid: L{bool}
  3144. @param uid: Indicates whether the message sequence set is of message
  3145. numbers or of unique message IDs.
  3146. @rtype: L{Deferred}
  3147. @return: A deferred whose callback is invoked with a dict mapping
  3148. message numbers to dict of the retrieved data values, or whose
  3149. errback is invoked if there is an error. They dictionary keys are
  3150. "flags", "date", and "size".
  3151. """
  3152. return self._fetch(
  3153. messages, useUID=uid, flags=1, internaldate=1, rfc822size=1)
  3154. def _parseFetchPairs(self, fetchResponseList):
  3155. """
  3156. Given the result of parsing a single I{FETCH} response, construct a
  3157. L{dict} mapping response keys to response values.
  3158. @param fetchResponseList: The result of parsing a I{FETCH} response
  3159. with L{parseNestedParens} and extracting just the response data
  3160. (that is, just the part that comes after C{"FETCH"}). The form
  3161. of this input (and therefore the output of this method) is very
  3162. disagreeable. A valuable improvement would be to enumerate the
  3163. possible keys (representing them as structured objects of some
  3164. sort) rather than using strings and tuples of tuples of strings
  3165. and so forth. This would allow the keys to be documented more
  3166. easily and would allow for a much simpler application-facing API
  3167. (one not based on looking up somewhat hard to predict keys in a
  3168. dict). Since C{fetchResponseList} notionally represents a
  3169. flattened sequence of pairs (identifying keys followed by their
  3170. associated values), collapsing such complex elements of this
  3171. list as C{["BODY", ["HEADER.FIELDS", ["SUBJECT"]]]} into a
  3172. single object would also greatly simplify the implementation of
  3173. this method.
  3174. @return: A C{dict} of the response data represented by C{pairs}. Keys
  3175. in this dictionary are things like C{"RFC822.TEXT"}, C{"FLAGS"}, or
  3176. C{("BODY", ("HEADER.FIELDS", ("SUBJECT",)))}. Values are entirely
  3177. dependent on the key with which they are associated, but retain the
  3178. same structured as produced by L{parseNestedParens}.
  3179. """
  3180. # TODO: RFC 3501 Section 7.4.2, "FETCH Response", says for
  3181. # BODY responses that "8-bit textual data is permitted if a
  3182. # charset identifier is part of the body parameter
  3183. # parenthesized list". Every other component is 7-bit. This
  3184. # should parse out the charset identifier and use it to decode
  3185. # 8-bit bodies. Until then, on Python 2 it should continue to
  3186. # return native (byte) strings, while on Python 3 it should
  3187. # decode bytes to native strings via charmap, ensuring data
  3188. # fidelity at the cost of mojibake.
  3189. if _PY3:
  3190. def nativeStringResponse(thing):
  3191. if isinstance(thing, bytes):
  3192. return thing.decode('charmap')
  3193. elif isinstance(thing, list):
  3194. return [nativeStringResponse(subthing)
  3195. for subthing in thing]
  3196. else:
  3197. def nativeStringResponse(thing):
  3198. return thing
  3199. values = {}
  3200. unstructured = []
  3201. responseParts = iter(fetchResponseList)
  3202. while True:
  3203. try:
  3204. key = next(responseParts)
  3205. except StopIteration:
  3206. break
  3207. try:
  3208. value = next(responseParts)
  3209. except StopIteration:
  3210. raise IllegalServerResponse(
  3211. b"Not enough arguments", fetchResponseList)
  3212. # The parsed forms of responses like:
  3213. #
  3214. # BODY[] VALUE
  3215. # BODY[TEXT] VALUE
  3216. # BODY[HEADER.FIELDS (SUBJECT)] VALUE
  3217. # BODY[HEADER.FIELDS (SUBJECT)]<N.M> VALUE
  3218. #
  3219. # are:
  3220. #
  3221. # ["BODY", [], VALUE]
  3222. # ["BODY", ["TEXT"], VALUE]
  3223. # ["BODY", ["HEADER.FIELDS", ["SUBJECT"]], VALUE]
  3224. # ["BODY", ["HEADER.FIELDS", ["SUBJECT"]], "<N.M>", VALUE]
  3225. #
  3226. # Additionally, BODY responses for multipart messages are
  3227. # represented as:
  3228. #
  3229. # ["BODY", VALUE]
  3230. #
  3231. # with list as the type of VALUE and the type of VALUE[0].
  3232. #
  3233. # See #6281 for ideas on how this might be improved.
  3234. if key not in (b"BODY", b"BODY.PEEK"):
  3235. # Only BODY (and by extension, BODY.PEEK) responses can have
  3236. # body sections.
  3237. hasSection = False
  3238. elif not isinstance(value, list):
  3239. # A BODY section is always represented as a list. Any non-list
  3240. # is not a BODY section.
  3241. hasSection = False
  3242. elif len(value) > 2:
  3243. # The list representing a BODY section has at most two elements.
  3244. hasSection = False
  3245. elif value and isinstance(value[0], list):
  3246. # A list containing a list represents the body structure of a
  3247. # multipart message, instead.
  3248. hasSection = False
  3249. else:
  3250. # Otherwise it must have a BODY section to examine.
  3251. hasSection = True
  3252. # If it has a BODY section, grab some extra elements and shuffle
  3253. # around the shape of the key a little bit.
  3254. key = nativeString(key)
  3255. unstructured.append(key)
  3256. if hasSection:
  3257. if len(value) < 2:
  3258. value = [nativeString(v) for v in value]
  3259. unstructured.append(value)
  3260. key = (key, tuple(value))
  3261. else:
  3262. valueHead = nativeString(value[0])
  3263. valueTail = [nativeString(v) for v in value[1]]
  3264. unstructured.append([valueHead, valueTail])
  3265. key = (key, (valueHead, tuple(valueTail)))
  3266. try:
  3267. value = next(responseParts)
  3268. except StopIteration:
  3269. raise IllegalServerResponse(
  3270. b"Not enough arguments", fetchResponseList)
  3271. # Handle partial ranges
  3272. if value.startswith(b'<') and value.endswith(b'>'):
  3273. try:
  3274. int(value[1:-1])
  3275. except ValueError:
  3276. # This isn't really a range, it's some content.
  3277. pass
  3278. else:
  3279. value = nativeString(value)
  3280. unstructured.append(value)
  3281. key = key + (value,)
  3282. try:
  3283. value = next(responseParts)
  3284. except StopIteration:
  3285. raise IllegalServerResponse(
  3286. b"Not enough arguments", fetchResponseList)
  3287. value = nativeStringResponse(value)
  3288. unstructured.append(value)
  3289. values[key] = value
  3290. return values, unstructured
  3291. def _cbFetch(self, result, requestedParts, structured):
  3292. (lines, last) = result
  3293. info = {}
  3294. for parts in lines:
  3295. if len(parts) == 3 and parts[1] == b'FETCH':
  3296. id = self._intOrRaise(parts[0], parts)
  3297. if id not in info:
  3298. info[id] = [parts[2]]
  3299. else:
  3300. info[id][0].extend(parts[2])
  3301. results = {}
  3302. decodedInfo = {}
  3303. for (messageId, values) in info.items():
  3304. structuredMap, unstructuredList = self._parseFetchPairs(values[0])
  3305. decodedInfo.setdefault(messageId, [[]])[0].extend(unstructuredList)
  3306. results.setdefault(messageId, {}).update(structuredMap)
  3307. info = decodedInfo
  3308. flagChanges = {}
  3309. for messageId in list(results.keys()):
  3310. values = results[messageId]
  3311. for part in list(values.keys()):
  3312. if part not in requestedParts and part == 'FLAGS':
  3313. flagChanges[messageId] = values['FLAGS']
  3314. # Find flags in the result and get rid of them.
  3315. for i in range(len(info[messageId][0])):
  3316. if info[messageId][0][i] == 'FLAGS':
  3317. del info[messageId][0][i:i+2]
  3318. break
  3319. del values['FLAGS']
  3320. if not values:
  3321. del results[messageId]
  3322. if flagChanges:
  3323. self.flagsChanged(flagChanges)
  3324. if structured:
  3325. return results
  3326. else:
  3327. return info
  3328. def fetchSpecific(self, messages, uid=0, headerType=None,
  3329. headerNumber=None, headerArgs=None, peek=None,
  3330. offset=None, length=None):
  3331. """
  3332. Retrieve a specific section of one or more messages
  3333. @type messages: L{MessageSet} or L{str}
  3334. @param messages: A message sequence set
  3335. @type uid: L{bool}
  3336. @param uid: Indicates whether the message sequence set is of message
  3337. numbers or of unique message IDs.
  3338. @type headerType: L{str}
  3339. @param headerType: If specified, must be one of HEADER, HEADER.FIELDS,
  3340. HEADER.FIELDS.NOT, MIME, or TEXT, and will determine which part of
  3341. the message is retrieved. For HEADER.FIELDS and HEADER.FIELDS.NOT,
  3342. C{headerArgs} must be a sequence of header names. For MIME,
  3343. C{headerNumber} must be specified.
  3344. @type headerNumber: L{int} or L{int} sequence
  3345. @param headerNumber: The nested rfc822 index specifying the entity to
  3346. retrieve. For example, C{1} retrieves the first entity of the
  3347. message, and C{(2, 1, 3}) retrieves the 3rd entity inside the first
  3348. entity inside the second entity of the message.
  3349. @type headerArgs: A sequence of L{str}
  3350. @param headerArgs: If C{headerType} is HEADER.FIELDS, these are the
  3351. headers to retrieve. If it is HEADER.FIELDS.NOT, these are the
  3352. headers to exclude from retrieval.
  3353. @type peek: C{bool}
  3354. @param peek: If true, cause the server to not set the \\Seen flag on
  3355. this message as a result of this command.
  3356. @type offset: L{int}
  3357. @param offset: The number of octets at the beginning of the result to
  3358. skip.
  3359. @type length: L{int}
  3360. @param length: The number of octets to retrieve.
  3361. @rtype: L{Deferred}
  3362. @return: A deferred whose callback is invoked with a mapping of message
  3363. numbers to retrieved data, or whose errback is invoked if there is
  3364. an error.
  3365. """
  3366. fmt = '%s BODY%s[%s%s%s]%s'
  3367. if headerNumber is None:
  3368. number = ''
  3369. elif isinstance(headerNumber, int):
  3370. number = str(headerNumber)
  3371. else:
  3372. number = '.'.join(map(str, headerNumber))
  3373. if headerType is None:
  3374. header = ''
  3375. elif number:
  3376. header = '.' + headerType
  3377. else:
  3378. header = headerType
  3379. if header and headerType in ('HEADER.FIELDS', 'HEADER.FIELDS.NOT'):
  3380. if headerArgs is not None:
  3381. payload = ' (%s)' % ' '.join(headerArgs)
  3382. else:
  3383. payload = ' ()'
  3384. else:
  3385. payload = ''
  3386. if offset is None:
  3387. extra = ''
  3388. else:
  3389. extra = '<%d.%d>' % (offset, length)
  3390. fetch = uid and b'UID FETCH' or b'FETCH'
  3391. cmd = fmt % (messages, peek and '.PEEK' or '', number, header, payload, extra)
  3392. # APPEND components should be encoded as ASCII unless a
  3393. # charset identifier is provided. See #9201.
  3394. if _PY3:
  3395. cmd = cmd.encode('charmap')
  3396. d = self.sendCommand(Command(fetch, cmd, wantResponse=(b'FETCH',)))
  3397. d.addCallback(self._cbFetch, (), False)
  3398. return d
  3399. def _fetch(self, messages, useUID=0, **terms):
  3400. messages = str(messages).encode('ascii')
  3401. fetch = useUID and b'UID FETCH' or b'FETCH'
  3402. if 'rfc822text' in terms:
  3403. del terms['rfc822text']
  3404. terms['rfc822.text'] = True
  3405. if 'rfc822size' in terms:
  3406. del terms['rfc822size']
  3407. terms['rfc822.size'] = True
  3408. if 'rfc822header' in terms:
  3409. del terms['rfc822header']
  3410. terms['rfc822.header'] = True
  3411. # The terms in 6.4.5 are all ASCII congruent, so wing it.
  3412. # Note that this isn't a public API, so terms in responses
  3413. # should not be decoded to native strings.
  3414. encodedTerms = [networkString(s) for s in terms]
  3415. cmd = messages + b' (' + b' '.join(
  3416. [s.upper() for s in encodedTerms]
  3417. ) + b')'
  3418. d = self.sendCommand(Command(fetch, cmd, wantResponse=(b'FETCH',)))
  3419. d.addCallback(self._cbFetch, [t.upper() for t in terms.keys()], True)
  3420. return d
  3421. def setFlags(self, messages, flags, silent=1, uid=0):
  3422. """
  3423. Set the flags for one or more messages.
  3424. This command is allowed in the Selected state.
  3425. @type messages: L{MessageSet} or L{str}
  3426. @param messages: A message sequence set
  3427. @type flags: Any iterable of L{str}
  3428. @param flags: The flags to set
  3429. @type silent: L{bool}
  3430. @param silent: If true, cause the server to suppress its verbose
  3431. response.
  3432. @type uid: L{bool}
  3433. @param uid: Indicates whether the message sequence set is of message
  3434. numbers or of unique message IDs.
  3435. @rtype: L{Deferred}
  3436. @return: A deferred whose callback is invoked with a list of the
  3437. server's responses (C{[]} if C{silent} is true) or whose
  3438. errback is invoked if there is an error.
  3439. """
  3440. return self._store(messages, b'FLAGS', silent, flags, uid)
  3441. def addFlags(self, messages, flags, silent=1, uid=0):
  3442. """
  3443. Add to the set flags for one or more messages.
  3444. This command is allowed in the Selected state.
  3445. @type messages: C{MessageSet} or L{str}
  3446. @param messages: A message sequence set
  3447. @type flags: Any iterable of L{str}
  3448. @param flags: The flags to set
  3449. @type silent: C{bool}
  3450. @param silent: If true, cause the server to suppress its verbose
  3451. response.
  3452. @type uid: C{bool}
  3453. @param uid: Indicates whether the message sequence set is of message
  3454. numbers or of unique message IDs.
  3455. @rtype: L{Deferred}
  3456. @return: A deferred whose callback is invoked with a list of the
  3457. server's responses (C{[]} if C{silent} is true) or whose
  3458. errback is invoked if there is an error.
  3459. """
  3460. return self._store(messages, b'+FLAGS', silent, flags, uid)
  3461. def removeFlags(self, messages, flags, silent=1, uid=0):
  3462. """
  3463. Remove from the set flags for one or more messages.
  3464. This command is allowed in the Selected state.
  3465. @type messages: L{MessageSet} or L{str}
  3466. @param messages: A message sequence set
  3467. @type flags: Any iterable of L{str}
  3468. @param flags: The flags to set
  3469. @type silent: L{bool}
  3470. @param silent: If true, cause the server to suppress its verbose
  3471. response.
  3472. @type uid: L{bool}
  3473. @param uid: Indicates whether the message sequence set is of message
  3474. numbers or of unique message IDs.
  3475. @rtype: L{Deferred}
  3476. @return: A deferred whose callback is invoked with a list of the
  3477. server's responses (C{[]} if C{silent} is true) or whose
  3478. errback is invoked if there is an error.
  3479. """
  3480. return self._store(messages, b'-FLAGS', silent, flags, uid)
  3481. def _store(self, messages, cmd, silent, flags, uid):
  3482. messages = str(messages).encode('ascii')
  3483. encodedFlags = [networkString(flag) for flag in flags]
  3484. if silent:
  3485. cmd = cmd + b'.SILENT'
  3486. store = uid and b'UID STORE' or b'STORE'
  3487. args = b' '.join((messages, cmd, b'('+ b' '.join(encodedFlags) + b')'))
  3488. d = self.sendCommand(Command(store, args, wantResponse=(b'FETCH',)))
  3489. expected = ()
  3490. if not silent:
  3491. expected = ('FLAGS',)
  3492. d.addCallback(self._cbFetch, expected, True)
  3493. return d
  3494. def copy(self, messages, mailbox, uid):
  3495. """
  3496. Copy the specified messages to the specified mailbox.
  3497. This command is allowed in the Selected state.
  3498. @type messages: L{MessageSet} or L{str}
  3499. @param messages: A message sequence set
  3500. @type mailbox: L{str}
  3501. @param mailbox: The mailbox to which to copy the messages
  3502. @type uid: C{bool}
  3503. @param uid: If true, the C{messages} refers to message UIDs, rather
  3504. than message sequence numbers.
  3505. @rtype: L{Deferred}
  3506. @return: A deferred whose callback is invoked with a true value
  3507. when the copy is successful, or whose errback is invoked if there
  3508. is an error.
  3509. """
  3510. messages = str(messages).encode('ascii')
  3511. if uid:
  3512. cmd = b'UID COPY'
  3513. else:
  3514. cmd = b'COPY'
  3515. args = b' '.join([messages, _prepareMailboxName(mailbox)])
  3516. return self.sendCommand(Command(cmd, args))
  3517. #
  3518. # IMailboxListener methods
  3519. #
  3520. def modeChanged(self, writeable):
  3521. """Override me"""
  3522. def flagsChanged(self, newFlags):
  3523. """Override me"""
  3524. def newMessages(self, exists, recent):
  3525. """Override me"""
  3526. def parseIdList(s, lastMessageId=None):
  3527. """
  3528. Parse a message set search key into a C{MessageSet}.
  3529. @type s: L{bytes}
  3530. @param s: A string description of an id list, for example "1:3, 4:*"
  3531. @type lastMessageId: L{int}
  3532. @param lastMessageId: The last message sequence id or UID, depending on
  3533. whether we are parsing the list in UID or sequence id context. The
  3534. caller should pass in the correct value.
  3535. @rtype: C{MessageSet}
  3536. @return: A C{MessageSet} that contains the ids defined in the list
  3537. """
  3538. res = MessageSet()
  3539. parts = s.split(b',')
  3540. for p in parts:
  3541. if b':' in p:
  3542. low, high = p.split(b':', 1)
  3543. try:
  3544. if low == b'*':
  3545. low = None
  3546. else:
  3547. low = int(low)
  3548. if high == b'*':
  3549. high = None
  3550. else:
  3551. high = int(high)
  3552. if low is high is None:
  3553. # *:* does not make sense
  3554. raise IllegalIdentifierError(p)
  3555. # non-positive values are illegal according to RFC 3501
  3556. if ((low is not None and low <= 0) or
  3557. (high is not None and high <= 0)):
  3558. raise IllegalIdentifierError(p)
  3559. # star means "highest value of an id in the mailbox"
  3560. high = high or lastMessageId
  3561. low = low or lastMessageId
  3562. res.add(low, high)
  3563. except ValueError:
  3564. raise IllegalIdentifierError(p)
  3565. else:
  3566. try:
  3567. if p == b'*':
  3568. p = None
  3569. else:
  3570. p = int(p)
  3571. if p is not None and p <= 0:
  3572. raise IllegalIdentifierError(p)
  3573. except ValueError:
  3574. raise IllegalIdentifierError(p)
  3575. else:
  3576. res.extend(p or lastMessageId)
  3577. return res
  3578. _SIMPLE_BOOL = (
  3579. 'ALL', 'ANSWERED', 'DELETED', 'DRAFT', 'FLAGGED', 'NEW', 'OLD',
  3580. 'RECENT', 'SEEN', 'UNANSWERED', 'UNDELETED', 'UNDRAFT', 'UNFLAGGED',
  3581. 'UNSEEN'
  3582. )
  3583. _NO_QUOTES = (
  3584. 'LARGER', 'SMALLER', 'UID'
  3585. )
  3586. _sorted = sorted
  3587. def Query(sorted=0, **kwarg):
  3588. """
  3589. Create a query string
  3590. Among the accepted keywords are::
  3591. all : If set to a true value, search all messages in the
  3592. current mailbox
  3593. answered : If set to a true value, search messages flagged with
  3594. \\Answered
  3595. bcc : A substring to search the BCC header field for
  3596. before : Search messages with an internal date before this
  3597. value. The given date should be a string in the format
  3598. of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
  3599. body : A substring to search the body of the messages for
  3600. cc : A substring to search the CC header field for
  3601. deleted : If set to a true value, search messages flagged with
  3602. \\Deleted
  3603. draft : If set to a true value, search messages flagged with
  3604. \\Draft
  3605. flagged : If set to a true value, search messages flagged with
  3606. \\Flagged
  3607. from : A substring to search the From header field for
  3608. header : A two-tuple of a header name and substring to search
  3609. for in that header
  3610. keyword : Search for messages with the given keyword set
  3611. larger : Search for messages larger than this number of octets
  3612. messages : Search only the given message sequence set.
  3613. new : If set to a true value, search messages flagged with
  3614. \\Recent but not \\Seen
  3615. old : If set to a true value, search messages not flagged with
  3616. \\Recent
  3617. on : Search messages with an internal date which is on this
  3618. date. The given date should be a string in the format
  3619. of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
  3620. recent : If set to a true value, search for messages flagged with
  3621. \\Recent
  3622. seen : If set to a true value, search for messages flagged with
  3623. \\Seen
  3624. sentbefore : Search for messages with an RFC822 'Date' header before
  3625. this date. The given date should be a string in the format
  3626. of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
  3627. senton : Search for messages with an RFC822 'Date' header which is
  3628. on this date The given date should be a string in the format
  3629. of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
  3630. sentsince : Search for messages with an RFC822 'Date' header which is
  3631. after this date. The given date should be a string in the format
  3632. of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
  3633. since : Search for messages with an internal date that is after
  3634. this date.. The given date should be a string in the format
  3635. of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
  3636. smaller : Search for messages smaller than this number of octets
  3637. subject : A substring to search the 'subject' header for
  3638. text : A substring to search the entire message for
  3639. to : A substring to search the 'to' header for
  3640. uid : Search only the messages in the given message set
  3641. unanswered : If set to a true value, search for messages not
  3642. flagged with \\Answered
  3643. undeleted : If set to a true value, search for messages not
  3644. flagged with \\Deleted
  3645. undraft : If set to a true value, search for messages not
  3646. flagged with \\Draft
  3647. unflagged : If set to a true value, search for messages not
  3648. flagged with \\Flagged
  3649. unkeyword : Search for messages without the given keyword set
  3650. unseen : If set to a true value, search for messages not
  3651. flagged with \\Seen
  3652. @type sorted: C{bool}
  3653. @param sorted: If true, the output will be sorted, alphabetically.
  3654. The standard does not require it, but it makes testing this function
  3655. easier. The default is zero, and this should be acceptable for any
  3656. application.
  3657. @rtype: L{str}
  3658. @return: The formatted query string
  3659. """
  3660. cmd = []
  3661. keys = kwarg.keys()
  3662. if sorted:
  3663. keys = _sorted(keys)
  3664. for k in keys:
  3665. v = kwarg[k]
  3666. k = k.upper()
  3667. if k in _SIMPLE_BOOL and v:
  3668. cmd.append(k)
  3669. elif k == 'HEADER':
  3670. cmd.extend([k, str(v[0]), str(v[1])])
  3671. elif k == 'KEYWORD' or k == 'UNKEYWORD':
  3672. # Discard anything that does not fit into an "atom". Perhaps turn
  3673. # the case where this actually removes bytes from the value into a
  3674. # warning and then an error, eventually. See #6277.
  3675. v = _nonAtomRE.sub("", v)
  3676. cmd.extend([k, v])
  3677. elif k not in _NO_QUOTES:
  3678. if isinstance(v, MessageSet):
  3679. fmt = '"%s"'
  3680. elif isinstance(v, str):
  3681. fmt = '"%s"'
  3682. else:
  3683. fmt = '"%d"'
  3684. cmd.extend([k, fmt % (v,)])
  3685. elif isinstance(v, int):
  3686. cmd.extend([k, '%d' % (v,)])
  3687. else:
  3688. cmd.extend([k, '%s' % (v,)])
  3689. if len(cmd) > 1:
  3690. return '(' + ' '.join(cmd) + ')'
  3691. else:
  3692. return ' '.join(cmd)
  3693. def Or(*args):
  3694. """
  3695. The disjunction of two or more queries
  3696. """
  3697. if len(args) < 2:
  3698. raise IllegalQueryError(args)
  3699. elif len(args) == 2:
  3700. return '(OR %s %s)' % args
  3701. else:
  3702. return '(OR %s %s)' % (args[0], Or(*args[1:]))
  3703. def Not(query):
  3704. """The negation of a query"""
  3705. return '(NOT %s)' % (query,)
  3706. def wildcardToRegexp(wildcard, delim=None):
  3707. wildcard = wildcard.replace('*', '(?:.*?)')
  3708. if delim is None:
  3709. wildcard = wildcard.replace('%', '(?:.*?)')
  3710. else:
  3711. wildcard = wildcard.replace('%', '(?:(?:[^%s])*?)' % re.escape(delim))
  3712. return re.compile(wildcard, re.I)
  3713. def splitQuoted(s):
  3714. """
  3715. Split a string into whitespace delimited tokens
  3716. Tokens that would otherwise be separated but are surrounded by \"
  3717. remain as a single token. Any token that is not quoted and is
  3718. equal to \"NIL\" is tokenized as L{None}.
  3719. @type s: L{bytes}
  3720. @param s: The string to be split
  3721. @rtype: L{list} of L{bytes}
  3722. @return: A list of the resulting tokens
  3723. @raise MismatchedQuoting: Raised if an odd number of quotes are present
  3724. """
  3725. s = s.strip()
  3726. result = []
  3727. word = []
  3728. inQuote = inWord = False
  3729. qu = _matchingString('"', s)
  3730. esc = _matchingString('\x5c', s)
  3731. empty = _matchingString('', s)
  3732. nil = _matchingString('NIL', s)
  3733. for i, c in enumerate(iterbytes(s)):
  3734. if c == qu:
  3735. if i and s[i-1:i] == esc:
  3736. word.pop()
  3737. word.append(qu)
  3738. elif not inQuote:
  3739. inQuote = True
  3740. else:
  3741. inQuote = False
  3742. result.append(empty.join(word))
  3743. word = []
  3744. elif (
  3745. not inWord and not inQuote and
  3746. c not in (qu + (string.whitespace.encode("ascii")))
  3747. ):
  3748. inWord = True
  3749. word.append(c)
  3750. elif inWord and not inQuote and c in string.whitespace.encode("ascii"):
  3751. w = empty.join(word)
  3752. if w == nil:
  3753. result.append(None)
  3754. else:
  3755. result.append(w)
  3756. word = []
  3757. inWord = False
  3758. elif inWord or inQuote:
  3759. word.append(c)
  3760. if inQuote:
  3761. raise MismatchedQuoting(s)
  3762. if inWord:
  3763. w = empty.join(word)
  3764. if w == nil:
  3765. result.append(None)
  3766. else:
  3767. result.append(w)
  3768. return result
  3769. def splitOn(sequence, predicate, transformers):
  3770. result = []
  3771. mode = predicate(sequence[0])
  3772. tmp = [sequence[0]]
  3773. for e in sequence[1:]:
  3774. p = predicate(e)
  3775. if p != mode:
  3776. result.extend(transformers[mode](tmp))
  3777. tmp = [e]
  3778. mode = p
  3779. else:
  3780. tmp.append(e)
  3781. result.extend(transformers[mode](tmp))
  3782. return result
  3783. def collapseStrings(results):
  3784. """
  3785. Turns a list of length-one strings and lists into a list of longer
  3786. strings and lists. For example,
  3787. ['a', 'b', ['c', 'd']] is returned as ['ab', ['cd']]
  3788. @type results: L{list} of L{bytes} and L{list}
  3789. @param results: The list to be collapsed
  3790. @rtype: L{list} of L{bytes} and L{list}
  3791. @return: A new list which is the collapsed form of C{results}
  3792. """
  3793. copy = []
  3794. begun = None
  3795. pred = lambda e: isinstance(e, tuple)
  3796. tran = {
  3797. 0: lambda e: splitQuoted(b''.join(e)),
  3798. 1: lambda e: [b''.join([i[0] for i in e])]
  3799. }
  3800. for i, c in enumerate(results):
  3801. if isinstance(c, list):
  3802. if begun is not None:
  3803. copy.extend(splitOn(results[begun:i], pred, tran))
  3804. begun = None
  3805. copy.append(collapseStrings(c))
  3806. elif begun is None:
  3807. begun = i
  3808. if begun is not None:
  3809. copy.extend(splitOn(results[begun:], pred, tran))
  3810. return copy
  3811. def parseNestedParens(s, handleLiteral = 1):
  3812. """
  3813. Parse an s-exp-like string into a more useful data structure.
  3814. @type s: L{bytes}
  3815. @param s: The s-exp-like string to parse
  3816. @rtype: L{list} of L{bytes} and L{list}
  3817. @return: A list containing the tokens present in the input.
  3818. @raise MismatchedNesting: Raised if the number or placement
  3819. of opening or closing parenthesis is invalid.
  3820. """
  3821. s = s.strip()
  3822. inQuote = 0
  3823. contentStack = [[]]
  3824. try:
  3825. i = 0
  3826. L = len(s)
  3827. while i < L:
  3828. c = s[i:i+1]
  3829. if inQuote:
  3830. if c == b'\\':
  3831. contentStack[-1].append(s[i:i+2])
  3832. i += 2
  3833. continue
  3834. elif c == b'"':
  3835. inQuote = not inQuote
  3836. contentStack[-1].append(c)
  3837. i += 1
  3838. else:
  3839. if c == b'"':
  3840. contentStack[-1].append(c)
  3841. inQuote = not inQuote
  3842. i += 1
  3843. elif handleLiteral and c == b'{':
  3844. end = s.find(b'}', i)
  3845. if end == -1:
  3846. raise ValueError("Malformed literal")
  3847. literalSize = int(s[i+1:end])
  3848. contentStack[-1].append((s[end+3:end+3+literalSize],))
  3849. i = end + 3 + literalSize
  3850. elif c == b'(' or c == b'[':
  3851. contentStack.append([])
  3852. i += 1
  3853. elif c == b')' or c == b']':
  3854. contentStack[-2].append(contentStack.pop())
  3855. i += 1
  3856. else:
  3857. contentStack[-1].append(c)
  3858. i += 1
  3859. except IndexError:
  3860. raise MismatchedNesting(s)
  3861. if len(contentStack) != 1:
  3862. raise MismatchedNesting(s)
  3863. return collapseStrings(contentStack[0])
  3864. def _quote(s):
  3865. qu = _matchingString('"', s)
  3866. esc = _matchingString('\x5c', s)
  3867. return qu + s.replace(esc, esc + esc).replace(qu, esc + qu) + qu
  3868. def _literal(s):
  3869. return b'{' + intToBytes(len(s)) + b'}\r\n' + s
  3870. class DontQuoteMe:
  3871. def __init__(self, value):
  3872. self.value = value
  3873. def __str__(self):
  3874. return str(self.value)
  3875. _ATOM_SPECIALS = b'(){ %*"'
  3876. def _needsQuote(s):
  3877. if s == b'':
  3878. return 1
  3879. for c in iterbytes(s):
  3880. if c < b'\x20' or c > b'\x7f':
  3881. return 1
  3882. if c in _ATOM_SPECIALS:
  3883. return 1
  3884. return 0
  3885. def _parseMbox(name):
  3886. if isinstance(name, unicode):
  3887. return name
  3888. try:
  3889. return name.decode('imap4-utf-7')
  3890. except:
  3891. log.err()
  3892. raise IllegalMailboxEncoding(name)
  3893. def _prepareMailboxName(name):
  3894. if not isinstance(name, unicode):
  3895. name = name.decode("charmap")
  3896. name = name.encode('imap4-utf-7')
  3897. if _needsQuote(name):
  3898. return _quote(name)
  3899. return name
  3900. def _needsLiteral(s):
  3901. # change this to "return 1" to wig out stupid clients
  3902. cr = _matchingString("\n", s)
  3903. lf = _matchingString("\r", s)
  3904. return cr in s or lf in s or len(s) > 1000
  3905. def collapseNestedLists(items):
  3906. """
  3907. Turn a nested list structure into an s-exp-like string.
  3908. Strings in C{items} will be sent as literals if they contain CR or LF,
  3909. otherwise they will be quoted. References to None in C{items} will be
  3910. translated to the atom NIL. Objects with a 'read' attribute will have
  3911. it called on them with no arguments and the returned string will be
  3912. inserted into the output as a literal. Integers will be converted to
  3913. strings and inserted into the output unquoted. Instances of
  3914. C{DontQuoteMe} will be converted to strings and inserted into the output
  3915. unquoted.
  3916. This function used to be much nicer, and only quote things that really
  3917. needed to be quoted (and C{DontQuoteMe} did not exist), however, many
  3918. broken IMAP4 clients were unable to deal with this level of sophistication,
  3919. forcing the current behavior to be adopted for practical reasons.
  3920. @type items: Any iterable
  3921. @rtype: L{str}
  3922. """
  3923. pieces = []
  3924. for i in items:
  3925. if isinstance(i, unicode):
  3926. # anything besides ASCII will have to wait for an RFC 5738
  3927. # implementation. See
  3928. # https://twistedmatrix.com/trac/ticket/9258
  3929. i = i.encode("ascii")
  3930. if i is None:
  3931. pieces.extend([b' ', b'NIL'])
  3932. elif isinstance(i, (int, long)):
  3933. pieces.extend([b' ', networkString(str(i))])
  3934. elif isinstance(i, DontQuoteMe):
  3935. pieces.extend([b' ', i.value])
  3936. elif isinstance(i, bytes):
  3937. # XXX warning
  3938. if _needsLiteral(i):
  3939. pieces.extend([b' ', b'{', intToBytes(len(i)), b'}',
  3940. IMAP4Server.delimiter, i])
  3941. else:
  3942. pieces.extend([b' ', _quote(i)])
  3943. elif hasattr(i, 'read'):
  3944. d = i.read()
  3945. pieces.extend([b' ', b'{', intToBytes(len(d)), b'}',
  3946. IMAP4Server.delimiter, d])
  3947. else:
  3948. pieces.extend([b' ', b'(' + collapseNestedLists(i) + b')'])
  3949. return b''.join(pieces[1:])
  3950. @implementer(IAccount)
  3951. class MemoryAccountWithoutNamespaces(object):
  3952. mailboxes = None
  3953. subscriptions = None
  3954. top_id = 0
  3955. def __init__(self, name):
  3956. self.name = name
  3957. self.mailboxes = {}
  3958. self.subscriptions = []
  3959. def allocateID(self):
  3960. id = self.top_id
  3961. self.top_id += 1
  3962. return id
  3963. ##
  3964. ## IAccount
  3965. ##
  3966. def addMailbox(self, name, mbox = None):
  3967. name = _parseMbox(name.upper())
  3968. if name in self.mailboxes:
  3969. raise MailboxCollision(name)
  3970. if mbox is None:
  3971. mbox = self._emptyMailbox(name, self.allocateID())
  3972. self.mailboxes[name] = mbox
  3973. return 1
  3974. def create(self, pathspec):
  3975. paths = [path for path in pathspec.split('/') if path]
  3976. for accum in range(1, len(paths)):
  3977. try:
  3978. self.addMailbox('/'.join(paths[:accum]))
  3979. except MailboxCollision:
  3980. pass
  3981. try:
  3982. self.addMailbox('/'.join(paths))
  3983. except MailboxCollision:
  3984. if not pathspec.endswith('/'):
  3985. return False
  3986. return True
  3987. def _emptyMailbox(self, name, id):
  3988. raise NotImplementedError
  3989. def select(self, name, readwrite=1):
  3990. return self.mailboxes.get(_parseMbox(name.upper()))
  3991. def delete(self, name):
  3992. name = _parseMbox(name.upper())
  3993. # See if this mailbox exists at all
  3994. mbox = self.mailboxes.get(name)
  3995. if not mbox:
  3996. raise MailboxException("No such mailbox")
  3997. # See if this box is flagged \Noselect
  3998. if r'\Noselect' in mbox.getFlags():
  3999. # Check for hierarchically inferior mailboxes with this one
  4000. # as part of their root.
  4001. for others in self.mailboxes.keys():
  4002. if others != name and others.startswith(name):
  4003. raise MailboxException("Hierarchically inferior mailboxes exist and \\Noselect is set")
  4004. mbox.destroy()
  4005. # iff there are no hierarchically inferior names, we will
  4006. # delete it from our ken.
  4007. if len(self._inferiorNames(name)) > 1:
  4008. raise MailboxException(
  4009. 'Name "%s" has inferior hierarchical names' % (name,))
  4010. del self.mailboxes[name]
  4011. def rename(self, oldname, newname):
  4012. oldname = _parseMbox(oldname.upper())
  4013. newname = _parseMbox(newname.upper())
  4014. if oldname not in self.mailboxes:
  4015. raise NoSuchMailbox(oldname)
  4016. inferiors = self._inferiorNames(oldname)
  4017. inferiors = [(o, o.replace(oldname, newname, 1)) for o in inferiors]
  4018. for (old, new) in inferiors:
  4019. if new in self.mailboxes:
  4020. raise MailboxCollision(new)
  4021. for (old, new) in inferiors:
  4022. self.mailboxes[new] = self.mailboxes[old]
  4023. del self.mailboxes[old]
  4024. def _inferiorNames(self, name):
  4025. inferiors = []
  4026. for infname in self.mailboxes.keys():
  4027. if infname.startswith(name):
  4028. inferiors.append(infname)
  4029. return inferiors
  4030. def isSubscribed(self, name):
  4031. return _parseMbox(name.upper()) in self.subscriptions
  4032. def subscribe(self, name):
  4033. name = _parseMbox(name.upper())
  4034. if name not in self.subscriptions:
  4035. self.subscriptions.append(name)
  4036. def unsubscribe(self, name):
  4037. name = _parseMbox(name.upper())
  4038. if name not in self.subscriptions:
  4039. raise MailboxException("Not currently subscribed to %s" % (name,))
  4040. self.subscriptions.remove(name)
  4041. def listMailboxes(self, ref, wildcard):
  4042. ref = self._inferiorNames(_parseMbox(ref.upper()))
  4043. wildcard = wildcardToRegexp(wildcard, '/')
  4044. return [(i, self.mailboxes[i]) for i in ref if wildcard.match(i)]
  4045. @implementer(INamespacePresenter)
  4046. class MemoryAccount(MemoryAccountWithoutNamespaces):
  4047. ##
  4048. ## INamespacePresenter
  4049. ##
  4050. def getPersonalNamespaces(self):
  4051. return [[b"", b"/"]]
  4052. def getSharedNamespaces(self):
  4053. return None
  4054. def getOtherNamespaces(self):
  4055. return None
  4056. _statusRequestDict = {
  4057. 'MESSAGES': 'getMessageCount',
  4058. 'RECENT': 'getRecentCount',
  4059. 'UIDNEXT': 'getUIDNext',
  4060. 'UIDVALIDITY': 'getUIDValidity',
  4061. 'UNSEEN': 'getUnseenCount'
  4062. }
  4063. def statusRequestHelper(mbox, names):
  4064. r = {}
  4065. for n in names:
  4066. r[n] = getattr(mbox, _statusRequestDict[n.upper()])()
  4067. return r
  4068. def parseAddr(addr):
  4069. if addr is None:
  4070. return [(None, None, None),]
  4071. addr = email.utils.getaddresses([addr])
  4072. return [[fn or None, None] + address.split('@') for fn, address in addr]
  4073. def getEnvelope(msg):
  4074. headers = msg.getHeaders(True)
  4075. date = headers.get('date')
  4076. subject = headers.get('subject')
  4077. from_ = headers.get('from')
  4078. sender = headers.get('sender', from_)
  4079. reply_to = headers.get('reply-to', from_)
  4080. to = headers.get('to')
  4081. cc = headers.get('cc')
  4082. bcc = headers.get('bcc')
  4083. in_reply_to = headers.get('in-reply-to')
  4084. mid = headers.get('message-id')
  4085. return (date, subject, parseAddr(from_), parseAddr(sender),
  4086. reply_to and parseAddr(reply_to), to and parseAddr(to),
  4087. cc and parseAddr(cc), bcc and parseAddr(bcc), in_reply_to, mid)
  4088. def getLineCount(msg):
  4089. # XXX - Super expensive, CACHE THIS VALUE FOR LATER RE-USE
  4090. # XXX - This must be the number of lines in the ENCODED version
  4091. lines = 0
  4092. for _ in msg.getBodyFile():
  4093. lines += 1
  4094. return lines
  4095. def unquote(s):
  4096. if s[0] == s[-1] == '"':
  4097. return s[1:-1]
  4098. return s
  4099. def _getContentType(msg):
  4100. """
  4101. Return a two-tuple of the main and subtype of the given message.
  4102. """
  4103. attrs = None
  4104. mm = msg.getHeaders(False, 'content-type').get('content-type', '')
  4105. mm = ''.join(mm.splitlines())
  4106. if mm:
  4107. mimetype = mm.split(';')
  4108. type = mimetype[0].split('/', 1)
  4109. if len(type) == 1:
  4110. major = type[0]
  4111. minor = None
  4112. else:
  4113. # length must be 2, because of split('/', 1)
  4114. major, minor = type
  4115. attrs = dict(x.strip().lower().split('=', 1) for x in mimetype[1:])
  4116. else:
  4117. major = minor = None
  4118. return major, minor, attrs
  4119. def _getMessageStructure(message):
  4120. """
  4121. Construct an appropriate type of message structure object for the given
  4122. message object.
  4123. @param message: A L{IMessagePart} provider
  4124. @return: A L{_MessageStructure} instance of the most specific type available
  4125. for the given message, determined by inspecting the MIME type of the
  4126. message.
  4127. """
  4128. main, subtype, attrs = _getContentType(message)
  4129. if main is not None:
  4130. main = main.lower()
  4131. if subtype is not None:
  4132. subtype = subtype.lower()
  4133. if main == 'multipart':
  4134. return _MultipartMessageStructure(message, subtype, attrs)
  4135. elif (main, subtype) == ('message', 'rfc822'):
  4136. return _RFC822MessageStructure(message, main, subtype, attrs)
  4137. elif main == 'text':
  4138. return _TextMessageStructure(message, main, subtype, attrs)
  4139. else:
  4140. return _SinglepartMessageStructure(message, main, subtype, attrs)
  4141. class _MessageStructure(object):
  4142. """
  4143. L{_MessageStructure} is a helper base class for message structure classes
  4144. representing the structure of particular kinds of messages, as defined by
  4145. their MIME type.
  4146. """
  4147. def __init__(self, message, attrs):
  4148. """
  4149. @param message: An L{IMessagePart} provider which this structure object
  4150. reports on.
  4151. @param attrs: A C{dict} giving the parameters of the I{Content-Type}
  4152. header of the message.
  4153. """
  4154. self.message = message
  4155. self.attrs = attrs
  4156. def _disposition(self, disp):
  4157. """
  4158. Parse a I{Content-Disposition} header into a two-sequence of the
  4159. disposition and a flattened list of its parameters.
  4160. @return: L{None} if there is no disposition header value, a L{list} with
  4161. two elements otherwise.
  4162. """
  4163. if disp:
  4164. disp = disp.split('; ')
  4165. if len(disp) == 1:
  4166. disp = (disp[0].lower(), None)
  4167. elif len(disp) > 1:
  4168. # XXX Poorly tested parser
  4169. params = [x for param in disp[1:] for x in param.split('=', 1)]
  4170. disp = [disp[0].lower(), params]
  4171. return disp
  4172. else:
  4173. return None
  4174. def _unquotedAttrs(self):
  4175. """
  4176. @return: The I{Content-Type} parameters, unquoted, as a flat list with
  4177. each Nth element giving a parameter name and N+1th element giving
  4178. the corresponding parameter value.
  4179. """
  4180. if self.attrs:
  4181. unquoted = [(k, unquote(v)) for (k, v) in self.attrs.items()]
  4182. return [y for x in sorted(unquoted) for y in x]
  4183. return None
  4184. class _SinglepartMessageStructure(_MessageStructure):
  4185. """
  4186. L{_SinglepartMessageStructure} represents the message structure of a
  4187. non-I{multipart/*} message.
  4188. """
  4189. _HEADERS = [
  4190. 'content-id', 'content-description',
  4191. 'content-transfer-encoding']
  4192. def __init__(self, message, main, subtype, attrs):
  4193. """
  4194. @param message: An L{IMessagePart} provider which this structure object
  4195. reports on.
  4196. @param main: A L{str} giving the main MIME type of the message (for
  4197. example, C{"text"}).
  4198. @param subtype: A L{str} giving the MIME subtype of the message (for
  4199. example, C{"plain"}).
  4200. @param attrs: A C{dict} giving the parameters of the I{Content-Type}
  4201. header of the message.
  4202. """
  4203. _MessageStructure.__init__(self, message, attrs)
  4204. self.main = main
  4205. self.subtype = subtype
  4206. self.attrs = attrs
  4207. def _basicFields(self):
  4208. """
  4209. Return a list of the basic fields for a single-part message.
  4210. """
  4211. headers = self.message.getHeaders(False, *self._HEADERS)
  4212. # Number of octets total
  4213. size = self.message.getSize()
  4214. major, minor = self.main, self.subtype
  4215. # content-type parameter list
  4216. unquotedAttrs = self._unquotedAttrs()
  4217. return [
  4218. major, minor, unquotedAttrs,
  4219. headers.get('content-id'),
  4220. headers.get('content-description'),
  4221. headers.get('content-transfer-encoding'),
  4222. size,
  4223. ]
  4224. def encode(self, extended):
  4225. """
  4226. Construct and return a list of the basic and extended fields for a
  4227. single-part message. The list suitable to be encoded into a BODY or
  4228. BODYSTRUCTURE response.
  4229. """
  4230. result = self._basicFields()
  4231. if extended:
  4232. result.extend(self._extended())
  4233. return result
  4234. def _extended(self):
  4235. """
  4236. The extension data of a non-multipart body part are in the
  4237. following order:
  4238. 1. body MD5
  4239. A string giving the body MD5 value as defined in [MD5].
  4240. 2. body disposition
  4241. A parenthesized list with the same content and function as
  4242. the body disposition for a multipart body part.
  4243. 3. body language
  4244. A string or parenthesized list giving the body language
  4245. value as defined in [LANGUAGE-TAGS].
  4246. 4. body location
  4247. A string list giving the body content URI as defined in
  4248. [LOCATION].
  4249. """
  4250. result = []
  4251. headers = self.message.getHeaders(
  4252. False, 'content-md5', 'content-disposition',
  4253. 'content-language', 'content-language')
  4254. result.append(headers.get('content-md5'))
  4255. result.append(self._disposition(headers.get('content-disposition')))
  4256. result.append(headers.get('content-language'))
  4257. result.append(headers.get('content-location'))
  4258. return result
  4259. class _TextMessageStructure(_SinglepartMessageStructure):
  4260. """
  4261. L{_TextMessageStructure} represents the message structure of a I{text/*}
  4262. message.
  4263. """
  4264. def encode(self, extended):
  4265. """
  4266. A body type of type TEXT contains, immediately after the basic
  4267. fields, the size of the body in text lines. Note that this
  4268. size is the size in its content transfer encoding and not the
  4269. resulting size after any decoding.
  4270. """
  4271. result = _SinglepartMessageStructure._basicFields(self)
  4272. result.append(getLineCount(self.message))
  4273. if extended:
  4274. result.extend(self._extended())
  4275. return result
  4276. class _RFC822MessageStructure(_SinglepartMessageStructure):
  4277. """
  4278. L{_RFC822MessageStructure} represents the message structure of a
  4279. I{message/rfc822} message.
  4280. """
  4281. def encode(self, extended):
  4282. """
  4283. A body type of type MESSAGE and subtype RFC822 contains,
  4284. immediately after the basic fields, the envelope structure,
  4285. body structure, and size in text lines of the encapsulated
  4286. message.
  4287. """
  4288. result = _SinglepartMessageStructure.encode(self, extended)
  4289. contained = self.message.getSubPart(0)
  4290. result.append(getEnvelope(contained))
  4291. result.append(getBodyStructure(contained, False))
  4292. result.append(getLineCount(contained))
  4293. return result
  4294. class _MultipartMessageStructure(_MessageStructure):
  4295. """
  4296. L{_MultipartMessageStructure} represents the message structure of a
  4297. I{multipart/*} message.
  4298. """
  4299. def __init__(self, message, subtype, attrs):
  4300. """
  4301. @param message: An L{IMessagePart} provider which this structure object
  4302. reports on.
  4303. @param subtype: A L{str} giving the MIME subtype of the message (for
  4304. example, C{"plain"}).
  4305. @param attrs: A C{dict} giving the parameters of the I{Content-Type}
  4306. header of the message.
  4307. """
  4308. _MessageStructure.__init__(self, message, attrs)
  4309. self.subtype = subtype
  4310. def _getParts(self):
  4311. """
  4312. Return an iterator over all of the sub-messages of this message.
  4313. """
  4314. i = 0
  4315. while True:
  4316. try:
  4317. part = self.message.getSubPart(i)
  4318. except IndexError:
  4319. break
  4320. else:
  4321. yield part
  4322. i += 1
  4323. def encode(self, extended):
  4324. """
  4325. Encode each sub-message and added the additional I{multipart} fields.
  4326. """
  4327. result = [_getMessageStructure(p).encode(extended) for p in self._getParts()]
  4328. result.append(self.subtype)
  4329. if extended:
  4330. result.extend(self._extended())
  4331. return result
  4332. def _extended(self):
  4333. """
  4334. The extension data of a multipart body part are in the following order:
  4335. 1. body parameter parenthesized list
  4336. A parenthesized list of attribute/value pairs [e.g., ("foo"
  4337. "bar" "baz" "rag") where "bar" is the value of "foo", and
  4338. "rag" is the value of "baz"] as defined in [MIME-IMB].
  4339. 2. body disposition
  4340. A parenthesized list, consisting of a disposition type
  4341. string, followed by a parenthesized list of disposition
  4342. attribute/value pairs as defined in [DISPOSITION].
  4343. 3. body language
  4344. A string or parenthesized list giving the body language
  4345. value as defined in [LANGUAGE-TAGS].
  4346. 4. body location
  4347. A string list giving the body content URI as defined in
  4348. [LOCATION].
  4349. """
  4350. result = []
  4351. headers = self.message.getHeaders(
  4352. False, 'content-language', 'content-location',
  4353. 'content-disposition')
  4354. result.append(self._unquotedAttrs())
  4355. result.append(self._disposition(headers.get('content-disposition')))
  4356. result.append(headers.get('content-language', None))
  4357. result.append(headers.get('content-location', None))
  4358. return result
  4359. def getBodyStructure(msg, extended=False):
  4360. """
  4361. RFC 3501, 7.4.2, BODYSTRUCTURE::
  4362. A parenthesized list that describes the [MIME-IMB] body structure of a
  4363. message. This is computed by the server by parsing the [MIME-IMB] header
  4364. fields, defaulting various fields as necessary.
  4365. For example, a simple text message of 48 lines and 2279 octets can have
  4366. a body structure of: ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL
  4367. "7BIT" 2279 48)
  4368. This is represented as::
  4369. ["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 2279, 48]
  4370. These basic fields are documented in the RFC as:
  4371. 1. body type
  4372. A string giving the content media type name as defined in
  4373. [MIME-IMB].
  4374. 2. body subtype
  4375. A string giving the content subtype name as defined in
  4376. [MIME-IMB].
  4377. 3. body parameter parenthesized list
  4378. A parenthesized list of attribute/value pairs [e.g., ("foo"
  4379. "bar" "baz" "rag") where "bar" is the value of "foo" and
  4380. "rag" is the value of "baz"] as defined in [MIME-IMB].
  4381. 4. body id
  4382. A string giving the content id as defined in [MIME-IMB].
  4383. 5. body description
  4384. A string giving the content description as defined in
  4385. [MIME-IMB].
  4386. 6. body encoding
  4387. A string giving the content transfer encoding as defined in
  4388. [MIME-IMB].
  4389. 7. body size
  4390. A number giving the size of the body in octets. Note that this size is
  4391. the size in its transfer encoding and not the resulting size after any
  4392. decoding.
  4393. Put another way, the body structure is a list of seven elements. The
  4394. semantics of the elements of this list are:
  4395. 1. Byte string giving the major MIME type
  4396. 2. Byte string giving the minor MIME type
  4397. 3. A list giving the Content-Type parameters of the message
  4398. 4. A byte string giving the content identifier for the message part, or
  4399. None if it has no content identifier.
  4400. 5. A byte string giving the content description for the message part, or
  4401. None if it has no content description.
  4402. 6. A byte string giving the Content-Encoding of the message body
  4403. 7. An integer giving the number of octets in the message body
  4404. The RFC goes on::
  4405. Multiple parts are indicated by parenthesis nesting. Instead of a body
  4406. type as the first element of the parenthesized list, there is a sequence
  4407. of one or more nested body structures. The second element of the
  4408. parenthesized list is the multipart subtype (mixed, digest, parallel,
  4409. alternative, etc.).
  4410. For example, a two part message consisting of a text and a
  4411. BASE64-encoded text attachment can have a body structure of: (("TEXT"
  4412. "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23)("TEXT" "PLAIN"
  4413. ("CHARSET" "US-ASCII" "NAME" "cc.diff")
  4414. "<960723163407.20117h@cac.washington.edu>" "Compiler diff" "BASE64" 4554
  4415. 73) "MIXED")
  4416. This is represented as::
  4417. [["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 1152,
  4418. 23],
  4419. ["TEXT", "PLAIN", ["CHARSET", "US-ASCII", "NAME", "cc.diff"],
  4420. "<960723163407.20117h@cac.washington.edu>", "Compiler diff",
  4421. "BASE64", 4554, 73],
  4422. "MIXED"]
  4423. In other words, a list of N + 1 elements, where N is the number of parts in
  4424. the message. The first N elements are structures as defined by the previous
  4425. section. The last element is the minor MIME subtype of the multipart
  4426. message.
  4427. Additionally, the RFC describes extension data::
  4428. Extension data follows the multipart subtype. Extension data is never
  4429. returned with the BODY fetch, but can be returned with a BODYSTRUCTURE
  4430. fetch. Extension data, if present, MUST be in the defined order.
  4431. The C{extended} flag controls whether extension data might be returned with
  4432. the normal data.
  4433. """
  4434. return _getMessageStructure(msg).encode(extended)
  4435. def _formatHeaders(headers):
  4436. # TODO: This should use email.header.Header, which handles encoding
  4437. hdrs = [': '.join((k.title(), '\r\n'.join(v.splitlines()))) for (k, v)
  4438. in headers.items()]
  4439. hdrs = '\r\n'.join(hdrs) + '\r\n'
  4440. return networkString(hdrs)
  4441. def subparts(m):
  4442. i = 0
  4443. try:
  4444. while True:
  4445. yield m.getSubPart(i)
  4446. i += 1
  4447. except IndexError:
  4448. pass
  4449. def iterateInReactor(i):
  4450. """
  4451. Consume an interator at most a single iteration per reactor iteration.
  4452. If the iterator produces a Deferred, the next iteration will not occur
  4453. until the Deferred fires, otherwise the next iteration will be taken
  4454. in the next reactor iteration.
  4455. @rtype: C{Deferred}
  4456. @return: A deferred which fires (with None) when the iterator is
  4457. exhausted or whose errback is called if there is an exception.
  4458. """
  4459. from twisted.internet import reactor
  4460. d = defer.Deferred()
  4461. def go(last):
  4462. try:
  4463. r = next(i)
  4464. except StopIteration:
  4465. d.callback(last)
  4466. except:
  4467. d.errback()
  4468. else:
  4469. if isinstance(r, defer.Deferred):
  4470. r.addCallback(go)
  4471. else:
  4472. reactor.callLater(0, go, r)
  4473. go(None)
  4474. return d
  4475. class MessageProducer:
  4476. CHUNK_SIZE = 2 ** 2 ** 2 ** 2
  4477. _uuid4 = staticmethod(uuid.uuid4)
  4478. def __init__(self, msg, buffer = None, scheduler = None):
  4479. """
  4480. Produce this message.
  4481. @param msg: The message I am to produce.
  4482. @type msg: L{IMessage}
  4483. @param buffer: A buffer to hold the message in. If None, I will
  4484. use a L{tempfile.TemporaryFile}.
  4485. @type buffer: file-like
  4486. """
  4487. self.msg = msg
  4488. if buffer is None:
  4489. buffer = tempfile.TemporaryFile()
  4490. self.buffer = buffer
  4491. if scheduler is None:
  4492. scheduler = iterateInReactor
  4493. self.scheduler = scheduler
  4494. self.write = self.buffer.write
  4495. def beginProducing(self, consumer):
  4496. self.consumer = consumer
  4497. return self.scheduler(self._produce())
  4498. def _produce(self):
  4499. headers = self.msg.getHeaders(True)
  4500. boundary = None
  4501. if self.msg.isMultipart():
  4502. content = headers.get('content-type')
  4503. parts = [x.split('=', 1) for x in content.split(';')[1:]]
  4504. parts = dict([(k.lower().strip(), v) for (k, v) in parts])
  4505. boundary = parts.get('boundary')
  4506. if boundary is None:
  4507. # Bastards
  4508. boundary = '----=%s' % (self._uuid4().hex,)
  4509. headers['content-type'] += '; boundary="%s"' % (boundary,)
  4510. else:
  4511. if boundary.startswith('"') and boundary.endswith('"'):
  4512. boundary = boundary[1:-1]
  4513. boundary = networkString(boundary)
  4514. self.write(_formatHeaders(headers))
  4515. self.write(b'\r\n')
  4516. if self.msg.isMultipart():
  4517. for p in subparts(self.msg):
  4518. self.write(b'\r\n--' + boundary + b'\r\n')
  4519. yield MessageProducer(p, self.buffer, self.scheduler
  4520. ).beginProducing(None
  4521. )
  4522. self.write(b'\r\n--' + boundary + b'--\r\n' )
  4523. else:
  4524. f = self.msg.getBodyFile()
  4525. while True:
  4526. b = f.read(self.CHUNK_SIZE)
  4527. if b:
  4528. self.buffer.write(b)
  4529. yield None
  4530. else:
  4531. break
  4532. if self.consumer:
  4533. self.buffer.seek(0, 0)
  4534. yield FileProducer(self.buffer
  4535. ).beginProducing(self.consumer
  4536. ).addCallback(lambda _: self
  4537. )
  4538. class _FetchParser:
  4539. class Envelope:
  4540. # Response should be a list of fields from the message:
  4541. # date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to,
  4542. # and message-id.
  4543. #
  4544. # from, sender, reply-to, to, cc, and bcc are themselves lists of
  4545. # address information:
  4546. # personal name, source route, mailbox name, host name
  4547. #
  4548. # reply-to and sender must not be None. If not present in a message
  4549. # they should be defaulted to the value of the from field.
  4550. type = 'envelope'
  4551. __str__ = lambda self: 'envelope'
  4552. class Flags:
  4553. type = 'flags'
  4554. __str__ = lambda self: 'flags'
  4555. class InternalDate:
  4556. type = 'internaldate'
  4557. __str__ = lambda self: 'internaldate'
  4558. class RFC822Header:
  4559. type = 'rfc822header'
  4560. __str__ = lambda self: 'rfc822.header'
  4561. class RFC822Text:
  4562. type = 'rfc822text'
  4563. __str__ = lambda self: 'rfc822.text'
  4564. class RFC822Size:
  4565. type = 'rfc822size'
  4566. __str__ = lambda self: 'rfc822.size'
  4567. class RFC822:
  4568. type = 'rfc822'
  4569. __str__ = lambda self: 'rfc822'
  4570. class UID:
  4571. type = 'uid'
  4572. __str__ = lambda self: 'uid'
  4573. class Body:
  4574. type = 'body'
  4575. peek = False
  4576. header = None
  4577. mime = None
  4578. text = None
  4579. part = ()
  4580. empty = False
  4581. partialBegin = None
  4582. partialLength = None
  4583. def __str__(self):
  4584. return nativeString(self.__bytes__())
  4585. def __bytes__(self):
  4586. base = b'BODY'
  4587. part = b''
  4588. separator = b''
  4589. if self.part:
  4590. part = b'.'.join([unicode(x + 1).encode("ascii")
  4591. for x in self.part])
  4592. separator = b'.'
  4593. # if self.peek:
  4594. # base += '.PEEK'
  4595. if self.header:
  4596. base += (b'[' + part + separator +
  4597. str(self.header).encode("ascii") + b']')
  4598. elif self.text:
  4599. base += b'[' + part + separator + b'TEXT]'
  4600. elif self.mime:
  4601. base += b'[' + part + separator + b'MIME]'
  4602. elif self.empty:
  4603. base += b'[' + part + b']'
  4604. if self.partialBegin is not None:
  4605. base += b'<' + intToBytes(self.partialBegin) + b'.' + intToBytes(self.partialLength) + b'>'
  4606. return base
  4607. class BodyStructure:
  4608. type = 'bodystructure'
  4609. __str__ = lambda self: 'bodystructure'
  4610. # These three aren't top-level, they don't need type indicators
  4611. class Header:
  4612. negate = False
  4613. fields = None
  4614. part = None
  4615. def __str__(self):
  4616. return nativeString(self.__bytes__())
  4617. def __bytes__(self):
  4618. base = b'HEADER'
  4619. if self.fields:
  4620. base += b'.FIELDS'
  4621. if self.negate:
  4622. base += b'.NOT'
  4623. fields = []
  4624. for f in self.fields:
  4625. f = f.title()
  4626. if _needsQuote(f):
  4627. f = _quote(f)
  4628. fields.append(f)
  4629. base += b' (' + b' '.join(fields) + b')'
  4630. if self.part:
  4631. # TODO: _FetchParser never assigns Header.part - dead
  4632. # code?
  4633. base = b'.'.join([(x + 1).__bytes__() for x in self.part]) + b'.' + base
  4634. return base
  4635. class Text:
  4636. pass
  4637. class MIME:
  4638. pass
  4639. parts = None
  4640. _simple_fetch_att = [
  4641. (b'envelope', Envelope),
  4642. (b'flags', Flags),
  4643. (b'internaldate', InternalDate),
  4644. (b'rfc822.header', RFC822Header),
  4645. (b'rfc822.text', RFC822Text),
  4646. (b'rfc822.size', RFC822Size),
  4647. (b'rfc822', RFC822),
  4648. (b'uid', UID),
  4649. (b'bodystructure', BodyStructure),
  4650. ]
  4651. def __init__(self):
  4652. self.state = ['initial']
  4653. self.result = []
  4654. self.remaining = b''
  4655. def parseString(self, s):
  4656. s = self.remaining + s
  4657. try:
  4658. while s or self.state:
  4659. if not self.state:
  4660. raise IllegalClientResponse("Invalid Argument")
  4661. # print 'Entering state_' + self.state[-1] + ' with', repr(s)
  4662. state = self.state.pop()
  4663. try:
  4664. used = getattr(self, 'state_' + state)(s)
  4665. except:
  4666. self.state.append(state)
  4667. raise
  4668. else:
  4669. # print state, 'consumed', repr(s[:used])
  4670. s = s[used:]
  4671. finally:
  4672. self.remaining = s
  4673. def state_initial(self, s):
  4674. # In the initial state, the literals "ALL", "FULL", and "FAST"
  4675. # are accepted, as is a ( indicating the beginning of a fetch_att
  4676. # token, as is the beginning of a fetch_att token.
  4677. if s == b'':
  4678. return 0
  4679. l = s.lower()
  4680. if l.startswith(b'all'):
  4681. self.result.extend((
  4682. self.Flags(), self.InternalDate(),
  4683. self.RFC822Size(), self.Envelope()
  4684. ))
  4685. return 3
  4686. if l.startswith(b'full'):
  4687. self.result.extend((
  4688. self.Flags(), self.InternalDate(),
  4689. self.RFC822Size(), self.Envelope(),
  4690. self.Body()
  4691. ))
  4692. return 4
  4693. if l.startswith(b'fast'):
  4694. self.result.extend((
  4695. self.Flags(), self.InternalDate(), self.RFC822Size(),
  4696. ))
  4697. return 4
  4698. if l.startswith(b'('):
  4699. self.state.extend(('close_paren', 'maybe_fetch_att', 'fetch_att'))
  4700. return 1
  4701. self.state.append('fetch_att')
  4702. return 0
  4703. def state_close_paren(self, s):
  4704. if s.startswith(b')'):
  4705. return 1
  4706. # TODO: does maybe_fetch_att's startswith(b')') make this dead
  4707. # code?
  4708. raise Exception("Missing )")
  4709. def state_whitespace(self, s):
  4710. # Eat up all the leading whitespace
  4711. if not s or not s[0:1].isspace():
  4712. raise Exception("Whitespace expected, none found")
  4713. i = 0
  4714. for i in range(len(s)):
  4715. if not s[i:i + 1].isspace():
  4716. break
  4717. return i
  4718. def state_maybe_fetch_att(self, s):
  4719. if not s.startswith(b')'):
  4720. self.state.extend(('maybe_fetch_att', 'fetch_att', 'whitespace'))
  4721. return 0
  4722. def state_fetch_att(self, s):
  4723. # Allowed fetch_att tokens are "ENVELOPE", "FLAGS", "INTERNALDATE",
  4724. # "RFC822", "RFC822.HEADER", "RFC822.SIZE", "RFC822.TEXT", "BODY",
  4725. # "BODYSTRUCTURE", "UID",
  4726. # "BODY [".PEEK"] [<section>] ["<" <number> "." <nz_number> ">"]
  4727. l = s.lower()
  4728. for (name, cls) in self._simple_fetch_att:
  4729. if l.startswith(name):
  4730. self.result.append(cls())
  4731. return len(name)
  4732. b = self.Body()
  4733. if l.startswith(b'body.peek'):
  4734. b.peek = True
  4735. used = 9
  4736. elif l.startswith(b'body'):
  4737. used = 4
  4738. else:
  4739. raise Exception("Nothing recognized in fetch_att: %s" % (l,))
  4740. self.pending_body = b
  4741. self.state.extend(('got_body', 'maybe_partial', 'maybe_section'))
  4742. return used
  4743. def state_got_body(self, s):
  4744. self.result.append(self.pending_body)
  4745. del self.pending_body
  4746. return 0
  4747. def state_maybe_section(self, s):
  4748. if not s.startswith(b"["):
  4749. return 0
  4750. self.state.extend(('section', 'part_number'))
  4751. return 1
  4752. _partExpr = re.compile(b'(\d+(?:\.\d+)*)\.?')
  4753. def state_part_number(self, s):
  4754. m = self._partExpr.match(s)
  4755. if m is not None:
  4756. self.parts = [int(p) - 1 for p in m.groups()[0].split(b'.')]
  4757. return m.end()
  4758. else:
  4759. self.parts = []
  4760. return 0
  4761. def state_section(self, s):
  4762. # Grab "HEADER]" or "HEADER.FIELDS (Header list)]" or
  4763. # "HEADER.FIELDS.NOT (Header list)]" or "TEXT]" or "MIME]" or
  4764. # just "]".
  4765. l = s.lower()
  4766. used = 0
  4767. if l.startswith(b']'):
  4768. self.pending_body.empty = True
  4769. used += 1
  4770. elif l.startswith(b'header]'):
  4771. h = self.pending_body.header = self.Header()
  4772. h.negate = True
  4773. h.fields = ()
  4774. used += 7
  4775. elif l.startswith(b'text]'):
  4776. self.pending_body.text = self.Text()
  4777. used += 5
  4778. elif l.startswith(b'mime]'):
  4779. self.pending_body.mime = self.MIME()
  4780. used += 5
  4781. else:
  4782. h = self.Header()
  4783. if l.startswith(b'header.fields.not'):
  4784. h.negate = True
  4785. used += 17
  4786. elif l.startswith(b'header.fields'):
  4787. used += 13
  4788. else:
  4789. raise Exception("Unhandled section contents: %r" % (l,))
  4790. self.pending_body.header = h
  4791. self.state.extend(('finish_section', 'header_list', 'whitespace'))
  4792. self.pending_body.part = tuple(self.parts)
  4793. self.parts = None
  4794. return used
  4795. def state_finish_section(self, s):
  4796. if not s.startswith(b']'):
  4797. raise Exception("section must end with ]")
  4798. return 1
  4799. def state_header_list(self, s):
  4800. if not s.startswith(b'('):
  4801. raise Exception("Header list must begin with (")
  4802. end = s.find(b')')
  4803. if end == -1:
  4804. raise Exception("Header list must end with )")
  4805. headers = s[1:end].split()
  4806. self.pending_body.header.fields = [h.upper() for h in headers]
  4807. return end + 1
  4808. def state_maybe_partial(self, s):
  4809. # Grab <number.number> or nothing at all
  4810. if not s.startswith(b'<'):
  4811. return 0
  4812. end = s.find(b'>')
  4813. if end == -1:
  4814. raise Exception("Found < but not >")
  4815. partial = s[1:end]
  4816. parts = partial.split(b'.', 1)
  4817. if len(parts) != 2:
  4818. raise Exception("Partial specification did not include two .-delimited integers")
  4819. begin, length = map(int, parts)
  4820. self.pending_body.partialBegin = begin
  4821. self.pending_body.partialLength = length
  4822. return end + 1
  4823. class FileProducer:
  4824. CHUNK_SIZE = 2 ** 2 ** 2 ** 2
  4825. firstWrite = True
  4826. def __init__(self, f):
  4827. self.f = f
  4828. def beginProducing(self, consumer):
  4829. self.consumer = consumer
  4830. self.produce = consumer.write
  4831. d = self._onDone = defer.Deferred()
  4832. self.consumer.registerProducer(self, False)
  4833. return d
  4834. def resumeProducing(self):
  4835. b = b''
  4836. if self.firstWrite:
  4837. b = b'{' + intToBytes(self._size()) + b'}\r\n'
  4838. self.firstWrite = False
  4839. if not self.f:
  4840. return
  4841. b = b + self.f.read(self.CHUNK_SIZE)
  4842. if not b:
  4843. self.consumer.unregisterProducer()
  4844. self._onDone.callback(self)
  4845. self._onDone = self.f = self.consumer = None
  4846. else:
  4847. self.produce(b)
  4848. def pauseProducing(self):
  4849. """
  4850. Pause the producer. This does nothing.
  4851. """
  4852. def stopProducing(self):
  4853. """
  4854. Stop the producer. This does nothing.
  4855. """
  4856. def _size(self):
  4857. b = self.f.tell()
  4858. self.f.seek(0, 2)
  4859. e = self.f.tell()
  4860. self.f.seek(b, 0)
  4861. return e - b
  4862. def parseTime(s):
  4863. # XXX - This may require localization :(
  4864. months = [
  4865. 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct',
  4866. 'nov', 'dec', 'january', 'february', 'march', 'april', 'may', 'june',
  4867. 'july', 'august', 'september', 'october', 'november', 'december'
  4868. ]
  4869. expr = {
  4870. 'day': r"(?P<day>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
  4871. 'mon': r"(?P<mon>\w+)",
  4872. 'year': r"(?P<year>\d\d\d\d)"
  4873. }
  4874. m = re.match('%(day)s-%(mon)s-%(year)s' % expr, s)
  4875. if not m:
  4876. raise ValueError("Cannot parse time string %r" % (s,))
  4877. d = m.groupdict()
  4878. try:
  4879. d['mon'] = 1 + (months.index(d['mon'].lower()) % 12)
  4880. d['year'] = int(d['year'])
  4881. d['day'] = int(d['day'])
  4882. except ValueError:
  4883. raise ValueError("Cannot parse time string %r" % (s,))
  4884. else:
  4885. return time.struct_time(
  4886. (d['year'], d['mon'], d['day'], 0, 0, 0, -1, -1, -1)
  4887. )
  4888. # we need to cast Python >=3.3 memoryview to chars (from unsigned bytes), but
  4889. # cast is absent in previous versions: thus, the lambda returns the
  4890. # memoryview instance while ignoring the format
  4891. memory_cast = getattr(memoryview, "cast", lambda *x: x[0])
  4892. def modified_base64(s):
  4893. s_utf7 = s.encode('utf-7')
  4894. return s_utf7[1:-1].replace(b'/', b',')
  4895. def modified_unbase64(s):
  4896. s_utf7 = b'+' + s.replace(b',', b'/') + b'-'
  4897. return s_utf7.decode('utf-7')
  4898. def encoder(s, errors=None):
  4899. """
  4900. Encode the given C{unicode} string using the IMAP4 specific variation of
  4901. UTF-7.
  4902. @type s: C{unicode}
  4903. @param s: The text to encode.
  4904. @param errors: Policy for handling encoding errors. Currently ignored.
  4905. @return: L{tuple} of a L{str} giving the encoded bytes and an L{int}
  4906. giving the number of code units consumed from the input.
  4907. """
  4908. r = bytearray()
  4909. _in = []
  4910. valid_chars = set(map(chr, range(0x20,0x7f))) - {u"&"}
  4911. for c in s:
  4912. if c in valid_chars:
  4913. if _in:
  4914. r += b'&' + modified_base64(''.join(_in)) + b'-'
  4915. del _in[:]
  4916. r.append(ord(c))
  4917. elif c == u'&':
  4918. if _in:
  4919. r += b'&' + modified_base64(''.join(_in)) + b'-'
  4920. del _in[:]
  4921. r += b'&-'
  4922. else:
  4923. _in.append(c)
  4924. if _in:
  4925. r.extend(b'&' + modified_base64(''.join(_in)) + b'-')
  4926. return (bytes(r), len(s))
  4927. def decoder(s, errors=None):
  4928. """
  4929. Decode the given L{str} using the IMAP4 specific variation of UTF-7.
  4930. @type s: L{str}
  4931. @param s: The bytes to decode.
  4932. @param errors: Policy for handling decoding errors. Currently ignored.
  4933. @return: a L{tuple} of a C{unicode} string giving the text which was
  4934. decoded and an L{int} giving the number of bytes consumed from the
  4935. input.
  4936. """
  4937. r = []
  4938. decode = []
  4939. s = memory_cast(memoryview(s), 'c')
  4940. for c in s:
  4941. if c == b'&' and not decode:
  4942. decode.append(b'&')
  4943. elif c == b'-' and decode:
  4944. if len(decode) == 1:
  4945. r.append(u'&')
  4946. else:
  4947. r.append(modified_unbase64(b''.join(decode[1:])))
  4948. decode = []
  4949. elif decode:
  4950. decode.append(c)
  4951. else:
  4952. r.append(c.decode())
  4953. if decode:
  4954. r.append(modified_unbase64(b''.join(decode[1:])))
  4955. return (u''.join(r), len(s))
  4956. class StreamReader(codecs.StreamReader):
  4957. def decode(self, s, errors='strict'):
  4958. return decoder(s)
  4959. class StreamWriter(codecs.StreamWriter):
  4960. def encode(self, s, errors='strict'):
  4961. return encoder(s)
  4962. _codecInfo = codecs.CodecInfo(encoder, decoder, StreamReader, StreamWriter)
  4963. def imap4_utf_7(name):
  4964. if name == 'imap4-utf-7':
  4965. return _codecInfo
  4966. codecs.register(imap4_utf_7)
  4967. __all__ = [
  4968. # Protocol classes
  4969. 'IMAP4Server', 'IMAP4Client',
  4970. # Interfaces
  4971. 'IMailboxListener', 'IClientAuthentication', 'IAccount', 'IMailbox',
  4972. 'INamespacePresenter', 'ICloseableMailbox', 'IMailboxInfo',
  4973. 'IMessage', 'IMessageCopier', 'IMessageFile', 'ISearchableMailbox',
  4974. 'IMessagePart',
  4975. # Exceptions
  4976. 'IMAP4Exception', 'IllegalClientResponse', 'IllegalOperation',
  4977. 'IllegalMailboxEncoding', 'UnhandledResponse', 'NegativeResponse',
  4978. 'NoSupportedAuthentication', 'IllegalServerResponse',
  4979. 'IllegalIdentifierError', 'IllegalQueryError', 'MismatchedNesting',
  4980. 'MismatchedQuoting', 'MailboxException', 'MailboxCollision',
  4981. 'NoSuchMailbox', 'ReadOnlyMailbox',
  4982. # Auth objects
  4983. 'CramMD5ClientAuthenticator', 'PLAINAuthenticator', 'LOGINAuthenticator',
  4984. 'PLAINCredentials', 'LOGINCredentials',
  4985. # Simple query interface
  4986. 'Query', 'Not', 'Or',
  4987. # Miscellaneous
  4988. 'MemoryAccount',
  4989. 'statusRequestHelper',
  4990. ]