XMLTokenizer.cpp 66.4 KB
Newer Older
darin@apple.com's avatar
darin@apple.com committed
1
/*
kocienda's avatar
kocienda committed
2
 * Copyright (C) 2000 Peter Kelly (pmk@post.com)
darin@apple.com's avatar
darin@apple.com committed
3
 * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved.
ap's avatar
ap committed
4
 * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
5
 * Copyright (C) 2007 Samuel Weinig (sam@webkit.org)
lars's avatar
lars committed
6
 * Copyright (C) 2007 Trolltech ASA
kocienda's avatar
kocienda committed
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
ddkilzer's avatar
ddkilzer committed
20 21
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
kocienda's avatar
kocienda committed
22 23
 */

mjs's avatar
mjs committed
24
#include "config.h"
darin's avatar
darin committed
25
#include "XMLTokenizer.h"
darin's avatar
darin committed
26

darin's avatar
darin committed
27
#include "CDATASection.h"
darin's avatar
darin committed
28
#include "CString.h"
29
#include "Cache.h"
darin's avatar
darin committed
30
#include "CachedScript.h"
darin's avatar
darin committed
31
#include "Comment.h"
darin's avatar
darin committed
32
#include "DocLoader.h"
darin's avatar
darin committed
33
#include "Document.h"
34
#include "DocumentFragment.h"
darin's avatar
darin committed
35
#include "DocumentType.h"
andersca's avatar
andersca committed
36
#include "EventNames.h"
darin's avatar
darin committed
37
#include "Frame.h"
darin's avatar
darin committed
38
#include "FrameLoader.h"
darin's avatar
darin committed
39
#include "FrameView.h"
40 41
#include "HTMLNames.h"
#include "HTMLScriptElement.h"
bdakin's avatar
bdakin committed
42
#include "HTMLStyleElement.h"
darin's avatar
darin committed
43
#include "HTMLTokenizer.h"
darin@apple.com's avatar
darin@apple.com committed
44
#include "ScriptController.h"
45
#include "ProcessingInstruction.h"
46
#include "ResourceError.h"
mjs's avatar
mjs committed
47
#include "ResourceHandle.h"
darin's avatar
darin committed
48
#include "ResourceRequest.h"
mjs's avatar
mjs committed
49
#include "ResourceResponse.h"
eric@webkit.org's avatar
eric@webkit.org committed
50
#include "TextResourceDecoder.h"
51
#ifndef USE_QXMLSTREAM
darin's avatar
darin committed
52 53
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
54 55
#else
#include <QDebug>
56
#endif
weinig's avatar
weinig committed
57
#include <wtf/Platform.h>
58
#include <wtf/StringExtras.h>
59
#include <wtf/Threading.h>
60
#include <wtf/Vector.h>
61

mjs's avatar
mjs committed
62
#if ENABLE(XSLT)
andersca's avatar
andersca committed
63 64 65
#include <libxslt/xslt.h>
#endif

mjs's avatar
mjs committed
66
#if ENABLE(SVG)
eseidel's avatar
eseidel committed
67
#include "SVGNames.h"
ddkilzer's avatar
ddkilzer committed
68
#include "SVGStyleElement.h"
eseidel's avatar
eseidel committed
69
#include "XLinkNames.h"
eseidel's avatar
eseidel committed
70 71
#endif

darin's avatar
darin committed
72 73
using namespace std;

darin's avatar
darin committed
74
namespace WebCore {
andersca's avatar
andersca committed
75 76

using namespace EventNames;
darin's avatar
darin committed
77
using namespace HTMLNames;
78

79 80
const int maxErrors = 25;

81
#ifndef USE_QXMLSTREAM
82 83 84 85 86 87 88
class PendingCallbacks {
public:
    PendingCallbacks()
    {
        m_callbacks.setAutoDelete(true);
    }
    
89 90
    void appendStartElementNSCallback(const xmlChar* xmlLocalName, const xmlChar* xmlPrefix, const xmlChar* xmlURI, int nb_namespaces,
                                      const xmlChar** namespaces, int nb_attributes, int nb_defaulted, const xmlChar** attributes)
91 92 93 94 95 96 97
    {
        PendingStartElementNSCallback* callback = new PendingStartElementNSCallback;
        
        callback->xmlLocalName = xmlStrdup(xmlLocalName);
        callback->xmlPrefix = xmlStrdup(xmlPrefix);
        callback->xmlURI = xmlStrdup(xmlURI);
        callback->nb_namespaces = nb_namespaces;
ap's avatar
ap committed
98
        callback->namespaces = reinterpret_cast<xmlChar**>(xmlMalloc(sizeof(xmlChar*) * nb_namespaces * 2));
99 100 101 102
        for (int i = 0; i < nb_namespaces * 2 ; i++)
            callback->namespaces[i] = xmlStrdup(namespaces[i]);
        callback->nb_attributes = nb_attributes;
        callback->nb_defaulted = nb_defaulted;
ap's avatar
ap committed
103
        callback->attributes =  reinterpret_cast<xmlChar**>(xmlMalloc(sizeof(xmlChar*) * nb_attributes * 5));
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        for (int i = 0; i < nb_attributes; i++) {
            // Each attribute has 5 elements in the array:
            // name, prefix, uri, value and an end pointer.
            
            for (int j = 0; j < 3; j++)
                callback->attributes[i * 5 + j] = xmlStrdup(attributes[i * 5 + j]);
            
            int len = attributes[i * 5 + 4] - attributes[i * 5 + 3];

            callback->attributes[i * 5 + 3] = xmlStrndup(attributes[i * 5 + 3], len);
            callback->attributes[i * 5 + 4] = callback->attributes[i * 5 + 3] + len;
        }
        
        m_callbacks.append(callback);
    }

