token.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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. if n, err := r.Read(b); n != 0 || err != nil {
  281. return n, err
  282. }
  283. }
  284. return 0, io.ErrNoProgress
  285. }
  286. // skipWhiteSpace skips past any white space.
  287. func (z *Tokenizer) skipWhiteSpace() {
  288. if z.err != nil {
  289. return
  290. }
  291. for {
  292. c := z.readByte()
  293. if z.err != nil {
  294. return
  295. }
  296. switch c {
  297. case ' ', '\n', '\r', '\t', '\f':
  298. // No-op.
  299. default:
  300. z.raw.end--
  301. return
  302. }
  303. }
  304. }
  305. // readRawOrRCDATA reads until the next "</foo>", where "foo" is z.rawTag and
  306. // is typically something like "script" or "textarea".
  307. func (z *Tokenizer) readRawOrRCDATA() {
  308. if z.rawTag == "script" {
  309. z.readScript()
  310. z.textIsRaw = true
  311. z.rawTag = ""
  312. return
  313. }
  314. loop:
  315. for {
  316. c := z.readByte()
  317. if z.err != nil {
  318. break loop
  319. }
  320. if c != '<' {
  321. continue loop
  322. }
  323. c = z.readByte()
  324. if z.err != nil {
  325. break loop
  326. }
  327. if c != '/' {
  328. z.raw.end--
  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. //
  1014. // The token stream's raw bytes partition the byte stream (up until an
  1015. // ErrorToken). There are no overlaps or gaps between two consecutive token's
  1016. // raw bytes. One implication is that the byte offset of the current token is
  1017. // the sum of the lengths of all previous tokens' raw bytes.
  1018. func (z *Tokenizer) Raw() []byte {
  1019. return z.buf[z.raw.start:z.raw.end]
  1020. }
  1021. // convertNewlines converts "\r" and "\r\n" in s to "\n".
  1022. // The conversion happens in place, but the resulting slice may be shorter.
  1023. func convertNewlines(s []byte) []byte {
  1024. for i, c := range s {
  1025. if c != '\r' {
  1026. continue
  1027. }
  1028. src := i + 1
  1029. if src >= len(s) || s[src] != '\n' {
  1030. s[i] = '\n'
  1031. continue
  1032. }
  1033. dst := i
  1034. for src < len(s) {
  1035. if s[src] == '\r' {
  1036. if src+1 < len(s) && s[src+1] == '\n' {
  1037. src++
  1038. }
  1039. s[dst] = '\n'
  1040. } else {
  1041. s[dst] = s[src]
  1042. }
  1043. src++
  1044. dst++
  1045. }
  1046. return s[:dst]
  1047. }
  1048. return s
  1049. }
  1050. var (
  1051. nul = []byte("\x00")
  1052. replacement = []byte("\ufffd")
  1053. )
  1054. // Text returns the unescaped text of a text, comment or doctype token. The
  1055. // contents of the returned slice may change on the next call to Next.
  1056. func (z *Tokenizer) Text() []byte {
  1057. switch z.tt {
  1058. case TextToken, CommentToken, DoctypeToken:
  1059. s := z.buf[z.data.start:z.data.end]
  1060. z.data.start = z.raw.end
  1061. z.data.end = z.raw.end
  1062. s = convertNewlines(s)
  1063. if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) {
  1064. s = bytes.Replace(s, nul, replacement, -1)
  1065. }
  1066. if !z.textIsRaw {
  1067. s = unescape(s, false)
  1068. }
  1069. return s
  1070. }
  1071. return nil
  1072. }
  1073. // TagName returns the lower-cased name of a tag token (the `img` out of
  1074. // `<IMG SRC="foo">`) and whether the tag has attributes.
  1075. // The contents of the returned slice may change on the next call to Next.
  1076. func (z *Tokenizer) TagName() (name []byte, hasAttr bool) {
  1077. if z.data.start < z.data.end {
  1078. switch z.tt {
  1079. case StartTagToken, EndTagToken, SelfClosingTagToken:
  1080. s := z.buf[z.data.start:z.data.end]
  1081. z.data.start = z.raw.end
  1082. z.data.end = z.raw.end
  1083. return lower(s), z.nAttrReturned < len(z.attr)
  1084. }
  1085. }
  1086. return nil, false
  1087. }
  1088. // TagAttr returns the lower-cased key and unescaped value of the next unparsed
  1089. // attribute for the current tag token and whether there are more attributes.
  1090. // The contents of the returned slices may change on the next call to Next.
  1091. func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) {
  1092. if z.nAttrReturned < len(z.attr) {
  1093. switch z.tt {
  1094. case StartTagToken, SelfClosingTagToken:
  1095. x := z.attr[z.nAttrReturned]
  1096. z.nAttrReturned++
  1097. key = z.buf[x[0].start:x[0].end]
  1098. val = z.buf[x[1].start:x[1].end]
  1099. return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr)
  1100. }
  1101. }
  1102. return nil, nil, false
  1103. }
  1104. // Token returns the current Token. The result's Data and Attr values remain
  1105. // valid after subsequent Next calls.
  1106. func (z *Tokenizer) Token() Token {
  1107. t := Token{Type: z.tt}
  1108. switch z.tt {
  1109. case TextToken, CommentToken, DoctypeToken:
  1110. t.Data = string(z.Text())
  1111. case StartTagToken, SelfClosingTagToken, EndTagToken:
  1112. name, moreAttr := z.TagName()
  1113. for moreAttr {
  1114. var key, val []byte
  1115. key, val, moreAttr = z.TagAttr()
  1116. t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)})
  1117. }
  1118. if a := atom.Lookup(name); a != 0 {
  1119. t.DataAtom, t.Data = a, a.String()
  1120. } else {
  1121. t.DataAtom, t.Data = 0, string(name)
  1122. }
  1123. }
  1124. return t
  1125. }
  1126. // SetMaxBuf sets a limit on the amount of data buffered during tokenization.
  1127. // A value of 0 means unlimited.
  1128. func (z *Tokenizer) SetMaxBuf(n int) {
  1129. z.maxBuf = n
  1130. }
  1131. // NewTokenizer returns a new HTML Tokenizer for the given Reader.
  1132. // The input is assumed to be UTF-8 encoded.
  1133. func NewTokenizer(r io.Reader) *Tokenizer {
  1134. return NewTokenizerFragment(r, "")
  1135. }
  1136. // NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for
  1137. // tokenizing an existing element's InnerHTML fragment. contextTag is that
  1138. // element's tag, such as "div" or "iframe".
  1139. //
  1140. // For example, how the InnerHTML "a<b" is tokenized depends on whether it is
  1141. // for a <p> tag or a <script> tag.
  1142. //
  1143. // The input is assumed to be UTF-8 encoded.
  1144. func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer {
  1145. z := &Tokenizer{
  1146. r: r,
  1147. buf: make([]byte, 0, 4096),
  1148. }
  1149. if contextTag != "" {
  1150. switch s := strings.ToLower(contextTag); s {
  1151. case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp":
  1152. z.rawTag = s
  1153. }
  1154. }
  1155. return z
  1156. }