_header_value_parser.py 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095
  1. """Header value parser implementing various email-related RFC parsing rules.
  2. The parsing methods defined in this module implement various email related
  3. parsing rules. Principal among them is RFC 5322, which is the followon
  4. to RFC 2822 and primarily a clarification of the former. It also implements
  5. RFC 2047 encoded word decoding.
  6. RFC 5322 goes to considerable trouble to maintain backward compatibility with
  7. RFC 822 in the parse phase, while cleaning up the structure on the generation
  8. phase. This parser supports correct RFC 5322 generation by tagging white space
  9. as folding white space only when folding is allowed in the non-obsolete rule
  10. sets. Actually, the parser is even more generous when accepting input than RFC
  11. 5322 mandates, following the spirit of Postel's Law, which RFC 5322 encourages.
  12. Where possible deviations from the standard are annotated on the 'defects'
  13. attribute of tokens that deviate.
  14. The general structure of the parser follows RFC 5322, and uses its terminology
  15. where there is a direct correspondence. Where the implementation requires a
  16. somewhat different structure than that used by the formal grammar, new terms
  17. that mimic the closest existing terms are used. Thus, it really helps to have
  18. a copy of RFC 5322 handy when studying this code.
  19. Input to the parser is a string that has already been unfolded according to
  20. RFC 5322 rules. According to the RFC this unfolding is the very first step, and
  21. this parser leaves the unfolding step to a higher level message parser, which
  22. will have already detected the line breaks that need unfolding while
  23. determining the beginning and end of each header.
  24. The output of the parser is a TokenList object, which is a list subclass. A
  25. TokenList is a recursive data structure. The terminal nodes of the structure
  26. are Terminal objects, which are subclasses of str. These do not correspond
  27. directly to terminal objects in the formal grammar, but are instead more
  28. practical higher level combinations of true terminals.
  29. All TokenList and Terminal objects have a 'value' attribute, which produces the
  30. semantically meaningful value of that part of the parse subtree. The value of
  31. all whitespace tokens (no matter how many sub-tokens they may contain) is a
  32. single space, as per the RFC rules. This includes 'CFWS', which is herein
  33. included in the general class of whitespace tokens. There is one exception to
  34. the rule that whitespace tokens are collapsed into single spaces in values: in
  35. the value of a 'bare-quoted-string' (a quoted-string with no leading or
  36. trailing whitespace), any whitespace that appeared between the quotation marks
  37. is preserved in the returned value. Note that in all Terminal strings quoted
  38. pairs are turned into their unquoted values.
  39. All TokenList and Terminal objects also have a string value, which attempts to
  40. be a "canonical" representation of the RFC-compliant form of the substring that
  41. produced the parsed subtree, including minimal use of quoted pair quoting.
  42. Whitespace runs are not collapsed.
  43. Comment tokens also have a 'content' attribute providing the string found
  44. between the parens (including any nested comments) with whitespace preserved.
  45. All TokenList and Terminal objects have a 'defects' attribute which is a
  46. possibly empty list all of the defects found while creating the token. Defects
  47. may appear on any token in the tree, and a composite list of all defects in the
  48. subtree is available through the 'all_defects' attribute of any node. (For
  49. Terminal notes x.defects == x.all_defects.)
  50. Each object in a parse tree is called a 'token', and each has a 'token_type'
  51. attribute that gives the name from the RFC 5322 grammar that it represents.
  52. Not all RFC 5322 nodes are produced, and there is one non-RFC 5322 node that
  53. may be produced: 'ptext'. A 'ptext' is a string of printable ascii characters.
  54. It is returned in place of lists of (ctext/quoted-pair) and
  55. (qtext/quoted-pair).
  56. XXX: provide complete list of token types.
  57. """
  58. import re
  59. import sys
  60. import urllib # For urllib.parse.unquote
  61. from string import hexdigits
  62. from operator import itemgetter
  63. from email import _encoded_words as _ew
  64. from email import errors
  65. from email import utils
  66. #
  67. # Useful constants and functions
  68. #
  69. WSP = set(' \t')
  70. CFWS_LEADER = WSP | set('(')
  71. SPECIALS = set(r'()<>@,:;.\"[]')
  72. ATOM_ENDS = SPECIALS | WSP
  73. DOT_ATOM_ENDS = ATOM_ENDS - set('.')
  74. # '.', '"', and '(' do not end phrases in order to support obs-phrase
  75. PHRASE_ENDS = SPECIALS - set('."(')
  76. TSPECIALS = (SPECIALS | set('/?=')) - set('.')
  77. TOKEN_ENDS = TSPECIALS | WSP
  78. ASPECIALS = TSPECIALS | set("*'%")
  79. ATTRIBUTE_ENDS = ASPECIALS | WSP
  80. EXTENDED_ATTRIBUTE_ENDS = ATTRIBUTE_ENDS - set('%')
  81. NLSET = {'\n', '\r'}
  82. SPECIALSNL = SPECIALS | NLSET
  83. def make_quoted_pairs(value):
  84. """Escape dquote and backslash for use within a quoted-string."""
  85. return str(value).replace('\\', '\\\\').replace('"', '\\"')
  86. def quote_string(value):
  87. escaped = make_quoted_pairs(value)
  88. return f'"{escaped}"'
  89. # Match a RFC 2047 word, looks like =?utf-8?q?someword?=
  90. rfc2047_matcher = re.compile(r'''
  91. =\? # literal =?
  92. [^?]* # charset
  93. \? # literal ?
  94. [qQbB] # literal 'q' or 'b', case insensitive
  95. \? # literal ?
  96. .*? # encoded word
  97. \?= # literal ?=
  98. ''', re.VERBOSE | re.MULTILINE)
  99. #
  100. # TokenList and its subclasses
  101. #
  102. class TokenList(list):
  103. token_type = None
  104. syntactic_break = True
  105. ew_combine_allowed = True
  106. def __init__(self, *args, **kw):
  107. super().__init__(*args, **kw)
  108. self.defects = []
  109. def __str__(self):
  110. return ''.join(str(x) for x in self)
  111. def __repr__(self):
  112. return '{}({})'.format(self.__class__.__name__,
  113. super().__repr__())
  114. @property
  115. def value(self):
  116. return ''.join(x.value for x in self if x.value)
  117. @property
  118. def all_defects(self):
  119. return sum((x.all_defects for x in self), self.defects)
  120. def startswith_fws(self):
  121. return self[0].startswith_fws()
  122. @property
  123. def as_ew_allowed(self):
  124. """True if all top level tokens of this part may be RFC2047 encoded."""
  125. return all(part.as_ew_allowed for part in self)
  126. @property
  127. def comments(self):
  128. comments = []
  129. for token in self:
  130. comments.extend(token.comments)
  131. return comments
  132. def fold(self, *, policy):
  133. return _refold_parse_tree(self, policy=policy)
  134. def pprint(self, indent=''):
  135. print(self.ppstr(indent=indent))
  136. def ppstr(self, indent=''):
  137. return '\n'.join(self._pp(indent=indent))
  138. def _pp(self, indent=''):
  139. yield '{}{}/{}('.format(
  140. indent,
  141. self.__class__.__name__,
  142. self.token_type)
  143. for token in self:
  144. if not hasattr(token, '_pp'):
  145. yield (indent + ' !! invalid element in token '
  146. 'list: {!r}'.format(token))
  147. else:
  148. yield from token._pp(indent+' ')
  149. if self.defects:
  150. extra = ' Defects: {}'.format(self.defects)
  151. else:
  152. extra = ''
  153. yield '{}){}'.format(indent, extra)
  154. class WhiteSpaceTokenList(TokenList):
  155. @property
  156. def value(self):
  157. return ' '
  158. @property
  159. def comments(self):
  160. return [x.content for x in self if x.token_type=='comment']
  161. class UnstructuredTokenList(TokenList):
  162. token_type = 'unstructured'
  163. class Phrase(TokenList):
  164. token_type = 'phrase'
  165. class Word(TokenList):
  166. token_type = 'word'
  167. class CFWSList(WhiteSpaceTokenList):
  168. token_type = 'cfws'
  169. class Atom(TokenList):
  170. token_type = 'atom'
  171. class Token(TokenList):
  172. token_type = 'token'
  173. encode_as_ew = False
  174. class EncodedWord(TokenList):
  175. token_type = 'encoded-word'
  176. cte = None
  177. charset = None
  178. lang = None
  179. class QuotedString(TokenList):
  180. token_type = 'quoted-string'
  181. @property
  182. def content(self):
  183. for x in self:
  184. if x.token_type == 'bare-quoted-string':
  185. return x.value
  186. @property
  187. def quoted_value(self):
  188. res = []
  189. for x in self:
  190. if x.token_type == 'bare-quoted-string':
  191. res.append(str(x))
  192. else:
  193. res.append(x.value)
  194. return ''.join(res)
  195. @property
  196. def stripped_value(self):
  197. for token in self:
  198. if token.token_type == 'bare-quoted-string':
  199. return token.value
  200. class BareQuotedString(QuotedString):
  201. token_type = 'bare-quoted-string'
  202. def __str__(self):
  203. return quote_string(''.join(str(x) for x in self))
  204. @property
  205. def value(self):
  206. return ''.join(str(x) for x in self)
  207. class Comment(WhiteSpaceTokenList):
  208. token_type = 'comment'
  209. def __str__(self):
  210. return ''.join(sum([
  211. ["("],
  212. [self.quote(x) for x in self],
  213. [")"],
  214. ], []))
  215. def quote(self, value):
  216. if value.token_type == 'comment':
  217. return str(value)
  218. return str(value).replace('\\', '\\\\').replace(
  219. '(', r'\(').replace(
  220. ')', r'\)')
  221. @property
  222. def content(self):
  223. return ''.join(str(x) for x in self)
  224. @property
  225. def comments(self):
  226. return [self.content]
  227. class AddressList(TokenList):
  228. token_type = 'address-list'
  229. @property
  230. def addresses(self):
  231. return [x for x in self if x.token_type=='address']
  232. @property
  233. def mailboxes(self):
  234. return sum((x.mailboxes
  235. for x in self if x.token_type=='address'), [])
  236. @property
  237. def all_mailboxes(self):
  238. return sum((x.all_mailboxes
  239. for x in self if x.token_type=='address'), [])
  240. class Address(TokenList):
  241. token_type = 'address'
  242. @property
  243. def display_name(self):
  244. if self[0].token_type == 'group':
  245. return self[0].display_name
  246. @property
  247. def mailboxes(self):
  248. if self[0].token_type == 'mailbox':
  249. return [self[0]]
  250. elif self[0].token_type == 'invalid-mailbox':
  251. return []
  252. return self[0].mailboxes
  253. @property
  254. def all_mailboxes(self):
  255. if self[0].token_type == 'mailbox':
  256. return [self[0]]
  257. elif self[0].token_type == 'invalid-mailbox':
  258. return [self[0]]
  259. return self[0].all_mailboxes
  260. class MailboxList(TokenList):
  261. token_type = 'mailbox-list'
  262. @property
  263. def mailboxes(self):
  264. return [x for x in self if x.token_type=='mailbox']
  265. @property
  266. def all_mailboxes(self):
  267. return [x for x in self
  268. if x.token_type in ('mailbox', 'invalid-mailbox')]
  269. class GroupList(TokenList):
  270. token_type = 'group-list'
  271. @property
  272. def mailboxes(self):
  273. if not self or self[0].token_type != 'mailbox-list':
  274. return []
  275. return self[0].mailboxes
  276. @property
  277. def all_mailboxes(self):
  278. if not self or self[0].token_type != 'mailbox-list':
  279. return []
  280. return self[0].all_mailboxes
  281. class Group(TokenList):
  282. token_type = "group"
  283. @property
  284. def mailboxes(self):
  285. if self[2].token_type != 'group-list':
  286. return []
  287. return self[2].mailboxes
  288. @property
  289. def all_mailboxes(self):
  290. if self[2].token_type != 'group-list':
  291. return []
  292. return self[2].all_mailboxes
  293. @property
  294. def display_name(self):
  295. return self[0].display_name
  296. class NameAddr(TokenList):
  297. token_type = 'name-addr'
  298. @property
  299. def display_name(self):
  300. if len(self) == 1:
  301. return None
  302. return self[0].display_name
  303. @property
  304. def local_part(self):
  305. return self[-1].local_part
  306. @property
  307. def domain(self):
  308. return self[-1].domain
  309. @property
  310. def route(self):
  311. return self[-1].route
  312. @property
  313. def addr_spec(self):
  314. return self[-1].addr_spec
  315. class AngleAddr(TokenList):
  316. token_type = 'angle-addr'
  317. @property
  318. def local_part(self):
  319. for x in self:
  320. if x.token_type == 'addr-spec':
  321. return x.local_part
  322. @property
  323. def domain(self):
  324. for x in self:
  325. if x.token_type == 'addr-spec':
  326. return x.domain
  327. @property
  328. def route(self):
  329. for x in self:
  330. if x.token_type == 'obs-route':
  331. return x.domains
  332. @property
  333. def addr_spec(self):
  334. for x in self:
  335. if x.token_type == 'addr-spec':
  336. if x.local_part:
  337. return x.addr_spec
  338. else:
  339. return quote_string(x.local_part) + x.addr_spec
  340. else:
  341. return '<>'
  342. class ObsRoute(TokenList):
  343. token_type = 'obs-route'
  344. @property
  345. def domains(self):
  346. return [x.domain for x in self if x.token_type == 'domain']
  347. class Mailbox(TokenList):
  348. token_type = 'mailbox'
  349. @property
  350. def display_name(self):
  351. if self[0].token_type == 'name-addr':
  352. return self[0].display_name
  353. @property
  354. def local_part(self):
  355. return self[0].local_part
  356. @property
  357. def domain(self):
  358. return self[0].domain
  359. @property
  360. def route(self):
  361. if self[0].token_type == 'name-addr':
  362. return self[0].route
  363. @property
  364. def addr_spec(self):
  365. return self[0].addr_spec
  366. class InvalidMailbox(TokenList):
  367. token_type = 'invalid-mailbox'
  368. @property
  369. def display_name(self):
  370. return None
  371. local_part = domain = route = addr_spec = display_name
  372. class Domain(TokenList):
  373. token_type = 'domain'
  374. as_ew_allowed = False
  375. @property
  376. def domain(self):
  377. return ''.join(super().value.split())
  378. class DotAtom(TokenList):
  379. token_type = 'dot-atom'
  380. class DotAtomText(TokenList):
  381. token_type = 'dot-atom-text'
  382. as_ew_allowed = True
  383. class NoFoldLiteral(TokenList):
  384. token_type = 'no-fold-literal'
  385. as_ew_allowed = False
  386. class AddrSpec(TokenList):
  387. token_type = 'addr-spec'
  388. as_ew_allowed = False
  389. @property
  390. def local_part(self):
  391. return self[0].local_part
  392. @property
  393. def domain(self):
  394. if len(self) < 3:
  395. return None
  396. return self[-1].domain
  397. @property
  398. def value(self):
  399. if len(self) < 3:
  400. return self[0].value
  401. return self[0].value.rstrip()+self[1].value+self[2].value.lstrip()
  402. @property
  403. def addr_spec(self):
  404. nameset = set(self.local_part)
  405. if len(nameset) > len(nameset-DOT_ATOM_ENDS):
  406. lp = quote_string(self.local_part)
  407. else:
  408. lp = self.local_part
  409. if self.domain is not None:
  410. return lp + '@' + self.domain
  411. return lp
  412. class ObsLocalPart(TokenList):
  413. token_type = 'obs-local-part'
  414. as_ew_allowed = False
  415. class DisplayName(Phrase):
  416. token_type = 'display-name'
  417. ew_combine_allowed = False
  418. @property
  419. def display_name(self):
  420. res = TokenList(self)
  421. if len(res) == 0:
  422. return res.value
  423. if res[0].token_type == 'cfws':
  424. res.pop(0)
  425. else:
  426. if (isinstance(res[0], TokenList) and
  427. res[0][0].token_type == 'cfws'):
  428. res[0] = TokenList(res[0][1:])
  429. if res[-1].token_type == 'cfws':
  430. res.pop()
  431. else:
  432. if (isinstance(res[-1], TokenList) and
  433. res[-1][-1].token_type == 'cfws'):
  434. res[-1] = TokenList(res[-1][:-1])
  435. return res.value
  436. @property
  437. def value(self):
  438. quote = False
  439. if self.defects:
  440. quote = True
  441. else:
  442. for x in self:
  443. if x.token_type == 'quoted-string':
  444. quote = True
  445. if len(self) != 0 and quote:
  446. pre = post = ''
  447. if (self[0].token_type == 'cfws' or
  448. isinstance(self[0], TokenList) and
  449. self[0][0].token_type == 'cfws'):
  450. pre = ' '
  451. if (self[-1].token_type == 'cfws' or
  452. isinstance(self[-1], TokenList) and
  453. self[-1][-1].token_type == 'cfws'):
  454. post = ' '
  455. return pre+quote_string(self.display_name)+post
  456. else:
  457. return super().value
  458. class LocalPart(TokenList):
  459. token_type = 'local-part'
  460. as_ew_allowed = False
  461. @property
  462. def value(self):
  463. if self[0].token_type == "quoted-string":
  464. return self[0].quoted_value
  465. else:
  466. return self[0].value
  467. @property
  468. def local_part(self):
  469. # Strip whitespace from front, back, and around dots.
  470. res = [DOT]
  471. last = DOT
  472. last_is_tl = False
  473. for tok in self[0] + [DOT]:
  474. if tok.token_type == 'cfws':
  475. continue
  476. if (last_is_tl and tok.token_type == 'dot' and
  477. last[-1].token_type == 'cfws'):
  478. res[-1] = TokenList(last[:-1])
  479. is_tl = isinstance(tok, TokenList)
  480. if (is_tl and last.token_type == 'dot' and
  481. tok[0].token_type == 'cfws'):
  482. res.append(TokenList(tok[1:]))
  483. else:
  484. res.append(tok)
  485. last = res[-1]
  486. last_is_tl = is_tl
  487. res = TokenList(res[1:-1])
  488. return res.value
  489. class DomainLiteral(TokenList):
  490. token_type = 'domain-literal'
  491. as_ew_allowed = False
  492. @property
  493. def domain(self):
  494. return ''.join(super().value.split())
  495. @property
  496. def ip(self):
  497. for x in self:
  498. if x.token_type == 'ptext':
  499. return x.value
  500. class MIMEVersion(TokenList):
  501. token_type = 'mime-version'
  502. major = None
  503. minor = None
  504. class Parameter(TokenList):
  505. token_type = 'parameter'
  506. sectioned = False
  507. extended = False
  508. charset = 'us-ascii'
  509. @property
  510. def section_number(self):
  511. # Because the first token, the attribute (name) eats CFWS, the second
  512. # token is always the section if there is one.
  513. return self[1].number if self.sectioned else 0
  514. @property
  515. def param_value(self):
  516. # This is part of the "handle quoted extended parameters" hack.
  517. for token in self:
  518. if token.token_type == 'value':
  519. return token.stripped_value
  520. if token.token_type == 'quoted-string':
  521. for token in token:
  522. if token.token_type == 'bare-quoted-string':
  523. for token in token:
  524. if token.token_type == 'value':
  525. return token.stripped_value
  526. return ''
  527. class InvalidParameter(Parameter):
  528. token_type = 'invalid-parameter'
  529. class Attribute(TokenList):
  530. token_type = 'attribute'
  531. @property
  532. def stripped_value(self):
  533. for token in self:
  534. if token.token_type.endswith('attrtext'):
  535. return token.value
  536. class Section(TokenList):
  537. token_type = 'section'
  538. number = None
  539. class Value(TokenList):
  540. token_type = 'value'
  541. @property
  542. def stripped_value(self):
  543. token = self[0]
  544. if token.token_type == 'cfws':
  545. token = self[1]
  546. if token.token_type.endswith(
  547. ('quoted-string', 'attribute', 'extended-attribute')):
  548. return token.stripped_value
  549. return self.value
  550. class MimeParameters(TokenList):
  551. token_type = 'mime-parameters'
  552. syntactic_break = False
  553. @property
  554. def params(self):
  555. # The RFC specifically states that the ordering of parameters is not
  556. # guaranteed and may be reordered by the transport layer. So we have
  557. # to assume the RFC 2231 pieces can come in any order. However, we
  558. # output them in the order that we first see a given name, which gives
  559. # us a stable __str__.
  560. params = {} # Using order preserving dict from Python 3.7+
  561. for token in self:
  562. if not token.token_type.endswith('parameter'):
  563. continue
  564. if token[0].token_type != 'attribute':
  565. continue
  566. name = token[0].value.strip()
  567. if name not in params:
  568. params[name] = []
  569. params[name].append((token.section_number, token))
  570. for name, parts in params.items():
  571. parts = sorted(parts, key=itemgetter(0))
  572. first_param = parts[0][1]
  573. charset = first_param.charset
  574. # Our arbitrary error recovery is to ignore duplicate parameters,
  575. # to use appearance order if there are duplicate rfc 2231 parts,
  576. # and to ignore gaps. This mimics the error recovery of get_param.
  577. if not first_param.extended and len(parts) > 1:
  578. if parts[1][0] == 0:
  579. parts[1][1].defects.append(errors.InvalidHeaderDefect(
  580. 'duplicate parameter name; duplicate(s) ignored'))
  581. parts = parts[:1]
  582. # Else assume the *0* was missing...note that this is different
  583. # from get_param, but we registered a defect for this earlier.
  584. value_parts = []
  585. i = 0
  586. for section_number, param in parts:
  587. if section_number != i:
  588. # We could get fancier here and look for a complete
  589. # duplicate extended parameter and ignore the second one
  590. # seen. But we're not doing that. The old code didn't.
  591. if not param.extended:
  592. param.defects.append(errors.InvalidHeaderDefect(
  593. 'duplicate parameter name; duplicate ignored'))
  594. continue
  595. else:
  596. param.defects.append(errors.InvalidHeaderDefect(
  597. "inconsistent RFC2231 parameter numbering"))
  598. i += 1
  599. value = param.param_value
  600. if param.extended:
  601. try:
  602. value = urllib.parse.unquote_to_bytes(value)
  603. except UnicodeEncodeError:
  604. # source had surrogate escaped bytes. What we do now
  605. # is a bit of an open question. I'm not sure this is
  606. # the best choice, but it is what the old algorithm did
  607. value = urllib.parse.unquote(value, encoding='latin-1')
  608. else:
  609. try:
  610. value = value.decode(charset, 'surrogateescape')
  611. except (LookupError, UnicodeEncodeError):
  612. # XXX: there should really be a custom defect for
  613. # unknown character set to make it easy to find,
  614. # because otherwise unknown charset is a silent
  615. # failure.
  616. value = value.decode('us-ascii', 'surrogateescape')
  617. if utils._has_surrogates(value):
  618. param.defects.append(errors.UndecodableBytesDefect())
  619. value_parts.append(value)
  620. value = ''.join(value_parts)
  621. yield name, value
  622. def __str__(self):
  623. params = []
  624. for name, value in self.params:
  625. if value:
  626. params.append('{}={}'.format(name, quote_string(value)))
  627. else:
  628. params.append(name)
  629. params = '; '.join(params)
  630. return ' ' + params if params else ''
  631. class ParameterizedHeaderValue(TokenList):
  632. # Set this false so that the value doesn't wind up on a new line even
  633. # if it and the parameters would fit there but not on the first line.
  634. syntactic_break = False
  635. @property
  636. def params(self):
  637. for token in reversed(self):
  638. if token.token_type == 'mime-parameters':
  639. return token.params
  640. return {}
  641. class ContentType(ParameterizedHeaderValue):
  642. token_type = 'content-type'
  643. as_ew_allowed = False
  644. maintype = 'text'
  645. subtype = 'plain'
  646. class ContentDisposition(ParameterizedHeaderValue):
  647. token_type = 'content-disposition'
  648. as_ew_allowed = False
  649. content_disposition = None
  650. class ContentTransferEncoding(TokenList):
  651. token_type = 'content-transfer-encoding'
  652. as_ew_allowed = False
  653. cte = '7bit'
  654. class HeaderLabel(TokenList):
  655. token_type = 'header-label'
  656. as_ew_allowed = False
  657. class MsgID(TokenList):
  658. token_type = 'msg-id'
  659. as_ew_allowed = False
  660. def fold(self, policy):
  661. # message-id tokens may not be folded.
  662. return str(self) + policy.linesep
  663. class MessageID(MsgID):
  664. token_type = 'message-id'
  665. class InvalidMessageID(MessageID):
  666. token_type = 'invalid-message-id'
  667. class Header(TokenList):
  668. token_type = 'header'
  669. #
  670. # Terminal classes and instances
  671. #
  672. class Terminal(str):
  673. as_ew_allowed = True
  674. ew_combine_allowed = True
  675. syntactic_break = True
  676. def __new__(cls, value, token_type):
  677. self = super().__new__(cls, value)
  678. self.token_type = token_type
  679. self.defects = []
  680. return self
  681. def __repr__(self):
  682. return "{}({})".format(self.__class__.__name__, super().__repr__())
  683. def pprint(self):
  684. print(self.__class__.__name__ + '/' + self.token_type)
  685. @property
  686. def all_defects(self):
  687. return list(self.defects)
  688. def _pp(self, indent=''):
  689. return ["{}{}/{}({}){}".format(
  690. indent,
  691. self.__class__.__name__,
  692. self.token_type,
  693. super().__repr__(),
  694. '' if not self.defects else ' {}'.format(self.defects),
  695. )]
  696. def pop_trailing_ws(self):
  697. # This terminates the recursion.
  698. return None
  699. @property
  700. def comments(self):
  701. return []
  702. def __getnewargs__(self):
  703. return(str(self), self.token_type)
  704. class WhiteSpaceTerminal(Terminal):
  705. @property
  706. def value(self):
  707. return ' '
  708. def startswith_fws(self):
  709. return True
  710. class ValueTerminal(Terminal):
  711. @property
  712. def value(self):
  713. return self
  714. def startswith_fws(self):
  715. return False
  716. class EWWhiteSpaceTerminal(WhiteSpaceTerminal):
  717. @property
  718. def value(self):
  719. return ''
  720. def __str__(self):
  721. return ''
  722. class _InvalidEwError(errors.HeaderParseError):
  723. """Invalid encoded word found while parsing headers."""
  724. # XXX these need to become classes and used as instances so
  725. # that a program can't change them in a parse tree and screw
  726. # up other parse trees. Maybe should have tests for that, too.
  727. DOT = ValueTerminal('.', 'dot')
  728. ListSeparator = ValueTerminal(',', 'list-separator')
  729. ListSeparator.as_ew_allowed = False
  730. ListSeparator.syntactic_break = False
  731. RouteComponentMarker = ValueTerminal('@', 'route-component-marker')
  732. #
  733. # Parser
  734. #
  735. # Parse strings according to RFC822/2047/2822/5322 rules.
  736. #
  737. # This is a stateless parser. Each get_XXX function accepts a string and
  738. # returns either a Terminal or a TokenList representing the RFC object named
  739. # by the method and a string containing the remaining unparsed characters
  740. # from the input. Thus a parser method consumes the next syntactic construct
  741. # of a given type and returns a token representing the construct plus the
  742. # unparsed remainder of the input string.
  743. #
  744. # For example, if the first element of a structured header is a 'phrase',
  745. # then:
  746. #
  747. # phrase, value = get_phrase(value)
  748. #
  749. # returns the complete phrase from the start of the string value, plus any
  750. # characters left in the string after the phrase is removed.
  751. _wsp_splitter = re.compile(r'([{}]+)'.format(''.join(WSP))).split
  752. _non_atom_end_matcher = re.compile(r"[^{}]+".format(
  753. re.escape(''.join(ATOM_ENDS)))).match
  754. _non_printable_finder = re.compile(r"[\x00-\x20\x7F]").findall
  755. _non_token_end_matcher = re.compile(r"[^{}]+".format(
  756. re.escape(''.join(TOKEN_ENDS)))).match
  757. _non_attribute_end_matcher = re.compile(r"[^{}]+".format(
  758. re.escape(''.join(ATTRIBUTE_ENDS)))).match
  759. _non_extended_attribute_end_matcher = re.compile(r"[^{}]+".format(
  760. re.escape(''.join(EXTENDED_ATTRIBUTE_ENDS)))).match
  761. def _validate_xtext(xtext):
  762. """If input token contains ASCII non-printables, register a defect."""
  763. non_printables = _non_printable_finder(xtext)
  764. if non_printables:
  765. xtext.defects.append(errors.NonPrintableDefect(non_printables))
  766. if utils._has_surrogates(xtext):
  767. xtext.defects.append(errors.UndecodableBytesDefect(
  768. "Non-ASCII characters found in header token"))
  769. def _get_ptext_to_endchars(value, endchars):
  770. """Scan printables/quoted-pairs until endchars and return unquoted ptext.
  771. This function turns a run of qcontent, ccontent-without-comments, or
  772. dtext-with-quoted-printables into a single string by unquoting any
  773. quoted printables. It returns the string, the remaining value, and
  774. a flag that is True iff there were any quoted printables decoded.
  775. """
  776. fragment, *remainder = _wsp_splitter(value, 1)
  777. vchars = []
  778. escape = False
  779. had_qp = False
  780. for pos in range(len(fragment)):
  781. if fragment[pos] == '\\':
  782. if escape:
  783. escape = False
  784. had_qp = True
  785. else:
  786. escape = True
  787. continue
  788. if escape:
  789. escape = False
  790. elif fragment[pos] in endchars:
  791. break
  792. vchars.append(fragment[pos])
  793. else:
  794. pos = pos + 1
  795. return ''.join(vchars), ''.join([fragment[pos:]] + remainder), had_qp
  796. def get_fws(value):
  797. """FWS = 1*WSP
  798. This isn't the RFC definition. We're using fws to represent tokens where
  799. folding can be done, but when we are parsing the *un*folding has already
  800. been done so we don't need to watch out for CRLF.
  801. """
  802. newvalue = value.lstrip()
  803. fws = WhiteSpaceTerminal(value[:len(value)-len(newvalue)], 'fws')
  804. return fws, newvalue
  805. def get_encoded_word(value):
  806. """ encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
  807. """
  808. ew = EncodedWord()
  809. if not value.startswith('=?'):
  810. raise errors.HeaderParseError(
  811. "expected encoded word but found {}".format(value))
  812. tok, *remainder = value[2:].split('?=', 1)
  813. if tok == value[2:]:
  814. raise errors.HeaderParseError(
  815. "expected encoded word but found {}".format(value))
  816. remstr = ''.join(remainder)
  817. if (len(remstr) > 1 and
  818. remstr[0] in hexdigits and
  819. remstr[1] in hexdigits and
  820. tok.count('?') < 2):
  821. # The ? after the CTE was followed by an encoded word escape (=XX).
  822. rest, *remainder = remstr.split('?=', 1)
  823. tok = tok + '?=' + rest
  824. if len(tok.split()) > 1:
  825. ew.defects.append(errors.InvalidHeaderDefect(
  826. "whitespace inside encoded word"))
  827. ew.cte = value
  828. value = ''.join(remainder)
  829. try:
  830. text, charset, lang, defects = _ew.decode('=?' + tok + '?=')
  831. except (ValueError, KeyError):
  832. raise _InvalidEwError(
  833. "encoded word format invalid: '{}'".format(ew.cte))
  834. ew.charset = charset
  835. ew.lang = lang
  836. ew.defects.extend(defects)
  837. while text:
  838. if text[0] in WSP:
  839. token, text = get_fws(text)
  840. ew.append(token)
  841. continue
  842. chars, *remainder = _wsp_splitter(text, 1)
  843. vtext = ValueTerminal(chars, 'vtext')
  844. _validate_xtext(vtext)
  845. ew.append(vtext)
  846. text = ''.join(remainder)
  847. # Encoded words should be followed by a WS
  848. if value and value[0] not in WSP:
  849. ew.defects.append(errors.InvalidHeaderDefect(
  850. "missing trailing whitespace after encoded-word"))
  851. return ew, value
  852. def get_unstructured(value):
  853. """unstructured = (*([FWS] vchar) *WSP) / obs-unstruct
  854. obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS)
  855. obs-utext = %d0 / obs-NO-WS-CTL / LF / CR
  856. obs-NO-WS-CTL is control characters except WSP/CR/LF.
  857. So, basically, we have printable runs, plus control characters or nulls in
  858. the obsolete syntax, separated by whitespace. Since RFC 2047 uses the
  859. obsolete syntax in its specification, but requires whitespace on either
  860. side of the encoded words, I can see no reason to need to separate the
  861. non-printable-non-whitespace from the printable runs if they occur, so we
  862. parse this into xtext tokens separated by WSP tokens.
  863. Because an 'unstructured' value must by definition constitute the entire
  864. value, this 'get' routine does not return a remaining value, only the
  865. parsed TokenList.
  866. """
  867. # XXX: but what about bare CR and LF? They might signal the start or
  868. # end of an encoded word. YAGNI for now, since our current parsers
  869. # will never send us strings with bare CR or LF.
  870. unstructured = UnstructuredTokenList()
  871. while value:
  872. if value[0] in WSP:
  873. token, value = get_fws(value)
  874. unstructured.append(token)
  875. continue
  876. valid_ew = True
  877. if value.startswith('=?'):
  878. try:
  879. token, value = get_encoded_word(value)
  880. except _InvalidEwError:
  881. valid_ew = False
  882. except errors.HeaderParseError:
  883. # XXX: Need to figure out how to register defects when
  884. # appropriate here.
  885. pass
  886. else:
  887. have_ws = True
  888. if len(unstructured) > 0:
  889. if unstructured[-1].token_type != 'fws':
  890. unstructured.defects.append(errors.InvalidHeaderDefect(
  891. "missing whitespace before encoded word"))
  892. have_ws = False
  893. if have_ws and len(unstructured) > 1:
  894. if unstructured[-2].token_type == 'encoded-word':
  895. unstructured[-1] = EWWhiteSpaceTerminal(
  896. unstructured[-1], 'fws')
  897. unstructured.append(token)
  898. continue
  899. tok, *remainder = _wsp_splitter(value, 1)
  900. # Split in the middle of an atom if there is a rfc2047 encoded word
  901. # which does not have WSP on both sides. The defect will be registered
  902. # the next time through the loop.
  903. # This needs to only be performed when the encoded word is valid;
  904. # otherwise, performing it on an invalid encoded word can cause
  905. # the parser to go in an infinite loop.
  906. if valid_ew and rfc2047_matcher.search(tok):
  907. tok, *remainder = value.partition('=?')
  908. vtext = ValueTerminal(tok, 'vtext')
  909. _validate_xtext(vtext)
  910. unstructured.append(vtext)
  911. value = ''.join(remainder)
  912. return unstructured
  913. def get_qp_ctext(value):
  914. r"""ctext = <printable ascii except \ ( )>
  915. This is not the RFC ctext, since we are handling nested comments in comment
  916. and unquoting quoted-pairs here. We allow anything except the '()'
  917. characters, but if we find any ASCII other than the RFC defined printable
  918. ASCII, a NonPrintableDefect is added to the token's defects list. Since
  919. quoted pairs are converted to their unquoted values, what is returned is
  920. a 'ptext' token. In this case it is a WhiteSpaceTerminal, so it's value
  921. is ' '.
  922. """
  923. ptext, value, _ = _get_ptext_to_endchars(value, '()')
  924. ptext = WhiteSpaceTerminal(ptext, 'ptext')
  925. _validate_xtext(ptext)
  926. return ptext, value
  927. def get_qcontent(value):
  928. """qcontent = qtext / quoted-pair
  929. We allow anything except the DQUOTE character, but if we find any ASCII
  930. other than the RFC defined printable ASCII, a NonPrintableDefect is
  931. added to the token's defects list. Any quoted pairs are converted to their
  932. unquoted values, so what is returned is a 'ptext' token. In this case it
  933. is a ValueTerminal.
  934. """
  935. ptext, value, _ = _get_ptext_to_endchars(value, '"')
  936. ptext = ValueTerminal(ptext, 'ptext')
  937. _validate_xtext(ptext)
  938. return ptext, value
  939. def get_atext(value):
  940. """atext = <matches _atext_matcher>
  941. We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to
  942. the token's defects list if we find non-atext characters.
  943. """
  944. m = _non_atom_end_matcher(value)
  945. if not m:
  946. raise errors.HeaderParseError(
  947. "expected atext but found '{}'".format(value))
  948. atext = m.group()
  949. value = value[len(atext):]
  950. atext = ValueTerminal(atext, 'atext')
  951. _validate_xtext(atext)
  952. return atext, value
  953. def get_bare_quoted_string(value):
  954. """bare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE
  955. A quoted-string without the leading or trailing white space. Its
  956. value is the text between the quote marks, with whitespace
  957. preserved and quoted pairs decoded.
  958. """
  959. if not value or value[0] != '"':
  960. raise errors.HeaderParseError(
  961. "expected '\"' but found '{}'".format(value))
  962. bare_quoted_string = BareQuotedString()
  963. value = value[1:]
  964. if value and value[0] == '"':
  965. token, value = get_qcontent(value)
  966. bare_quoted_string.append(token)
  967. while value and value[0] != '"':
  968. if value[0] in WSP:
  969. token, value = get_fws(value)
  970. elif value[:2] == '=?':
  971. valid_ew = False
  972. try:
  973. token, value = get_encoded_word(value)
  974. bare_quoted_string.defects.append(errors.InvalidHeaderDefect(
  975. "encoded word inside quoted string"))
  976. valid_ew = True
  977. except errors.HeaderParseError:
  978. token, value = get_qcontent(value)
  979. # Collapse the whitespace between two encoded words that occur in a
  980. # bare-quoted-string.
  981. if valid_ew and len(bare_quoted_string) > 1:
  982. if (bare_quoted_string[-1].token_type == 'fws' and
  983. bare_quoted_string[-2].token_type == 'encoded-word'):
  984. bare_quoted_string[-1] = EWWhiteSpaceTerminal(
  985. bare_quoted_string[-1], 'fws')
  986. else:
  987. token, value = get_qcontent(value)
  988. bare_quoted_string.append(token)
  989. if not value:
  990. bare_quoted_string.defects.append(errors.InvalidHeaderDefect(
  991. "end of header inside quoted string"))
  992. return bare_quoted_string, value
  993. return bare_quoted_string, value[1:]
  994. def get_comment(value):
  995. """comment = "(" *([FWS] ccontent) [FWS] ")"
  996. ccontent = ctext / quoted-pair / comment
  997. We handle nested comments here, and quoted-pair in our qp-ctext routine.
  998. """
  999. if value and value[0] != '(':
  1000. raise errors.HeaderParseError(
  1001. "expected '(' but found '{}'".format(value))
  1002. comment = Comment()
  1003. value = value[1:]
  1004. while value and value[0] != ")":
  1005. if value[0] in WSP:
  1006. token, value = get_fws(value)
  1007. elif value[0] == '(':
  1008. token, value = get_comment(value)
  1009. else:
  1010. token, value = get_qp_ctext(value)
  1011. comment.append(token)
  1012. if not value:
  1013. comment.defects.append(errors.InvalidHeaderDefect(
  1014. "end of header inside comment"))
  1015. return comment, value
  1016. return comment, value[1:]
  1017. def get_cfws(value):
  1018. """CFWS = (1*([FWS] comment) [FWS]) / FWS
  1019. """
  1020. cfws = CFWSList()
  1021. while value and value[0] in CFWS_LEADER:
  1022. if value[0] in WSP:
  1023. token, value = get_fws(value)
  1024. else:
  1025. token, value = get_comment(value)
  1026. cfws.append(token)
  1027. return cfws, value
  1028. def get_quoted_string(value):
  1029. """quoted-string = [CFWS] <bare-quoted-string> [CFWS]
  1030. 'bare-quoted-string' is an intermediate class defined by this
  1031. parser and not by the RFC grammar. It is the quoted string
  1032. without any attached CFWS.
  1033. """
  1034. quoted_string = QuotedString()
  1035. if value and value[0] in CFWS_LEADER:
  1036. token, value = get_cfws(value)
  1037. quoted_string.append(token)
  1038. token, value = get_bare_quoted_string(value)
  1039. quoted_string.append(token)
  1040. if value and value[0] in CFWS_LEADER:
  1041. token, value = get_cfws(value)
  1042. quoted_string.append(token)
  1043. return quoted_string, value
  1044. def get_atom(value):
  1045. """atom = [CFWS] 1*atext [CFWS]
  1046. An atom could be an rfc2047 encoded word.
  1047. """
  1048. atom = Atom()
  1049. if value and value[0] in CFWS_LEADER:
  1050. token, value = get_cfws(value)
  1051. atom.append(token)
  1052. if value and value[0] in ATOM_ENDS:
  1053. raise errors.HeaderParseError(
  1054. "expected atom but found '{}'".format(value))
  1055. if value.startswith('=?'):
  1056. try:
  1057. token, value = get_encoded_word(value)
  1058. except errors.HeaderParseError:
  1059. # XXX: need to figure out how to register defects when
  1060. # appropriate here.
  1061. token, value = get_atext(value)
  1062. else:
  1063. token, value = get_atext(value)
  1064. atom.append(token)
  1065. if value and value[0] in CFWS_LEADER:
  1066. token, value = get_cfws(value)
  1067. atom.append(token)
  1068. return atom, value
  1069. def get_dot_atom_text(value):
  1070. """ dot-text = 1*atext *("." 1*atext)
  1071. """
  1072. dot_atom_text = DotAtomText()
  1073. if not value or value[0] in ATOM_ENDS:
  1074. raise errors.HeaderParseError("expected atom at a start of "
  1075. "dot-atom-text but found '{}'".format(value))
  1076. while value and value[0] not in ATOM_ENDS:
  1077. token, value = get_atext(value)
  1078. dot_atom_text.append(token)
  1079. if value and value[0] == '.':
  1080. dot_atom_text.append(DOT)
  1081. value = value[1:]
  1082. if dot_atom_text[-1] is DOT:
  1083. raise errors.HeaderParseError("expected atom at end of dot-atom-text "
  1084. "but found '{}'".format('.'+value))
  1085. return dot_atom_text, value
  1086. def get_dot_atom(value):
  1087. """ dot-atom = [CFWS] dot-atom-text [CFWS]
  1088. Any place we can have a dot atom, we could instead have an rfc2047 encoded
  1089. word.
  1090. """
  1091. dot_atom = DotAtom()
  1092. if value[0] in CFWS_LEADER:
  1093. token, value = get_cfws(value)
  1094. dot_atom.append(token)
  1095. if value.startswith('=?'):
  1096. try:
  1097. token, value = get_encoded_word(value)
  1098. except errors.HeaderParseError:
  1099. # XXX: need to figure out how to register defects when
  1100. # appropriate here.
  1101. token, value = get_dot_atom_text(value)
  1102. else:
  1103. token, value = get_dot_atom_text(value)
  1104. dot_atom.append(token)
  1105. if value and value[0] in CFWS_LEADER:
  1106. token, value = get_cfws(value)
  1107. dot_atom.append(token)
  1108. return dot_atom, value
  1109. def get_word(value):
  1110. """word = atom / quoted-string
  1111. Either atom or quoted-string may start with CFWS. We have to peel off this
  1112. CFWS first to determine which type of word to parse. Afterward we splice
  1113. the leading CFWS, if any, into the parsed sub-token.
  1114. If neither an atom or a quoted-string is found before the next special, a
  1115. HeaderParseError is raised.
  1116. The token returned is either an Atom or a QuotedString, as appropriate.
  1117. This means the 'word' level of the formal grammar is not represented in the
  1118. parse tree; this is because having that extra layer when manipulating the
  1119. parse tree is more confusing than it is helpful.
  1120. """
  1121. if value[0] in CFWS_LEADER:
  1122. leader, value = get_cfws(value)
  1123. else:
  1124. leader = None
  1125. if not value:
  1126. raise errors.HeaderParseError(
  1127. "Expected 'atom' or 'quoted-string' but found nothing.")
  1128. if value[0]=='"':
  1129. token, value = get_quoted_string(value)
  1130. elif value[0] in SPECIALS:
  1131. raise errors.HeaderParseError("Expected 'atom' or 'quoted-string' "
  1132. "but found '{}'".format(value))
  1133. else:
  1134. token, value = get_atom(value)
  1135. if leader is not None:
  1136. token[:0] = [leader]
  1137. return token, value
  1138. def get_phrase(value):
  1139. """ phrase = 1*word / obs-phrase
  1140. obs-phrase = word *(word / "." / CFWS)
  1141. This means a phrase can be a sequence of words, periods, and CFWS in any
  1142. order as long as it starts with at least one word. If anything other than
  1143. words is detected, an ObsoleteHeaderDefect is added to the token's defect
  1144. list. We also accept a phrase that starts with CFWS followed by a dot;
  1145. this is registered as an InvalidHeaderDefect, since it is not supported by
  1146. even the obsolete grammar.
  1147. """
  1148. phrase = Phrase()
  1149. try:
  1150. token, value = get_word(value)
  1151. phrase.append(token)
  1152. except errors.HeaderParseError:
  1153. phrase.defects.append(errors.InvalidHeaderDefect(
  1154. "phrase does not start with word"))
  1155. while value and value[0] not in PHRASE_ENDS:
  1156. if value[0]=='.':
  1157. phrase.append(DOT)
  1158. phrase.defects.append(errors.ObsoleteHeaderDefect(
  1159. "period in 'phrase'"))
  1160. value = value[1:]
  1161. else:
  1162. try:
  1163. token, value = get_word(value)
  1164. except errors.HeaderParseError:
  1165. if value[0] in CFWS_LEADER:
  1166. token, value = get_cfws(value)
  1167. phrase.defects.append(errors.ObsoleteHeaderDefect(
  1168. "comment found without atom"))
  1169. else:
  1170. raise
  1171. phrase.append(token)
  1172. return phrase, value
  1173. def get_local_part(value):
  1174. """ local-part = dot-atom / quoted-string / obs-local-part
  1175. """
  1176. local_part = LocalPart()
  1177. leader = None
  1178. if value and value[0] in CFWS_LEADER:
  1179. leader, value = get_cfws(value)
  1180. if not value:
  1181. raise errors.HeaderParseError(
  1182. "expected local-part but found '{}'".format(value))
  1183. try:
  1184. token, value = get_dot_atom(value)
  1185. except errors.HeaderParseError:
  1186. try:
  1187. token, value = get_word(value)
  1188. except errors.HeaderParseError:
  1189. if value[0] != '\\' and value[0] in PHRASE_ENDS:
  1190. raise
  1191. token = TokenList()
  1192. if leader is not None:
  1193. token[:0] = [leader]
  1194. local_part.append(token)
  1195. if value and (value[0]=='\\' or value[0] not in PHRASE_ENDS):
  1196. obs_local_part, value = get_obs_local_part(str(local_part) + value)
  1197. if obs_local_part.token_type == 'invalid-obs-local-part':
  1198. local_part.defects.append(errors.InvalidHeaderDefect(
  1199. "local-part is not dot-atom, quoted-string, or obs-local-part"))
  1200. else:
  1201. local_part.defects.append(errors.ObsoleteHeaderDefect(
  1202. "local-part is not a dot-atom (contains CFWS)"))
  1203. local_part[0] = obs_local_part
  1204. try:
  1205. local_part.value.encode('ascii')
  1206. except UnicodeEncodeError:
  1207. local_part.defects.append(errors.NonASCIILocalPartDefect(
  1208. "local-part contains non-ASCII characters)"))
  1209. return local_part, value
  1210. def get_obs_local_part(value):
  1211. """ obs-local-part = word *("." word)
  1212. """
  1213. obs_local_part = ObsLocalPart()
  1214. last_non_ws_was_dot = False
  1215. while value and (value[0]=='\\' or value[0] not in PHRASE_ENDS):
  1216. if value[0] == '.':
  1217. if last_non_ws_was_dot:
  1218. obs_local_part.defects.append(errors.InvalidHeaderDefect(
  1219. "invalid repeated '.'"))
  1220. obs_local_part.append(DOT)
  1221. last_non_ws_was_dot = True
  1222. value = value[1:]
  1223. continue
  1224. elif value[0]=='\\':
  1225. obs_local_part.append(ValueTerminal(value[0],
  1226. 'misplaced-special'))
  1227. value = value[1:]
  1228. obs_local_part.defects.append(errors.InvalidHeaderDefect(
  1229. "'\\' character outside of quoted-string/ccontent"))
  1230. last_non_ws_was_dot = False
  1231. continue
  1232. if obs_local_part and obs_local_part[-1].token_type != 'dot':
  1233. obs_local_part.defects.append(errors.InvalidHeaderDefect(
  1234. "missing '.' between words"))
  1235. try:
  1236. token, value = get_word(value)
  1237. last_non_ws_was_dot = False
  1238. except errors.HeaderParseError:
  1239. if value[0] not in CFWS_LEADER:
  1240. raise
  1241. token, value = get_cfws(value)
  1242. obs_local_part.append(token)
  1243. if not obs_local_part:
  1244. raise errors.HeaderParseError(
  1245. "expected obs-local-part but found '{}'".format(value))
  1246. if (obs_local_part[0].token_type == 'dot' or
  1247. obs_local_part[0].token_type=='cfws' and
  1248. len(obs_local_part) > 1 and
  1249. obs_local_part[1].token_type=='dot'):
  1250. obs_local_part.defects.append(errors.InvalidHeaderDefect(
  1251. "Invalid leading '.' in local part"))
  1252. if (obs_local_part[-1].token_type == 'dot' or
  1253. obs_local_part[-1].token_type=='cfws' and
  1254. len(obs_local_part) > 1 and
  1255. obs_local_part[-2].token_type=='dot'):
  1256. obs_local_part.defects.append(errors.InvalidHeaderDefect(
  1257. "Invalid trailing '.' in local part"))
  1258. if obs_local_part.defects:
  1259. obs_local_part.token_type = 'invalid-obs-local-part'
  1260. return obs_local_part, value
  1261. def get_dtext(value):
  1262. r""" dtext = <printable ascii except \ [ ]> / obs-dtext
  1263. obs-dtext = obs-NO-WS-CTL / quoted-pair
  1264. We allow anything except the excluded characters, but if we find any
  1265. ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is
  1266. added to the token's defects list. Quoted pairs are converted to their
  1267. unquoted values, so what is returned is a ptext token, in this case a
  1268. ValueTerminal. If there were quoted-printables, an ObsoleteHeaderDefect is
  1269. added to the returned token's defect list.
  1270. """
  1271. ptext, value, had_qp = _get_ptext_to_endchars(value, '[]')
  1272. ptext = ValueTerminal(ptext, 'ptext')
  1273. if had_qp:
  1274. ptext.defects.append(errors.ObsoleteHeaderDefect(
  1275. "quoted printable found in domain-literal"))
  1276. _validate_xtext(ptext)
  1277. return ptext, value
  1278. def _check_for_early_dl_end(value, domain_literal):
  1279. if value:
  1280. return False
  1281. domain_literal.append(errors.InvalidHeaderDefect(
  1282. "end of input inside domain-literal"))
  1283. domain_literal.append(ValueTerminal(']', 'domain-literal-end'))
  1284. return True
  1285. def get_domain_literal(value):
  1286. """ domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
  1287. """
  1288. domain_literal = DomainLiteral()
  1289. if value[0] in CFWS_LEADER:
  1290. token, value = get_cfws(value)
  1291. domain_literal.append(token)
  1292. if not value:
  1293. raise errors.HeaderParseError("expected domain-literal")
  1294. if value[0] != '[':
  1295. raise errors.HeaderParseError("expected '[' at start of domain-literal "
  1296. "but found '{}'".format(value))
  1297. value = value[1:]
  1298. if _check_for_early_dl_end(value, domain_literal):
  1299. return domain_literal, value
  1300. domain_literal.append(ValueTerminal('[', 'domain-literal-start'))
  1301. if value[0] in WSP:
  1302. token, value = get_fws(value)
  1303. domain_literal.append(token)
  1304. token, value = get_dtext(value)
  1305. domain_literal.append(token)
  1306. if _check_for_early_dl_end(value, domain_literal):
  1307. return domain_literal, value
  1308. if value[0] in WSP:
  1309. token, value = get_fws(value)
  1310. domain_literal.append(token)
  1311. if _check_for_early_dl_end(value, domain_literal):
  1312. return domain_literal, value
  1313. if value[0] != ']':
  1314. raise errors.HeaderParseError("expected ']' at end of domain-literal "
  1315. "but found '{}'".format(value))
  1316. domain_literal.append(ValueTerminal(']', 'domain-literal-end'))
  1317. value = value[1:]
  1318. if value and value[0] in CFWS_LEADER:
  1319. token, value = get_cfws(value)
  1320. domain_literal.append(token)
  1321. return domain_literal, value
  1322. def get_domain(value):
  1323. """ domain = dot-atom / domain-literal / obs-domain
  1324. obs-domain = atom *("." atom))
  1325. """
  1326. domain = Domain()
  1327. leader = None
  1328. if value and value[0] in CFWS_LEADER:
  1329. leader, value = get_cfws(value)
  1330. if not value:
  1331. raise errors.HeaderParseError(
  1332. "expected domain but found '{}'".format(value))
  1333. if value[0] == '[':
  1334. token, value = get_domain_literal(value)
  1335. if leader is not None:
  1336. token[:0] = [leader]
  1337. domain.append(token)
  1338. return domain, value
  1339. try:
  1340. token, value = get_dot_atom(value)
  1341. except errors.HeaderParseError:
  1342. token, value = get_atom(value)
  1343. if value and value[0] == '@':
  1344. raise errors.HeaderParseError('Invalid Domain')
  1345. if leader is not None:
  1346. token[:0] = [leader]
  1347. domain.append(token)
  1348. if value and value[0] == '.':
  1349. domain.defects.append(errors.ObsoleteHeaderDefect(
  1350. "domain is not a dot-atom (contains CFWS)"))
  1351. if domain[0].token_type == 'dot-atom':
  1352. domain[:] = domain[0]
  1353. while value and value[0] == '.':
  1354. domain.append(DOT)
  1355. token, value = get_atom(value[1:])
  1356. domain.append(token)
  1357. return domain, value
  1358. def get_addr_spec(value):
  1359. """ addr-spec = local-part "@" domain
  1360. """
  1361. addr_spec = AddrSpec()
  1362. token, value = get_local_part(value)
  1363. addr_spec.append(token)
  1364. if not value or value[0] != '@':
  1365. addr_spec.defects.append(errors.InvalidHeaderDefect(
  1366. "addr-spec local part with no domain"))
  1367. return addr_spec, value
  1368. addr_spec.append(ValueTerminal('@', 'address-at-symbol'))
  1369. token, value = get_domain(value[1:])
  1370. addr_spec.append(token)
  1371. return addr_spec, value
  1372. def get_obs_route(value):
  1373. """ obs-route = obs-domain-list ":"
  1374. obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain])
  1375. Returns an obs-route token with the appropriate sub-tokens (that is,
  1376. there is no obs-domain-list in the parse tree).
  1377. """
  1378. obs_route = ObsRoute()
  1379. while value and (value[0]==',' or value[0] in CFWS_LEADER):
  1380. if value[0] in CFWS_LEADER:
  1381. token, value = get_cfws(value)
  1382. obs_route.append(token)
  1383. elif value[0] == ',':
  1384. obs_route.append(ListSeparator)
  1385. value = value[1:]
  1386. if not value or value[0] != '@':
  1387. raise errors.HeaderParseError(
  1388. "expected obs-route domain but found '{}'".format(value))
  1389. obs_route.append(RouteComponentMarker)
  1390. token, value = get_domain(value[1:])
  1391. obs_route.append(token)
  1392. while value and value[0]==',':
  1393. obs_route.append(ListSeparator)
  1394. value = value[1:]
  1395. if not value:
  1396. break
  1397. if value[0] in CFWS_LEADER:
  1398. token, value = get_cfws(value)
  1399. obs_route.append(token)
  1400. if not value:
  1401. break
  1402. if value[0] == '@':
  1403. obs_route.append(RouteComponentMarker)
  1404. token, value = get_domain(value[1:])
  1405. obs_route.append(token)
  1406. if not value:
  1407. raise errors.HeaderParseError("end of header while parsing obs-route")
  1408. if value[0] != ':':
  1409. raise errors.HeaderParseError( "expected ':' marking end of "
  1410. "obs-route but found '{}'".format(value))
  1411. obs_route.append(ValueTerminal(':', 'end-of-obs-route-marker'))
  1412. return obs_route, value[1:]
  1413. def get_angle_addr(value):
  1414. """ angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr
  1415. obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
  1416. """
  1417. angle_addr = AngleAddr()
  1418. if value and value[0] in CFWS_LEADER:
  1419. token, value = get_cfws(value)
  1420. angle_addr.append(token)
  1421. if not value or value[0] != '<':
  1422. raise errors.HeaderParseError(
  1423. "expected angle-addr but found '{}'".format(value))
  1424. angle_addr.append(ValueTerminal('<', 'angle-addr-start'))
  1425. value = value[1:]
  1426. # Although it is not legal per RFC5322, SMTP uses '<>' in certain
  1427. # circumstances.
  1428. if value and value[0] == '>':
  1429. angle_addr.append(ValueTerminal('>', 'angle-addr-end'))
  1430. angle_addr.defects.append(errors.InvalidHeaderDefect(
  1431. "null addr-spec in angle-addr"))
  1432. value = value[1:]
  1433. return angle_addr, value
  1434. try:
  1435. token, value = get_addr_spec(value)
  1436. except errors.HeaderParseError:
  1437. try:
  1438. token, value = get_obs_route(value)
  1439. angle_addr.defects.append(errors.ObsoleteHeaderDefect(
  1440. "obsolete route specification in angle-addr"))
  1441. except errors.HeaderParseError:
  1442. raise errors.HeaderParseError(
  1443. "expected addr-spec or obs-route but found '{}'".format(value))
  1444. angle_addr.append(token)
  1445. token, value = get_addr_spec(value)
  1446. angle_addr.append(token)
  1447. if value and value[0] == '>':
  1448. value = value[1:]
  1449. else:
  1450. angle_addr.defects.append(errors.InvalidHeaderDefect(
  1451. "missing trailing '>' on angle-addr"))
  1452. angle_addr.append(ValueTerminal('>', 'angle-addr-end'))
  1453. if value and value[0] in CFWS_LEADER:
  1454. token, value = get_cfws(value)
  1455. angle_addr.append(token)
  1456. return angle_addr, value
  1457. def get_display_name(value):
  1458. """ display-name = phrase
  1459. Because this is simply a name-rule, we don't return a display-name
  1460. token containing a phrase, but rather a display-name token with
  1461. the content of the phrase.
  1462. """
  1463. display_name = DisplayName()
  1464. token, value = get_phrase(value)
  1465. display_name.extend(token[:])
  1466. display_name.defects = token.defects[:]
  1467. return display_name, value
  1468. def get_name_addr(value):
  1469. """ name-addr = [display-name] angle-addr
  1470. """
  1471. name_addr = NameAddr()
  1472. # Both the optional display name and the angle-addr can start with cfws.
  1473. leader = None
  1474. if not value:
  1475. raise errors.HeaderParseError(
  1476. "expected name-addr but found '{}'".format(value))
  1477. if value[0] in CFWS_LEADER:
  1478. leader, value = get_cfws(value)
  1479. if not value:
  1480. raise errors.HeaderParseError(
  1481. "expected name-addr but found '{}'".format(leader))
  1482. if value[0] != '<':
  1483. if value[0] in PHRASE_ENDS:
  1484. raise errors.HeaderParseError(
  1485. "expected name-addr but found '{}'".format(value))
  1486. token, value = get_display_name(value)
  1487. if not value:
  1488. raise errors.HeaderParseError(
  1489. "expected name-addr but found '{}'".format(token))
  1490. if leader is not None:
  1491. if isinstance(token[0], TokenList):
  1492. token[0][:0] = [leader]
  1493. else:
  1494. token[:0] = [leader]
  1495. leader = None
  1496. name_addr.append(token)
  1497. token, value = get_angle_addr(value)
  1498. if leader is not None:
  1499. token[:0] = [leader]
  1500. name_addr.append(token)
  1501. return name_addr, value
  1502. def get_mailbox(value):
  1503. """ mailbox = name-addr / addr-spec
  1504. """
  1505. # The only way to figure out if we are dealing with a name-addr or an
  1506. # addr-spec is to try parsing each one.
  1507. mailbox = Mailbox()
  1508. try:
  1509. token, value = get_name_addr(value)
  1510. except errors.HeaderParseError:
  1511. try:
  1512. token, value = get_addr_spec(value)
  1513. except errors.HeaderParseError:
  1514. raise errors.HeaderParseError(
  1515. "expected mailbox but found '{}'".format(value))
  1516. if any(isinstance(x, errors.InvalidHeaderDefect)
  1517. for x in token.all_defects):
  1518. mailbox.token_type = 'invalid-mailbox'
  1519. mailbox.append(token)
  1520. return mailbox, value
  1521. def get_invalid_mailbox(value, endchars):
  1522. """ Read everything up to one of the chars in endchars.
  1523. This is outside the formal grammar. The InvalidMailbox TokenList that is
  1524. returned acts like a Mailbox, but the data attributes are None.
  1525. """
  1526. invalid_mailbox = InvalidMailbox()
  1527. while value and value[0] not in endchars:
  1528. if value[0] in PHRASE_ENDS:
  1529. invalid_mailbox.append(ValueTerminal(value[0],
  1530. 'misplaced-special'))
  1531. value = value[1:]
  1532. else:
  1533. token, value = get_phrase(value)
  1534. invalid_mailbox.append(token)
  1535. return invalid_mailbox, value
  1536. def get_mailbox_list(value):
  1537. """ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
  1538. obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
  1539. For this routine we go outside the formal grammar in order to improve error
  1540. handling. We recognize the end of the mailbox list only at the end of the
  1541. value or at a ';' (the group terminator). This is so that we can turn
  1542. invalid mailboxes into InvalidMailbox tokens and continue parsing any
  1543. remaining valid mailboxes. We also allow all mailbox entries to be null,
  1544. and this condition is handled appropriately at a higher level.
  1545. """
  1546. mailbox_list = MailboxList()
  1547. while value and value[0] != ';':
  1548. try:
  1549. token, value = get_mailbox(value)
  1550. mailbox_list.append(token)
  1551. except errors.HeaderParseError:
  1552. leader = None
  1553. if value[0] in CFWS_LEADER:
  1554. leader, value = get_cfws(value)
  1555. if not value or value[0] in ',;':
  1556. mailbox_list.append(leader)
  1557. mailbox_list.defects.append(errors.ObsoleteHeaderDefect(
  1558. "empty element in mailbox-list"))
  1559. else:
  1560. token, value = get_invalid_mailbox(value, ',;')
  1561. if leader is not None:
  1562. token[:0] = [leader]
  1563. mailbox_list.append(token)
  1564. mailbox_list.defects.append(errors.InvalidHeaderDefect(
  1565. "invalid mailbox in mailbox-list"))
  1566. elif value[0] == ',':
  1567. mailbox_list.defects.append(errors.ObsoleteHeaderDefect(
  1568. "empty element in mailbox-list"))
  1569. else:
  1570. token, value = get_invalid_mailbox(value, ',;')
  1571. if leader is not None:
  1572. token[:0] = [leader]
  1573. mailbox_list.append(token)
  1574. mailbox_list.defects.append(errors.InvalidHeaderDefect(
  1575. "invalid mailbox in mailbox-list"))
  1576. if value and value[0] not in ',;':
  1577. # Crap after mailbox; treat it as an invalid mailbox.
  1578. # The mailbox info will still be available.
  1579. mailbox = mailbox_list[-1]
  1580. mailbox.token_type = 'invalid-mailbox'
  1581. token, value = get_invalid_mailbox(value, ',;')
  1582. mailbox.extend(token)
  1583. mailbox_list.defects.append(errors.InvalidHeaderDefect(
  1584. "invalid mailbox in mailbox-list"))
  1585. if value and value[0] == ',':
  1586. mailbox_list.append(ListSeparator)
  1587. value = value[1:]
  1588. return mailbox_list, value
  1589. def get_group_list(value):
  1590. """ group-list = mailbox-list / CFWS / obs-group-list
  1591. obs-group-list = 1*([CFWS] ",") [CFWS]
  1592. """
  1593. group_list = GroupList()
  1594. if not value:
  1595. group_list.defects.append(errors.InvalidHeaderDefect(
  1596. "end of header before group-list"))
  1597. return group_list, value
  1598. leader = None
  1599. if value and value[0] in CFWS_LEADER:
  1600. leader, value = get_cfws(value)
  1601. if not value:
  1602. # This should never happen in email parsing, since CFWS-only is a
  1603. # legal alternative to group-list in a group, which is the only
  1604. # place group-list appears.
  1605. group_list.defects.append(errors.InvalidHeaderDefect(
  1606. "end of header in group-list"))
  1607. group_list.append(leader)
  1608. return group_list, value
  1609. if value[0] == ';':
  1610. group_list.append(leader)
  1611. return group_list, value
  1612. token, value = get_mailbox_list(value)
  1613. if len(token.all_mailboxes)==0:
  1614. if leader is not None:
  1615. group_list.append(leader)
  1616. group_list.extend(token)
  1617. group_list.defects.append(errors.ObsoleteHeaderDefect(
  1618. "group-list with empty entries"))
  1619. return group_list, value
  1620. if leader is not None:
  1621. token[:0] = [leader]
  1622. group_list.append(token)
  1623. return group_list, value
  1624. def get_group(value):
  1625. """ group = display-name ":" [group-list] ";" [CFWS]
  1626. """
  1627. group = Group()
  1628. token, value = get_display_name(value)
  1629. if not value or value[0] != ':':
  1630. raise errors.HeaderParseError("expected ':' at end of group "
  1631. "display name but found '{}'".format(value))
  1632. group.append(token)
  1633. group.append(ValueTerminal(':', 'group-display-name-terminator'))
  1634. value = value[1:]
  1635. if value and value[0] == ';':
  1636. group.append(ValueTerminal(';', 'group-terminator'))
  1637. return group, value[1:]
  1638. token, value = get_group_list(value)
  1639. group.append(token)
  1640. if not value:
  1641. group.defects.append(errors.InvalidHeaderDefect(
  1642. "end of header in group"))
  1643. elif value[0] != ';':
  1644. raise errors.HeaderParseError(
  1645. "expected ';' at end of group but found {}".format(value))
  1646. group.append(ValueTerminal(';', 'group-terminator'))
  1647. value = value[1:]
  1648. if value and value[0] in CFWS_LEADER:
  1649. token, value = get_cfws(value)
  1650. group.append(token)
  1651. return group, value
  1652. def get_address(value):
  1653. """ address = mailbox / group
  1654. Note that counter-intuitively, an address can be either a single address or
  1655. a list of addresses (a group). This is why the returned Address object has
  1656. a 'mailboxes' attribute which treats a single address as a list of length
  1657. one. When you need to differentiate between to two cases, extract the single
  1658. element, which is either a mailbox or a group token.
  1659. """
  1660. # The formal grammar isn't very helpful when parsing an address. mailbox
  1661. # and group, especially when allowing for obsolete forms, start off very
  1662. # similarly. It is only when you reach one of @, <, or : that you know
  1663. # what you've got. So, we try each one in turn, starting with the more
  1664. # likely of the two. We could perhaps make this more efficient by looking
  1665. # for a phrase and then branching based on the next character, but that
  1666. # would be a premature optimization.
  1667. address = Address()
  1668. try:
  1669. token, value = get_group(value)
  1670. except errors.HeaderParseError:
  1671. try:
  1672. token, value = get_mailbox(value)
  1673. except errors.HeaderParseError:
  1674. raise errors.HeaderParseError(
  1675. "expected address but found '{}'".format(value))
  1676. address.append(token)
  1677. return address, value
  1678. def get_address_list(value):
  1679. """ address_list = (address *("," address)) / obs-addr-list
  1680. obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])
  1681. We depart from the formal grammar here by continuing to parse until the end
  1682. of the input, assuming the input to be entirely composed of an
  1683. address-list. This is always true in email parsing, and allows us
  1684. to skip invalid addresses to parse additional valid ones.
  1685. """
  1686. address_list = AddressList()
  1687. while value:
  1688. try:
  1689. token, value = get_address(value)
  1690. address_list.append(token)
  1691. except errors.HeaderParseError:
  1692. leader = None
  1693. if value[0] in CFWS_LEADER:
  1694. leader, value = get_cfws(value)
  1695. if not value or value[0] == ',':
  1696. address_list.append(leader)
  1697. address_list.defects.append(errors.ObsoleteHeaderDefect(
  1698. "address-list entry with no content"))
  1699. else:
  1700. token, value = get_invalid_mailbox(value, ',')
  1701. if leader is not None:
  1702. token[:0] = [leader]
  1703. address_list.append(Address([token]))
  1704. address_list.defects.append(errors.InvalidHeaderDefect(
  1705. "invalid address in address-list"))
  1706. elif value[0] == ',':
  1707. address_list.defects.append(errors.ObsoleteHeaderDefect(
  1708. "empty element in address-list"))
  1709. else:
  1710. token, value = get_invalid_mailbox(value, ',')
  1711. if leader is not None:
  1712. token[:0] = [leader]
  1713. address_list.append(Address([token]))
  1714. address_list.defects.append(errors.InvalidHeaderDefect(
  1715. "invalid address in address-list"))
  1716. if value and value[0] != ',':
  1717. # Crap after address; treat it as an invalid mailbox.
  1718. # The mailbox info will still be available.
  1719. mailbox = address_list[-1][0]
  1720. mailbox.token_type = 'invalid-mailbox'
  1721. token, value = get_invalid_mailbox(value, ',')
  1722. mailbox.extend(token)
  1723. address_list.defects.append(errors.InvalidHeaderDefect(
  1724. "invalid address in address-list"))
  1725. if value: # Must be a , at this point.
  1726. address_list.append(ListSeparator)
  1727. value = value[1:]
  1728. return address_list, value
  1729. def get_no_fold_literal(value):
  1730. """ no-fold-literal = "[" *dtext "]"
  1731. """
  1732. no_fold_literal = NoFoldLiteral()
  1733. if not value:
  1734. raise errors.HeaderParseError(
  1735. "expected no-fold-literal but found '{}'".format(value))
  1736. if value[0] != '[':
  1737. raise errors.HeaderParseError(
  1738. "expected '[' at the start of no-fold-literal "
  1739. "but found '{}'".format(value))
  1740. no_fold_literal.append(ValueTerminal('[', 'no-fold-literal-start'))
  1741. value = value[1:]
  1742. token, value = get_dtext(value)
  1743. no_fold_literal.append(token)
  1744. if not value or value[0] != ']':
  1745. raise errors.HeaderParseError(
  1746. "expected ']' at the end of no-fold-literal "
  1747. "but found '{}'".format(value))
  1748. no_fold_literal.append(ValueTerminal(']', 'no-fold-literal-end'))
  1749. return no_fold_literal, value[1:]
  1750. def get_msg_id(value):
  1751. """msg-id = [CFWS] "<" id-left '@' id-right ">" [CFWS]
  1752. id-left = dot-atom-text / obs-id-left
  1753. id-right = dot-atom-text / no-fold-literal / obs-id-right
  1754. no-fold-literal = "[" *dtext "]"
  1755. """
  1756. msg_id = MsgID()
  1757. if value and value[0] in CFWS_LEADER:
  1758. token, value = get_cfws(value)
  1759. msg_id.append(token)
  1760. if not value or value[0] != '<':
  1761. raise errors.HeaderParseError(
  1762. "expected msg-id but found '{}'".format(value))
  1763. msg_id.append(ValueTerminal('<', 'msg-id-start'))
  1764. value = value[1:]
  1765. # Parse id-left.
  1766. try:
  1767. token, value = get_dot_atom_text(value)
  1768. except errors.HeaderParseError:
  1769. try:
  1770. # obs-id-left is same as local-part of add-spec.
  1771. token, value = get_obs_local_part(value)
  1772. msg_id.defects.append(errors.ObsoleteHeaderDefect(
  1773. "obsolete id-left in msg-id"))
  1774. except errors.HeaderParseError:
  1775. raise errors.HeaderParseError(
  1776. "expected dot-atom-text or obs-id-left"
  1777. " but found '{}'".format(value))
  1778. msg_id.append(token)
  1779. if not value or value[0] != '@':
  1780. msg_id.defects.append(errors.InvalidHeaderDefect(
  1781. "msg-id with no id-right"))
  1782. # Even though there is no id-right, if the local part
  1783. # ends with `>` let's just parse it too and return
  1784. # along with the defect.
  1785. if value and value[0] == '>':
  1786. msg_id.append(ValueTerminal('>', 'msg-id-end'))
  1787. value = value[1:]
  1788. return msg_id, value
  1789. msg_id.append(ValueTerminal('@', 'address-at-symbol'))
  1790. value = value[1:]
  1791. # Parse id-right.
  1792. try:
  1793. token, value = get_dot_atom_text(value)
  1794. except errors.HeaderParseError:
  1795. try:
  1796. token, value = get_no_fold_literal(value)
  1797. except errors.HeaderParseError:
  1798. try:
  1799. token, value = get_domain(value)
  1800. msg_id.defects.append(errors.ObsoleteHeaderDefect(
  1801. "obsolete id-right in msg-id"))
  1802. except errors.HeaderParseError:
  1803. raise errors.HeaderParseError(
  1804. "expected dot-atom-text, no-fold-literal or obs-id-right"
  1805. " but found '{}'".format(value))
  1806. msg_id.append(token)
  1807. if value and value[0] == '>':
  1808. value = value[1:]
  1809. else:
  1810. msg_id.defects.append(errors.InvalidHeaderDefect(
  1811. "missing trailing '>' on msg-id"))
  1812. msg_id.append(ValueTerminal('>', 'msg-id-end'))
  1813. if value and value[0] in CFWS_LEADER:
  1814. token, value = get_cfws(value)
  1815. msg_id.append(token)
  1816. return msg_id, value
  1817. def parse_message_id(value):
  1818. """message-id = "Message-ID:" msg-id CRLF
  1819. """
  1820. message_id = MessageID()
  1821. try:
  1822. token, value = get_msg_id(value)
  1823. message_id.append(token)
  1824. except errors.HeaderParseError as ex:
  1825. token = get_unstructured(value)
  1826. message_id = InvalidMessageID(token)
  1827. message_id.defects.append(
  1828. errors.InvalidHeaderDefect("Invalid msg-id: {!r}".format(ex)))
  1829. else:
  1830. # Value after parsing a valid msg_id should be None.
  1831. if value:
  1832. message_id.defects.append(errors.InvalidHeaderDefect(
  1833. "Unexpected {!r}".format(value)))
  1834. return message_id
  1835. #
  1836. # XXX: As I begin to add additional header parsers, I'm realizing we probably
  1837. # have two level of parser routines: the get_XXX methods that get a token in
  1838. # the grammar, and parse_XXX methods that parse an entire field value. So
  1839. # get_address_list above should really be a parse_ method, as probably should
  1840. # be get_unstructured.
  1841. #
  1842. def parse_mime_version(value):
  1843. """ mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS]
  1844. """
  1845. # The [CFWS] is implicit in the RFC 2045 BNF.
  1846. # XXX: This routine is a bit verbose, should factor out a get_int method.
  1847. mime_version = MIMEVersion()
  1848. if not value:
  1849. mime_version.defects.append(errors.HeaderMissingRequiredValue(
  1850. "Missing MIME version number (eg: 1.0)"))
  1851. return mime_version
  1852. if value[0] in CFWS_LEADER:
  1853. token, value = get_cfws(value)
  1854. mime_version.append(token)
  1855. if not value:
  1856. mime_version.defects.append(errors.HeaderMissingRequiredValue(
  1857. "Expected MIME version number but found only CFWS"))
  1858. digits = ''
  1859. while value and value[0] != '.' and value[0] not in CFWS_LEADER:
  1860. digits += value[0]
  1861. value = value[1:]
  1862. if not digits.isdigit():
  1863. mime_version.defects.append(errors.InvalidHeaderDefect(
  1864. "Expected MIME major version number but found {!r}".format(digits)))
  1865. mime_version.append(ValueTerminal(digits, 'xtext'))
  1866. else:
  1867. mime_version.major = int(digits)
  1868. mime_version.append(ValueTerminal(digits, 'digits'))
  1869. if value and value[0] in CFWS_LEADER:
  1870. token, value = get_cfws(value)
  1871. mime_version.append(token)
  1872. if not value or value[0] != '.':
  1873. if mime_version.major is not None:
  1874. mime_version.defects.append(errors.InvalidHeaderDefect(
  1875. "Incomplete MIME version; found only major number"))
  1876. if value:
  1877. mime_version.append(ValueTerminal(value, 'xtext'))
  1878. return mime_version
  1879. mime_version.append(ValueTerminal('.', 'version-separator'))
  1880. value = value[1:]
  1881. if value and value[0] in CFWS_LEADER:
  1882. token, value = get_cfws(value)
  1883. mime_version.append(token)
  1884. if not value:
  1885. if mime_version.major is not None:
  1886. mime_version.defects.append(errors.InvalidHeaderDefect(
  1887. "Incomplete MIME version; found only major number"))
  1888. return mime_version
  1889. digits = ''
  1890. while value and value[0] not in CFWS_LEADER:
  1891. digits += value[0]
  1892. value = value[1:]
  1893. if not digits.isdigit():
  1894. mime_version.defects.append(errors.InvalidHeaderDefect(
  1895. "Expected MIME minor version number but found {!r}".format(digits)))
  1896. mime_version.append(ValueTerminal(digits, 'xtext'))
  1897. else:
  1898. mime_version.minor = int(digits)
  1899. mime_version.append(ValueTerminal(digits, 'digits'))
  1900. if value and value[0] in CFWS_LEADER:
  1901. token, value = get_cfws(value)
  1902. mime_version.append(token)
  1903. if value:
  1904. mime_version.defects.append(errors.InvalidHeaderDefect(
  1905. "Excess non-CFWS text after MIME version"))
  1906. mime_version.append(ValueTerminal(value, 'xtext'))
  1907. return mime_version
  1908. def get_invalid_parameter(value):
  1909. """ Read everything up to the next ';'.
  1910. This is outside the formal grammar. The InvalidParameter TokenList that is
  1911. returned acts like a Parameter, but the data attributes are None.
  1912. """
  1913. invalid_parameter = InvalidParameter()
  1914. while value and value[0] != ';':
  1915. if value[0] in PHRASE_ENDS:
  1916. invalid_parameter.append(ValueTerminal(value[0],
  1917. 'misplaced-special'))
  1918. value = value[1:]
  1919. else:
  1920. token, value = get_phrase(value)
  1921. invalid_parameter.append(token)
  1922. return invalid_parameter, value
  1923. def get_ttext(value):
  1924. """ttext = <matches _ttext_matcher>
  1925. We allow any non-TOKEN_ENDS in ttext, but add defects to the token's
  1926. defects list if we find non-ttext characters. We also register defects for
  1927. *any* non-printables even though the RFC doesn't exclude all of them,
  1928. because we follow the spirit of RFC 5322.
  1929. """
  1930. m = _non_token_end_matcher(value)
  1931. if not m:
  1932. raise errors.HeaderParseError(
  1933. "expected ttext but found '{}'".format(value))
  1934. ttext = m.group()
  1935. value = value[len(ttext):]
  1936. ttext = ValueTerminal(ttext, 'ttext')
  1937. _validate_xtext(ttext)
  1938. return ttext, value
  1939. def get_token(value):
  1940. """token = [CFWS] 1*ttext [CFWS]
  1941. The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or
  1942. tspecials. We also exclude tabs even though the RFC doesn't.
  1943. The RFC implies the CFWS but is not explicit about it in the BNF.
  1944. """
  1945. mtoken = Token()
  1946. if value and value[0] in CFWS_LEADER:
  1947. token, value = get_cfws(value)
  1948. mtoken.append(token)
  1949. if value and value[0] in TOKEN_ENDS:
  1950. raise errors.HeaderParseError(
  1951. "expected token but found '{}'".format(value))
  1952. token, value = get_ttext(value)
  1953. mtoken.append(token)
  1954. if value and value[0] in CFWS_LEADER:
  1955. token, value = get_cfws(value)
  1956. mtoken.append(token)
  1957. return mtoken, value
  1958. def get_attrtext(value):
  1959. """attrtext = 1*(any non-ATTRIBUTE_ENDS character)
  1960. We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the
  1961. token's defects list if we find non-attrtext characters. We also register
  1962. defects for *any* non-printables even though the RFC doesn't exclude all of
  1963. them, because we follow the spirit of RFC 5322.
  1964. """
  1965. m = _non_attribute_end_matcher(value)
  1966. if not m:
  1967. raise errors.HeaderParseError(
  1968. "expected attrtext but found {!r}".format(value))
  1969. attrtext = m.group()
  1970. value = value[len(attrtext):]
  1971. attrtext = ValueTerminal(attrtext, 'attrtext')
  1972. _validate_xtext(attrtext)
  1973. return attrtext, value
  1974. def get_attribute(value):
  1975. """ [CFWS] 1*attrtext [CFWS]
  1976. This version of the BNF makes the CFWS explicit, and as usual we use a
  1977. value terminal for the actual run of characters. The RFC equivalent of
  1978. attrtext is the token characters, with the subtraction of '*', "'", and '%'.
  1979. We include tab in the excluded set just as we do for token.
  1980. """
  1981. attribute = Attribute()
  1982. if value and value[0] in CFWS_LEADER:
  1983. token, value = get_cfws(value)
  1984. attribute.append(token)
  1985. if value and value[0] in ATTRIBUTE_ENDS:
  1986. raise errors.HeaderParseError(
  1987. "expected token but found '{}'".format(value))
  1988. token, value = get_attrtext(value)
  1989. attribute.append(token)
  1990. if value and value[0] in CFWS_LEADER:
  1991. token, value = get_cfws(value)
  1992. attribute.append(token)
  1993. return attribute, value
  1994. def get_extended_attrtext(value):
  1995. """attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%')
  1996. This is a special parsing routine so that we get a value that
  1997. includes % escapes as a single string (which we decode as a single
  1998. string later).
  1999. """
  2000. m = _non_extended_attribute_end_matcher(value)
  2001. if not m:
  2002. raise errors.HeaderParseError(
  2003. "expected extended attrtext but found {!r}".format(value))
  2004. attrtext = m.group()
  2005. value = value[len(attrtext):]
  2006. attrtext = ValueTerminal(attrtext, 'extended-attrtext')
  2007. _validate_xtext(attrtext)
  2008. return attrtext, value
  2009. def get_extended_attribute(value):
  2010. """ [CFWS] 1*extended_attrtext [CFWS]
  2011. This is like the non-extended version except we allow % characters, so that
  2012. we can pick up an encoded value as a single string.
  2013. """
  2014. # XXX: should we have an ExtendedAttribute TokenList?
  2015. attribute = Attribute()
  2016. if value and value[0] in CFWS_LEADER:
  2017. token, value = get_cfws(value)
  2018. attribute.append(token)
  2019. if value and value[0] in EXTENDED_ATTRIBUTE_ENDS:
  2020. raise errors.HeaderParseError(
  2021. "expected token but found '{}'".format(value))
  2022. token, value = get_extended_attrtext(value)
  2023. attribute.append(token)
  2024. if value and value[0] in CFWS_LEADER:
  2025. token, value = get_cfws(value)
  2026. attribute.append(token)
  2027. return attribute, value
  2028. def get_section(value):
  2029. """ '*' digits
  2030. The formal BNF is more complicated because leading 0s are not allowed. We
  2031. check for that and add a defect. We also assume no CFWS is allowed between
  2032. the '*' and the digits, though the RFC is not crystal clear on that.
  2033. The caller should already have dealt with leading CFWS.
  2034. """
  2035. section = Section()
  2036. if not value or value[0] != '*':
  2037. raise errors.HeaderParseError("Expected section but found {}".format(
  2038. value))
  2039. section.append(ValueTerminal('*', 'section-marker'))
  2040. value = value[1:]
  2041. if not value or not value[0].isdigit():
  2042. raise errors.HeaderParseError("Expected section number but "
  2043. "found {}".format(value))
  2044. digits = ''
  2045. while value and value[0].isdigit():
  2046. digits += value[0]
  2047. value = value[1:]
  2048. if digits[0] == '0' and digits != '0':
  2049. section.defects.append(errors.InvalidHeaderDefect(
  2050. "section number has an invalid leading 0"))
  2051. section.number = int(digits)
  2052. section.append(ValueTerminal(digits, 'digits'))
  2053. return section, value
  2054. def get_value(value):
  2055. """ quoted-string / attribute
  2056. """
  2057. v = Value()
  2058. if not value:
  2059. raise errors.HeaderParseError("Expected value but found end of string")
  2060. leader = None
  2061. if value[0] in CFWS_LEADER:
  2062. leader, value = get_cfws(value)
  2063. if not value:
  2064. raise errors.HeaderParseError("Expected value but found "
  2065. "only {}".format(leader))
  2066. if value[0] == '"':
  2067. token, value = get_quoted_string(value)
  2068. else:
  2069. token, value = get_extended_attribute(value)
  2070. if leader is not None:
  2071. token[:0] = [leader]
  2072. v.append(token)
  2073. return v, value
  2074. def get_parameter(value):
  2075. """ attribute [section] ["*"] [CFWS] "=" value
  2076. The CFWS is implied by the RFC but not made explicit in the BNF. This
  2077. simplified form of the BNF from the RFC is made to conform with the RFC BNF
  2078. through some extra checks. We do it this way because it makes both error
  2079. recovery and working with the resulting parse tree easier.
  2080. """
  2081. # It is possible CFWS would also be implicitly allowed between the section
  2082. # and the 'extended-attribute' marker (the '*') , but we've never seen that
  2083. # in the wild and we will therefore ignore the possibility.
  2084. param = Parameter()
  2085. token, value = get_attribute(value)
  2086. param.append(token)
  2087. if not value or value[0] == ';':
  2088. param.defects.append(errors.InvalidHeaderDefect("Parameter contains "
  2089. "name ({}) but no value".format(token)))
  2090. return param, value
  2091. if value[0] == '*':
  2092. try:
  2093. token, value = get_section(value)
  2094. param.sectioned = True
  2095. param.append(token)
  2096. except errors.HeaderParseError:
  2097. pass
  2098. if not value:
  2099. raise errors.HeaderParseError("Incomplete parameter")
  2100. if value[0] == '*':
  2101. param.append(ValueTerminal('*', 'extended-parameter-marker'))
  2102. value = value[1:]
  2103. param.extended = True
  2104. if value[0] != '=':
  2105. raise errors.HeaderParseError("Parameter not followed by '='")
  2106. param.append(ValueTerminal('=', 'parameter-separator'))
  2107. value = value[1:]
  2108. if value and value[0] in CFWS_LEADER:
  2109. token, value = get_cfws(value)
  2110. param.append(token)
  2111. remainder = None
  2112. appendto = param
  2113. if param.extended and value and value[0] == '"':
  2114. # Now for some serious hackery to handle the common invalid case of
  2115. # double quotes around an extended value. We also accept (with defect)
  2116. # a value marked as encoded that isn't really.
  2117. qstring, remainder = get_quoted_string(value)
  2118. inner_value = qstring.stripped_value
  2119. semi_valid = False
  2120. if param.section_number == 0:
  2121. if inner_value and inner_value[0] == "'":
  2122. semi_valid = True
  2123. else:
  2124. token, rest = get_attrtext(inner_value)
  2125. if rest and rest[0] == "'":
  2126. semi_valid = True
  2127. else:
  2128. try:
  2129. token, rest = get_extended_attrtext(inner_value)
  2130. except:
  2131. pass
  2132. else:
  2133. if not rest:
  2134. semi_valid = True
  2135. if semi_valid:
  2136. param.defects.append(errors.InvalidHeaderDefect(
  2137. "Quoted string value for extended parameter is invalid"))
  2138. param.append(qstring)
  2139. for t in qstring:
  2140. if t.token_type == 'bare-quoted-string':
  2141. t[:] = []
  2142. appendto = t
  2143. break
  2144. value = inner_value
  2145. else:
  2146. remainder = None
  2147. param.defects.append(errors.InvalidHeaderDefect(
  2148. "Parameter marked as extended but appears to have a "
  2149. "quoted string value that is non-encoded"))
  2150. if value and value[0] == "'":
  2151. token = None
  2152. else:
  2153. token, value = get_value(value)
  2154. if not param.extended or param.section_number > 0:
  2155. if not value or value[0] != "'":
  2156. appendto.append(token)
  2157. if remainder is not None:
  2158. assert not value, value
  2159. value = remainder
  2160. return param, value
  2161. param.defects.append(errors.InvalidHeaderDefect(
  2162. "Apparent initial-extended-value but attribute "
  2163. "was not marked as extended or was not initial section"))
  2164. if not value:
  2165. # Assume the charset/lang is missing and the token is the value.
  2166. param.defects.append(errors.InvalidHeaderDefect(
  2167. "Missing required charset/lang delimiters"))
  2168. appendto.append(token)
  2169. if remainder is None:
  2170. return param, value
  2171. else:
  2172. if token is not None:
  2173. for t in token:
  2174. if t.token_type == 'extended-attrtext':
  2175. break
  2176. t.token_type == 'attrtext'
  2177. appendto.append(t)
  2178. param.charset = t.value
  2179. if value[0] != "'":
  2180. raise errors.HeaderParseError("Expected RFC2231 char/lang encoding "
  2181. "delimiter, but found {!r}".format(value))
  2182. appendto.append(ValueTerminal("'", 'RFC2231-delimiter'))
  2183. value = value[1:]
  2184. if value and value[0] != "'":
  2185. token, value = get_attrtext(value)
  2186. appendto.append(token)
  2187. param.lang = token.value
  2188. if not value or value[0] != "'":
  2189. raise errors.HeaderParseError("Expected RFC2231 char/lang encoding "
  2190. "delimiter, but found {}".format(value))
  2191. appendto.append(ValueTerminal("'", 'RFC2231-delimiter'))
  2192. value = value[1:]
  2193. if remainder is not None:
  2194. # Treat the rest of value as bare quoted string content.
  2195. v = Value()
  2196. while value:
  2197. if value[0] in WSP:
  2198. token, value = get_fws(value)
  2199. elif value[0] == '"':
  2200. token = ValueTerminal('"', 'DQUOTE')
  2201. value = value[1:]
  2202. else:
  2203. token, value = get_qcontent(value)
  2204. v.append(token)
  2205. token = v
  2206. else:
  2207. token, value = get_value(value)
  2208. appendto.append(token)
  2209. if remainder is not None:
  2210. assert not value, value
  2211. value = remainder
  2212. return param, value
  2213. def parse_mime_parameters(value):
  2214. """ parameter *( ";" parameter )
  2215. That BNF is meant to indicate this routine should only be called after
  2216. finding and handling the leading ';'. There is no corresponding rule in
  2217. the formal RFC grammar, but it is more convenient for us for the set of
  2218. parameters to be treated as its own TokenList.
  2219. This is 'parse' routine because it consumes the remaining value, but it
  2220. would never be called to parse a full header. Instead it is called to
  2221. parse everything after the non-parameter value of a specific MIME header.
  2222. """
  2223. mime_parameters = MimeParameters()
  2224. while value:
  2225. try:
  2226. token, value = get_parameter(value)
  2227. mime_parameters.append(token)
  2228. except errors.HeaderParseError:
  2229. leader = None
  2230. if value[0] in CFWS_LEADER:
  2231. leader, value = get_cfws(value)
  2232. if not value:
  2233. mime_parameters.append(leader)
  2234. return mime_parameters
  2235. if value[0] == ';':
  2236. if leader is not None:
  2237. mime_parameters.append(leader)
  2238. mime_parameters.defects.append(errors.InvalidHeaderDefect(
  2239. "parameter entry with no content"))
  2240. else:
  2241. token, value = get_invalid_parameter(value)
  2242. if leader:
  2243. token[:0] = [leader]
  2244. mime_parameters.append(token)
  2245. mime_parameters.defects.append(errors.InvalidHeaderDefect(
  2246. "invalid parameter {!r}".format(token)))
  2247. if value and value[0] != ';':
  2248. # Junk after the otherwise valid parameter. Mark it as
  2249. # invalid, but it will have a value.
  2250. param = mime_parameters[-1]
  2251. param.token_type = 'invalid-parameter'
  2252. token, value = get_invalid_parameter(value)
  2253. param.extend(token)
  2254. mime_parameters.defects.append(errors.InvalidHeaderDefect(
  2255. "parameter with invalid trailing text {!r}".format(token)))
  2256. if value:
  2257. # Must be a ';' at this point.
  2258. mime_parameters.append(ValueTerminal(';', 'parameter-separator'))
  2259. value = value[1:]
  2260. return mime_parameters
  2261. def _find_mime_parameters(tokenlist, value):
  2262. """Do our best to find the parameters in an invalid MIME header
  2263. """
  2264. while value and value[0] != ';':
  2265. if value[0] in PHRASE_ENDS:
  2266. tokenlist.append(ValueTerminal(value[0], 'misplaced-special'))
  2267. value = value[1:]
  2268. else:
  2269. token, value = get_phrase(value)
  2270. tokenlist.append(token)
  2271. if not value:
  2272. return
  2273. tokenlist.append(ValueTerminal(';', 'parameter-separator'))
  2274. tokenlist.append(parse_mime_parameters(value[1:]))
  2275. def parse_content_type_header(value):
  2276. """ maintype "/" subtype *( ";" parameter )
  2277. The maintype and substype are tokens. Theoretically they could
  2278. be checked against the official IANA list + x-token, but we
  2279. don't do that.
  2280. """
  2281. ctype = ContentType()
  2282. if not value:
  2283. ctype.defects.append(errors.HeaderMissingRequiredValue(
  2284. "Missing content type specification"))
  2285. return ctype
  2286. try:
  2287. token, value = get_token(value)
  2288. except errors.HeaderParseError:
  2289. ctype.defects.append(errors.InvalidHeaderDefect(
  2290. "Expected content maintype but found {!r}".format(value)))
  2291. _find_mime_parameters(ctype, value)
  2292. return ctype
  2293. ctype.append(token)
  2294. # XXX: If we really want to follow the formal grammar we should make
  2295. # mantype and subtype specialized TokenLists here. Probably not worth it.
  2296. if not value or value[0] != '/':
  2297. ctype.defects.append(errors.InvalidHeaderDefect(
  2298. "Invalid content type"))
  2299. if value:
  2300. _find_mime_parameters(ctype, value)
  2301. return ctype
  2302. ctype.maintype = token.value.strip().lower()
  2303. ctype.append(ValueTerminal('/', 'content-type-separator'))
  2304. value = value[1:]
  2305. try:
  2306. token, value = get_token(value)
  2307. except errors.HeaderParseError:
  2308. ctype.defects.append(errors.InvalidHeaderDefect(
  2309. "Expected content subtype but found {!r}".format(value)))
  2310. _find_mime_parameters(ctype, value)
  2311. return ctype
  2312. ctype.append(token)
  2313. ctype.subtype = token.value.strip().lower()
  2314. if not value:
  2315. return ctype
  2316. if value[0] != ';':
  2317. ctype.defects.append(errors.InvalidHeaderDefect(
  2318. "Only parameters are valid after content type, but "
  2319. "found {!r}".format(value)))
  2320. # The RFC requires that a syntactically invalid content-type be treated
  2321. # as text/plain. Perhaps we should postel this, but we should probably
  2322. # only do that if we were checking the subtype value against IANA.
  2323. del ctype.maintype, ctype.subtype
  2324. _find_mime_parameters(ctype, value)
  2325. return ctype
  2326. ctype.append(ValueTerminal(';', 'parameter-separator'))
  2327. ctype.append(parse_mime_parameters(value[1:]))
  2328. return ctype
  2329. def parse_content_disposition_header(value):
  2330. """ disposition-type *( ";" parameter )
  2331. """
  2332. disp_header = ContentDisposition()
  2333. if not value:
  2334. disp_header.defects.append(errors.HeaderMissingRequiredValue(
  2335. "Missing content disposition"))
  2336. return disp_header
  2337. try:
  2338. token, value = get_token(value)
  2339. except errors.HeaderParseError:
  2340. disp_header.defects.append(errors.InvalidHeaderDefect(
  2341. "Expected content disposition but found {!r}".format(value)))
  2342. _find_mime_parameters(disp_header, value)
  2343. return disp_header
  2344. disp_header.append(token)
  2345. disp_header.content_disposition = token.value.strip().lower()
  2346. if not value:
  2347. return disp_header
  2348. if value[0] != ';':
  2349. disp_header.defects.append(errors.InvalidHeaderDefect(
  2350. "Only parameters are valid after content disposition, but "
  2351. "found {!r}".format(value)))
  2352. _find_mime_parameters(disp_header, value)
  2353. return disp_header
  2354. disp_header.append(ValueTerminal(';', 'parameter-separator'))
  2355. disp_header.append(parse_mime_parameters(value[1:]))
  2356. return disp_header
  2357. def parse_content_transfer_encoding_header(value):
  2358. """ mechanism
  2359. """
  2360. # We should probably validate the values, since the list is fixed.
  2361. cte_header = ContentTransferEncoding()
  2362. if not value:
  2363. cte_header.defects.append(errors.HeaderMissingRequiredValue(
  2364. "Missing content transfer encoding"))
  2365. return cte_header
  2366. try:
  2367. token, value = get_token(value)
  2368. except errors.HeaderParseError:
  2369. cte_header.defects.append(errors.InvalidHeaderDefect(
  2370. "Expected content transfer encoding but found {!r}".format(value)))
  2371. else:
  2372. cte_header.append(token)
  2373. cte_header.cte = token.value.strip().lower()
  2374. if not value:
  2375. return cte_header
  2376. while value:
  2377. cte_header.defects.append(errors.InvalidHeaderDefect(
  2378. "Extra text after content transfer encoding"))
  2379. if value[0] in PHRASE_ENDS:
  2380. cte_header.append(ValueTerminal(value[0], 'misplaced-special'))
  2381. value = value[1:]
  2382. else:
  2383. token, value = get_phrase(value)
  2384. cte_header.append(token)
  2385. return cte_header
  2386. #
  2387. # Header folding
  2388. #
  2389. # Header folding is complex, with lots of rules and corner cases. The
  2390. # following code does its best to obey the rules and handle the corner
  2391. # cases, but you can be sure there are few bugs:)
  2392. #
  2393. # This folder generally canonicalizes as it goes, preferring the stringified
  2394. # version of each token. The tokens contain information that supports the
  2395. # folder, including which tokens can be encoded in which ways.
  2396. #
  2397. # Folded text is accumulated in a simple list of strings ('lines'), each
  2398. # one of which should be less than policy.max_line_length ('maxlen').
  2399. #
  2400. def _steal_trailing_WSP_if_exists(lines):
  2401. wsp = ''
  2402. if lines and lines[-1] and lines[-1][-1] in WSP:
  2403. wsp = lines[-1][-1]
  2404. lines[-1] = lines[-1][:-1]
  2405. return wsp
  2406. def _refold_parse_tree(parse_tree, *, policy):
  2407. """Return string of contents of parse_tree folded according to RFC rules.
  2408. """
  2409. # max_line_length 0/None means no limit, ie: infinitely long.
  2410. maxlen = policy.max_line_length or sys.maxsize
  2411. encoding = 'utf-8' if policy.utf8 else 'us-ascii'
  2412. lines = [''] # Folded lines to be output
  2413. leading_whitespace = '' # When we have whitespace between two encoded
  2414. # words, we may need to encode the whitespace
  2415. # at the beginning of the second word.
  2416. last_ew = None # Points to the last encoded character if there's an ew on
  2417. # the line
  2418. last_charset = None
  2419. wrap_as_ew_blocked = 0
  2420. want_encoding = False # This is set to True if we need to encode this part
  2421. end_ew_not_allowed = Terminal('', 'wrap_as_ew_blocked')
  2422. parts = list(parse_tree)
  2423. while parts:
  2424. part = parts.pop(0)
  2425. if part is end_ew_not_allowed:
  2426. wrap_as_ew_blocked -= 1
  2427. continue
  2428. tstr = str(part)
  2429. if not want_encoding:
  2430. if part.token_type == 'ptext':
  2431. # Encode if tstr contains special characters.
  2432. want_encoding = not SPECIALSNL.isdisjoint(tstr)
  2433. else:
  2434. # Encode if tstr contains newlines.
  2435. want_encoding = not NLSET.isdisjoint(tstr)
  2436. try:
  2437. tstr.encode(encoding)
  2438. charset = encoding
  2439. except UnicodeEncodeError:
  2440. if any(isinstance(x, errors.UndecodableBytesDefect)
  2441. for x in part.all_defects):
  2442. charset = 'unknown-8bit'
  2443. else:
  2444. # If policy.utf8 is false this should really be taken from a
  2445. # 'charset' property on the policy.
  2446. charset = 'utf-8'
  2447. want_encoding = True
  2448. if part.token_type == 'mime-parameters':
  2449. # Mime parameter folding (using RFC2231) is extra special.
  2450. _fold_mime_parameters(part, lines, maxlen, encoding)
  2451. continue
  2452. if want_encoding and not wrap_as_ew_blocked:
  2453. if not part.as_ew_allowed:
  2454. want_encoding = False
  2455. last_ew = None
  2456. if part.syntactic_break:
  2457. encoded_part = part.fold(policy=policy)[:-len(policy.linesep)]
  2458. if policy.linesep not in encoded_part:
  2459. # It fits on a single line
  2460. if len(encoded_part) > maxlen - len(lines[-1]):
  2461. # But not on this one, so start a new one.
  2462. newline = _steal_trailing_WSP_if_exists(lines)
  2463. # XXX what if encoded_part has no leading FWS?
  2464. lines.append(newline)
  2465. lines[-1] += encoded_part
  2466. continue
  2467. # Either this is not a major syntactic break, so we don't
  2468. # want it on a line by itself even if it fits, or it
  2469. # doesn't fit on a line by itself. Either way, fall through
  2470. # to unpacking the subparts and wrapping them.
  2471. if not hasattr(part, 'encode'):
  2472. # It's not a Terminal, do each piece individually.
  2473. parts = list(part) + parts
  2474. want_encoding = False
  2475. continue
  2476. elif part.as_ew_allowed:
  2477. # It's a terminal, wrap it as an encoded word, possibly
  2478. # combining it with previously encoded words if allowed.
  2479. if (last_ew is not None and
  2480. charset != last_charset and
  2481. (last_charset == 'unknown-8bit' or
  2482. last_charset == 'utf-8' and charset != 'us-ascii')):
  2483. last_ew = None
  2484. last_ew = _fold_as_ew(tstr, lines, maxlen, last_ew,
  2485. part.ew_combine_allowed, charset, leading_whitespace)
  2486. # This whitespace has been added to the lines in _fold_as_ew()
  2487. # so clear it now.
  2488. leading_whitespace = ''
  2489. last_charset = charset
  2490. want_encoding = False
  2491. continue
  2492. else:
  2493. # It's a terminal which should be kept non-encoded
  2494. # (e.g. a ListSeparator).
  2495. last_ew = None
  2496. want_encoding = False
  2497. # fall through
  2498. if len(tstr) <= maxlen - len(lines[-1]):
  2499. lines[-1] += tstr
  2500. continue
  2501. # This part is too long to fit. The RFC wants us to break at
  2502. # "major syntactic breaks", so unless we don't consider this
  2503. # to be one, check if it will fit on the next line by itself.
  2504. leading_whitespace = ''
  2505. if (part.syntactic_break and
  2506. len(tstr) + 1 <= maxlen):
  2507. newline = _steal_trailing_WSP_if_exists(lines)
  2508. if newline or part.startswith_fws():
  2509. # We're going to fold the data onto a new line here. Due to
  2510. # the way encoded strings handle continuation lines, we need to
  2511. # be prepared to encode any whitespace if the next line turns
  2512. # out to start with an encoded word.
  2513. lines.append(newline + tstr)
  2514. whitespace_accumulator = []
  2515. for char in lines[-1]:
  2516. if char not in WSP:
  2517. break
  2518. whitespace_accumulator.append(char)
  2519. leading_whitespace = ''.join(whitespace_accumulator)
  2520. last_ew = None
  2521. continue
  2522. if not hasattr(part, 'encode'):
  2523. # It's not a terminal, try folding the subparts.
  2524. newparts = list(part)
  2525. if part.token_type == 'bare-quoted-string':
  2526. # To fold a quoted string we need to create a list of terminal
  2527. # tokens that will render the leading and trailing quotes
  2528. # and use quoted pairs in the value as appropriate.
  2529. newparts = (
  2530. [ValueTerminal('"', 'ptext')] +
  2531. [ValueTerminal(make_quoted_pairs(p), 'ptext')
  2532. for p in newparts] +
  2533. [ValueTerminal('"', 'ptext')])
  2534. if not part.as_ew_allowed:
  2535. wrap_as_ew_blocked += 1
  2536. newparts.append(end_ew_not_allowed)
  2537. parts = newparts + parts
  2538. continue
  2539. if part.as_ew_allowed and not wrap_as_ew_blocked:
  2540. # It doesn't need CTE encoding, but encode it anyway so we can
  2541. # wrap it.
  2542. parts.insert(0, part)
  2543. want_encoding = True
  2544. continue
  2545. # We can't figure out how to wrap, it, so give up.
  2546. newline = _steal_trailing_WSP_if_exists(lines)
  2547. if newline or part.startswith_fws():
  2548. lines.append(newline + tstr)
  2549. else:
  2550. # We can't fold it onto the next line either...
  2551. lines[-1] += tstr
  2552. return policy.linesep.join(lines) + policy.linesep
  2553. def _fold_as_ew(to_encode, lines, maxlen, last_ew, ew_combine_allowed, charset, leading_whitespace):
  2554. """Fold string to_encode into lines as encoded word, combining if allowed.
  2555. Return the new value for last_ew, or None if ew_combine_allowed is False.
  2556. If there is already an encoded word in the last line of lines (indicated by
  2557. a non-None value for last_ew) and ew_combine_allowed is true, decode the
  2558. existing ew, combine it with to_encode, and re-encode. Otherwise, encode
  2559. to_encode. In either case, split to_encode as necessary so that the
  2560. encoded segments fit within maxlen.
  2561. """
  2562. if last_ew is not None and ew_combine_allowed:
  2563. to_encode = str(
  2564. get_unstructured(lines[-1][last_ew:] + to_encode))
  2565. lines[-1] = lines[-1][:last_ew]
  2566. elif to_encode[0] in WSP:
  2567. # We're joining this to non-encoded text, so don't encode
  2568. # the leading blank.
  2569. leading_wsp = to_encode[0]
  2570. to_encode = to_encode[1:]
  2571. if (len(lines[-1]) == maxlen):
  2572. lines.append(_steal_trailing_WSP_if_exists(lines))
  2573. lines[-1] += leading_wsp
  2574. trailing_wsp = ''
  2575. if to_encode[-1] in WSP:
  2576. # Likewise for the trailing space.
  2577. trailing_wsp = to_encode[-1]
  2578. to_encode = to_encode[:-1]
  2579. new_last_ew = len(lines[-1]) if last_ew is None else last_ew
  2580. encode_as = 'utf-8' if charset == 'us-ascii' else charset
  2581. # The RFC2047 chrome takes up 7 characters plus the length
  2582. # of the charset name.
  2583. chrome_len = len(encode_as) + 7
  2584. if (chrome_len + 1) >= maxlen:
  2585. raise errors.HeaderParseError(
  2586. "max_line_length is too small to fit an encoded word")
  2587. while to_encode:
  2588. remaining_space = maxlen - len(lines[-1])
  2589. text_space = remaining_space - chrome_len - len(leading_whitespace)
  2590. if text_space <= 0:
  2591. lines.append(' ')
  2592. continue
  2593. # If we are at the start of a continuation line, prepend whitespace
  2594. # (we only want to do this when the line starts with an encoded word
  2595. # but if we're folding in this helper function, then we know that we
  2596. # are going to be writing out an encoded word.)
  2597. if len(lines) > 1 and len(lines[-1]) == 1 and leading_whitespace:
  2598. encoded_word = _ew.encode(leading_whitespace, charset=encode_as)
  2599. lines[-1] += encoded_word
  2600. leading_whitespace = ''
  2601. to_encode_word = to_encode[:text_space]
  2602. encoded_word = _ew.encode(to_encode_word, charset=encode_as)
  2603. excess = len(encoded_word) - remaining_space
  2604. while excess > 0:
  2605. # Since the chunk to encode is guaranteed to fit into less than 100 characters,
  2606. # shrinking it by one at a time shouldn't take long.
  2607. to_encode_word = to_encode_word[:-1]
  2608. encoded_word = _ew.encode(to_encode_word, charset=encode_as)
  2609. excess = len(encoded_word) - remaining_space
  2610. lines[-1] += encoded_word
  2611. to_encode = to_encode[len(to_encode_word):]
  2612. leading_whitespace = ''
  2613. if to_encode:
  2614. lines.append(' ')
  2615. new_last_ew = len(lines[-1])
  2616. lines[-1] += trailing_wsp
  2617. return new_last_ew if ew_combine_allowed else None
  2618. def _fold_mime_parameters(part, lines, maxlen, encoding):
  2619. """Fold TokenList 'part' into the 'lines' list as mime parameters.
  2620. Using the decoded list of parameters and values, format them according to
  2621. the RFC rules, including using RFC2231 encoding if the value cannot be
  2622. expressed in 'encoding' and/or the parameter+value is too long to fit
  2623. within 'maxlen'.
  2624. """
  2625. # Special case for RFC2231 encoding: start from decoded values and use
  2626. # RFC2231 encoding iff needed.
  2627. #
  2628. # Note that the 1 and 2s being added to the length calculations are
  2629. # accounting for the possibly-needed spaces and semicolons we'll be adding.
  2630. #
  2631. for name, value in part.params:
  2632. # XXX What if this ';' puts us over maxlen the first time through the
  2633. # loop? We should split the header value onto a newline in that case,
  2634. # but to do that we need to recognize the need earlier or reparse the
  2635. # header, so I'm going to ignore that bug for now. It'll only put us
  2636. # one character over.
  2637. if not lines[-1].rstrip().endswith(';'):
  2638. lines[-1] += ';'
  2639. charset = encoding
  2640. error_handler = 'strict'
  2641. try:
  2642. value.encode(encoding)
  2643. encoding_required = False
  2644. except UnicodeEncodeError:
  2645. encoding_required = True
  2646. if utils._has_surrogates(value):
  2647. charset = 'unknown-8bit'
  2648. error_handler = 'surrogateescape'
  2649. else:
  2650. charset = 'utf-8'
  2651. if encoding_required:
  2652. encoded_value = urllib.parse.quote(
  2653. value, safe='', errors=error_handler)
  2654. tstr = "{}*={}''{}".format(name, charset, encoded_value)
  2655. else:
  2656. tstr = '{}={}'.format(name, quote_string(value))
  2657. if len(lines[-1]) + len(tstr) + 1 < maxlen:
  2658. lines[-1] = lines[-1] + ' ' + tstr
  2659. continue
  2660. elif len(tstr) + 2 <= maxlen:
  2661. lines.append(' ' + tstr)
  2662. continue
  2663. # We need multiple sections. We are allowed to mix encoded and
  2664. # non-encoded sections, but we aren't going to. We'll encode them all.
  2665. section = 0
  2666. extra_chrome = charset + "''"
  2667. while value:
  2668. chrome_len = len(name) + len(str(section)) + 3 + len(extra_chrome)
  2669. if maxlen <= chrome_len + 3:
  2670. # We need room for the leading blank, the trailing semicolon,
  2671. # and at least one character of the value. If we don't
  2672. # have that, we'd be stuck, so in that case fall back to
  2673. # the RFC standard width.
  2674. maxlen = 78
  2675. splitpoint = maxchars = maxlen - chrome_len - 2
  2676. while True:
  2677. partial = value[:splitpoint]
  2678. encoded_value = urllib.parse.quote(
  2679. partial, safe='', errors=error_handler)
  2680. if len(encoded_value) <= maxchars:
  2681. break
  2682. splitpoint -= 1
  2683. lines.append(" {}*{}*={}{}".format(
  2684. name, section, extra_chrome, encoded_value))
  2685. extra_chrome = ''
  2686. section += 1
  2687. value = value[splitpoint:]
  2688. if value:
  2689. lines[-1] += ';'