token.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  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. "code.google.com/p/go.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. // readAtLeastOneByte wraps an io.Reader so that reading cannot return (0, nil).
  272. // It returns io.ErrNoProgress if the underlying r.Read method returns (0, nil)
  273. // too many times in succession.
  274. func readAtLeastOneByte(r io.Reader, b []byte) (int, error) {
  275. for i := 0; i < 100; i++ {
  276. n, err := r.Read(b)
  277. if n != 0 || err != nil {
  278. return n, err
  279. }
  280. }
  281. return 0, io.ErrNoProgress
  282. }
  283. // skipWhiteSpace skips past any white space.
  284. func (z *Tokenizer) skipWhiteSpace() {
  285. if z.err != nil {
  286. return
  287. }
  288. for {
  289. c := z.readByte()
  290. if z.err != nil {
  291. return
  292. }
  293. switch c {
  294. case ' ', '\n', '\r', '\t', '\f':
  295. // No-op.
  296. default:
  297. z.raw.end--
  298. return
  299. }
  300. }
  301. }
  302. // readRawOrRCDATA reads until the next "</foo>", where "foo" is z.rawTag and
  303. // is typically something like "script" or "textarea".
  304. func (z *Tokenizer) readRawOrRCDATA() {
  305. if z.rawTag == "script" {
  306. z.readScript()
  307. z.textIsRaw = true
  308. z.rawTag = ""
  309. return
  310. }
  311. loop:
  312. for {
  313. c := z.readByte()
  314. if z.err != nil {
  315. break loop
  316. }
  317. if c != '<' {
  318. continue loop
  319. }
  320. c = z.readByte()
  321. if z.err != nil {
  322. break loop
  323. }
  324. if c != '/' {
  325. continue loop
  326. }
  327. if z.readRawEndTag() || z.err != nil {
  328. break loop
  329. }
  330. }
  331. z.data.end = z.raw.end
  332. // A textarea's or title's RCDATA can contain escaped entities.
  333. z.textIsRaw = z.rawTag != "textarea" && z.rawTag != "title"
  334. z.rawTag = ""
  335. }
  336. // readRawEndTag attempts to read a tag like "</foo>", where "foo" is z.rawTag.
  337. // If it succeeds, it backs up the input position to reconsume the tag and
  338. // returns true. Otherwise it returns false. The opening "</" has already been
  339. // consumed.
  340. func (z *Tokenizer) readRawEndTag() bool {
  341. for i := 0; i < len(z.rawTag); i++ {
  342. c := z.readByte()
  343. if z.err != nil {
  344. return false
  345. }
  346. if c != z.rawTag[i] && c != z.rawTag[i]-('a'-'A') {
  347. z.raw.end--
  348. return false
  349. }
  350. }
  351. c := z.readByte()
  352. if z.err != nil {
  353. return false
  354. }
  355. switch c {
  356. case ' ', '\n', '\r', '\t', '\f', '/', '>':
  357. // The 3 is 2 for the leading "</" plus 1 for the trailing character c.
  358. z.raw.end -= 3 + len(z.rawTag)
  359. return true
  360. }
  361. z.raw.end--
  362. return false
  363. }
  364. // readScript reads until the next </script> tag, following the byzantine
  365. // rules for escaping/hiding the closing tag.
  366. func (z *Tokenizer) readScript() {
  367. defer func() {
  368. z.data.end = z.raw.end
  369. }()
  370. var c byte
  371. scriptData:
  372. c = z.readByte()
  373. if z.err != nil {
  374. return
  375. }
  376. if c == '<' {
  377. goto scriptDataLessThanSign
  378. }
  379. goto scriptData
  380. scriptDataLessThanSign:
  381. c = z.readByte()
  382. if z.err != nil {
  383. return
  384. }
  385. switch c {
  386. case '/':
  387. goto scriptDataEndTagOpen
  388. case '!':
  389. goto scriptDataEscapeStart
  390. }
  391. z.raw.end--
  392. goto scriptData
  393. scriptDataEndTagOpen:
  394. if z.readRawEndTag() || z.err != nil {
  395. return
  396. }
  397. goto scriptData
  398. scriptDataEscapeStart:
  399. c = z.readByte()
  400. if z.err != nil {
  401. return
  402. }
  403. if c == '-' {
  404. goto scriptDataEscapeStartDash
  405. }
  406. z.raw.end--
  407. goto scriptData
  408. scriptDataEscapeStartDash:
  409. c = z.readByte()
  410. if z.err != nil {
  411. return
  412. }
  413. if c == '-' {
  414. goto scriptDataEscapedDashDash
  415. }
  416. z.raw.end--
  417. goto scriptData
  418. scriptDataEscaped:
  419. c = z.readByte()
  420. if z.err != nil {
  421. return
  422. }
  423. switch c {
  424. case '-':
  425. goto scriptDataEscapedDash
  426. case '<':
  427. goto scriptDataEscapedLessThanSign
  428. }
  429. goto scriptDataEscaped
  430. scriptDataEscapedDash:
  431. c = z.readByte()
  432. if z.err != nil {
  433. return
  434. }
  435. switch c {
  436. case '-':
  437. goto scriptDataEscapedDashDash
  438. case '<':
  439. goto scriptDataEscapedLessThanSign
  440. }
  441. goto scriptDataEscaped
  442. scriptDataEscapedDashDash:
  443. c = z.readByte()
  444. if z.err != nil {
  445. return
  446. }
  447. switch c {
  448. case '-':
  449. goto scriptDataEscapedDashDash
  450. case '<':
  451. goto scriptDataEscapedLessThanSign
  452. case '>':
  453. goto scriptData
  454. }
  455. goto scriptDataEscaped
  456. scriptDataEscapedLessThanSign:
  457. c = z.readByte()
  458. if z.err != nil {
  459. return
  460. }
  461. if c == '/' {
  462. goto scriptDataEscapedEndTagOpen
  463. }
  464. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
  465. goto scriptDataDoubleEscapeStart
  466. }
  467. z.raw.end--
  468. goto scriptData
  469. scriptDataEscapedEndTagOpen:
  470. if z.readRawEndTag() || z.err != nil {
  471. return
  472. }
  473. goto scriptDataEscaped
  474. scriptDataDoubleEscapeStart:
  475. z.raw.end--
  476. for i := 0; i < len("script"); i++ {
  477. c = z.readByte()
  478. if z.err != nil {
  479. return
  480. }
  481. if c != "script"[i] && c != "SCRIPT"[i] {
  482. z.raw.end--
  483. goto scriptDataEscaped
  484. }
  485. }
  486. c = z.readByte()
  487. if z.err != nil {
  488. return
  489. }
  490. switch c {
  491. case ' ', '\n', '\r', '\t', '\f', '/', '>':
  492. goto scriptDataDoubleEscaped
  493. }
  494. z.raw.end--
  495. goto scriptDataEscaped
  496. scriptDataDoubleEscaped:
  497. c = z.readByte()
  498. if z.err != nil {
  499. return
  500. }
  501. switch c {
  502. case '-':
  503. goto scriptDataDoubleEscapedDash
  504. case '<':
  505. goto scriptDataDoubleEscapedLessThanSign
  506. }
  507. goto scriptDataDoubleEscaped
  508. scriptDataDoubleEscapedDash:
  509. c = z.readByte()
  510. if z.err != nil {
  511. return
  512. }
  513. switch c {
  514. case '-':
  515. goto scriptDataDoubleEscapedDashDash
  516. case '<':
  517. goto scriptDataDoubleEscapedLessThanSign
  518. }
  519. goto scriptDataDoubleEscaped
  520. scriptDataDoubleEscapedDashDash:
  521. c = z.readByte()
  522. if z.err != nil {
  523. return
  524. }
  525. switch c {
  526. case '-':
  527. goto scriptDataDoubleEscapedDashDash
  528. case '<':
  529. goto scriptDataDoubleEscapedLessThanSign
  530. case '>':
  531. goto scriptData
  532. }
  533. goto scriptDataDoubleEscaped
  534. scriptDataDoubleEscapedLessThanSign:
  535. c = z.readByte()
  536. if z.err != nil {
  537. return
  538. }
  539. if c == '/' {
  540. goto scriptDataDoubleEscapeEnd
  541. }
  542. z.raw.end--
  543. goto scriptDataDoubleEscaped
  544. scriptDataDoubleEscapeEnd:
  545. if z.readRawEndTag() {
  546. z.raw.end += len("</script>")
  547. goto scriptDataEscaped
  548. }
  549. if z.err != nil {
  550. return
  551. }
  552. goto scriptDataDoubleEscaped
  553. }
  554. // readComment reads the next comment token starting with "<!--". The opening
  555. // "<!--" has already been consumed.
  556. func (z *Tokenizer) readComment() {
  557. z.data.start = z.raw.end
  558. defer func() {
  559. if z.data.end < z.data.start {
  560. // It's a comment with no data, like <!-->.
  561. z.data.end = z.data.start
  562. }
  563. }()
  564. for dashCount := 2; ; {
  565. c := z.readByte()
  566. if z.err != nil {
  567. // Ignore up to two dashes at EOF.
  568. if dashCount > 2 {
  569. dashCount = 2
  570. }
  571. z.data.end = z.raw.end - dashCount
  572. return
  573. }
  574. switch c {
  575. case '-':
  576. dashCount++
  577. continue
  578. case '>':
  579. if dashCount >= 2 {
  580. z.data.end = z.raw.end - len("-->")
  581. return
  582. }
  583. case '!':
  584. if dashCount >= 2 {
  585. c = z.readByte()
  586. if z.err != nil {
  587. z.data.end = z.raw.end
  588. return
  589. }
  590. if c == '>' {
  591. z.data.end = z.raw.end - len("--!>")
  592. return
  593. }
  594. }
  595. }
  596. dashCount = 0
  597. }
  598. }
  599. // readUntilCloseAngle reads until the next ">".
  600. func (z *Tokenizer) readUntilCloseAngle() {
  601. z.data.start = z.raw.end
  602. for {
  603. c := z.readByte()
  604. if z.err != nil {
  605. z.data.end = z.raw.end
  606. return
  607. }
  608. if c == '>' {
  609. z.data.end = z.raw.end - len(">")
  610. return
  611. }
  612. }
  613. }
  614. // readMarkupDeclaration reads the next token starting with "<!". It might be
  615. // a "<!--comment-->", a "<!DOCTYPE foo>", a "<![CDATA[section]]>" or
  616. // "<!a bogus comment". The opening "<!" has already been consumed.
  617. func (z *Tokenizer) readMarkupDeclaration() TokenType {
  618. z.data.start = z.raw.end
  619. var c [2]byte
  620. for i := 0; i < 2; i++ {
  621. c[i] = z.readByte()
  622. if z.err != nil {
  623. z.data.end = z.raw.end
  624. return CommentToken
  625. }
  626. }
  627. if c[0] == '-' && c[1] == '-' {
  628. z.readComment()
  629. return CommentToken
  630. }
  631. z.raw.end -= 2
  632. if z.readDoctype() {
  633. return DoctypeToken
  634. }
  635. if z.allowCDATA && z.readCDATA() {
  636. z.convertNUL = true
  637. return TextToken
  638. }
  639. // It's a bogus comment.
  640. z.readUntilCloseAngle()
  641. return CommentToken
  642. }
  643. // readDoctype attempts to read a doctype declaration and returns true if
  644. // successful. The opening "<!" has already been consumed.
  645. func (z *Tokenizer) readDoctype() bool {
  646. const s = "DOCTYPE"
  647. for i := 0; i < len(s); i++ {
  648. c := z.readByte()
  649. if z.err != nil {
  650. z.data.end = z.raw.end
  651. return false
  652. }
  653. if c != s[i] && c != s[i]+('a'-'A') {
  654. // Back up to read the fragment of "DOCTYPE" again.
  655. z.raw.end = z.data.start
  656. return false
  657. }
  658. }
  659. if z.skipWhiteSpace(); z.err != nil {
  660. z.data.start = z.raw.end
  661. z.data.end = z.raw.end
  662. return true
  663. }
  664. z.readUntilCloseAngle()
  665. return true
  666. }
  667. // readCDATA attempts to read a CDATA section and returns true if
  668. // successful. The opening "<!" has already been consumed.
  669. func (z *Tokenizer) readCDATA() bool {
  670. const s = "[CDATA["
  671. for i := 0; i < len(s); i++ {
  672. c := z.readByte()
  673. if z.err != nil {
  674. z.data.end = z.raw.end
  675. return false
  676. }
  677. if c != s[i] {
  678. // Back up to read the fragment of "[CDATA[" again.
  679. z.raw.end = z.data.start
  680. return false
  681. }
  682. }
  683. z.data.start = z.raw.end
  684. brackets := 0
  685. for {
  686. c := z.readByte()
  687. if z.err != nil {
  688. z.data.end = z.raw.end
  689. return true
  690. }
  691. switch c {
  692. case ']':
  693. brackets++
  694. case '>':
  695. if brackets >= 2 {
  696. z.data.end = z.raw.end - len("]]>")
  697. return true
  698. }
  699. brackets = 0
  700. default:
  701. brackets = 0
  702. }
  703. }
  704. }
  705. // startTagIn returns whether the start tag in z.buf[z.data.start:z.data.end]
  706. // case-insensitively matches any element of ss.
  707. func (z *Tokenizer) startTagIn(ss ...string) bool {
  708. loop:
  709. for _, s := range ss {
  710. if z.data.end-z.data.start != len(s) {
  711. continue loop
  712. }
  713. for i := 0; i < len(s); i++ {
  714. c := z.buf[z.data.start+i]
  715. if 'A' <= c && c <= 'Z' {
  716. c += 'a' - 'A'
  717. }
  718. if c != s[i] {
  719. continue loop
  720. }
  721. }
  722. return true
  723. }
  724. return false
  725. }
  726. // readStartTag reads the next start tag token. The opening "<a" has already
  727. // been consumed, where 'a' means anything in [A-Za-z].
  728. func (z *Tokenizer) readStartTag() TokenType {
  729. z.readTag(true)
  730. if z.err != nil {
  731. return ErrorToken
  732. }
  733. // Several tags flag the tokenizer's next token as raw.
  734. c, raw := z.buf[z.data.start], false
  735. if 'A' <= c && c <= 'Z' {
  736. c += 'a' - 'A'
  737. }
  738. switch c {
  739. case 'i':
  740. raw = z.startTagIn("iframe")
  741. case 'n':
  742. raw = z.startTagIn("noembed", "noframes", "noscript")
  743. case 'p':
  744. raw = z.startTagIn("plaintext")
  745. case 's':
  746. raw = z.startTagIn("script", "style")
  747. case 't':
  748. raw = z.startTagIn("textarea", "title")
  749. case 'x':
  750. raw = z.startTagIn("xmp")
  751. }
  752. if raw {
  753. z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end]))
  754. }
  755. // Look for a self-closing token like "<br/>".
  756. if z.err == nil && z.buf[z.raw.end-2] == '/' {
  757. return SelfClosingTagToken
  758. }
  759. return StartTagToken
  760. }
  761. // readTag reads the next tag token and its attributes. If saveAttr, those
  762. // attributes are saved in z.attr, otherwise z.attr is set to an empty slice.
  763. // The opening "<a" or "</a" has already been consumed, where 'a' means anything
  764. // in [A-Za-z].
  765. func (z *Tokenizer) readTag(saveAttr bool) {
  766. z.attr = z.attr[:0]
  767. z.nAttrReturned = 0
  768. // Read the tag name and attribute key/value pairs.
  769. z.readTagName()
  770. if z.skipWhiteSpace(); z.err != nil {
  771. return
  772. }
  773. for {
  774. c := z.readByte()
  775. if z.err != nil || c == '>' {
  776. break
  777. }
  778. z.raw.end--
  779. z.readTagAttrKey()
  780. z.readTagAttrVal()
  781. // Save pendingAttr if saveAttr and that attribute has a non-empty key.
  782. if saveAttr && z.pendingAttr[0].start != z.pendingAttr[0].end {
  783. z.attr = append(z.attr, z.pendingAttr)
  784. }
  785. if z.skipWhiteSpace(); z.err != nil {
  786. break
  787. }
  788. }
  789. }
  790. // readTagName sets z.data to the "div" in "<div k=v>". The reader (z.raw.end)
  791. // is positioned such that the first byte of the tag name (the "d" in "<div")
  792. // has already been consumed.
  793. func (z *Tokenizer) readTagName() {
  794. z.data.start = z.raw.end - 1
  795. for {
  796. c := z.readByte()
  797. if z.err != nil {
  798. z.data.end = z.raw.end
  799. return
  800. }
  801. switch c {
  802. case ' ', '\n', '\r', '\t', '\f':
  803. z.data.end = z.raw.end - 1
  804. return
  805. case '/', '>':
  806. z.raw.end--
  807. z.data.end = z.raw.end
  808. return
  809. }
  810. }
  811. }
  812. // readTagAttrKey sets z.pendingAttr[0] to the "k" in "<div k=v>".
  813. // Precondition: z.err == nil.
  814. func (z *Tokenizer) readTagAttrKey() {
  815. z.pendingAttr[0].start = z.raw.end
  816. for {
  817. c := z.readByte()
  818. if z.err != nil {
  819. z.pendingAttr[0].end = z.raw.end
  820. return
  821. }
  822. switch c {
  823. case ' ', '\n', '\r', '\t', '\f', '/':
  824. z.pendingAttr[0].end = z.raw.end - 1
  825. return
  826. case '=', '>':
  827. z.raw.end--
  828. z.pendingAttr[0].end = z.raw.end
  829. return
  830. }
  831. }
  832. }
  833. // readTagAttrVal sets z.pendingAttr[1] to the "v" in "<div k=v>".
  834. func (z *Tokenizer) readTagAttrVal() {
  835. z.pendingAttr[1].start = z.raw.end
  836. z.pendingAttr[1].end = z.raw.end
  837. if z.skipWhiteSpace(); z.err != nil {
  838. return
  839. }
  840. c := z.readByte()
  841. if z.err != nil {
  842. return
  843. }
  844. if c != '=' {
  845. z.raw.end--
  846. return
  847. }
  848. if z.skipWhiteSpace(); z.err != nil {
  849. return
  850. }
  851. quote := z.readByte()
  852. if z.err != nil {
  853. return
  854. }
  855. switch quote {
  856. case '>':
  857. z.raw.end--
  858. return
  859. case '\'', '"':
  860. z.pendingAttr[1].start = z.raw.end
  861. for {
  862. c := z.readByte()
  863. if z.err != nil {
  864. z.pendingAttr[1].end = z.raw.end
  865. return
  866. }
  867. if c == quote {
  868. z.pendingAttr[1].end = z.raw.end - 1
  869. return
  870. }
  871. }
  872. default:
  873. z.pendingAttr[1].start = z.raw.end - 1
  874. for {
  875. c := z.readByte()
  876. if z.err != nil {
  877. z.pendingAttr[1].end = z.raw.end
  878. return
  879. }
  880. switch c {
  881. case ' ', '\n', '\r', '\t', '\f':
  882. z.pendingAttr[1].end = z.raw.end - 1
  883. return
  884. case '>':
  885. z.raw.end--
  886. z.pendingAttr[1].end = z.raw.end
  887. return
  888. }
  889. }
  890. }
  891. }
  892. // Next scans the next token and returns its type.
  893. func (z *Tokenizer) Next() TokenType {
  894. z.raw.start = z.raw.end
  895. z.data.start = z.raw.end
  896. z.data.end = z.raw.end
  897. if z.err != nil {
  898. z.tt = ErrorToken
  899. return z.tt
  900. }
  901. if z.rawTag != "" {
  902. if z.rawTag == "plaintext" {
  903. // Read everything up to EOF.
  904. for z.err == nil {
  905. z.readByte()
  906. }
  907. z.data.end = z.raw.end
  908. z.textIsRaw = true
  909. } else {
  910. z.readRawOrRCDATA()
  911. }
  912. if z.data.end > z.data.start {
  913. z.tt = TextToken
  914. z.convertNUL = true
  915. return z.tt
  916. }
  917. }
  918. z.textIsRaw = false
  919. z.convertNUL = false
  920. loop:
  921. for {
  922. c := z.readByte()
  923. if z.err != nil {
  924. break loop
  925. }
  926. if c != '<' {
  927. continue loop
  928. }
  929. // Check if the '<' we have just read is part of a tag, comment
  930. // or doctype. If not, it's part of the accumulated text token.
  931. c = z.readByte()
  932. if z.err != nil {
  933. break loop
  934. }
  935. var tokenType TokenType
  936. switch {
  937. case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
  938. tokenType = StartTagToken
  939. case c == '/':
  940. tokenType = EndTagToken
  941. case c == '!' || c == '?':
  942. // We use CommentToken to mean any of "<!--actual comments-->",
  943. // "<!DOCTYPE declarations>" and "<?xml processing instructions?>".
  944. tokenType = CommentToken
  945. default:
  946. continue
  947. }
  948. // We have a non-text token, but we might have accumulated some text
  949. // before that. If so, we return the text first, and return the non-
  950. // text token on the subsequent call to Next.
  951. if x := z.raw.end - len("<a"); z.raw.start < x {
  952. z.raw.end = x
  953. z.data.end = x
  954. z.tt = TextToken
  955. return z.tt
  956. }
  957. switch tokenType {
  958. case StartTagToken:
  959. z.tt = z.readStartTag()
  960. return z.tt
  961. case EndTagToken:
  962. c = z.readByte()
  963. if z.err != nil {
  964. break loop
  965. }
  966. if c == '>' {
  967. // "</>" does not generate a token at all. Generate an empty comment
  968. // to allow passthrough clients to pick up the data using Raw.
  969. // Reset the tokenizer state and start again.
  970. z.tt = CommentToken
  971. return z.tt
  972. }
  973. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
  974. z.readTag(false)
  975. if z.err != nil {
  976. z.tt = ErrorToken
  977. } else {
  978. z.tt = EndTagToken
  979. }
  980. return z.tt
  981. }
  982. z.raw.end--
  983. z.readUntilCloseAngle()
  984. z.tt = CommentToken
  985. return z.tt
  986. case CommentToken:
  987. if c == '!' {
  988. z.tt = z.readMarkupDeclaration()
  989. return z.tt
  990. }
  991. z.raw.end--
  992. z.readUntilCloseAngle()
  993. z.tt = CommentToken
  994. return z.tt
  995. }
  996. }
  997. if z.raw.start < z.raw.end {
  998. z.data.end = z.raw.end
  999. z.tt = TextToken
  1000. return z.tt
  1001. }
  1002. z.tt = ErrorToken
  1003. return z.tt
  1004. }
  1005. // Raw returns the unmodified text of the current token. Calling Next, Token,
  1006. // Text, TagName or TagAttr may change the contents of the returned slice.
  1007. func (z *Tokenizer) Raw() []byte {
  1008. return z.buf[z.raw.start:z.raw.end]
  1009. }
  1010. // convertNewlines converts "\r" and "\r\n" in s to "\n".
  1011. // The conversion happens in place, but the resulting slice may be shorter.
  1012. func convertNewlines(s []byte) []byte {
  1013. for i, c := range s {
  1014. if c != '\r' {
  1015. continue
  1016. }
  1017. src := i + 1
  1018. if src >= len(s) || s[src] != '\n' {
  1019. s[i] = '\n'
  1020. continue
  1021. }
  1022. dst := i
  1023. for src < len(s) {
  1024. if s[src] == '\r' {
  1025. if src+1 < len(s) && s[src+1] == '\n' {
  1026. src++
  1027. }
  1028. s[dst] = '\n'
  1029. } else {
  1030. s[dst] = s[src]
  1031. }
  1032. src++
  1033. dst++
  1034. }
  1035. return s[:dst]
  1036. }
  1037. return s
  1038. }
  1039. var (
  1040. nul = []byte("\x00")
  1041. replacement = []byte("\ufffd")
  1042. )
  1043. // Text returns the unescaped text of a text, comment or doctype token. The
  1044. // contents of the returned slice may change on the next call to Next.
  1045. func (z *Tokenizer) Text() []byte {
  1046. switch z.tt {
  1047. case TextToken, CommentToken, DoctypeToken:
  1048. s := z.buf[z.data.start:z.data.end]
  1049. z.data.start = z.raw.end
  1050. z.data.end = z.raw.end
  1051. s = convertNewlines(s)
  1052. if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) {
  1053. s = bytes.Replace(s, nul, replacement, -1)
  1054. }
  1055. if !z.textIsRaw {
  1056. s = unescape(s, false)
  1057. }
  1058. return s
  1059. }
  1060. return nil
  1061. }
  1062. // TagName returns the lower-cased name of a tag token (the `img` out of
  1063. // `<IMG SRC="foo">`) and whether the tag has attributes.
  1064. // The contents of the returned slice may change on the next call to Next.
  1065. func (z *Tokenizer) TagName() (name []byte, hasAttr bool) {
  1066. if z.data.start < z.data.end {
  1067. switch z.tt {
  1068. case StartTagToken, EndTagToken, SelfClosingTagToken:
  1069. s := z.buf[z.data.start:z.data.end]
  1070. z.data.start = z.raw.end
  1071. z.data.end = z.raw.end
  1072. return lower(s), z.nAttrReturned < len(z.attr)
  1073. }
  1074. }
  1075. return nil, false
  1076. }
  1077. // TagAttr returns the lower-cased key and unescaped value of the next unparsed
  1078. // attribute for the current tag token and whether there are more attributes.
  1079. // The contents of the returned slices may change on the next call to Next.
  1080. func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) {
  1081. if z.nAttrReturned < len(z.attr) {
  1082. switch z.tt {
  1083. case StartTagToken, SelfClosingTagToken:
  1084. x := z.attr[z.nAttrReturned]
  1085. z.nAttrReturned++
  1086. key = z.buf[x[0].start:x[0].end]
  1087. val = z.buf[x[1].start:x[1].end]
  1088. return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr)
  1089. }
  1090. }
  1091. return nil, nil, false
  1092. }
  1093. // Token returns the next Token. The result's Data and Attr values remain valid
  1094. // after subsequent Next calls.
  1095. func (z *Tokenizer) Token() Token {
  1096. t := Token{Type: z.tt}
  1097. switch z.tt {
  1098. case TextToken, CommentToken, DoctypeToken:
  1099. t.Data = string(z.Text())
  1100. case StartTagToken, SelfClosingTagToken, EndTagToken:
  1101. name, moreAttr := z.TagName()
  1102. for moreAttr {
  1103. var key, val []byte
  1104. key, val, moreAttr = z.TagAttr()
  1105. t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)})
  1106. }
  1107. if a := atom.Lookup(name); a != 0 {
  1108. t.DataAtom, t.Data = a, a.String()
  1109. } else {
  1110. t.DataAtom, t.Data = 0, string(name)
  1111. }
  1112. }
  1113. return t
  1114. }
  1115. // SetMaxBuf sets a limit on the amount of data buffered during tokenization.
  1116. // A value of 0 means unlimited.
  1117. func (z *Tokenizer) SetMaxBuf(n int) {
  1118. z.maxBuf = n
  1119. }
  1120. // NewTokenizer returns a new HTML Tokenizer for the given Reader.
  1121. // The input is assumed to be UTF-8 encoded.
  1122. func NewTokenizer(r io.Reader) *Tokenizer {
  1123. return NewTokenizerFragment(r, "")
  1124. }
  1125. // NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for
  1126. // tokenizing an exisitng element's InnerHTML fragment. contextTag is that
  1127. // element's tag, such as "div" or "iframe".
  1128. //
  1129. // For example, how the InnerHTML "a<b" is tokenized depends on whether it is
  1130. // for a <p> tag or a <script> tag.
  1131. //
  1132. // The input is assumed to be UTF-8 encoded.
  1133. func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer {
  1134. z := &Tokenizer{
  1135. r: r,
  1136. buf: make([]byte, 0, 4096),
  1137. }
  1138. if contextTag != "" {
  1139. switch s := strings.ToLower(contextTag); s {
  1140. case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp":
  1141. z.rawTag = s
  1142. }
  1143. }
  1144. return z
  1145. }