    void appendEndElementNSCallback()
    {
        PendingEndElementNSCallback* callback = new PendingEndElementNSCallback;
        
        m_callbacks.append(callback);
    }
    
ap's avatar
ap committed
127
    void appendCharactersCallback(const xmlChar* s, int len)
128 129 130 131 132 133 134 135 136
    {
        PendingCharactersCallback* callback = new PendingCharactersCallback;
        
        callback->s = xmlStrndup(s, len);
        callback->len = len;
        
        m_callbacks.append(callback);        
    }
    
ap's avatar
ap committed
137
    void appendProcessingInstructionCallback(const xmlChar* target, const xmlChar* data)
138 139 140 141 142 143 144 145 146
    {
        PendingProcessingInstructionCallback* callback = new PendingProcessingInstructionCallback;
        
        callback->target = xmlStrdup(target);
        callback->data = xmlStrdup(data);
        
        m_callbacks.append(callback);
    }
    
ap's avatar
ap committed
147
    void appendCDATABlockCallback(const xmlChar* s, int len)
148 149 150 151 152 153 154 155 156
    {
        PendingCDATABlockCallback* callback = new PendingCDATABlockCallback;
        
        callback->s = xmlStrndup(s, len);
        callback->len = len;
        
        m_callbacks.append(callback);        
    }

ap's avatar
ap committed
157
    void appendCommentCallback(const xmlChar* s)
158 159 160 161 162 163 164 165
    {
        PendingCommentCallback* callback = new PendingCommentCallback;
        
        callback->s = xmlStrdup(s);
        
        m_callbacks.append(callback);        
    }

ap's avatar
ap committed
166
    void appendInternalSubsetCallback(const xmlChar* name, const xmlChar* externalID, const xmlChar* systemID)
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    {
        PendingInternalSubsetCallback* callback = new PendingInternalSubsetCallback;
        
        callback->name = xmlStrdup(name);
        callback->externalID = xmlStrdup(externalID);
        callback->systemID = xmlStrdup(systemID);
        
        m_callbacks.append(callback);        
    }
    
    void appendErrorCallback(XMLTokenizer::ErrorType type, const char* message, int lineNumber, int columnNumber)
    {
        PendingErrorCallback* callback = new PendingErrorCallback;
        
        callback->message = strdup(message);
        callback->type = type;
        callback->lineNumber = lineNumber;
        callback->columnNumber = columnNumber;
        
        m_callbacks.append(callback);
    }

    void callAndRemoveFirstCallback(XMLTokenizer* tokenizer)
    {
ap's avatar
ap committed
191
        PendingCallback* cb = m_callbacks.getFirst();
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
            
        cb->call(tokenizer);
        m_callbacks.removeFirst();
    }
    
    bool isEmpty() const { return m_callbacks.isEmpty(); }
    
private:    
    struct PendingCallback {        
        
        virtual ~PendingCallback() { } 

        virtual void call(XMLTokenizer* tokenizer) = 0;
    };  
    
    struct PendingStartElementNSCallback : public PendingCallback {        
        virtual ~PendingStartElementNSCallback() {
            xmlFree(xmlLocalName);
            xmlFree(xmlPrefix);
            xmlFree(xmlURI);
            for (int i = 0; i < nb_namespaces * 2; i++)
                xmlFree(namespaces[i]);
            xmlFree(namespaces);
            for (int i = 0; i < nb_attributes; i++)
                for (int j = 0; j < 4; j++) 
                    xmlFree(attributes[i * 5 + j]);
            xmlFree(attributes);
        }
        
        virtual void call(XMLTokenizer* tokenizer) {
            tokenizer->startElementNs(xmlLocalName, xmlPrefix, xmlURI, 
                                      nb_namespaces, (const xmlChar**)namespaces,
                                      nb_attributes, nb_defaulted, (const xmlChar**)(attributes));
        }

        xmlChar* xmlLocalName;
        xmlChar* xmlPrefix;
        xmlChar* xmlURI;
        int nb_namespaces;
        xmlChar** namespaces;
        int nb_attributes;
        int nb_defaulted;
        xmlChar** attributes;
    };
    
    struct PendingEndElementNSCallback : public PendingCallback {
        virtual void call(XMLTokenizer* tokenizer) 
        {
            tokenizer->endElementNs();
        }
    };
    
    struct PendingCharactersCallback : public PendingCallback {
        virtual ~PendingCharactersCallback() 
        {
            xmlFree(s);
        }
    
        virtual void call(XMLTokenizer* tokenizer) 
        {
            tokenizer->characters(s, len);
        }
        
        xmlChar* s;
        int len;
    };

    struct PendingProcessingInstructionCallback : public PendingCallback {
        virtual ~PendingProcessingInstructionCallback() 
        {
            xmlFree(target);
            xmlFree(data);
        }
        
        virtual void call(XMLTokenizer* tokenizer) 
        {
            tokenizer->processingInstruction(target, data);
        }
        
        xmlChar* target;
        xmlChar* data;
    };
    
    struct PendingCDATABlockCallback : public PendingCallback {
        virtual ~PendingCDATABlockCallback() 
        {
            xmlFree(s);
        }
        
        virtual void call(XMLTokenizer* tokenizer) 
        {
            tokenizer->cdataBlock(s, len);
        }
        
        xmlChar* s;
        int len;
    };

    struct PendingCommentCallback : public PendingCallback {
        virtual ~PendingCommentCallback() 
        {
            xmlFree(s);
        }
        
