Coverage Report

Created: 2023-06-07 06:14

/src/libxml2/HTMLparser.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * HTMLparser.c : an HTML 4.0 non-verifying parser
3
 *
4
 * See Copyright for the status of this software.
5
 *
6
 * daniel@veillard.com
7
 */
8
9
#define IN_LIBXML
10
#include "libxml.h"
11
#ifdef LIBXML_HTML_ENABLED
12
13
#include <string.h>
14
#include <ctype.h>
15
#include <stdlib.h>
16
17
#include <libxml/xmlmemory.h>
18
#include <libxml/tree.h>
19
#include <libxml/parser.h>
20
#include <libxml/parserInternals.h>
21
#include <libxml/xmlerror.h>
22
#include <libxml/HTMLparser.h>
23
#include <libxml/HTMLtree.h>
24
#include <libxml/entities.h>
25
#include <libxml/encoding.h>
26
#include <libxml/valid.h>
27
#include <libxml/xmlIO.h>
28
#include <libxml/globals.h>
29
#include <libxml/uri.h>
30
31
#include "private/buf.h"
32
#include "private/enc.h"
33
#include "private/error.h"
34
#include "private/html.h"
35
#include "private/parser.h"
36
#include "private/tree.h"
37
38
#define HTML_MAX_NAMELEN 1000
39
0
#define HTML_PARSER_BIG_BUFFER_SIZE 1000
40
0
#define HTML_PARSER_BUFFER_SIZE 100
41
42
/* #define DEBUG */
43
/* #define DEBUG_PUSH */
44
45
static int htmlOmittedDefaultValue = 1;
46
47
xmlChar * htmlDecodeEntities(htmlParserCtxtPtr ctxt, int len,
48
           xmlChar end, xmlChar  end2, xmlChar end3);
49
static void htmlParseComment(htmlParserCtxtPtr ctxt);
50
51
/************************************************************************
52
 *                  *
53
 *    Some factorized error routines        *
54
 *                  *
55
 ************************************************************************/
56
57
/**
58
 * htmlErrMemory:
59
 * @ctxt:  an HTML parser context
60
 * @extra:  extra information
61
 *
62
 * Handle a redefinition of attribute error
63
 */
64
static void
65
htmlErrMemory(xmlParserCtxtPtr ctxt, const char *extra)
66
1
{
67
1
    if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
68
1
        (ctxt->instate == XML_PARSER_EOF))
69
0
  return;
70
1
    if (ctxt != NULL) {
71
0
        ctxt->errNo = XML_ERR_NO_MEMORY;
72
0
        ctxt->instate = XML_PARSER_EOF;
73
0
        ctxt->disableSAX = 1;
74
0
    }
75
1
    if (extra)
76
1
        __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER,
77
1
                        XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra,
78
1
                        NULL, NULL, 0, 0,
79
1
                        "Memory allocation failed : %s\n", extra);
80
0
    else
81
0
        __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER,
82
0
                        XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, NULL,
83
0
                        NULL, NULL, 0, 0, "Memory allocation failed\n");
84
1
}
85
86
/**
87
 * htmlParseErr:
88
 * @ctxt:  an HTML parser context
89
 * @error:  the error number
90
 * @msg:  the error message
91
 * @str1:  string infor
92
 * @str2:  string infor
93
 *
94
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
95
 */
96
static void LIBXML_ATTR_FORMAT(3,0)
97
htmlParseErr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
98
             const char *msg, const xmlChar *str1, const xmlChar *str2)
99
0
{
100
0
    if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
101
0
        (ctxt->instate == XML_PARSER_EOF))
102
0
  return;
103
0
    if (ctxt != NULL)
104
0
  ctxt->errNo = error;
105
0
    __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_HTML, error,
106
0
                    XML_ERR_ERROR, NULL, 0,
107
0
        (const char *) str1, (const char *) str2,
108
0
        NULL, 0, 0,
109
0
        msg, str1, str2);
110
0
    if (ctxt != NULL)
111
0
  ctxt->wellFormed = 0;
112
0
}
113
114
/**
115
 * htmlParseErrInt:
116
 * @ctxt:  an HTML parser context
117
 * @error:  the error number
118
 * @msg:  the error message
119
 * @val:  integer info
120
 *
121
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
122
 */
123
static void LIBXML_ATTR_FORMAT(3,0)
124
htmlParseErrInt(xmlParserCtxtPtr ctxt, xmlParserErrors error,
125
             const char *msg, int val)
126
0
{
127
0
    if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
128
0
        (ctxt->instate == XML_PARSER_EOF))
129
0
  return;
130
0
    if (ctxt != NULL)
131
0
  ctxt->errNo = error;
132
0
    __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_HTML, error,
133
0
                    XML_ERR_ERROR, NULL, 0, NULL, NULL,
134
0
        NULL, val, 0, msg, val);
135
0
    if (ctxt != NULL)
136
0
  ctxt->wellFormed = 0;
137
0
}
138
139
/************************************************************************
140
 *                  *
141
 *  Parser stacks related functions and macros    *
142
 *                  *
143
 ************************************************************************/
144
145
/**
146
 * htmlnamePush:
147
 * @ctxt:  an HTML parser context
148
 * @value:  the element name
149
 *
150
 * Pushes a new element name on top of the name stack
151
 *
152
 * Returns -1 in case of error, the index in the stack otherwise
153
 */
154
static int
155
htmlnamePush(htmlParserCtxtPtr ctxt, const xmlChar * value)
156
0
{
157
0
    if ((ctxt->html < 3) && (xmlStrEqual(value, BAD_CAST "head")))
158
0
        ctxt->html = 3;
159
0
    if ((ctxt->html < 10) && (xmlStrEqual(value, BAD_CAST "body")))
160
0
        ctxt->html = 10;
161
0
    if (ctxt->nameNr >= ctxt->nameMax) {
162
0
        size_t newSize = ctxt->nameMax * 2;
163
0
        const xmlChar **tmp;
164
165
0
        tmp = xmlRealloc((xmlChar **) ctxt->nameTab,
166
0
                         newSize * sizeof(ctxt->nameTab[0]));
167
0
        if (tmp == NULL) {
168
0
            htmlErrMemory(ctxt, NULL);
169
0
            return (-1);
170
0
        }
171
0
        ctxt->nameTab = tmp;
172
0
        ctxt->nameMax = newSize;
173
0
    }
174
0
    ctxt->nameTab[ctxt->nameNr] = value;
175
0
    ctxt->name = value;
176
0
    return (ctxt->nameNr++);
177
0
}
178
/**
179
 * htmlnamePop:
180
 * @ctxt: an HTML parser context
181
 *
182
 * Pops the top element name from the name stack
183
 *
184
 * Returns the name just removed
185
 */
186
static const xmlChar *
187
htmlnamePop(htmlParserCtxtPtr ctxt)
188
0
{
189
0
    const xmlChar *ret;
190
191
0
    if (ctxt->nameNr <= 0)
192
0
        return (NULL);
193
0
    ctxt->nameNr--;
194
0
    if (ctxt->nameNr < 0)
195
0
        return (NULL);
196
0
    if (ctxt->nameNr > 0)
197
0
        ctxt->name = ctxt->nameTab[ctxt->nameNr - 1];
198
0
    else
199
0
        ctxt->name = NULL;
200
0
    ret = ctxt->nameTab[ctxt->nameNr];
201
0
    ctxt->nameTab[ctxt->nameNr] = NULL;
202
0
    return (ret);
203
0
}
204
205
/**
206
 * htmlNodeInfoPush:
207
 * @ctxt:  an HTML parser context
208
 * @value:  the node info
209
 *
210
 * Pushes a new element name on top of the node info stack
211
 *
212
 * Returns 0 in case of error, the index in the stack otherwise
213
 */
214
static int
215
htmlNodeInfoPush(htmlParserCtxtPtr ctxt, htmlParserNodeInfo *value)
216
0
{
217
0
    if (ctxt->nodeInfoNr >= ctxt->nodeInfoMax) {
218
0
        if (ctxt->nodeInfoMax == 0)
219
0
                ctxt->nodeInfoMax = 5;
220
0
        ctxt->nodeInfoMax *= 2;
221
0
        ctxt->nodeInfoTab = (htmlParserNodeInfo *)
222
0
                         xmlRealloc((htmlParserNodeInfo *)ctxt->nodeInfoTab,
223
0
                                    ctxt->nodeInfoMax *
224
0
                                    sizeof(ctxt->nodeInfoTab[0]));
225
0
        if (ctxt->nodeInfoTab == NULL) {
226
0
            htmlErrMemory(ctxt, NULL);
227
0
            return (0);
228
0
        }
229
0
    }
230
0
    ctxt->nodeInfoTab[ctxt->nodeInfoNr] = *value;
231
0
    ctxt->nodeInfo = &ctxt->nodeInfoTab[ctxt->nodeInfoNr];
232
0
    return (ctxt->nodeInfoNr++);
233
0
}
234
235
/**
236
 * htmlNodeInfoPop:
237
 * @ctxt:  an HTML parser context
238
 *
239
 * Pops the top element name from the node info stack
240
 *
241
 * Returns 0 in case of error, the pointer to NodeInfo otherwise
242
 */
243
static htmlParserNodeInfo *
244
htmlNodeInfoPop(htmlParserCtxtPtr ctxt)
245
0
{
246
0
    if (ctxt->nodeInfoNr <= 0)
247
0
        return (NULL);
248
0
    ctxt->nodeInfoNr--;
249
0
    if (ctxt->nodeInfoNr < 0)
250
0
        return (NULL);
251
0
    if (ctxt->nodeInfoNr > 0)
252
0
        ctxt->nodeInfo = &ctxt->nodeInfoTab[ctxt->nodeInfoNr - 1];
253
0
    else
254
0
        ctxt->nodeInfo = NULL;
255
0
    return &ctxt->nodeInfoTab[ctxt->nodeInfoNr];
256
0
}
257
258
/*
259
 * Macros for accessing the content. Those should be used only by the parser,
260
 * and not exported.
261
 *
262
 * Dirty macros, i.e. one need to make assumption on the context to use them
263
 *
264
 *   CUR_PTR return the current pointer to the xmlChar to be parsed.
265
 *   CUR     returns the current xmlChar value, i.e. a 8 bit value if compiled
266
 *           in ISO-Latin or UTF-8, and the current 16 bit value if compiled
267
 *           in UNICODE mode. This should be used internally by the parser
268
 *           only to compare to ASCII values otherwise it would break when
269
 *           running with UTF-8 encoding.
270
 *   NXT(n)  returns the n'th next xmlChar. Same as CUR is should be used only
271
 *           to compare on ASCII based substring.
272
 *   UPP(n)  returns the n'th next xmlChar converted to uppercase. Same as CUR
273
 *           it should be used only to compare on ASCII based substring.
274
 *   SKIP(n) Skip n xmlChar, and must also be used only to skip ASCII defined
275
 *           strings without newlines within the parser.
276
 *
277
 * Clean macros, not dependent of an ASCII context, expect UTF-8 encoding
278
 *
279
 *   NEXT    Skip to the next character, this does the proper decoding
280
 *           in UTF-8 mode. It also pop-up unfinished entities on the fly.
281
 *   NEXTL(l) Skip the current unicode character of l xmlChars long.
282
 *   COPY(to) copy one char to *to, increment CUR_PTR and to accordingly
283
 */
284
285
0
#define UPPER (toupper(*ctxt->input->cur))
286
287
0
#define SKIP(val) ctxt->input->cur += (val),ctxt->input->col+=(val)
288
289
0
#define NXT(val) ctxt->input->cur[(val)]
290
291
0
#define UPP(val) (toupper(ctxt->input->cur[(val)]))
292
293
0
#define CUR_PTR ctxt->input->cur
294
0
#define BASE_PTR ctxt->input->base
295
296
0
#define SHRINK if ((ctxt->input->cur - ctxt->input->base > 2 * INPUT_CHUNK) && \
297
0
       (ctxt->input->end - ctxt->input->cur < 2 * INPUT_CHUNK)) \
298
0
  xmlParserShrink(ctxt)
299
300
0
#define GROW if ((ctxt->progressive == 0) &&       \
301
0
     (ctxt->input->end - ctxt->input->cur < INPUT_CHUNK))  \
302
0
  xmlParserGrow(ctxt)
303
304
0
#define SKIP_BLANKS htmlSkipBlankChars(ctxt)
305
306
/* Imported from XML */
307
308
0
#define CUR (*ctxt->input->cur)
309
0
#define NEXT xmlNextChar(ctxt)
310
311
0
#define RAW (ctxt->token ? -1 : (*ctxt->input->cur))
312
313
314
0
#define NEXTL(l) do {             \
315
0
    if (*(ctxt->input->cur) == '\n') {         \
316
0
  ctxt->input->line++; ctxt->input->col = 1;      \
317
0
    } else ctxt->input->col++;           \
318
0
    ctxt->token = 0; ctxt->input->cur += l;       \
319
0
  } while (0)
320
321
/************
322
    \
323
    if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt); \
324
    if (*ctxt->input->cur == '&') xmlParserHandleReference(ctxt);
325
 ************/
326
327
0
#define CUR_CHAR(l) htmlCurrentChar(ctxt, &l)
328
#define CUR_SCHAR(s, l) xmlStringCurrentChar(ctxt, s, &l)
329
330
#define COPY_BUF(l,b,i,v)           \
331
0
    if (l == 1) b[i++] = v;           \
332
0
    else i += xmlCopyChar(l,&b[i],v)
333
334
/**
335
 * htmlFindEncoding:
336
 * @the HTML parser context
337
 *
338
 * Ty to find and encoding in the current data available in the input
339
 * buffer this is needed to try to switch to the proper encoding when
340
 * one face a character error.
341
 * That's an heuristic, since it's operating outside of parsing it could
342
 * try to use a meta which had been commented out, that's the reason it
343
 * should only be used in case of error, not as a default.
344
 *
345
 * Returns an encoding string or NULL if not found, the string need to
346
 *   be freed
347
 */
348
static xmlChar *
349
0
htmlFindEncoding(xmlParserCtxtPtr ctxt) {
350
0
    const xmlChar *start, *cur, *end;
351
352
0
    if ((ctxt == NULL) || (ctxt->input == NULL) ||
353
0
        (ctxt->input->encoding != NULL) || (ctxt->input->buf == NULL) ||
354
0
        (ctxt->input->buf->encoder != NULL))
355
0
        return(NULL);
356
0
    if ((ctxt->input->cur == NULL) || (ctxt->input->end == NULL))
357
0
        return(NULL);
358
359
0
    start = ctxt->input->cur;
360
0
    end = ctxt->input->end;
361
    /* we also expect the input buffer to be zero terminated */
362
0
    if (*end != 0)
363
0
        return(NULL);
364
365
0
    cur = xmlStrcasestr(start, BAD_CAST "HTTP-EQUIV");
366
0
    if (cur == NULL)
367
0
        return(NULL);
368
0
    cur = xmlStrcasestr(cur, BAD_CAST  "CONTENT");
369
0
    if (cur == NULL)
370
0
        return(NULL);
371
0
    cur = xmlStrcasestr(cur, BAD_CAST  "CHARSET=");
372
0
    if (cur == NULL)
373
0
        return(NULL);
374
0
    cur += 8;
375
0
    start = cur;
376
0
    while (((*cur >= 'A') && (*cur <= 'Z')) ||
377
0
           ((*cur >= 'a') && (*cur <= 'z')) ||
378
0
           ((*cur >= '0') && (*cur <= '9')) ||
379
0
           (*cur == '-') || (*cur == '_') || (*cur == ':') || (*cur == '/'))
380
0
           cur++;
381
0
    if (cur == start)
382
0
        return(NULL);
383
0
    return(xmlStrndup(start, cur - start));
384
0
}
385
386
/**
387
 * htmlCurrentChar:
388
 * @ctxt:  the HTML parser context
389
 * @len:  pointer to the length of the char read
390
 *
391
 * The current char value, if using UTF-8 this may actually span multiple
392
 * bytes in the input buffer. Implement the end of line normalization:
393
 * 2.11 End-of-Line Handling
394
 * If the encoding is unspecified, in the case we find an ISO-Latin-1
395
 * char, then the encoding converter is plugged in automatically.
396
 *
397
 * Returns the current char value and its length
398
 */
399
400
static int
401
0
htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) {
402
0
    const unsigned char *cur;
403
0
    unsigned char c;
404
0
    unsigned int val;
405
406
0
    if (ctxt->instate == XML_PARSER_EOF)
407
0
  return(0);
408
409
0
    if (ctxt->token != 0) {
410
0
  *len = 0;
411
0
  return(ctxt->token);
412
0
    }
413
414
0
    if ((ctxt->input->end - ctxt->input->cur < INPUT_CHUNK) &&
415
0
        (xmlParserGrow(ctxt) < 0))
416
0
        return(0);
417
418
0
    if (ctxt->charset != XML_CHAR_ENCODING_UTF8) {
419
0
        xmlChar * guess;
420
0
        xmlCharEncodingHandlerPtr handler;
421
422
        /*
423
         * Assume it's a fixed length encoding (1) with
424
         * a compatible encoding for the ASCII set, since
425
         * HTML constructs only use < 128 chars
426
         */
427
0
        if (*ctxt->input->cur < 0x80) {
428
0
            *len = 1;
429
0
            if ((*ctxt->input->cur == 0) &&
430
0
                (ctxt->input->cur < ctxt->input->end)) {
431
0
                htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
432
0
                                "Char 0x%X out of allowed range\n", 0);
433
0
                return(' ');
434
0
            }
435
0
            return(*ctxt->input->cur);
436
0
        }
437
438
        /*
439
         * Humm this is bad, do an automatic flow conversion
440
         */
441
0
        guess = htmlFindEncoding(ctxt);
442
0
        if (guess == NULL) {
443
0
            xmlSwitchEncoding(ctxt, XML_CHAR_ENCODING_8859_1);
444
0
        } else {
445
0
            if (ctxt->input->encoding != NULL)
446
0
                xmlFree((xmlChar *) ctxt->input->encoding);
447
0
            ctxt->input->encoding = guess;
448
0
            handler = xmlFindCharEncodingHandler((const char *) guess);
449
0
            if (handler != NULL) {
450
                /*
451
                 * Don't use UTF-8 encoder which isn't required and
452
                 * can produce invalid UTF-8.
453
                 */
454
0
                if (!xmlStrEqual(BAD_CAST handler->name, BAD_CAST "UTF-8"))
455
0
                    xmlSwitchToEncoding(ctxt, handler);
456
0
            } else {
457
0
                htmlParseErr(ctxt, XML_ERR_INVALID_ENCODING,
458
0
                             "Unsupported encoding %s", guess, NULL);
459
0
            }
460
0
        }
461
0
        ctxt->charset = XML_CHAR_ENCODING_UTF8;
462
0
    }
463
464
    /*
465
     * We are supposed to handle UTF8, check it's valid
466
     * From rfc2044: encoding of the Unicode values on UTF-8:
467
     *
468
     * UCS-4 range (hex.)           UTF-8 octet sequence (binary)
469
     * 0000 0000-0000 007F   0xxxxxxx
470
     * 0000 0080-0000 07FF   110xxxxx 10xxxxxx
471
     * 0000 0800-0000 FFFF   1110xxxx 10xxxxxx 10xxxxxx
472
     *
473
     * Check for the 0x110000 limit too
474
     */
475
0
    cur = ctxt->input->cur;
476
0
    c = *cur;
477
0
    if (c & 0x80) {
478
0
        size_t avail;
479
480
0
        if ((c & 0x40) == 0)
481
0
            goto encoding_error;
482
483
0
        avail = ctxt->input->end - ctxt->input->cur;
484
485
0
        if ((avail < 2) || ((cur[1] & 0xc0) != 0x80))
486
0
            goto encoding_error;
487
0
        if ((c & 0xe0) == 0xe0) {
488
0
            if ((avail < 3) || ((cur[2] & 0xc0) != 0x80))
489
0
                goto encoding_error;
490
0
            if ((c & 0xf0) == 0xf0) {
491
0
                if (((c & 0xf8) != 0xf0) ||
492
0
                    (avail < 4) || ((cur[3] & 0xc0) != 0x80))
493
0
                    goto encoding_error;
494
                /* 4-byte code */
495
0
                *len = 4;
496
0
                val = (cur[0] & 0x7) << 18;
497
0
                val |= (cur[1] & 0x3f) << 12;
498
0
                val |= (cur[2] & 0x3f) << 6;
499
0
                val |= cur[3] & 0x3f;
500
0
                if (val < 0x10000)
501
0
                    goto encoding_error;
502
0
            } else {
503
              /* 3-byte code */
504
0
                *len = 3;
505
0
                val = (cur[0] & 0xf) << 12;
506
0
                val |= (cur[1] & 0x3f) << 6;
507
0
                val |= cur[2] & 0x3f;
508
0
                if (val < 0x800)
509
0
                    goto encoding_error;
510
0
            }
511
0
        } else {
512
          /* 2-byte code */
513
0
            *len = 2;
514
0
            val = (cur[0] & 0x1f) << 6;
515
0
            val |= cur[1] & 0x3f;
516
0
            if (val < 0x80)
517
0
                goto encoding_error;
518
0
        }
519
0
        if (!IS_CHAR(val)) {
520
0
            htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
521
0
                            "Char 0x%X out of allowed range\n", val);
522
0
        }
523
0
        return(val);
524
0
    } else {
525
0
        if ((*ctxt->input->cur == 0) &&
526
0
            (ctxt->input->cur < ctxt->input->end)) {
527
0
            htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
528
0
                            "Char 0x%X out of allowed range\n", 0);
529
0
            *len = 1;
530
0
            return(' ');
531
0
        }
532
        /* 1-byte code */
533
0
        *len = 1;
534
0
        return(*ctxt->input->cur);
535
0
    }
536
537
0
encoding_error:
538
    /*
539
     * If we detect an UTF8 error that probably mean that the
540
     * input encoding didn't get properly advertised in the
541
     * declaration header. Report the error and switch the encoding
542
     * to ISO-Latin-1 (if you don't like this policy, just declare the
543
     * encoding !)
544
     */
545
0
    {
546
0
        char buffer[150];
547
548
0
  if (ctxt->input->end - ctxt->input->cur >= 4) {
549
0
      snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n",
550
0
          ctxt->input->cur[0], ctxt->input->cur[1],
551
0
          ctxt->input->cur[2], ctxt->input->cur[3]);
552
0
  } else {
553
0
      snprintf(buffer, 149, "Bytes: 0x%02X\n", ctxt->input->cur[0]);
554
0
  }
555
0
  htmlParseErr(ctxt, XML_ERR_INVALID_ENCODING,
556
0
         "Input is not proper UTF-8, indicate encoding !\n",
557
0
         BAD_CAST buffer, NULL);
558
0
    }
559
560
    /*
561
     * Don't switch encodings twice. Note that if there's an encoder, we
562
     * shouldn't receive invalid UTF-8 anyway.
563
     *
564
     * Note that if ctxt->input->buf == NULL, switching encodings is
565
     * impossible, see Gitlab issue #34.
566
     */
567
0
    if ((ctxt->input->buf != NULL) &&
568
0
        (ctxt->input->buf->encoder == NULL))
569
0
        xmlSwitchEncoding(ctxt, XML_CHAR_ENCODING_8859_1);
570
0
    *len = 1;
571
0
    return(*ctxt->input->cur);
572
0
}
573
574
/**
575
 * htmlSkipBlankChars:
576
 * @ctxt:  the HTML parser context
577
 *
578
 * skip all blanks character found at that point in the input streams.
579
 *
580
 * Returns the number of space chars skipped
581
 */
582
583
static int
584
0
htmlSkipBlankChars(xmlParserCtxtPtr ctxt) {
585
0
    int res = 0;
586
587
0
    while (IS_BLANK_CH(*(ctxt->input->cur))) {
588
0
        if (*(ctxt->input->cur) == '\n') {
589
0
            ctxt->input->line++; ctxt->input->col = 1;
590
0
        } else ctxt->input->col++;
591
0
        ctxt->input->cur++;
592
0
        if (*ctxt->input->cur == 0)
593
0
            xmlParserGrow(ctxt);
594
0
  if (res < INT_MAX)
595
0
      res++;
596
0
    }
597
0
    return(res);
598
0
}
599
600
601
602
/************************************************************************
603
 *                  *
604
 *  The list of HTML elements and their properties    *
605
 *                  *
606
 ************************************************************************/
607
608
/*
609
 *  Start Tag: 1 means the start tag can be omitted
610
 *  End Tag:   1 means the end tag can be omitted
611
 *             2 means it's forbidden (empty elements)
612
 *             3 means the tag is stylistic and should be closed easily
613
 *  Depr:      this element is deprecated
614
 *  DTD:       1 means that this element is valid only in the Loose DTD
615
 *             2 means that this element is valid only in the Frameset DTD
616
 *
617
 * Name,Start Tag,End Tag,Save End,Empty,Deprecated,DTD,inline,Description
618
  , subElements , impliedsubelt , Attributes, userdata
619
 */
620
621
/* Definitions and a couple of vars for HTML Elements */
622
623
#define FONTSTYLE "tt", "i", "b", "u", "s", "strike", "big", "small"
624
#define NB_FONTSTYLE 8
625
#define PHRASE "em", "strong", "dfn", "code", "samp", "kbd", "var", "cite", "abbr", "acronym"
626
#define NB_PHRASE 10
627
#define SPECIAL "a", "img", "applet", "embed", "object", "font", "basefont", "br", "script", "map", "q", "sub", "sup", "span", "bdo", "iframe"
628
#define NB_SPECIAL 16
629
#define INLINE FONTSTYLE, PHRASE, SPECIAL, FORMCTRL
630
#define NB_INLINE NB_PCDATA + NB_FONTSTYLE + NB_PHRASE + NB_SPECIAL + NB_FORMCTRL
631
#define BLOCK HEADING, LIST, "pre", "p", "dl", "div", "center", "noscript", "noframes", "blockquote", "form", "isindex", "hr", "table", "fieldset", "address"
632
#define NB_BLOCK NB_HEADING + NB_LIST + 14
633
#define FORMCTRL "input", "select", "textarea", "label", "button"
634
#define NB_FORMCTRL 5
635
#define PCDATA
636
#define NB_PCDATA 0
637
#define HEADING "h1", "h2", "h3", "h4", "h5", "h6"
638
#define NB_HEADING 6
639
#define LIST "ul", "ol", "dir", "menu"
640
#define NB_LIST 4
641
#define MODIFIER
642
#define NB_MODIFIER 0
643
#define FLOW BLOCK,INLINE
644
#define NB_FLOW NB_BLOCK + NB_INLINE
645
#define EMPTY NULL
646
647
648
static const char* const html_flow[] = { FLOW, NULL } ;
649
static const char* const html_inline[] = { INLINE, NULL } ;
650
651
/* placeholders: elts with content but no subelements */
652
static const char* const html_pcdata[] = { NULL } ;
653
#define html_cdata html_pcdata
654
655
656
/* ... and for HTML Attributes */
657
658
#define COREATTRS "id", "class", "style", "title"
659
#define NB_COREATTRS 4
660
#define I18N "lang", "dir"
661
#define NB_I18N 2
662
#define EVENTS "onclick", "ondblclick", "onmousedown", "onmouseup", "onmouseover", "onmouseout", "onkeypress", "onkeydown", "onkeyup"
663
#define NB_EVENTS 9
664
#define ATTRS COREATTRS,I18N,EVENTS
665
#define NB_ATTRS NB_NB_COREATTRS + NB_I18N + NB_EVENTS
666
#define CELLHALIGN "align", "char", "charoff"
667
#define NB_CELLHALIGN 3
668
#define CELLVALIGN "valign"
669
#define NB_CELLVALIGN 1
670
671
static const char* const html_attrs[] = { ATTRS, NULL } ;
672
static const char* const core_i18n_attrs[] = { COREATTRS, I18N, NULL } ;
673
static const char* const core_attrs[] = { COREATTRS, NULL } ;
674
static const char* const i18n_attrs[] = { I18N, NULL } ;
675
676
677
/* Other declarations that should go inline ... */
678
static const char* const a_attrs[] = { ATTRS, "charset", "type", "name",
679
  "href", "hreflang", "rel", "rev", "accesskey", "shape", "coords",
680
  "tabindex", "onfocus", "onblur", NULL } ;
681
static const char* const target_attr[] = { "target", NULL } ;
682
static const char* const rows_cols_attr[] = { "rows", "cols", NULL } ;
683
static const char* const alt_attr[] = { "alt", NULL } ;
684
static const char* const src_alt_attrs[] = { "src", "alt", NULL } ;
685
static const char* const href_attrs[] = { "href", NULL } ;
686
static const char* const clear_attrs[] = { "clear", NULL } ;
687
static const char* const inline_p[] = { INLINE, "p", NULL } ;
688
689
static const char* const flow_param[] = { FLOW, "param", NULL } ;
690
static const char* const applet_attrs[] = { COREATTRS , "codebase",
691
    "archive", "alt", "name", "height", "width", "align",
692
    "hspace", "vspace", NULL } ;
693
static const char* const area_attrs[] = { "shape", "coords", "href", "nohref",
694
  "tabindex", "accesskey", "onfocus", "onblur", NULL } ;
695
static const char* const basefont_attrs[] =
696
  { "id", "size", "color", "face", NULL } ;
697
static const char* const quote_attrs[] = { ATTRS, "cite", NULL } ;
698
static const char* const body_contents[] = { FLOW, "ins", "del", NULL } ;
699
static const char* const body_attrs[] = { ATTRS, "onload", "onunload", NULL } ;
700
static const char* const body_depr[] = { "background", "bgcolor", "text",
701
  "link", "vlink", "alink", NULL } ;
702
static const char* const button_attrs[] = { ATTRS, "name", "value", "type",
703
  "disabled", "tabindex", "accesskey", "onfocus", "onblur", NULL } ;
