_header_value_parser.py 104 KB

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