You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1219 lines
30 KiB

  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package html
  5. import (
  6. "bytes"
  7. "errors"
  8. "io"
  9. "strconv"
  10. "strings"
  11. "golang.org/x/net/html/atom"
  12. )
  13. // A TokenType is the type of a Token.
  14. type TokenType uint32
  15. const (
  16. // ErrorToken means that an error occurred during tokenization.
  17. ErrorToken TokenType = iota
  18. // TextToken means a text node.
  19. TextToken
  20. // A StartTagToken looks like <a>.
  21. StartTagToken
  22. // An EndTagToken looks like </a>.
  23. EndTagToken
  24. // A SelfClosingTagToken tag looks like <br/>.
  25. SelfClosingTagToken
  26. // A CommentToken looks like <!--x-->.
  27. CommentToken
  28. // A DoctypeToken looks like <!DOCTYPE x>
  29. DoctypeToken
  30. )
  31. // ErrBufferExceeded means that the buffering limit was exceeded.
  32. var ErrBufferExceeded = errors.New("max buffer exceeded")
  33. // String returns a string representation of the TokenType.
  34. func (t TokenType) String() string {
  35. switch t {
  36. case ErrorToken:
  37. return "Error"
  38. case TextToken:
  39. return "Text"
  40. case StartTagToken:
  41. return "StartTag"
  42. case EndTagToken:
  43. return "EndTag"
  44. case SelfClosingTagToken:
  45. return "SelfClosingTag"
  46. case CommentToken:
  47. return "Comment"
  48. case DoctypeToken:
  49. return "Doctype"
  50. }
  51. return "Invalid(" + strconv.Itoa(int(t)) + ")"
  52. }
  53. // An Attribute is an attribute namespace-key-value triple. Namespace is
  54. // non-empty for foreign attributes like xlink, Key is alphabetic (and hence
  55. // does not contain escapable characters like '&', '<' or '>'), and Val is
  56. // unescaped (it looks like "a<b" rather than "a&lt;b").
  57. //
  58. // Namespace is only used by the parser, not the tokenizer.
  59. type Attribute struct {
  60. Namespace, Key, Val string
  61. }
  62. // A Token consists of a TokenType and some Data (tag name for start and end
  63. // tags, content for text, comments and doctypes). A tag Token may also contain
  64. // a slice of Attributes. Data is unescaped for all Tokens (it looks like "a<b"
  65. // rather than "a&lt;b"). For tag Tokens, DataAtom is the atom for Data, or
  66. // zero if Data is not a known tag name.
  67. type Token struct {
  68. Type TokenType
  69. DataAtom atom.Atom
  70. Data string
  71. Attr []Attribute
  72. }
  73. // tagString returns a string representation of a tag Token's Data and Attr.
  74. func (t Token) tagString() string {
  75. if len(t.Attr) == 0 {
  76. return t.Data
  77. }
  78. buf := bytes.NewBufferString(t.Data)
  79. for _, a := range t.Attr {
  80. buf.WriteByte(' ')
  81. buf.WriteString(a.Key)
  82. buf.WriteString(`="`)
  83. escape(buf, a.Val)
  84. buf.WriteByte('"')
  85. }
  86. return buf.String()
  87. }
  88. // String returns a string representation of the Token.
  89. func (t Token) String() string {
  90. switch t.Type {
  91. case ErrorToken:
  92. return ""
  93. case TextToken:
  94. return EscapeString(t.Data)
  95. case StartTagToken:
  96. return "<" + t.tagString() + ">"
  97. case EndTagToken:
  98. return "</" + t.tagString() + ">"
  99. case SelfClosingTagToken:
  100. return "<" + t.tagString() + "/>"
  101. case CommentToken:
  102. return "<!--" + t.Data + "-->"
  103. case DoctypeToken:
  104. return "<!DOCTYPE " + t.Data + ">"
  105. }
  106. return "Invalid(" + strconv.Itoa(int(t.Type)) + ")"
  107. }
  108. // span is a range of bytes in a Tokenizer's buffer. The start is inclusive,
  109. // the end is exclusive.
  110. type span struct {
  111. start, end int
  112. }
  113. // A Tokenizer returns a stream of HTML Tokens.
  114. type Tokenizer struct {
  115. // r is the source of the HTML text.
  116. r io.Reader
  117. // tt is the TokenType of the current token.
  118. tt TokenType
  119. // err is the first error encountered during tokenization. It is possible
  120. // for tt != Error && err != nil to hold: this means that Next returned a
  121. // valid token but the subsequent Next call will return an error token.
  122. // For example, if the HTML text input was just "plain", then the first
  123. // Next call would set z.err to io.EOF but return a TextToken, and all
  124. // subsequent Next calls would return an ErrorToken.
  125. // err is never reset. Once it becomes non-nil, it stays non-nil.
  126. err error
  127. // readErr is the error returned by the io.Reader r. It is separate from
  128. // err because it is valid for an io.Reader to return (n int, err1 error)
  129. // such that n > 0 && err1 != nil, and callers should always process the
  130. // n > 0 bytes before considering the error err1.
  131. readErr error
  132. // buf[raw.start:raw.end] holds the raw bytes of the current token.
  133. // buf[raw.end:] is buffered input that will yield future tokens.
  134. raw span
  135. buf []byte
  136. // maxBuf limits the data buffered in buf. A value of 0 means unlimited.
  137. maxBuf int
  138. // buf[data.start:data.end] holds the raw bytes of the current token's data:
  139. // a text token's text, a tag token's tag name, etc.
  140. data span
  141. // pendingAttr is the attribute key and value currently being tokenized.
  142. // When complete, pendingAttr is pushed onto attr. nAttrReturned is
  143. // incremented on each call to TagAttr.
  144. pendingAttr [2]span
  145. attr [][2]span
  146. nAttrReturned int
  147. // rawTag is the "script" in "</script>" that closes the next token. If
  148. // non-empty, the subsequent call to Next will return a raw or RCDATA text
  149. // token: one that treats "<p>" as text instead of an element.
  150. // rawTag's contents are lower-cased.
  151. rawTag string
  152. // textIsRaw is whether the current text token's data is not escaped.
  153. textIsRaw bool
  154. // convertNUL is whether NUL bytes in the current token's data should
  155. // be converted into \ufffd replacement characters.
  156. convertNUL bool
  157. // allowCDATA is whether CDATA sections are allowed in the current context.
  158. allowCDATA bool
  159. }
  160. // AllowCDATA sets whether or not the tokenizer recognizes <![CDATA[foo]]> as
  161. // the text "foo". The default value is false, which means to recognize it as
  162. // a bogus comment "<!-- [CDATA[foo]] -->" instead.
  163. //
  164. // Strictly speaking, an HTML5 compliant tokenizer should allow CDATA if and
  165. // only if tokenizing foreign content, such as MathML and SVG. However,
  166. // tracking foreign-contentness is difficult to do purely in the tokenizer,
  167. // as opposed to the parser, due to HTML integration points: an <svg> element
  168. // can contain a <foreignObject> that is foreign-to-SVG but not foreign-to-
  169. // HTML. For strict compliance with the HTML5 tokenization algorithm, it is the
  170. // responsibility of the user of a tokenizer to call AllowCDATA as appropriate.
  171. // In practice, if using the tokenizer without caring whether MathML or SVG
  172. // CDATA is text or comments, such as tokenizing HTML to find all the anchor
  173. // text, it is acceptable to ignore this responsibility.
  174. func (z *Tokenizer) AllowCDATA(allowCDATA bool) {
  175. z.allowCDATA = allowCDATA
  176. }
  177. // NextIsNotRawText instructs the tokenizer that the next token should not be
  178. // considered as 'raw text'. Some elements, such as script and title elements,
  179. // normally require the next token after the opening tag to be 'raw text' that
  180. // has no child elements. For example, tokenizing "<title>a<b>c</b>d</title>"
  181. // yields a start tag token for "<title>", a text token for "a<b>c</b>d", and
  182. // an end tag token for "</title>". There are no distinct start tag or end tag
  183. // tokens for the "<b>" and "</b>".
  184. //
  185. // This tokenizer implementation will generally look for raw text at the right
  186. // times. Strictly speaking, an HTML5 compliant tokenizer should not look for
  187. // raw text if in foreign content: <title> generally needs raw text, but a
  188. // <title> inside an <svg> does not. Another example is that a <textarea>
  189. // generally needs raw text, but a <textarea> is not allowed as an immediate
  190. // child of a <select>; in normal parsing, a <textarea> implies </select>, but
  191. // one cannot close the implicit element when parsing a <select>'s InnerHTML.
  192. // Similarly to AllowCDATA, tracking the correct moment to override raw-text-
  193. // ness is difficult to do purely in the tokenizer, as opposed to the parser.
  194. // For strict compliance with the HTML5 tokenization algorithm, it is the
  195. // responsibility of the user of a tokenizer to call NextIsNotRawText as
  196. // appropriate. In practice, like AllowCDATA, it is acceptable to ignore this
  197. // responsibility for basic usage.
  198. //
  199. // Note that this 'raw text' concept is different from the one offered by the
  200. // Tokenizer.Raw method.
  201. func (z *Tokenizer) NextIsNotRawText() {
  202. z.rawTag = ""
  203. }
  204. // Err returns the error associated with the most recent ErrorToken token.
  205. // This is typically io.EOF, meaning the end of tokenization.
  206. func (z *Tokenizer) Err() error {
  207. if z.tt != ErrorToken {
  208. return nil
  209. }
  210. return z.err
  211. }
  212. // readByte returns the next byte from the input stream, doing a buffered read
  213. // from z.r into z.buf if necessary. z.buf[z.raw.start:z.raw.end] remains a contiguous byte
  214. // slice that holds all the bytes read so far for the current token.
  215. // It sets z.err if the underlying reader returns an error.
  216. // Pre-condition: z.err == nil.
  217. func (z *Tokenizer) readByte() byte {
  218. if z.raw.end >= len(z.buf) {
  219. // Our buffer is exhausted and we have to read from z.r. Check if the
  220. // previous read resulted in an error.
  221. if z.readErr != nil {
  222. z.err = z.readErr
  223. return 0
  224. }
  225. // We copy z.buf[z.raw.start:z.raw.end] to the beginning of z.buf. If the length
  226. // z.raw.end - z.raw.start is more than half the capacity of z.buf, then we
  227. // allocate a new buffer before the copy.
  228. c := cap(z.buf)
  229. d := z.raw.end - z.raw.start
  230. var buf1 []byte
  231. if 2*d > c {
  232. buf1 = make([]byte, d, 2*c)
  233. } else {
  234. buf1 = z.buf[:d]
  235. }
  236. copy(buf1, z.buf[z.raw.start:z.raw.end])
  237. if x := z.raw.start; x != 0 {
  238. // Adjust the data/attr spans to refer to the same contents after the copy.
  239. z.data.start -= x
  240. z.data.end -= x
  241. z.pendingAttr[0].start -= x
  242. z.pendingAttr[0].end -= x
  243. z.pendingAttr[1].start -= x
  244. z.pendingAttr[1].end -= x
  245. for i := range z.attr {
  246. z.attr[i][0].start -= x
  247. z.attr[i][0].end -= x
  248. z.attr[i][1].start -= x
  249. z.attr[i][1].end -= x
  250. }
  251. }
  252. z.raw.start, z.raw.end, z.buf = 0, d, buf1[:d]
  253. // Now that we have copied the live bytes to the start of the buffer,
  254. // we read from z.r into the remainder.
  255. var n int
  256. n, z.readErr = readAtLeastOneByte(z.r, buf1[d:cap(buf1)])
  257. if n == 0 {
  258. z.err = z.readErr
  259. return 0
  260. }
  261. z.buf = buf1[:d+n]
  262. }
  263. x := z.buf[z.raw.end]
  264. z.raw.end++
  265. if z.maxBuf > 0 && z.raw.end-z.raw.start >= z.maxBuf {
  266. z.err = ErrBufferExceeded
  267. return 0
  268. }
  269. return x
  270. }
  271. // Buffered returns a slice containing data buffered but not yet tokenized.
  272. func (z *Tokenizer) Buffered() []byte {
  273. return z.buf[z.raw.end:]
  274. }
  275. // readAtLeastOneByte wraps an io.Reader so that reading cannot return (0, nil).
  276. // It returns io.ErrNoProgress if the underlying r.Read method returns (0, nil)
  277. // too many times in succession.
  278. func readAtLeastOneByte(r io.Reader, b []byte) (int, error) {
  279. for i := 0; i < 100; i++ {
  280. n, err := r.Read(b)
  281. if n != 0 || err != nil {
  282. return n, err
  283. }
  284. }
  285. return 0, io.ErrNoProgress
  286. }
  287. // skipWhiteSpace skips past any white space.
  288. func (z *Tokenizer) skipWhiteSpace() {
  289. if z.err != nil {
  290. return
  291. }
  292. for {
  293. c := z.readByte()
  294. if z.err != nil {
  295. return
  296. }
  297. switch c {
  298. case ' ', '\n', '\r', '\t', '\f':
  299. // No-op.
  300. default:
  301. z.raw.end--
  302. return
  303. }
  304. }
  305. }
  306. // readRawOrRCDATA reads until the next "</foo>", where "foo" is z.rawTag and
  307. // is typically something like "script" or "textarea".
  308. func (z *Tokenizer) readRawOrRCDATA() {
  309. if z.rawTag == "script" {
  310. z.readScript()
  311. z.textIsRaw = true
  312. z.rawTag = ""
  313. return
  314. }
  315. loop:
  316. for {
  317. c := z.readByte()
  318. if z.err != nil {
  319. break loop
  320. }
  321. if c != '<' {
  322. continue loop
  323. }
  324. c = z.readByte()
  325. if z.err != nil {
  326. break loop
  327. }
  328. if c != '/' {
  329. continue loop
  330. }
  331. if z.readRawEndTag() || z.err != nil {
  332. break loop
  333. }
  334. }
  335. z.data.end = z.raw.end
  336. // A textarea's or title's RCDATA can contain escaped entities.
  337. z.textIsRaw = z.rawTag != "textarea" && z.rawTag != "title"
  338. z.rawTag = ""
  339. }
  340. // readRawEndTag attempts to read a tag like "</foo>", where "foo" is z.rawTag.
  341. // If it succeeds, it backs up the input position to reconsume the tag and
  342. // returns true. Otherwise it returns false. The opening "</" has already been
  343. // consumed.
  344. func (z *Tokenizer) readRawEndTag() bool {
  345. for i := 0; i < len(z.rawTag); i++ {
  346. c := z.readByte()
  347. if z.err != nil {
  348. return false
  349. }
  350. if c != z.rawTag[i] && c != z.rawTag[i]-('a'-'A') {
  351. z.raw.end--
  352. return false
  353. }
  354. }
  355. c := z.readByte()
  356. if z.err != nil {
  357. return false
  358. }
  359. switch c {
  360. case ' ', '\n', '\r', '\t', '\f', '/', '>':
  361. // The 3 is 2 for the leading "</" plus 1 for the trailing character c.
  362. z.raw.end -= 3 + len(z.rawTag)
  363. return true
  364. }
  365. z.raw.end--
  366. return false
  367. }
  368. // readScript reads until the next </script> tag, following the byzantine
  369. // rules for escaping/hiding the closing tag.
  370. func (z *Tokenizer) readScript() {
  371. defer func() {
  372. z.data.end = z.raw.end
  373. }()
  374. var c byte
  375. scriptData:
  376. c = z.readByte()
  377. if z.err != nil {
  378. return
  379. }
  380. if c == '<' {
  381. goto scriptDataLessThanSign
  382. }
  383. goto scriptData
  384. scriptDataLessThanSign:
  385. c = z.readByte()
  386. if z.err != nil {
  387. return
  388. }
  389. switch c {
  390. case '/':
  391. goto scriptDataEndTagOpen
  392. case '!':
  393. goto scriptDataEscapeStart
  394. }
  395. z.raw.end--
  396. goto scriptData
  397. scriptDataEndTagOpen:
  398. if z.readRawEndTag() || z.err != nil {
  399. return
  400. }
  401. goto scriptData
  402. scriptDataEscapeStart:
  403. c = z.readByte()
  404. if z.err != nil {
  405. return
  406. }
  407. if c == '-' {
  408. goto scriptDataEscapeStartDash
  409. }
  410. z.raw.end--
  411. goto scriptData
  412. scriptDataEscapeStartDash:
  413. c = z.readByte()
  414. if z.err != nil {
  415. return
  416. }
  417. if c == '-' {
  418. goto scriptDataEscapedDashDash
  419. }
  420. z.raw.end--
  421. goto scriptData
  422. scriptDataEscaped:
  423. c = z.readByte()
  424. if z.err != nil {
  425. return
  426. }
  427. switch c {
  428. case '-':
  429. goto scriptDataEscapedDash
  430. case '<':
  431. goto scriptDataEscapedLessThanSign
  432. }
  433. goto scriptDataEscaped
  434. scriptDataEscapedDash:
  435. c = z.readByte()
  436. if z.err != nil {
  437. return
  438. }
  439. switch c {
  440. case '-':
  441. goto scriptDataEscapedDashDash
  442. case '<':
  443. goto scriptDataEscapedLessThanSign
  444. }
  445. goto scriptDataEscaped
  446. scriptDataEscapedDashDash:
  447. c = z.readByte()
  448. if z.err != nil {
  449. return
  450. }
  451. switch c {
  452. case '-':
  453. goto scriptDataEscapedDashDash
  454. case '<':
  455. goto scriptDataEscapedLessThanSign
  456. case '>':
  457. goto scriptData
  458. }
  459. goto scriptDataEscaped
  460. scriptDataEscapedLessThanSign:
  461. c = z.readByte()
  462. if z.err != nil {
  463. return
  464. }
  465. if c == '/' {
  466. goto scriptDataEscapedEndTagOpen
  467. }
  468. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
  469. goto scriptDataDoubleEscapeStart
  470. }
  471. z.raw.end--
  472. goto scriptData
  473. scriptDataEscapedEndTagOpen:
  474. if z.readRawEndTag() || z.err != nil {
  475. return
  476. }
  477. goto scriptDataEscaped
  478. scriptDataDoubleEscapeStart:
  479. z.raw.end--
  480. for i := 0; i < len("script"); i++ {
  481. c = z.readByte()
  482. if z.err != nil {
  483. return
  484. }
  485. if c != "script"[i] && c != "SCRIPT"[i] {
  486. z.raw.end--
  487. goto scriptDataEscaped
  488. }
  489. }
  490. c = z.readByte()
  491. if z.err != nil {
  492. return
  493. }
  494. switch c {
  495. case ' ', '\n', '\r', '\t', '\f', '/', '>':
  496. goto scriptDataDoubleEscaped
  497. }
  498. z.raw.end--
  499. goto scriptDataEscaped
  500. scriptDataDoubleEscaped:
  501. c = z.readByte()
  502. if z.err != nil {
  503. return
  504. }
  505. switch c {
  506. case '-':
  507. goto scriptDataDoubleEscapedDash
  508. case '<':
  509. goto scriptDataDoubleEscapedLessThanSign
  510. }
  511. goto scriptDataDoubleEscaped
  512. scriptDataDoubleEscapedDash:
  513. c = z.readByte()
  514. if z.err != nil {
  515. return
  516. }
  517. switch c {
  518. case '-':
  519. goto scriptDataDoubleEscapedDashDash
  520. case '<':
  521. goto scriptDataDoubleEscapedLessThanSign
  522. }
  523. goto scriptDataDoubleEscaped
  524. scriptDataDoubleEscapedDashDash:
  525. c = z.readByte()
  526. if z.err != nil {
  527. return
  528. }
  529. switch c {
  530. case '-':
  531. goto scriptDataDoubleEscapedDashDash
  532. case '<':
  533. goto scriptDataDoubleEscapedLessThanSign
  534. case '>':
  535. goto scriptData
  536. }
  537. goto scriptDataDoubleEscaped
  538. scriptDataDoubleEscapedLessThanSign:
  539. c = z.readByte()
  540. if z.err != nil {
  541. return
  542. }
  543. if c == '/' {
  544. goto scriptDataDoubleEscapeEnd
  545. }
  546. z.raw.end--
  547. goto scriptDataDoubleEscaped
  548. scriptDataDoubleEscapeEnd:
  549. if z.readRawEndTag() {
  550. z.raw.end += len("</script>")
  551. goto scriptDataEscaped
  552. }
  553. if z.err != nil {
  554. return
  555. }
  556. goto scriptDataDoubleEscaped
  557. }
  558. // readComment reads the next comment token starting with "<!--". The opening
  559. // "<!--" has already been consumed.
  560. func (z *Tokenizer) readComment() {
  561. z.data.start = z.raw.end
  562. defer func() {
  563. if z.data.end < z.data.start {
  564. // It's a comment with no data, like <!-->.
  565. z.data.end = z.data.start
  566. }
  567. }()
  568. for dashCount := 2; ; {
  569. c := z.readByte()
  570. if z.err != nil {
  571. // Ignore up to two dashes at EOF.
  572. if dashCount > 2 {
  573. dashCount = 2
  574. }
  575. z.data.end = z.raw.end - dashCount
  576. return
  577. }
  578. switch c {
  579. case '-':
  580. dashCount++
  581. continue
  582. case '>':
  583. if dashCount >= 2 {
  584. z.data.end = z.raw.end - len("-->")
  585. return
  586. }
  587. case '!':
  588. if dashCount >= 2 {
  589. c = z.readByte()
  590. if z.err != nil {
  591. z.data.end = z.raw.end
  592. return
  593. }
  594. if c == '>' {
  595. z.data.end = z.raw.end - len("--!>")
  596. return
  597. }
  598. }
  599. }
  600. dashCount = 0
  601. }
  602. }
  603. // readUntilCloseAngle reads until the next ">".
  604. func (z *Tokenizer) readUntilCloseAngle() {
  605. z.data.start = z.raw.end
  606. for {
  607. c := z.readByte()
  608. if z.err != nil {
  609. z.data.end = z.raw.end
  610. return
  611. }
  612. if c == '>' {
  613. z.data.end = z.raw.end - len(">")
  614. return
  615. }
  616. }
  617. }
  618. // readMarkupDeclaration reads the next token starting with "<!". It might be
  619. // a "<!--comment-->", a "<!DOCTYPE foo>", a "<![CDATA[section]]>" or
  620. // "<!a bogus comment". The opening "<!" has already been consumed.
  621. func (z *Tokenizer) readMarkupDeclaration() TokenType {
  622. z.data.start = z.raw.end
  623. var c [2]byte
  624. for i := 0; i < 2; i++ {
  625. c[i] = z.readByte()
  626. if z.err != nil {
  627. z.data.end = z.raw.end
  628. return CommentToken
  629. }
  630. }
  631. if c[0] == '-' && c[1] == '-' {
  632. z.readComment()
  633. return CommentToken
  634. }
  635. z.raw.end -= 2
  636. if z.readDoctype() {
  637. return DoctypeToken
  638. }
  639. if z.allowCDATA && z.readCDATA() {
  640. z.convertNUL = true
  641. return TextToken
  642. }
  643. // It's a bogus comment.
  644. z.readUntilCloseAngle()
  645. return CommentToken
  646. }
  647. // readDoctype attempts to read a doctype declaration and returns true if
  648. // successful. The opening "<!" has already been consumed.
  649. func (z *Tokenizer) readDoctype() bool {
  650. const s = "DOCTYPE"
  651. for i := 0; i < len(s); i++ {
  652. c := z.readByte()
  653. if z.err != nil {
  654. z.data.end = z.raw.end
  655. return false
  656. }
  657. if c != s[i] && c != s[i]+('a'-'A') {
  658. // Back up to read the fragment of "DOCTYPE" again.
  659. z.raw.end = z.data.start
  660. return false
  661. }
  662. }
  663. if z.skipWhiteSpace(); z.err != nil {
  664. z.data.start = z.raw.end
  665. z.data.end = z.raw.end
  666. return true
  667. }
  668. z.readUntilCloseAngle()
  669. return true
  670. }
  671. // readCDATA attempts to read a CDATA section and returns true if
  672. // successful. The opening "<!" has already been consumed.
  673. func (z *Tokenizer) readCDATA() bool {
  674. const s = "[CDATA["
  675. for i := 0; i < len(s); i++ {
  676. c := z.readByte()
  677. if z.err != nil {
  678. z.data.end = z.raw.end
  679. return false
  680. }
  681. if c != s[i] {
  682. // Back up to read the fragment of "[CDATA[" again.
  683. z.raw.end = z.data.start
  684. return false
  685. }
  686. }
  687. z.data.start = z.raw.end
  688. brackets := 0
  689. for {
  690. c := z.readByte()
  691. if z.err != nil {
  692. z.data.end = z.raw.end
  693. return true
  694. }
  695. switch c {
  696. case ']':
  697. brackets++
  698. case '>':
  699. if brackets >= 2 {
  700. z.data.end = z.raw.end - len("]]>")
  701. return true
  702. }
  703. brackets = 0
  704. default:
  705. brackets = 0
  706. }
  707. }
  708. }
  709. // startTagIn returns whether the start tag in z.buf[z.data.start:z.data.end]
  710. // case-insensitively matches any element of ss.
  711. func (z *Tokenizer) startTagIn(ss ...string) bool {
  712. loop:
  713. for _, s := range ss {
  714. if z.data.end-z.data.start != len(s) {
  715. continue loop
  716. }
  717. for i := 0; i < len(s); i++ {
  718. c := z.buf[z.data.start+i]
  719. if 'A' <= c && c <= 'Z' {
  720. c += 'a' - 'A'
  721. }
  722. if c != s[i] {
  723. continue loop
  724. }
  725. }
  726. return true
  727. }
  728. return false
  729. }
  730. // readStartTag reads the next start tag token. The opening "<a" has already
  731. // been consumed, where 'a' means anything in [A-Za-z].
  732. func (z *Tokenizer) readStartTag() TokenType {
  733. z.readTag(true)
  734. if z.err != nil {
  735. return ErrorToken
  736. }
  737. // Several tags flag the tokenizer's next token as raw.
  738. c, raw := z.buf[z.data.start], false
  739. if 'A' <= c && c <= 'Z' {
  740. c += 'a' - 'A'
  741. }
  742. switch c {
  743. case 'i':
  744. raw = z.startTagIn("iframe")
  745. case 'n':
  746. raw = z.startTagIn("noembed", "noframes", "noscript")
  747. case 'p':
  748. raw = z.startTagIn("plaintext")
  749. case 's':
  750. raw = z.startTagIn("script", "style")
  751. case 't':
  752. raw = z.startTagIn("textarea", "title")
  753. case 'x':
  754. raw = z.startTagIn("xmp")
  755. }
  756. if raw {
  757. z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end]))
  758. }
  759. // Look for a self-closing token like "<br/>".
  760. if z.err == nil && z.buf[z.raw.end-2] == '/' {
  761. return SelfClosingTagToken
  762. }
  763. return StartTagToken
  764. }
  765. // readTag reads the next tag token and its attributes. If saveAttr, those
  766. // attributes are saved in z.attr, otherwise z.attr is set to an empty slice.
  767. // The opening "<a" or "</a" has already been consumed, where 'a' means anything
  768. // in [A-Za-z].
  769. func (z *Tokenizer) readTag(saveAttr bool) {
  770. z.attr = z.attr[:0]
  771. z.nAttrReturned = 0
  772. // Read the tag name and attribute key/value pairs.
  773. z.readTagName()
  774. if z.skipWhiteSpace(); z.err != nil {
  775. return
  776. }
  777. for {
  778. c := z.readByte()
  779. if z.err != nil || c == '>' {
  780. break
  781. }
  782. z.raw.end--
  783. z.readTagAttrKey()
  784. z.readTagAttrVal()
  785. // Save pendingAttr if saveAttr and that attribute has a non-empty key.
  786. if saveAttr && z.pendingAttr[0].start != z.pendingAttr[0].end {
  787. z.attr = append(z.attr, z.pendingAttr)
  788. }
  789. if z.skipWhiteSpace(); z.err != nil {
  790. break
  791. }
  792. }
  793. }
  794. // readTagName sets z.data to the "div" in "<div k=v>". The reader (z.raw.end)
  795. // is positioned such that the first byte of the tag name (the "d" in "<div")
  796. // has already been consumed.
  797. func (z *Tokenizer) readTagName() {
  798. z.data.start = z.raw.end - 1
  799. for {
  800. c := z.readByte()
  801. if z.err != nil {
  802. z.data.end = z.raw.end
  803. return
  804. }
  805. switch c {
  806. case ' ', '\n', '\r', '\t', '\f':
  807. z.data.end = z.raw.end - 1
  808. return
  809. case '/', '>':
  810. z.raw.end--
  811. z.data.end = z.raw.end
  812. return
  813. }
  814. }
  815. }
  816. // readTagAttrKey sets z.pendingAttr[0] to the "k" in "<div k=v>".
  817. // Precondition: z.err == nil.
  818. func (z *Tokenizer) readTagAttrKey() {
  819. z.pendingAttr[0].start = z.raw.end
  820. for {
  821. c := z.readByte()
  822. if z.err != nil {
  823. z.pendingAttr[0].end = z.raw.end
  824. return
  825. }
  826. switch c {
  827. case ' ', '\n', '\r', '\t', '\f', '/':
  828. z.pendingAttr[0].end = z.raw.end - 1
  829. return
  830. case '=', '>':
  831. z.raw.end--
  832. z.pendingAttr[0].end = z.raw.end
  833. return
  834. }
  835. }
  836. }
  837. // readTagAttrVal sets z.pendingAttr[1] to the "v" in "<div k=v>".
  838. func (z *Tokenizer) readTagAttrVal() {
  839. z.pendingAttr[1].start = z.raw.end
  840. z.pendingAttr[1].end = z.raw.end
  841. if z.skipWhiteSpace(); z.err != nil {
  842. return
  843. }
  844. c := z.readByte()
  845. if z.err != nil {
  846. return
  847. }
  848. if c != '=' {
  849. z.raw.end--
  850. return
  851. }
  852. if z.skipWhiteSpace(); z.err != nil {
  853. return
  854. }
  855. quote := z.readByte()
  856. if z.err != nil {
  857. return
  858. }
  859. switch quote {
  860. case '>':
  861. z.raw.end--
  862. return
  863. case '\'', '"':
  864. z.pendingAttr[1].start = z.raw.end
  865. for {
  866. c := z.readByte()
  867. if z.err != nil {
  868. z.pendingAttr[1].end = z.raw.end
  869. return
  870. }
  871. if c == quote {
  872. z.pendingAttr[1].end = z.raw.end - 1
  873. return
  874. }
  875. }
  876. default:
  877. z.pendingAttr[1].start = z.raw.end - 1
  878. for {
  879. c := z.readByte()
  880. if z.err != nil {
  881. z.pendingAttr[1].end = z.raw.end
  882. return
  883. }
  884. switch c {
  885. case ' ', '\n', '\r', '\t', '\f':
  886. z.pendingAttr[1].end = z.raw.end - 1
  887. return
  888. case '>':
  889. z.raw.end--
  890. z.pendingAttr[1].end = z.raw.end
  891. return
  892. }
  893. }
  894. }
  895. }
  896. // Next scans the next token and returns its type.
  897. func (z *Tokenizer) Next() TokenType {
  898. z.raw.start = z.raw.end
  899. z.data.start = z.raw.end
  900. z.data.end = z.raw.end
  901. if z.err != nil {
  902. z.tt = ErrorToken
  903. return z.tt
  904. }
  905. if z.rawTag != "" {
  906. if z.rawTag == "plaintext" {
  907. // Read everything up to EOF.
  908. for z.err == nil {
  909. z.readByte()
  910. }
  911. z.data.end = z.raw.end
  912. z.textIsRaw = true
  913. } else {
  914. z.readRawOrRCDATA()
  915. }
  916. if z.data.end > z.data.start {
  917. z.tt = TextToken
  918. z.convertNUL = true
  919. return z.tt
  920. }
  921. }
  922. z.textIsRaw = false
  923. z.convertNUL = false
  924. loop:
  925. for {
  926. c := z.readByte()
  927. if z.err != nil {
  928. break loop
  929. }
  930. if c != '<' {
  931. continue loop
  932. }
  933. // Check if the '<' we have just read is part of a tag, comment
  934. // or doctype. If not, it's part of the accumulated text token.
  935. c = z.readByte()
  936. if z.err != nil {
  937. break loop
  938. }
  939. var tokenType TokenType
  940. switch {
  941. case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
  942. tokenType = StartTagToken
  943. case c == '/':
  944. tokenType = EndTagToken
  945. case c == '!' || c == '?':
  946. // We use CommentToken to mean any of "<!--actual comments-->",
  947. // "<!DOCTYPE declarations>" and "<?xml processing instructions?>".
  948. tokenType = CommentToken
  949. default:
  950. // Reconsume the current character.
  951. z.raw.end--
  952. continue
  953. }
  954. // We have a non-text token, but we might have accumulated some text
  955. // before that. If so, we return the text first, and return the non-
  956. // text token on the subsequent call to Next.
  957. if x := z.raw.end - len("<a"); z.raw.start < x {
  958. z.raw.end = x
  959. z.data.end = x
  960. z.tt = TextToken
  961. return z.tt
  962. }
  963. switch tokenType {
  964. case StartTagToken:
  965. z.tt = z.readStartTag()
  966. return z.tt
  967. case EndTagToken:
  968. c = z.readByte()
  969. if z.err != nil {
  970. break loop
  971. }
  972. if c == '>' {
  973. // "</>" does not generate a token at all. Generate an empty comment
  974. // to allow passthrough clients to pick up the data using Raw.
  975. // Reset the tokenizer state and start again.
  976. z.tt = CommentToken
  977. return z.tt
  978. }
  979. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
  980. z.readTag(false)
  981. if z.err != nil {
  982. z.tt = ErrorToken
  983. } else {
  984. z.tt = EndTagToken
  985. }
  986. return z.tt
  987. }
  988. z.raw.end--
  989. z.readUntilCloseAngle()
  990. z.tt = CommentToken
  991. return z.tt
  992. case CommentToken:
  993. if c == '!' {
  994. z.tt = z.readMarkupDeclaration()
  995. return z.tt
  996. }
  997. z.raw.end--
  998. z.readUntilCloseAngle()
  999. z.tt = CommentToken
  1000. return z.tt
  1001. }
  1002. }
  1003. if z.raw.start < z.raw.end {
  1004. z.data.end = z.raw.end
  1005. z.tt = TextToken
  1006. return z.tt
  1007. }
  1008. z.tt = ErrorToken
  1009. return z.tt
  1010. }
  1011. // Raw returns the unmodified text of the current token. Calling Next, Token,
  1012. // Text, TagName or TagAttr may change the contents of the returned slice.
  1013. func (z *Tokenizer) Raw() []byte {
  1014. return z.buf[z.raw.start:z.raw.end]
  1015. }
  1016. // convertNewlines converts "\r" and "\r\n" in s to "\n".
  1017. // The conversion happens in place, but the resulting slice may be shorter.
  1018. func convertNewlines(s []byte) []byte {
  1019. for i, c := range s {
  1020. if c != '\r' {
  1021. continue
  1022. }
  1023. src := i + 1
  1024. if src >= len(s) || s[src] != '\n' {
  1025. s[i] = '\n'
  1026. continue
  1027. }
  1028. dst := i
  1029. for src < len(s) {
  1030. if s[src] == '\r' {
  1031. if src+1 < len(s) && s[src+1] == '\n' {
  1032. src++
  1033. }
  1034. s[dst] = '\n'
  1035. } else {
  1036. s[dst] = s[src]
  1037. }
  1038. src++
  1039. dst++
  1040. }
  1041. return s[:dst]
  1042. }
  1043. return s
  1044. }
  1045. var (
  1046. nul = []byte("\x00")
  1047. replacement = []byte("\ufffd")
  1048. )
  1049. // Text returns the unescaped text of a text, comment or doctype token. The
  1050. // contents of the returned slice may change on the next call to Next.
  1051. func (z *Tokenizer) Text() []byte {
  1052. switch z.tt {
  1053. case TextToken, CommentToken, DoctypeToken:
  1054. s := z.buf[z.data.start:z.data.end]
  1055. z.data.start = z.raw.end
  1056. z.data.end = z.raw.end
  1057. s = convertNewlines(s)
  1058. if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) {
  1059. s = bytes.Replace(s, nul, replacement, -1)
  1060. }
  1061. if !z.textIsRaw {
  1062. s = unescape(s, false)
  1063. }
  1064. return s
  1065. }
  1066. return nil
  1067. }
  1068. // TagName returns the lower-cased name of a tag token (the `img` out of
  1069. // `<IMG SRC="foo">`) and whether the tag has attributes.
  1070. // The contents of the returned slice may change on the next call to Next.
  1071. func (z *Tokenizer) TagName() (name []byte, hasAttr bool) {
  1072. if z.data.start < z.data.end {
  1073. switch z.tt {
  1074. case StartTagToken, EndTagToken, SelfClosingTagToken:
  1075. s := z.buf[z.data.start:z.data.end]
  1076. z.data.start = z.raw.end
  1077. z.data.end = z.raw.end
  1078. return lower(s), z.nAttrReturned < len(z.attr)
  1079. }
  1080. }
  1081. return nil, false
  1082. }
  1083. // TagAttr returns the lower-cased key and unescaped value of the next unparsed
  1084. // attribute for the current tag token and whether there are more attributes.
  1085. // The contents of the returned slices may change on the next call to Next.
  1086. func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) {
  1087. if z.nAttrReturned < len(z.attr) {
  1088. switch z.tt {
  1089. case StartTagToken, SelfClosingTagToken:
  1090. x := z.attr[z.nAttrReturned]
  1091. z.nAttrReturned++
  1092. key = z.buf[x[0].start:x[0].end]
  1093. val = z.buf[x[1].start:x[1].end]
  1094. return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr)
  1095. }
  1096. }
  1097. return nil, nil, false
  1098. }
  1099. // Token returns the current Token. The result's Data and Attr values remain
  1100. // valid after subsequent Next calls.
  1101. func (z *Tokenizer) Token() Token {
  1102. t := Token{Type: z.tt}
  1103. switch z.tt {
  1104. case TextToken, CommentToken, DoctypeToken:
  1105. t.Data = string(z.Text())
  1106. case StartTagToken, SelfClosingTagToken, EndTagToken:
  1107. name, moreAttr := z.TagName()
  1108. for moreAttr {
  1109. var key, val []byte
  1110. key, val, moreAttr = z.TagAttr()
  1111. t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)})
  1112. }
  1113. if a := atom.Lookup(name); a != 0 {
  1114. t.DataAtom, t.Data = a, a.String()
  1115. } else {
  1116. t.DataAtom, t.Data = 0, string(name)
  1117. }
  1118. }
  1119. return t
  1120. }
  1121. // SetMaxBuf sets a limit on the amount of data buffered during tokenization.
  1122. // A value of 0 means unlimited.
  1123. func (z *Tokenizer) SetMaxBuf(n int) {
  1124. z.maxBuf = n
  1125. }
  1126. // NewTokenizer returns a new HTML Tokenizer for the given Reader.
  1127. // The input is assumed to be UTF-8 encoded.
  1128. func NewTokenizer(r io.Reader) *Tokenizer {
  1129. return NewTokenizerFragment(r, "")
  1130. }
  1131. // NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for
  1132. // tokenizing an existing element's InnerHTML fragment. contextTag is that
  1133. // element's tag, such as "div" or "iframe".
  1134. //
  1135. // For example, how the InnerHTML "a<b" is tokenized depends on whether it is
  1136. // for a <p> tag or a <script> tag.
  1137. //
  1138. // The input is assumed to be UTF-8 encoded.
  1139. func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer {
  1140. z := &Tokenizer{
  1141. r: r,
  1142. buf: make([]byte, 0, 4096),
  1143. }
  1144. if contextTag != "" {
  1145. switch s := strings.ToLower(contextTag); s {
  1146. case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp":
  1147. z.rawTag = s
  1148. }
  1149. }
  1150. return z
  1151. }