        virtual void call(XMLTokenizer* tokenizer) 
        {
            tokenizer->comment(s);
        }

        xmlChar* s;
    };
    
    struct PendingInternalSubsetCallback : public PendingCallback {
        virtual ~PendingInternalSubsetCallback() 
        {
            xmlFree(name);
            xmlFree(externalID);
            xmlFree(systemID);
        }
        
        virtual void call(XMLTokenizer* tokenizer)
        {
            tokenizer->internalSubset(name, externalID, systemID);
        }
        
        xmlChar* name;
        xmlChar* externalID;
        xmlChar* systemID;        
    };
    
    struct PendingErrorCallback: public PendingCallback {
        virtual ~PendingErrorCallback() 
        {
            free (message);
        }
        
        virtual void call(XMLTokenizer* tokenizer) 
        {
            tokenizer->handleError(type, message, lineNumber, columnNumber);
        }
        
        XMLTokenizer::ErrorType type;
        char* message;
        int lineNumber;
        int columnNumber;
    };
    
public:
    DeprecatedPtrList<PendingCallback> m_callbacks;
darin's avatar
darin committed
341 342 343
};
// --------------------------------

344
static int globalDescriptor = 0;
345 346
static DocLoader* globalDocLoader = 0;
static ThreadIdentifier libxmlLoaderThread = 0;
347 348

static int matchFunc(const char* uri)
349
{
350 351 352
    // Only match loads initiated due to uses of libxml2 from within XMLTokenizer to avoid
    // interfering with client applications that also use libxml2.  http://bugs.webkit.org/show_bug.cgi?id=17353
    return globalDocLoader && currentThread() == libxmlLoaderThread;
353 354
}

355 356
class OffsetBuffer {
public:
357
    OffsetBuffer(const Vector<char>& b) : m_buffer(b), m_currentOffset(0) { }
358
    
ap's avatar
ap committed
359
    int readOutBytes(char* outputBuffer, unsigned askedToRead) {
360
        unsigned bytesLeft = m_buffer.size() - m_currentOffset;
darin's avatar
darin committed
361
        unsigned lenToCopy = min(askedToRead, bytesLeft);
362 363 364 365 366 367 368 369
        if (lenToCopy) {
            memcpy(outputBuffer, m_buffer.data() + m_currentOffset, lenToCopy);
            m_currentOffset += lenToCopy;
        }
        return lenToCopy;
    }

private:
370
    Vector<char> m_buffer;
371 372 373
    unsigned m_currentOffset;
};

abarth@webkit.org's avatar
abarth@webkit.org committed
374
static bool shouldAllowExternalLoad(const KURL& url)
375
{
abarth@webkit.org's avatar
abarth@webkit.org committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389
    String urlString = url.string();

    // On non-Windows platforms libxml asks for this URL, the
    // "XML_XML_DEFAULT_CATALOG", on initialization.
    if (urlString == "file:///etc/xml/catalog")
        return false;

    // On Windows, libxml computes a URL relative to where its DLL resides.
    if (urlString.startsWith("file:///", false) && urlString.endsWith("/etc/catalog", false))
        return false;

    // The most common DTD.  There isn't much point in hammering www.w3c.org
    // by requesting this URL for every XHTML document.
    if (urlString.startsWith("http://www.w3.org/TR/xhtml", false))
390
        return false;
abarth@webkit.org's avatar
abarth@webkit.org committed
391 392 393 394 395 396 397 398 399

    // Similarly, there isn't much point in requesting the SVG DTD.
    if (urlString.startsWith("http://www.w3.org/Graphics/SVG", false))
        return false;

    // The libxml doesn't give us a lot of context for deciding whether to
    // allow this request.  In the worst case, this load could be for an
    // external entity and the resulting document could simply read the
    // retrieved content.  If we had more context, we could potentially allow
400 401
    // the parser to load a DTD.  As things stand, we take the conservative
    // route and allow same-origin requests only.
abarth@webkit.org's avatar
abarth@webkit.org committed
402
    return globalDocLoader->doc()->securityOrigin()->canRequest(url);
403
}
abarth@webkit.org's avatar
abarth@webkit.org committed
404

405 406
static void* openFunc(const char* uri)
{
407 408 409
    ASSERT(globalDocLoader);
    ASSERT(currentThread() == libxmlLoaderThread);

abarth@webkit.org's avatar
abarth@webkit.org committed
410 411 412
    KURL url(uri);

    if (!shouldAllowExternalLoad(url))
413 414
        return &globalDescriptor;

ap's avatar
ap committed
415
    ResourceError error;
mjs's avatar
mjs committed
416
    ResourceResponse response;
andersca's avatar
andersca committed
417
    Vector<char> data;
418
    
419 420 421 422 423
    DocLoader* docLoader = globalDocLoader;
    globalDocLoader = 0;
    // FIXME: We should restore the original global error handler as well.

    if (docLoader->frame()) 
abarth@webkit.org's avatar
abarth@webkit.org committed
424
        docLoader->frame()->loader()->loadResourceSynchronously(url, error, response, data);
425 426

    globalDocLoader = docLoader;
andersca's avatar
andersca committed
427

428
    return new OffsetBuffer(data);
429 430 431 432
}

static int readFunc(void* context, char* buffer, int len)
{
433 434 435 436
    // Do 0-byte reads in case of a null descriptor
    if (context == &globalDescriptor)
        return 0;
        
ap's avatar
ap committed
437
    OffsetBuffer* data = static_cast<OffsetBuffer*>(context);
438
    return data->readOutBytes(buffer, len);
439 440 441 442 443 444
}

static int writeFunc(void* context, const char* buffer, int len)
{
    // Always just do 0-byte writes
    return 0;
445 446
}

ap's avatar
ap committed
447
static int closeFunc(void* context)
448 449
{
    if (context != &globalDescriptor) {
ap's avatar
ap committed
450
        OffsetBuffer* data = static_cast<OffsetBuffer*>(context);
451 452 453 454 455
        delete data;
    }
    return 0;
}

andersca's avatar
andersca committed
456 457 458 459 460
static void errorFunc(void*, const char*, ...)
{
    // FIXME: It would be nice to display error messages somewhere.
}

ap's avatar
ap committed
461
void setLoaderForLibXMLCallbacks(DocLoader* docLoader)
462 463 464 465
{
    globalDocLoader = docLoader;
}

466 467
static bool didInit = false;

darin's avatar
darin committed
468
static xmlParserCtxtPtr createStringParser(xmlSAXHandlerPtr handlers, void* userData)
kocienda's avatar
kocienda committed
469
{
darin's avatar
darin committed
470 471
    if (!didInit) {
        xmlInitParser();
472 473
        xmlRegisterInputCallbacks(matchFunc, openFunc, readFunc, closeFunc);
        xmlRegisterOutputCallbacks(matchFunc, openFunc, writeFunc, closeFunc);
474
        libxmlLoaderThread = currentThread();
darin's avatar
darin committed
475 476
        didInit = true;
    }
kocienda's avatar
kocienda committed
477

darin's avatar
darin committed
478
    xmlParserCtxtPtr parser = xmlCreatePushParserCtxt(handlers, 0, 0, 0, 0);
eseidel's avatar
eseidel committed
479 480
    parser->_private = userData;
    parser->replaceEntities = true;
darin's avatar
darin committed
481 482
    const UChar BOM = 0xFEFF;
    const unsigned char BOMHighByte = *reinterpret_cast<const unsigned char*>(&BOM);
darin's avatar
darin committed
483
    xmlSwitchEncoding(parser, BOMHighByte == 0xFF ? XML_CHAR_ENCODING_UTF16LE : XML_CHAR_ENCODING_UTF16BE);
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

    return parser;
}


// Chunk should be encoded in UTF-8
static xmlParserCtxtPtr createMemoryParser(xmlSAXHandlerPtr handlers, void* userData, const char* chunk)
{
    if (!didInit) {
        xmlInitParser();
        xmlRegisterInputCallbacks(matchFunc, openFunc, readFunc, closeFunc);
        xmlRegisterOutputCallbacks(matchFunc, openFunc, writeFunc, closeFunc);
        libxmlLoaderThread = currentThread();
        didInit = true;
    }

    xmlParserCtxtPtr parser = xmlCreateMemoryParserCtxt(chunk, xmlStrlen((const xmlChar*)chunk));

    if (!parser)
        return 0;

    // Copy the sax handler
    memcpy(parser->sax, handlers, sizeof(xmlSAXHandler));

    // Set parser options.
    // XML_PARSE_NODICT: default dictionary option.
    // XML_PARSE_NOENT: force entities substitutions.
    xmlCtxtUseOptions(parser, XML_PARSE_NODICT | XML_PARSE_NOENT);

    // Internal initialization
    parser->sax2 = 1;
    parser->instate = XML_PARSER_CONTENT; // We are parsing a CONTENT
    parser->depth = 0;
    parser->str_xml = xmlDictLookup(parser->dict, BAD_CAST "xml", 3);
    parser->str_xmlns = xmlDictLookup(parser->dict, BAD_CAST "xmlns", 5);
    parser->str_xml_ns = xmlDictLookup(parser->dict, XML_XML_NAMESPACE, 36);
    parser->_private = userData;

darin's avatar
darin committed
522 523
    return parser;
}
524
#endif
kocienda's avatar
kocienda committed
525

526
#if defined(USE_QXMLSTREAM) && QT_VERSION >= 0x040400
527 528 529 530 531 532 533 534 535 536 537 538
class EntityResolver : public QXmlStreamEntityResolver
{
    virtual QString resolveUndeclaredEntity(const QString &name);
};

QString EntityResolver::resolveUndeclaredEntity(const QString &name)
{
    UChar c = decodeNamedEntity(name.toUtf8().constData());
    return QString(c);
}
#endif

darin's avatar
darin committed
539
// --------------------------------
kocienda's avatar
kocienda committed
540

ap's avatar
ap committed
541
XMLTokenizer::XMLTokenizer(Document* _doc, FrameView* _view)
542 543
    : m_doc(_doc)
    , m_view(_view)
544 545 546
#ifdef USE_QXMLSTREAM
    , m_wroteText(false)
#else
547
    , m_context(0)
548
#endif
549 550 551 552
    , m_currentNode(_doc)
    , m_currentNodeIsReferenced(false)
    , m_sawError(false)
    , m_sawXSLTransform(false)
553
    , m_sawFirstElement(false)
554
    , m_isXHTMLDocument(false)
555
    , m_parserPaused(false)
andersca's avatar
andersca committed
556 557
    , m_requestingScript(false)
    , m_finishCalled(false)
558 559 560
    , m_errorCount(0)
    , m_lastErrorLine(0)
    , m_lastErrorColumn(0)
andersca's avatar
andersca committed
561
    , m_pendingScript(0)
562
    , m_scriptStartLine(0)
563
    , m_parsingFragment(false)
564
#ifndef USE_QXMLSTREAM
565
    , m_pendingCallbacks(new PendingCallbacks)
566
#endif
kocienda's avatar
kocienda committed
567
{
568 569 570
#if defined(USE_QXMLSTREAM) && QT_VERSION >= 0x040400
    m_stream.setEntityResolver(new EntityResolver);
#endif
darin's avatar
darin committed
571
}
kocienda's avatar
kocienda committed
572

ap's avatar
ap committed
573
XMLTokenizer::XMLTokenizer(DocumentFragment* fragment, Element* parentElement)
ggaren's avatar
ggaren committed
574
    : m_doc(fragment->document())
575
    , m_view(0)
576 577 578
#ifdef USE_QXMLSTREAM
    , m_wroteText(false)
#else
579
    , m_context(0)
580
#endif
581 582 583 584
    , m_currentNode(fragment)
    , m_currentNodeIsReferenced(fragment)
    , m_sawError(false)
    , m_sawXSLTransform(false)
585
    , m_sawFirstElement(false)
586
    , m_isXHTMLDocument(false)
587
    , m_parserPaused(false)
andersca's avatar
andersca committed
588 589
    , m_requestingScript(false)
    , m_finishCalled(false)
590 591 592
    , m_errorCount(0)
    , m_lastErrorLine(0)
    , m_lastErrorColumn(0)
andersca's avatar
andersca committed
593
    , m_pendingScript(0)
594
    , m_scriptStartLine(0)
595
    , m_parsingFragment(true)
596
#ifndef USE_QXMLSTREAM
597
    , m_pendingCallbacks(new PendingCallbacks)
598
#endif
darin's avatar
darin committed
599
{
darin's avatar
darin committed
600 601
    if (fragment)
        fragment->ref();
darin's avatar
darin committed
602 603
    if (m_doc)
        m_doc->ref();
ggaren's avatar
ggaren committed
604
          
eseidel's avatar
eseidel committed
605
    // Add namespaces based on the parent node
darin's avatar
darin committed
606
    Vector<Element*> elemStack;
eseidel's avatar
eseidel committed
607
    while (parentElement) {
mjs's avatar
mjs committed
608
        elemStack.append(parentElement);
eseidel's avatar
eseidel committed
609
        
ap's avatar
ap committed
610
        Node* n = parentElement->parentNode();
eseidel's avatar
eseidel committed
611 612
        if (!n || !n->isElementNode())
            break;
ap's avatar
ap committed
613
        parentElement = static_cast<Element*>(n);
eseidel's avatar
eseidel committed
614
    }
ap's avatar
ap committed
615 616 617 618
    
    if (elemStack.isEmpty())
        return;
    
hausmann's avatar
hausmann committed
619
#if !PLATFORM(QT) || QT_VERSION < 0x040400
ap's avatar
ap committed
620 621
    for (Element* element = elemStack.last(); !elemStack.isEmpty(); elemStack.removeLast()) {
        if (NamedAttrMap* attrs = element->attributes()) {
eseidel's avatar
eseidel committed
622
            for (unsigned i = 0; i < attrs->length(); i++) {
ap's avatar
ap committed
623
                Attribute* attr = attrs->attributeItem(i);
eseidel's avatar
eseidel committed
624 625 626
                if (attr->localName() == "xmlns")
                    m_defaultNamespaceURI = attr->value();
                else if (attr->prefix() == "xmlns")
andersca's avatar
andersca committed
627
                    m_prefixToNamespaceMap.set(attr->localName(), attr->value());
eseidel's avatar
eseidel committed
628 629 630
            }
        }
    }
631 632 633 634 635 636 637 638 639 640 641 642 643 644
#else
    QXmlStreamNamespaceDeclarations namespaces;
    for (Element* element = elemStack.last(); !elemStack.isEmpty(); elemStack.removeLast()) {
        if (NamedAttrMap* attrs = element->attributes()) {
            for (unsigned i = 0; i < attrs->length(); i++) {
                Attribute* attr = attrs->attributeItem(i);
                if (attr->localName() == "xmlns")
                    m_defaultNamespaceURI = attr->value();
                else if (attr->prefix() == "xmlns")
                    namespaces.append(QXmlStreamNamespaceDeclaration(attr->localName(), attr->value()));
            }
        }
    }
    m_stream.addExtraNamespaceDeclarations(namespaces);
645
    m_stream.setEntityResolver(new EntityResolver);
646
#endif
ap@webkit.org's avatar
ap@webkit.org committed
647 648 649 650

    // If the parent element is not in document tree, there may be no xmlns attribute; just default to the parent's namespace.
    if (m_defaultNamespaceURI.isNull() && !parentElement->inDocument())
        m_defaultNamespaceURI = parentElement->namespaceURI();
darin's avatar
darin committed
651 652
}

darin's avatar
darin committed
653 654
XMLTokenizer::~XMLTokenizer()
{
darin's avatar
darin committed
655 656
    setCurrentNode(0);
    if (m_parsingFragment && m_doc)
darin's avatar
darin committed
657
        m_doc->deref();
andersca's avatar
andersca committed
658
    if (m_pendingScript)
hyatt@apple.com's avatar
hyatt@apple.com committed
659
        m_pendingScript->removeClient(this);
660 661 662
#if defined(USE_QXMLSTREAM) && QT_VERSION >= 0x040400
    delete m_stream.entityResolver();
#endif
663 664 665 666
#ifndef USE_QXMLSTREAM
    if (m_context)
        xmlFreeParserCtxt(m_context);
#endif
kocienda's avatar
kocienda committed
667 668
}

darin's avatar
darin committed
669
void XMLTokenizer::setCurrentNode(Node* n)
darin's avatar
darin committed
670 671 672 673 674 675 676 677 678 679
{
    bool nodeNeedsReference = n && n != m_doc;
    if (nodeNeedsReference)
        n->ref(); 
    if (m_currentNodeIsReferenced) 
        m_currentNode->deref(); 
    m_currentNode = n;
    m_currentNodeIsReferenced = nodeNeedsReference;
}

darin's avatar
darin committed
680
bool XMLTokenizer::write(const SegmentedString& s, bool /*appendData*/)
darin's avatar
darin committed
681
{
darin's avatar
darin committed
682
    String parseString = s.toString();
683
    
684 685
    if (m_sawXSLTransform || !m_sawFirstElement)
        m_originalSourceForTransform += parseString;
kocienda's avatar
kocienda committed
686

687 688
    if (m_parserStopped || m_sawXSLTransform)
        return false;
689
    
andersca's avatar
andersca committed
690
    if (m_parserPaused) {
691 692 693 694
        m_pendingSrc.append(s);
        return false;
    }
    
695
#ifndef USE_QXMLSTREAM
696 697 698
    if (!m_context)
        initializeParserContext();
    
699 700 701 702 703 704
    // libXML throws an error if you try to switch the encoding for an empty string.
    if (parseString.length()) {
        // Hack around libxml2's lack of encoding overide support by manually
        // resetting the encoding to UTF-16 before every chunk.  Otherwise libxml
        // will detect <?xml version="1.0" encoding="<encoding name>"?> blocks 
        // and switch encodings, causing the parse to fail.
darin's avatar
darin committed
705 706
        const UChar BOM = 0xFEFF;
        const unsigned char BOMHighByte = *reinterpret_cast<const unsigned char*>(&BOM);
707
        xmlSwitchEncoding(m_context, BOMHighByte == 0xFF ? XML_CHAR_ENCODING_UTF16LE : XML_CHAR_ENCODING_UTF16BE);
darin's avatar
darin committed
708 709

        xmlParseChunk(m_context, reinterpret_cast<const char*>(parseString.characters()), sizeof(UChar) * parseString.length(), 0);
710
    }
711
#else
712
    m_wroteText = true;
713 714
    QString data(parseString);
    if (!data.isEmpty()) {
715
#if QT_VERSION < 0x040400
716 717 718 719 720 721 722 723 724 725 726
        if (!m_sawFirstElement) {
            int idx = data.indexOf(QLatin1String("<?xml"));
            if (idx != -1) {
                int start = idx + 5;
                int end = data.indexOf(QLatin1String("?>"), start);
                QString content = data.mid(start, end-start);
                bool ok = true;
                HashMap<String, String> attrs = parseAttributes(content, ok);
                String version = attrs.get("version");
                String encoding = attrs.get("encoding");
                ExceptionCode ec = 0;
727 728 729 730 731 732
                if (!m_parsingFragment) {
                    if (!version.isEmpty())
                        m_doc->setXMLVersion(version, ec);
                    if (!encoding.isEmpty())
                        m_doc->setXMLEncoding(encoding);
                }
733 734
            }
        }
735
#endif
736
        m_stream.addData(data);
737 738
        parse();
    }
739
#endif
740
    
eric@webkit.org's avatar
eric@webkit.org committed
741
    if (m_doc->decoder() && m_doc->decoder()->sawError()) {
eric@webkit.org's avatar
eric@webkit.org committed
742 743
        // If the decoder saw an error, report it as fatal (stops parsing)
        handleError(fatal, "Encoding error", lineNumber(), columnNumber());
eric@webkit.org's avatar
eric@webkit.org committed
744
    }
eric@webkit.org's avatar
eric@webkit.org committed
745

746
    return false;
darin's avatar
darin committed
747
}
748
#ifndef USE_QXMLSTREAM
rwlbuis's avatar
rwlbuis committed
749
static inline String toString(const xmlChar* str, unsigned len)
darin's avatar
darin committed
750
{
darin's avatar
darin committed
751
    return UTF8Encoding().decode(reinterpret_cast<const char*>(str), len);
darin's avatar
darin committed
752 753
}

rwlbuis's avatar
rwlbuis committed
754
static inline String toString(const xmlChar* str)
darin's avatar
darin committed
755
{
andersca's avatar
andersca committed
756 757 758 759
    if (!str)
        return String();
    
    return UTF8Encoding().decode(reinterpret_cast<const char*>(str), strlen(reinterpret_cast<const char*>(str)));
darin's avatar
darin committed
760 761
}

eseidel's avatar
eseidel committed
762
struct _xmlSAX2Namespace {
ap's avatar
ap committed
763 764
    const xmlChar* prefix;
    const xmlChar* uri;
eseidel's avatar
eseidel committed
765 766 767
};
typedef struct _xmlSAX2Namespace xmlSAX2Namespace;

ap's avatar
ap committed
768
static inline void handleElementNamespaces(Element* newElement, const xmlChar** libxmlNamespaces, int nb_namespaces, ExceptionCode& ec)
eseidel's avatar
eseidel committed
769
{
ap's avatar
ap committed
770
    xmlSAX2Namespace* namespaces = reinterpret_cast<xmlSAX2Namespace*>(libxmlNamespaces);
eseidel's avatar
eseidel committed
771
    for(int i = 0; i < nb_namespaces; i++) {
darin's avatar
darin committed
772 773
        String namespaceQName = "xmlns";
        String namespaceURI = toString(namespaces[i].uri);
darin's avatar
darin committed
774 775
        if (namespaces[i].prefix)
            namespaceQName = "xmlns:" + toString(namespaces[i].prefix);
darin's avatar
darin committed
776 777
        newElement->setAttributeNS("http://www.w3.org/2000/xmlns/", namespaceQName, namespaceURI, ec);
        if (ec) // exception setting attributes
eseidel's avatar
eseidel committed
778 779 780 781 782
            return;
    }
}

struct _xmlSAX2Attributes {
ap's avatar
ap committed
783 784 785 786 787
    const xmlChar* localname;
    const xmlChar* prefix;
    const xmlChar* uri;
    const xmlChar* value;
    const xmlChar* end;
eseidel's avatar
eseidel committed
788 789 790
};
typedef struct _xmlSAX2Attributes xmlSAX2Attributes;

ap's avatar
ap committed
791
static inline void handleElementAttributes(Element* newElement, const xmlChar** libxmlAttributes, int nb_attributes, ExceptionCode& ec)
eseidel's avatar
eseidel committed
792
{
ap's avatar
ap committed
793
    xmlSAX2Attributes* attributes = reinterpret_cast<xmlSAX2Attributes*>(libxmlAttributes);
eseidel's avatar
eseidel committed
794
    for(int i = 0; i < nb_attributes; i++) {
darin's avatar
darin committed
795
        String attrLocalName = toString(attributes[i].localname);
eseidel's avatar
eseidel committed
796
        int valueLength = (int) (attributes[i].end - attributes[i].value);
darin's avatar
darin committed
797 798 799
        String attrValue = toString(attributes[i].value, valueLength);
        String attrPrefix = toString(attributes[i].prefix);
        String attrURI = attrPrefix.isEmpty() ? String() : toString(attributes[i].uri);
800
        String attrQName = attrPrefix.isEmpty() ? attrLocalName : attrPrefix + ":" + attrLocalName;
eseidel's avatar
eseidel committed
801
        
darin's avatar
darin committed
802 803
        newElement->setAttributeNS(attrURI, attrQName, attrValue, ec);
        if (ec) // exception setting attributes
eseidel's avatar
eseidel committed
804
            return;
darin's avatar
darin committed
805
    }
eseidel's avatar
eseidel committed
806 807
}

808 809
void XMLTokenizer::startElementNs(const xmlChar* xmlLocalName, const xmlChar* xmlPrefix, const xmlChar* xmlURI, int nb_namespaces,
                                  const xmlChar** libxmlNamespaces, int nb_attributes, int nb_defaulted, const xmlChar** libxmlAttributes)
eseidel's avatar
eseidel committed
810 811 812
{
    if (m_parserStopped)
        return;
813
    
814 815 816
    if (m_parserPaused) {
        m_pendingCallbacks->appendStartElementNSCallback(xmlLocalName, xmlPrefix, xmlURI, nb_namespaces, libxmlNamespaces,
                                                         nb_attributes, nb_defaulted, libxmlAttributes);
817 818 819
        return;
    }
    
820
    m_sawFirstElement = true;
darin's avatar
darin committed
821 822 823

    exitText();

darin's avatar
darin committed
824 825 826
    String localName = toString(xmlLocalName);
    String uri = toString(xmlURI);
    String prefix = toString(xmlPrefix);
827

andersca's avatar
andersca committed
828 829 830
    if (m_parsingFragment && uri.isNull()) {
        if (!prefix.isNull())
            uri = m_prefixToNamespaceMap.get(prefix);
eseidel's avatar
eseidel committed
831 832 833
        else
            uri = m_defaultNamespaceURI;
    }
kocienda's avatar
kocienda committed
834

darin's avatar
darin committed
835
    ExceptionCode ec = 0;
andersca's avatar
andersca committed
836 837
    QualifiedName qName(prefix, localName, uri);
    RefPtr<Element> newElement = m_doc->createElement(qName, true, ec);
darin's avatar
darin committed
838 839
    if (!newElement) {
        stopParsing();
darin's avatar
darin committed
840
        return;
darin's avatar
darin committed
841
    }
eseidel's avatar
eseidel committed
842
    
darin's avatar
darin committed
843 844
    handleElementNamespaces(newElement.get(), libxmlNamespaces, nb_namespaces, ec);
    if (ec) {
darin's avatar
darin committed
845
        stopParsing();
eseidel's avatar
eseidel committed
846
        return;
darin's avatar
darin committed
847
    }
848

darin@apple.com's avatar
darin@apple.com committed
849 850
    ScriptController* jsProxy = m_doc->frame() ? m_doc->frame()->script() : 0;
    if (jsProxy && m_doc->frame()->script()->isEnabled())
851 852
        jsProxy->setEventHandlerLineno(lineNumber());

darin's avatar
darin committed
853 854
    handleElementAttributes(newElement.get(), libxmlAttributes, nb_attributes, ec);
    if (ec) {
darin's avatar
darin committed
855
        stopParsing();
eseidel's avatar
eseidel committed
856
        return;
darin's avatar
darin committed
857
    }
858

859 860 861
    if (jsProxy)
        jsProxy->setEventHandlerLineno(0);

862 863
    newElement->beginParsingChildren();

864
    if (newElement->hasTagName(scriptTag))
ap's avatar
ap committed
865
        static_cast<HTMLScriptElement*>(newElement.get())->setCreatedByParser(true);
bdakin's avatar
bdakin committed
866 867 868 869 870 871
    else if (newElement->hasTagName(HTMLNames::styleTag))
        static_cast<HTMLStyleElement*>(newElement.get())->setCreatedByParser(true);
#if ENABLE(SVG)
    else if (newElement->hasTagName(SVGNames::styleTag))
        static_cast<SVGStyleElement*>(newElement.get())->setCreatedByParser(true);
#endif
872
    
beidson's avatar
beidson committed
873
    if (newElement->hasTagName(HTMLNames::scriptTag)
mjs's avatar
mjs committed
874
#if ENABLE(SVG)
beidson's avatar
beidson committed
875 876 877
        || newElement->hasTagName(SVGNames::scriptTag)
#endif
        )
878 879
        m_scriptStartLine = lineNumber();
    
darin's avatar
darin committed
880 881
    if (!m_currentNode->addChild(newElement.get())) {
        stopParsing();
darin's avatar
darin committed
882
        return;
kocienda's avatar
kocienda committed
883
    }
eseidel's avatar
eseidel committed
884
    
darin's avatar
darin committed
885
    setCurrentNode(newElement.get());
eseidel's avatar
eseidel committed
886
    if (m_view && !newElement->attached())
darin's avatar
darin committed
887
        newElement->attach();
kocienda's avatar
kocienda committed
888 889
}

eseidel's avatar
eseidel committed
890
void XMLTokenizer::endElementNs()
kocienda's avatar
kocienda committed
891
{
darin's avatar
darin committed
892
    if (m_parserStopped)
ggaren's avatar
ggaren committed
893
        return;
darin's avatar
darin committed
894

895 896 897 898 899
    if (m_parserPaused) {
        m_pendingCallbacks->appendEndElementNSCallback();
        return;
    }
    
darin's avatar
darin committed
900 901
    exitText();

ap's avatar
ap committed
902
    Node* n = m_currentNode;
darin's avatar
darin committed
903
    RefPtr<Node> parent = n->parentNode();
904
    n->finishParsingChildren();
andersca's avatar
andersca committed
905 906 907
    
    // don't load external scripts for standalone documents (for now)
    if (n->isElementNode() && m_view && (static_cast<Element*>(n)->hasTagName(scriptTag) 
mjs's avatar
mjs committed
908
#if ENABLE(SVG)
andersca's avatar
andersca committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922
                                         || static_cast<Element*>(n)->hasTagName(SVGNames::scriptTag)
#endif
                                         )) {

                                         
        ASSERT(!m_pendingScript);
        
        m_requestingScript = true;
        
        Element* scriptElement = static_cast<Element*>(n);        
        String scriptHref;
        
        if (static_cast<Element*>(n)->hasTagName(scriptTag))
            scriptHref = scriptElement->getAttribute(srcAttr);
mjs's avatar
mjs committed
923
#if ENABLE(SVG)
andersca's avatar
andersca committed
924 925 926 927 928 929
        else if (static_cast<Element*>(n)->hasTagName(SVGNames::scriptTag))
            scriptHref = scriptElement->getAttribute(XLinkNames::hrefAttr);
#endif
        
        if (!scriptHref.isEmpty()) {
            // we have a src attribute 
darin's avatar
darin committed
930
            const AtomicString& charset = scriptElement->getAttribute(charsetAttr);
andersca's avatar
andersca committed
931 932
            if ((m_pendingScript = m_doc->docLoader()->requestScript(scriptHref, charset))) {
                m_scriptElement = scriptElement;
hyatt@apple.com's avatar
hyatt@apple.com committed
933
                m_pendingScript->addClient(this);
andersca's avatar
andersca committed
934 935 936 937 938 939 940 941
                    
                // m_pendingScript will be 0 if script was already loaded and ref() executed it
                if (m_pendingScript)
                    pauseParsing();
            } else 
                m_scriptElement = 0;

        } else {
darin's avatar
darin committed
942
            String scriptCode = "";
ap's avatar
ap committed
943
            for (Node* child = scriptElement->firstChild(); child; child = child->nextSibling()) {
andersca's avatar
andersca committed
944
                if (child->isTextNode() || child->nodeType() == Node::CDATA_SECTION_NODE)
darin's avatar
darin committed
945
                    scriptCode += static_cast<CharacterData*>(child)->data();
andersca's avatar
andersca committed
946
            }
947
            m_view->frame()->loader()->executeScript(m_doc->url().string(), m_scriptStartLine, scriptCode);
andersca's avatar
andersca committed
948 949 950 951 952
        }
        
        m_requestingScript = false;
    }

darin's avatar
darin committed
953
    setCurrentNode(parent.get());
kocienda's avatar
kocienda committed
954 955
}

ap's avatar
ap committed
956
void XMLTokenizer::characters(const xmlChar* s, int len)
kocienda's avatar
kocienda committed
957
{
darin's avatar
darin committed
958
    if (m_parserStopped)
ggaren's avatar
ggaren committed
959
        return;
960
    
961 962 963 964 965
    if (m_parserPaused) {
        m_pendingCallbacks->appendCharactersCallback(s, len);
        return;
    }
    
966 967
    if (m_currentNode->isTextNode() || enterText())
        m_bufferedText.append(s, len);
darin's avatar
darin committed
968 969
}

ap's avatar
ap committed
970
void XMLTokenizer::error(ErrorType type, const char* message, va_list args)
971 972 973 974
{
    if (m_parserStopped)
        return;

weinig's avatar
weinig committed
975
#if PLATFORM(WIN_OS)
976 977 978
    char m[1024];
    vsnprintf(m, sizeof(m) - 1, message, args);
#else
ap's avatar
ap committed
979
    char* m;
980 981 982 983 984 985 986 987
    vasprintf(&m, message, args);
#endif
    
    if (m_parserPaused)
        m_pendingCallbacks->appendErrorCallback(type, m, lineNumber(), columnNumber());
    else
        handleError(type, m, lineNumber(), columnNumber());

weinig's avatar
weinig committed
988
#if !PLATFORM(WIN_OS)
989 990
    free(m);
#endif
991
}
kocienda's avatar
kocienda committed
992

ap's avatar
ap committed
993