704
705
706
static const char* const col_attrs[] = { ATTRS, "span", "width", CELLHALIGN, CELLVALIGN, NULL } ;
707
static const char* const col_elt[] = { "col", NULL } ;
708
static const char* const edit_attrs[] = { ATTRS, "datetime", "cite", NULL } ;
709
static const char* const compact_attrs[] = { ATTRS, "compact", NULL } ;
710
static const char* const dl_contents[] = { "dt", "dd", NULL } ;
711
static const char* const compact_attr[] = { "compact", NULL } ;
712
static const char* const label_attr[] = { "label", NULL } ;
713
static const char* const fieldset_contents[] = { FLOW, "legend" } ;
714
static const char* const font_attrs[] = { COREATTRS, I18N, "size", "color", "face" , NULL } ;
715
static const char* const form_contents[] = { HEADING, LIST, INLINE, "pre", "p", "div", "center", "noscript", "noframes", "blockquote", "isindex", "hr", "table", "fieldset", "address", NULL } ;
716
static const char* const form_attrs[] = { ATTRS, "method", "enctype", "accept", "name", "onsubmit", "onreset", "accept-charset", NULL } ;
717
static const char* const frame_attrs[] = { COREATTRS, "longdesc", "name", "src", "frameborder", "marginwidth", "marginheight", "noresize", "scrolling" , NULL } ;
718
static const char* const frameset_attrs[] = { COREATTRS, "rows", "cols", "onload", "onunload", NULL } ;
719
static const char* const frameset_contents[] = { "frameset", "frame", "noframes", NULL } ;
720
static const char* const head_attrs[] = { I18N, "profile", NULL } ;
721
static const char* const head_contents[] = { "title", "isindex", "base", "script", "style", "meta", "link", "object", NULL } ;
722
static const char* const hr_depr[] = { "align", "noshade", "size", "width", NULL } ;
723
static const char* const version_attr[] = { "version", NULL } ;
724
static const char* const html_content[] = { "head", "body", "frameset", NULL } ;
725
static const char* const iframe_attrs[] = { COREATTRS, "longdesc", "name", "src", "frameborder", "marginwidth", "marginheight", "scrolling", "align", "height", "width", NULL } ;
726
static const char* const img_attrs[] = { ATTRS, "longdesc", "name", "height", "width", "usemap", "ismap", NULL } ;
727
static const char* const embed_attrs[] = { COREATTRS, "align", "alt", "border", "code", "codebase", "frameborder", "height", "hidden", "hspace", "name", "palette", "pluginspace", "pluginurl", "src", "type", "units", "vspace", "width", NULL } ;
728
static const char* const input_attrs[] = { ATTRS, "type", "name", "value", "checked", "disabled", "readonly", "size", "maxlength", "src", "alt", "usemap", "ismap", "tabindex", "accesskey", "onfocus", "onblur", "onselect", "onchange", "accept", NULL } ;
729
static const char* const prompt_attrs[] = { COREATTRS, I18N, "prompt", NULL } ;
730
static const char* const label_attrs[] = { ATTRS, "for", "accesskey", "onfocus", "onblur", NULL } ;
731
static const char* const legend_attrs[] = { ATTRS, "accesskey", NULL } ;
732
static const char* const align_attr[] = { "align", NULL } ;
733
static const char* const link_attrs[] = { ATTRS, "charset", "href", "hreflang", "type", "rel", "rev", "media", NULL } ;
734
static const char* const map_contents[] = { BLOCK, "area", NULL } ;
735
static const char* const name_attr[] = { "name", NULL } ;
736
static const char* const action_attr[] = { "action", NULL } ;
737
static const char* const blockli_elt[] = { BLOCK, "li", NULL } ;
738
static const char* const meta_attrs[] = { I18N, "http-equiv", "name", "scheme", "charset", NULL } ;
739
static const char* const content_attr[] = { "content", NULL } ;
740
static const char* const type_attr[] = { "type", NULL } ;
741
static const char* const noframes_content[] = { "body", FLOW MODIFIER, NULL } ;
742
static const char* const object_contents[] = { FLOW, "param", NULL } ;
743
static const char* const object_attrs[] = { ATTRS, "declare", "classid", "codebase", "data", "type", "codetype", "archive", "standby", "height", "width", "usemap", "name", "tabindex", NULL } ;
744
static const char* const object_depr[] = { "align", "border", "hspace", "vspace", NULL } ;
745
static const char* const ol_attrs[] = { "type", "compact", "start", NULL} ;
746
static const char* const option_elt[] = { "option", NULL } ;
747
static const char* const optgroup_attrs[] = { ATTRS, "disabled", NULL } ;
748
static const char* const option_attrs[] = { ATTRS, "disabled", "label", "selected", "value", NULL } ;
749
static const char* const param_attrs[] = { "id", "value", "valuetype", "type", NULL } ;
750
static const char* const width_attr[] = { "width", NULL } ;
751
static const char* const pre_content[] = { PHRASE, "tt", "i", "b", "u", "s", "strike", "a", "br", "script", "map", "q", "span", "bdo", "iframe", NULL } ;
752
static const char* const script_attrs[] = { "charset", "src", "defer", "event", "for", NULL } ;
753
static const char* const language_attr[] = { "language", NULL } ;
754
static const char* const select_content[] = { "optgroup", "option", NULL } ;
755
static const char* const select_attrs[] = { ATTRS, "name", "size", "multiple", "disabled", "tabindex", "onfocus", "onblur", "onchange", NULL } ;
756
static const char* const style_attrs[] = { I18N, "media", "title", NULL } ;
757
static const char* const table_attrs[] = { ATTRS, "summary", "width", "border", "frame", "rules", "cellspacing", "cellpadding", "datapagesize", NULL } ;
758
static const char* const table_depr[] = { "align", "bgcolor", NULL } ;
759
static const char* const table_contents[] = { "caption", "col", "colgroup", "thead", "tfoot", "tbody", "tr", NULL} ;
760
static const char* const tr_elt[] = { "tr", NULL } ;
761
static const char* const talign_attrs[] = { ATTRS, CELLHALIGN, CELLVALIGN, NULL} ;
762
static const char* const th_td_depr[] = { "nowrap", "bgcolor", "width", "height", NULL } ;
763
static const char* const th_td_attr[] = { ATTRS, "abbr", "axis", "headers", "scope", "rowspan", "colspan", CELLHALIGN, CELLVALIGN, NULL } ;
764
static const char* const textarea_attrs[] = { ATTRS, "name", "disabled", "readonly", "tabindex", "accesskey", "onfocus", "onblur", "onselect", "onchange", NULL } ;
765
static const char* const tr_contents[] = { "th", "td", NULL } ;
766
static const char* const bgcolor_attr[] = { "bgcolor", NULL } ;
767
static const char* const li_elt[] = { "li", NULL } ;
768
static const char* const ul_depr[] = { "type", "compact", NULL} ;
769
static const char* const dir_attr[] = { "dir", NULL} ;
770
771
#define DECL (const char**)
772
773
static const htmlElemDesc
774
html40ElementTable[] = {
775
{ "a",    0, 0, 0, 0, 0, 0, 1, "anchor ",
776
  DECL html_inline , NULL , DECL a_attrs , DECL target_attr, NULL
777
},
778
{ "abbr", 0, 0, 0, 0, 0, 0, 1, "abbreviated form",
779
  DECL html_inline , NULL , DECL html_attrs, NULL, NULL
780
},
781
{ "acronym",  0, 0, 0, 0, 0, 0, 1, "",
782
  DECL html_inline , NULL , DECL html_attrs, NULL, NULL
783
},
784
{ "address",  0, 0, 0, 0, 0, 0, 0, "information on author ",
785
  DECL inline_p  , NULL , DECL html_attrs, NULL, NULL
786
},
787
{ "applet", 0, 0, 0, 0, 1, 1, 2, "java applet ",
788
  DECL flow_param , NULL , NULL , DECL applet_attrs, NULL
789
},
790
{ "area", 0, 2, 2, 1, 0, 0, 0, "client-side image map area ",
791
  EMPTY ,  NULL , DECL area_attrs , DECL target_attr, DECL alt_attr
792
},
793
{ "b",    0, 3, 0, 0, 0, 0, 1, "bold text style",
794
  DECL html_inline , NULL , DECL html_attrs, NULL, NULL
795
},
796
{ "base", 0, 2, 2, 1, 0, 0, 0, "document base uri ",
797
  EMPTY , NULL , NULL , DECL target_attr, DECL href_attrs
798
},
799
{ "basefont", 0, 2, 2, 1, 1, 1, 1, "base font size " ,
800
  EMPTY , NULL , NULL, DECL basefont_attrs, NULL
801
},
802
{ "bdo",  0, 0, 0, 0, 0, 0, 1, "i18n bidi over-ride ",
803
  DECL html_inline , NULL , DECL core_i18n_attrs, NULL, DECL dir_attr
804
},
805
{ "big",  0, 3, 0, 0, 0, 0, 1, "large text style",
806
  DECL html_inline , NULL , DECL html_attrs, NULL, NULL
807
},
808
{ "blockquote", 0, 0, 0, 0, 0, 0, 0, "long quotation ",
809
  DECL html_flow , NULL , DECL quote_attrs , NULL, NULL
810
},
811
{ "body", 1, 1, 0, 0, 0, 0, 0, "document body ",
812
  DECL body_contents , "div" , DECL body_attrs, DECL body_depr, NULL
813
},
814
{ "br",   0, 2, 2, 1, 0, 0, 1, "forced line break ",
815
  EMPTY , NULL , DECL core_attrs, DECL clear_attrs , NULL
816
},
817
{ "button", 0, 0, 0, 0, 0, 0, 2, "push button ",
818
  DECL html_flow MODIFIER , NULL , DECL button_attrs, NULL, NULL
819
},
820
{ "caption",  0, 0, 0, 0, 0, 0, 0, "table caption ",
821
  DECL html_inline , NULL , DECL html_attrs, NULL, NULL
822
},
823
{ "center", 0, 3, 0, 0, 1, 1, 0, "shorthand for div align=center ",
824
  DECL html_flow , NULL , NULL, DECL html_attrs, NULL
825
},
826
{ "cite", 0, 0, 0, 0, 0, 0, 1, "citation",
827
  DECL html_inline , NULL , DECL html_attrs, NULL, NULL
828
},
829
{ "code", 0, 0, 0, 0, 0, 0, 1, "computer code fragment",
830
  DECL html_inline , NULL , DECL html_attrs, NULL, NULL
831
},
832
{ "col",  0, 2, 2, 1, 0, 0, 0, "table column ",
833
  EMPTY , NULL , DECL col_attrs , NULL, NULL
834
},
835
{ "colgroup", 0, 1, 0, 0, 0, 0, 0, "table column group ",
836
  DECL col_elt , "col" , DECL col_attrs , NULL, NULL
837
},
838
{ "dd",   0, 1, 0, 0, 0, 0, 0, "definition description ",
839
  DECL html_flow , NULL , DECL html_attrs, NULL, NULL
840
},
841
{ "del",  0, 0, 0, 0, 0, 0, 2, "deleted text ",
842
  DECL html_flow , NULL , DECL edit_attrs , NULL, NULL
843
},
844
{ "dfn",  0, 0, 0, 0, 0, 0, 1, "instance definition",
845
  DECL html_inline , NULL , DECL html_attrs, NULL, NULL
846
},
847
{ "dir",  0, 0, 0, 0, 1, 1, 0, "directory list",
848
  DECL blockli_elt, "li" , NULL, DECL compact_attrs, NULL
849
},
850
{ "div",  0, 0, 0, 0, 0, 0, 0, "generic language/style container",
851
  DECL html_flow, NULL, DECL html_attrs, DECL align_attr, NULL
852
},
853
{ "dl",   0, 0, 0, 0, 0, 0, 0, "definition list ",
854
  DECL dl_contents , "dd" , DECL html_attrs, DECL compact_attr, NULL
855
},
856
{ "dt",   0, 1, 0, 0, 0, 0, 0, "definition term ",
857
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
858
},
859
{ "em",   0, 3, 0, 0, 0, 0, 1, "emphasis",
860
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
861
},
862
{ "embed",  0, 1, 0, 0, 1, 1, 1, "generic embedded object ",
863
  EMPTY, NULL, DECL embed_attrs, NULL, NULL
864
},
865
{ "fieldset", 0, 0, 0, 0, 0, 0, 0, "form control group ",
866
  DECL fieldset_contents , NULL, DECL html_attrs, NULL, NULL
867
},
868
{ "font", 0, 3, 0, 0, 1, 1, 1, "local change to font ",
869
  DECL html_inline, NULL, NULL, DECL font_attrs, NULL
870
},
871
{ "form", 0, 0, 0, 0, 0, 0, 0, "interactive form ",
872
  DECL form_contents, "fieldset", DECL form_attrs , DECL target_attr, DECL action_attr
873
},
874
{ "frame",  0, 2, 2, 1, 0, 2, 0, "subwindow " ,
875
  EMPTY, NULL, NULL, DECL frame_attrs, NULL
876
},
877
{ "frameset", 0, 0, 0, 0, 0, 2, 0, "window subdivision" ,
878
  DECL frameset_contents, "noframes" , NULL , DECL frameset_attrs, NULL
879
},
880
{ "h1",   0, 0, 0, 0, 0, 0, 0, "heading ",
881
  DECL html_inline, NULL, DECL html_attrs, DECL align_attr, NULL
882
},
883
{ "h2",   0, 0, 0, 0, 0, 0, 0, "heading ",
884
  DECL html_inline, NULL, DECL html_attrs, DECL align_attr, NULL
885
},
886
{ "h3",   0, 0, 0, 0, 0, 0, 0, "heading ",
887
  DECL html_inline, NULL, DECL html_attrs, DECL align_attr, NULL
888
},
889
{ "h4",   0, 0, 0, 0, 0, 0, 0, "heading ",
890
  DECL html_inline, NULL, DECL html_attrs, DECL align_attr, NULL
891
},
892
{ "h5",   0, 0, 0, 0, 0, 0, 0, "heading ",
893
  DECL html_inline, NULL, DECL html_attrs, DECL align_attr, NULL
894
},
895
{ "h6",   0, 0, 0, 0, 0, 0, 0, "heading ",
896
  DECL html_inline, NULL, DECL html_attrs, DECL align_attr, NULL
897
},
898
{ "head", 1, 1, 0, 0, 0, 0, 0, "document head ",
899
  DECL head_contents, NULL, DECL head_attrs, NULL, NULL
900
},
901
{ "hr",   0, 2, 2, 1, 0, 0, 0, "horizontal rule " ,
902
  EMPTY, NULL, DECL html_attrs, DECL hr_depr, NULL
903
},
904
{ "html", 1, 1, 0, 0, 0, 0, 0, "document root element ",
905
  DECL html_content , NULL , DECL i18n_attrs, DECL version_attr, NULL
906
},
907
{ "i",    0, 3, 0, 0, 0, 0, 1, "italic text style",
908
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
909
},
910
{ "iframe", 0, 0, 0, 0, 0, 1, 2, "inline subwindow ",
911
  DECL html_flow, NULL, NULL, DECL iframe_attrs, NULL
912
},
913
{ "img",  0, 2, 2, 1, 0, 0, 1, "embedded image ",
914
  EMPTY, NULL, DECL img_attrs, DECL align_attr, DECL src_alt_attrs
915
},
916
{ "input",  0, 2, 2, 1, 0, 0, 1, "form control ",
917
  EMPTY, NULL, DECL input_attrs , DECL align_attr, NULL
918
},
919
{ "ins",  0, 0, 0, 0, 0, 0, 2, "inserted text",
920
  DECL html_flow, NULL, DECL edit_attrs, NULL, NULL
921
},
922
{ "isindex",  0, 2, 2, 1, 1, 1, 0, "single line prompt ",
923
  EMPTY, NULL, NULL, DECL prompt_attrs, NULL
924
},
925
{ "kbd",  0, 0, 0, 0, 0, 0, 1, "text to be entered by the user",
926
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
927
},
928
{ "label",  0, 0, 0, 0, 0, 0, 1, "form field label text ",
929
  DECL html_inline MODIFIER, NULL, DECL label_attrs , NULL, NULL
930
},
931
{ "legend", 0, 0, 0, 0, 0, 0, 0, "fieldset legend ",
932
  DECL html_inline, NULL, DECL legend_attrs , DECL align_attr, NULL
933
},
934
{ "li",   0, 1, 1, 0, 0, 0, 0, "list item ",
935
  DECL html_flow, NULL, DECL html_attrs, NULL, NULL
936
},
937
{ "link", 0, 2, 2, 1, 0, 0, 0, "a media-independent link ",
938
  EMPTY, NULL, DECL link_attrs, DECL target_attr, NULL
939
},
940
{ "map",  0, 0, 0, 0, 0, 0, 2, "client-side image map ",
941
  DECL map_contents , NULL, DECL html_attrs , NULL, DECL name_attr
942
},
943
{ "menu", 0, 0, 0, 0, 1, 1, 0, "menu list ",
944
  DECL blockli_elt , NULL, NULL, DECL compact_attrs, NULL
945
},
946
{ "meta", 0, 2, 2, 1, 0, 0, 0, "generic metainformation ",
947
  EMPTY, NULL, DECL meta_attrs , NULL , DECL content_attr
948
},
949
{ "noframes", 0, 0, 0, 0, 0, 2, 0, "alternate content container for non frame-based rendering ",
950
  DECL noframes_content, "body" , DECL html_attrs, NULL, NULL
951
},
952
{ "noscript", 0, 0, 0, 0, 0, 0, 0, "alternate content container for non script-based rendering ",
953
  DECL html_flow, "div", DECL html_attrs, NULL, NULL
954
},
955
{ "object", 0, 0, 0, 0, 0, 0, 2, "generic embedded object ",
956
  DECL object_contents , "div" , DECL object_attrs, DECL object_depr, NULL
957
},
958
{ "ol",   0, 0, 0, 0, 0, 0, 0, "ordered list ",
959
  DECL li_elt , "li" , DECL html_attrs, DECL ol_attrs, NULL
960
},
961
{ "optgroup", 0, 0, 0, 0, 0, 0, 0, "option group ",
962
  DECL option_elt , "option", DECL optgroup_attrs, NULL, DECL label_attr
963
},
964
{ "option", 0, 1, 0, 0, 0, 0, 0, "selectable choice " ,
965
  DECL html_pcdata, NULL, DECL option_attrs, NULL, NULL
966
},
967
{ "p",    0, 1, 0, 0, 0, 0, 0, "paragraph ",
968
  DECL html_inline, NULL, DECL html_attrs, DECL align_attr, NULL
969
},
970
{ "param",  0, 2, 2, 1, 0, 0, 0, "named property value ",
971
  EMPTY, NULL, DECL param_attrs, NULL, DECL name_attr
972
},
973
{ "pre",  0, 0, 0, 0, 0, 0, 0, "preformatted text ",
974
  DECL pre_content, NULL, DECL html_attrs, DECL width_attr, NULL
975
},
976
{ "q",    0, 0, 0, 0, 0, 0, 1, "short inline quotation ",
977
  DECL html_inline, NULL, DECL quote_attrs, NULL, NULL
978
},
979
{ "s",    0, 3, 0, 0, 1, 1, 1, "strike-through text style",
980
  DECL html_inline, NULL, NULL, DECL html_attrs, NULL
981
},
982
{ "samp", 0, 0, 0, 0, 0, 0, 1, "sample program output, scripts, etc.",
983
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
984
},
985
{ "script", 0, 0, 0, 0, 0, 0, 2, "script statements ",
986
  DECL html_cdata, NULL, DECL script_attrs, DECL language_attr, DECL type_attr
987
},
988
{ "select", 0, 0, 0, 0, 0, 0, 1, "option selector ",
989
  DECL select_content, NULL, DECL select_attrs, NULL, NULL
990
},
991
{ "small",  0, 3, 0, 0, 0, 0, 1, "small text style",
992
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
993
},
994
{ "span", 0, 0, 0, 0, 0, 0, 1, "generic language/style container ",
995
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
996
},
997
{ "strike", 0, 3, 0, 0, 1, 1, 1, "strike-through text",
998
  DECL html_inline, NULL, NULL, DECL html_attrs, NULL
999
},
1000
{ "strong", 0, 3, 0, 0, 0, 0, 1, "strong emphasis",
1001
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
1002
},
1003
{ "style",  0, 0, 0, 0, 0, 0, 0, "style info ",
1004
  DECL html_cdata, NULL, DECL style_attrs, NULL, DECL type_attr
1005
},
1006
{ "sub",  0, 3, 0, 0, 0, 0, 1, "subscript",
1007
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
1008
},
1009
{ "sup",  0, 3, 0, 0, 0, 0, 1, "superscript ",
1010
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
1011
},
1012
{ "table",  0, 0, 0, 0, 0, 0, 0, "",
1013
  DECL table_contents , "tr" , DECL table_attrs , DECL table_depr, NULL
1014
},
1015
{ "tbody",  1, 0, 0, 0, 0, 0, 0, "table body ",
1016
  DECL tr_elt , "tr" , DECL talign_attrs, NULL, NULL
1017
},
1018
{ "td",   0, 0, 0, 0, 0, 0, 0, "table data cell",
1019
  DECL html_flow, NULL, DECL th_td_attr, DECL th_td_depr, NULL
1020
},
1021
{ "textarea", 0, 0, 0, 0, 0, 0, 1, "multi-line text field ",
1022
  DECL html_pcdata, NULL, DECL textarea_attrs, NULL, DECL rows_cols_attr
1023
},
1024
{ "tfoot",  0, 1, 0, 0, 0, 0, 0, "table footer ",
1025
  DECL tr_elt , "tr" , DECL talign_attrs, NULL, NULL
1026
},
1027
{ "th",   0, 1, 0, 0, 0, 0, 0, "table header cell",
1028
  DECL html_flow, NULL, DECL th_td_attr, DECL th_td_depr, NULL
1029
},
1030
{ "thead",  0, 1, 0, 0, 0, 0, 0, "table header ",
1031
  DECL tr_elt , "tr" , DECL talign_attrs, NULL, NULL
1032
},
1033
{ "title",  0, 0, 0, 0, 0, 0, 0, "document title ",
1034
  DECL html_pcdata, NULL, DECL i18n_attrs, NULL, NULL
1035
},
1036
{ "tr",   0, 0, 0, 0, 0, 0, 0, "table row ",
1037
  DECL tr_contents , "td" , DECL talign_attrs, DECL bgcolor_attr, NULL
1038
},
1039
{ "tt",   0, 3, 0, 0, 0, 0, 1, "teletype or monospaced text style",
1040
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
1041
},
1042
{ "u",    0, 3, 0, 0, 1, 1, 1, "underlined text style",
1043
  DECL html_inline, NULL, NULL, DECL html_attrs, NULL
1044
},
1045
{ "ul",   0, 0, 0, 0, 0, 0, 0, "unordered list ",
1046
  DECL li_elt , "li" , DECL html_attrs, DECL ul_depr, NULL
1047
},
1048
{ "var",  0, 0, 0, 0, 0, 0, 1, "instance of a variable or program argument",
1049
  DECL html_inline, NULL, DECL html_attrs, NULL, NULL
1050
}
1051
};
1052
1053
typedef struct {
1054
    const char *oldTag;
1055
    const char *newTag;
1056
} htmlStartCloseEntry;
1057
1058
/*
1059
 * start tags that imply the end of current element
1060
 */
1061
static const htmlStartCloseEntry htmlStartClose[] = {
1062
    { "a", "a" },
1063
    { "a", "fieldset" },
1064
    { "a", "table" },
1065
    { "a", "td" },
1066
    { "a", "th" },
1067
    { "address", "dd" },
1068
    { "address", "dl" },
1069
    { "address", "dt" },
1070
    { "address", "form" },
1071
    { "address", "li" },
1072
    { "address", "ul" },
1073
    { "b", "center" },
1074
    { "b", "p" },
1075
    { "b", "td" },
1076
    { "b", "th" },
1077
    { "big", "p" },
1078
    { "caption", "col" },
1079
    { "caption", "colgroup" },
1080
    { "caption", "tbody" },
1081
    { "caption", "tfoot" },
1082
    { "caption", "thead" },
1083
    { "caption", "tr" },
1084
    { "col", "col" },
1085
    { "col", "colgroup" },
1086
    { "col", "tbody" },
1087
    { "col", "tfoot" },
1088
    { "col", "thead" },
1089
    { "col", "tr" },
1090
    { "colgroup", "colgroup" },
1091
    { "colgroup", "tbody" },
1092
    { "colgroup", "tfoot" },
1093
    { "colgroup", "thead" },
1094
    { "colgroup", "tr" },
1095
    { "dd", "dt" },
1096
    { "dir", "dd" },
1097
    { "dir", "dl" },
1098
    { "dir", "dt" },
1099
    { "dir", "form" },
1100
    { "dir", "ul" },
1101
    { "dl", "form" },
1102
    { "dl", "li" },
1103
    { "dt", "dd" },
1104
    { "dt", "dl" },
1105
    { "font", "center" },
1106
    { "font", "td" },
1107
    { "font", "th" },
1108
    { "form", "form" },
1109
    { "h1", "fieldset" },
1110
    { "h1", "form" },
1111
    { "h1", "li" },
1112
    { "h1", "p" },
1113
    { "h1", "table" },
1114
    { "h2", "fieldset" },
1115
    { "h2", "form" },
1116
    { "h2", "li" },
1117
    { "h2", "p" },
1118
    { "h2", "table" },
1119
    { "h3", "fieldset" },
1120
    { "h3", "form" },
1121
    { "h3", "li" },
1122
    { "h3", "p" },
1123
    { "h3", "table" },
1124
    { "h4", "fieldset" },
1125
    { "h4", "form" },
1126
    { "h4", "li" },
1127
    { "h4", "p" },
1128
    { "h4", "table" },
1129
    { "h5", "fieldset" },
1130
    { "h5", "form" },
1131
    { "h5", "li" },
1132
    { "h5", "p" },
1133
    { "h5", "table" },
1134
    { "h6", "fieldset" },
1135
    { "h6", "form" },
1136
    { "h6", "li" },
1137
    { "h6", "p" },
1138
    { "h6", "table" },
1139
    { "head", "a" },
1140
    { "head", "abbr" },
1141
    { "head", "acronym" },
1142
    { "head", "address" },
1143
    { "head", "b" },
1144
    { "head", "bdo" },
1145
    { "head", "big" },
1146
    { "head", "blockquote" },
1147
    { "head", "body" },
1148
    { "head", "br" },
1149
    { "head", "center" },
1150
    { "head", "cite" },
1151
    { "head", "code" },
1152
    { "head", "dd" },
1153
    { "head", "dfn" },
1154
    { "head", "dir" },
1155
    { "head", "div" },
1156
    { "head", "dl" },
1157
    { "head", "dt" },
1158
    { "head", "em" },
1159
    { "head", "fieldset" },
1160
    { "head", "font" },
1161
    { "head", "form" },
1162
    { "head", "frameset" },
1163
    { "head", "h1" },
1164
    { "head", "h2" },
1165
    { "head", "h3" },
1166
    { "head", "h4" },
1167
    { "head", "h5" },
1168
    { "head", "h6" },
1169
    { "head", "hr" },
1170
    { "head", "i" },
1171
    { "head", "iframe" },
1172
    { "head", "img" },
1173
    { "head", "kbd" },
1174
    { "head", "li" },
1175
    { "head", "listing" },
1176
    { "head", "map" },
1177
    { "head", "menu" },
1178
    { "head", "ol" },
1179
    { "head", "p" },
1180
    { "head", "pre" },
1181
    { "head", "q" },
1182
    { "head", "s" },
1183
    { "head", "samp" },
1184
    { "head", "small" },
1185
    { "head", "span" },
1186
    { "head", "strike" },
1187
    { "head", "strong" },
1188
    { "head", "sub" },
1189
    { "head", "sup" },
1190
    { "head", "table" },
1191
    { "head", "tt" },
1192
    { "head", "u" },
1193
    { "head", "ul" },
1194
    { "head", "var" },
1195
    { "head", "xmp" },
1196
    { "hr", "form" },
1197
    { "i", "center" },
1198
    { "i", "p" },
1199
    { "i", "td" },
1200
    { "i", "th" },
1201
    { "legend", "fieldset" },
1202
    { "li", "li" },
1203
    { "link", "body" },
1204
    { "link", "frameset" },
1205
    { "listing", "dd" },
1206
    { "listing", "dl" },
1207
    { "listing", "dt" },
1208
    { "listing", "fieldset" },
1209
    { "listing", "form" },
1210
    { "listing", "li" },
1211
    { "listing", "table" },
1212
    { "listing", "ul" },
1213
    { "menu", "dd" },
1214
    { "menu", "dl" },
1215
    { "menu", "dt" },
1216
    { "menu", "form" },
1217
    { "menu", "ul" },
1218
    { "ol", "form" },
1219
    { "option", "optgroup" },
1220
    { "option", "option" },
1221
    { "p", "address" },
1222
    { "p", "blockquote" },
1223
    { "p", "body" },
1224
    { "p", "caption" },
1225
    { "p", "center" },
1226
    { "p", "col" },
1227
    { "p", "colgroup" },
1228
    { "p", "dd" },
1229
    { "p", "dir" },
1230
    { "p", "div" },
1231
    { "p", "dl" },
1232
    { "p", "dt" },
1233
    { "p", "fieldset" },
1234
    { "p", "form" },
1235
    { "p", "frameset" },
1236
    { "p", "h1" },
1237
    { "p", "h2" },
1238
    { "p", "h3" },
1239
    { "p", "h4" },
1240
    { "p", "h5" },
1241
    { "p", "h6" },
1242
    { "p", "head" },
1243
    { "p", "hr" },
1244
    { "p", "li" },
1245
    { "p", "listing" },
1246
    { "p", "menu" },
1247
    { "p", "ol" },
1248
    { "p", "p" },
1249
    { "p", "pre" },
1250
    { "p", "table" },
1251
    { "p", "tbody" },
1252
    { "p", "td" },
1253
    { "p", "tfoot" },
1254
    { "p", "th" },
1255
    { "p", "title" },
1256
    { "p", "tr" },
1257
    { "p", "ul" },
1258
    { "p", "xmp" },
1259
    { "pre", "dd" },
1260
    { "pre", "dl" },
1261
    { "pre", "dt" },
1262
    { "pre", "fieldset" },
1263
    { "pre", "form" },
1264
    { "pre", "li" },
1265
    { "pre", "table" },
1266
    { "pre", "ul" },
1267
    { "s", "p" },
1268
    { "script", "noscript" },
1269
    { "small", "p" },
1270
    { "span", "td" },
1271
    { "span", "th" },
1272
    { "strike", "p" },
1273
    { "style", "body" },
1274
    { "style", "frameset" },
1275
    { "tbody", "tbody" },
1276
    { "tbody", "tfoot" },
1277
    { "td", "tbody" },
1278
    { "td", "td" },
1279
    { "td", "tfoot" },
1280
    { "td", "th" },
1281
    { "td", "tr" },
1282
    { "tfoot", "tbody" },
1283
    { "th", "tbody" },
1284
    { "th", "td" },
1285
    { "th", "tfoot" },
1286
    { "th", "th" },
1287
    { "th", "tr" },
1288
    { "thead", "tbody" },
1289
    { "thead", "tfoot" },
1290
    { "title", "body" },
1291
    { "title", "frameset" },
1292
    { "tr", "tbody" },
1293
    { "tr", "tfoot" },
1294
    { "tr", "tr" },
1295
    { "tt", "p" },
1296
    { "u", "p" },
1297
    { "u", "td" },
1298
    { "u", "th" },
1299
    { "ul", "address" },
1300
    { "ul", "form" },
1301
    { "ul", "menu" },
1302
    { "ul", "pre" },
1303
    { "xmp", "dd" },
1304
    { "xmp", "dl" },
1305
    { "xmp", "dt" },
1306
    { "xmp", "fieldset" },
1307
    { "xmp", "form" },
1308
    { "xmp", "li" },
1309
    { "xmp", "table" },
1310
    { "xmp", "ul" }
1311
};
1312
1313
/*
1314
 * The list of HTML elements which are supposed not to have
1315
 * CDATA content and where a p element will be implied
1316
 *
1317
 * TODO: extend that list by reading the HTML SGML DTD on
1318
 *       implied paragraph
1319
 */
1320
static const char *const htmlNoContentElements[] = {
1321
    "html",
1322
    "head",
1323
    NULL
1324
};
1325
1326
/*
1327
 * The list of HTML attributes which are of content %Script;
1328
 * NOTE: when adding ones, check htmlIsScriptAttribute() since
1329
 *       it assumes the name starts with 'on'
1330
 */
1331
static const char *const htmlScriptAttributes[] = {
1332
    "onclick",
1333
    "ondblclick",
1334
    "onmousedown",
1335
    "onmouseup",
1336
    "onmouseover",
1337
    "onmousemove",
1338
    "onmouseout",
1339
    "onkeypress",
1340
    "onkeydown",
1341
    "onkeyup",
1342
    "onload",
1343
    "onunload",
1344
    "onfocus",
1345
    "onblur",
1346
    "onsubmit",
1347
    "onreset",
1348
    "onchange",
1349
    "onselect"
1350
};
1351
1352
/*
1353
 * This table is used by the htmlparser to know what to do with
1354
 * broken html pages. By assigning different priorities to different
1355
 * elements the parser can decide how to handle extra endtags.
1356
 * Endtags are only allowed to close elements with lower or equal
1357
 * priority.
1358
 */
1359
1360
typedef struct {
1361
    const char *name;
1362
    int priority;
1363
} elementPriority;
1364
1365
static const elementPriority htmlEndPriority[] = {
1366
    {"div",   150},
1367
    {"td",    160},
1368
    {"th",    160},
1369
    {"tr",    170},
1370
    {"thead", 180},
1371
    {"tbody", 180},
1372
    {"tfoot", 180},
1373
    {"table", 190},
1374
    {"head",  200},
1375
    {"body",  200},
1376
    {"html",  220},
1377
    {NULL,    100} /* Default priority */
1378
};
1379
1380
/************************************************************************
1381
 *                  *
1382
 *  functions to handle HTML specific data      *
1383
 *                  *
1384
 ************************************************************************/
1385
1386
/**
1387
 * htmlInitAutoClose:
1388
 *
1389
 * DEPRECATED: This is a no-op.
1390
 */
1391
void
1392
0
htmlInitAutoClose(void) {
1393
0
}
1394
1395
static int
1396
1.44M
htmlCompareTags(const void *key, const void *member) {
1397
1.44M
    const xmlChar *tag = (const xmlChar *) key;
1398
1.44M
    const htmlElemDesc *desc = (const htmlElemDesc *) member;
1399
1400
1.44M
    return(xmlStrcasecmp(tag, BAD_CAST desc->name));
1401
1.44M
}
1402
1403
/**
1404
 * htmlTagLookup:
1405
 * @tag:  The tag name in lowercase
1406
 *
1407
 * Lookup the HTML tag in the ElementTable
1408
 *
1409
 * Returns the related htmlElemDescPtr or NULL if not found.
1410
 */
1411
const htmlElemDesc *
1412
211k
htmlTagLookup(const xmlChar *tag) {
1413
211k
    if (tag == NULL)
1414
0
        return(NULL);
1415
1416
211k
    return((const htmlElemDesc *) bsearch(tag, html40ElementTable,
1417
211k
                sizeof(html40ElementTable) / sizeof(htmlElemDesc),
1418
211k
                sizeof(htmlElemDesc), htmlCompareTags));
1419
211k
}
1420
1421
/**
1422
 * htmlGetEndPriority:
1423
 * @name: The name of the element to look up the priority for.
1424
 *
1425
 * Return value: The "endtag" priority.
1426
 **/
1427
static int
1428
0
htmlGetEndPriority (const xmlChar *name) {
1429
0
    int i = 0;
1430
1431
0
    while ((htmlEndPriority[i].name != NULL) &&
1432
0
     (!xmlStrEqual((const xmlChar *)htmlEndPriority[i].name, name)))
1433
0
  i++;
1434
1435
0
    return(htmlEndPriority[i].priority);
1436
0
}
1437
1438
1439
static int
1440
0
htmlCompareStartClose(const void *vkey, const void *member) {
1441
0
    const htmlStartCloseEntry *key = (const htmlStartCloseEntry *) vkey;
1442
0
    const htmlStartCloseEntry *entry = (const htmlStartCloseEntry *) member;
1443
0
    int ret;
1444
1445
0
    ret = strcmp(key->oldTag, entry->oldTag);
1446
0
    if (ret == 0)
1447
0
        ret = strcmp(key->newTag, entry->newTag);
1448
1449
0
    return(ret);
1450
0
}
1451
1452
/**
1453
 * htmlCheckAutoClose:
1454
 * @newtag:  The new tag name
1455
 * @oldtag:  The old tag name
1456
 *
1457
 * Checks whether the new tag is one of the registered valid tags for
1458
 * closing old.
1459
 *
1460
 * Returns 0 if no, 1 if yes.
1461
 */
1462
static int
1463
htmlCheckAutoClose(const xmlChar * newtag, const xmlChar * oldtag)
1464
0
{
1465
0
    htmlStartCloseEntry key;
1466
0
    void *res;
1467
1468
0
    key.oldTag = (const char *) oldtag;
1469
0
    key.newTag = (const char *) newtag;
1470
0
    res = bsearch(&key, htmlStartClose,
1471
0
            sizeof(htmlStartClose) / sizeof(htmlStartCloseEntry),
1472
0
            sizeof(htmlStartCloseEntry), htmlCompareStartClose);
1473
0
    return(res != NULL);
1474
0
}
1475
1476
/**
1477
 * htmlAutoCloseOnClose:
1478
 * @ctxt:  an HTML parser context
1479
 * @newtag:  The new tag name
1480
 * @force:  force the tag closure
1481
 *
1482
 * The HTML DTD allows an ending tag to implicitly close other tags.
1483
 */
1484
static void
1485
htmlAutoCloseOnClose(htmlParserCtxtPtr ctxt, const xmlChar * newtag)
1486
0
{
1487
0
    const htmlElemDesc *info;
1488
0
    int i, priority;
1489
1490
0
    priority = htmlGetEndPriority(newtag);
1491
1492
0
    for (i = (ctxt->nameNr - 1); i >= 0; i--) {
1493
1494
0
        if (xmlStrEqual(newtag, ctxt->nameTab[i]))
1495
0
            break;
1496
        /*
1497
         * A misplaced endtag can only close elements with lower
1498
         * or equal priority, so if we find an element with higher
1499
         * priority before we find an element with
1500
         * matching name, we just ignore this endtag
1501
         */
1502
0
        if (htmlGetEndPriority(ctxt->nameTab[i]) > priority)
1503
0
            return;
1504
0
    }
1505
0
    if (i < 0)
1506
0
        return;
1507
1508
0
    while (!xmlStrEqual(newtag, ctxt->name)) {
1509
0
        info = htmlTagLookup(ctxt->name);
1510
0
        if ((info != NULL) && (info->endTag == 3)) {
1511
0
            htmlParseErr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
1512
0
                   "Opening and ending tag mismatch: %s and %s\n",
1513
0
       newtag, ctxt->name);
1514
0
        }
1515
0
        if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
1516
0
            ctxt->sax->endElement(ctxt->userData, ctxt->name);
1517
0
  htmlnamePop(ctxt);
1518
0
    }
1519
0
}
1520
1521
/**
1522
 * htmlAutoCloseOnEnd:
1523
 * @ctxt:  an HTML parser context
1524
 *
1525
 * Close all remaining tags at the end of the stream
1526
 */
1527
static void
1528
htmlAutoCloseOnEnd(htmlParserCtxtPtr ctxt)
1529
0
{
1530
0
    int i;
1531
1532
0
    if (ctxt->nameNr == 0)
1533
0
        return;
1534
0
    for (i = (ctxt->nameNr - 1); i >= 0; i--) {
1535
0
        if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
1536
0
            ctxt->sax->endElement(ctxt->userData, ctxt->name);
1537
0
  htmlnamePop(ctxt);
1538
0
    }
1539
0
}
1540
1541
/**
1542
 * htmlAutoClose:
1543
 * @ctxt:  an HTML parser context
1544
 * @newtag:  The new tag name or NULL
1545
 *
1546
 * The HTML DTD allows a tag to implicitly close other tags.
1547
 * The list is kept in htmlStartClose array. This function is
1548
 * called when a new tag has been detected and generates the
1549
 * appropriates closes if possible/needed.
1550
 * If newtag is NULL this mean we are at the end of the resource
1551
 * and we should check
1552
 */
1553
static void
1554
htmlAutoClose(htmlParserCtxtPtr ctxt, const xmlChar * newtag)
1555
0
{
1556
0
    while ((newtag != NULL) && (ctxt->name != NULL) &&
1557
0
           (htmlCheckAutoClose(newtag, ctxt->name))) {
1558
0
        if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
1559
0
            ctxt->sax->endElement(ctxt->userData, ctxt->name);
1560
0
  htmlnamePop(ctxt);
1561
0
    }
1562
0
    if (newtag == NULL) {
1563
0
        htmlAutoCloseOnEnd(ctxt);
1564
0
        return;
1565
0
    }
1566
0
    while ((newtag == NULL) && (ctxt->name != NULL) &&
1567
0
           ((xmlStrEqual(ctxt->name, BAD_CAST "head")) ||
1568
0
            (xmlStrEqual(ctxt->name, BAD_CAST "body")) ||
1569
0
            (xmlStrEqual(ctxt->name, BAD_CAST "html")))) {
1570
0
        if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
1571
0
            ctxt->sax->endElement(ctxt->userData, ctxt->name);
1572
0
  htmlnamePop(ctxt);
1573
0
    }
1574
0
}
1575
1576
/**
1577
 * htmlAutoCloseTag:
1578
 * @doc:  the HTML document
1579
 * @name:  The tag name
1580
 * @elem:  the HTML element
1581
 *
1582
 * The HTML DTD allows a tag to implicitly close other tags.
1583
 * The list is kept in htmlStartClose array. This function checks
1584
 * if the element or one of it's children would autoclose the
1585
 * given tag.
1586
 *
1587
 * Returns 1 if autoclose, 0 otherwise
1588
 */
1589
int
1590
0
htmlAutoCloseTag(htmlDocPtr doc, const xmlChar *name, htmlNodePtr elem) {
1591
0
    htmlNodePtr child;
1592
1593
0
    if (elem == NULL) return(1);
1594
0
    if (xmlStrEqual(name, elem->name)) return(0);
1595
0
    if (htmlCheckAutoClose(elem->name, name)) return(1);
1596
0
    child = elem->children;
1597
0
    while (child != NULL) {
1598
0
        if (htmlAutoCloseTag(doc, name, child)) return(1);
1599
0
  child = child->next;
1600
0
    }
1601
0
    return(0);
1602
0
}
1603
1604
/**
1605
 * htmlIsAutoClosed:
1606
 * @doc:  the HTML document
1607
 * @elem:  the HTML element
1608
 *
1609
 * The HTML DTD allows a tag to implicitly close other tags.
1610
 * The list is kept in htmlStartClose array. This function checks
1611
 * if a tag is autoclosed by one of it's child
1612
 *
1613
 * Returns 1 if autoclosed, 0 otherwise
1614
 */
1615
int
1616
0
htmlIsAutoClosed(htmlDocPtr doc, htmlNodePtr elem) {
1617
0
    htmlNodePtr child;
1618
1619
0
    if (elem == NULL) return(1);
1620
0
    child = elem->children;
1621
0
    while (child != NULL) {
1622
0
  if (htmlAutoCloseTag(doc, elem->name, child)) return(1);
1623
0
  child = child->next;
1624
0
    }
1625
0
    return(0);
1626
0
}
1627
1628
/**
1629
 * htmlCheckImplied:
1630
 * @ctxt:  an HTML parser context
1631
 * @newtag:  The new tag name
1632
 *
1633
 * The HTML DTD allows a tag to exists only implicitly
1634
 * called when a new tag has been detected and generates the
1635
 * appropriates implicit tags if missing
1636
 */
1637
static void
1638
0
htmlCheckImplied(htmlParserCtxtPtr ctxt, const xmlChar *newtag) {
1639
0
    int i;
1640
1641
0
    if (ctxt->options & HTML_PARSE_NOIMPLIED)
1642
0
        return;
1643
0
    if (!htmlOmittedDefaultValue)
1644
0
  return;
1645
0
    if (xmlStrEqual(newtag, BAD_CAST"html"))
1646
0
  return;
1647
0
    if (ctxt->nameNr <= 0) {
1648
0
  htmlnamePush(ctxt, BAD_CAST"html");
1649
0
  if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL))
1650
0
      ctxt->sax->startElement(ctxt->userData, BAD_CAST"html", NULL);
1651
0
    }
1652
0
    if ((xmlStrEqual(newtag, BAD_CAST"body")) || (xmlStrEqual(newtag, BAD_CAST"head")))
1653
0
        return;
1654
0
    if ((ctxt->nameNr <= 1) &&
1655
0
        ((xmlStrEqual(newtag, BAD_CAST"script")) ||
1656
0
   (xmlStrEqual(newtag, BAD_CAST"style")) ||
1657
0
   (xmlStrEqual(newtag, BAD_CAST"meta")) ||
1658
0
   (xmlStrEqual(newtag, BAD_CAST"link")) ||
1659
0
   (xmlStrEqual(newtag, BAD_CAST"title")) ||
1660
0
   (xmlStrEqual(newtag, BAD_CAST"base")))) {
1661
0
        if (ctxt->html >= 3) {
1662
            /* we already saw or generated an <head> before */
1663
0
            return;
1664
0
        }
1665
        /*
1666
         * dropped OBJECT ... i you put it first BODY will be
1667
         * assumed !
1668
         */
1669
0
        htmlnamePush(ctxt, BAD_CAST"head");
1670
0
        if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL))
1671
0
            ctxt->sax->startElement(ctxt->userData, BAD_CAST"head", NULL);
1672
0
    } else if ((!xmlStrEqual(newtag, BAD_CAST"noframes")) &&
1673
0
         (!xmlStrEqual(newtag, BAD_CAST"frame")) &&
1674
0
         (!xmlStrEqual(newtag, BAD_CAST"frameset"))) {
1675
0
        if (ctxt->html >= 10) {
1676
            /* we already saw or generated a <body> before */
1677
0
            return;
1678
0
        }
1679
0
  for (i = 0;i < ctxt->nameNr;i++) {
1680
0
      if (xmlStrEqual(ctxt->nameTab[i], BAD_CAST"body")) {
1681
0
    return;
1682
0
      }
1683
0
      if (xmlStrEqual(ctxt->nameTab[i], BAD_CAST"head")) {
1684
0
    return;
1685
0
      }
1686
0
  }
1687
1688
0
  htmlnamePush(ctxt, BAD_CAST"body");
1689
0
  if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL))
1690
0
      ctxt->sax->startElement(ctxt->userData, BAD_CAST"body", NULL);
1691
0
    }
1692
0
}
1693
1694
/**
1695
 * htmlCheckParagraph
1696
 * @ctxt:  an HTML parser context
1697
 *
1698
 * Check whether a p element need to be implied before inserting
1699
 * characters in the current element.
1700
 *
1701
 * Returns 1 if a paragraph has been inserted, 0 if not and -1
1702
 *         in case of error.
1703
 */
1704
1705
static int
1706
0
htmlCheckParagraph(htmlParserCtxtPtr ctxt) {
1707
0
    const xmlChar *tag;
1708
0
    int i;
1709
1710
0
    if (ctxt == NULL)
1711
0
  return(-1);
1712
0
    tag = ctxt->name;
1713
0
    if (tag == NULL) {
1714
0
  htmlAutoClose(ctxt, BAD_CAST"p");
1715
0
  htmlCheckImplied(ctxt, BAD_CAST"p");
1716
0
  htmlnamePush(ctxt, BAD_CAST"p");
1717
0
  if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL))
1718
0
      ctxt->sax->startElement(ctxt->userData, BAD_CAST"p", NULL);
1719
0
  return(1);
1720
0
    }
1721
0
    if (!htmlOmittedDefaultValue)
1722
0
  return(0);
1723
0
    for (i = 0; htmlNoContentElements[i] != NULL; i++) {
1724
0
  if (xmlStrEqual(tag, BAD_CAST htmlNoContentElements[i])) {
1725
0
      htmlAutoClose(ctxt, BAD_CAST"p");
1726
0
      htmlCheckImplied(ctxt, BAD_CAST"p");
1727
0
      htmlnamePush(ctxt, BAD_CAST"p");
1728
0
      if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL))
1729
0
    ctxt->sax->startElement(ctxt->userData, BAD_CAST"p", NULL);
1730
0
      return(1);
1731
0
  }
1732
0
    }
1733
0
    return(0);
1734
0
}
1735
1736
/**
1737
 * htmlIsScriptAttribute:
1738
 * @name:  an attribute name
1739
 *
1740
 * Check if an attribute is of content type Script
1741
 *
1742
 * Returns 1 is the attribute is a script 0 otherwise
1743
 */
