_header_value_parser.py 99 KB

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