html_parse.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. """
  2. This module implements a VERY limited parser that finds <link> tags in
  3. the head of HTML or XHTML documents and parses out their attributes
  4. according to the OpenID spec. It is a liberal parser, but it requires
  5. these things from the data in order to work:
  6. - There must be an open <html> tag
  7. - There must be an open <head> tag inside of the <html> tag
  8. - Only <link>s that are found inside of the <head> tag are parsed
  9. (this is by design)
  10. - The parser follows the OpenID specification in resolving the
  11. attributes of the link tags. This means that the attributes DO NOT
  12. get resolved as they would by an XML or HTML parser. In particular,
  13. only certain entities get replaced, and href attributes do not get
  14. resolved relative to a base URL.
  15. From http://openid.net/specs.bml#linkrel:
  16. - The openid.server URL MUST be an absolute URL. OpenID consumers
  17. MUST NOT attempt to resolve relative URLs.
  18. - The openid.server URL MUST NOT include entities other than &amp;,
  19. &lt;, &gt;, and &quot;.
  20. The parser ignores SGML comments and <![CDATA[blocks]]>. Both kinds of
  21. quoting are allowed for attributes.
  22. The parser deals with invalid markup in these ways:
  23. - Tag names are not case-sensitive
  24. - The <html> tag is accepted even when it is not at the top level
  25. - The <head> tag is accepted even when it is not a direct child of
  26. the <html> tag, but a <html> tag must be an ancestor of the <head>
  27. tag
  28. - <link> tags are accepted even when they are not direct children of
  29. the <head> tag, but a <head> tag must be an ancestor of the <link>
  30. tag
  31. - If there is no closing tag for an open <html> or <head> tag, the
  32. remainder of the document is viewed as being inside of the tag. If
  33. there is no closing tag for a <link> tag, the link tag is treated
  34. as a short tag. Exceptions to this rule are that <html> closes
  35. <html> and <body> or <head> closes <head>
  36. - Attributes of the <link> tag are not required to be quoted.
  37. - In the case of duplicated attribute names, the attribute coming
  38. last in the tag will be the value returned.
  39. - Any text that does not parse as an attribute within a link tag will
  40. be ignored. (e.g. <link pumpkin rel='openid.server' /> will ignore
  41. pumpkin)
  42. - If there are more than one <html> or <head> tag, the parser only
  43. looks inside of the first one.
  44. - The contents of <script> tags are ignored entirely, except unclosed
  45. <script> tags. Unclosed <script> tags are ignored.
  46. - Any other invalid markup is ignored, including unclosed SGML
  47. comments and unclosed <![CDATA[blocks.
  48. """
  49. __all__ = ['parseLinkAttrs']
  50. import re
  51. flags = ( re.DOTALL # Match newlines with '.'
  52. | re.IGNORECASE
  53. | re.VERBOSE # Allow comments and whitespace in patterns
  54. | re.UNICODE # Make \b respect Unicode word boundaries
  55. )
  56. # Stuff to remove before we start looking for tags
  57. removed_re = re.compile(r'''
  58. # Comments
  59. <!--.*?-->
  60. # CDATA blocks
  61. | <!\[CDATA\[.*?\]\]>
  62. # script blocks
  63. | <script\b
  64. # make sure script is not an XML namespace
  65. (?!:)
  66. [^>]*>.*?</script>
  67. ''', flags)
  68. tag_expr = r'''
  69. # Starts with the tag name at a word boundary, where the tag name is
  70. # not a namespace
  71. <%(tag_name)s\b(?!:)
  72. # All of the stuff up to a ">", hopefully attributes.
  73. (?P<attrs>[^>]*?)
  74. (?: # Match a short tag
  75. />
  76. | # Match a full tag
  77. >
  78. (?P<contents>.*?)
  79. # Closed by
  80. (?: # One of the specified close tags
  81. </?%(closers)s\s*>
  82. # End of the string
  83. | \Z
  84. )
  85. )
  86. '''
  87. def tagMatcher(tag_name, *close_tags):
  88. if close_tags:
  89. options = '|'.join((tag_name,) + close_tags)
  90. closers = '(?:%s)' % (options,)
  91. else:
  92. closers = tag_name
  93. expr = tag_expr % locals()
  94. return re.compile(expr, flags)
  95. # Must contain at least an open html and an open head tag
  96. html_find = tagMatcher('html')
  97. head_find = tagMatcher('head', 'body')
  98. link_find = re.compile(r'<link\b(?!:)', flags)
  99. attr_find = re.compile(r'''
  100. # Must start with a sequence of word-characters, followed by an equals sign
  101. (?P<attr_name>\w+)=
  102. # Then either a quoted or unquoted attribute
  103. (?:
  104. # Match everything that\'s between matching quote marks
  105. (?P<qopen>["\'])(?P<q_val>.*?)(?P=qopen)
  106. |
  107. # If the value is not quoted, match up to whitespace
  108. (?P<unq_val>(?:[^\s<>/]|/(?!>))+)
  109. )
  110. |
  111. (?P<end_link>[<>])
  112. ''', flags)
  113. # Entity replacement:
  114. replacements = {
  115. 'amp':'&',
  116. 'lt':'<',
  117. 'gt':'>',
  118. 'quot':'"',
  119. }
  120. ent_replace = re.compile(r'&(%s);' % '|'.join(replacements.keys()))
  121. def replaceEnt(mo):
  122. "Replace the entities that are specified by OpenID"
  123. return replacements.get(mo.group(1), mo.group())
  124. def parseLinkAttrs(html):
  125. """Find all link tags in a string representing a HTML document and
  126. return a list of their attributes.
  127. @param html: the text to parse
  128. @type html: str or unicode
  129. @return: A list of dictionaries of attributes, one for each link tag
  130. @rtype: [[(type(html), type(html))]]
  131. """
  132. stripped = removed_re.sub('', html)
  133. html_mo = html_find.search(stripped)
  134. if html_mo is None or html_mo.start('contents') == -1:
  135. return []
  136. start, end = html_mo.span('contents')
  137. head_mo = head_find.search(stripped, start, end)
  138. if head_mo is None or head_mo.start('contents') == -1:
  139. return []
  140. start, end = head_mo.span('contents')
  141. link_mos = link_find.finditer(stripped, head_mo.start(), head_mo.end())
  142. matches = []
  143. for link_mo in link_mos:
  144. start = link_mo.start() + 5
  145. link_attrs = {}
  146. for attr_mo in attr_find.finditer(stripped, start):
  147. if attr_mo.lastgroup == 'end_link':
  148. break
  149. # Either q_val or unq_val must be present, but not both
  150. # unq_val is a True (non-empty) value if it is present
  151. attr_name, q_val, unq_val = attr_mo.group(
  152. 'attr_name', 'q_val', 'unq_val')
  153. attr_val = ent_replace.sub(replaceEnt, unq_val or q_val)
  154. link_attrs[attr_name] = attr_val
  155. matches.append(link_attrs)
  156. return matches
  157. def relMatches(rel_attr, target_rel):
  158. """Does this target_rel appear in the rel_str?"""
  159. # XXX: TESTME
  160. rels = rel_attr.strip().split()
  161. for rel in rels:
  162. rel = rel.lower()
  163. if rel == target_rel:
  164. return 1
  165. return 0
  166. def linkHasRel(link_attrs, target_rel):
  167. """Does this link have target_rel as a relationship?"""
  168. # XXX: TESTME
  169. rel_attr = link_attrs.get('rel')
  170. return rel_attr and relMatches(rel_attr, target_rel)
  171. def findLinksRel(link_attrs_list, target_rel):
  172. """Filter the list of link attributes on whether it has target_rel
  173. as a relationship."""
  174. # XXX: TESTME
  175. matchesTarget = lambda attrs: linkHasRel(attrs, target_rel)
  176. return filter(matchesTarget, link_attrs_list)
  177. def findFirstHref(link_attrs_list, target_rel):
  178. """Return the value of the href attribute for the first link tag
  179. in the list that has target_rel as a relationship."""
  180. # XXX: TESTME
  181. matches = findLinksRel(link_attrs_list, target_rel)
  182. if not matches:
  183. return None
  184. first = matches[0]
  185. return first.get('href')