1744
int
1745
0
htmlIsScriptAttribute(const xmlChar *name) {
1746
0
    unsigned int i;
1747
1748
0
    if (name == NULL)
1749
0
      return(0);
1750
    /*
1751
     * all script attributes start with 'on'
1752
     */
1753
0
    if ((name[0] != 'o') || (name[1] != 'n'))
1754
0
      return(0);
1755
0
    for (i = 0;
1756
0
   i < sizeof(htmlScriptAttributes)/sizeof(htmlScriptAttributes[0]);
1757
0
   i++) {
1758
0
  if (xmlStrEqual(name, (const xmlChar *) htmlScriptAttributes[i]))
1759
0
      return(1);
1760
0
    }
1761
0
    return(0);
1762
0
}
1763
1764
/************************************************************************
1765
 *                  *
1766
 *  The list of HTML predefined entities      *
1767
 *                  *
1768
 ************************************************************************/
1769
1770
1771
static const htmlEntityDesc  html40EntitiesTable[] = {
1772
/*
1773
 * the 4 absolute ones, plus apostrophe.
1774
 */
1775
{ 34, "quot", "quotation mark = APL quote, U+0022 ISOnum" },
1776
{ 38, "amp",  "ampersand, U+0026 ISOnum" },
1777
{ 39, "apos", "single quote" },
1778
{ 60, "lt", "less-than sign, U+003C ISOnum" },
1779
{ 62, "gt", "greater-than sign, U+003E ISOnum" },
1780
1781
/*
1782
 * A bunch still in the 128-255 range
1783
 * Replacing them depend really on the charset used.
1784
 */
1785
{ 160,  "nbsp", "no-break space = non-breaking space, U+00A0 ISOnum" },
1786
{ 161,  "iexcl","inverted exclamation mark, U+00A1 ISOnum" },
1787
{ 162,  "cent", "cent sign, U+00A2 ISOnum" },
1788
{ 163,  "pound","pound sign, U+00A3 ISOnum" },
1789
{ 164,  "curren","currency sign, U+00A4 ISOnum" },
1790
{ 165,  "yen",  "yen sign = yuan sign, U+00A5 ISOnum" },
1791
{ 166,  "brvbar","broken bar = broken vertical bar, U+00A6 ISOnum" },
1792
{ 167,  "sect", "section sign, U+00A7 ISOnum" },
1793
{ 168,  "uml",  "diaeresis = spacing diaeresis, U+00A8 ISOdia" },
1794
{ 169,  "copy", "copyright sign, U+00A9 ISOnum" },
1795
{ 170,  "ordf", "feminine ordinal indicator, U+00AA ISOnum" },
1796
{ 171,  "laquo","left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum" },
1797
{ 172,  "not",  "not sign, U+00AC ISOnum" },
1798
{ 173,  "shy",  "soft hyphen = discretionary hyphen, U+00AD ISOnum" },
1799
{ 174,  "reg",  "registered sign = registered trade mark sign, U+00AE ISOnum" },
1800
{ 175,  "macr", "macron = spacing macron = overline = APL overbar, U+00AF ISOdia" },
1801
{ 176,  "deg",  "degree sign, U+00B0 ISOnum" },
1802
{ 177,  "plusmn","plus-minus sign = plus-or-minus sign, U+00B1 ISOnum" },
1803
{ 178,  "sup2", "superscript two = superscript digit two = squared, U+00B2 ISOnum" },
1804
{ 179,  "sup3", "superscript three = superscript digit three = cubed, U+00B3 ISOnum" },
1805
{ 180,  "acute","acute accent = spacing acute, U+00B4 ISOdia" },
1806
{ 181,  "micro","micro sign, U+00B5 ISOnum" },
1807
{ 182,  "para", "pilcrow sign = paragraph sign, U+00B6 ISOnum" },
1808
{ 183,  "middot","middle dot = Georgian comma Greek middle dot, U+00B7 ISOnum" },
1809
{ 184,  "cedil","cedilla = spacing cedilla, U+00B8 ISOdia" },
1810
{ 185,  "sup1", "superscript one = superscript digit one, U+00B9 ISOnum" },
1811
{ 186,  "ordm", "masculine ordinal indicator, U+00BA ISOnum" },
1812
{ 187,  "raquo","right-pointing double angle quotation mark right pointing guillemet, U+00BB ISOnum" },
1813
{ 188,  "frac14","vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum" },
1814
{ 189,  "frac12","vulgar fraction one half = fraction one half, U+00BD ISOnum" },
1815
{ 190,  "frac34","vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum" },
1816
{ 191,  "iquest","inverted question mark = turned question mark, U+00BF ISOnum" },
1817
{ 192,  "Agrave","latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1" },
1818
{ 193,  "Aacute","latin capital letter A with acute, U+00C1 ISOlat1" },
1819
{ 194,  "Acirc","latin capital letter A with circumflex, U+00C2 ISOlat1" },
1820
{ 195,  "Atilde","latin capital letter A with tilde, U+00C3 ISOlat1" },
1821
{ 196,  "Auml", "latin capital letter A with diaeresis, U+00C4 ISOlat1" },
1822
{ 197,  "Aring","latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1" },
1823
{ 198,  "AElig","latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1" },
1824
{ 199,  "Ccedil","latin capital letter C with cedilla, U+00C7 ISOlat1" },
1825
{ 200,  "Egrave","latin capital letter E with grave, U+00C8 ISOlat1" },
1826
{ 201,  "Eacute","latin capital letter E with acute, U+00C9 ISOlat1" },
1827
{ 202,  "Ecirc","latin capital letter E with circumflex, U+00CA ISOlat1" },
1828
{ 203,  "Euml", "latin capital letter E with diaeresis, U+00CB ISOlat1" },
1829
{ 204,  "Igrave","latin capital letter I with grave, U+00CC ISOlat1" },
1830
{ 205,  "Iacute","latin capital letter I with acute, U+00CD ISOlat1" },
1831
{ 206,  "Icirc","latin capital letter I with circumflex, U+00CE ISOlat1" },
1832
{ 207,  "Iuml", "latin capital letter I with diaeresis, U+00CF ISOlat1" },
1833
{ 208,  "ETH",  "latin capital letter ETH, U+00D0 ISOlat1" },
1834
{ 209,  "Ntilde","latin capital letter N with tilde, U+00D1 ISOlat1" },
1835
{ 210,  "Ograve","latin capital letter O with grave, U+00D2 ISOlat1" },
1836
{ 211,  "Oacute","latin capital letter O with acute, U+00D3 ISOlat1" },
1837
{ 212,  "Ocirc","latin capital letter O with circumflex, U+00D4 ISOlat1" },
1838
{ 213,  "Otilde","latin capital letter O with tilde, U+00D5 ISOlat1" },
1839
{ 214,  "Ouml", "latin capital letter O with diaeresis, U+00D6 ISOlat1" },
1840
{ 215,  "times","multiplication sign, U+00D7 ISOnum" },
1841
{ 216,  "Oslash","latin capital letter O with stroke latin capital letter O slash, U+00D8 ISOlat1" },
1842
{ 217,  "Ugrave","latin capital letter U with grave, U+00D9 ISOlat1" },
1843
{ 218,  "Uacute","latin capital letter U with acute, U+00DA ISOlat1" },
1844
{ 219,  "Ucirc","latin capital letter U with circumflex, U+00DB ISOlat1" },
1845
{ 220,  "Uuml", "latin capital letter U with diaeresis, U+00DC ISOlat1" },
1846
{ 221,  "Yacute","latin capital letter Y with acute, U+00DD ISOlat1" },
1847
{ 222,  "THORN","latin capital letter THORN, U+00DE ISOlat1" },
1848
{ 223,  "szlig","latin small letter sharp s = ess-zed, U+00DF ISOlat1" },
1849
{ 224,  "agrave","latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1" },
1850
{ 225,  "aacute","latin small letter a with acute, U+00E1 ISOlat1" },
1851
{ 226,  "acirc","latin small letter a with circumflex, U+00E2 ISOlat1" },
1852
{ 227,  "atilde","latin small letter a with tilde, U+00E3 ISOlat1" },
1853
{ 228,  "auml", "latin small letter a with diaeresis, U+00E4 ISOlat1" },
1854
{ 229,  "aring","latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1" },
1855
{ 230,  "aelig","latin small letter ae = latin small ligature ae, U+00E6 ISOlat1" },
1856
{ 231,  "ccedil","latin small letter c with cedilla, U+00E7 ISOlat1" },
1857
{ 232,  "egrave","latin small letter e with grave, U+00E8 ISOlat1" },
1858
{ 233,  "eacute","latin small letter e with acute, U+00E9 ISOlat1" },
1859
{ 234,  "ecirc","latin small letter e with circumflex, U+00EA ISOlat1" },
1860
{ 235,  "euml", "latin small letter e with diaeresis, U+00EB ISOlat1" },
1861
{ 236,  "igrave","latin small letter i with grave, U+00EC ISOlat1" },
1862
{ 237,  "iacute","latin small letter i with acute, U+00ED ISOlat1" },
1863
{ 238,  "icirc","latin small letter i with circumflex, U+00EE ISOlat1" },
1864
{ 239,  "iuml", "latin small letter i with diaeresis, U+00EF ISOlat1" },
1865
{ 240,  "eth",  "latin small letter eth, U+00F0 ISOlat1" },
1866
{ 241,  "ntilde","latin small letter n with tilde, U+00F1 ISOlat1" },
1867
{ 242,  "ograve","latin small letter o with grave, U+00F2 ISOlat1" },
1868
{ 243,  "oacute","latin small letter o with acute, U+00F3 ISOlat1" },
1869
{ 244,  "ocirc","latin small letter o with circumflex, U+00F4 ISOlat1" },
1870
{ 245,  "otilde","latin small letter o with tilde, U+00F5 ISOlat1" },
1871
{ 246,  "ouml", "latin small letter o with diaeresis, U+00F6 ISOlat1" },
1872
{ 247,  "divide","division sign, U+00F7 ISOnum" },
1873
{ 248,  "oslash","latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1" },
1874
{ 249,  "ugrave","latin small letter u with grave, U+00F9 ISOlat1" },
1875
{ 250,  "uacute","latin small letter u with acute, U+00FA ISOlat1" },
1876
{ 251,  "ucirc","latin small letter u with circumflex, U+00FB ISOlat1" },
1877
{ 252,  "uuml", "latin small letter u with diaeresis, U+00FC ISOlat1" },
1878
{ 253,  "yacute","latin small letter y with acute, U+00FD ISOlat1" },
1879
{ 254,  "thorn","latin small letter thorn with, U+00FE ISOlat1" },
1880
{ 255,  "yuml", "latin small letter y with diaeresis, U+00FF ISOlat1" },
1881
1882
{ 338,  "OElig","latin capital ligature OE, U+0152 ISOlat2" },
1883
{ 339,  "oelig","latin small ligature oe, U+0153 ISOlat2" },
1884
{ 352,  "Scaron","latin capital letter S with caron, U+0160 ISOlat2" },
1885
{ 353,  "scaron","latin small letter s with caron, U+0161 ISOlat2" },
1886
{ 376,  "Yuml", "latin capital letter Y with diaeresis, U+0178 ISOlat2" },
1887
1888
/*
1889
 * Anything below should really be kept as entities references
1890
 */
1891
{ 402,  "fnof", "latin small f with hook = function = florin, U+0192 ISOtech" },
1892
1893
{ 710,  "circ", "modifier letter circumflex accent, U+02C6 ISOpub" },
1894
{ 732,  "tilde","small tilde, U+02DC ISOdia" },
1895
1896
{ 913,  "Alpha","greek capital letter alpha, U+0391" },
1897
{ 914,  "Beta", "greek capital letter beta, U+0392" },
1898
{ 915,  "Gamma","greek capital letter gamma, U+0393 ISOgrk3" },
1899
{ 916,  "Delta","greek capital letter delta, U+0394 ISOgrk3" },
1900
{ 917,  "Epsilon","greek capital letter epsilon, U+0395" },
1901
{ 918,  "Zeta", "greek capital letter zeta, U+0396" },
1902
{ 919,  "Eta",  "greek capital letter eta, U+0397" },
1903
{ 920,  "Theta","greek capital letter theta, U+0398 ISOgrk3" },
1904
{ 921,  "Iota", "greek capital letter iota, U+0399" },
1905
{ 922,  "Kappa","greek capital letter kappa, U+039A" },
1906
{ 923,  "Lambda", "greek capital letter lambda, U+039B ISOgrk3" },
1907
{ 924,  "Mu", "greek capital letter mu, U+039C" },
1908
{ 925,  "Nu", "greek capital letter nu, U+039D" },
1909
{ 926,  "Xi", "greek capital letter xi, U+039E ISOgrk3" },
1910
{ 927,  "Omicron","greek capital letter omicron, U+039F" },
1911
{ 928,  "Pi", "greek capital letter pi, U+03A0 ISOgrk3" },
1912
{ 929,  "Rho",  "greek capital letter rho, U+03A1" },
1913
{ 931,  "Sigma","greek capital letter sigma, U+03A3 ISOgrk3" },
1914
{ 932,  "Tau",  "greek capital letter tau, U+03A4" },
1915
{ 933,  "Upsilon","greek capital letter upsilon, U+03A5 ISOgrk3" },
1916
{ 934,  "Phi",  "greek capital letter phi, U+03A6 ISOgrk3" },
1917
{ 935,  "Chi",  "greek capital letter chi, U+03A7" },
1918
{ 936,  "Psi",  "greek capital letter psi, U+03A8 ISOgrk3" },
1919
{ 937,  "Omega","greek capital letter omega, U+03A9 ISOgrk3" },
1920
1921
{ 945,  "alpha","greek small letter alpha, U+03B1 ISOgrk3" },
1922
{ 946,  "beta", "greek small letter beta, U+03B2 ISOgrk3" },
1923
{ 947,  "gamma","greek small letter gamma, U+03B3 ISOgrk3" },
1924
{ 948,  "delta","greek small letter delta, U+03B4 ISOgrk3" },
1925
{ 949,  "epsilon","greek small letter epsilon, U+03B5 ISOgrk3" },
1926
{ 950,  "zeta", "greek small letter zeta, U+03B6 ISOgrk3" },
1927
{ 951,  "eta",  "greek small letter eta, U+03B7 ISOgrk3" },
1928
{ 952,  "theta","greek small letter theta, U+03B8 ISOgrk3" },
1929
{ 953,  "iota", "greek small letter iota, U+03B9 ISOgrk3" },
1930
{ 954,  "kappa","greek small letter kappa, U+03BA ISOgrk3" },
1931
{ 955,  "lambda","greek small letter lambda, U+03BB ISOgrk3" },
1932
{ 956,  "mu", "greek small letter mu, U+03BC ISOgrk3" },
1933
{ 957,  "nu", "greek small letter nu, U+03BD ISOgrk3" },
1934
{ 958,  "xi", "greek small letter xi, U+03BE ISOgrk3" },
1935
{ 959,  "omicron","greek small letter omicron, U+03BF NEW" },
1936
{ 960,  "pi", "greek small letter pi, U+03C0 ISOgrk3" },
1937
{ 961,  "rho",  "greek small letter rho, U+03C1 ISOgrk3" },
1938
{ 962,  "sigmaf","greek small letter final sigma, U+03C2 ISOgrk3" },
1939
{ 963,  "sigma","greek small letter sigma, U+03C3 ISOgrk3" },
1940
{ 964,  "tau",  "greek small letter tau, U+03C4 ISOgrk3" },
1941
{ 965,  "upsilon","greek small letter upsilon, U+03C5 ISOgrk3" },
1942
{ 966,  "phi",  "greek small letter phi, U+03C6 ISOgrk3" },
1943
{ 967,  "chi",  "greek small letter chi, U+03C7 ISOgrk3" },
1944
{ 968,  "psi",  "greek small letter psi, U+03C8 ISOgrk3" },
1945
{ 969,  "omega","greek small letter omega, U+03C9 ISOgrk3" },
1946
{ 977,  "thetasym","greek small letter theta symbol, U+03D1 NEW" },
1947
{ 978,  "upsih","greek upsilon with hook symbol, U+03D2 NEW" },
1948
{ 982,  "piv",  "greek pi symbol, U+03D6 ISOgrk3" },
1949
1950
{ 8194, "ensp", "en space, U+2002 ISOpub" },
1951
{ 8195, "emsp", "em space, U+2003 ISOpub" },
1952
{ 8201, "thinsp","thin space, U+2009 ISOpub" },
1953
{ 8204, "zwnj", "zero width non-joiner, U+200C NEW RFC 2070" },
1954
{ 8205, "zwj",  "zero width joiner, U+200D NEW RFC 2070" },
1955
{ 8206, "lrm",  "left-to-right mark, U+200E NEW RFC 2070" },
1956
{ 8207, "rlm",  "right-to-left mark, U+200F NEW RFC 2070" },
1957
{ 8211, "ndash","en dash, U+2013 ISOpub" },
1958
{ 8212, "mdash","em dash, U+2014 ISOpub" },
1959
{ 8216, "lsquo","left single quotation mark, U+2018 ISOnum" },
1960
{ 8217, "rsquo","right single quotation mark, U+2019 ISOnum" },
1961
{ 8218, "sbquo","single low-9 quotation mark, U+201A NEW" },
1962
{ 8220, "ldquo","left double quotation mark, U+201C ISOnum" },
1963
{ 8221, "rdquo","right double quotation mark, U+201D ISOnum" },
1964
{ 8222, "bdquo","double low-9 quotation mark, U+201E NEW" },
1965
{ 8224, "dagger","dagger, U+2020 ISOpub" },
1966
{ 8225, "Dagger","double dagger, U+2021 ISOpub" },
1967
1968
{ 8226, "bull", "bullet = black small circle, U+2022 ISOpub" },
1969
{ 8230, "hellip","horizontal ellipsis = three dot leader, U+2026 ISOpub" },
1970
1971
{ 8240, "permil","per mille sign, U+2030 ISOtech" },
1972
1973
{ 8242, "prime","prime = minutes = feet, U+2032 ISOtech" },
1974
{ 8243, "Prime","double prime = seconds = inches, U+2033 ISOtech" },
1975
1976
{ 8249, "lsaquo","single left-pointing angle quotation mark, U+2039 ISO proposed" },
1977
{ 8250, "rsaquo","single right-pointing angle quotation mark, U+203A ISO proposed" },
1978
1979
{ 8254, "oline","overline = spacing overscore, U+203E NEW" },
1980
{ 8260, "frasl","fraction slash, U+2044 NEW" },
1981
1982
{ 8364, "euro", "euro sign, U+20AC NEW" },
1983
1984
{ 8465, "image","blackletter capital I = imaginary part, U+2111 ISOamso" },
1985
{ 8472, "weierp","script capital P = power set = Weierstrass p, U+2118 ISOamso" },
1986
{ 8476, "real", "blackletter capital R = real part symbol, U+211C ISOamso" },
1987
{ 8482, "trade","trade mark sign, U+2122 ISOnum" },
1988
{ 8501, "alefsym","alef symbol = first transfinite cardinal, U+2135 NEW" },
1989
{ 8592, "larr", "leftwards arrow, U+2190 ISOnum" },
1990
{ 8593, "uarr", "upwards arrow, U+2191 ISOnum" },
1991
{ 8594, "rarr", "rightwards arrow, U+2192 ISOnum" },
1992
{ 8595, "darr", "downwards arrow, U+2193 ISOnum" },
1993
{ 8596, "harr", "left right arrow, U+2194 ISOamsa" },
1994
{ 8629, "crarr","downwards arrow with corner leftwards = carriage return, U+21B5 NEW" },
1995
{ 8656, "lArr", "leftwards double arrow, U+21D0 ISOtech" },
1996
{ 8657, "uArr", "upwards double arrow, U+21D1 ISOamsa" },
1997
{ 8658, "rArr", "rightwards double arrow, U+21D2 ISOtech" },
1998
{ 8659, "dArr", "downwards double arrow, U+21D3 ISOamsa" },
1999
{ 8660, "hArr", "left right double arrow, U+21D4 ISOamsa" },
2000
2001
{ 8704, "forall","for all, U+2200 ISOtech" },
2002
{ 8706, "part", "partial differential, U+2202 ISOtech" },
2003
{ 8707, "exist","there exists, U+2203 ISOtech" },
2004
{ 8709, "empty","empty set = null set = diameter, U+2205 ISOamso" },
2005
{ 8711, "nabla","nabla = backward difference, U+2207 ISOtech" },
2006
{ 8712, "isin", "element of, U+2208 ISOtech" },
2007
{ 8713, "notin","not an element of, U+2209 ISOtech" },
2008
{ 8715, "ni", "contains as member, U+220B ISOtech" },
2009
{ 8719, "prod", "n-ary product = product sign, U+220F ISOamsb" },
2010
{ 8721, "sum",  "n-ary summation, U+2211 ISOamsb" },
2011
{ 8722, "minus","minus sign, U+2212 ISOtech" },
2012
{ 8727, "lowast","asterisk operator, U+2217 ISOtech" },
2013
{ 8730, "radic","square root = radical sign, U+221A ISOtech" },
2014
{ 8733, "prop", "proportional to, U+221D ISOtech" },
2015
{ 8734, "infin","infinity, U+221E ISOtech" },
2016
{ 8736, "ang",  "angle, U+2220 ISOamso" },
2017
{ 8743, "and",  "logical and = wedge, U+2227 ISOtech" },
2018
{ 8744, "or", "logical or = vee, U+2228 ISOtech" },
2019
{ 8745, "cap",  "intersection = cap, U+2229 ISOtech" },
2020
{ 8746, "cup",  "union = cup, U+222A ISOtech" },
2021
{ 8747, "int",  "integral, U+222B ISOtech" },
2022
{ 8756, "there4","therefore, U+2234 ISOtech" },
2023
{ 8764, "sim",  "tilde operator = varies with = similar to, U+223C ISOtech" },
2024
{ 8773, "cong", "approximately equal to, U+2245 ISOtech" },
2025
{ 8776, "asymp","almost equal to = asymptotic to, U+2248 ISOamsr" },
2026
{ 8800, "ne", "not equal to, U+2260 ISOtech" },
2027
{ 8801, "equiv","identical to, U+2261 ISOtech" },
2028
{ 8804, "le", "less-than or equal to, U+2264 ISOtech" },
2029
{ 8805, "ge", "greater-than or equal to, U+2265 ISOtech" },
2030
{ 8834, "sub",  "subset of, U+2282 ISOtech" },
2031
{ 8835, "sup",  "superset of, U+2283 ISOtech" },
2032
{ 8836, "nsub", "not a subset of, U+2284 ISOamsn" },
2033
{ 8838, "sube", "subset of or equal to, U+2286 ISOtech" },
2034
{ 8839, "supe", "superset of or equal to, U+2287 ISOtech" },
2035
{ 8853, "oplus","circled plus = direct sum, U+2295 ISOamsb" },
2036
{ 8855, "otimes","circled times = vector product, U+2297 ISOamsb" },
2037
{ 8869, "perp", "up tack = orthogonal to = perpendicular, U+22A5 ISOtech" },
2038
{ 8901, "sdot", "dot operator, U+22C5 ISOamsb" },
2039
{ 8968, "lceil","left ceiling = apl upstile, U+2308 ISOamsc" },
2040
{ 8969, "rceil","right ceiling, U+2309 ISOamsc" },
2041
{ 8970, "lfloor","left floor = apl downstile, U+230A ISOamsc" },
2042
{ 8971, "rfloor","right floor, U+230B ISOamsc" },
2043
{ 9001, "lang", "left-pointing angle bracket = bra, U+2329 ISOtech" },
2044
{ 9002, "rang", "right-pointing angle bracket = ket, U+232A ISOtech" },
2045
{ 9674, "loz",  "lozenge, U+25CA ISOpub" },
2046
2047
{ 9824, "spades","black spade suit, U+2660 ISOpub" },
2048
{ 9827, "clubs","black club suit = shamrock, U+2663 ISOpub" },
2049
{ 9829, "hearts","black heart suit = valentine, U+2665 ISOpub" },
2050
{ 9830, "diams","black diamond suit, U+2666 ISOpub" },
2051
2052
};
2053
2054
/************************************************************************
2055
 *                  *
2056
 *    Commodity functions to handle entities      *
2057
 *                  *
2058
 ************************************************************************/
2059
2060
/*
2061
 * Macro used to grow the current buffer.
2062
 */
2063
0
#define growBuffer(buffer) {           \
2064
0
    xmlChar *tmp;             \
2065
0
    buffer##_size *= 2;             \
2066
0
    tmp = (xmlChar *) xmlRealloc(buffer, buffer##_size);    \
2067
0
    if (tmp == NULL) {             \
2068
0
  htmlErrMemory(ctxt, "growing buffer\n");      \
2069
0
  xmlFree(buffer);            \
2070
0
  return(NULL);             \
2071
0
    }                  \
2072
0
    buffer = tmp;             \
2073
0
}
2074
2075
/**
2076
 * htmlEntityLookup:
2077
 * @name: the entity name
2078
 *
2079
 * Lookup the given entity in EntitiesTable
2080
 *
2081
 * TODO: the linear scan is really ugly, an hash table is really needed.
2082
 *
2083
 * Returns the associated htmlEntityDescPtr if found, NULL otherwise.
2084
 */
2085
const htmlEntityDesc *
2086
0
htmlEntityLookup(const xmlChar *name) {
2087
0
    unsigned int i;
2088
2089
0
    for (i = 0;i < (sizeof(html40EntitiesTable)/
2090
0
                    sizeof(html40EntitiesTable[0]));i++) {
2091
0
        if (xmlStrEqual(name, BAD_CAST html40EntitiesTable[i].name)) {
2092
0
            return((htmlEntityDescPtr) &html40EntitiesTable[i]);
2093
0
  }
2094
0
    }
2095
0
    return(NULL);
2096
0
}
2097
2098
/**
2099
 * htmlEntityValueLookup:
2100
 * @value: the entity's unicode value
2101
 *
2102
 * Lookup the given entity in EntitiesTable
2103
 *
2104
 * TODO: the linear scan is really ugly, an hash table is really needed.
2105
 *
2106
 * Returns the associated htmlEntityDescPtr if found, NULL otherwise.
2107
 */
2108
const htmlEntityDesc *
2109
5.72M
htmlEntityValueLookup(unsigned int value) {
2110
5.72M
    unsigned int i;
2111
2112
202M
    for (i = 0;i < (sizeof(html40EntitiesTable)/
2113
202M
                    sizeof(html40EntitiesTable[0]));i++) {
2114
202M
        if (html40EntitiesTable[i].value >= value) {
2115
5.72M
      if (html40EntitiesTable[i].value > value)
2116
759k
    break;
2117
4.96M
            return((htmlEntityDescPtr) &html40EntitiesTable[i]);
2118
5.72M
  }
2119
202M
    }
2120
759k
    return(NULL);
2121
5.72M
}
2122
2123
/**
2124
 * UTF8ToHtml:
2125
 * @out:  a pointer to an array of bytes to store the result
2126
 * @outlen:  the length of @out
2127
 * @in:  a pointer to an array of UTF-8 chars
2128
 * @inlen:  the length of @in
2129
 *
2130
 * Take a block of UTF-8 chars in and try to convert it to an ASCII
2131
 * plus HTML entities block of chars out.
2132
 *
2133
 * Returns 0 if success, -2 if the transcoding fails, or -1 otherwise
2134
 * The value of @inlen after return is the number of octets consumed
2135
 *     as the return value is positive, else unpredictable.
2136
 * The value of @outlen after return is the number of octets consumed.
2137
 */
2138
int
2139
UTF8ToHtml(unsigned char* out, int *outlen,
2140
1.24k
              const unsigned char* in, int *inlen) {
2141
1.24k
    const unsigned char* processed = in;
2142
1.24k
    const unsigned char* outend;
2143
1.24k
    const unsigned char* outstart = out;
2144
1.24k
    const unsigned char* instart = in;
2145
1.24k
    const unsigned char* inend;
2146
1.24k
    unsigned int c, d;
2147
1.24k
    int trailing;
2148
2149
1.24k
    if ((out == NULL) || (outlen == NULL) || (inlen == NULL)) return(-1);
2150
1.10k
    if (in == NULL) {
2151
        /*
2152
   * initialization nothing to do
2153
   */
2154
117
  *outlen = 0;
2155
117
  *inlen = 0;
2156
117
  return(0);
2157
117
    }
2158
983
    inend = in + (*inlen);
2159
983
    outend = out + (*outlen);
2160
7.14M
    while (in < inend) {
2161
7.14M
  d = *in++;
2162
7.14M
  if      (d < 0x80)  { c= d; trailing= 0; }
2163
5.72M
  else if (d < 0xC0) {
2164
      /* trailing byte in leading position */
2165
0
      *outlen = out - outstart;
2166
0
      *inlen = processed - instart;
2167
0
      return(-2);
2168
5.72M
        } else if (d < 0xE0)  { c= d & 0x1F; trailing= 1; }
2169
1.29k
        else if (d < 0xF0)  { c= d & 0x0F; trailing= 2; }
2170
303
        else if (d < 0xF8)  { c= d & 0x07; trailing= 3; }
2171
0
  else {
2172
      /* no chance for this in Ascii */
2173
0
      *outlen = out - outstart;
2174
0
      *inlen = processed - instart;
2175
0
      return(-2);
2176
0
  }
2177
2178
7.14M
  if (inend - in < trailing) {
2179
237
      break;
2180
237
  }
2181
2182
12.8M
  for ( ; trailing; trailing--) {
2183
5.72M
      if ((in >= inend) || (((d= *in++) & 0xC0) != 0x80))
2184
0
    break;
2185
5.72M
      c <<= 6;
2186
5.72M
      c |= d & 0x3F;
2187
5.72M
  }
2188
2189
  /* assertion: c is a single UTF-4 value */
2190
7.14M
  if (c < 0x80) {
2191
1.41M
      if (out + 1 >= outend)
2192
0
    break;
2193
1.41M
      *out++ = c;
2194
5.72M
  } else {
2195
5.72M
      int len;
2196
5.72M
      const htmlEntityDesc * ent;
2197
5.72M
      const char *cp;
2198
5.72M
      char nbuf[16];
2199
2200
      /*
2201
       * Try to lookup a predefined HTML entity for it
2202
       */
2203
2204
5.72M
      ent = htmlEntityValueLookup(c);
2205
5.72M
      if (ent == NULL) {
2206
759k
        snprintf(nbuf, sizeof(nbuf), "#%u", c);
2207
759k
        cp = nbuf;
2208
759k
      }
2209
4.96M
      else
2210
4.96M
        cp = ent->name;
2211
5.72M
      len = strlen(cp);
2212
5.72M
      if (out + 2 + len >= outend)
2213
53
    break;
2214
5.72M
      *out++ = '&';
2215
5.72M
      memcpy(out, cp, len);
2216
5.72M
      out += len;
2217
5.72M
      *out++ = ';';
2218
5.72M
  }
2219
7.14M
  processed = in;
2220
7.14M
    }
2221
983
    *outlen = out - outstart;
2222
983
    *inlen = processed - instart;
2223
983
    return(0);
2224
983
}
2225
2226
/**
2227
 * htmlEncodeEntities:
2228
 * @out:  a pointer to an array of bytes to store the result
2229
 * @outlen:  the length of @out
2230
 * @in:  a pointer to an array of UTF-8 chars
2231
 * @inlen:  the length of @in
2232
 * @quoteChar: the quote character to escape (' or ") or zero.
2233
 *
2234
 * Take a block of UTF-8 chars in and try to convert it to an ASCII
2235
 * plus HTML entities block of chars out.
2236
 *
2237
 * Returns 0 if success, -2 if the transcoding fails, or -1 otherwise
2238
 * The value of @inlen after return is the number of octets consumed
2239
 *     as the return value is positive, else unpredictable.
2240
 * The value of @outlen after return is the number of octets consumed.
2241
 */
2242
int
2243
htmlEncodeEntities(unsigned char* out, int *outlen,
2244
0
       const unsigned char* in, int *inlen, int quoteChar) {
2245
0
    const unsigned char* processed = in;
2246
0
    const unsigned char* outend;
2247
0
    const unsigned char* outstart = out;
2248
0
    const unsigned char* instart = in;
2249
0
    const unsigned char* inend;
2250
0
    unsigned int c, d;
2251
0
    int trailing;
2252
2253
0
    if ((out == NULL) || (outlen == NULL) || (inlen == NULL) || (in == NULL))
2254
0
        return(-1);
2255
0
    outend = out + (*outlen);
2256
0
    inend = in + (*inlen);
2257
0
    while (in < inend) {
2258
0
  d = *in++;
2259
0
  if      (d < 0x80)  { c= d; trailing= 0; }
2260
0
  else if (d < 0xC0) {
2261
      /* trailing byte in leading position */
2262
0
      *outlen = out - outstart;
2263
0
      *inlen = processed - instart;
2264
0
      return(-2);
2265
0
        } else if (d < 0xE0)  { c= d & 0x1F; trailing= 1; }
2266
0
        else if (d < 0xF0)  { c= d & 0x0F; trailing= 2; }
2267
0
        else if (d < 0xF8)  { c= d & 0x07; trailing= 3; }
2268
0
  else {
2269
      /* no chance for this in Ascii */
2270
0
      *outlen = out - outstart;
2271
0
      *inlen = processed - instart;
2272
0
      return(-2);
2273
0
  }
2274
2275
0
  if (inend - in < trailing)
2276
0
      break;
2277
2278
0
  while (trailing--) {
2279
0
      if (((d= *in++) & 0xC0) != 0x80) {
2280
0
    *outlen = out - outstart;
2281
0
    *inlen = processed - instart;
2282
0
    return(-2);
2283
0
      }
2284
0
      c <<= 6;
2285
0
      c |= d & 0x3F;
2286
0
  }
2287
2288
  /* assertion: c is a single UTF-4 value */
2289
0
  if ((c < 0x80) && (c != (unsigned int) quoteChar) &&
2290
0
      (c != '&') && (c != '<') && (c != '>')) {
2291
0
      if (out >= outend)
2292
0
    break;
2293
0
      *out++ = c;
2294
0
  } else {
2295
0
      const htmlEntityDesc * ent;
2296
0
      const char *cp;
2297
0
      char nbuf[16];
2298
0
      int len;
2299
2300
      /*
2301
       * Try to lookup a predefined HTML entity for it
2302
       */
2303
0
      ent = htmlEntityValueLookup(c);
2304
0
      if (ent == NULL) {
2305
0
    snprintf(nbuf, sizeof(nbuf), "#%u", c);
2306
0
    cp = nbuf;
2307
0
      }
2308
0
      else
2309
0
    cp = ent->name;
2310
0
      len = strlen(cp);
2311
0
      if (outend - out < len + 2)
2312
0
    break;
2313
0
      *out++ = '&';
2314
0
      memcpy(out, cp, len);
2315
0
      out += len;
2316
0
      *out++ = ';';
2317
0
  }
2318
0
  processed = in;
2319
0
    }
2320
0
    *outlen = out - outstart;
2321
0
    *inlen = processed - instart;
2322
0
    return(0);
2323
0
}
2324
2325
/************************************************************************
2326
 *                  *
2327
 *    Commodity functions to handle streams     *
2328
 *                  *
2329
 ************************************************************************/
2330
2331
#ifdef LIBXML_PUSH_ENABLED
2332
/**
2333
 * htmlNewInputStream:
2334
 * @ctxt:  an HTML parser context
2335
 *
2336
 * Create a new input stream structure
2337
 * Returns the new input stream or NULL
2338
 */
2339
static htmlParserInputPtr
2340
htmlNewInputStream(htmlParserCtxtPtr ctxt) {
2341
    htmlParserInputPtr input;
2342
2343
    input = (xmlParserInputPtr) xmlMalloc(sizeof(htmlParserInput));
2344
    if (input == NULL) {
2345
        htmlErrMemory(ctxt, "couldn't allocate a new input stream\n");
2346
  return(NULL);
2347
    }
2348
    memset(input, 0, sizeof(htmlParserInput));
2349
    input->filename = NULL;
2350
    input->directory = NULL;
2351
    input->base = NULL;
2352
    input->cur = NULL;
2353
    input->buf = NULL;
2354
    input->line = 1;
2355
    input->col = 1;
2356
    input->buf = NULL;
2357
    input->free = NULL;
2358
    input->version = NULL;
2359
    input->consumed = 0;
2360
    input->length = 0;
2361
    return(input);
2362
}
2363
#endif
2364
2365
2366
/************************************************************************
2367
 *                  *
2368
 *    Commodity functions, cleanup needed ?     *
2369
 *                  *
2370
 ************************************************************************/
2371
/*
2372
 * all tags allowing pc data from the html 4.01 loose dtd
2373
 * NOTE: it might be more appropriate to integrate this information
2374
 * into the html40ElementTable array but I don't want to risk any
2375
 * binary incompatibility
2376
 */
2377
static const char *allowPCData[] = {
2378
    "a", "abbr", "acronym", "address", "applet", "b", "bdo", "big",
2379
    "blockquote", "body", "button", "caption", "center", "cite", "code",
2380
    "dd", "del", "dfn", "div", "dt", "em", "font", "form", "h1", "h2",
2381
    "h3", "h4", "h5", "h6", "i", "iframe", "ins", "kbd", "label", "legend",
2382
    "li", "noframes", "noscript", "object", "p", "pre", "q", "s", "samp",
2383
    "small", "span", "strike", "strong", "td", "th", "tt", "u", "var"
2384
};
2385
2386
/**
2387
 * areBlanks:
2388
 * @ctxt:  an HTML parser context
2389
 * @str:  a xmlChar *
2390
 * @len:  the size of @str
2391
 *
2392
 * Is this a sequence of blank chars that one can ignore ?
2393
 *
2394
 * Returns 1 if ignorable 0 otherwise.
2395
 */
2396
2397
0
static int areBlanks(htmlParserCtxtPtr ctxt, const xmlChar *str, int len) {
2398
0
    unsigned int i;
2399
0
    int j;
2400
0
    xmlNodePtr lastChild;
2401
0
    xmlDtdPtr dtd;
2402
2403
0
    for (j = 0;j < len;j++)
2404
0
        if (!(IS_BLANK_CH(str[j]))) return(0);
2405
2406
0
    if (CUR == 0) return(1);
2407
0
    if (CUR != '<') return(0);
2408
0
    if (ctxt->name == NULL)
2409
0
  return(1);
2410
0
    if (xmlStrEqual(ctxt->name, BAD_CAST"html"))
2411
0
  return(1);
2412
0
    if (xmlStrEqual(ctxt->name, BAD_CAST"head"))
2413
0
  return(1);
2414
2415
    /* Only strip CDATA children of the body tag for strict HTML DTDs */
2416
0
    if (xmlStrEqual(ctxt->name, BAD_CAST "body") && ctxt->myDoc != NULL) {
2417
0
        dtd = xmlGetIntSubset(ctxt->myDoc);
2418
0
        if (dtd != NULL && dtd->ExternalID != NULL) {
2419
0
            if (!xmlStrcasecmp(dtd->ExternalID, BAD_CAST "-//W3C//DTD HTML 4.01//EN") ||
2420
0
                    !xmlStrcasecmp(dtd->ExternalID, BAD_CAST "-//W3C//DTD HTML 4//EN"))
2421
0
                return(1);
2422
0
        }
2423
0
    }
2424
2425
0
    if (ctxt->node == NULL) return(0);
2426
0
    lastChild = xmlGetLastChild(ctxt->node);
2427
0
    while ((lastChild) && (lastChild->type == XML_COMMENT_NODE))
2428
0
  lastChild = lastChild->prev;
2429
0
    if (lastChild == NULL) {
2430
0
        if ((ctxt->node->type != XML_ELEMENT_NODE) &&
2431
0
            (ctxt->node->content != NULL)) return(0);
2432
  /* keep ws in constructs like ...<b> </b>...
2433
     for all tags "b" allowing PCDATA */
2434
0
  for ( i = 0; i < sizeof(allowPCData)/sizeof(allowPCData[0]); i++ ) {
2435
0
      if ( xmlStrEqual(ctxt->name, BAD_CAST allowPCData[i]) ) {
2436
0
    return(0);
2437
0
      }
2438
0
  }
2439
0
    } else if (xmlNodeIsText(lastChild)) {
2440
0
        return(0);
2441
0
    } else {
2442
  /* keep ws in constructs like <p><b>xy</b> <i>z</i><p>
2443
     for all tags "p" allowing PCDATA */
2444
0
  for ( i = 0; i < sizeof(allowPCData)/sizeof(allowPCData[0]); i++ ) {
2445
0
      if ( xmlStrEqual(lastChild->name, BAD_CAST allowPCData[i]) ) {
2446
0
    return(0);
2447
0
      }
2448
0
  }
2449
0
    }
2450
0
    return(1);
2451
0
}
2452
2453
/**
2454
 * htmlNewDocNoDtD:
2455
 * @URI:  URI for the dtd, or NULL
2456
 * @ExternalID:  the external ID of the DTD, or NULL
2457
 *
2458
 * Creates a new HTML document without a DTD node if @URI and @ExternalID
2459
 * are NULL
2460
 *
2461
 * Returns a new document, do not initialize the DTD if not provided
2462
 */
