token.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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 "<!--" + escapeCommentString(t.Data) + "-->"
  103. case DoctypeToken:
  104. return "<!DOCTYPE " + EscapeString(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. // When modifying this function, consider manually increasing the
  562. // maxSuffixLen constant in func TestComments, from 6 to e.g. 9 or more.
  563. // That increase should only be temporary, not committed, as it
  564. // exponentially affects the test running time.
  565. z.data.start = z.raw.end
  566. defer func() {
  567. if z.data.end < z.data.start {
  568. // It's a comment with no data, like <!-->.
  569. z.data.end = z.data.start
  570. }
  571. }()
  572. var dashCount int
  573. beginning := true
  574. for {
  575. c := z.readByte()
  576. if z.err != nil {
  577. z.data.end = z.calculateAbruptCommentDataEnd()
  578. return
  579. }
  580. switch c {
  581. case '-':
  582. dashCount++
  583. continue
  584. case '>':
  585. if dashCount >= 2 || beginning {
  586. z.data.end = z.raw.end - len("-->")
  587. return
  588. }
  589. case '!':
  590. if dashCount >= 2 {
  591. c = z.readByte()
  592. if z.err != nil {
  593. z.data.end = z.calculateAbruptCommentDataEnd()
  594. return
  595. } else if c == '>' {
  596. z.data.end = z.raw.end - len("--!>")
  597. return
  598. } else if c == '-' {
  599. dashCount = 1
  600. beginning = false
  601. continue
  602. }
  603. }
  604. }
  605. dashCount = 0
  606. beginning = false
  607. }
  608. }
  609. func (z *Tokenizer) calculateAbruptCommentDataEnd() int {
  610. raw := z.Raw()
  611. const prefixLen = len("<!--")
  612. if len(raw) >= prefixLen {
  613. raw = raw[prefixLen:]
  614. if hasSuffix(raw, "--!") {
  615. return z.raw.end - 3
  616. } else if hasSuffix(raw, "--") {
  617. return z.raw.end - 2
  618. } else if hasSuffix(raw, "-") {
  619. return z.raw.end - 1
  620. }
  621. }
  622. return z.raw.end
  623. }
  624. func hasSuffix(b []byte, suffix string) bool {
  625. if len(b) < len(suffix) {
  626. return false
  627. }
  628. b = b[len(b)-len(suffix):]
  629. for i := range b {
  630. if b[i] != suffix[i] {
  631. return false
  632. }
  633. }
  634. return true
  635. }
  636. // readUntilCloseAngle reads until the next ">".
  637. func (z *Tokenizer) readUntilCloseAngle() {
  638. z.data.start = z.raw.end
  639. for {
  640. c := z.readByte()
  641. if z.err != nil {
  642. z.data.end = z.raw.end
  643. return
  644. }
  645. if c == '>' {
  646. z.data.end = z.raw.end - len(">")
  647. return
  648. }
  649. }
  650. }
  651. // readMarkupDeclaration reads the next token starting with "<!". It might be
  652. // a "<!--comment-->", a "<!DOCTYPE foo>", a "<![CDATA[section]]>" or
  653. // "<!a bogus comment". The opening "<!" has already been consumed.
  654. func (z *Tokenizer) readMarkupDeclaration() TokenType {
  655. z.data.start = z.raw.end
  656. var c [2]byte
  657. for i := 0; i < 2; i++ {
  658. c[i] = z.readByte()
  659. if z.err != nil {
  660. z.data.end = z.raw.end
  661. return CommentToken
  662. }
  663. }
  664. if c[0] == '-' && c[1] == '-' {
  665. z.readComment()
  666. return CommentToken
  667. }
  668. z.raw.end -= 2
  669. if z.readDoctype() {
  670. return DoctypeToken
  671. }
  672. if z.allowCDATA && z.readCDATA() {
  673. z.convertNUL = true
  674. return TextToken
  675. }
  676. // It's a bogus comment.
  677. z.readUntilCloseAngle()
  678. return CommentToken
  679. }
  680. // readDoctype attempts to read a doctype declaration and returns true if
  681. // successful. The opening "<!" has already been consumed.
  682. func (z *Tokenizer) readDoctype() bool {
  683. const s = "DOCTYPE"
  684. for i := 0; i < len(s); i++ {
  685. c := z.readByte()
  686. if z.err != nil {
  687. z.data.end = z.raw.end
  688. return false
  689. }
  690. if c != s[i] && c != s[i]+('a'-'A') {
  691. // Back up to read the fragment of "DOCTYPE" again.
  692. z.raw.end = z.data.start
  693. return false
  694. }
  695. }
  696. if z.skipWhiteSpace(); z.err != nil {
  697. z.data.start = z.raw.end
  698. z.data.end = z.raw.end
  699. return true
  700. }
  701. z.readUntilCloseAngle()
  702. return true
  703. }
  704. // readCDATA attempts to read a CDATA section and returns true if
  705. // successful. The opening "<!" has already been consumed.
  706. func (z *Tokenizer) readCDATA() bool {
  707. const s = "[CDATA["
  708. for i := 0; i < len(s); i++ {
  709. c := z.readByte()
  710. if z.err != nil {
  711. z.data.end = z.raw.end
  712. return false
  713. }
  714. if c != s[i] {
  715. // Back up to read the fragment of "[CDATA[" again.
  716. z.raw.end = z.data.start
  717. return false
  718. }
  719. }
  720. z.data.start = z.raw.end
  721. brackets := 0
  722. for {
  723. c := z.readByte()
  724. if z.err != nil {
  725. z.data.end = z.raw.end
  726. return true
  727. }
  728. switch c {
  729. case ']':
  730. brackets++
  731. case '>':
  732. if brackets >= 2 {
  733. z.data.end = z.raw.end - len("]]>")
  734. return true
  735. }
  736. brackets = 0
  737. default:
  738. brackets = 0
  739. }
  740. }
  741. }
  742. // startTagIn returns whether the start tag in z.buf[z.data.start:z.data.end]
  743. // case-insensitively matches any element of ss.
  744. func (z *Tokenizer) startTagIn(ss ...string) bool {
  745. loop:
  746. for _, s := range ss {
  747. if z.data.end-z.data.start != len(s) {
  748. continue loop
  749. }
  750. for i := 0; i < len(s); i++ {
  751. c := z.buf[z.data.start+i]
  752. if 'A' <= c && c <= 'Z' {
  753. c += 'a' - 'A'
  754. }
  755. if c != s[i] {
  756. continue loop
  757. }
  758. }
  759. return true
  760. }
  761. return false
  762. }
  763. // readStartTag reads the next start tag token. The opening "<a" has already
  764. // been consumed, where 'a' means anything in [A-Za-z].
  765. func (z *Tokenizer) readStartTag() TokenType {
  766. z.readTag(true)
  767. if z.err != nil {
  768. return ErrorToken
  769. }
  770. // Several tags flag the tokenizer's next token as raw.
  771. c, raw := z.buf[z.data.start], false
  772. if 'A' <= c && c <= 'Z' {
  773. c += 'a' - 'A'
  774. }
  775. switch c {
  776. case 'i':
  777. raw = z.startTagIn("iframe")
  778. case 'n':
  779. raw = z.startTagIn("noembed", "noframes", "noscript")
  780. case 'p':
  781. raw = z.startTagIn("plaintext")
  782. case 's':
  783. raw = z.startTagIn("script", "style")
  784. case 't':
  785. raw = z.startTagIn("textarea", "title")
  786. case 'x':
  787. raw = z.startTagIn("xmp")
  788. }
  789. if raw {
  790. z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end]))
  791. }
  792. // Look for a self-closing token like "<br/>".
  793. if z.err == nil && z.buf[z.raw.end-2] == '/' {
  794. return SelfClosingTagToken
  795. }
  796. return StartTagToken
  797. }
  798. // readTag reads the next tag token and its attributes. If saveAttr, those
  799. // attributes are saved in z.attr, otherwise z.attr is set to an empty slice.
  800. // The opening "<a" or "</a" has already been consumed, where 'a' means anything
  801. // in [A-Za-z].
  802. func (z *Tokenizer) readTag(saveAttr bool) {
  803. z.attr = z.attr[:0]
  804. z.nAttrReturned = 0
  805. // Read the tag name and attribute key/value pairs.
  806. z.readTagName()
  807. if z.skipWhiteSpace(); z.err != nil {
  808. return
  809. }
  810. for {
  811. c := z.readByte()
  812. if z.err != nil || c == '>' {
  813. break
  814. }
  815. z.raw.end--
  816. z.readTagAttrKey()
  817. z.readTagAttrVal()
  818. // Save pendingAttr if saveAttr and that attribute has a non-empty key.
  819. if saveAttr && z.pendingAttr[0].start != z.pendingAttr[0].end {
  820. z.attr = append(z.attr, z.pendingAttr)
  821. }
  822. if z.skipWhiteSpace(); z.err != nil {
  823. break
  824. }
  825. }
  826. }
  827. // readTagName sets z.data to the "div" in "<div k=v>". The reader (z.raw.end)
  828. // is positioned such that the first byte of the tag name (the "d" in "<div")
  829. // has already been consumed.
  830. func (z *Tokenizer) readTagName() {
  831. z.data.start = z.raw.end - 1
  832. for {
  833. c := z.readByte()
  834. if z.err != nil {
  835. z.data.end = z.raw.end
  836. return
  837. }
  838. switch c {
  839. case ' ', '\n', '\r', '\t', '\f':
  840. z.data.end = z.raw.end - 1
  841. return
  842. case '/', '>':
  843. z.raw.end--
  844. z.data.end = z.raw.end
  845. return
  846. }
  847. }
  848. }
  849. // readTagAttrKey sets z.pendingAttr[0] to the "k" in "<div k=v>".
  850. // Precondition: z.err == nil.
  851. func (z *Tokenizer) readTagAttrKey() {
  852. z.pendingAttr[0].start = z.raw.end
  853. for {
  854. c := z.readByte()
  855. if z.err != nil {
  856. z.pendingAttr[0].end = z.raw.end
  857. return
  858. }
  859. switch c {
  860. case ' ', '\n', '\r', '\t', '\f', '/':
  861. z.pendingAttr[0].end = z.raw.end - 1
  862. return
  863. case '=':
  864. if z.pendingAttr[0].start+1 == z.raw.end {
  865. // WHATWG 13.2.5.32, if we see an equals sign before the attribute name
  866. // begins, we treat it as a character in the attribute name and continue.
  867. continue
  868. }
  869. fallthrough
  870. case '>':
  871. z.raw.end--
  872. z.pendingAttr[0].end = z.raw.end
  873. return
  874. }
  875. }
  876. }
  877. // readTagAttrVal sets z.pendingAttr[1] to the "v" in "<div k=v>".
  878. func (z *Tokenizer) readTagAttrVal() {
  879. z.pendingAttr[1].start = z.raw.end
  880. z.pendingAttr[1].end = z.raw.end
  881. if z.skipWhiteSpace(); z.err != nil {
  882. return
  883. }
  884. c := z.readByte()
  885. if z.err != nil {
  886. return
  887. }
  888. if c != '=' {
  889. z.raw.end--
  890. return
  891. }
  892. if z.skipWhiteSpace(); z.err != nil {
  893. return
  894. }
  895. quote := z.readByte()
  896. if z.err != nil {
  897. return
  898. }
  899. switch quote {
  900. case '>':
  901. z.raw.end--
  902. return
  903. case '\'', '"':
  904. z.pendingAttr[1].start = z.raw.end
  905. for {
  906. c := z.readByte()
  907. if z.err != nil {
  908. z.pendingAttr[1].end = z.raw.end
  909. return
  910. }
  911. if c == quote {
  912. z.pendingAttr[1].end = z.raw.end - 1
  913. return
  914. }
  915. }
  916. default:
  917. z.pendingAttr[1].start = z.raw.end - 1
  918. for {
  919. c := z.readByte()
  920. if z.err != nil {
  921. z.pendingAttr[1].end = z.raw.end
  922. return
  923. }
  924. switch c {
  925. case ' ', '\n', '\r', '\t', '\f':
  926. z.pendingAttr[1].end = z.raw.end - 1
  927. return
  928. case '>':
  929. z.raw.end--
  930. z.pendingAttr[1].end = z.raw.end
  931. return
  932. }
  933. }
  934. }
  935. }
  936. // Next scans the next token and returns its type.
  937. func (z *Tokenizer) Next() TokenType {
  938. z.raw.start = z.raw.end
  939. z.data.start = z.raw.end
  940. z.data.end = z.raw.end
  941. if z.err != nil {
  942. z.tt = ErrorToken
  943. return z.tt
  944. }
  945. if z.rawTag != "" {
  946. if z.rawTag == "plaintext" {
  947. // Read everything up to EOF.
  948. for z.err == nil {
  949. z.readByte()
  950. }
  951. z.data.end = z.raw.end
  952. z.textIsRaw = true
  953. } else {
  954. z.readRawOrRCDATA()
  955. }
  956. if z.data.end > z.data.start {
  957. z.tt = TextToken
  958. z.convertNUL = true
  959. return z.tt
  960. }
  961. }
  962. z.textIsRaw = false
  963. z.convertNUL = false
  964. loop:
  965. for {
  966. c := z.readByte()
  967. if z.err != nil {
  968. break loop
  969. }
  970. if c != '<' {
  971. continue loop
  972. }
  973. // Check if the '<' we have just read is part of a tag, comment
  974. // or doctype. If not, it's part of the accumulated text token.
  975. c = z.readByte()
  976. if z.err != nil {
  977. break loop
  978. }
  979. var tokenType TokenType
  980. switch {
  981. case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
  982. tokenType = StartTagToken
  983. case c == '/':
  984. tokenType = EndTagToken
  985. case c == '!' || c == '?':
  986. // We use CommentToken to mean any of "<!--actual comments-->",
  987. // "<!DOCTYPE declarations>" and "<?xml processing instructions?>".
  988. tokenType = CommentToken
  989. default:
  990. // Reconsume the current character.
  991. z.raw.end--
  992. continue
  993. }
  994. // We have a non-text token, but we might have accumulated some text
  995. // before that. If so, we return the text first, and return the non-
  996. // text token on the subsequent call to Next.
  997. if x := z.raw.end - len("<a"); z.raw.start < x {
  998. z.raw.end = x
  999. z.data.end = x
  1000. z.tt = TextToken
  1001. return z.tt
  1002. }
  1003. switch tokenType {
  1004. case StartTagToken:
  1005. z.tt = z.readStartTag()
  1006. return z.tt
  1007. case EndTagToken:
  1008. c = z.readByte()
  1009. if z.err != nil {
  1010. break loop
  1011. }
  1012. if c == '>' {
  1013. // "</>" does not generate a token at all. Generate an empty comment
  1014. // to allow passthrough clients to pick up the data using Raw.
  1015. // Reset the tokenizer state and start again.
  1016. z.tt = CommentToken
  1017. return z.tt
  1018. }
  1019. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
  1020. z.readTag(false)
  1021. if z.err != nil {
  1022. z.tt = ErrorToken
  1023. } else {
  1024. z.tt = EndTagToken
  1025. }
  1026. return z.tt
  1027. }
  1028. z.raw.end--
  1029. z.readUntilCloseAngle()
  1030. z.tt = CommentToken
  1031. return z.tt
  1032. case CommentToken:
  1033. if c == '!' {
  1034. z.tt = z.readMarkupDeclaration()
  1035. return z.tt
  1036. }
  1037. z.raw.end--
  1038. z.readUntilCloseAngle()
  1039. z.tt = CommentToken
  1040. return z.tt
  1041. }
  1042. }
  1043. if z.raw.start < z.raw.end {
  1044. z.data.end = z.raw.end
  1045. z.tt = TextToken
  1046. return z.tt
  1047. }
  1048. z.tt = ErrorToken
  1049. return z.tt
  1050. }
  1051. // Raw returns the unmodified text of the current token. Calling Next, Token,
  1052. // Text, TagName or TagAttr may change the contents of the returned slice.
  1053. //
  1054. // The token stream's raw bytes partition the byte stream (up until an
  1055. // ErrorToken). There are no overlaps or gaps between two consecutive token's
  1056. // raw bytes. One implication is that the byte offset of the current token is
  1057. // the sum of the lengths of all previous tokens' raw bytes.
  1058. func (z *Tokenizer) Raw() []byte {
  1059. return z.buf[z.raw.start:z.raw.end]
  1060. }
  1061. // convertNewlines converts "\r" and "\r\n" in s to "\n".
  1062. // The conversion happens in place, but the resulting slice may be shorter.
  1063. func convertNewlines(s []byte) []byte {
  1064. for i, c := range s {
  1065. if c != '\r' {
  1066. continue
  1067. }
  1068. src := i + 1
  1069. if src >= len(s) || s[src] != '\n' {
  1070. s[i] = '\n'
  1071. continue
  1072. }
  1073. dst := i
  1074. for src < len(s) {
  1075. if s[src] == '\r' {
  1076. if src+1 < len(s) && s[src+1] == '\n' {
  1077. src++
  1078. }
  1079. s[dst] = '\n'
  1080. } else {
  1081. s[dst] = s[src]
  1082. }
  1083. src++
  1084. dst++
  1085. }
  1086. return s[:dst]
  1087. }
  1088. return s
  1089. }
  1090. var (
  1091. nul = []byte("\x00")
  1092. replacement = []byte("\ufffd")
  1093. )
  1094. // Text returns the unescaped text of a text, comment or doctype token. The
  1095. // contents of the returned slice may change on the next call to Next.
  1096. func (z *Tokenizer) Text() []byte {
  1097. switch z.tt {
  1098. case TextToken, CommentToken, DoctypeToken:
  1099. s := z.buf[z.data.start:z.data.end]
  1100. z.data.start = z.raw.end
  1101. z.data.end = z.raw.end
  1102. s = convertNewlines(s)
  1103. if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) {
  1104. s = bytes.Replace(s, nul, replacement, -1)
  1105. }
  1106. if !z.textIsRaw {
  1107. s = unescape(s, false)
  1108. }
  1109. return s
  1110. }
  1111. return nil
  1112. }
  1113. // TagName returns the lower-cased name of a tag token (the `img` out of
  1114. // `<IMG SRC="foo">`) and whether the tag has attributes.
  1115. // The contents of the returned slice may change on the next call to Next.
  1116. func (z *Tokenizer) TagName() (name []byte, hasAttr bool) {
  1117. if z.data.start < z.data.end {
  1118. switch z.tt {
  1119. case StartTagToken, EndTagToken, SelfClosingTagToken:
  1120. s := z.buf[z.data.start:z.data.end]
  1121. z.data.start = z.raw.end
  1122. z.data.end = z.raw.end
  1123. return lower(s), z.nAttrReturned < len(z.attr)
  1124. }
  1125. }
  1126. return nil, false
  1127. }
  1128. // TagAttr returns the lower-cased key and unescaped value of the next unparsed
  1129. // attribute for the current tag token and whether there are more attributes.
  1130. // The contents of the returned slices may change on the next call to Next.
  1131. func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) {
  1132. if z.nAttrReturned < len(z.attr) {
  1133. switch z.tt {
  1134. case StartTagToken, SelfClosingTagToken:
  1135. x := z.attr[z.nAttrReturned]
  1136. z.nAttrReturned++
  1137. key = z.buf[x[0].start:x[0].end]
  1138. val = z.buf[x[1].start:x[1].end]
  1139. return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr)
  1140. }
  1141. }
  1142. return nil, nil, false
  1143. }
  1144. // Token returns the current Token. The result's Data and Attr values remain
  1145. // valid after subsequent Next calls.
  1146. func (z *Tokenizer) Token() Token {
  1147. t := Token{Type: z.tt}
  1148. switch z.tt {
  1149. case TextToken, CommentToken, DoctypeToken:
  1150. t.Data = string(z.Text())
  1151. case StartTagToken, SelfClosingTagToken, EndTagToken:
  1152. name, moreAttr := z.TagName()
  1153. for moreAttr {
  1154. var key, val []byte
  1155. key, val, moreAttr = z.TagAttr()
  1156. t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)})
  1157. }
  1158. if a := atom.Lookup(name); a != 0 {
  1159. t.DataAtom, t.Data = a, a.String()
  1160. } else {
  1161. t.DataAtom, t.Data = 0, string(name)
  1162. }
  1163. }
  1164. return t
  1165. }
  1166. // SetMaxBuf sets a limit on the amount of data buffered during tokenization.
  1167. // A value of 0 means unlimited.
  1168. func (z *Tokenizer) SetMaxBuf(n int) {
  1169. z.maxBuf = n
  1170. }
  1171. // NewTokenizer returns a new HTML Tokenizer for the given Reader.
  1172. // The input is assumed to be UTF-8 encoded.
  1173. func NewTokenizer(r io.Reader) *Tokenizer {
  1174. return NewTokenizerFragment(r, "")
  1175. }
  1176. // NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for
  1177. // tokenizing an existing element's InnerHTML fragment. contextTag is that
  1178. // element's tag, such as "div" or "iframe".
  1179. //
  1180. // For example, how the InnerHTML "a<b" is tokenized depends on whether it is
  1181. // for a <p> tag or a <script> tag.
  1182. //
  1183. // The input is assumed to be UTF-8 encoded.
  1184. func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer {
  1185. z := &Tokenizer{
  1186. r: r,
  1187. buf: make([]byte, 0, 4096),
  1188. }
  1189. if contextTag != "" {
  1190. switch s := strings.ToLower(contextTag); s {
  1191. case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp":
  1192. z.rawTag = s
  1193. }
  1194. }
  1195. return z
  1196. }