github.com/Psiphon-Labs/net@v0.0.0-20191204183604-f5d60dada742/html/token.go (about)

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