2463
htmlDocPtr
2464
384
htmlNewDocNoDtD(const xmlChar *URI, const xmlChar *ExternalID) {
2465
384
    xmlDocPtr cur;
2466
2467
    /*
2468
     * Allocate a new document and fill the fields.
2469
     */
2470
384
    cur = (xmlDocPtr) xmlMalloc(sizeof(xmlDoc));
2471
384
    if (cur == NULL) {
2472
1
  htmlErrMemory(NULL, "HTML document creation failed\n");
2473
1
  return(NULL);
2474
1
    }
2475
383
    memset(cur, 0, sizeof(xmlDoc));
2476
2477
383
    cur->type = XML_HTML_DOCUMENT_NODE;
2478
383
    cur->version = NULL;
2479
383
    cur->intSubset = NULL;
2480
383
    cur->doc = cur;
2481
383
    cur->name = NULL;
2482
383
    cur->children = NULL;
2483
383
    cur->extSubset = NULL;
2484
383
    cur->oldNs = NULL;
2485
383
    cur->encoding = NULL;
2486
383
    cur->standalone = 1;
2487
383
    cur->compression = 0;
2488
383
    cur->ids = NULL;
2489
383
    cur->refs = NULL;
2490
383
    cur->_private = NULL;
2491
383
    cur->charset = XML_CHAR_ENCODING_UTF8;
2492
383
    cur->properties = XML_DOC_HTML | XML_DOC_USERBUILT;
2493
383
    if ((ExternalID != NULL) ||
2494
383
  (URI != NULL))
2495
383
  xmlCreateIntSubset(cur, BAD_CAST "html", ExternalID, URI);
2496
383
    if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2497
0
  xmlRegisterNodeDefaultValue((xmlNodePtr)cur);
2498
383
    return(cur);
2499
384
}
2500
2501
/**
2502
 * htmlNewDoc:
2503
 * @URI:  URI for the dtd, or NULL
2504
 * @ExternalID:  the external ID of the DTD, or NULL
2505
 *
2506
 * Creates a new HTML document
2507
 *
2508
 * Returns a new document
2509
 */
2510
htmlDocPtr
2511
384
htmlNewDoc(const xmlChar *URI, const xmlChar *ExternalID) {
2512
384
    if ((URI == NULL) && (ExternalID == NULL))
2513
384
  return(htmlNewDocNoDtD(
2514
384
        BAD_CAST "http://www.w3.org/TR/REC-html40/loose.dtd",
2515
384
        BAD_CAST "-//W3C//DTD HTML 4.0 Transitional//EN"));
2516
2517
0
    return(htmlNewDocNoDtD(URI, ExternalID));
2518
384
}
2519
2520
2521
/************************************************************************
2522
 *                  *
2523
 *      The parser itself       *
2524
 *  Relates to http://www.w3.org/TR/html40        *
2525
 *                  *
2526
 ************************************************************************/
2527
2528
/************************************************************************
2529
 *                  *
2530
 *      The parser itself       *
2531
 *                  *
2532
 ************************************************************************/
2533
2534
static const xmlChar * htmlParseNameComplex(xmlParserCtxtPtr ctxt);
2535
2536
static void
2537
0
htmlSkipBogusComment(htmlParserCtxtPtr ctxt) {
2538
0
    int c;
2539
2540
0
    htmlParseErr(ctxt, XML_HTML_INCORRECTLY_OPENED_COMMENT,
2541
0
                 "Incorrectly opened comment\n", NULL, NULL);
2542
2543
0
    do {
2544
0
        c = CUR;
2545
0
        if (c == 0)
2546
0
            break;
2547
0
        NEXT;
2548
0
    } while (c != '>');
2549
0
}
2550
2551
/**
2552
 * htmlParseHTMLName:
2553
 * @ctxt:  an HTML parser context
2554
 *
2555
 * parse an HTML tag or attribute name, note that we convert it to lowercase
2556
 * since HTML names are not case-sensitive.
2557
 *
2558
 * Returns the Tag Name parsed or NULL
2559
 */
2560
2561
static const xmlChar *
2562
0
htmlParseHTMLName(htmlParserCtxtPtr ctxt) {
2563
0
    const xmlChar *ret;
2564
0
    int i = 0;
2565
0
    xmlChar loc[HTML_PARSER_BUFFER_SIZE];
2566
2567
0
    if (!IS_ASCII_LETTER(CUR) && (CUR != '_') &&
2568
0
        (CUR != ':') && (CUR != '.')) return(NULL);
2569
2570
0
    while ((i < HTML_PARSER_BUFFER_SIZE) &&
2571
0
           ((IS_ASCII_LETTER(CUR)) || (IS_ASCII_DIGIT(CUR)) ||
2572
0
     (CUR == ':') || (CUR == '-') || (CUR == '_') ||
2573
0
           (CUR == '.'))) {
2574
0
  if ((CUR >= 'A') && (CUR <= 'Z')) loc[i] = CUR + 0x20;
2575
0
        else loc[i] = CUR;
2576
0
  i++;
2577
2578
0
  NEXT;
2579
0
    }
2580
2581
0
    ret = xmlDictLookup(ctxt->dict, loc, i);
2582
0
    if (ret == NULL)
2583
0
        htmlErrMemory(ctxt, NULL);
2584
2585
0
    return(ret);
2586
0
}
2587
2588
2589
/**
2590
 * htmlParseHTMLName_nonInvasive:
2591
 * @ctxt:  an HTML parser context
2592
 *
2593
 * parse an HTML tag or attribute name, note that we convert it to lowercase
2594
 * since HTML names are not case-sensitive, this doesn't consume the data
2595
 * from the stream, it's a look-ahead
2596
 *
2597
 * Returns the Tag Name parsed or NULL
2598
 */
2599
2600
static const xmlChar *
2601
0
htmlParseHTMLName_nonInvasive(htmlParserCtxtPtr ctxt) {
2602
0
    int i = 0;
2603
0
    xmlChar loc[HTML_PARSER_BUFFER_SIZE];
2604
2605
0
    if (!IS_ASCII_LETTER(NXT(1)) && (NXT(1) != '_') &&
2606
0
        (NXT(1) != ':')) return(NULL);
2607
2608
0
    while ((i < HTML_PARSER_BUFFER_SIZE) &&
2609
0
           ((IS_ASCII_LETTER(NXT(1+i))) || (IS_ASCII_DIGIT(NXT(1+i))) ||
2610
0
     (NXT(1+i) == ':') || (NXT(1+i) == '-') || (NXT(1+i) == '_'))) {
2611
0
  if ((NXT(1+i) >= 'A') && (NXT(1+i) <= 'Z')) loc[i] = NXT(1+i) + 0x20;
2612
0
        else loc[i] = NXT(1+i);
2613
0
  i++;
2614
0
    }
2615
2616
0
    return(xmlDictLookup(ctxt->dict, loc, i));
2617
0
}
2618
2619
2620
/**
2621
 * htmlParseName:
2622
 * @ctxt:  an HTML parser context
2623
 *
2624
 * parse an HTML name, this routine is case sensitive.
2625
 *
2626
 * Returns the Name parsed or NULL
2627
 */
2628
2629
static const xmlChar *
2630
0
htmlParseName(htmlParserCtxtPtr ctxt) {
2631
0
    const xmlChar *in;
2632
0
    const xmlChar *ret;
2633
0
    int count = 0;
2634
2635
0
    GROW;
2636
2637
    /*
2638
     * Accelerator for simple ASCII names
2639
     */
2640
0
    in = ctxt->input->cur;
2641
0
    if (((*in >= 0x61) && (*in <= 0x7A)) ||
2642
0
  ((*in >= 0x41) && (*in <= 0x5A)) ||
2643
0
  (*in == '_') || (*in == ':')) {
2644
0
  in++;
2645
0
  while (((*in >= 0x61) && (*in <= 0x7A)) ||
2646
0
         ((*in >= 0x41) && (*in <= 0x5A)) ||
2647
0
         ((*in >= 0x30) && (*in <= 0x39)) ||
2648
0
         (*in == '_') || (*in == '-') ||
2649
0
         (*in == ':') || (*in == '.'))
2650
0
      in++;
2651
2652
0
  if (in == ctxt->input->end)
2653
0
      return(NULL);
2654
2655
0
  if ((*in > 0) && (*in < 0x80)) {
2656
0
      count = in - ctxt->input->cur;
2657
0
      ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count);
2658
0
      ctxt->input->cur = in;
2659
0
      ctxt->input->col += count;
2660
0
      return(ret);
2661
0
  }
2662
0
    }
2663
0
    return(htmlParseNameComplex(ctxt));
2664
0
}
2665
2666
static const xmlChar *
2667
0
htmlParseNameComplex(xmlParserCtxtPtr ctxt) {
2668
0
    int len = 0, l;
2669
0
    int c;
2670
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
2671
0
                    XML_MAX_TEXT_LENGTH :
2672
0
                    XML_MAX_NAME_LENGTH;
2673
0
    const xmlChar *base = ctxt->input->base;
2674
2675
    /*
2676
     * Handler for more complex cases
2677
     */
2678
0
    c = CUR_CHAR(l);
2679
0
    if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
2680
0
  (!IS_LETTER(c) && (c != '_') &&
2681
0
         (c != ':'))) {
2682
0
  return(NULL);
2683
0
    }
2684
2685
0
    while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
2686
0
     ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
2687
0
            (c == '.') || (c == '-') ||
2688
0
      (c == '_') || (c == ':') ||
2689
0
      (IS_COMBINING(c)) ||
2690
0
      (IS_EXTENDER(c)))) {
2691
0
  len += l;
2692
0
        if (len > maxLength) {
2693
0
            htmlParseErr(ctxt, XML_ERR_NAME_TOO_LONG, "name too long", NULL, NULL);
2694
0
            return(NULL);
2695
0
        }
2696
0
  NEXTL(l);
2697
0
  c = CUR_CHAR(l);
2698
0
  if (ctxt->input->base != base) {
2699
      /*
2700
       * We changed encoding from an unknown encoding
2701
       * Input buffer changed location, so we better start again
2702
       */
2703
0
      return(htmlParseNameComplex(ctxt));
2704
0
  }
2705
0
    }
2706
0
    if (ctxt->instate == XML_PARSER_EOF)
2707
0
        return(NULL);
2708
2709
0
    if (ctxt->input->cur - ctxt->input->base < len) {
2710
        /* Sanity check */
2711
0
  htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
2712
0
                     "unexpected change of input buffer", NULL, NULL);
2713
0
        return (NULL);
2714
0
    }
2715
2716
0
    return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
2717
0
}
2718
2719
2720
/**
2721
 * htmlParseHTMLAttribute:
2722
 * @ctxt:  an HTML parser context
2723
 * @stop:  a char stop value
2724
 *
2725
 * parse an HTML attribute value till the stop (quote), if
2726
 * stop is 0 then it stops at the first space
2727
 *
2728
 * Returns the attribute parsed or NULL
2729
 */
2730
2731
static xmlChar *
2732
0
htmlParseHTMLAttribute(htmlParserCtxtPtr ctxt, const xmlChar stop) {
2733
0
    xmlChar *buffer = NULL;
2734
0
    int buffer_size = 0;
2735
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
2736
0
                    XML_MAX_HUGE_LENGTH :
2737
0
                    XML_MAX_TEXT_LENGTH;
2738
0
    xmlChar *out = NULL;
2739
0
    const xmlChar *name = NULL;
2740
0
    const xmlChar *cur = NULL;
2741
0
    const htmlEntityDesc * ent;
2742
2743
    /*
2744
     * allocate a translation buffer.
2745
     */
2746
0
    buffer_size = HTML_PARSER_BUFFER_SIZE;
2747
0
    buffer = (xmlChar *) xmlMallocAtomic(buffer_size);
2748
0
    if (buffer == NULL) {
2749
0
  htmlErrMemory(ctxt, "buffer allocation failed\n");
2750
0
  return(NULL);
2751
0
    }
2752
0
    out = buffer;
2753
2754
    /*
2755
     * Ok loop until we reach one of the ending chars
2756
     */
2757
0
    while ((CUR != 0) && (CUR != stop)) {
2758
0
  if ((stop == 0) && (CUR == '>')) break;
2759
0
  if ((stop == 0) && (IS_BLANK_CH(CUR))) break;
2760
0
        if (CUR == '&') {
2761
0
      if (NXT(1) == '#') {
2762
0
    unsigned int c;
2763
0
    int bits;
2764
2765
0
    c = htmlParseCharRef(ctxt);
2766
0
    if      (c <    0x80)
2767
0
            { *out++  = c;                bits= -6; }
2768
0
    else if (c <   0x800)
2769
0
            { *out++  =((c >>  6) & 0x1F) | 0xC0;  bits=  0; }
2770
0
    else if (c < 0x10000)
2771
0
            { *out++  =((c >> 12) & 0x0F) | 0xE0;  bits=  6; }
2772
0
    else
2773
0
            { *out++  =((c >> 18) & 0x07) | 0xF0;  bits= 12; }
2774
2775
0
    for ( ; bits >= 0; bits-= 6) {
2776
0
        *out++  = ((c >> bits) & 0x3F) | 0x80;
2777
0
    }
2778
2779
0
    if (out - buffer > buffer_size - 100) {
2780
0
      int indx = out - buffer;
2781
2782
0
      growBuffer(buffer);
2783
0
      out = &buffer[indx];
2784
0
    }
2785
0
      } else {
2786
0
    ent = htmlParseEntityRef(ctxt, &name);
2787
0
    if (name == NULL) {
2788
0
        *out++ = '&';
2789
0
        if (out - buffer > buffer_size - 100) {
2790
0
      int indx = out - buffer;
2791
2792
0
      growBuffer(buffer);
2793
0
      out = &buffer[indx];
2794
0
        }
2795
0
    } else if (ent == NULL) {
2796
0
        *out++ = '&';
2797
0
        cur = name;
2798
0
        while (*cur != 0) {
2799
0
      if (out - buffer > buffer_size - 100) {
2800
0
          int indx = out - buffer;
2801
2802
0
          growBuffer(buffer);
2803
0
          out = &buffer[indx];
2804
0
      }
2805
0
      *out++ = *cur++;
2806
0
        }
2807
0
    } else {
2808
0
        unsigned int c;
2809
0
        int bits;
2810
2811
0
        if (out - buffer > buffer_size - 100) {
2812
0
      int indx = out - buffer;
2813
2814
0
      growBuffer(buffer);
2815
0
      out = &buffer[indx];
2816
0
        }
2817
0
        c = ent->value;
2818
0
        if      (c <    0x80)
2819
0
      { *out++  = c;                bits= -6; }
2820
0
        else if (c <   0x800)
2821
0
      { *out++  =((c >>  6) & 0x1F) | 0xC0;  bits=  0; }
2822
0
        else if (c < 0x10000)
2823
0
      { *out++  =((c >> 12) & 0x0F) | 0xE0;  bits=  6; }
2824
0
        else
2825
0
      { *out++  =((c >> 18) & 0x07) | 0xF0;  bits= 12; }
2826
2827
0
        for ( ; bits >= 0; bits-= 6) {
2828
0
      *out++  = ((c >> bits) & 0x3F) | 0x80;
2829
0
        }
2830
0
    }
2831
0
      }
2832
0
  } else {
2833
0
      unsigned int c;
2834
0
      int bits, l;
2835
2836
0
      if (out - buffer > buffer_size - 100) {
2837
0
    int indx = out - buffer;
2838
2839
0
    growBuffer(buffer);
2840
0
    out = &buffer[indx];
2841
0
      }
2842
0
      c = CUR_CHAR(l);
2843
0
            if (ctxt->instate == XML_PARSER_EOF) {
2844
0
                xmlFree(buffer);
2845
0
                return(NULL);
2846
0
            }
2847
0
      if      (c <    0x80)
2848
0
        { *out++  = c;                bits= -6; }
2849
0
      else if (c <   0x800)
2850
0
        { *out++  =((c >>  6) & 0x1F) | 0xC0;  bits=  0; }
2851
0
      else if (c < 0x10000)
2852
0
        { *out++  =((c >> 12) & 0x0F) | 0xE0;  bits=  6; }
2853
0
      else
2854
0
        { *out++  =((c >> 18) & 0x07) | 0xF0;  bits= 12; }
2855
2856
0
      for ( ; bits >= 0; bits-= 6) {
2857
0
    *out++  = ((c >> bits) & 0x3F) | 0x80;
2858
0
      }
2859
0
      NEXTL(l);
2860
0
  }
2861
0
        if (out - buffer > maxLength) {
2862
0
            htmlParseErr(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
2863
0
                         "attribute value too long\n", NULL, NULL);
2864
0
            xmlFree(buffer);
2865
0
            return(NULL);
2866
0
        }
2867
0
    }
2868
0
    *out = 0;
2869
0
    return(buffer);
2870
0
}
2871
2872
/**
2873
 * htmlParseEntityRef:
2874
 * @ctxt:  an HTML parser context
2875
 * @str:  location to store the entity name
2876
 *
2877
 * DEPRECATED: Internal function, don't use.
2878
 *
2879
 * parse an HTML ENTITY references
2880
 *
2881
 * [68] EntityRef ::= '&' Name ';'
2882
 *
2883
 * Returns the associated htmlEntityDescPtr if found, or NULL otherwise,
2884
 *         if non-NULL *str will have to be freed by the caller.
2885
 */
2886
const htmlEntityDesc *
2887
0
htmlParseEntityRef(htmlParserCtxtPtr ctxt, const xmlChar **str) {
2888
0
    const xmlChar *name;
2889
0
    const htmlEntityDesc * ent = NULL;
2890
2891
0
    if (str != NULL) *str = NULL;
2892
0
    if ((ctxt == NULL) || (ctxt->input == NULL)) return(NULL);
2893
2894
0
    if (CUR == '&') {
2895
0
        NEXT;
2896
0
        name = htmlParseName(ctxt);
2897
0
  if (name == NULL) {
2898
0
      htmlParseErr(ctxt, XML_ERR_NAME_REQUIRED,
2899
0
                   "htmlParseEntityRef: no name\n", NULL, NULL);
2900
0
  } else {
2901
0
      GROW;
2902
0
      if (CUR == ';') {
2903
0
          if (str != NULL)
2904
0
        *str = name;
2905
2906
    /*
2907
     * Lookup the entity in the table.
2908
     */
2909
0
    ent = htmlEntityLookup(name);
2910
0
    if (ent != NULL) /* OK that's ugly !!! */
2911
0
        NEXT;
2912
0
      } else {
2913
0
    htmlParseErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING,
2914
0
                 "htmlParseEntityRef: expecting ';'\n",
2915
0
           NULL, NULL);
2916
0
          if (str != NULL)
2917
0
        *str = name;
2918
0
      }
2919
0
  }
2920
0
    }
2921
0
    return(ent);
2922
0
}
2923
2924
/**
2925
 * htmlParseAttValue:
2926
 * @ctxt:  an HTML parser context
2927
 *
2928
 * parse a value for an attribute
2929
 * Note: the parser won't do substitution of entities here, this
2930
 * will be handled later in xmlStringGetNodeList, unless it was
2931
 * asked for ctxt->replaceEntities != 0
2932
 *
2933
 * Returns the AttValue parsed or NULL.
2934
 */
2935
2936
static xmlChar *
2937
0
htmlParseAttValue(htmlParserCtxtPtr ctxt) {
2938
0
    xmlChar *ret = NULL;
2939
2940
0
    if (CUR == '"') {
2941
0
        NEXT;
2942
0
  ret = htmlParseHTMLAttribute(ctxt, '"');
2943
0
        if (CUR != '"') {
2944
0
      htmlParseErr(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
2945
0
                   "AttValue: \" expected\n", NULL, NULL);
2946
0
  } else
2947
0
      NEXT;
2948
0
    } else if (CUR == '\'') {
2949
0
        NEXT;
2950
0
  ret = htmlParseHTMLAttribute(ctxt, '\'');
2951
0
        if (CUR != '\'') {
2952
0
      htmlParseErr(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
2953
0
                   "AttValue: ' expected\n", NULL, NULL);
2954
0
  } else
2955
0
      NEXT;
2956
0
    } else {
2957
        /*
2958
   * That's an HTMLism, the attribute value may not be quoted
2959
   */
2960
0
  ret = htmlParseHTMLAttribute(ctxt, 0);
2961
0
  if (ret == NULL) {
2962
0
      htmlParseErr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE,
2963
0
                   "AttValue: no value found\n", NULL, NULL);
2964
0
  }
2965
0
    }
2966
0
    return(ret);
2967
0
}
2968
2969
/**
2970
 * htmlParseSystemLiteral:
2971
 * @ctxt:  an HTML parser context
2972
 *
2973
 * parse an HTML Literal
2974
 *
2975
 * [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
2976
 *
2977
 * Returns the SystemLiteral parsed or NULL
2978
 */
2979
2980
static xmlChar *
2981
0
htmlParseSystemLiteral(htmlParserCtxtPtr ctxt) {
2982
0
    size_t len = 0, startPosition = 0;
2983
0
    int err = 0;
2984
0
    int quote;
2985
0
    xmlChar *ret = NULL;
2986
2987
0
    if ((CUR != '"') && (CUR != '\'')) {
2988
0
  htmlParseErr(ctxt, XML_ERR_LITERAL_NOT_STARTED,
2989
0
               "SystemLiteral \" or ' expected\n", NULL, NULL);
2990
0
        return(NULL);
2991
0
    }
2992
0
    quote = CUR;
2993
0
    NEXT;
2994
2995
0
    if (CUR_PTR < BASE_PTR)
2996
0
        return(ret);
2997
0
    startPosition = CUR_PTR - BASE_PTR;
2998
2999
0
    while ((CUR != 0) && (CUR != quote)) {
3000
        /* TODO: Handle UTF-8 */
3001
0
        if (!IS_CHAR_CH(CUR)) {
3002
0
            htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
3003
0
                            "Invalid char in SystemLiteral 0x%X\n", CUR);
3004
0
            err = 1;
3005
0
        }
3006
0
        NEXT;
3007
0
        len++;
3008
0
    }
3009
0
    if (CUR != quote) {
3010
0
        htmlParseErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED,
3011
0
                     "Unfinished SystemLiteral\n", NULL, NULL);
3012
0
    } else {
3013
0
        if (err == 0)
3014
0
            ret = xmlStrndup((BASE_PTR+startPosition), len);
3015
0
        NEXT;
3016
0
    }
3017
3018
0
    return(ret);
3019
0
}
3020
3021
/**
3022
 * htmlParsePubidLiteral:
3023
 * @ctxt:  an HTML parser context
3024
 *
3025
 * parse an HTML public literal
3026
 *
3027
 * [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
3028
 *
3029
 * Returns the PubidLiteral parsed or NULL.
3030
 */
3031
3032
static xmlChar *
3033
0
htmlParsePubidLiteral(htmlParserCtxtPtr ctxt) {
3034
0
    size_t len = 0, startPosition = 0;
3035
0
    int err = 0;
3036
0
    int quote;
3037
0
    xmlChar *ret = NULL;
3038
3039
0
    if ((CUR != '"') && (CUR != '\'')) {
3040
0
  htmlParseErr(ctxt, XML_ERR_LITERAL_NOT_STARTED,
3041
0
               "PubidLiteral \" or ' expected\n", NULL, NULL);
3042
0
        return(NULL);
3043
0
    }
3044
0
    quote = CUR;
3045
0
    NEXT;
3046
3047
    /*
3048
     * Name ::= (Letter | '_') (NameChar)*
3049
     */
3050
0
    if (CUR_PTR < BASE_PTR)
3051
0
        return(ret);
3052
0
    startPosition = CUR_PTR - BASE_PTR;
3053
3054
0
    while ((CUR != 0) && (CUR != quote)) {
3055
0
        if (!IS_PUBIDCHAR_CH(CUR)) {
3056
0
            htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
3057
0
                            "Invalid char in PubidLiteral 0x%X\n", CUR);
3058
0
            err = 1;
3059
0
        }
3060
0
        len++;
3061
0
        NEXT;
3062
0
    }
3063
3064
0
    if (CUR != quote) {
3065
0
        htmlParseErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED,
3066
0
                     "Unfinished PubidLiteral\n", NULL, NULL);
3067
0
    } else {
3068
0
        if (err == 0)
3069
0
            ret = xmlStrndup((BASE_PTR + startPosition), len);
3070
0
        NEXT;
3071
0
    }
3072
3073
0
    return(ret);
3074
0
}
3075
3076
/**
3077
 * htmlParseScript:
3078
 * @ctxt:  an HTML parser context
3079
 *
3080
 * parse the content of an HTML SCRIPT or STYLE element
3081
 * http://www.w3.org/TR/html4/sgml/dtd.html#Script
3082
 * http://www.w3.org/TR/html4/sgml/dtd.html#StyleSheet
3083
 * http://www.w3.org/TR/html4/types.html#type-script
3084
 * http://www.w3.org/TR/html4/types.html#h-6.15
3085
 * http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2.1
3086
 *
3087
 * Script data ( %Script; in the DTD) can be the content of the SCRIPT
3088
 * element and the value of intrinsic event attributes. User agents must
3089
 * not evaluate script data as HTML markup but instead must pass it on as
3090
 * data to a script engine.
3091
 * NOTES:
3092
 * - The content is passed like CDATA
3093
 * - the attributes for style and scripting "onXXX" are also described
3094
 *   as CDATA but SGML allows entities references in attributes so their
3095
 *   processing is identical as other attributes
3096
 */
3097
static void
3098
0
htmlParseScript(htmlParserCtxtPtr ctxt) {
3099
0
    xmlChar buf[HTML_PARSER_BIG_BUFFER_SIZE + 5];
3100
0
    int nbchar = 0;
3101
0
    int cur,l;
3102
3103
0
    cur = CUR_CHAR(l);
3104
0
    while (cur != 0) {
3105
0
  if ((cur == '<') && (NXT(1) == '/')) {
3106
            /*
3107
             * One should break here, the specification is clear:
3108
             * Authors should therefore escape "</" within the content.
3109
             * Escape mechanisms are specific to each scripting or
3110
             * style sheet language.
3111
             *
3112
             * In recovery mode, only break if end tag match the
3113
             * current tag, effectively ignoring all tags inside the
3114
             * script/style block and treating the entire block as
3115
             * CDATA.
3116
             */
3117
0
            if (ctxt->recovery) {
3118
0
                if (xmlStrncasecmp(ctxt->name, ctxt->input->cur+2,
3119
0
           xmlStrlen(ctxt->name)) == 0)
3120
0
                {
3121
0
                    break; /* while */
3122
0
                } else {
3123
0
        htmlParseErr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
3124
0
         "Element %s embeds close tag\n",
3125
0
                     ctxt->name, NULL);
3126
0
    }
3127
0
            } else {
3128
0
                if (((NXT(2) >= 'A') && (NXT(2) <= 'Z')) ||
3129
0
                    ((NXT(2) >= 'a') && (NXT(2) <= 'z')))
3130
0
                {
3131
0
                    break; /* while */
3132
0
                }
3133
0
            }
3134
0
  }
3135
0
        if (IS_CHAR(cur)) {
3136
0
      COPY_BUF(l,buf,nbchar,cur);
3137
0
        } else {
3138
0
            htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
3139
0
                            "Invalid char in CDATA 0x%X\n", cur);
3140
0
        }
3141
0
  NEXTL(l);
3142
0
  if (nbchar >= HTML_PARSER_BIG_BUFFER_SIZE) {
3143
0
            buf[nbchar] = 0;
3144
0
      if (ctxt->sax->cdataBlock!= NULL) {
3145
    /*
3146
     * Insert as CDATA, which is the same as HTML_PRESERVE_NODE
3147
     */
3148
0
    ctxt->sax->cdataBlock(ctxt->userData, buf, nbchar);
3149
0
      } else if (ctxt->sax->characters != NULL) {
3150
0
    ctxt->sax->characters(ctxt->userData, buf, nbchar);
3151
0
      }
3152
0
      nbchar = 0;
3153
0
            SHRINK;
3154
0
  }
3155
0
  cur = CUR_CHAR(l);
3156
0
    }
3157
3158
0
    if (ctxt->instate == XML_PARSER_EOF)
3159
0
        return;
3160
3161
0
    if ((nbchar != 0) && (ctxt->sax != NULL) && (!ctxt->disableSAX)) {
3162
0
        buf[nbchar] = 0;
3163
0
  if (ctxt->sax->cdataBlock!= NULL) {
3164
      /*
3165
       * Insert as CDATA, which is the same as HTML_PRESERVE_NODE
3166
       */
3167
0
      ctxt->sax->cdataBlock(ctxt->userData, buf, nbchar);
3168
0
  } else if (ctxt->sax->characters != NULL) {
3169
0
      ctxt->sax->characters(ctxt->userData, buf, nbchar);
3170
0
  }
3171
0
    }
3172
0
}
3173
3174
3175
/**
3176
 * htmlParseCharDataInternal:
3177
 * @ctxt:  an HTML parser context
3178
 * @readahead: optional read ahead character in ascii range
3179
 *
3180
 * parse a CharData section.
3181
 * if we are within a CDATA section ']]>' marks an end of section.
3182
 *
3183
 * [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
3184
 */
3185
3186
static void
3187
0
htmlParseCharDataInternal(htmlParserCtxtPtr ctxt, int readahead) {
3188
0
    xmlChar buf[HTML_PARSER_BIG_BUFFER_SIZE + 6];
3189
0
    int nbchar = 0;
3190
0
    int cur, l;
3191
3192
0
    if (readahead)
3193
0
        buf[nbchar++] = readahead;
3194
3195
0
    cur = CUR_CHAR(l);
3196
0
    while (((cur != '<') || (ctxt->token == '<')) &&
3197
0
           ((cur != '&') || (ctxt->token == '&')) &&
3198
0
     (cur != 0)) {
3199
0
  if (!(IS_CHAR(cur))) {
3200
0
      htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
3201
0
                  "Invalid char in CDATA 0x%X\n", cur);
3202
0
  } else {
3203
0
      COPY_BUF(l,buf,nbchar,cur);
3204
0
  }
3205
0
  NEXTL(l);
3206
0
  if (nbchar >= HTML_PARSER_BIG_BUFFER_SIZE) {
3207
0
            buf[nbchar] = 0;
3208
3209
      /*
3210
       * Ok the segment is to be consumed as chars.
3211
       */
3212
0
      if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
3213
0
    if (areBlanks(ctxt, buf, nbchar)) {
3214
0
        if (ctxt->keepBlanks) {
3215
0
      if (ctxt->sax->characters != NULL)
3216
0
          ctxt->sax->characters(ctxt->userData, buf, nbchar);
3217
0
        } else {
3218
0
      if (ctxt->sax->ignorableWhitespace != NULL)
3219
0
          ctxt->sax->ignorableWhitespace(ctxt->userData,
3220
0
                                         buf, nbchar);
3221
0
        }
3222
0
    } else {
3223
0
        htmlCheckParagraph(ctxt);
3224
0
        if (ctxt->sax->characters != NULL)
3225
0
      ctxt->sax->characters(ctxt->userData, buf, nbchar);
3226
0
    }
3227
0
      }
3228
0
      nbchar = 0;
3229
0
            SHRINK;
3230
0
  }
3231
0
  cur = CUR_CHAR(l);
3232
0
    }
3233
0
    if (ctxt->instate == XML_PARSER_EOF)
3234
0
        return;
3235
0
    if (nbchar != 0) {
3236
0
        buf[nbchar] = 0;
3237
3238
  /*
3239
   * Ok the segment is to be consumed as chars.
3240
   */
3241
0
  if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
3242
0
      if (areBlanks(ctxt, buf, nbchar)) {
3243
0
    if (ctxt->keepBlanks) {
3244
0
        if (ctxt->sax->characters != NULL)
3245
0
      ctxt->sax->characters(ctxt->userData, buf, nbchar);
3246
0
    } else {
3247
0
        if (ctxt->sax->ignorableWhitespace != NULL)
3248
0
      ctxt->sax->ignorableWhitespace(ctxt->userData,
3249
0
                                     buf, nbchar);
3250
0
    }
3251
0
      } else {
3252
0
    htmlCheckParagraph(ctxt);
3253
0
    if (ctxt->sax->characters != NULL)
3254
0
        ctxt->sax->characters(ctxt->userData, buf, nbchar);
3255
0
      }
3256
0
  }
3257
0
    }
3258
0
}
3259
3260
/**
3261
 * htmlParseCharData:
3262
 * @ctxt:  an HTML parser context
3263
 *
3264
 * parse a CharData section.
3265
 * if we are within a CDATA section ']]>' marks an end of section.
3266
 *
3267
 * [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
3268
 */
3269
3270
static void
3271
0
htmlParseCharData(htmlParserCtxtPtr ctxt) {
3272
0
    htmlParseCharDataInternal(ctxt, 0);
3273
0
}
3274
3275
/**
3276
 * htmlParseExternalID:
3277
 * @ctxt:  an HTML parser context
3278
 * @publicID:  a xmlChar** receiving PubidLiteral
3279
 *
3280
 * Parse an External ID or a Public ID
3281
 *
3282
 * [75] ExternalID ::= 'SYSTEM' S SystemLiteral
3283
 *                   | 'PUBLIC' S PubidLiteral S SystemLiteral
3284
 *
3285
 * [83] PublicID ::= 'PUBLIC' S PubidLiteral
3286
 *
3287
 * Returns the function returns SystemLiteral and in the second
3288
 *                case publicID receives PubidLiteral, is strict is off
3289
 *                it is possible to return NULL and have publicID set.
3290
 */
3291
3292
static xmlChar *
3293
0
htmlParseExternalID(htmlParserCtxtPtr ctxt, xmlChar **publicID) {
3294
0
    xmlChar *URI = NULL;
3295
3296
0
    if ((UPPER == 'S') && (UPP(1) == 'Y') &&
3297
0
         (UPP(2) == 'S') && (UPP(3) == 'T') &&
3298
0
   (UPP(4) == 'E') && (UPP(5) == 'M')) {
3299
0
        SKIP(6);
3300
0
  if (!IS_BLANK_CH(CUR)) {
3301
0
      htmlParseErr(ctxt, XML_ERR_SPACE_REQUIRED,
3302
0
                   "Space required after 'SYSTEM'\n", NULL, NULL);
3303
0
  }
3304
0
        SKIP_BLANKS;
3305
0
  URI = htmlParseSystemLiteral(ctxt);
3306
0
  if (URI == NULL) {
3307
0
      htmlParseErr(ctxt, XML_ERR_URI_REQUIRED,
3308
0
                   "htmlParseExternalID: SYSTEM, no URI\n", NULL, NULL);
3309
0
        }
3310
0
    } else if ((UPPER == 'P') && (UPP(1) == 'U') &&
3311
0
         (UPP(2) == 'B') && (UPP(3) == 'L') &&
3312
0
         (UPP(4) == 'I') && (UPP(5) == 'C')) {
3313
0
        SKIP(6);
3314
0
  if (!IS_BLANK_CH(CUR)) {
3315
0
      htmlParseErr(ctxt, XML_ERR_SPACE_REQUIRED,
3316
0
                   "Space required after 'PUBLIC'\n", NULL, NULL);
3317
0
  }
3318
0
        SKIP_BLANKS;
3319
0
  *publicID = htmlParsePubidLiteral(ctxt);
3320
0
  if (*publicID == NULL) {
3321
0
      htmlParseErr(ctxt, XML_ERR_PUBID_REQUIRED,
3322
0
                   "htmlParseExternalID: PUBLIC, no Public Identifier\n",
3323
0
       NULL, NULL);
3324
0
  }
3325
0
        SKIP_BLANKS;
3326
0
        if ((CUR == '"') || (CUR == '\'')) {
3327
0
      URI = htmlParseSystemLiteral(ctxt);
3328
0
  }
3329
0
    }
3330
0
    return(URI);
3331
0
}
3332
3333
/**
3334
 * xmlParsePI:
3335
 * @ctxt:  an XML parser context
3336
 *
3337
 * parse an XML Processing Instruction.
3338
 *
3339
 * [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
3340
 */
