token.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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 (e.g. <br/>).
  793. //
  794. // Originally, we did this by just checking that the last character of the
  795. // tag (ignoring the closing bracket) was a solidus (/) character, but this
  796. // is not always accurate.
  797. //
  798. // We need to be careful that we don't misinterpret a non-self-closing tag
  799. // as self-closing, as can happen if the tag contains unquoted attribute
  800. // values (i.e. <p a=/>).
  801. //
  802. // To avoid this, we check that the last non-bracket character of the tag
  803. // (z.raw.end-2) isn't the same character as the last non-quote character of
  804. // the last attribute of the tag (z.pendingAttr[1].end-1), if the tag has
  805. // attributes.
  806. nAttrs := len(z.attr)
  807. if z.err == nil && z.buf[z.raw.end-2] == '/' && (nAttrs == 0 || z.raw.end-2 != z.attr[nAttrs-1][1].end-1) {
  808. return SelfClosingTagToken
  809. }
  810. return StartTagToken
  811. }
  812. // readTag reads the next tag token and its attributes. If saveAttr, those
  813. // attributes are saved in z.attr, otherwise z.attr is set to an empty slice.
  814. // The opening "<a" or "</a" has already been consumed, where 'a' means anything
  815. // in [A-Za-z].
  816. func (z *Tokenizer) readTag(saveAttr bool) {
  817. z.attr = z.attr[:0]
  818. z.nAttrReturned = 0
  819. // Read the tag name and attribute key/value pairs.
  820. z.readTagName()
  821. if z.skipWhiteSpace(); z.err != nil {
  822. return
  823. }
  824. for {
  825. c := z.readByte()
  826. if z.err != nil || c == '>' {
  827. break
  828. }
  829. z.raw.end--
  830. z.readTagAttrKey()
  831. z.readTagAttrVal()
  832. // Save pendingAttr if saveAttr and that attribute has a non-empty key.
  833. if saveAttr && z.pendingAttr[0].start != z.pendingAttr[0].end {
  834. z.attr = append(z.attr, z.pendingAttr)
  835. }
  836. if z.skipWhiteSpace(); z.err != nil {
  837. break
  838. }
  839. }
  840. }
  841. // readTagName sets z.data to the "div" in "<div k=v>". The reader (z.raw.end)
  842. // is positioned such that the first byte of the tag name (the "d" in "<div")
  843. // has already been consumed.
  844. func (z *Tokenizer) readTagName() {
  845. z.data.start = z.raw.end - 1
  846. for {
  847. c := z.readByte()
  848. if z.err != nil {
  849. z.data.end = z.raw.end
  850. return
  851. }
  852. switch c {
  853. case ' ', '\n', '\r', '\t', '\f':
  854. z.data.end = z.raw.end - 1
  855. return
  856. case '/', '>':
  857. z.raw.end--
  858. z.data.end = z.raw.end
  859. return
  860. }
  861. }
  862. }
  863. // readTagAttrKey sets z.pendingAttr[0] to the "k" in "<div k=v>".
  864. // Precondition: z.err == nil.
  865. func (z *Tokenizer) readTagAttrKey() {
  866. z.pendingAttr[0].start = z.raw.end
  867. for {
  868. c := z.readByte()
  869. if z.err != nil {
  870. z.pendingAttr[0].end = z.raw.end
  871. return
  872. }
  873. switch c {
  874. case '=':
  875. if z.pendingAttr[0].start+1 == z.raw.end {
  876. // WHATWG 13.2.5.32, if we see an equals sign before the attribute name
  877. // begins, we treat it as a character in the attribute name and continue.
  878. continue
  879. }
  880. fallthrough
  881. case ' ', '\n', '\r', '\t', '\f', '/', '>':
  882. // WHATWG 13.2.5.33 Attribute name state
  883. // We need to reconsume the char in the after attribute name state to support the / character
  884. z.raw.end--
  885. z.pendingAttr[0].end = z.raw.end
  886. return
  887. }
  888. }
  889. }
  890. // readTagAttrVal sets z.pendingAttr[1] to the "v" in "<div k=v>".
  891. func (z *Tokenizer) readTagAttrVal() {
  892. z.pendingAttr[1].start = z.raw.end
  893. z.pendingAttr[1].end = z.raw.end
  894. if z.skipWhiteSpace(); z.err != nil {
  895. return
  896. }
  897. c := z.readByte()
  898. if z.err != nil {
  899. return
  900. }
  901. if c == '/' {
  902. // WHATWG 13.2.5.34 After attribute name state
  903. // U+002F SOLIDUS (/) - Switch to the self-closing start tag state.
  904. return
  905. }
  906. if c != '=' {
  907. z.raw.end--
  908. return
  909. }
  910. if z.skipWhiteSpace(); z.err != nil {
  911. return
  912. }
  913. quote := z.readByte()
  914. if z.err != nil {
  915. return
  916. }
  917. switch quote {
  918. case '>':
  919. z.raw.end--
  920. return
  921. case '\'', '"':
  922. z.pendingAttr[1].start = z.raw.end
  923. for {
  924. c := z.readByte()
  925. if z.err != nil {
  926. z.pendingAttr[1].end = z.raw.end
  927. return
  928. }
  929. if c == quote {
  930. z.pendingAttr[1].end = z.raw.end - 1
  931. return
  932. }
  933. }
  934. default:
  935. z.pendingAttr[1].start = z.raw.end - 1
  936. for {
  937. c := z.readByte()
  938. if z.err != nil {
  939. z.pendingAttr[1].end = z.raw.end
  940. return
  941. }
  942. switch c {
  943. case ' ', '\n', '\r', '\t', '\f':
  944. z.pendingAttr[1].end = z.raw.end - 1
  945. return
  946. case '>':
  947. z.raw.end--
  948. z.pendingAttr[1].end = z.raw.end
  949. return
  950. }
  951. }
  952. }
  953. }
  954. // Next scans the next token and returns its type.
  955. func (z *Tokenizer) Next() TokenType {
  956. z.raw.start = z.raw.end
  957. z.data.start = z.raw.end
  958. z.data.end = z.raw.end
  959. if z.err != nil {
  960. z.tt = ErrorToken
  961. return z.tt
  962. }
  963. if z.rawTag != "" {
  964. if z.rawTag == "plaintext" {
  965. // Read everything up to EOF.
  966. for z.err == nil {
  967. z.readByte()
  968. }
  969. z.data.end = z.raw.end
  970. z.textIsRaw = true
  971. } else {
  972. z.readRawOrRCDATA()
  973. }
  974. if z.data.end > z.data.start {
  975. z.tt = TextToken
  976. z.convertNUL = true
  977. return z.tt
  978. }
  979. }
  980. z.textIsRaw = false
  981. z.convertNUL = false
  982. loop:
  983. for {
  984. c := z.readByte()
  985. if z.err != nil {
  986. break loop
  987. }
  988. if c != '<' {
  989. continue loop
  990. }
  991. // Check if the '<' we have just read is part of a tag, comment
  992. // or doctype. If not, it's part of the accumulated text token.
  993. c = z.readByte()
  994. if z.err != nil {
  995. break loop
  996. }
  997. var tokenType TokenType
  998. switch {
  999. case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
  1000. tokenType = StartTagToken
  1001. case c == '/':
  1002. tokenType = EndTagToken
  1003. case c == '!' || c == '?':
  1004. // We use CommentToken to mean any of "<!--actual comments-->",
  1005. // "<!DOCTYPE declarations>" and "<?xml processing instructions?>".
  1006. tokenType = CommentToken
  1007. default:
  1008. // Reconsume the current character.
  1009. z.raw.end--
  1010. continue
  1011. }
  1012. // We have a non-text token, but we might have accumulated some text
  1013. // before that. If so, we return the text first, and return the non-
  1014. // text token on the subsequent call to Next.
  1015. if x := z.raw.end - len("<a"); z.raw.start < x {
  1016. z.raw.end = x
  1017. z.data.end = x
  1018. z.tt = TextToken
  1019. return z.tt
  1020. }
  1021. switch tokenType {
  1022. case StartTagToken:
  1023. z.tt = z.readStartTag()
  1024. return z.tt
  1025. case EndTagToken:
  1026. c = z.readByte()
  1027. if z.err != nil {
  1028. break loop
  1029. }
  1030. if c == '>' {
  1031. // "</>" does not generate a token at all. Generate an empty comment
  1032. // to allow passthrough clients to pick up the data using Raw.
  1033. // Reset the tokenizer state and start again.
  1034. z.tt = CommentToken
  1035. return z.tt
  1036. }
  1037. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
  1038. z.readTag(false)
  1039. if z.err != nil {
  1040. z.tt = ErrorToken
  1041. } else {
  1042. z.tt = EndTagToken
  1043. }
  1044. return z.tt
  1045. }
  1046. z.raw.end--
  1047. z.readUntilCloseAngle()
  1048. z.tt = CommentToken
  1049. return z.tt
  1050. case CommentToken:
  1051. if c == '!' {
  1052. z.tt = z.readMarkupDeclaration()
  1053. return z.tt
  1054. }
  1055. z.raw.end--
  1056. z.readUntilCloseAngle()
  1057. z.tt = CommentToken
  1058. return z.tt
  1059. }
  1060. }
  1061. if z.raw.start < z.raw.end {
  1062. z.data.end = z.raw.end
  1063. z.tt = TextToken
  1064. return z.tt
  1065. }
  1066. z.tt = ErrorToken
  1067. return z.tt
  1068. }
  1069. // Raw returns the unmodified text of the current token. Calling Next, Token,
  1070. // Text, TagName or TagAttr may change the contents of the returned slice.
  1071. //
  1072. // The token stream's raw bytes partition the byte stream (up until an
  1073. // ErrorToken). There are no overlaps or gaps between two consecutive token's
  1074. // raw bytes. One implication is that the byte offset of the current token is
  1075. // the sum of the lengths of all previous tokens' raw bytes.
  1076. func (z *Tokenizer) Raw() []byte {
  1077. return z.buf[z.raw.start:z.raw.end]
  1078. }
  1079. // convertNewlines converts "\r" and "\r\n" in s to "\n".
  1080. // The conversion happens in place, but the resulting slice may be shorter.
  1081. func convertNewlines(s []byte) []byte {
  1082. for i, c := range s {
  1083. if c != '\r' {
  1084. continue
  1085. }
  1086. src := i + 1
  1087. if src >= len(s) || s[src] != '\n' {
  1088. s[i] = '\n'
  1089. continue
  1090. }
  1091. dst := i
  1092. for src < len(s) {
  1093. if s[src] == '\r' {
  1094. if src+1 < len(s) && s[src+1] == '\n' {
  1095. src++
  1096. }
  1097. s[dst] = '\n'
  1098. } else {
  1099. s[dst] = s[src]
  1100. }
  1101. src++
  1102. dst++
  1103. }
  1104. return s[:dst]
  1105. }
  1106. return s
  1107. }
  1108. var (
  1109. nul = []byte("\x00")
  1110. replacement = []byte("\ufffd")
  1111. )
  1112. // Text returns the unescaped text of a text, comment or doctype token. The
  1113. // contents of the returned slice may change on the next call to Next.
  1114. func (z *Tokenizer) Text() []byte {
  1115. switch z.tt {
  1116. case TextToken, CommentToken, DoctypeToken:
  1117. s := z.buf[z.data.start:z.data.end]
  1118. z.data.start = z.raw.end
  1119. z.data.end = z.raw.end
  1120. s = convertNewlines(s)
  1121. if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) {
  1122. s = bytes.Replace(s, nul, replacement, -1)
  1123. }
  1124. if !z.textIsRaw {
  1125. s = unescape(s, false)
  1126. }
  1127. return s
  1128. }
  1129. return nil
  1130. }
  1131. // TagName returns the lower-cased name of a tag token (the `img` out of
  1132. // `<IMG SRC="foo">`) and whether the tag has attributes.
  1133. // The contents of the returned slice may change on the next call to Next.
  1134. func (z *Tokenizer) TagName() (name []byte, hasAttr bool) {
  1135. if z.data.start < z.data.end {
  1136. switch z.tt {
  1137. case StartTagToken, EndTagToken, SelfClosingTagToken:
  1138. s := z.buf[z.data.start:z.data.end]
  1139. z.data.start = z.raw.end
  1140. z.data.end = z.raw.end
  1141. return lower(s), z.nAttrReturned < len(z.attr)
  1142. }
  1143. }
  1144. return nil, false
  1145. }
  1146. // TagAttr returns the lower-cased key and unescaped value of the next unparsed
  1147. // attribute for the current tag token and whether there are more attributes.
  1148. // The contents of the returned slices may change on the next call to Next.
  1149. func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) {
  1150. if z.nAttrReturned < len(z.attr) {
  1151. switch z.tt {
  1152. case StartTagToken, SelfClosingTagToken:
  1153. x := z.attr[z.nAttrReturned]
  1154. z.nAttrReturned++
  1155. key = z.buf[x[0].start:x[0].end]
  1156. val = z.buf[x[1].start:x[1].end]
  1157. return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr)
  1158. }
  1159. }
  1160. return nil, nil, false
  1161. }
  1162. // Token returns the current Token. The result's Data and Attr values remain
  1163. // valid after subsequent Next calls.
  1164. func (z *Tokenizer) Token() Token {
  1165. t := Token{Type: z.tt}
  1166. switch z.tt {
  1167. case TextToken, CommentToken, DoctypeToken:
  1168. t.Data = string(z.Text())
  1169. case StartTagToken, SelfClosingTagToken, EndTagToken:
  1170. name, moreAttr := z.TagName()
  1171. for moreAttr {
  1172. var key, val []byte
  1173. key, val, moreAttr = z.TagAttr()
  1174. t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)})
  1175. }
  1176. if a := atom.Lookup(name); a != 0 {
  1177. t.DataAtom, t.Data = a, a.String()
  1178. } else {
  1179. t.DataAtom, t.Data = 0, string(name)
  1180. }
  1181. }
  1182. return t
  1183. }
  1184. // SetMaxBuf sets a limit on the amount of data buffered during tokenization.
  1185. // A value of 0 means unlimited.
  1186. func (z *Tokenizer) SetMaxBuf(n int) {
  1187. z.maxBuf = n
  1188. }
  1189. // NewTokenizer returns a new HTML Tokenizer for the given Reader.
  1190. // The input is assumed to be UTF-8 encoded.
  1191. func NewTokenizer(r io.Reader) *Tokenizer {
  1192. return NewTokenizerFragment(r, "")
  1193. }
  1194. // NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for
  1195. // tokenizing an existing element's InnerHTML fragment. contextTag is that
  1196. // element's tag, such as "div" or "iframe".
  1197. //
  1198. // For example, how the InnerHTML "a<b" is tokenized depends on whether it is
  1199. // for a <p> tag or a <script> tag.
  1200. //
  1201. // The input is assumed to be UTF-8 encoded.
  1202. func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer {
  1203. z := &Tokenizer{
  1204. r: r,
  1205. buf: make([]byte, 0, 4096),
  1206. }
  1207. if contextTag != "" {
  1208. switch s := strings.ToLower(contextTag); s {
  1209. case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp":
  1210. z.rawTag = s
  1211. }
  1212. }
  1213. return z
  1214. }