3341
static void
3342
0
htmlParsePI(htmlParserCtxtPtr ctxt) {
3343
0
    xmlChar *buf = NULL;
3344
0
    int len = 0;
3345
0
    int size = HTML_PARSER_BUFFER_SIZE;
3346
0
    int cur, l;
3347
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3348
0
                    XML_MAX_HUGE_LENGTH :
3349
0
                    XML_MAX_TEXT_LENGTH;
3350
0
    const xmlChar *target;
3351
0
    xmlParserInputState state;
3352
3353
0
    if ((RAW == '<') && (NXT(1) == '?')) {
3354
0
  state = ctxt->instate;
3355
0
        ctxt->instate = XML_PARSER_PI;
3356
  /*
3357
   * this is a Processing Instruction.
3358
   */
3359
0
  SKIP(2);
3360
3361
  /*
3362
   * Parse the target name and check for special support like
3363
   * namespace.
3364
   */
3365
0
        target = htmlParseName(ctxt);
3366
0
  if (target != NULL) {
3367
0
      if (RAW == '>') {
3368
0
    SKIP(1);
3369
3370
    /*
3371
     * SAX: PI detected.
3372
     */
3373
0
    if ((ctxt->sax) && (!ctxt->disableSAX) &&
3374
0
        (ctxt->sax->processingInstruction != NULL))
3375
0
        ctxt->sax->processingInstruction(ctxt->userData,
3376
0
                                         target, NULL);
3377
0
    ctxt->instate = state;
3378
0
    return;
3379
0
      }
3380
0
      buf = (xmlChar *) xmlMallocAtomic(size);
3381
0
      if (buf == NULL) {
3382
0
    htmlErrMemory(ctxt, NULL);
3383
0
    ctxt->instate = state;
3384
0
    return;
3385
0
      }
3386
0
      cur = CUR;
3387
0
      if (!IS_BLANK(cur)) {
3388
0
    htmlParseErr(ctxt, XML_ERR_SPACE_REQUIRED,
3389
0
        "ParsePI: PI %s space expected\n", target, NULL);
3390
0
      }
3391
0
            SKIP_BLANKS;
3392
0
      cur = CUR_CHAR(l);
3393
0
      while ((cur != 0) && (cur != '>')) {
3394
0
    if (len + 5 >= size) {
3395
0
        xmlChar *tmp;
3396
3397
0
        size *= 2;
3398
0
        tmp = (xmlChar *) xmlRealloc(buf, size);
3399
0
        if (tmp == NULL) {
3400
0
      htmlErrMemory(ctxt, NULL);
3401
0
      xmlFree(buf);
3402
0
      ctxt->instate = state;
3403
0
      return;
3404
0
        }
3405
0
        buf = tmp;
3406
0
    }
3407
0
                if (IS_CHAR(cur)) {
3408
0
        COPY_BUF(l,buf,len,cur);
3409
0
                } else {
3410
0
                    htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
3411
0
                                    "Invalid char in processing instruction "
3412
0
                                    "0x%X\n", cur);
3413
0
                }
3414
0
                if (len > maxLength) {
3415
0
                    htmlParseErr(ctxt, XML_ERR_PI_NOT_FINISHED,
3416
0
                                 "PI %s too long", target, NULL);
3417
0
                    xmlFree(buf);
3418
0
                    ctxt->instate = state;
3419
0
                    return;
3420
0
                }
3421
0
    NEXTL(l);
3422
0
    cur = CUR_CHAR(l);
3423
0
      }
3424
0
      buf[len] = 0;
3425
0
            if (ctxt->instate == XML_PARSER_EOF) {
3426
0
                xmlFree(buf);
3427
0
                return;
3428
0
            }
3429
0
      if (cur != '>') {
3430
0
    htmlParseErr(ctxt, XML_ERR_PI_NOT_FINISHED,
3431
0
          "ParsePI: PI %s never end ...\n", target, NULL);
3432
0
      } else {
3433
0
    SKIP(1);
3434
3435
    /*
3436
     * SAX: PI detected.
3437
     */
3438
0
    if ((ctxt->sax) && (!ctxt->disableSAX) &&
3439
0
        (ctxt->sax->processingInstruction != NULL))
3440
0
        ctxt->sax->processingInstruction(ctxt->userData,
3441
0
                                         target, buf);
3442
0
      }
3443
0
      xmlFree(buf);
3444
0
  } else {
3445
0
      htmlParseErr(ctxt, XML_ERR_PI_NOT_STARTED,
3446
0
                         "PI is not started correctly", NULL, NULL);
3447
0
  }
3448
0
  ctxt->instate = state;
3449
0
    }
3450
0
}
3451
3452
/**
3453
 * htmlParseComment:
3454
 * @ctxt:  an HTML parser context
3455
 *
3456
 * Parse an XML (SGML) comment <!-- .... -->
3457
 *
3458
 * [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
3459
 */
3460
static void
3461
0
htmlParseComment(htmlParserCtxtPtr ctxt) {
3462
0
    xmlChar *buf = NULL;
3463
0
    int len;
3464
0
    int size = HTML_PARSER_BUFFER_SIZE;
3465
0
    int q, ql;
3466
0
    int r, rl;
3467
0
    int cur, l;
3468
0
    int next, nl;
3469
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3470
0
                    XML_MAX_HUGE_LENGTH :
3471
0
                    XML_MAX_TEXT_LENGTH;
3472
0
    xmlParserInputState state;
3473
3474
    /*
3475
     * Check that there is a comment right here.
3476
     */
3477
0
    if ((RAW != '<') || (NXT(1) != '!') ||
3478
0
        (NXT(2) != '-') || (NXT(3) != '-')) return;
3479
3480
0
    state = ctxt->instate;
3481
0
    ctxt->instate = XML_PARSER_COMMENT;
3482
0
    SKIP(4);
3483
0
    buf = (xmlChar *) xmlMallocAtomic(size);
3484
0
    if (buf == NULL) {
3485
0
        htmlErrMemory(ctxt, "buffer allocation failed\n");
3486
0
  ctxt->instate = state;
3487
0
  return;
3488
0
    }
3489
0
    len = 0;
3490
0
    buf[len] = 0;
3491
0
    q = CUR_CHAR(ql);
3492
0
    if (q == 0)
3493
0
        goto unfinished;
3494
0
    if (q == '>') {
3495
0
        htmlParseErr(ctxt, XML_ERR_COMMENT_ABRUPTLY_ENDED, "Comment abruptly ended", NULL, NULL);
3496
0
        cur = '>';
3497
0
        goto finished;
3498
0
    }
3499
0
    NEXTL(ql);
3500
0
    r = CUR_CHAR(rl);
3501
0
    if (r == 0)
3502
0
        goto unfinished;
3503
0
    if (q == '-' && r == '>') {
3504
0
        htmlParseErr(ctxt, XML_ERR_COMMENT_ABRUPTLY_ENDED, "Comment abruptly ended", NULL, NULL);
3505
0
        cur = '>';
3506
0
        goto finished;
3507
0
    }
3508
0
    NEXTL(rl);
3509
0
    cur = CUR_CHAR(l);
3510
0
    while ((cur != 0) &&
3511
0
           ((cur != '>') ||
3512
0
      (r != '-') || (q != '-'))) {
3513
0
  NEXTL(l);
3514
0
  next = CUR_CHAR(nl);
3515
3516
0
  if ((q == '-') && (r == '-') && (cur == '!') && (next == '>')) {
3517
0
    htmlParseErr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
3518
0
           "Comment incorrectly closed by '--!>'", NULL, NULL);
3519
0
    cur = '>';
3520
0
    break;
3521
0
  }
3522
3523
0
  if (len + 5 >= size) {
3524
0
      xmlChar *tmp;
3525
3526
0
      size *= 2;
3527
0
      tmp = (xmlChar *) xmlRealloc(buf, size);
3528
0
      if (tmp == NULL) {
3529
0
          xmlFree(buf);
3530
0
          htmlErrMemory(ctxt, "growing buffer failed\n");
3531
0
    ctxt->instate = state;
3532
0
    return;
3533
0
      }
3534
0
      buf = tmp;
3535
0
  }
3536
0
        if (IS_CHAR(q)) {
3537
0
      COPY_BUF(ql,buf,len,q);
3538
0
        } else {
3539
0
            htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
3540
0
                            "Invalid char in comment 0x%X\n", q);
3541
0
        }
3542
0
        if (len > maxLength) {
3543
0
            htmlParseErr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
3544
0
                         "comment too long", NULL, NULL);
3545
0
            xmlFree(buf);
3546
0
            ctxt->instate = state;
3547
0
            return;
3548
0
        }
3549
3550
0
  q = r;
3551
0
  ql = rl;
3552
0
  r = cur;
3553
0
  rl = l;
3554
0
  cur = next;
3555
0
  l = nl;
3556
0
    }
3557
0
finished:
3558
0
    buf[len] = 0;
3559
0
    if (ctxt->instate == XML_PARSER_EOF) {
3560
0
        xmlFree(buf);
3561
0
        return;
3562
0
    }
3563
0
    if (cur == '>') {
3564
0
        NEXT;
3565
0
  if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
3566
0
      (!ctxt->disableSAX))
3567
0
      ctxt->sax->comment(ctxt->userData, buf);
3568
0
  xmlFree(buf);
3569
0
  ctxt->instate = state;
3570
0
  return;
3571
0
    }
3572
3573
0
unfinished:
3574
0
    htmlParseErr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
3575
0
     "Comment not terminated \n<!--%.50s\n", buf, NULL);
3576
0
    xmlFree(buf);
3577
0
}
3578
3579
/**
3580
 * htmlParseCharRef:
3581
 * @ctxt:  an HTML parser context
3582
 *
3583
 * DEPRECATED: Internal function, don't use.
3584
 *
3585
 * parse Reference declarations
3586
 *
3587
 * [66] CharRef ::= '&#' [0-9]+ ';' |
3588
 *                  '&#x' [0-9a-fA-F]+ ';'
3589
 *
3590
 * Returns the value parsed (as an int)
3591
 */
3592
int
3593
0
htmlParseCharRef(htmlParserCtxtPtr ctxt) {
3594
0
    int val = 0;
3595
3596
0
    if ((ctxt == NULL) || (ctxt->input == NULL)) {
3597
0
  htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
3598
0
         "htmlParseCharRef: context error\n",
3599
0
         NULL, NULL);
3600
0
        return(0);
3601
0
    }
3602
0
    if ((CUR == '&') && (NXT(1) == '#') &&
3603
0
        ((NXT(2) == 'x') || NXT(2) == 'X')) {
3604
0
  SKIP(3);
3605
0
  while (CUR != ';') {
3606
0
      if ((CUR >= '0') && (CUR <= '9')) {
3607
0
                if (val < 0x110000)
3608
0
              val = val * 16 + (CUR - '0');
3609
0
            } else if ((CUR >= 'a') && (CUR <= 'f')) {
3610
0
                if (val < 0x110000)
3611
0
              val = val * 16 + (CUR - 'a') + 10;
3612
0
            } else if ((CUR >= 'A') && (CUR <= 'F')) {
3613
0
                if (val < 0x110000)
3614
0
              val = val * 16 + (CUR - 'A') + 10;
3615
0
            } else {
3616
0
          htmlParseErr(ctxt, XML_ERR_INVALID_HEX_CHARREF,
3617
0
                 "htmlParseCharRef: missing semicolon\n",
3618
0
           NULL, NULL);
3619
0
    break;
3620
0
      }
3621
0
      NEXT;
3622
0
  }
3623
0
  if (CUR == ';')
3624
0
      NEXT;
3625
0
    } else if  ((CUR == '&') && (NXT(1) == '#')) {
3626
0
  SKIP(2);
3627
0
  while (CUR != ';') {
3628
0
      if ((CUR >= '0') && (CUR <= '9')) {
3629
0
                if (val < 0x110000)
3630
0
              val = val * 10 + (CUR - '0');
3631
0
            } else {
3632
0
          htmlParseErr(ctxt, XML_ERR_INVALID_DEC_CHARREF,
3633
0
                 "htmlParseCharRef: missing semicolon\n",
3634
0
           NULL, NULL);
3635
0
    break;
3636
0
      }
3637
0
      NEXT;
3638
0
  }
3639
0
  if (CUR == ';')
3640
0
      NEXT;
3641
0
    } else {
3642
0
  htmlParseErr(ctxt, XML_ERR_INVALID_CHARREF,
3643
0
               "htmlParseCharRef: invalid value\n", NULL, NULL);
3644
0
    }
3645
    /*
3646
     * Check the value IS_CHAR ...
3647
     */
3648
0
    if (IS_CHAR(val)) {
3649
0
        return(val);
3650
0
    } else if (val >= 0x110000) {
3651
0
  htmlParseErr(ctxt, XML_ERR_INVALID_CHAR,
3652
0
         "htmlParseCharRef: value too large\n", NULL, NULL);
3653
0
    } else {
3654
0
  htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
3655
0
      "htmlParseCharRef: invalid xmlChar value %d\n",
3656
0
      val);
3657
0
    }
3658
0
    return(0);
3659
0
}
3660
3661
3662
/**
3663
 * htmlParseDocTypeDecl:
3664
 * @ctxt:  an HTML parser context
3665
 *
3666
 * parse a DOCTYPE declaration
3667
 *
3668
 * [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
3669
 *                      ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
3670
 */
3671
3672
static void
3673
0
htmlParseDocTypeDecl(htmlParserCtxtPtr ctxt) {
3674
0
    const xmlChar *name;
3675
0
    xmlChar *ExternalID = NULL;
3676
0
    xmlChar *URI = NULL;
3677
3678
    /*
3679
     * We know that '<!DOCTYPE' has been detected.
3680
     */
3681
0
    SKIP(9);
3682
3683
0
    SKIP_BLANKS;
3684
3685
    /*
3686
     * Parse the DOCTYPE name.
3687
     */
3688
0
    name = htmlParseName(ctxt);
3689
0
    if (name == NULL) {
3690
0
  htmlParseErr(ctxt, XML_ERR_NAME_REQUIRED,
3691
0
               "htmlParseDocTypeDecl : no DOCTYPE name !\n",
3692
0
         NULL, NULL);
3693
0
    }
3694
    /*
3695
     * Check that upper(name) == "HTML" !!!!!!!!!!!!!
3696
     */
3697
3698
0
    SKIP_BLANKS;
3699
3700
    /*
3701
     * Check for SystemID and ExternalID
3702
     */
3703
0
    URI = htmlParseExternalID(ctxt, &ExternalID);
3704
0
    SKIP_BLANKS;
3705
3706
    /*
3707
     * We should be at the end of the DOCTYPE declaration.
3708
     */
3709
0
    if (CUR != '>') {
3710
0
  htmlParseErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED,
3711
0
               "DOCTYPE improperly terminated\n", NULL, NULL);
3712
        /* Ignore bogus content */
3713
0
        while ((CUR != 0) && (CUR != '>') &&
3714
0
               (ctxt->instate != XML_PARSER_EOF))
3715
0
            NEXT;
3716
0
    }
3717
0
    if (CUR == '>')
3718
0
        NEXT;
3719
3720
    /*
3721
     * Create or update the document accordingly to the DOCTYPE
3722
     */
3723
0
    if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) &&
3724
0
  (!ctxt->disableSAX))
3725
0
  ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI);
3726
3727
    /*
3728
     * Cleanup, since we don't use all those identifiers
3729
     */
3730
0
    if (URI != NULL) xmlFree(URI);
3731
0
    if (ExternalID != NULL) xmlFree(ExternalID);
3732
0
}
3733
3734
/**
3735
 * htmlParseAttribute:
3736
 * @ctxt:  an HTML parser context
3737
 * @value:  a xmlChar ** used to store the value of the attribute
3738
 *
3739
 * parse an attribute
3740
 *
3741
 * [41] Attribute ::= Name Eq AttValue
3742
 *
3743
 * [25] Eq ::= S? '=' S?
3744
 *
3745
 * With namespace:
3746
 *
3747
 * [NS 11] Attribute ::= QName Eq AttValue
3748
 *
3749
 * Also the case QName == xmlns:??? is handled independently as a namespace
3750
 * definition.
3751
 *
3752
 * Returns the attribute name, and the value in *value.
3753
 */
3754
3755
static const xmlChar *
3756
0
htmlParseAttribute(htmlParserCtxtPtr ctxt, xmlChar **value) {
3757
0
    const xmlChar *name;
3758
0
    xmlChar *val = NULL;
3759
3760
0
    *value = NULL;
3761
0
    name = htmlParseHTMLName(ctxt);
3762
0
    if (name == NULL) {
3763
0
  htmlParseErr(ctxt, XML_ERR_NAME_REQUIRED,
3764
0
               "error parsing attribute name\n", NULL, NULL);
3765
0
        return(NULL);
3766
0
    }
3767
3768
    /*
3769
     * read the value
3770
     */
3771
0
    SKIP_BLANKS;
3772
0
    if (CUR == '=') {
3773
0
        NEXT;
3774
0
  SKIP_BLANKS;
3775
0
  val = htmlParseAttValue(ctxt);
3776
0
    }
3777
3778
0
    *value = val;
3779
0
    return(name);
3780
0
}
3781
3782
/**
3783
 * htmlCheckEncodingDirect:
3784
 * @ctxt:  an HTML parser context
3785
 * @attvalue: the attribute value
3786
 *
3787
 * Checks an attribute value to detect
3788
 * the encoding
3789
 * If a new encoding is detected the parser is switched to decode
3790
 * it and pass UTF8
3791
 */
3792
static void
3793
0
htmlCheckEncodingDirect(htmlParserCtxtPtr ctxt, const xmlChar *encoding) {
3794
3795
0
    if ((ctxt == NULL) || (encoding == NULL) ||
3796
0
        (ctxt->options & HTML_PARSE_IGNORE_ENC))
3797
0
  return;
3798
3799
    /* do not change encoding */
3800
0
    if (ctxt->input->encoding != NULL)
3801
0
        return;
3802
3803
0
    if (encoding != NULL) {
3804
0
  xmlCharEncoding enc;
3805
0
  xmlCharEncodingHandlerPtr handler;
3806
3807
0
  while ((*encoding == ' ') || (*encoding == '\t')) encoding++;
3808
3809
0
  if (ctxt->input->encoding != NULL)
3810
0
      xmlFree((xmlChar *) ctxt->input->encoding);
3811
0
  ctxt->input->encoding = xmlStrdup(encoding);
3812
3813
0
  enc = xmlParseCharEncoding((const char *) encoding);
3814
  /*
3815
   * registered set of known encodings
3816
   */
3817
0
  if (enc != XML_CHAR_ENCODING_ERROR) {
3818
0
      if (((enc == XML_CHAR_ENCODING_UTF16LE) ||
3819
0
           (enc == XML_CHAR_ENCODING_UTF16BE) ||
3820
0
     (enc == XML_CHAR_ENCODING_UCS4LE) ||
3821
0
     (enc == XML_CHAR_ENCODING_UCS4BE)) &&
3822
0
    (ctxt->input->buf != NULL) &&
3823
0
    (ctxt->input->buf->encoder == NULL)) {
3824
0
    htmlParseErr(ctxt, XML_ERR_INVALID_ENCODING,
3825
0
                 "htmlCheckEncoding: wrong encoding meta\n",
3826
0
           NULL, NULL);
3827
0
      } else {
3828
0
    xmlSwitchEncoding(ctxt, enc);
3829
0
      }
3830
0
      ctxt->charset = XML_CHAR_ENCODING_UTF8;
3831
0
  } else {
3832
      /*
3833
       * fallback for unknown encodings
3834
       */
3835
0
      handler = xmlFindCharEncodingHandler((const char *) encoding);
3836
0
      if (handler != NULL) {
3837
0
    xmlSwitchToEncoding(ctxt, handler);
3838
0
    ctxt->charset = XML_CHAR_ENCODING_UTF8;
3839
0
      } else {
3840
0
    htmlParseErr(ctxt, XML_ERR_UNSUPPORTED_ENCODING,
3841
0
                 "htmlCheckEncoding: unknown encoding %s\n",
3842
0
           encoding, NULL);
3843
0
      }
3844
0
  }
3845
3846
0
  if ((ctxt->input->buf != NULL) &&
3847
0
      (ctxt->input->buf->encoder != NULL) &&
3848
0
      (ctxt->input->buf->raw != NULL) &&
3849
0
      (ctxt->input->buf->buffer != NULL)) {
3850
0
      int nbchars;
3851
0
      size_t processed;
3852
3853
      /*
3854
       * convert as much as possible to the parser reading buffer.
3855
       */
3856
0
      processed = ctxt->input->cur - ctxt->input->base;
3857
0
      xmlBufShrink(ctxt->input->buf->buffer, processed);
3858
0
      nbchars = xmlCharEncInput(ctxt->input->buf, 1);
3859
0
            xmlBufResetInput(ctxt->input->buf->buffer, ctxt->input);
3860
0
      if (nbchars < 0) {
3861
0
    htmlParseErr(ctxt, ctxt->input->buf->error,
3862
0
                 "htmlCheckEncoding: encoder error\n",
3863
0
           NULL, NULL);
3864
0
                xmlHaltParser(ctxt);
3865
0
      }
3866
0
  }
3867
0
    }
3868
0
}
3869
3870
/**
3871
 * htmlCheckEncoding:
3872
 * @ctxt:  an HTML parser context
3873
 * @attvalue: the attribute value
3874
 *
3875
 * Checks an http-equiv attribute from a Meta tag to detect
3876
 * the encoding
3877
 * If a new encoding is detected the parser is switched to decode
3878
 * it and pass UTF8
3879
 */
3880
static void
3881
0
htmlCheckEncoding(htmlParserCtxtPtr ctxt, const xmlChar *attvalue) {
3882
0
    const xmlChar *encoding;
3883
3884
0
    if (!attvalue)
3885
0
  return;
3886
3887
0
    encoding = xmlStrcasestr(attvalue, BAD_CAST"charset");
3888
0
    if (encoding != NULL) {
3889
0
  encoding += 7;
3890
0
    }
3891
    /*
3892
     * skip blank
3893
     */
3894
0
    if (encoding && IS_BLANK_CH(*encoding))
3895
0
  encoding = xmlStrcasestr(attvalue, BAD_CAST"=");
3896
0
    if (encoding && *encoding == '=') {
3897
0
  encoding ++;
3898
0
  htmlCheckEncodingDirect(ctxt, encoding);
3899
0
    }
3900
0
}
3901
3902
/**
3903
 * htmlCheckMeta:
3904
 * @ctxt:  an HTML parser context
3905
 * @atts:  the attributes values
3906
 *
3907
 * Checks an attributes from a Meta tag
3908
 */
3909
static void
3910
0
htmlCheckMeta(htmlParserCtxtPtr ctxt, const xmlChar **atts) {
3911
0
    int i;
3912
0
    const xmlChar *att, *value;
3913
0
    int http = 0;
3914
0
    const xmlChar *content = NULL;
3915
3916
0
    if ((ctxt == NULL) || (atts == NULL))
3917
0
  return;
3918
3919
0
    i = 0;
3920
0
    att = atts[i++];
3921
0
    while (att != NULL) {
3922
0
  value = atts[i++];
3923
0
  if ((value != NULL) && (!xmlStrcasecmp(att, BAD_CAST"http-equiv"))
3924
0
   && (!xmlStrcasecmp(value, BAD_CAST"Content-Type")))
3925
0
      http = 1;
3926
0
  else if ((value != NULL) && (!xmlStrcasecmp(att, BAD_CAST"charset")))
3927
0
      htmlCheckEncodingDirect(ctxt, value);
3928
0
  else if ((value != NULL) && (!xmlStrcasecmp(att, BAD_CAST"content")))
3929
0
      content = value;
3930
0
  att = atts[i++];
3931
0
    }
3932
0
    if ((http) && (content != NULL))
3933
0
  htmlCheckEncoding(ctxt, content);
3934
3935
0
}
3936
3937
/**
3938
 * htmlParseStartTag:
3939
 * @ctxt:  an HTML parser context
3940
 *
3941
 * parse a start of tag either for rule element or
3942
 * EmptyElement. In both case we don't parse the tag closing chars.
3943
 *
3944
 * [40] STag ::= '<' Name (S Attribute)* S? '>'
3945
 *
3946
 * [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
3947
 *
3948
 * With namespace:
3949
 *
3950
 * [NS 8] STag ::= '<' QName (S Attribute)* S? '>'
3951
 *
3952
 * [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
3953
 *
3954
 * Returns 0 in case of success, -1 in case of error and 1 if discarded
3955
 */
3956
3957
static int
3958
0
htmlParseStartTag(htmlParserCtxtPtr ctxt) {
3959
0
    const xmlChar *name;
3960
0
    const xmlChar *attname;
3961
0
    xmlChar *attvalue;
3962
0
    const xmlChar **atts;
3963
0
    int nbatts = 0;
3964
0
    int maxatts;
3965
0
    int meta = 0;
3966
0
    int i;
3967
0
    int discardtag = 0;
3968
3969
0
    if ((ctxt == NULL) || (ctxt->input == NULL)) {
3970
0
  htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
3971
0
         "htmlParseStartTag: context error\n", NULL, NULL);
3972
0
  return -1;
3973
0
    }
3974
0
    if (ctxt->instate == XML_PARSER_EOF)
3975
0
        return(-1);
3976
0
    if (CUR != '<') return -1;
3977
0
    NEXT;
3978
3979
0
    atts = ctxt->atts;
3980
0
    maxatts = ctxt->maxatts;
3981
3982
0
    GROW;
3983
0
    name = htmlParseHTMLName(ctxt);
3984
0
    if (name == NULL) {
3985
0
  htmlParseErr(ctxt, XML_ERR_NAME_REQUIRED,
3986
0
               "htmlParseStartTag: invalid element name\n",
3987
0
         NULL, NULL);
3988
  /* Dump the bogus tag like browsers do */
3989
0
  while ((CUR != 0) && (CUR != '>') &&
3990
0
               (ctxt->instate != XML_PARSER_EOF))
3991
0
      NEXT;
3992
0
        return -1;
3993
0
    }
3994
0
    if (xmlStrEqual(name, BAD_CAST"meta"))
3995
0
  meta = 1;
3996
3997
    /*
3998
     * Check for auto-closure of HTML elements.
3999
     */
4000
0
    htmlAutoClose(ctxt, name);
4001
4002
    /*
4003
     * Check for implied HTML elements.
4004
     */
4005
0
    htmlCheckImplied(ctxt, name);
4006
4007
    /*
4008
     * Avoid html at any level > 0, head at any level != 1
4009
     * or any attempt to recurse body
4010
     */
4011
0
    if ((ctxt->nameNr > 0) && (xmlStrEqual(name, BAD_CAST"html"))) {
4012
0
  htmlParseErr(ctxt, XML_HTML_STRUCURE_ERROR,
4013
0
               "htmlParseStartTag: misplaced <html> tag\n",
4014
0
         name, NULL);
4015
0
  discardtag = 1;
4016
0
  ctxt->depth++;
4017
0
    }
4018
0
    if ((ctxt->nameNr != 1) &&
4019
0
  (xmlStrEqual(name, BAD_CAST"head"))) {
4020
0
  htmlParseErr(ctxt, XML_HTML_STRUCURE_ERROR,
4021
0
               "htmlParseStartTag: misplaced <head> tag\n",
4022
0
         name, NULL);
4023
0
  discardtag = 1;
4024
0
  ctxt->depth++;
4025
0
    }
4026
0
    if (xmlStrEqual(name, BAD_CAST"body")) {
4027
0
  int indx;
4028
0
  for (indx = 0;indx < ctxt->nameNr;indx++) {
4029
0
      if (xmlStrEqual(ctxt->nameTab[indx], BAD_CAST"body")) {
4030
0
    htmlParseErr(ctxt, XML_HTML_STRUCURE_ERROR,
4031
0
                 "htmlParseStartTag: misplaced <body> tag\n",
4032
0
           name, NULL);
4033
0
    discardtag = 1;
4034
0
    ctxt->depth++;
4035
0
      }
4036
0
  }
4037
0
    }
4038
4039
    /*
4040
     * Now parse the attributes, it ends up with the ending
4041
     *
4042
     * (S Attribute)* S?
4043
     */
4044
0
    SKIP_BLANKS;
4045
0
    while ((CUR != 0) &&
4046
0
           (CUR != '>') &&
4047
0
     ((CUR != '/') || (NXT(1) != '>')) &&
4048
0
           (ctxt->instate != XML_PARSER_EOF)) {
4049
0
  GROW;
4050
0
  attname = htmlParseAttribute(ctxt, &attvalue);
4051
0
        if (attname != NULL) {
4052
4053
      /*
4054
       * Well formedness requires at most one declaration of an attribute
4055
       */
4056
0
      for (i = 0; i < nbatts;i += 2) {
4057
0
          if (xmlStrEqual(atts[i], attname)) {
4058
0
        htmlParseErr(ctxt, XML_ERR_ATTRIBUTE_REDEFINED,
4059
0
                     "Attribute %s redefined\n", attname, NULL);
4060
0
        if (attvalue != NULL)
4061
0
      xmlFree(attvalue);
4062
0
        goto failed;
4063
0
    }
4064
0
      }
4065
4066
      /*
4067
       * Add the pair to atts
4068
       */
4069
0
      if (atts == NULL) {
4070
0
          maxatts = 22; /* allow for 10 attrs by default */
4071
0
          atts = (const xmlChar **)
4072
0
           xmlMalloc(maxatts * sizeof(xmlChar *));
4073
0
    if (atts == NULL) {
4074
0
        htmlErrMemory(ctxt, NULL);
4075
0
        if (attvalue != NULL)
4076
0
      xmlFree(attvalue);
4077
0
        goto failed;
4078
0
    }
4079
0
    ctxt->atts = atts;
4080
0
    ctxt->maxatts = maxatts;
4081
0
      } else if (nbatts + 4 > maxatts) {
4082
0
          const xmlChar **n;
4083
4084
0
          maxatts *= 2;
4085
0
          n = (const xmlChar **) xmlRealloc((void *) atts,
4086
0
               maxatts * sizeof(const xmlChar *));
4087
0
    if (n == NULL) {
4088
0
        htmlErrMemory(ctxt, NULL);
4089
0
        if (attvalue != NULL)
4090
0
      xmlFree(attvalue);
4091
0
        goto failed;
4092
0
    }
4093
0
    atts = n;
4094
0
    ctxt->atts = atts;
4095
0
    ctxt->maxatts = maxatts;
4096
0
      }
4097
0
      atts[nbatts++] = attname;
4098
0
      atts[nbatts++] = attvalue;
4099
0
      atts[nbatts] = NULL;
4100
0
      atts[nbatts + 1] = NULL;
4101
0
  }
4102
0
  else {
4103
0
      if (attvalue != NULL)
4104
0
          xmlFree(attvalue);
4105
      /* Dump the bogus attribute string up to the next blank or
4106
       * the end of the tag. */
4107
0
      while ((CUR != 0) &&
4108
0
             !(IS_BLANK_CH(CUR)) && (CUR != '>') &&
4109
0
       ((CUR != '/') || (NXT(1) != '>')) &&
4110
0
                   (ctxt->instate != XML_PARSER_EOF))
4111
0
    NEXT;
4112
0
  }
4113
4114
0
failed:
4115
0
  SKIP_BLANKS;
4116
0
    }
4117
4118
    /*
4119
     * Handle specific association to the META tag
4120
     */
4121
0
    if (meta && (nbatts != 0))
4122
0
  htmlCheckMeta(ctxt, atts);
4123
4124
    /*
4125
     * SAX: Start of Element !
4126
     */
4127
0
    if (!discardtag) {
4128
0
  htmlnamePush(ctxt, name);
4129
0
  if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL)) {
4130
0
      if (nbatts != 0)
4131
0
    ctxt->sax->startElement(ctxt->userData, name, atts);
4132
0
      else
4133
0
    ctxt->sax->startElement(ctxt->userData, name, NULL);
4134
0
  }
4135
0
    }
4136
4137
0
    if (atts != NULL) {
4138
0
        for (i = 1;i < nbatts;i += 2) {
4139
0
      if (atts[i] != NULL)
4140
0
    xmlFree((xmlChar *) atts[i]);
4141
0
  }
4142
0
    }
4143
4144
0
    return(discardtag);
4145
0
}
4146
4147
/**
4148
 * htmlParseEndTag:
4149
 * @ctxt:  an HTML parser context
4150
 *
4151
 * parse an end of tag
4152
 *
4153
 * [42] ETag ::= '</' Name S? '>'
4154
 *
4155
 * With namespace
4156
 *
4157
 * [NS 9] ETag ::= '</' QName S? '>'
4158
 *
4159
 * Returns 1 if the current level should be closed.
4160
 */
4161
4162
static int
4163
htmlParseEndTag(htmlParserCtxtPtr ctxt)
4164
0
{
4165
0
    const xmlChar *name;
4166
0
    const xmlChar *oldname;
4167
0
    int i, ret;
4168
4169
0
    if ((CUR != '<') || (NXT(1) != '/')) {
4170
0
        htmlParseErr(ctxt, XML_ERR_LTSLASH_REQUIRED,
4171
0
               "htmlParseEndTag: '</' not found\n", NULL, NULL);
4172
0
        return (0);
4173
0
    }
4174
0
    SKIP(2);
4175
4176
0
    name = htmlParseHTMLName(ctxt);
4177
0
    if (name == NULL)
4178
0
        return (0);
4179
    /*
4180
     * We should definitely be at the ending "S? '>'" part
4181
     */
4182
0
    SKIP_BLANKS;
4183
0
    if (CUR != '>') {
4184
0
        htmlParseErr(ctxt, XML_ERR_GT_REQUIRED,
4185
0
               "End tag : expected '>'\n", NULL, NULL);
4186
        /* Skip to next '>' */
4187
0
        while ((CUR != 0) && (CUR != '>'))
4188
0
            NEXT;
4189
0
    }
4190
0
    if (CUR == '>')
4191
0
        NEXT;
4192
4193
    /*
4194
     * if we ignored misplaced tags in htmlParseStartTag don't pop them
4195
     * out now.
4196
     */
4197
0
    if ((ctxt->depth > 0) &&
4198
0
        (xmlStrEqual(name, BAD_CAST "html") ||
4199
0
         xmlStrEqual(name, BAD_CAST "body") ||
4200
0
   xmlStrEqual(name, BAD_CAST "head"))) {
4201
0
  ctxt->depth--;
4202
0
  return (0);
4203
0
    }
4204
4205
    /*
4206
     * If the name read is not one of the element in the parsing stack
4207
     * then return, it's just an error.
4208
     */
4209
0
    for (i = (ctxt->nameNr - 1); i >= 0; i--) {
4210
0
        if (xmlStrEqual(name, ctxt->nameTab[i]))
4211
0
            break;
4212
0
    }
4213
0
    if (i < 0) {
4214
0
        htmlParseErr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
4215
0
               "Unexpected end tag : %s\n", name, NULL);
4216
0
        return (0);
4217
0
    }
4218
4219
4220
    /*
4221
     * Check for auto-closure of HTML elements.
4222
     */
4223
4224
0
    htmlAutoCloseOnClose(ctxt, name);
4225
4226
    /*
4227
     * Well formedness constraints, opening and closing must match.
4228
     * With the exception that the autoclose may have popped stuff out
4229
     * of the stack.
4230
     */
4231
0
    if ((ctxt->name != NULL) && (!xmlStrEqual(ctxt->name, name))) {
4232
0
        htmlParseErr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
4233
0
                     "Opening and ending tag mismatch: %s and %s\n",
4234
0
                     name, ctxt->name);
4235
0
    }
4236
4237
    /*
4238
     * SAX: End of Tag
4239
     */
4240
0
    oldname = ctxt->name;
4241
0
    if ((oldname != NULL) && (xmlStrEqual(oldname, name))) {
4242
0
        if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
4243
0
            ctxt->sax->endElement(ctxt->userData, name);
4244
0
  htmlNodeInfoPop(ctxt);
4245
0
        htmlnamePop(ctxt);
4246
0
        ret = 1;
4247
0
    } else {
4248
0
        ret = 0;
4249
0
    }
4250
4251
0
    return (ret);
4252
0
}
4253
4254
4255
/**
4256
 * htmlParseReference:
4257
 * @ctxt:  an HTML parser context
4258
 *
4259
 * parse and handle entity references in content,
4260
 * this will end-up in a call to character() since this is either a
4261
 * CharRef, or a predefined entity.
4262
 */
4263
static void
4264
0
htmlParseReference(htmlParserCtxtPtr ctxt) {
4265
0
    const htmlEntityDesc * ent;
4266
0
    xmlChar out[6];
4267
0
    const xmlChar *name;
4268
0
    if (CUR != '&') return;
4269
4270
0
    if (NXT(1) == '#') {
4271
0
  unsigned int c;
4272
0
  int bits, i = 0;
4273
4274
0
  c = htmlParseCharRef(ctxt);
4275
0
  if (c == 0)
4276
0
      return;
4277
4278
0
        if      (c <    0x80) { out[i++]= c;                bits= -6; }
4279
0
        else if (c <   0x800) { out[i++]=((c >>  6) & 0x1F) | 0xC0;  bits=  0; }
4280
0
        else if (c < 0x10000) { out[i++]=((c >> 12) & 0x0F) | 0xE0;  bits=  6; }
4281
0
        else                  { out[i++]=((c >> 18) & 0x07) | 0xF0;  bits= 12; }
4282
4283
0
        for ( ; bits >= 0; bits-= 6) {
4284
0
            out[i++]= ((c >> bits) & 0x3F) | 0x80;
4285
0
        }
4286
0
  out[i] = 0;
4287
4288
0
  htmlCheckParagraph(ctxt);
4289
0
  if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL))
4290
0
      ctxt->sax->characters(ctxt->userData, out, i);
4291
0
    } else {
4292
0
  ent = htmlParseEntityRef(ctxt, &name);
4293
0
  if (name == NULL) {
4294
0
      htmlCheckParagraph(ctxt);
4295
0
      if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL))
4296
0
          ctxt->sax->characters(ctxt->userData, BAD_CAST "&", 1);
4297
0
      return;
4298
0
  }
4299
0
  if ((ent == NULL) || !(ent->value > 0)) {
4300
0
      htmlCheckParagraph(ctxt);
4301
0
      if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL)) {
4302
0
    ctxt->sax->characters(ctxt->userData, BAD_CAST "&", 1);
4303
0
    ctxt->sax->characters(ctxt->userData, name, xmlStrlen(name));
4304
    /* ctxt->sax->characters(ctxt->userData, BAD_CAST ";", 1); */
4305
0
      }
4306
0
  } else {
4307
0
      unsigned int c;
4308
0
      int bits, i = 0;
4309
4310
0
      c = ent->value;
4311
0
      if      (c <    0x80)
4312
0
              { out[i++]= c;                bits= -6; }
4313
0
      else if (c <   0x800)
4314
0
              { out[i++]=((c >>  6) & 0x1F) | 0xC0;  bits=  0; }
4315
0
      else if (c < 0x10000)
4316
0
              { out[i++]=((c >> 12) & 0x0F) | 0xE0;  bits=  6; }
4317
0
      else
4318
0
              { out[i++]=((c >> 18) & 0x07) | 0xF0;  bits= 12; }
4319
4320
0
      for ( ; bits >= 0; bits-= 6) {
4321
0
    out[i++]= ((c >> bits) & 0x3F) | 0x80;
4322
0
      }
4323
0
      out[i] = 0;
4324
4325
0
      htmlCheckParagraph(ctxt);
4326
0
      if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL))
4327
0
    ctxt->sax->characters(ctxt->userData, out, i);
4328
0
  }
4329
0
    }
4330
0
}
4331
4332
/**
4333
 * htmlParseContent:
4334
 * @ctxt:  an HTML parser context
4335
 *
4336
 * Parse a content: comment, sub-element, reference or text.
4337
 * Kept for compatibility with old code
4338
 */
4339
4340
static void
4341
0
htmlParseContent(htmlParserCtxtPtr ctxt) {
4342
0
    xmlChar *currentNode;
4343
0
    int depth;
4344
0
    const xmlChar *name;
4345
4346
0
    currentNode = xmlStrdup(ctxt->name);
4347
0
    depth = ctxt->nameNr;
4348
0
    while (1) {
4349
0
        GROW;
4350
4351
0
        if (ctxt->instate == XML_PARSER_EOF)
4352
0
            break;
4353
4354
  /*
4355
   * Our tag or one of it's parent or children is ending.
4356
   */
4357
0
        if ((CUR == '<') && (NXT(1) == '/')) {
4358
0
      if (htmlParseEndTag(ctxt) &&
4359
0
    ((currentNode != NULL) || (ctxt->nameNr == 0))) {
4360
0
    if (currentNode != NULL)
4361
0
        xmlFree(currentNode);
4362
0
    return;
4363
0
      }
4364
0
      continue; /* while */
4365
0
        }
4366
4367
0
  else if ((CUR == '<') &&
4368
0
           ((IS_ASCII_LETTER(NXT(1))) ||
4369
0
      (NXT(1) == '_') || (NXT(1) == ':'))) {
4370
0
      name = htmlParseHTMLName_nonInvasive(ctxt);
4371
0
      if (name == NULL) {
4372
0
          htmlParseErr(ctxt, XML_ERR_NAME_REQUIRED,
4373
0
       "htmlParseStartTag: invalid element name\n",
4374
0
       NULL, NULL);
4375
          /* Dump the bogus tag like browsers do */
4376
0
                while ((CUR != 0) && (CUR != '>'))
4377
0
              NEXT;
4378
4379
0
          if (currentNode != NULL)
4380
0
              xmlFree(currentNode);
4381
0
          return;
4382
0
      }
4383
4384
0
      if (ctxt->name != NULL) {
4385
0
          if (htmlCheckAutoClose(name, ctxt->name) == 1) {
4386
0
              htmlAutoClose(ctxt, name);
4387
0
              continue;
4388
0
          }
4389
0
      }
4390
0
  }
4391
4392
  /*
4393
   * Has this node been popped out during parsing of
4394
   * the next element
4395
   */
4396
0
        if ((ctxt->nameNr > 0) && (depth >= ctxt->nameNr) &&
4397
0
      (!xmlStrEqual(currentNode, ctxt->name)))
4398
0
       {
4399
0
      if (currentNode != NULL) xmlFree(currentNode);
4400
0
      return;
4401
0
  }
4402
4403
0
  if ((CUR != 0) && ((xmlStrEqual(currentNode, BAD_CAST"script")) ||
4404
0
      (xmlStrEqual(currentNode, BAD_CAST"style")))) {
4405
      /*
4406
       * Handle SCRIPT/STYLE separately
4407
       */
4408
0
      htmlParseScript(ctxt);
4409
0
  }
4410
4411
0
        else if ((CUR == '<') && (NXT(1) == '!')) {
4412
            /*
4413
             * Sometimes DOCTYPE arrives in the middle of the document
4414
             */
4415
0
            if ((UPP(2) == 'D') && (UPP(3) == 'O') &&
4416
0
                (UPP(4) == 'C') && (UPP(5) == 'T') &&
4417
0
                (UPP(6) == 'Y') && (UPP(7) == 'P') &&
4418
0
                (UPP(8) == 'E')) {
4419
0
                htmlParseErr(ctxt, XML_HTML_STRUCURE_ERROR,
4420
0
                             "Misplaced DOCTYPE declaration\n",
4421
0
                             BAD_CAST "DOCTYPE" , NULL);
4422
0
                htmlParseDocTypeDecl(ctxt);
4423
0
            }
4424
            /*
4425
             * First case :  a comment
4426
             */
4427
0
            else if ((NXT(2) == '-') && (NXT(3) == '-')) {
4428
0
                htmlParseComment(ctxt);
4429
0
            }
4430
0
            else {
4431
0
                htmlSkipBogusComment(ctxt);
4432
0
            }
4433
0
        }
4434
4435
        /*
4436
         * Second case : a Processing Instruction.
4437
         */
4438
0
        else if ((CUR == '<') && (NXT(1) == '?')) {
4439
0
            htmlParsePI(ctxt);
4440
0
        }
4441
4442
        /*
4443
         * Third case :  a sub-element.
4444
         */
4445
0
        else if ((CUR == '<') && IS_ASCII_LETTER(NXT(1))) {
4446
0
            htmlParseElement(ctxt);
4447
0
        }
4448
0
        else if (CUR == '<') {
4449
0
            if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
4450
0
                (ctxt->sax->characters != NULL))
4451
0
                ctxt->sax->characters(ctxt->userData, BAD_CAST "<", 1);
4452
0
            NEXT;
4453
0
        }
4454
4455
        /*
4456
         * Fourth case : a reference. If if has not been resolved,
4457
         *    parsing returns it's Name, create the node
4458
         */
4459
0
        else if (CUR == '&') {
4460
0
            htmlParseReference(ctxt);
4461
0
        }
4462
4463
        /*
4464
         * Fifth case : end of the resource
4465
         */
4466
0
        else if (CUR == 0) {
4467
0
            htmlAutoCloseOnEnd(ctxt);
4468
0
            break;
4469
0
        }
4470
4471
        /*
4472
         * Last case, text. Note that References are handled directly.
4473
         */
4474
0
        else {
4475
0
            htmlParseCharData(ctxt);
4476
0
        }
4477
4478
0
        SHRINK;
4479
0
        GROW;
4480
0
    }
4481
0
    if (currentNode != NULL) xmlFree(currentNode);
4482
0
}
4483
4484
/**
4485
 * htmlParseElement:
4486
 * @ctxt:  an HTML parser context
4487
 *
4488
 * DEPRECATED: Internal function, don't use.
4489
 *
4490
 * parse an HTML element, this is highly recursive
4491
 * this is kept for compatibility with previous code versions
4492
 *
4493
 * [39] element ::= EmptyElemTag | STag content ETag
4494
 *
4495
 * [41] Attribute ::= Name Eq AttValue
4496
 */
4497
4498
void
4499
0
htmlParseElement(htmlParserCtxtPtr ctxt) {
4500
0
    const xmlChar *name;
4501
0
    xmlChar *currentNode = NULL;
4502
0
    const htmlElemDesc * info;
4503
0
    htmlParserNodeInfo node_info;
4504
0
    int failed;
4505
0
    int depth;
4506
0
    const xmlChar *oldptr;
4507
4508
0
    if ((ctxt == NULL) || (ctxt->input == NULL)) {
4509
0
  htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
4510
0
         "htmlParseElement: context error\n", NULL, NULL);
4511
0
  return;
4512
0
    }
4513
4514
0
    if (ctxt->instate == XML_PARSER_EOF)
4515
0
        return;
4516
4517
    /* Capture start position */
4518
0
    if (ctxt->record_info) {
4519
0
        node_info.begin_pos = ctxt->input->consumed +
4520
0
                          (CUR_PTR - ctxt->input->base);
4521
0
  node_info.begin_line = ctxt->input->line;
4522
0
    }
4523
4524
0
    failed = htmlParseStartTag(ctxt);
4525
0
    name = ctxt->name;
4526
0
    if ((failed == -1) || (name == NULL)) {
4527
0
  if (CUR == '>')
4528
0
      NEXT;
4529
0
        return;
4530
0
    }
4531
4532
    /*
4533
     * Lookup the info for that element.
4534
     */
4535
0
    info = htmlTagLookup(name);
4536
0
    if (info == NULL) {
4537
0
  htmlParseErr(ctxt, XML_HTML_UNKNOWN_TAG,
4538
0
               "Tag %s invalid\n", name, NULL);
4539
0
    }
4540
4541
    /*
4542
     * Check for an Empty Element labeled the XML/SGML way
4543
     */
4544
0
    if ((CUR == '/') && (NXT(1) == '>')) {
4545
0
        SKIP(2);
4546
0
  if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
4547
0
      ctxt->sax->endElement(ctxt->userData, name);
4548
0
  htmlnamePop(ctxt);
4549
0
  return;
4550
0
    }
4551
4552
0
    if (CUR == '>') {
4553
0
        NEXT;
4554
0
    } else {
4555
0
  htmlParseErr(ctxt, XML_ERR_GT_REQUIRED,
4556
0
               "Couldn't find end of Start Tag %s\n", name, NULL);
4557
4558
  /*
4559
   * end of parsing of this node.
4560
   */
4561
0
  if (xmlStrEqual(name, ctxt->name)) {
4562
0
      nodePop(ctxt);
4563
0
      htmlnamePop(ctxt);
4564
0
  }
4565
4566
  /*
4567
   * Capture end position and add node
4568
   */
4569
0
  if (ctxt->record_info) {
4570
0
     node_info.end_pos = ctxt->input->consumed +
4571
0
            (CUR_PTR - ctxt->input->base);
4572
0
     node_info.end_line = ctxt->input->line;
4573
0
     node_info.node = ctxt->node;
4574
0
     xmlParserAddNodeInfo(ctxt, &node_info);
4575
0
  }
4576
0
  return;
4577
0
    }
4578
4579
    /*
4580
     * Check for an Empty Element from DTD definition
4581
     */
4582
0
    if ((info != NULL) && (info->empty)) {
4583
0
  if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
4584
0
      ctxt->sax->endElement(ctxt->userData, name);
4585
0
  htmlnamePop(ctxt);
4586
0
  return;
4587
0
    }
4588
4589
    /*
4590
     * Parse the content of the element:
4591
     */
4592
0
    currentNode = xmlStrdup(ctxt->name);
4593
0
    depth = ctxt->nameNr;
4594
0
    while (CUR != 0) {
4595
0
  oldptr = ctxt->input->cur;
4596
0
  htmlParseContent(ctxt);
4597
0
  if (oldptr==ctxt->input->cur) break;
4598
0
  if (ctxt->nameNr < depth) break;
4599
0
    }
4600
4601
    /*
4602
     * Capture end position and add node
4603
     */
4604
0
    if ( currentNode != NULL && ctxt->record_info ) {
4605
0
       node_info.end_pos = ctxt->input->consumed +
4606
0
                          (CUR_PTR - ctxt->input->base);
4607
0
       node_info.end_line = ctxt->input->line;
4608
0
       node_info.node = ctxt->node;
4609
0
       xmlParserAddNodeInfo(ctxt, &node_info);
4610
0
    }
4611
0
    if (CUR == 0) {
4612
0
  htmlAutoCloseOnEnd(ctxt);
4613
0
    }
4614
4615
0
    if (currentNode != NULL)
4616
0
  xmlFree(currentNode);
4617
0
}
4618
4619
static void
4620
0
htmlParserFinishElementParsing(htmlParserCtxtPtr ctxt) {
4621
    /*
4622
     * Capture end position and add node
4623
     */
4624
0
    if ( ctxt->node != NULL && ctxt->record_info ) {
4625
0
       ctxt->nodeInfo->end_pos = ctxt->input->consumed +
4626
0
                                (CUR_PTR - ctxt->input->base);
4627
0
       ctxt->nodeInfo->end_line = ctxt->input->line;
4628
0
       ctxt->nodeInfo->node = ctxt->node;
4629
0
       xmlParserAddNodeInfo(ctxt, ctxt->nodeInfo);
4630
0
       htmlNodeInfoPop(ctxt);
4631
0
    }
4632
0
    if (CUR == 0) {
4633
0
       htmlAutoCloseOnEnd(ctxt);
4634
0
    }
4635
0
}
4636
4637
/**
4638
 * htmlParseElementInternal:
4639
 * @ctxt:  an HTML parser context
4640
 *
4641
 * parse an HTML element, new version, non recursive
4642
 *
4643
 * [39] element ::= EmptyElemTag | STag content ETag
4644
 *
4645
 * [41] Attribute ::= Name Eq AttValue
4646
 */
4647
4648
static void
4649
0
htmlParseElementInternal(htmlParserCtxtPtr ctxt) {
4650
0
    const xmlChar *name;
4651
0
    const htmlElemDesc * info;
4652
0
    htmlParserNodeInfo node_info = { NULL, 0, 0, 0, 0 };
4653
0
    int failed;
4654
4655
0
    if ((ctxt == NULL) || (ctxt->input == NULL)) {
4656
0
  htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
4657
0
         "htmlParseElementInternal: context error\n", NULL, NULL);
4658
0
  return;
4659
0
    }
4660
4661
0
    if (ctxt->instate == XML_PARSER_EOF)
4662
0
        return;
4663
4664
    /* Capture start position */
4665
0
    if (ctxt->record_info) {
4666
0
        node_info.begin_pos = ctxt->input->consumed +
4667
0
                          (CUR_PTR - ctxt->input->base);
4668
0
  node_info.begin_line = ctxt->input->line;
4669
0
    }
4670
4671
0
    failed = htmlParseStartTag(ctxt);
4672
0
    name = ctxt->name;
4673
0
    if ((failed == -1) || (name == NULL)) {
4674
0
  if (CUR == '>')
4675
0
      NEXT;
4676
0
        return;
4677
0
    }
4678
4679
    /*
4680
     * Lookup the info for that element.
4681
     */
4682
0
    info = htmlTagLookup(name);
4683
0
    if (info == NULL) {
4684
0
  htmlParseErr(ctxt, XML_HTML_UNKNOWN_TAG,
4685
0
               "Tag %s invalid\n", name, NULL);
4686
0
    }
4687
4688
    /*
4689
     * Check for an Empty Element labeled the XML/SGML way
4690
     */
4691
0
    if ((CUR == '/') && (NXT(1) == '>')) {
4692
0
        SKIP(2);
4693
0
  if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
4694
0
      ctxt->sax->endElement(ctxt->userData, name);
4695
0
  htmlnamePop(ctxt);
4696
0
  return;
4697
0
    }
4698
4699
0
    if (CUR == '>') {
4700
0
        NEXT;
4701
0
    } else {
4702
0
  htmlParseErr(ctxt, XML_ERR_GT_REQUIRED,
4703
0
               "Couldn't find end of Start Tag %s\n", name, NULL);
4704
4705
  /*
4706
   * end of parsing of this node.
4707
   */
4708
0
  if (xmlStrEqual(name, ctxt->name)) {
4709
0
      nodePop(ctxt);
4710
0
      htmlnamePop(ctxt);
4711
0
  }
4712
4713
0
        if (ctxt->record_info)
4714
0
            htmlNodeInfoPush(ctxt, &node_info);
4715
0
        htmlParserFinishElementParsing(ctxt);
4716
0
  return;
4717
0
    }
4718
4719
    /*
4720
     * Check for an Empty Element from DTD definition
4721
     */
4722
0
    if ((info != NULL) && (info->empty)) {
4723
0
  if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
4724
0
      ctxt->sax->endElement(ctxt->userData, name);
4725
0
  htmlnamePop(ctxt);
4726
0
  return;
4727
0
    }
4728
4729
0
    if (ctxt->record_info)
4730
0
        htmlNodeInfoPush(ctxt, &node_info);
4731
0
}
4732
4733
/**
4734
 * htmlParseContentInternal:
4735
 * @ctxt:  an HTML parser context
4736
 *
4737
 * Parse a content: comment, sub-element, reference or text.
4738
 * New version for non recursive htmlParseElementInternal
4739
 */
4740
4741
static void
4742
0
htmlParseContentInternal(htmlParserCtxtPtr ctxt) {
4743
0
    xmlChar *currentNode;
4744
0
    int depth;
4745
0
    const xmlChar *name;
4746
4747
0
    depth = ctxt->nameNr;
4748
0
    if (depth <= 0) {
4749
0
        currentNode = NULL;
4750
0
    } else {
4751
0
        currentNode = xmlStrdup(ctxt->name);
4752
0
        if (currentNode == NULL) {
4753
0
            htmlErrMemory(ctxt, NULL);
4754
0
            return;
4755
0
        }
4756
0
    }
4757
0
    while (1) {
4758
0
        GROW;
4759
4760
0
        if (ctxt->instate == XML_PARSER_EOF)
4761
0
            break;
4762
4763
  /*
4764
   * Our tag or one of it's parent or children is ending.
4765
   */
4766
0
        if ((CUR == '<') && (NXT(1) == '/')) {
4767
0
      if (htmlParseEndTag(ctxt) &&
4768
0
    ((currentNode != NULL) || (ctxt->nameNr == 0))) {
4769
0
    if (currentNode != NULL)
4770
0
        xmlFree(currentNode);
4771
4772
0
          depth = ctxt->nameNr;
4773
0
                if (depth <= 0) {
4774
0
                    currentNode = NULL;
4775
0
                } else {
4776
0
                    currentNode = xmlStrdup(ctxt->name);
4777
0
                    if (currentNode == NULL) {
4778
0
                        htmlErrMemory(ctxt, NULL);
4779
0
                        break;
4780
0
                    }
4781
0
                }
4782
0
      }
4783
0
      continue; /* while */
4784
0
        }
4785
4786
0
  else if ((CUR == '<') &&
4787
0
           ((IS_ASCII_LETTER(NXT(1))) ||
4788
0
      (NXT(1) == '_') || (NXT(1) == ':'))) {
4789
0
      name = htmlParseHTMLName_nonInvasive(ctxt);
4790
0
      if (name == NULL) {
4791
0
          htmlParseErr(ctxt, XML_ERR_NAME_REQUIRED,
4792
0
       "htmlParseStartTag: invalid element name\n",
4793
0
       NULL, NULL);
4794
          /* Dump the bogus tag like browsers do */
4795
0
          while ((CUR == 0) && (CUR != '>'))
4796
0
              NEXT;
4797
4798
0
          htmlParserFinishElementParsing(ctxt);
4799
0
          if (currentNode != NULL)
4800
0
              xmlFree(currentNode);
4801
4802
0
          currentNode = xmlStrdup(ctxt->name);
4803
0
                if (currentNode == NULL) {
4804
0
                    htmlErrMemory(ctxt, NULL);
4805
0
                    break;
4806
0
                }
4807
0
          depth = ctxt->nameNr;
4808
0
          continue;
4809
0
      }
4810
4811
0
      if (ctxt->name != NULL) {
4812
0
          if (htmlCheckAutoClose(name, ctxt->name) == 1) {
4813
0
              htmlAutoClose(ctxt, name);
4814
0
              continue;
4815
0
          }
4816
0
      }
4817
0
  }
4818
4819
  /*
4820
   * Has this node been popped out during parsing of
4821
   * the next element
4822
   */
4823
0
        if ((ctxt->nameNr > 0) && (depth >= ctxt->nameNr) &&
4824
0
      (!xmlStrEqual(currentNode, ctxt->name)))
4825
0
       {
4826
0
      htmlParserFinishElementParsing(ctxt);
4827
0
      if (currentNode != NULL) xmlFree(currentNode);
4828
4829
0
      currentNode = xmlStrdup(ctxt->name);
4830
0
            if (currentNode == NULL) {
4831
0
                htmlErrMemory(ctxt, NULL);
4832
0
                break;
4833
0
            }
4834
0
      depth = ctxt->nameNr;
4835
0
      continue;
4836
0
  }
4837
4838
0
  if ((CUR != 0) && ((xmlStrEqual(currentNode, BAD_CAST"script")) ||
4839
0
      (xmlStrEqual(currentNode, BAD_CAST"style")))) {
4840
      /*
4841
       * Handle SCRIPT/STYLE separately
4842
       */
4843
0
      htmlParseScript(ctxt);
4844
0
  }
4845
4846
0
        else if ((CUR == '<') && (NXT(1) == '!')) {
4847
            /*
4848
             * Sometimes DOCTYPE arrives in the middle of the document
4849
             */
4850
0
            if ((UPP(2) == 'D') && (UPP(3) == 'O') &&
4851
0
                (UPP(4) == 'C') && (UPP(5) == 'T') &&
4852
0
                (UPP(6) == 'Y') && (UPP(7) == 'P') &&
4853
0
                (UPP(8) == 'E')) {
4854
0
                htmlParseErr(ctxt, XML_HTML_STRUCURE_ERROR,
4855
0
                             "Misplaced DOCTYPE declaration\n",
4856
0
                             BAD_CAST "DOCTYPE" , NULL);
4857
0
                htmlParseDocTypeDecl(ctxt);
4858
0
            }
4859
            /*
4860
             * First case :  a comment
4861
             */
4862
0
            else if ((NXT(2) == '-') && (NXT(3) == '-')) {
4863
0
                htmlParseComment(ctxt);
4864
0
            }
4865
0
            else {
4866
0
                htmlSkipBogusComment(ctxt);
4867
0
            }
4868
0
        }
4869
4870
        /*
4871
         * Second case : a Processing Instruction.
4872
         */
4873
0
        else if ((CUR == '<') && (NXT(1) == '?')) {
4874
0
            htmlParsePI(ctxt);
4875
0
        }
4876
4877
        /*
4878
         * Third case :  a sub-element.
4879
         */
4880
0
        else if ((CUR == '<') && IS_ASCII_LETTER(NXT(1))) {
4881
0
            htmlParseElementInternal(ctxt);
4882
0
            if (currentNode != NULL) xmlFree(currentNode);
4883
4884
0
            currentNode = xmlStrdup(ctxt->name);
4885
0
            if (currentNode == NULL) {
4886
0
                htmlErrMemory(ctxt, NULL);
4887
0
                break;
4888
0
            }
4889
0
            depth = ctxt->nameNr;
4890
0
        }
4891
0
        else if (CUR == '<') {
4892
0
            if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
4893
0
                (ctxt->sax->characters != NULL))
4894
0
                ctxt->sax->characters(ctxt->userData, BAD_CAST "<", 1);
4895
0
            NEXT;
4896
0
        }
4897
4898
        /*
4899
         * Fourth case : a reference. If if has not been resolved,
4900
         *    parsing returns it's Name, create the node
4901
         */
4902
0
        else if (CUR == '&') {
4903
0
            htmlParseReference(ctxt);
4904
0
        }
4905
4906
        /*
4907
         * Fifth case : end of the resource
4908
         */
4909
0
        else if (CUR == 0) {
4910
0
            htmlAutoCloseOnEnd(ctxt);
4911
0
            break;
4912
0
        }
4913
4914
        /*
4915
         * Last case, text. Note that References are handled directly.
4916
         */
4917
0
        else {
4918
0
            htmlParseCharData(ctxt);
4919
0
        }
4920
4921
0
        SHRINK;
4922
0
        GROW;
4923
0
    }
4924
0
    if (currentNode != NULL) xmlFree(currentNode);
4925
0
}
4926
4927
/**
4928
 * htmlParseContent:
4929
 * @ctxt:  an HTML parser context
4930
 *
4931
 * Parse a content: comment, sub-element, reference or text.
4932
 * This is the entry point when called from parser.c
4933
 */
4934
4935
void
4936
0
__htmlParseContent(void *ctxt) {
4937
0
    if (ctxt != NULL)
4938
0
  htmlParseContentInternal((htmlParserCtxtPtr) ctxt);
4939
0
}
4940
4941
/**
4942
 * htmlParseDocument:
4943
 * @ctxt:  an HTML parser context
4944
 *
4945
 * parse an HTML document (and build a tree if using the standard SAX
4946
 * interface).
4947
 *
4948
 * Returns 0, -1 in case of error. the parser context is augmented
4949
 *                as a result of the parsing.
4950
 */
4951
4952
int
4953
0
htmlParseDocument(htmlParserCtxtPtr ctxt) {
4954
0
    xmlChar start[4];
4955
0
    xmlCharEncoding enc;
4956
0
    xmlDtdPtr dtd;
4957
4958
0
    xmlInitParser();
4959
4960
0
    if ((ctxt == NULL) || (ctxt->input == NULL)) {
4961
0
  htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
4962
0
         "htmlParseDocument: context error\n", NULL, NULL);
4963
0
  return(XML_ERR_INTERNAL_ERROR);
4964
0
    }
4965
0
    GROW;
4966
    /*
4967
     * SAX: beginning of the document processing.
4968
     */
4969
0
    if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
4970
0
        ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
4971
4972
0
    if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) &&
4973
0
        ((ctxt->input->end - ctxt->input->cur) >= 4)) {
4974
  /*
4975
   * Get the 4 first bytes and decode the charset
4976
   * if enc != XML_CHAR_ENCODING_NONE
4977
   * plug some encoding conversion routines.
4978
   */
4979
0
  start[0] = RAW;
4980
0
  start[1] = NXT(1);
4981
0
  start[2] = NXT(2);
4982
0
  start[3] = NXT(3);
4983
0
  enc = xmlDetectCharEncoding(&start[0], 4);
4984
0
  if (enc != XML_CHAR_ENCODING_NONE) {
4985
0
      xmlSwitchEncoding(ctxt, enc);
4986
0
  }
4987
0
    }
4988
4989
    /*
4990
     * Wipe out everything which is before the first '<'
4991
     */
4992
0
    SKIP_BLANKS;
4993
0
    if (CUR == 0) {
4994
0
  htmlParseErr(ctxt, XML_ERR_DOCUMENT_EMPTY,
4995
0
               "Document is empty\n", NULL, NULL);
4996
0
    }
4997
4998
0
    if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
4999
0
  ctxt->sax->startDocument(ctxt->userData);
5000
5001
5002
    /*
5003
     * Parse possible comments and PIs before any content
5004
     */
5005
0
    while (((CUR == '<') && (NXT(1) == '!') &&
5006
0
            (NXT(2) == '-') && (NXT(3) == '-')) ||
5007
0
     ((CUR == '<') && (NXT(1) == '?'))) {
5008
0
        htmlParseComment(ctxt);
5009
0
        htmlParsePI(ctxt);
5010
0
  SKIP_BLANKS;
5011
0
    }
5012
5013
5014
    /*
5015
     * Then possibly doc type declaration(s) and more Misc
5016
     * (doctypedecl Misc*)?
5017
     */
5018
0
    if ((CUR == '<') && (NXT(1) == '!') &&
5019
0
  (UPP(2) == 'D') && (UPP(3) == 'O') &&
5020
0
  (UPP(4) == 'C') && (UPP(5) == 'T') &&
5021
0
  (UPP(6) == 'Y') && (UPP(7) == 'P') &&
5022
0
  (UPP(8) == 'E')) {
5023
0
  htmlParseDocTypeDecl(ctxt);
5024
0
    }
5025
0
    SKIP_BLANKS;
5026
5027
    /*
5028
     * Parse possible comments and PIs before any content
5029
     */
5030
0
    while (((CUR == '<') && (NXT(1) == '!') &&
5031
0
            (NXT(2) == '-') && (NXT(3) == '-')) ||
5032
0
     ((CUR == '<') && (NXT(1) == '?'))) {
5033
0
        htmlParseComment(ctxt);
5034
0
        htmlParsePI(ctxt);
5035
0
  SKIP_BLANKS;
5036
0
    }
5037
5038
    /*
5039
     * Time to start parsing the tree itself
5040
     */
5041
0
    htmlParseContentInternal(ctxt);
5042
5043
    /*
5044
     * autoclose
5045
     */
5046
0
    if (CUR == 0)
5047
0
  htmlAutoCloseOnEnd(ctxt);
5048
5049
5050
    /*
5051
     * SAX: end of the document processing.
5052
     */
5053
0
    if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
5054
0
        ctxt->sax->endDocument(ctxt->userData);
5055
5056
0
    if ((!(ctxt->options & HTML_PARSE_NODEFDTD)) && (ctxt->myDoc != NULL)) {
5057
0
  dtd = xmlGetIntSubset(ctxt->myDoc);
5058
0
  if (dtd == NULL)
5059
0
      ctxt->myDoc->intSubset =
5060
0
    xmlCreateIntSubset(ctxt->myDoc, BAD_CAST "html",
5061
0
        BAD_CAST "-//W3C//DTD HTML 4.0 Transitional//EN",
5062
0
        BAD_CAST "http://www.w3.org/TR/REC-html40/loose.dtd");
5063
0
    }
5064
0
    if (! ctxt->wellFormed) return(-1);
5065
0
    return(0);
5066
0
}
5067
5068
5069
/************************************************************************
5070
 *                  *
5071
 *      Parser contexts handling      *
5072
 *                  *
5073
 ************************************************************************/
5074
5075
/**
5076
 * htmlInitParserCtxt:
5077
 * @ctxt:  an HTML parser context
5078
 * @sax:  SAX handler
5079
 * @userData:  user data
5080
 *
5081
 * Initialize a parser context
5082
 *
5083
 * Returns 0 in case of success and -1 in case of error
5084
 */
5085
5086
static int
5087
htmlInitParserCtxt(htmlParserCtxtPtr ctxt, const htmlSAXHandler *sax,
5088
                   void *userData)
5089
0
{
5090
0
    if (ctxt == NULL) return(-1);
5091
0
    memset(ctxt, 0, sizeof(htmlParserCtxt));
5092
5093
0
    ctxt->dict = xmlDictCreate();
5094
0
    if (ctxt->dict == NULL) {
5095
0
        htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
5096
0
  return(-1);
5097
0
    }
5098
5099
0
    if (ctxt->sax == NULL)
5100
0
        ctxt->sax = (htmlSAXHandler *) xmlMalloc(sizeof(htmlSAXHandler));
5101
0
    if (ctxt->sax == NULL) {
5102
0
        htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
5103
0
  return(-1);
5104
0
    }
5105
0
    if (sax == NULL) {
5106
0
        memset(ctxt->sax, 0, sizeof(htmlSAXHandler));
5107
0
        xmlSAX2InitHtmlDefaultSAXHandler(ctxt->sax);
5108
0
        ctxt->userData = ctxt;
5109
0
    } else {
5110
0
        memcpy(ctxt->sax, sax, sizeof(htmlSAXHandler));
5111
0
        ctxt->userData = userData ? userData : ctxt;
5112
0
    }
5113
5114
    /* Allocate the Input stack */
5115
0
    ctxt->inputTab = (htmlParserInputPtr *)
5116
0
                      xmlMalloc(5 * sizeof(htmlParserInputPtr));
5117
0
    if (ctxt->inputTab == NULL) {
5118
0
        htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
5119
0
  ctxt->inputNr = 0;
5120
0
  ctxt->inputMax = 0;
5121
0
  ctxt->input = NULL;
5122
0
  return(-1);
5123
0
    }
5124
0
    ctxt->inputNr = 0;
5125
0
    ctxt->inputMax = 5;
5126
0
    ctxt->input = NULL;
5127
0
    ctxt->version = NULL;
5128
0
    ctxt->encoding = NULL;
5129
0
    ctxt->standalone = -1;
5130
0
    ctxt->instate = XML_PARSER_START;
5131
5132
    /* Allocate the Node stack */
5133
0
    ctxt->nodeTab = (htmlNodePtr *) xmlMalloc(10 * sizeof(htmlNodePtr));
5134
0
    if (ctxt->nodeTab == NULL) {
5135
0
        htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
5136
0
  ctxt->nodeNr = 0;
5137
0
  ctxt->nodeMax = 0;
5138
0
  ctxt->node = NULL;
5139
0
  ctxt->inputNr = 0;
5140
0
  ctxt->inputMax = 0;
5141
0
  ctxt->input = NULL;
5142
0
  return(-1);
5143
0
    }
5144
0
    ctxt->nodeNr = 0;
5145
0
    ctxt->nodeMax = 10;
5146
0
    ctxt->node = NULL;
5147
5148
    /* Allocate the Name stack */
5149
0
    ctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *));
5150
0
    if (ctxt->nameTab == NULL) {
5151
0
        htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n");
5152
0
  ctxt->nameNr = 0;
5153
0
  ctxt->nameMax = 0;
5154
0
  ctxt->name = NULL;
5155
0
  ctxt->nodeNr = 0;
5156
0
  ctxt->nodeMax = 0;
5157
0
  ctxt->node = NULL;
5158
0
  ctxt->inputNr = 0;
5159
0
  ctxt->inputMax = 0;
5160
0
  ctxt->input = NULL;
5161
0
  return(-1);
5162
0
    }
5163
0
    ctxt->nameNr = 0;
5164
0
    ctxt->nameMax = 10;
5165
0
    ctxt->name = NULL;
5166
5167
0
    ctxt->nodeInfoTab = NULL;
5168
0
    ctxt->nodeInfoNr  = 0;
5169
0
    ctxt->nodeInfoMax = 0;
5170
5171
0
    ctxt->myDoc = NULL;
5172
0
    ctxt->wellFormed = 1;
5173
0
    ctxt->replaceEntities = 0;
5174
0
    ctxt->linenumbers = xmlLineNumbersDefaultValue;
5175
0
    ctxt->keepBlanks = xmlKeepBlanksDefaultValue;
5176
0
    ctxt->html = 1;
5177
0
    ctxt->vctxt.flags = XML_VCTXT_USE_PCTXT;
5178
0
    ctxt->vctxt.userData = ctxt;
5179
0
    ctxt->vctxt.error = xmlParserValidityError;
5180
0
    ctxt->vctxt.warning = xmlParserValidityWarning;
5181
0
    ctxt->record_info = 0;
5182
0
    ctxt->validate = 0;
5183
0
    ctxt->checkIndex = 0;
5184
0
    ctxt->catalogs = NULL;
5185
0
    xmlInitNodeInfoSeq(&ctxt->node_seq);
5186
0
    return(0);
5187
0
}
5188
5189
/**
5190
 * htmlFreeParserCtxt:
5191
 * @ctxt:  an HTML parser context
5192
 *
5193
 * Free all the memory used by a parser context. However the parsed
5194
 * document in ctxt->myDoc is not freed.
5195
 */
5196
5197
void
5198
htmlFreeParserCtxt(htmlParserCtxtPtr ctxt)
5199
0
{
5200
0
    xmlFreeParserCtxt(ctxt);
5201
0
}
5202
5203
/**
5204
 * htmlNewParserCtxt:
5205
 *
5206
 * Allocate and initialize a new parser context.
5207
 *
5208
 * Returns the htmlParserCtxtPtr or NULL in case of allocation error
5209
 */
5210
5211
htmlParserCtxtPtr
5212
htmlNewParserCtxt(void)
5213
0
{
5214
0
    return(htmlNewSAXParserCtxt(NULL, NULL));
5215
0
}
5216
5217
/**
5218
 * htmlNewSAXParserCtxt:
5219
 * @sax:  SAX handler
5220
 * @userData:  user data
5221
 *
5222
 * Allocate and initialize a new SAX parser context. If userData is NULL,
5223
 * the parser context will be passed as user data.
5224
 *
5225
 * Returns the htmlParserCtxtPtr or NULL in case of allocation error
5226
 */
5227
5228
htmlParserCtxtPtr
5229
htmlNewSAXParserCtxt(const htmlSAXHandler *sax, void *userData)
5230
0
{
5231
0
    xmlParserCtxtPtr ctxt;
5232
5233
0
    ctxt = (xmlParserCtxtPtr) xmlMalloc(sizeof(xmlParserCtxt));
5234
0
    if (ctxt == NULL) {
5235
0
        htmlErrMemory(NULL, "NewParserCtxt: out of memory\n");
5236
0
  return(NULL);
5237
0
    }
5238
0
    memset(ctxt, 0, sizeof(xmlParserCtxt));
5239
0
    if (htmlInitParserCtxt(ctxt, sax, userData) < 0) {
5240
0
        htmlFreeParserCtxt(ctxt);
5241
0
  return(NULL);
5242
0
    }
5243
0
    return(ctxt);
5244
0
}
5245
5246
/**
5247
 * htmlCreateMemoryParserCtxt:
5248
 * @buffer:  a pointer to a char array
5249
 * @size:  the size of the array
5250
 *
5251
 * Create a parser context for an HTML in-memory document.
5252
 *
5253
 * Returns the new parser context or NULL
5254
 */
5255
htmlParserCtxtPtr
5256
0
htmlCreateMemoryParserCtxt(const char *buffer, int size) {
5257
0
    xmlParserCtxtPtr ctxt;
5258
0
    xmlParserInputPtr input;
5259
0
    xmlParserInputBufferPtr buf;
5260
5261
0
    if (buffer == NULL)
5262
0
  return(NULL);
5263
0
    if (size <= 0)
5264
0
  return(NULL);
5265
5266
0
    ctxt = htmlNewParserCtxt();
5267
0
    if (ctxt == NULL)
5268
0
  return(NULL);
5269
5270
0
    buf = xmlParserInputBufferCreateMem(buffer, size, XML_CHAR_ENCODING_NONE);
5271
0
    if (buf == NULL) {
5272
0
  xmlFreeParserCtxt(ctxt);
5273
0
        return(NULL);
5274
0
    }
5275
5276
0
    input = xmlNewInputStream(ctxt);
5277
0
    if (input == NULL) {
5278
0
  xmlFreeParserInputBuffer(buf);
5279
0
  xmlFreeParserCtxt(ctxt);
5280
0
  return(NULL);
5281
0
    }
5282
5283
0
    input->filename = NULL;
5284
0
    input->buf = buf;
5285
0
    xmlBufResetInput(buf->buffer, input);
5286
5287
0
    inputPush(ctxt, input);
5288
0
    return(ctxt);
5289
0
}
5290
5291
/**
5292
 * htmlCreateDocParserCtxt:
5293
 * @cur:  a pointer to an array of xmlChar
5294
 * @encoding:  a free form C string describing the HTML document encoding, or NULL
5295
 *
5296
 * Create a parser context for an HTML document.
5297
 *
5298
 * TODO: check the need to add encoding handling there
5299
 *
5300
 * Returns the new parser context or NULL
5301
 */
5302
static htmlParserCtxtPtr
5303
0
htmlCreateDocParserCtxt(const xmlChar *cur, const char *encoding) {
5304
0
    int len;
5305
0
    htmlParserCtxtPtr ctxt;
5306
5307
0
    if (cur == NULL)
5308
0
  return(NULL);
5309
0
    len = xmlStrlen(cur);
5310
0
    ctxt = htmlCreateMemoryParserCtxt((char *)cur, len);
5311
0
    if (ctxt == NULL)
5312
0
  return(NULL);
5313
5314
0
    if (encoding != NULL) {
5315
0
  xmlCharEncoding enc;
5316
0
  xmlCharEncodingHandlerPtr handler;
5317
5318
0
  if (ctxt->input->encoding != NULL)
5319
0
      xmlFree((xmlChar *) ctxt->input->encoding);
5320
0
  ctxt->input->encoding = xmlStrdup((const xmlChar *) encoding);
5321
5322
0
  enc = xmlParseCharEncoding(encoding);
5323
  /*
5324
   * registered set of known encodings
5325
   */
5326
0
  if (enc != XML_CHAR_ENCODING_ERROR) {
5327
0
      xmlSwitchEncoding(ctxt, enc);
5328
0
      if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
5329
0
    htmlParseErr(ctxt, XML_ERR_UNSUPPORTED_ENCODING,
5330
0
                 "Unsupported encoding %s\n",
5331
0
           (const xmlChar *) encoding, NULL);
5332
0
      }
5333
0
  } else {
5334
      /*
5335
       * fallback for unknown encodings
5336
       */
5337
0
      handler = xmlFindCharEncodingHandler((const char *) encoding);
5338
0
      if (handler != NULL) {
5339
0
    xmlSwitchToEncoding(ctxt, handler);
5340
0
      } else {
5341
0
    htmlParseErr(ctxt, XML_ERR_UNSUPPORTED_ENCODING,
5342
0
                 "Unsupported encoding %s\n",
5343
0
           (const xmlChar *) encoding, NULL);
5344
0
      }
5345
0
  }
5346
0
    }
5347
0
    return(ctxt);
5348
0
}
5349
5350
#ifdef LIBXML_PUSH_ENABLED
5351
/************************************************************************
5352
 *                  *
5353
 *  Progressive parsing interfaces        *
5354
 *                  *
5355
 ************************************************************************/
5356
5357
/**
5358
 * htmlParseLookupSequence:
5359
 * @ctxt:  an HTML parser context
5360
 * @first:  the first char to lookup
5361
 * @next:  the next char to lookup or zero
5362
 * @third:  the next char to lookup or zero
5363
 * @ignoreattrval: skip over attribute values
5364
 *
5365
 * Try to find if a sequence (first, next, third) or  just (first next) or
5366
 * (first) is available in the input stream.
5367
 * This function has a side effect of (possibly) incrementing ctxt->checkIndex
5368
 * to avoid rescanning sequences of bytes, it DOES change the state of the
5369
 * parser, do not use liberally.
5370
 * This is basically similar to xmlParseLookupSequence()
5371
 *
5372
 * Returns the index to the current parsing point if the full sequence
5373
 *      is available, -1 otherwise.
5374
 */
5375
static int
5376
htmlParseLookupSequence(htmlParserCtxtPtr ctxt, xmlChar first,
5377
                        xmlChar next, xmlChar third, int ignoreattrval)
5378
{
5379
    size_t base, len;
5380
    htmlParserInputPtr in;
5381
    const xmlChar *buf;
5382
    int quote;
5383
5384
    in = ctxt->input;
5385
    if (in == NULL)
5386
        return (-1);
5387
5388
    base = ctxt->checkIndex;
5389
    quote = ctxt->endCheckState;
5390
5391
    buf = in->cur;
5392
    len = in->end - in->cur;
5393
5394
    /* take into account the sequence length */
5395
    if (third)
5396
        len -= 2;
5397
    else if (next)
5398
        len--;
5399
    for (; base < len; base++) {
5400
        if (base >= INT_MAX / 2) {
5401
            ctxt->checkIndex = 0;
5402
            ctxt->endCheckState = 0;
5403
            return (base - 2);
5404
        }
5405
        if (ignoreattrval) {
5406
            if (quote) {
5407
                if (buf[base] == quote)
5408
                    quote = 0;
5409
                continue;
5410
            }
5411
            if (buf[base] == '"' || buf[base] == '\'') {
5412
                quote = buf[base];
5413
                continue;
5414
            }
5415
        }
5416
        if (buf[base] == first) {
5417
            if (third != 0) {
5418
                if ((buf[base + 1] != next) || (buf[base + 2] != third))
5419
                    continue;
5420
            } else if (next != 0) {
5421
                if (buf[base + 1] != next)
5422
                    continue;
5423
            }
5424
            ctxt->checkIndex = 0;
5425
            ctxt->endCheckState = 0;
5426
            return (base);
5427
        }
5428
    }
5429
    ctxt->checkIndex = base;
5430
    ctxt->endCheckState = quote;
5431
#ifdef DEBUG_PUSH
5432
    if (next == 0)
5433
        xmlGenericError(xmlGenericErrorContext,
5434
                        "HPP: lookup '%c' failed\n", first);
5435
    else if (third == 0)
5436
        xmlGenericError(xmlGenericErrorContext,
5437
                        "HPP: lookup '%c%c' failed\n", first, next);
5438
    else
5439
        xmlGenericError(xmlGenericErrorContext,
5440
                        "HPP: lookup '%c%c%c' failed\n", first, next,
5441
                        third);
5442
#endif
5443
    return (-1);
5444
}
5445
5446
/**
5447
 * htmlParseLookupCommentEnd:
5448
 * @ctxt: an HTML parser context
5449
 *
5450
 * Try to find a comment end tag in the input stream
5451
 * The search includes "-->" as well as WHATWG-recommended incorrectly-closed tags.
5452
 * (See https://html.spec.whatwg.org/multipage/parsing.html#parse-error-incorrectly-closed-comment)
5453
 * This function has a side effect of (possibly) incrementing ctxt->checkIndex
5454
 * to avoid rescanning sequences of bytes, it DOES change the state of the
5455
 * parser, do not use liberally.
5456
 * This wraps to htmlParseLookupSequence()
5457
 *
5458
 * Returns the index to the current parsing point if the full sequence is available, -1 otherwise.
5459
 */
5460
static int
5461
htmlParseLookupCommentEnd(htmlParserCtxtPtr ctxt)
5462
{
5463
    int mark = 0;
5464
    int offset;
5465
5466
    while (1) {
5467
  mark = htmlParseLookupSequence(ctxt, '-', '-', 0, 0);
5468
  if (mark < 0)
5469
            break;
5470
        if ((NXT(mark+2) == '>') ||
5471
      ((NXT(mark+2) == '!') && (NXT(mark+3) == '>'))) {
5472
            ctxt->checkIndex = 0;
5473
      break;
5474
  }
5475
        offset = (NXT(mark+2) == '!') ? 3 : 2;
5476
        if (mark + offset >= ctxt->input->end - ctxt->input->cur) {
5477
      ctxt->checkIndex = mark;
5478
            return(-1);
5479
        }
5480
  ctxt->checkIndex = mark + 1;
5481
    }
5482
    return mark;
5483
}
5484
5485
5486
/**
5487
 * htmlParseTryOrFinish:
5488
 * @ctxt:  an HTML parser context
5489
 * @terminate:  last chunk indicator
5490
 *
5491
 * Try to progress on parsing
5492
 *
5493
 * Returns zero if no parsing was possible
5494
 */
5495
static int
5496
htmlParseTryOrFinish(htmlParserCtxtPtr ctxt, int terminate) {
5497
    int ret = 0;
5498
    htmlParserInputPtr in;
5499
    ptrdiff_t avail = 0;
5500
    xmlChar cur, next;
5501
5502
    htmlParserNodeInfo node_info;
5503
5504
#ifdef DEBUG_PUSH
5505
    switch (ctxt->instate) {
5506
  case XML_PARSER_EOF:
5507
      xmlGenericError(xmlGenericErrorContext,
5508
        "HPP: try EOF\n"); break;
5509
  case XML_PARSER_START:
5510
      xmlGenericError(xmlGenericErrorContext,
5511
        "HPP: try START\n"); break;
5512
  case XML_PARSER_MISC:
5513
      xmlGenericError(xmlGenericErrorContext,
5514
        "HPP: try MISC\n");break;
5515
  case XML_PARSER_COMMENT:
5516
      xmlGenericError(xmlGenericErrorContext,
5517
        "HPP: try COMMENT\n");break;
5518
  case XML_PARSER_PROLOG:
5519
      xmlGenericError(xmlGenericErrorContext,
5520
        "HPP: try PROLOG\n");break;
5521
  case XML_PARSER_START_TAG:
5522
      xmlGenericError(xmlGenericErrorContext,
5523
        "HPP: try START_TAG\n");break;
5524
  case XML_PARSER_CONTENT:
5525
      xmlGenericError(xmlGenericErrorContext,
5526
        "HPP: try CONTENT\n");break;
5527
  case XML_PARSER_CDATA_SECTION:
5528
      xmlGenericError(xmlGenericErrorContext,
5529
        "HPP: try CDATA_SECTION\n");break;
5530
  case XML_PARSER_END_TAG:
5531
      xmlGenericError(xmlGenericErrorContext,
5532
        "HPP: try END_TAG\n");break;
5533
  case XML_PARSER_ENTITY_DECL:
5534
      xmlGenericError(xmlGenericErrorContext,
5535
        "HPP: try ENTITY_DECL\n");break;
5536
  case XML_PARSER_ENTITY_VALUE:
5537
      xmlGenericError(xmlGenericErrorContext,
5538
        "HPP: try ENTITY_VALUE\n");break;
5539
  case XML_PARSER_ATTRIBUTE_VALUE:
5540
      xmlGenericError(xmlGenericErrorContext,
5541
        "HPP: try ATTRIBUTE_VALUE\n");break;
5542
  case XML_PARSER_DTD:
5543
      xmlGenericError(xmlGenericErrorContext,
5544
        "HPP: try DTD\n");break;
5545
  case XML_PARSER_EPILOG:
5546
      xmlGenericError(xmlGenericErrorContext,
5547
        "HPP: try EPILOG\n");break;
5548
  case XML_PARSER_PI:
5549
      xmlGenericError(xmlGenericErrorContext,
5550
        "HPP: try PI\n");break;
5551
  case XML_PARSER_SYSTEM_LITERAL:
5552
      xmlGenericError(xmlGenericErrorContext,
5553
        "HPP: try SYSTEM_LITERAL\n");break;
5554
    }
5555
#endif
5556
5557
    while (1) {
5558
5559
  in = ctxt->input;
5560
  if (in == NULL) break;
5561
  avail = in->end - in->cur;
5562
  if ((avail == 0) && (terminate)) {
5563
      htmlAutoCloseOnEnd(ctxt);
5564
      if ((ctxt->nameNr == 0) && (ctxt->instate != XML_PARSER_EOF)) {
5565
    /*
5566
     * SAX: end of the document processing.
5567
     */
5568
    ctxt->instate = XML_PARSER_EOF;
5569
    if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
5570
        ctxt->sax->endDocument(ctxt->userData);
5571
      }
5572
  }
5573
        if (avail < 1)
5574
      goto done;
5575
        /*
5576
         * This is done to make progress and avoid an infinite loop
5577
         * if a parsing attempt was aborted by hitting a NUL byte. After
5578
         * changing htmlCurrentChar, this probably isn't necessary anymore.
5579
         * We should consider removing this check.
5580
         */
5581
  cur = in->cur[0];
5582
  if (cur == 0) {
5583
      SKIP(1);
5584
      continue;
5585
  }
5586
5587
        switch (ctxt->instate) {
5588
            case XML_PARSER_EOF:
5589
          /*
5590
     * Document parsing is done !
5591
     */
5592
          goto done;
5593
            case XML_PARSER_START:
5594
          /*
5595
     * Very first chars read from the document flow.
5596
     */
5597
    cur = in->cur[0];
5598
    if (IS_BLANK_CH(cur)) {
5599
        SKIP_BLANKS;
5600
                    avail = in->end - in->cur;
5601
    }
5602
    if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
5603
        ctxt->sax->setDocumentLocator(ctxt->userData,
5604
              &xmlDefaultSAXLocator);
5605
    if ((ctxt->sax) && (ctxt->sax->startDocument) &&
5606
              (!ctxt->disableSAX))
5607
        ctxt->sax->startDocument(ctxt->userData);
5608
5609
    cur = in->cur[0];
5610
    next = in->cur[1];
5611
    if ((cur == '<') && (next == '!') &&
5612
        (UPP(2) == 'D') && (UPP(3) == 'O') &&
5613
        (UPP(4) == 'C') && (UPP(5) == 'T') &&
5614
        (UPP(6) == 'Y') && (UPP(7) == 'P') &&
5615
        (UPP(8) == 'E')) {
5616
        if ((!terminate) &&
5617
            (htmlParseLookupSequence(ctxt, '>', 0, 0, 1) < 0))
5618
      goto done;
5619
#ifdef DEBUG_PUSH
5620
        xmlGenericError(xmlGenericErrorContext,
5621
          "HPP: Parsing internal subset\n");
5622
#endif
5623
        htmlParseDocTypeDecl(ctxt);
5624
        ctxt->instate = XML_PARSER_PROLOG;
5625
#ifdef DEBUG_PUSH
5626
        xmlGenericError(xmlGenericErrorContext,
5627
          "HPP: entering PROLOG\n");
5628
#endif
5629
                } else {
5630
        ctxt->instate = XML_PARSER_MISC;
5631
#ifdef DEBUG_PUSH
5632
        xmlGenericError(xmlGenericErrorContext,
5633
          "HPP: entering MISC\n");
5634
#endif
5635
    }
5636
    break;
5637
            case XML_PARSER_MISC:
5638
    SKIP_BLANKS;
5639
                avail = in->end - in->cur;
5640
    /*
5641
     * no chars in buffer
5642
     */
5643
    if (avail < 1)
5644
        goto done;
5645
    /*
5646
     * not enough chars in buffer
5647
     */
5648
    if (avail < 2) {
5649
        if (!terminate)
5650
      goto done;
5651
        else
5652
      next = ' ';
5653
    } else {
5654
        next = in->cur[1];
5655
    }
5656
    cur = in->cur[0];
5657
          if ((cur == '<') && (next == '!') &&
5658
        (in->cur[2] == '-') && (in->cur[3] == '-')) {
5659
        if ((!terminate) && (htmlParseLookupCommentEnd(ctxt) < 0))
5660
      goto done;
5661
#ifdef DEBUG_PUSH
5662
        xmlGenericError(xmlGenericErrorContext,
5663
          "HPP: Parsing Comment\n");
5664
#endif
5665
        htmlParseComment(ctxt);
5666
        ctxt->instate = XML_PARSER_MISC;
5667
          } else if ((cur == '<') && (next == '?')) {
5668
        if ((!terminate) &&
5669
            (htmlParseLookupSequence(ctxt, '>', 0, 0, 0) < 0))
5670
      goto done;
5671
#ifdef DEBUG_PUSH
5672
        xmlGenericError(xmlGenericErrorContext,
5673
          "HPP: Parsing PI\n");
5674
#endif
5675
        htmlParsePI(ctxt);
5676
        ctxt->instate = XML_PARSER_MISC;
5677
    } else if ((cur == '<') && (next == '!') &&
5678
        (UPP(2) == 'D') && (UPP(3) == 'O') &&
5679
        (UPP(4) == 'C') && (UPP(5) == 'T') &&
5680
        (UPP(6) == 'Y') && (UPP(7) == 'P') &&
5681
        (UPP(8) == 'E')) {
5682
        if ((!terminate) &&
5683
            (htmlParseLookupSequence(ctxt, '>', 0, 0, 1) < 0))
5684
      goto done;
5685
#ifdef DEBUG_PUSH
5686
        xmlGenericError(xmlGenericErrorContext,
5687
          "HPP: Parsing internal subset\n");
5688
#endif
5689
        htmlParseDocTypeDecl(ctxt);
5690
        ctxt->instate = XML_PARSER_PROLOG;
5691
#ifdef DEBUG_PUSH
5692
        xmlGenericError(xmlGenericErrorContext,
5693
          "HPP: entering PROLOG\n");
5694
#endif
5695
    } else if ((cur == '<') && (next == '!') &&
5696
               (avail < 9)) {
5697
        goto done;
5698
    } else {
5699
        ctxt->instate = XML_PARSER_CONTENT;
5700
#ifdef DEBUG_PUSH
5701
        xmlGenericError(xmlGenericErrorContext,
5702
          "HPP: entering START_TAG\n");
5703
#endif
5704
    }
5705
    break;
5706
            case XML_PARSER_PROLOG:
5707
    SKIP_BLANKS;
5708
                avail = in->end - in->cur;
5709
    if (avail < 2)
5710
        goto done;
5711
    cur = in->cur[0];
5712
    next = in->cur[1];
5713
    if ((cur == '<') && (next == '!') &&
5714
        (in->cur[2] == '-') && (in->cur[3] == '-')) {
5715
        if ((!terminate) && (htmlParseLookupCommentEnd(ctxt) < 0))
5716
      goto done;
5717
#ifdef DEBUG_PUSH
5718
        xmlGenericError(xmlGenericErrorContext,
5719
          "HPP: Parsing Comment\n");
5720
#endif
5721
        htmlParseComment(ctxt);
5722
        ctxt->instate = XML_PARSER_PROLOG;
5723
          } else if ((cur == '<') && (next == '?')) {
5724
        if ((!terminate) &&
5725
            (htmlParseLookupSequence(ctxt, '>', 0, 0, 0) < 0))
5726
      goto done;
5727
#ifdef DEBUG_PUSH
5728
        xmlGenericError(xmlGenericErrorContext,
5729
          "HPP: Parsing PI\n");
5730
#endif
5731
        htmlParsePI(ctxt);
5732
        ctxt->instate = XML_PARSER_PROLOG;
5733
    } else if ((cur == '<') && (next == '!') &&
5734
               (avail < 4)) {
5735
        goto done;
5736
    } else {
5737
        ctxt->instate = XML_PARSER_CONTENT;
5738
#ifdef DEBUG_PUSH
5739
        xmlGenericError(xmlGenericErrorContext,
5740
          "HPP: entering START_TAG\n");
5741
#endif
5742
    }
5743
    break;
5744
            case XML_PARSER_EPILOG:
5745
                avail = in->end - in->cur;
5746
    if (avail < 1)
5747
        goto done;
5748
    cur = in->cur[0];
5749
    if (IS_BLANK_CH(cur)) {
5750
        htmlParseCharData(ctxt);
5751
        goto done;
5752
    }
5753
    if (avail < 2)
5754
        goto done;
5755
    next = in->cur[1];
5756
          if ((cur == '<') && (next == '!') &&
5757
        (in->cur[2] == '-') && (in->cur[3] == '-')) {
5758
        if ((!terminate) && (htmlParseLookupCommentEnd(ctxt) < 0))
5759
      goto done;
5760
#ifdef DEBUG_PUSH
5761
        xmlGenericError(xmlGenericErrorContext,
5762
          "HPP: Parsing Comment\n");
5763
#endif
5764
        htmlParseComment(ctxt);
5765
        ctxt->instate = XML_PARSER_EPILOG;
5766
          } else if ((cur == '<') && (next == '?')) {
5767
        if ((!terminate) &&
5768
            (htmlParseLookupSequence(ctxt, '>', 0, 0, 0) < 0))
5769
      goto done;
5770
#ifdef DEBUG_PUSH
5771
        xmlGenericError(xmlGenericErrorContext,
5772
          "HPP: Parsing PI\n");
5773
#endif
5774
        htmlParsePI(ctxt);
5775
        ctxt->instate = XML_PARSER_EPILOG;
5776
    } else if ((cur == '<') && (next == '!') &&
5777
               (avail < 4)) {
5778
        goto done;
5779
    } else {
5780
        ctxt->errNo = XML_ERR_DOCUMENT_END;
5781
        ctxt->wellFormed = 0;
5782
        ctxt->instate = XML_PARSER_EOF;
5783
#ifdef DEBUG_PUSH
5784
        xmlGenericError(xmlGenericErrorContext,
5785
          "HPP: entering EOF\n");
5786
#endif
5787
        if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
5788
      ctxt->sax->endDocument(ctxt->userData);
5789
        goto done;
5790
    }
5791
    break;
5792
            case XML_PARSER_START_TAG: {
5793
          const xmlChar *name;
5794
    int failed;
5795
    const htmlElemDesc * info;
5796
5797
    /*
5798
     * no chars in buffer
5799
     */
5800
    if (avail < 1)
5801
        goto done;
5802
    /*
5803
     * not enough chars in buffer
5804
     */
5805
    if (avail < 2) {
5806
        if (!terminate)
5807
      goto done;
5808
        else
5809
      next = ' ';
5810
    } else {
5811
        next = in->cur[1];
5812
    }
5813
    cur = in->cur[0];
5814
          if (cur != '<') {
5815
        ctxt->instate = XML_PARSER_CONTENT;
5816
#ifdef DEBUG_PUSH
5817
        xmlGenericError(xmlGenericErrorContext,
5818
          "HPP: entering CONTENT\n");
5819
#endif
5820
        break;
5821
    }
5822
    if (next == '/') {
5823
        ctxt->instate = XML_PARSER_END_TAG;
5824
        ctxt->checkIndex = 0;
5825
#ifdef DEBUG_PUSH
5826
        xmlGenericError(xmlGenericErrorContext,
5827
          "HPP: entering END_TAG\n");
5828
#endif
5829
        break;
5830
    }
5831
    if ((!terminate) &&
5832
        (htmlParseLookupSequence(ctxt, '>', 0, 0, 1) < 0))
5833
        goto done;
5834
5835
                /* Capture start position */
5836
          if (ctxt->record_info) {
5837
               node_info.begin_pos = ctxt->input->consumed +
5838
                                  (CUR_PTR - ctxt->input->base);
5839
               node_info.begin_line = ctxt->input->line;
5840
          }
5841
5842
5843
    failed = htmlParseStartTag(ctxt);
5844
    name = ctxt->name;
5845
    if ((failed == -1) ||
5846
        (name == NULL)) {
5847
        if (CUR == '>')
5848
      NEXT;
5849
        break;
5850
    }
5851
5852
    /*
5853
     * Lookup the info for that element.
5854
     */
5855
    info = htmlTagLookup(name);
5856
    if (info == NULL) {
5857
        htmlParseErr(ctxt, XML_HTML_UNKNOWN_TAG,
5858
                     "Tag %s invalid\n", name, NULL);
5859
    }
5860
5861
    /*
5862
     * Check for an Empty Element labeled the XML/SGML way
5863
     */
5864
    if ((CUR == '/') && (NXT(1) == '>')) {
5865
        SKIP(2);
5866
        if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
5867
      ctxt->sax->endElement(ctxt->userData, name);
5868
        htmlnamePop(ctxt);
5869
        ctxt->instate = XML_PARSER_CONTENT;
5870
#ifdef DEBUG_PUSH
5871
        xmlGenericError(xmlGenericErrorContext,
5872
          "HPP: entering CONTENT\n");
5873
#endif
5874
        break;
5875
    }
5876
5877
    if (CUR == '>') {
5878
        NEXT;
5879
    } else {
5880
        htmlParseErr(ctxt, XML_ERR_GT_REQUIRED,
5881
                     "Couldn't find end of Start Tag %s\n",
5882
         name, NULL);
5883
5884
        /*
5885
         * end of parsing of this node.
5886
         */
5887
        if (xmlStrEqual(name, ctxt->name)) {
5888
      nodePop(ctxt);
5889
      htmlnamePop(ctxt);
5890
        }
5891
5892
        if (ctxt->record_info)
5893
            htmlNodeInfoPush(ctxt, &node_info);
5894
5895
        ctxt->instate = XML_PARSER_CONTENT;
5896
#ifdef DEBUG_PUSH
5897
        xmlGenericError(xmlGenericErrorContext,
5898
          "HPP: entering CONTENT\n");
5899
#endif
5900
        break;
5901
    }
5902
5903
    /*
5904
     * Check for an Empty Element from DTD definition
5905
     */
5906
    if ((info != NULL) && (info->empty)) {
5907
        if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL))
5908
      ctxt->sax->endElement(ctxt->userData, name);
5909
        htmlnamePop(ctxt);
5910
    }
5911
5912
                if (ctxt->record_info)
5913
              htmlNodeInfoPush(ctxt, &node_info);
5914
5915
    ctxt->instate = XML_PARSER_CONTENT;
5916
#ifdef DEBUG_PUSH
5917
    xmlGenericError(xmlGenericErrorContext,
5918
      "HPP: entering CONTENT\n");
5919
#endif
5920
                break;
5921
      }
5922
            case XML_PARSER_CONTENT: {
5923
    xmlChar chr[2] = { 0, 0 };
5924
5925
                /*
5926
     * Handle preparsed entities and charRef
5927
     */
5928
    if (ctxt->token != 0) {
5929
        chr[0] = ctxt->token;
5930
        htmlCheckParagraph(ctxt);
5931
        if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL))
5932
      ctxt->sax->characters(ctxt->userData, chr, 1);
5933
        ctxt->token = 0;
5934
        ctxt->checkIndex = 0;
5935
    }
5936
    if ((avail == 1) && (terminate)) {
5937
        cur = in->cur[0];
5938
        if ((cur != '<') && (cur != '&')) {
5939
      if (ctxt->sax != NULL) {
5940
                            chr[0] = cur;
5941
          if (IS_BLANK_CH(cur)) {
5942
        if (ctxt->keepBlanks) {
5943
            if (ctxt->sax->characters != NULL)
5944
          ctxt->sax->characters(
5945
            ctxt->userData, chr, 1);
5946
        } else {
5947
            if (ctxt->sax->ignorableWhitespace != NULL)
5948
          ctxt->sax->ignorableWhitespace(
5949
            ctxt->userData, chr, 1);
5950
        }
5951
          } else {
5952
        htmlCheckParagraph(ctxt);
5953
        if (ctxt->sax->characters != NULL)
5954
            ctxt->sax->characters(
5955
              ctxt->userData, chr, 1);
5956
          }
5957
      }
5958
      ctxt->token = 0;
5959
      ctxt->checkIndex = 0;
5960
      in->cur++;
5961
      break;
5962
        }
5963
    }
5964
    if (avail < 2)
5965
        goto done;
5966
    cur = in->cur[0];
5967
    next = in->cur[1];
5968
    if ((xmlStrEqual(ctxt->name, BAD_CAST"script")) ||
5969
        (xmlStrEqual(ctxt->name, BAD_CAST"style"))) {
5970
        /*
5971
         * Handle SCRIPT/STYLE separately
5972
         */
5973
        if (!terminate) {
5974
            int idx;
5975
      xmlChar val;
5976
5977
      idx = htmlParseLookupSequence(ctxt, '<', '/', 0, 0);
5978
      if (idx < 0)
5979
          goto done;
5980
            val = in->cur[idx + 2];
5981
      if (val == 0) { /* bad cut of input */
5982
                            /*
5983
                             * FIXME: htmlParseScript checks for additional
5984
                             * characters after '</'.
5985
                             */
5986
                            ctxt->checkIndex = idx;
5987
          goto done;
5988
                        }
5989
        }
5990
        htmlParseScript(ctxt);
5991
        if ((cur == '<') && (next == '/')) {
5992
      ctxt->instate = XML_PARSER_END_TAG;
5993
      ctxt->checkIndex = 0;
5994
#ifdef DEBUG_PUSH
5995
      xmlGenericError(xmlGenericErrorContext,
5996
        "HPP: entering END_TAG\n");
5997
#endif
5998
      break;
5999
        }
6000
    } else if ((cur == '<') && (next == '!')) {
6001
                    if (avail < 4)
6002
                        goto done;
6003
                    /*
6004
                     * Sometimes DOCTYPE arrives in the middle of the document
6005
                     */
6006
                    if ((UPP(2) == 'D') && (UPP(3) == 'O') &&
6007
                        (UPP(4) == 'C') && (UPP(5) == 'T') &&
6008
                        (UPP(6) == 'Y') && (UPP(7) == 'P') &&
6009
                        (UPP(8) == 'E')) {
6010
                        if ((!terminate) &&
6011
                            (htmlParseLookupSequence(ctxt, '>', 0, 0, 1) < 0))
6012
                            goto done;
6013
                        htmlParseErr(ctxt, XML_HTML_STRUCURE_ERROR,
6014
                                     "Misplaced DOCTYPE declaration\n",
6015
                                     BAD_CAST "DOCTYPE" , NULL);
6016
                        htmlParseDocTypeDecl(ctxt);
6017
                    } else if ((in->cur[2] == '-') && (in->cur[3] == '-')) {
6018
                        if ((!terminate) &&
6019
                            (htmlParseLookupCommentEnd(ctxt) < 0))
6020
                            goto done;
6021
#ifdef DEBUG_PUSH
6022
                        xmlGenericError(xmlGenericErrorContext,
6023
                                "HPP: Parsing Comment\n");
6024
#endif
6025
                        htmlParseComment(ctxt);
6026
                        ctxt->instate = XML_PARSER_CONTENT;
6027
                    } else {
6028
                        if ((!terminate) &&
6029
                            (htmlParseLookupSequence(ctxt, '>', 0, 0, 0) < 0))
6030
                            goto done;
6031
                        htmlSkipBogusComment(ctxt);
6032
                    }
6033
                } else if ((cur == '<') && (next == '?')) {
6034
                    if ((!terminate) &&
6035
                        (htmlParseLookupSequence(ctxt, '>', 0, 0, 0) < 0))
6036
                        goto done;
6037
#ifdef DEBUG_PUSH
6038
                    xmlGenericError(xmlGenericErrorContext,
6039
                            "HPP: Parsing PI\n");
6040
#endif
6041
                    htmlParsePI(ctxt);
6042
                    ctxt->instate = XML_PARSER_CONTENT;
6043
                } else if ((cur == '<') && (next == '/')) {
6044
                    ctxt->instate = XML_PARSER_END_TAG;
6045
                    ctxt->checkIndex = 0;
6046
#ifdef DEBUG_PUSH
6047
                    xmlGenericError(xmlGenericErrorContext,
6048
                            "HPP: entering END_TAG\n");
6049
#endif
6050
                    break;
6051
                } else if ((cur == '<') && IS_ASCII_LETTER(next)) {
6052
                    if ((!terminate) && (next == 0))
6053
                        goto done;
6054
                    ctxt->instate = XML_PARSER_START_TAG;
6055
                    ctxt->checkIndex = 0;
6056
#ifdef DEBUG_PUSH
6057
                    xmlGenericError(xmlGenericErrorContext,
6058
                            "HPP: entering START_TAG\n");
6059
#endif
6060
                    break;
6061
                } else if (cur == '<') {
6062
                    if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
6063
                        (ctxt->sax->characters != NULL))
6064
                        ctxt->sax->characters(ctxt->userData,
6065
                                              BAD_CAST "<", 1);
6066
                    NEXT;
6067
                } else {
6068
                    /*
6069
                     * check that the text sequence is complete
6070
                     * before handing out the data to the parser
6071
                     * to avoid problems with erroneous end of
6072
                     * data detection.
6073
                     */
6074
                    if ((!terminate) &&
6075
                        (htmlParseLookupSequence(ctxt, '<', 0, 0, 0) < 0))
6076
                        goto done;
6077
                    ctxt->checkIndex = 0;
6078
#ifdef DEBUG_PUSH
6079
                    xmlGenericError(xmlGenericErrorContext,
6080
                            "HPP: Parsing char data\n");
6081
#endif
6082
                    while ((ctxt->instate != XML_PARSER_EOF) &&
6083
                           (cur != '<') && (in->cur < in->end)) {
6084
                        if (cur == '&') {
6085
                            htmlParseReference(ctxt);
6086
                        } else {
6087
                            htmlParseCharData(ctxt);
6088
                        }
6089
                        cur = in->cur[0];
6090
                    }
6091
    }
6092
6093
    break;
6094
      }
6095
            case XML_PARSER_END_TAG:
6096
    if (avail < 2)
6097
        goto done;
6098
    if ((!terminate) &&
6099
        (htmlParseLookupSequence(ctxt, '>', 0, 0, 0) < 0))
6100
        goto done;
6101
    htmlParseEndTag(ctxt);
6102
    if (ctxt->nameNr == 0) {
6103
        ctxt->instate = XML_PARSER_EPILOG;
6104
    } else {
6105
        ctxt->instate = XML_PARSER_CONTENT;
6106
    }
6107
    ctxt->checkIndex = 0;
6108
#ifdef DEBUG_PUSH
6109
    xmlGenericError(xmlGenericErrorContext,
6110
      "HPP: entering CONTENT\n");
6111
#endif
6112
          break;
6113
            case XML_PARSER_CDATA_SECTION:
6114
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6115
      "HPP: internal error, state == CDATA\n",
6116
           NULL, NULL);
6117
    ctxt->instate = XML_PARSER_CONTENT;
6118
    ctxt->checkIndex = 0;
6119
#ifdef DEBUG_PUSH
6120
    xmlGenericError(xmlGenericErrorContext,
6121
      "HPP: entering CONTENT\n");
6122
#endif
6123
    break;
6124
            case XML_PARSER_DTD:
6125
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6126
      "HPP: internal error, state == DTD\n",
6127
           NULL, NULL);
6128
    ctxt->instate = XML_PARSER_CONTENT;
6129
    ctxt->checkIndex = 0;
6130
#ifdef DEBUG_PUSH
6131
    xmlGenericError(xmlGenericErrorContext,
6132
      "HPP: entering CONTENT\n");
6133
#endif
6134
    break;
6135
            case XML_PARSER_COMMENT:
6136
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6137
      "HPP: internal error, state == COMMENT\n",
6138
           NULL, NULL);
6139
    ctxt->instate = XML_PARSER_CONTENT;
6140
    ctxt->checkIndex = 0;
6141
#ifdef DEBUG_PUSH
6142
    xmlGenericError(xmlGenericErrorContext,
6143
      "HPP: entering CONTENT\n");
6144
#endif
6145
    break;
6146
            case XML_PARSER_PI:
6147
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6148
      "HPP: internal error, state == PI\n",
6149
           NULL, NULL);
6150
    ctxt->instate = XML_PARSER_CONTENT;
6151
    ctxt->checkIndex = 0;
6152
#ifdef DEBUG_PUSH
6153
    xmlGenericError(xmlGenericErrorContext,
6154
      "HPP: entering CONTENT\n");
6155
#endif
6156
    break;
6157
            case XML_PARSER_ENTITY_DECL:
6158
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6159
      "HPP: internal error, state == ENTITY_DECL\n",
6160
           NULL, NULL);
6161
    ctxt->instate = XML_PARSER_CONTENT;
6162
    ctxt->checkIndex = 0;
6163
#ifdef DEBUG_PUSH
6164
    xmlGenericError(xmlGenericErrorContext,
6165
      "HPP: entering CONTENT\n");
6166
#endif
6167
    break;
6168
            case XML_PARSER_ENTITY_VALUE:
6169
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6170
      "HPP: internal error, state == ENTITY_VALUE\n",
6171
           NULL, NULL);
6172
    ctxt->instate = XML_PARSER_CONTENT;
6173
    ctxt->checkIndex = 0;
6174
#ifdef DEBUG_PUSH
6175
    xmlGenericError(xmlGenericErrorContext,
6176
      "HPP: entering DTD\n");
6177
#endif
6178
    break;
6179
            case XML_PARSER_ATTRIBUTE_VALUE:
6180
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6181
      "HPP: internal error, state == ATTRIBUTE_VALUE\n",
6182
           NULL, NULL);
6183
    ctxt->instate = XML_PARSER_START_TAG;
6184
    ctxt->checkIndex = 0;
6185
#ifdef DEBUG_PUSH
6186
    xmlGenericError(xmlGenericErrorContext,
6187
      "HPP: entering START_TAG\n");
6188
#endif
6189
    break;
6190
      case XML_PARSER_SYSTEM_LITERAL:
6191
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6192
        "HPP: internal error, state == XML_PARSER_SYSTEM_LITERAL\n",
6193
           NULL, NULL);
6194
    ctxt->instate = XML_PARSER_CONTENT;
6195
    ctxt->checkIndex = 0;
6196
#ifdef DEBUG_PUSH
6197
    xmlGenericError(xmlGenericErrorContext,
6198
      "HPP: entering CONTENT\n");
6199
#endif
6200
    break;
6201
      case XML_PARSER_IGNORE:
6202
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6203
      "HPP: internal error, state == XML_PARSER_IGNORE\n",
6204
           NULL, NULL);
6205
    ctxt->instate = XML_PARSER_CONTENT;
6206
    ctxt->checkIndex = 0;
6207
#ifdef DEBUG_PUSH
6208
    xmlGenericError(xmlGenericErrorContext,
6209
      "HPP: entering CONTENT\n");
6210
#endif
6211
    break;
6212
      case XML_PARSER_PUBLIC_LITERAL:
6213
    htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6214
      "HPP: internal error, state == XML_PARSER_LITERAL\n",
6215
           NULL, NULL);
6216
    ctxt->instate = XML_PARSER_CONTENT;
6217
    ctxt->checkIndex = 0;
6218
#ifdef DEBUG_PUSH
6219
    xmlGenericError(xmlGenericErrorContext,
6220
      "HPP: entering CONTENT\n");
6221
#endif
6222
    break;
6223
6224
  }
6225
    }
6226
done:
6227
    if ((avail == 0) && (terminate)) {
6228
  htmlAutoCloseOnEnd(ctxt);
6229
  if ((ctxt->nameNr == 0) && (ctxt->instate != XML_PARSER_EOF)) {
6230
      /*
6231
       * SAX: end of the document processing.
6232
       */
6233
      ctxt->instate = XML_PARSER_EOF;
6234
      if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
6235
    ctxt->sax->endDocument(ctxt->userData);
6236
  }
6237
    }
6238
    if ((!(ctxt->options & HTML_PARSE_NODEFDTD)) && (ctxt->myDoc != NULL) &&
6239
  ((terminate) || (ctxt->instate == XML_PARSER_EOF) ||
6240
   (ctxt->instate == XML_PARSER_EPILOG))) {
6241
  xmlDtdPtr dtd;
6242
  dtd = xmlGetIntSubset(ctxt->myDoc);
6243
  if (dtd == NULL)
6244
      ctxt->myDoc->intSubset =
6245
    xmlCreateIntSubset(ctxt->myDoc, BAD_CAST "html",
6246
        BAD_CAST "-//W3C//DTD HTML 4.0 Transitional//EN",
6247
        BAD_CAST "http://www.w3.org/TR/REC-html40/loose.dtd");
6248
    }
6249
#ifdef DEBUG_PUSH
6250
    xmlGenericError(xmlGenericErrorContext, "HPP: done %d\n", ret);
6251
#endif
6252
    return(ret);
6253
}
6254
6255
/**
6256
 * htmlParseChunk:
6257
 * @ctxt:  an HTML parser context
6258
 * @chunk:  an char array
6259
 * @size:  the size in byte of the chunk
6260
 * @terminate:  last chunk indicator
6261
 *
6262
 * Parse a Chunk of memory
6263
 *
6264
 * Returns zero if no error, the xmlParserErrors otherwise.
6265
 */
6266
int
6267
htmlParseChunk(htmlParserCtxtPtr ctxt, const char *chunk, int size,
6268
              int terminate) {
6269
    if ((ctxt == NULL) || (ctxt->input == NULL)) {
6270
  htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
6271
         "htmlParseChunk: context error\n", NULL, NULL);
6272
  return(XML_ERR_INTERNAL_ERROR);
6273
    }
6274
    if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) &&
6275
        (ctxt->input->buf != NULL) && (ctxt->instate != XML_PARSER_EOF))  {
6276
  size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input);
6277
  size_t cur = ctxt->input->cur - ctxt->input->base;
6278
  int res;
6279
6280
  res = xmlParserInputBufferPush(ctxt->input->buf, size, chunk);
6281
        xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur);
6282
  if (res < 0) {
6283
            htmlParseErr(ctxt, ctxt->input->buf->error,
6284
                         "xmlParserInputBufferPush failed", NULL, NULL);
6285
            xmlHaltParser(ctxt);
6286
      return (ctxt->errNo);
6287
  }
6288
#ifdef DEBUG_PUSH
6289
  xmlGenericError(xmlGenericErrorContext, "HPP: pushed %d\n", size);
6290
#endif
6291
6292
#if 0
6293
  if ((terminate) || (ctxt->input->buf->buffer->use > 80))
6294
      htmlParseTryOrFinish(ctxt, terminate);
6295
#endif
6296
    } else if (ctxt->instate != XML_PARSER_EOF) {
6297
  if ((ctxt->input != NULL) && ctxt->input->buf != NULL) {
6298
      xmlParserInputBufferPtr in = ctxt->input->buf;
6299
      if ((in->encoder != NULL) && (in->buffer != NULL) &&
6300
        (in->raw != NULL)) {
6301
    int nbchars;
6302
    size_t base = xmlBufGetInputBase(in->buffer, ctxt->input);
6303
    size_t current = ctxt->input->cur - ctxt->input->base;
6304
6305
    nbchars = xmlCharEncInput(in, terminate);
6306
    xmlBufSetInputBaseCur(in->buffer, ctxt->input, base, current);
6307
    if (nbchars < 0) {
6308
        htmlParseErr(ctxt, in->error,
6309
               "encoder error\n", NULL, NULL);
6310
                    xmlHaltParser(ctxt);
6311
        return(XML_ERR_INVALID_ENCODING);
6312
    }
6313
      }
6314
  }
6315
    }
6316
    htmlParseTryOrFinish(ctxt, terminate);
6317
    if (terminate) {
6318
  if ((ctxt->instate != XML_PARSER_EOF) &&
6319
      (ctxt->instate != XML_PARSER_EPILOG) &&
6320
      (ctxt->instate != XML_PARSER_MISC)) {
6321
      ctxt->errNo = XML_ERR_DOCUMENT_END;
6322
      ctxt->wellFormed = 0;
6323
  }
6324
  if (ctxt->instate != XML_PARSER_EOF) {
6325
      if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
6326
    ctxt->sax->endDocument(ctxt->userData);
6327
  }
6328
  ctxt->instate = XML_PARSER_EOF;
6329
    }
6330
    return((xmlParserErrors) ctxt->errNo);
6331
}
6332
6333
/************************************************************************
6334
 *                  *
6335
 *      User entry points       *
6336
 *                  *
6337
 ************************************************************************/
6338
6339
/**
6340
 * htmlCreatePushParserCtxt:
6341
 * @sax:  a SAX handler
6342
 * @user_data:  The user data returned on SAX callbacks
6343
 * @chunk:  a pointer to an array of chars
6344
 * @size:  number of chars in the array
6345
 * @filename:  an optional file name or URI
6346
 * @enc:  an optional encoding
6347
 *
6348
 * Create a parser context for using the HTML parser in push mode
6349
 * The value of @filename is used for fetching external entities
6350
 * and error/warning reports.
6351
 *
6352
 * Returns the new parser context or NULL
6353
 */
6354
htmlParserCtxtPtr
6355
htmlCreatePushParserCtxt(htmlSAXHandlerPtr sax, void *user_data,
6356
                         const char *chunk, int size, const char *filename,
6357
       xmlCharEncoding enc) {
6358
    htmlParserCtxtPtr ctxt;
6359
    htmlParserInputPtr inputStream;
6360
    xmlParserInputBufferPtr buf;
6361
6362
    xmlInitParser();
6363
6364
    buf = xmlAllocParserInputBuffer(enc);
6365
    if (buf == NULL) return(NULL);
6366
6367
    ctxt = htmlNewSAXParserCtxt(sax, user_data);
6368
    if (ctxt == NULL) {
6369
  xmlFreeParserInputBuffer(buf);
6370
  return(NULL);
6371
    }
6372
    if(enc==XML_CHAR_ENCODING_UTF8 || buf->encoder)
6373
  ctxt->charset=XML_CHAR_ENCODING_UTF8;
6374
    if (filename == NULL) {
6375
  ctxt->directory = NULL;
6376
    } else {
6377
        ctxt->directory = xmlParserGetDirectory(filename);
6378
    }
6379
6380
    inputStream = htmlNewInputStream(ctxt);
6381
    if (inputStream == NULL) {
6382
  xmlFreeParserCtxt(ctxt);
6383
  xmlFreeParserInputBuffer(buf);
6384
  return(NULL);
6385
    }
6386
6387
    if (filename == NULL)
6388
  inputStream->filename = NULL;
6389
    else
6390
  inputStream->filename = (char *)
6391
      xmlCanonicPath((const xmlChar *) filename);
6392
    inputStream->buf = buf;
6393
    xmlBufResetInput(buf->buffer, inputStream);
6394
6395
    inputPush(ctxt, inputStream);
6396
6397
    if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) &&
6398
        (ctxt->input->buf != NULL))  {
6399
  size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input);
6400
  size_t cur = ctxt->input->cur - ctxt->input->base;
6401
        int res;
6402
6403
  res = xmlParserInputBufferPush(ctxt->input->buf, size, chunk);
6404
        xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur);
6405
        if (res < 0) {
6406
            htmlParseErr(ctxt, ctxt->input->buf->error,
6407
                         "xmlParserInputBufferPush failed\n", NULL, NULL);
6408
            xmlHaltParser(ctxt);
6409
        }
6410
#ifdef DEBUG_PUSH
6411
  xmlGenericError(xmlGenericErrorContext, "HPP: pushed %d\n", size);
6412
#endif
6413
    }
6414
    ctxt->progressive = 1;
6415
6416
    return(ctxt);
6417
}
6418
#endif /* LIBXML_PUSH_ENABLED */
6419
6420
/**
6421
 * htmlSAXParseDoc:
6422
 * @cur:  a pointer to an array of xmlChar
6423
 * @encoding:  a free form C string describing the HTML document encoding, or NULL
6424
 * @sax:  the SAX handler block
6425
 * @userData: if using SAX, this pointer will be provided on callbacks.
6426
 *
6427
 * DEPRECATED: Use htmlNewSAXParserCtxt and htmlCtxtReadDoc.
6428
 *
6429
 * Parse an HTML in-memory document. If sax is not NULL, use the SAX callbacks
6430
 * to handle parse events. If sax is NULL, fallback to the default DOM
6431
 * behavior and return a tree.
6432
 *
6433
 * Returns the resulting document tree unless SAX is NULL or the document is
6434
 *     not well formed.
6435
 */
6436
6437
htmlDocPtr
6438
htmlSAXParseDoc(const xmlChar *cur, const char *encoding,
6439
0
                htmlSAXHandlerPtr sax, void *userData) {
6440
0
    htmlDocPtr ret;
6441
0
    htmlParserCtxtPtr ctxt;
6442
6443
0
    xmlInitParser();
6444
6445
0
    if (cur == NULL) return(NULL);
6446
6447
6448
0
    ctxt = htmlCreateDocParserCtxt(cur, encoding);
6449
0
    if (ctxt == NULL) return(NULL);
6450
0
    if (sax != NULL) {
6451
0
        if (ctxt->sax != NULL) xmlFree (ctxt->sax);
6452
0
        ctxt->sax = sax;
6453
0
        ctxt->userData = userData;
6454
0
    }
6455
6456
0
    htmlParseDocument(ctxt);
6457
0
    ret = ctxt->myDoc;
6458
0
    if (sax != NULL) {
6459
0
  ctxt->sax = NULL;
6460
0
  ctxt->userData = NULL;
6461
0
    }
6462
0
    htmlFreeParserCtxt(ctxt);
6463
6464
0
    return(ret);
6465
0
}
6466
6467
/**
6468
 * htmlParseDoc:
6469
 * @cur:  a pointer to an array of xmlChar
6470
 * @encoding:  a free form C string describing the HTML document encoding, or NULL
6471
 *
6472
 * parse an HTML in-memory document and build a tree.
6473
 *
6474
 * Returns the resulting document tree
6475
 */
6476
6477
htmlDocPtr
6478
0
htmlParseDoc(const xmlChar *cur, const char *encoding) {
6479
0
    return(htmlSAXParseDoc(cur, encoding, NULL, NULL));
6480
0
}
6481
6482
6483
/**
6484
 * htmlCreateFileParserCtxt:
6485
 * @filename:  the filename
6486
 * @encoding:  a free form C string describing the HTML document encoding, or NULL
6487
 *
6488
 * Create a parser context for a file content.
6489
 * Automatic support for ZLIB/Compress compressed document is provided
6490
 * by default if found at compile-time.
6491
 *
6492
 * Returns the new parser context or NULL
6493
 */
6494
htmlParserCtxtPtr
6495
htmlCreateFileParserCtxt(const char *filename, const char *encoding)
6496
0
{
6497
0
    htmlParserCtxtPtr ctxt;
6498
0
    htmlParserInputPtr inputStream;
6499
0
    char *canonicFilename;
6500
    /* htmlCharEncoding enc; */
6501
0
    xmlChar *content, *content_line = (xmlChar *) "charset=";
6502
6503
0
    if (filename == NULL)
6504
0
        return(NULL);
6505
6506
0
    ctxt = htmlNewParserCtxt();
6507
0
    if (ctxt == NULL) {
6508
0
  return(NULL);
6509
0
    }
6510
0
    canonicFilename = (char *) xmlCanonicPath((const xmlChar *) filename);
6511
0
    if (canonicFilename == NULL) {
6512
0
  xmlFreeParserCtxt(ctxt);
6513
0
  return(NULL);
6514
0
    }
6515
6516
0
    inputStream = xmlLoadExternalEntity(canonicFilename, NULL, ctxt);
6517
0
    xmlFree(canonicFilename);
6518
0
    if (inputStream == NULL) {
6519
0
  xmlFreeParserCtxt(ctxt);
6520
0
  return(NULL);
6521
0
    }
6522
6523
0
    inputPush(ctxt, inputStream);
6524
6525
    /* set encoding */
6526
0
    if (encoding) {
6527
0
        size_t l = strlen(encoding);
6528
6529
0
  if (l < 1000) {
6530
0
      content = xmlMallocAtomic (xmlStrlen(content_line) + l + 1);
6531
0
      if (content) {
6532
0
    strcpy ((char *)content, (char *)content_line);
6533
0
    strcat ((char *)content, (char *)encoding);
6534
0
    htmlCheckEncoding (ctxt, content);
6535
0
    xmlFree (content);
6536
0
      }
6537
0
  }
6538
0
    }
6539
6540
0
    return(ctxt);
6541
0
}
6542
6543
/**
6544
 * htmlSAXParseFile:
6545
 * @filename:  the filename
6546
 * @encoding:  a free form C string describing the HTML document encoding, or NULL
6547
 * @sax:  the SAX handler block
6548
 * @userData: if using SAX, this pointer will be provided on callbacks.
6549
 *
6550
 * DEPRECATED: Use htmlNewSAXParserCtxt and htmlCtxtReadFile.
6551
 *
6552
 * parse an HTML file and build a tree. Automatic support for ZLIB/Compress
6553
 * compressed document is provided by default if found at compile-time.
6554
 * It use the given SAX function block to handle the parsing callback.
6555
 * If sax is NULL, fallback to the default DOM tree building routines.
6556
 *
6557
 * Returns the resulting document tree unless SAX is NULL or the document is
6558
 *     not well formed.
6559
 */
6560
6561
htmlDocPtr
6562
htmlSAXParseFile(const char *filename, const char *encoding, htmlSAXHandlerPtr sax,
6563
0
                 void *userData) {
6564
0
    htmlDocPtr ret;
6565
0
    htmlParserCtxtPtr ctxt;
6566
0
    htmlSAXHandlerPtr oldsax = NULL;
6567
6568
0
    xmlInitParser();
6569
6570
0
    ctxt = htmlCreateFileParserCtxt(filename, encoding);
6571
0
    if (ctxt == NULL) return(NULL);
6572
0
    if (sax != NULL) {
6573
0
  oldsax = ctxt->sax;
6574
0
        ctxt->sax = sax;
6575
0
        ctxt->userData = userData;
6576
0
    }
6577
6578
0
    htmlParseDocument(ctxt);
6579
6580
0
    ret = ctxt->myDoc;
6581
0
    if (sax != NULL) {
6582
0
        ctxt->sax = oldsax;
6583
0
        ctxt->userData = NULL;
6584
0
    }
6585
0
    htmlFreeParserCtxt(ctxt);
6586
6587
0
    return(ret);
6588
0
}
6589
6590
/**
6591
 * htmlParseFile:
6592
 * @filename:  the filename
6593
 * @encoding:  a free form C string describing the HTML document encoding, or NULL
6594
 *
6595
 * parse an HTML file and build a tree. Automatic support for ZLIB/Compress
6596
 * compressed document is provided by default if found at compile-time.
6597
 *
6598
 * Returns the resulting document tree
6599
 */
6600
6601
htmlDocPtr
6602
0
htmlParseFile(const char *filename, const char *encoding) {
6603
0
    return(htmlSAXParseFile(filename, encoding, NULL, NULL));
6604
0
}
6605
6606
/**
6607
 * htmlHandleOmittedElem:
6608
 * @val:  int 0 or 1
6609
 *
6610
 * Set and return the previous value for handling HTML omitted tags.
6611
 *
6612
 * Returns the last value for 0 for no handling, 1 for auto insertion.
6613
 */
6614
6615
int
6616
0
htmlHandleOmittedElem(int val) {
6617
0
    int old = htmlOmittedDefaultValue;
6618
6619
0
    htmlOmittedDefaultValue = val;
6620
0
    return(old);
6621
0
}
6622
6623
/**
6624
 * htmlElementAllowedHere:
6625
 * @parent: HTML parent element
6626
 * @elt: HTML element
6627
 *
6628
 * Checks whether an HTML element may be a direct child of a parent element.
6629
 * Note - doesn't check for deprecated elements
6630
 *
6631
 * Returns 1 if allowed; 0 otherwise.
6632
 */
6633
int
6634
0
htmlElementAllowedHere(const htmlElemDesc* parent, const xmlChar* elt) {
6635
0
  const char** p ;
6636
6637
0
  if ( ! elt || ! parent || ! parent->subelts )
6638
0
  return 0 ;
6639
6640
0
  for ( p = parent->subelts; *p; ++p )
6641
0
    if ( !xmlStrcmp((const xmlChar *)*p, elt) )
6642
0
      return 1 ;
6643
6644
0
  return 0 ;
6645
0
}
6646
/**
6647
 * htmlElementStatusHere:
6648
 * @parent: HTML parent element
6649
 * @elt: HTML element
6650
 *
6651
 * Checks whether an HTML element may be a direct child of a parent element.
6652
 * and if so whether it is valid or deprecated.
6653
 *
6654
 * Returns one of HTML_VALID, HTML_DEPRECATED, HTML_INVALID
6655
 */
6656
htmlStatus
6657
0
htmlElementStatusHere(const htmlElemDesc* parent, const htmlElemDesc* elt) {
6658
0
  if ( ! parent || ! elt )
6659
0
    return HTML_INVALID ;
6660
0
  if ( ! htmlElementAllowedHere(parent, (const xmlChar*) elt->name ) )
6661
0
    return HTML_INVALID ;
6662
6663
0
  return ( elt->dtd == 0 ) ? HTML_VALID : HTML_DEPRECATED ;
6664
0
}
6665
/**
6666
 * htmlAttrAllowed:
6667
 * @elt: HTML element
6668
 * @attr: HTML attribute
6669
 * @legacy: whether to allow deprecated attributes
6670
 *
6671
 * Checks whether an attribute is valid for an element
6672
 * Has full knowledge of Required and Deprecated attributes
6673
 *
6674
 * Returns one of HTML_REQUIRED, HTML_VALID, HTML_DEPRECATED, HTML_INVALID
6675
 */
6676
htmlStatus
6677
0
htmlAttrAllowed(const htmlElemDesc* elt, const xmlChar* attr, int legacy) {
6678
0
  const char** p ;
6679
6680
0
  if ( !elt || ! attr )
6681
0
  return HTML_INVALID ;
6682
6683
0
  if ( elt->attrs_req )
6684
0
    for ( p = elt->attrs_req; *p; ++p)
6685
0
      if ( !xmlStrcmp((const xmlChar*)*p, attr) )
6686
0
        return HTML_REQUIRED ;
6687
6688
0
  if ( elt->attrs_opt )
6689
0
    for ( p = elt->attrs_opt; *p; ++p)
6690
0
      if ( !xmlStrcmp((const xmlChar*)*p, attr) )
6691
0
        return HTML_VALID ;
6692
6693
0
  if ( legacy && elt->attrs_depr )
6694
0
    for ( p = elt->attrs_depr; *p; ++p)
6695
0
      if ( !xmlStrcmp((const xmlChar*)*p, attr) )
6696
0
        return HTML_DEPRECATED ;
6697
6698
0
  return HTML_INVALID ;
6699
0
}
6700
/**
6701
 * htmlNodeStatus:
6702
 * @node: an htmlNodePtr in a tree
6703
 * @legacy: whether to allow deprecated elements (YES is faster here
6704
 *  for Element nodes)
6705
 *
6706
 * Checks whether the tree node is valid.  Experimental (the author
6707
 *     only uses the HTML enhancements in a SAX parser)
6708
 *
6709
 * Return: for Element nodes, a return from htmlElementAllowedHere (if
6710
 *  legacy allowed) or htmlElementStatusHere (otherwise).
6711
 *  for Attribute nodes, a return from htmlAttrAllowed
6712
 *  for other nodes, HTML_NA (no checks performed)
6713
 */
6714
htmlStatus
6715
0
htmlNodeStatus(const htmlNodePtr node, int legacy) {
6716
0
  if ( ! node )
6717
0
    return HTML_INVALID ;
6718
6719
0
  switch ( node->type ) {
6720
0
    case XML_ELEMENT_NODE:
6721
0
      return legacy
6722
0
  ? ( htmlElementAllowedHere (
6723
0
    htmlTagLookup(node->parent->name) , node->name
6724
0
    ) ? HTML_VALID : HTML_INVALID )
6725
0
  : htmlElementStatusHere(
6726
0
    htmlTagLookup(node->parent->name) ,
6727
0
    htmlTagLookup(node->name) )
6728
0
  ;
6729
0
    case XML_ATTRIBUTE_NODE:
6730
0
      return htmlAttrAllowed(
6731
0
  htmlTagLookup(node->parent->name) , node->name, legacy) ;
6732
0
    default: return HTML_NA ;
6733
0
  }
6734
0
}
6735
/************************************************************************
6736
 *                  *
6737
 *  New set (2.6.0) of simpler and more flexible APIs   *
6738
 *                  *
6739
 ************************************************************************/
6740
/**
6741
 * DICT_FREE:
6742
 * @str:  a string
6743
 *
6744
 * Free a string if it is not owned by the "dict" dictionary in the
6745
 * current scope
6746
 */
6747
#define DICT_FREE(str)            \
6748
0
  if ((str) && ((!dict) ||       \
6749
0
      (xmlDictOwns(dict, (const xmlChar *)(str)) == 0)))  \
6750
0
      xmlFree((char *)(str));
6751
6752
/**
6753
 * htmlCtxtReset:
6754
 * @ctxt: an HTML parser context
6755
 *
6756
 * Reset a parser context
6757
 */
6758
void
6759
htmlCtxtReset(htmlParserCtxtPtr ctxt)
6760
0
{
6761
0
    xmlParserInputPtr input;
6762
0
    xmlDictPtr dict;
6763
6764
0
    if (ctxt == NULL)
6765
0
        return;
6766
6767
0
    xmlInitParser();
6768
0
    dict = ctxt->dict;
6769
6770
0
    while ((input = inputPop(ctxt)) != NULL) { /* Non consuming */
6771
0
        xmlFreeInputStream(input);
6772
0
    }
6773
0
    ctxt->inputNr = 0;
6774
0
    ctxt->input = NULL;
6775
6776
0
    ctxt->spaceNr = 0;
6777
0
    if (ctxt->spaceTab != NULL) {
6778
0
  ctxt->spaceTab[0] = -1;
6779
0
  ctxt->space = &ctxt->spaceTab[0];
6780
0
    } else {
6781
0
  ctxt->space = NULL;
6782
0
    }
6783
6784
6785
0
    ctxt->nodeNr = 0;
6786
0
    ctxt->node = NULL;
6787
6788
0
    ctxt->nameNr = 0;
6789
0
    ctxt->name = NULL;
6790
6791
0
    ctxt->nsNr = 0;
6792
6793
0
    DICT_FREE(ctxt->version);
6794
0
    ctxt->version = NULL;
6795
0
    DICT_FREE(ctxt->encoding);
6796
0
    ctxt->encoding = NULL;
6797
0
    DICT_FREE(ctxt->directory);
6798
0
    ctxt->directory = NULL;
6799
0
    DICT_FREE(ctxt->extSubURI);
6800
0
    ctxt->extSubURI = NULL;
6801
0
    DICT_FREE(ctxt->extSubSystem);
6802
0
    ctxt->extSubSystem = NULL;
6803
0
    if (ctxt->myDoc != NULL)
6804
0
        xmlFreeDoc(ctxt->myDoc);
6805
0
    ctxt->myDoc = NULL;
6806
6807
0
    ctxt->standalone = -1;
6808
0
    ctxt->hasExternalSubset = 0;
6809
0
    ctxt->hasPErefs = 0;
6810
0
    ctxt->html = 1;
6811
0
    ctxt->external = 0;
6812
0
    ctxt->instate = XML_PARSER_START;
6813
0
    ctxt->token = 0;
6814
6815
0
    ctxt->wellFormed = 1;
6816
0
    ctxt->nsWellFormed = 1;
6817
0
    ctxt->disableSAX = 0;
6818
0
    ctxt->valid = 1;
6819
0
    ctxt->vctxt.userData = ctxt;
6820
0
    ctxt->vctxt.flags = XML_VCTXT_USE_PCTXT;
6821
0
    ctxt->vctxt.error = xmlParserValidityError;
6822
0
    ctxt->vctxt.warning = xmlParserValidityWarning;
6823
0
    ctxt->record_info = 0;
6824
0
    ctxt->checkIndex = 0;
6825
0
    ctxt->endCheckState = 0;
6826
0
    ctxt->inSubset = 0;
6827
0
    ctxt->errNo = XML_ERR_OK;
6828
0
    ctxt->depth = 0;
6829
0
    ctxt->charset = XML_CHAR_ENCODING_NONE;
6830
0
    ctxt->catalogs = NULL;
6831
0
    xmlInitNodeInfoSeq(&ctxt->node_seq);
6832
6833
0
    if (ctxt->attsDefault != NULL) {
6834
0
        xmlHashFree(ctxt->attsDefault, xmlHashDefaultDeallocator);
6835
0
        ctxt->attsDefault = NULL;
6836
0
    }
6837
0
    if (ctxt->attsSpecial != NULL) {
6838
0
        xmlHashFree(ctxt->attsSpecial, NULL);
6839
0
        ctxt->attsSpecial = NULL;
6840
0
    }
6841
6842
0
    ctxt->nbErrors = 0;
6843
0
    ctxt->nbWarnings = 0;
6844
0
    if (ctxt->lastError.code != XML_ERR_OK)
6845
0
        xmlResetError(&ctxt->lastError);
6846
0
}
6847
6848
/**
6849
 * htmlCtxtUseOptions:
6850
 * @ctxt: an HTML parser context
6851
 * @options:  a combination of htmlParserOption(s)
6852
 *
6853
 * Applies the options to the parser context
6854
 *
6855
 * Returns 0 in case of success, the set of unknown or unimplemented options
6856
 *         in case of error.
6857
 */
6858
int
6859
htmlCtxtUseOptions(htmlParserCtxtPtr ctxt, int options)
6860
0
{
6861
0
    if (ctxt == NULL)
6862
0
        return(-1);
6863
6864
0
    if (options & HTML_PARSE_NOWARNING) {
6865
0
        ctxt->sax->warning = NULL;
6866
0
        ctxt->vctxt.warning = NULL;
6867
0
        options -= XML_PARSE_NOWARNING;
6868
0
  ctxt->options |= XML_PARSE_NOWARNING;
6869
0
    }
6870
0
    if (options & HTML_PARSE_NOERROR) {
6871
0
        ctxt->sax->error = NULL;
6872
0
        ctxt->vctxt.error = NULL;
6873
0
        ctxt->sax->fatalError = NULL;
6874
0
        options -= XML_PARSE_NOERROR;
6875
0
  ctxt->options |= XML_PARSE_NOERROR;
6876
0
    }
6877
0
    if (options & HTML_PARSE_PEDANTIC) {
6878
0
        ctxt->pedantic = 1;
6879
0
        options -= XML_PARSE_PEDANTIC;
6880
0
  ctxt->options |= XML_PARSE_PEDANTIC;
6881
0
    } else
6882
0
        ctxt->pedantic = 0;
6883
0
    if (options & XML_PARSE_NOBLANKS) {
6884
0
        ctxt->keepBlanks = 0;
6885
0
        ctxt->sax->ignorableWhitespace = xmlSAX2IgnorableWhitespace;
6886
0
        options -= XML_PARSE_NOBLANKS;
6887
0
  ctxt->options |= XML_PARSE_NOBLANKS;
6888
0
    } else
6889
0
        ctxt->keepBlanks = 1;
6890
0
    if (options & HTML_PARSE_RECOVER) {
6891
0
        ctxt->recovery = 1;
6892
0
  options -= HTML_PARSE_RECOVER;
6893
0
    } else
6894
0
        ctxt->recovery = 0;
6895
0
    if (options & HTML_PARSE_COMPACT) {
6896
0
  ctxt->options |= HTML_PARSE_COMPACT;
6897
0
        options -= HTML_PARSE_COMPACT;
6898
0
    }
6899
0
    if (options & XML_PARSE_HUGE) {
6900
0
  ctxt->options |= XML_PARSE_HUGE;
6901
0
        options -= XML_PARSE_HUGE;
6902
0
    }
6903
0
    if (options & HTML_PARSE_NODEFDTD) {
6904
0
  ctxt->options |= HTML_PARSE_NODEFDTD;
6905
0
        options -= HTML_PARSE_NODEFDTD;
6906
0
    }
6907
0
    if (options & HTML_PARSE_IGNORE_ENC) {
6908
0
  ctxt->options |= HTML_PARSE_IGNORE_ENC;
6909
0
        options -= HTML_PARSE_IGNORE_ENC;
6910
0
    }
6911
0
    if (options & HTML_PARSE_NOIMPLIED) {
6912
0
        ctxt->options |= HTML_PARSE_NOIMPLIED;
6913
0
        options -= HTML_PARSE_NOIMPLIED;
6914
0
    }
6915
0
    ctxt->dictNames = 0;
6916
0
    ctxt->linenumbers = 1;
6917
0
    return (options);
6918
0
}
6919
6920
/**
6921
 * htmlDoRead:
6922
 * @ctxt:  an HTML parser context
6923
 * @URL:  the base URL to use for the document
6924
 * @encoding:  the document encoding, or NULL
6925
 * @options:  a combination of htmlParserOption(s)
6926
 * @reuse:  keep the context for reuse
6927
 *
6928
 * Common front-end for the htmlRead functions
6929
 *
6930
 * Returns the resulting document tree or NULL
6931
 */
6932
static htmlDocPtr
6933
htmlDoRead(htmlParserCtxtPtr ctxt, const char *URL, const char *encoding,
6934
          int options, int reuse)
6935
0
{
6936
0
    htmlDocPtr ret;
6937
6938
0
    htmlCtxtUseOptions(ctxt, options);
6939
0
    ctxt->html = 1;
6940
0
    if (encoding != NULL) {
6941
0
        xmlCharEncodingHandlerPtr hdlr;
6942
6943
0
  hdlr = xmlFindCharEncodingHandler(encoding);
6944
0
  if (hdlr != NULL) {
6945
0
      xmlSwitchToEncoding(ctxt, hdlr);
6946
0
      if (ctxt->input->encoding != NULL)
6947
0
        xmlFree((xmlChar *) ctxt->input->encoding);
6948
0
            ctxt->input->encoding = xmlStrdup((xmlChar *)encoding);
6949
0
        }
6950
0
    }
6951
0
    if ((URL != NULL) && (ctxt->input != NULL) &&
6952
0
        (ctxt->input->filename == NULL))
6953
0
        ctxt->input->filename = (char *) xmlStrdup((const xmlChar *) URL);
6954
0
    htmlParseDocument(ctxt);
6955
0
    ret = ctxt->myDoc;
6956
0
    ctxt->myDoc = NULL;
6957
0
    if (!reuse) {
6958
0
        if ((ctxt->dictNames) &&
6959
0
      (ret != NULL) &&
6960
0
      (ret->dict == ctxt->dict))
6961
0
      ctxt->dict = NULL;
6962
0
  xmlFreeParserCtxt(ctxt);
6963
0
    }
6964
0
    return (ret);
6965
0
}
6966
6967
/**
6968
 * htmlReadDoc:
6969
 * @cur:  a pointer to a zero terminated string
6970
 * @URL:  the base URL to use for the document
6971
 * @encoding:  the document encoding, or NULL
6972
 * @options:  a combination of htmlParserOption(s)
6973
 *
6974
 * parse an XML in-memory document and build a tree.
6975
 *
6976
 * Returns the resulting document tree
6977
 */
6978
htmlDocPtr
6979
htmlReadDoc(const xmlChar * cur, const char *URL, const char *encoding, int options)
6980
0
{
6981
0
    htmlParserCtxtPtr ctxt;
6982
6983
0
    if (cur == NULL)
6984
0
        return (NULL);
6985
6986
0
    xmlInitParser();
6987
0
    ctxt = htmlCreateDocParserCtxt(cur, NULL);
6988
0
    if (ctxt == NULL)
6989
0
        return (NULL);
6990
0
    return (htmlDoRead(ctxt, URL, encoding, options, 0));
6991
0
}
6992
6993
/**
6994
 * htmlReadFile:
6995
 * @filename:  a file or URL
6996
 * @encoding:  the document encoding, or NULL
6997
 * @options:  a combination of htmlParserOption(s)
6998
 *
6999
 * parse an XML file from the filesystem or the network.
7000
 *
7001
 * Returns the resulting document tree
7002
 */
7003
htmlDocPtr
7004
htmlReadFile(const char *filename, const char *encoding, int options)
7005
0
{
7006
0
    htmlParserCtxtPtr ctxt;
7007
7008
0
    xmlInitParser();
7009
0
    ctxt = htmlCreateFileParserCtxt(filename, encoding);
7010
0
    if (ctxt == NULL)
7011
0
        return (NULL);
7012
0
    return (htmlDoRead(ctxt, NULL, NULL, options, 0));
7013
0
}
7014
7015
/**
7016
 * htmlReadMemory:
7017
 * @buffer:  a pointer to a char array
7018
 * @size:  the size of the array
7019
 * @URL:  the base URL to use for the document
7020
 * @encoding:  the document encoding, or NULL
7021
 * @options:  a combination of htmlParserOption(s)
7022
 *
7023
 * parse an XML in-memory document and build a tree.
7024
 *
7025
 * Returns the resulting document tree
7026
 */
7027
htmlDocPtr
7028
htmlReadMemory(const char *buffer, int size, const char *URL, const char *encoding, int options)
7029
0
{
7030
0
    htmlParserCtxtPtr ctxt;
7031
7032
0
    xmlInitParser();
7033
0
    ctxt = htmlCreateMemoryParserCtxt(buffer, size);
7034
0
    if (ctxt == NULL)
7035
0
        return (NULL);
7036
0
    return (htmlDoRead(ctxt, URL, encoding, options, 0));
7037
0
}
7038
7039
/**
7040
 * htmlReadFd:
7041
 * @fd:  an open file descriptor
7042
 * @URL:  the base URL to use for the document
7043
 * @encoding:  the document encoding, or NULL
7044
 * @options:  a combination of htmlParserOption(s)
7045
 *
7046
 * parse an HTML from a file descriptor and build a tree.
7047
 * NOTE that the file descriptor will not be closed when the
7048
 *      reader is closed or reset.
7049
 *
7050
 * Returns the resulting document tree
7051
 */
7052
htmlDocPtr
7053
htmlReadFd(int fd, const char *URL, const char *encoding, int options)
7054
0
{
7055
0
    htmlParserCtxtPtr ctxt;
7056
0
    xmlParserInputBufferPtr input;
7057
0
    htmlParserInputPtr stream;
7058
7059
0
    if (fd < 0)
7060
0
        return (NULL);
7061
7062
0
    xmlInitParser();
7063
0
    input = xmlParserInputBufferCreateFd(fd, XML_CHAR_ENCODING_NONE);
7064
0
    if (input == NULL)
7065
0
        return (NULL);
7066
0
    input->closecallback = NULL;
7067
0
    ctxt = htmlNewParserCtxt();
7068
0
    if (ctxt == NULL) {
7069
0
        xmlFreeParserInputBuffer(input);
7070
0
        return (NULL);
7071
0
    }
7072
0
    stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
7073
0
    if (stream == NULL) {
7074
0
        xmlFreeParserInputBuffer(input);
7075
0
  htmlFreeParserCtxt(ctxt);
7076
0
        return (NULL);
7077
0
    }
7078
0
    inputPush(ctxt, stream);
7079
0
    return (htmlDoRead(ctxt, URL, encoding, options, 0));
7080
0
}
7081
7082
/**
7083
 * htmlReadIO:
7084
 * @ioread:  an I/O read function
7085
 * @ioclose:  an I/O close function
7086
 * @ioctx:  an I/O handler
7087
 * @URL:  the base URL to use for the document
7088
 * @encoding:  the document encoding, or NULL
7089
 * @options:  a combination of htmlParserOption(s)
7090
 *
7091
 * parse an HTML document from I/O functions and source and build a tree.
7092
 *
7093
 * Returns the resulting document tree
7094
 */
7095
htmlDocPtr
7096
htmlReadIO(xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
7097
          void *ioctx, const char *URL, const char *encoding, int options)
7098
0
{
7099
0
    htmlParserCtxtPtr ctxt;
7100
0
    xmlParserInputBufferPtr input;
7101
0
    xmlParserInputPtr stream;
7102
7103
0
    if (ioread == NULL)
7104
0
        return (NULL);
7105
0
    xmlInitParser();
7106
7107
0
    input = xmlParserInputBufferCreateIO(ioread, ioclose, ioctx,
7108
0
                                         XML_CHAR_ENCODING_NONE);
7109
0
    if (input == NULL) {
7110
0
        if (ioclose != NULL)
7111
0
            ioclose(ioctx);
7112
0
        return (NULL);
7113
0
    }
7114
0
    ctxt = htmlNewParserCtxt();
7115
0
    if (ctxt == NULL) {
7116
0
        xmlFreeParserInputBuffer(input);
7117
0
        return (NULL);
7118
0
    }
7119
0
    stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
7120
0
    if (stream == NULL) {
7121
0
        xmlFreeParserInputBuffer(input);
7122
0
  xmlFreeParserCtxt(ctxt);
7123
0
        return (NULL);
7124
0
    }
7125
0
    inputPush(ctxt, stream);
7126
0
    return (htmlDoRead(ctxt, URL, encoding, options, 0));
7127
0
}
7128
7129
/**
7130
 * htmlCtxtReadDoc:
7131
 * @ctxt:  an HTML parser context
7132
 * @cur:  a pointer to a zero terminated string
7133
 * @URL:  the base URL to use for the document
7134
 * @encoding:  the document encoding, or NULL
7135
 * @options:  a combination of htmlParserOption(s)
7136
 *
7137
 * parse an XML in-memory document and build a tree.
7138
 * This reuses the existing @ctxt parser context
7139
 *
7140
 * Returns the resulting document tree
7141
 */
7142
htmlDocPtr
7143
htmlCtxtReadDoc(htmlParserCtxtPtr ctxt, const xmlChar * cur,
7144
               const char *URL, const char *encoding, int options)
7145
0
{
7146
0
    if (cur == NULL)
7147
0
        return (NULL);
7148
0
    return (htmlCtxtReadMemory(ctxt, (const char *) cur, xmlStrlen(cur), URL,
7149
0
                               encoding, options));
7150
0
}
7151
7152
/**
7153
 * htmlCtxtReadFile:
7154
 * @ctxt:  an HTML parser context
7155
 * @filename:  a file or URL
7156
 * @encoding:  the document encoding, or NULL
7157
 * @options:  a combination of htmlParserOption(s)
7158
 *
7159
 * parse an XML file from the filesystem or the network.
7160
 * This reuses the existing @ctxt parser context
7161
 *
7162
 * Returns the resulting document tree
7163
 */
7164
htmlDocPtr
7165
htmlCtxtReadFile(htmlParserCtxtPtr ctxt, const char *filename,
7166
                const char *encoding, int options)
7167
0
{
7168
0
    xmlParserInputPtr stream;
7169
7170
0
    if (filename == NULL)
7171
0
        return (NULL);
7172
0
    if (ctxt == NULL)
7173
0
        return (NULL);
7174
0
    xmlInitParser();
7175
7176
0
    htmlCtxtReset(ctxt);
7177
7178
0
    stream = xmlLoadExternalEntity(filename, NULL, ctxt);
7179
0
    if (stream == NULL) {
7180
0
        return (NULL);
7181
0
    }
7182
0
    inputPush(ctxt, stream);
7183
0
    return (htmlDoRead(ctxt, NULL, encoding, options, 1));
7184
0
}
7185
7186
/**
7187
 * htmlCtxtReadMemory:
7188
 * @ctxt:  an HTML parser context
7189
 * @buffer:  a pointer to a char array
7190
 * @size:  the size of the array
7191
 * @URL:  the base URL to use for the document
7192
 * @encoding:  the document encoding, or NULL
7193
 * @options:  a combination of htmlParserOption(s)
7194
 *
7195
 * parse an XML in-memory document and build a tree.
7196
 * This reuses the existing @ctxt parser context
7197
 *
7198
 * Returns the resulting document tree
7199
 */
7200
htmlDocPtr
7201
htmlCtxtReadMemory(htmlParserCtxtPtr ctxt, const char *buffer, int size,
7202
                  const char *URL, const char *encoding, int options)
7203
0
{
7204
0
    xmlParserInputBufferPtr input;
7205
0
    xmlParserInputPtr stream;
7206
7207
0
    if (ctxt == NULL)
7208
0
        return (NULL);
7209
0
    if (buffer == NULL)
7210
0
        return (NULL);
7211
0
    xmlInitParser();
7212
7213
0
    htmlCtxtReset(ctxt);
7214
7215
0
    input = xmlParserInputBufferCreateMem(buffer, size, XML_CHAR_ENCODING_NONE);
7216
0
    if (input == NULL) {
7217
0
  return(NULL);
7218
0
    }
7219
7220
0
    stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
7221
0
    if (stream == NULL) {
7222
0
  xmlFreeParserInputBuffer(input);
7223
0
  return(NULL);
7224
0
    }
7225
7226
0
    inputPush(ctxt, stream);
7227
0
    return (htmlDoRead(ctxt, URL, encoding, options, 1));
7228
0
}
7229
7230
/**
7231
 * htmlCtxtReadFd:
7232
 * @ctxt:  an HTML parser context
7233
 * @fd:  an open file descriptor
7234
 * @URL:  the base URL to use for the document
7235
 * @encoding:  the document encoding, or NULL
7236
 * @options:  a combination of htmlParserOption(s)
7237
 *
7238
 * parse an XML from a file descriptor and build a tree.
7239
 * This reuses the existing @ctxt parser context
7240
 *
7241
 * Returns the resulting document tree
7242
 */
7243
htmlDocPtr
7244
htmlCtxtReadFd(htmlParserCtxtPtr ctxt, int fd,
7245
              const char *URL, const char *encoding, int options)
7246
0
{
7247
0
    xmlParserInputBufferPtr input;
7248
0
    xmlParserInputPtr stream;
7249
7250
0
    if (fd < 0)
7251
0
        return (NULL);
7252
0
    if (ctxt == NULL)
7253
0
        return (NULL);
7254
0
    xmlInitParser();
7255
7256
0
    htmlCtxtReset(ctxt);
7257
7258
7259
0
    input = xmlParserInputBufferCreateFd(fd, XML_CHAR_ENCODING_NONE);
7260
0
    if (input == NULL)
7261
0
        return (NULL);
7262
0
    stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
7263
0
    if (stream == NULL) {
7264
0
        xmlFreeParserInputBuffer(input);
7265
0
        return (NULL);
7266
0
    }
7267
0
    inputPush(ctxt, stream);
7268
0
    return (htmlDoRead(ctxt, URL, encoding, options, 1));
7269
0
}
7270
7271
/**
7272
 * htmlCtxtReadIO:
7273
 * @ctxt:  an HTML parser context
7274
 * @ioread:  an I/O read function
7275
 * @ioclose:  an I/O close function
7276
 * @ioctx:  an I/O handler
7277
 * @URL:  the base URL to use for the document
7278
 * @encoding:  the document encoding, or NULL
7279
 * @options:  a combination of htmlParserOption(s)
7280
 *
7281
 * parse an HTML document from I/O functions and source and build a tree.
7282
 * This reuses the existing @ctxt parser context
7283
 *
7284
 * Returns the resulting document tree
7285
 */
7286
htmlDocPtr
7287
htmlCtxtReadIO(htmlParserCtxtPtr ctxt, xmlInputReadCallback ioread,
7288
              xmlInputCloseCallback ioclose, void *ioctx,
7289
        const char *URL,
7290
              const char *encoding, int options)
7291
0
{
7292
0
    xmlParserInputBufferPtr input;
7293
0
    xmlParserInputPtr stream;
7294
7295
0
    if (ioread == NULL)
7296
0
        return (NULL);
7297
0
    if (ctxt == NULL)
7298
0
        return (NULL);
7299
0
    xmlInitParser();
7300
7301
0
    htmlCtxtReset(ctxt);
7302
7303
0
    input = xmlParserInputBufferCreateIO(ioread, ioclose, ioctx,
7304
0
                                         XML_CHAR_ENCODING_NONE);
7305
0
    if (input == NULL) {
7306
0
        if (ioclose != NULL)
7307
0
            ioclose(ioctx);
7308
0
        return (NULL);
7309
0
    }
7310
0
    stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
7311
0
    if (stream == NULL) {
7312
0
        xmlFreeParserInputBuffer(input);
7313
0
        return (NULL);
7314
0
    }
7315
0
    inputPush(ctxt, stream);
7316
0
    return (htmlDoRead(ctxt, URL, encoding, options, 1));
7317
0
}
7318
7319
#endif /* LIBXML_HTML_ENABLED */