schema.c 45.5 KB
Newer Older
1 2 3 4
/*
 * Schema cache implementation
 *
 * Copyright 2007 Huw Davies
5
 * Copyright 2010 Adam Martinson for CodeWeavers
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#define COBJMACROS

#include "config.h"

26
#include <assert.h>
27
#include <stdarg.h>
28 29 30 31 32 33 34 35 36
#ifdef HAVE_LIBXML2
# include <libxml/xmlerror.h>
# include <libxml/tree.h>
# include <libxml/xmlschemas.h>
# include <libxml/schemasInternals.h>
# include <libxml/hash.h>
# include <libxml/parser.h>
# include <libxml/parserInternals.h>
# include <libxml/xmlIO.h>
37
# include <libxml/xmlversion.h>
38
# include <libxml/xpath.h>
39 40
#endif

41 42 43 44
#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "ole2.h"
45
#include "msxml6.h"
46 47 48 49 50

#include "wine/debug.h"

#include "msxml_private.h"

51 52
#ifdef HAVE_LIBXML2

53 54
WINE_DEFAULT_DEBUG_CHANNEL(msxml);

55 56 57 58 59 60
/* We use a chained hashtable, which can hold any number of schemas
 * TODO: grow/shrink hashtable depending on load factor
 * TODO: implement read-only where appropriate
 */

/* This is just the number of buckets, should be prime */
61
#define DEFAULT_HASHTABLE_SIZE 17
62

63 64
xmlDocPtr XDR_to_XSD_doc(xmlDocPtr xdr_doc, xmlChar const* nsURI);

65 66 67 68
static const xmlChar XSD_schema[] = "schema";
static const xmlChar XSD_nsURI[] = "http://www.w3.org/2001/XMLSchema";
static const xmlChar XDR_schema[] = "Schema";
static const xmlChar XDR_nsURI[] = "urn:schemas-microsoft-com:xml-data";
69 70
static const xmlChar DT_nsURI[] = "urn:schemas-microsoft-com:datatypes";

71
static xmlChar *        datatypes_src;
72 73 74 75 76 77
static int              datatypes_len;
static HGLOBAL          datatypes_handle;
static HRSRC            datatypes_rsrc;
static xmlSchemaPtr     datatypes_schema;

static const WCHAR      emptyW[] = {0};
78

79
/* Supported types:
80 81 82 83
 * msxml3 - XDR only
 * msxml4 - XDR & XSD
 * msxml5 - XDR & XSD
 * mxsml6 - XSD only
84 85 86
 *
 * CacheType_NS is a special type used for read-only collection build with
 * IXMLDOMDocument2::namespaces()
87
 */
88 89 90 91 92 93
typedef enum  {
    CacheEntryType_Invalid,
    CacheEntryType_XDR,
    CacheEntryType_XSD,
    CacheEntryType_NS
} CacheEntryType;
94

95
typedef struct
96
{
97
    DispatchEx dispex;
98 99 100
    IXMLDOMSchemaCollection2 IXMLDOMSchemaCollection2_iface;
    LONG ref;

101
    MSXML_VERSION version;
102
    xmlHashTablePtr cache;
103 104 105
    xmlChar **uris;
    int allocated;
    int count;
106 107

    VARIANT_BOOL validateOnLoad;
108
    int read_only;
109 110
} schema_cache;

111
typedef struct
112
{
113
    CacheEntryType type;
114 115
    xmlSchemaPtr schema;
    xmlDocPtr doc;
116
    LONG ref;
117
} cache_entry;
118

119 120 121 122 123 124
static const tid_t schema_cache_se_tids[] = {
    IXMLDOMSchemaCollection_tid,
    IXMLDOMSchemaCollection2_tid,
    NULL_tid
};

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
/* datatypes lookup stuff
 * generated with help from gperf */
#define DT_MIN_STR_LEN 2
#define DT_MAX_STR_LEN 11
#define DT_MIN_HASH_VALUE 2
#define DT_MAX_HASH_VALUE 115

static const xmlChar DT_bin_base64[] = "bin.base64";
static const xmlChar DT_bin_hex[] = "bin.hex";
static const xmlChar DT_boolean[] = "boolean";
static const xmlChar DT_char[] = "char";
static const xmlChar DT_date[] = "date";
static const xmlChar DT_date_tz[] = "date.tz";
static const xmlChar DT_dateTime[] = "dateTime";
static const xmlChar DT_dateTime_tz[] = "dateTime.tz";
static const xmlChar DT_entity[] = "entity";
static const xmlChar DT_entities[] = "entities";
static const xmlChar DT_enumeration[] = "enumeration";
static const xmlChar DT_fixed_14_4[] = "fixed.14.4";
static const xmlChar DT_float[] = "float";
static const xmlChar DT_i1[] = "i1";
static const xmlChar DT_i2[] = "i2";
static const xmlChar DT_i4[] = "i4";
static const xmlChar DT_i8[] = "i8";
static const xmlChar DT_id[] = "id";
static const xmlChar DT_idref[] = "idref";
static const xmlChar DT_idrefs[] = "idrefs";
static const xmlChar DT_int[] = "int";
static const xmlChar DT_nmtoken[] = "nmtoken";
static const xmlChar DT_nmtokens[] = "nmtokens";
static const xmlChar DT_notation[] = "notation";
static const xmlChar DT_number[] = "number";
static const xmlChar DT_r4[] = "r4";
static const xmlChar DT_r8[] = "r8";
static const xmlChar DT_string[] = "string";
static const xmlChar DT_time[] = "time";
static const xmlChar DT_time_tz[] = "time.tz";
static const xmlChar DT_ui1[] = "ui1";
static const xmlChar DT_ui2[] = "ui2";
static const xmlChar DT_ui4[] = "ui4";
static const xmlChar DT_ui8[] = "ui8";
static const xmlChar DT_uri[] = "uri";
static const xmlChar DT_uuid[] = "uuid";

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 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
static const OLECHAR wDT_bin_base64[] = {'b','i','n','.','b','a','s','e','6','4',0};
static const OLECHAR wDT_bin_hex[] = {'b','i','n','.','h','e','x',0};
static const OLECHAR wDT_boolean[] = {'b','o','o','l','e','a','n',0};
static const OLECHAR wDT_char[] = {'c','h','a','r',0};
static const OLECHAR wDT_date[] = {'d','a','t','e',0};
static const OLECHAR wDT_date_tz[] = {'d','a','t','e','.','t','z',0};
static const OLECHAR wDT_dateTime[] = {'d','a','t','e','T','i','m','e',0};
static const OLECHAR wDT_dateTime_tz[] = {'d','a','t','e','T','i','m','e','.','t','z',0};
static const OLECHAR wDT_entity[] = {'e','n','t','i','t','y',0};
static const OLECHAR wDT_entities[] = {'e','n','t','i','t','i','e','s',0};
static const OLECHAR wDT_enumeration[] = {'e','n','u','m','e','r','a','t','i','o','n',0};
static const OLECHAR wDT_fixed_14_4[] = {'f','i','x','e','d','.','1','4','.','4',0};
static const OLECHAR wDT_float[] = {'f','l','o','a','t',0};
static const OLECHAR wDT_i1[] = {'i','1',0};
static const OLECHAR wDT_i2[] = {'i','2',0};
static const OLECHAR wDT_i4[] = {'i','4',0};
static const OLECHAR wDT_i8[] = {'i','8',0};
static const OLECHAR wDT_id[] = {'i','d',0};
static const OLECHAR wDT_idref[] = {'i','d','r','e','f',0};
static const OLECHAR wDT_idrefs[] = {'i','d','r','e','f','s',0};
static const OLECHAR wDT_int[] = {'i','n','t',0};
static const OLECHAR wDT_nmtoken[] = {'n','m','t','o','k','e','n',0};
static const OLECHAR wDT_nmtokens[] = {'n','m','t','o','k','e','n','s',0};
static const OLECHAR wDT_notation[] = {'n','o','t','a','t','i','o','n',0};
static const OLECHAR wDT_number[] = {'n','u','m','b','e','r',0};
static const OLECHAR wDT_r4[] = {'r','4',0};
static const OLECHAR wDT_r8[] = {'r','8',0};
static const OLECHAR wDT_string[] = {'s','t','r','i','n','g',0};
static const OLECHAR wDT_time[] = {'t','i','m','e',0};
static const OLECHAR wDT_time_tz[] = {'t','i','m','e','.','t','z',0};
static const OLECHAR wDT_ui1[] = {'u','i','1',0};
static const OLECHAR wDT_ui2[] = {'u','i','2',0};
static const OLECHAR wDT_ui4[] = {'u','i','4',0};
static const OLECHAR wDT_ui8[] = {'u','i','8',0};
static const OLECHAR wDT_uri[] = {'u','r','i',0};
static const OLECHAR wDT_uuid[] = {'u','u','i','d',0};

static const BYTE hash_assoc_values[] =
{
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116,  10, 116, 116,  55,
     45, 116,   5, 116,   0, 116,   0, 116, 116, 116,
    116, 116, 116, 116, 116,   5,   0,   0,  20,   0,
      0,  10,   0,   0, 116,   0,   0,   0,  15,   5,
    116, 116,  10,   0,   0,   0, 116, 116,   0,   0,
     10, 116, 116, 116, 116, 116, 116,   5,   0,   0,
     20,   0,   0,  10,   0,   0, 116,   0,   0,   0,
     15,   5, 116, 116,  10,   0,   0,   0, 116, 116,
      0,   0,  10, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116, 116, 116, 116, 116,
    116, 116, 116, 116, 116, 116
};

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
static void LIBXML2_LOG_CALLBACK parser_error(void* ctx, char const* msg, ...)
{
    va_list ap;
    va_start(ap, msg);
    LIBXML2_CALLBACK_ERR(Schema_parse, msg, ap);
    va_end(ap);
}

static void LIBXML2_LOG_CALLBACK parser_warning(void* ctx, char const* msg, ...)
{
    va_list ap;
    va_start(ap, msg);
    LIBXML2_CALLBACK_WARN(Schema_parse, msg, ap);
    va_end(ap);
}

#ifdef HAVE_XMLSCHEMASSETPARSERSTRUCTUREDERRORS
static void parser_serror(void* ctx, xmlErrorPtr err)
{
    LIBXML2_CALLBACK_SERROR(Schema_parse, err);
}
#endif

static inline xmlSchemaPtr Schema_parse(xmlSchemaParserCtxtPtr spctx)
{
    TRACE("(%p)\n", spctx);

    xmlSchemaSetParserErrors(spctx, parser_error, parser_warning, NULL);
#ifdef HAVE_XMLSCHEMASSETPARSERSTRUCTUREDERRORS
    xmlSchemaSetParserStructuredErrors(spctx, parser_serror, NULL);
#endif

    return xmlSchemaParse(spctx);
}

static void LIBXML2_LOG_CALLBACK validate_error(void* ctx, char const* msg, ...)
{
    va_list ap;
    va_start(ap, msg);
    LIBXML2_CALLBACK_ERR(Schema_validate_tree, msg, ap);
    va_end(ap);
}

static void LIBXML2_LOG_CALLBACK validate_warning(void* ctx, char const* msg, ...)
{
    va_list ap;
    va_start(ap, msg);
    LIBXML2_CALLBACK_WARN(Schema_validate_tree, msg, ap);
    va_end(ap);
}

#ifdef HAVE_XMLSCHEMASSETVALIDSTRUCTUREDERRORS
static void validate_serror(void* ctx, xmlErrorPtr err)
{
    LIBXML2_CALLBACK_SERROR(Schema_validate_tree, err);
}
#endif

294 295 296 297 298 299 300 301 302 303 304
static HRESULT schema_cache_get_item(IUnknown *iface, LONG index, VARIANT *item)
{
    V_VT(item) = VT_BSTR;
    return IXMLDOMSchemaCollection2_get_namespaceURI((IXMLDOMSchemaCollection2*)iface, index, &V_BSTR(item));
}

static const struct enumvariant_funcs schemacache_enumvariant = {
    schema_cache_get_item,
    NULL
};

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
static inline HRESULT Schema_validate_tree(xmlSchemaPtr schema, xmlNodePtr tree)
{
    xmlSchemaValidCtxtPtr svctx;
    int err;

    TRACE("(%p, %p)\n", schema, tree);
    /* TODO: if validateOnLoad property is false,
     *       we probably need to validate the schema here. */
    svctx = xmlSchemaNewValidCtxt(schema);
    xmlSchemaSetValidErrors(svctx, validate_error, validate_warning, NULL);
#ifdef HAVE_XMLSCHEMASSETVALIDSTRUCTUREDERRORS
    xmlSchemaSetValidStructuredErrors(svctx, validate_serror, NULL);
#endif

    if (tree->type == XML_DOCUMENT_NODE)
        err = xmlSchemaValidateDoc(svctx, (xmlDocPtr)tree);
    else
        err = xmlSchemaValidateOneElement(svctx, tree);

    xmlSchemaFreeValidCtxt(svctx);
    return err? S_FALSE : S_OK;
}

328
static DWORD dt_hash(xmlChar const* str, int len /* calculated if -1 */)
329 330 331 332 333 334
{
    DWORD hval = (len == -1)? xmlStrlen(str) : len;

    switch (hval)
    {
        default:
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
            hval += hash_assoc_values[str[10]];
            /*FALLTHROUGH*/
        case 10:
            hval += hash_assoc_values[str[9]];
            /*FALLTHROUGH*/
        case 9:
            hval += hash_assoc_values[str[8]];
            /*FALLTHROUGH*/
        case 8:
            hval += hash_assoc_values[str[7]];
            /*FALLTHROUGH*/
        case 7:
            hval += hash_assoc_values[str[6]];
            /*FALLTHROUGH*/
        case 6:
            hval += hash_assoc_values[str[5]];
            /*FALLTHROUGH*/
        case 5:
            hval += hash_assoc_values[str[4]];
            /*FALLTHROUGH*/
        case 4:
            hval += hash_assoc_values[str[3]];
            /*FALLTHROUGH*/
        case 3:
            hval += hash_assoc_values[str[2]];
            /*FALLTHROUGH*/
        case 2:
            hval += hash_assoc_values[str[1]];
            /*FALLTHROUGH*/
        case 1:
            hval += hash_assoc_values[str[0]];
            break;
    }
    return hval;
}

static DWORD dt_hash_bstr(OLECHAR const* bstr, int len /* calculated if -1 */)
{
    DWORD hval = (len == -1)? lstrlenW(bstr) : len;

    switch (hval)
    {
        default:
            hval += (bstr[10] & 0xFF00)? 116 : hash_assoc_values[bstr[10]];
379 380
            /*FALLTHROUGH*/
        case 10:
381
            hval += (bstr[9] & 0xFF00)? 116 : hash_assoc_values[bstr[9]];
382 383
            /*FALLTHROUGH*/
        case 9:
384
            hval += (bstr[8] & 0xFF00)? 116 : hash_assoc_values[bstr[8]];
385 386
            /*FALLTHROUGH*/
        case 8:
387
            hval += (bstr[7] & 0xFF00)? 116 : hash_assoc_values[bstr[7]];
388 389
            /*FALLTHROUGH*/
        case 7:
390
            hval += (bstr[6] & 0xFF00)? 116 : hash_assoc_values[bstr[6]];
391 392
            /*FALLTHROUGH*/
        case 6:
393
            hval += (bstr[5] & 0xFF00)? 116 : hash_assoc_values[bstr[5]];
394 395
            /*FALLTHROUGH*/
        case 5:
396
            hval += (bstr[4] & 0xFF00)? 116 : hash_assoc_values[bstr[4]];
397 398
            /*FALLTHROUGH*/
        case 4:
399
            hval += (bstr[3] & 0xFF00)? 116 : hash_assoc_values[bstr[3]];
400 401
            /*FALLTHROUGH*/
        case 3:
402
            hval += (bstr[2] & 0xFF00)? 116 : hash_assoc_values[bstr[2]];
403 404
            /*FALLTHROUGH*/
        case 2:
405
            hval += (bstr[1] & 0xFF00)? 116 : hash_assoc_values[bstr[1]];
406 407
            /*FALLTHROUGH*/
        case 1:
408
            hval += (bstr[0] & 0xFF00)? 116 : hash_assoc_values[bstr[0]];
409 410 411 412 413
            break;
    }
    return hval;
}

414
static const xmlChar *const DT_string_table[LAST_DT] =
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
{
    DT_bin_base64,
    DT_bin_hex,
    DT_boolean,
    DT_char,
    DT_date,
    DT_date_tz,
    DT_dateTime,
    DT_dateTime_tz,
    DT_entity,
    DT_entities,
    DT_enumeration,
    DT_fixed_14_4,
    DT_float,
    DT_i1,
    DT_i2,
    DT_i4,
    DT_i8,
    DT_id,
    DT_idref,
    DT_idrefs,
    DT_int,
    DT_nmtoken,
    DT_nmtokens,
    DT_notation,
    DT_number,
    DT_r4,
    DT_r8,
    DT_string,
    DT_time,
    DT_time_tz,
    DT_ui1,
    DT_ui2,
    DT_ui4,
    DT_ui8,
    DT_uri,
    DT_uuid
};

454
static const WCHAR *const DT_wstring_table[LAST_DT] =
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
{
    wDT_bin_base64,
    wDT_bin_hex,
    wDT_boolean,
    wDT_char,
    wDT_date,
    wDT_date_tz,
    wDT_dateTime,
    wDT_dateTime_tz,
    wDT_entity,
    wDT_entities,
    wDT_enumeration,
    wDT_fixed_14_4,
    wDT_float,
    wDT_i1,
    wDT_i2,
    wDT_i4,
    wDT_i8,
    wDT_id,
    wDT_idref,
    wDT_idrefs,
    wDT_int,
    wDT_nmtoken,
    wDT_nmtokens,
    wDT_notation,
    wDT_number,
    wDT_r4,
    wDT_r8,
    wDT_string,
    wDT_time,
    wDT_time_tz,
    wDT_ui1,
    wDT_ui2,
    wDT_ui4,
    wDT_ui8,
    wDT_uri,
    wDT_uuid
};

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 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
static const XDR_DT DT_lookup_table[] =
{
    -1, -1,
    DT_I8,
    DT_UI8,
    DT_TIME,
    -1, -1,
    DT_I4,
    DT_UI4,
    -1, -1, -1,
    DT_R8,
    DT_URI,
    -1,
    DT_FLOAT,
    -1,
    DT_R4,
    DT_INT,
    DT_CHAR,
    -1,
    DT_ENTITY,
    DT_ID,
    DT_ENTITIES,
    DT_UUID,
    -1, -1,
    DT_TIME_TZ,
    -1,
    DT_DATE,
    -1,
    DT_NUMBER,
    DT_BIN_HEX,
    DT_DATETIME,
    -1,
    DT_IDREF,
    DT_IDREFS,
    DT_BOOLEAN,
    -1, -1, -1,
    DT_STRING,
    DT_NMTOKEN,
    DT_NMTOKENS,
    -1,
    DT_BIN_BASE64,
    -1,
    DT_I2,
    DT_UI2,
    -1, -1, -1,
    DT_DATE_TZ,
    DT_NOTATION,
    -1, -1,
    DT_DATETIME_TZ,
    DT_I1,
    DT_UI1,
    -1, -1,
    DT_ENUMERATION,
    -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1,
    DT_FIXED_14_4
};

556
XDR_DT str_to_dt(xmlChar const* str, int len /* calculated if -1 */)
557 558 559 560 561 562 563 564 565 566 567 568 569
{
    DWORD hash = dt_hash(str, len);
    XDR_DT dt = DT_INVALID;

    if (hash <= DT_MAX_HASH_VALUE)
        dt = DT_lookup_table[hash];

    if (dt != DT_INVALID && xmlStrcasecmp(str, DT_string_table[dt]) == 0)
        return dt;

    return DT_INVALID;
}

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
XDR_DT bstr_to_dt(OLECHAR const* bstr, int len /* calculated if -1 */)
{
    DWORD hash = dt_hash_bstr(bstr, len);
    XDR_DT dt = DT_INVALID;

    if (hash <= DT_MAX_HASH_VALUE)
        dt = DT_lookup_table[hash];

    if (dt != DT_INVALID && lstrcmpiW(bstr, DT_wstring_table[dt]) == 0)
        return dt;

    return DT_INVALID;
}

xmlChar const* dt_to_str(XDR_DT dt)
585 586 587 588 589 590 591
{
    if (dt == DT_INVALID)
        return NULL;

    return DT_string_table[dt];
}

592 593 594 595 596 597 598 599
OLECHAR const* dt_to_bstr(XDR_DT dt)
{
    if (dt == DT_INVALID)
        return NULL;

    return DT_wstring_table[dt];
}

600 601 602 603 604
const char* debugstr_dt(XDR_DT dt)
{
    return debugstr_a(dt != DT_INVALID ? (const char*)DT_string_table[dt] : NULL);
}

605 606 607 608 609
HRESULT dt_validate(XDR_DT dt, xmlChar const* content)
{
    xmlDocPtr tmp_doc;
    xmlNodePtr node;
    xmlNsPtr ns;
610 611
    HRESULT hr;

612
    TRACE("(dt:%s, %s)\n", debugstr_dt(dt), debugstr_a((char const*)content));
613

614 615 616 617 618
    if (!datatypes_schema)
    {
        xmlSchemaParserCtxtPtr spctx;
        assert(datatypes_src != NULL);
        spctx = xmlSchemaNewMemParserCtxt((char const*)datatypes_src, datatypes_len);
619
        datatypes_schema = Schema_parse(spctx);
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
        xmlSchemaFreeParserCtxt(spctx);
    }

    switch (dt)
    {
        case DT_INVALID:
            return E_FAIL;
        case DT_BIN_BASE64:
        case DT_BIN_HEX:
        case DT_BOOLEAN:
        case DT_CHAR:
        case DT_DATE:
        case DT_DATE_TZ:
        case DT_DATETIME:
        case DT_DATETIME_TZ:
        case DT_FIXED_14_4:
        case DT_FLOAT:
        case DT_I1:
        case DT_I2:
        case DT_I4:
        case DT_I8:
        case DT_INT:
        case DT_NMTOKEN:
        case DT_NMTOKENS:
        case DT_NUMBER:
        case DT_R4:
        case DT_R8:
        case DT_STRING:
        case DT_TIME:
        case DT_TIME_TZ:
        case DT_UI1:
        case DT_UI2:
        case DT_UI4:
        case DT_UI8:
        case DT_URI:
        case DT_UUID:
656 657 658 659 660 661 662 663 664
            if (!datatypes_schema)
            {
                ERR("failed to load schema for urn:schemas-microsoft-com:datatypes, "
                    "you're probably using an old version of libxml2: " LIBXML_DOTTED_VERSION "\n");

                /* Hopefully they don't need much in the way of XDR datatypes support... */
                return S_OK;
            }

665 666 667 668 669 670 671 672
            if (content && xmlStrlen(content))
            {
                tmp_doc = xmlNewDoc(NULL);
                node = xmlNewChild((xmlNodePtr)tmp_doc, NULL, dt_to_str(dt), content);
                ns = xmlNewNs(node, DT_nsURI, BAD_CAST "dt");
                xmlSetNs(node, ns);
                xmlDocSetRootElement(tmp_doc, node);

673
                hr = Schema_validate_tree(datatypes_schema, (xmlNodePtr)tmp_doc);
674 675 676 677
                xmlFreeDoc(tmp_doc);
            }
            else
            {   /* probably the node is being created manually and has no content yet */
678
                hr = S_OK;
679
            }
680
            return hr;
681
        default:
682
            FIXME("need to handle dt:%s\n", debugstr_dt(dt));
683 684 685 686
            return S_OK;
    }
}

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
static inline xmlChar const* get_node_nsURI(xmlNodePtr node)
{
    return (node->ns != NULL)? node->ns->href : NULL;
}

static inline cache_entry* get_entry(schema_cache* This, xmlChar const* nsURI)
{
    return (!nsURI)? xmlHashLookup(This->cache, BAD_CAST "") :
                     xmlHashLookup(This->cache, nsURI);
}

static inline xmlSchemaPtr get_node_schema(schema_cache* This, xmlNodePtr node)
{
    cache_entry* entry = get_entry(This, get_node_nsURI(node));
    return (!entry)? NULL : entry->schema;
}

704
static xmlExternalEntityLoader _external_entity_loader;
705 706 707 708 709 710

static xmlParserInputPtr external_entity_loader(const char *URL, const char *ID,
                                                xmlParserCtxtPtr ctxt)
{
    xmlParserInputPtr input;

711
    TRACE("(%s %s %p)\n", debugstr_a(URL), debugstr_a(ID), ctxt);
712 713 714 715

    assert(MSXML_hInstance != NULL);
    assert(datatypes_rsrc != NULL);
    assert(datatypes_handle != NULL);
716
    assert(datatypes_src != NULL);
717 718 719 720 721

    /* TODO: if the desired schema is in the cache, load it from there */
    if (lstrcmpA(URL, "urn:schemas-microsoft-com:datatypes") == 0)
    {
        TRACE("loading built-in schema for %s\n", URL);
722
        input = xmlNewStringInputStream(ctxt, datatypes_src);
723 724 725 726 727 728 729 730 731 732 733
    }
    else
    {
        input = _external_entity_loader(URL, ID, ctxt);
    }

    return input;
}

void schemasInit(void)
{
734
    xmlChar* buf;
735 736 737 738 739 740 741 742 743 744 745 746
    if (!(datatypes_rsrc = FindResourceA(MSXML_hInstance, "DATATYPES", "XML")))
    {
        FIXME("failed to find resource for %s\n", DT_nsURI);
        return;
    }

    if (!(datatypes_handle = LoadResource(MSXML_hInstance, datatypes_rsrc)))
    {
        FIXME("failed to load resource for %s\n", DT_nsURI);
        return;
    }
    buf = LockResource(datatypes_handle);
747
    datatypes_len = SizeofResource(MSXML_hInstance, datatypes_rsrc);
748 749 750

    /* Resource is loaded as raw data,
     * need a null-terminated string */
751 752 753 754
    while (buf[datatypes_len - 1] != '>') datatypes_len--;
    datatypes_src = HeapAlloc(GetProcessHeap(), 0, datatypes_len + 1);
    memcpy(datatypes_src, buf, datatypes_len);
    datatypes_src[datatypes_len] = 0;
755

756
    if (xmlGetExternalEntityLoader() != external_entity_loader)
757 758 759 760 761 762 763 764
    {
        _external_entity_loader = xmlGetExternalEntityLoader();
        xmlSetExternalEntityLoader(external_entity_loader);
    }
}

void schemasCleanup(void)
{
765
    xmlSchemaFree(datatypes_schema);
766
    HeapFree(GetProcessHeap(), 0, datatypes_src);
767 768 769
    xmlSetExternalEntityLoader(_external_entity_loader);
}

770
static LONG cache_entry_add_ref(cache_entry* entry)
771
{
772
    LONG ref = InterlockedIncrement(&entry->ref);
773
    TRACE("(%p)->(%d)\n", entry, ref);
774
    return ref;
775 776
}

777
static LONG cache_entry_release(cache_entry* entry)
778
{
779
    LONG ref = InterlockedDecrement(&entry->ref);
780
    TRACE("(%p)->(%d)\n", entry, ref);
781

782 783
    if (ref == 0)
    {
784
        if (entry->type == CacheEntryType_XSD)
785 786 787 788 789
        {
            xmldoc_release(entry->doc);
            entry->schema->doc = NULL;
            xmlSchemaFree(entry->schema);
        }
790
        else if (entry->type == CacheEntryType_XDR)
791 792
        {
            xmldoc_release(entry->doc);
793 794 795
            xmldoc_release(entry->schema->doc);
            entry->schema->doc = NULL;
            xmlSchemaFree(entry->schema);
796
        }
797 798

        heap_free(entry);
799 800 801
    }
    return ref;
}
802

803 804
static const struct IXMLDOMSchemaCollection2Vtbl XMLDOMSchemaCollection2Vtbl;

805
static inline schema_cache* impl_from_IXMLDOMSchemaCollection2(IXMLDOMSchemaCollection2* iface)
806
{
807
    return CONTAINING_RECORD(iface, schema_cache, IXMLDOMSchemaCollection2_iface);
808 809
}

810 811 812 813 814 815 816 817 818 819
static inline schema_cache* impl_from_IXMLDOMSchemaCollection(IXMLDOMSchemaCollection* iface)
{
    return CONTAINING_RECORD(iface, schema_cache, IXMLDOMSchemaCollection2_iface);
}

static inline schema_cache* unsafe_impl_from_IXMLDOMSchemaCollection(IXMLDOMSchemaCollection *iface)
{
    return iface->lpVtbl == (void*)&XMLDOMSchemaCollection2Vtbl ? impl_from_IXMLDOMSchemaCollection(iface) : NULL;
}

820
static inline CacheEntryType cache_type_from_xmlDocPtr(xmlDocPtr schema)
821
{
822
    xmlNodePtr root = NULL;
823 824 825 826 827 828 829 830
    if (schema)
        root = xmlDocGetRootElement(schema);
    if (root && root->ns)
    {

        if (xmlStrEqual(root->name, XDR_schema) &&
            xmlStrEqual(root->ns->href, XDR_nsURI))
        {
831
            return CacheEntryType_XDR;
832 833 834 835
        }
        else if (xmlStrEqual(root->name, XSD_schema) &&
                 xmlStrEqual(root->ns->href, XSD_nsURI))
        {
836
            return CacheEntryType_XSD;
837 838
        }
    }
839
    return CacheEntryType_Invalid;
840 841
}

842 843 844 845 846
static BOOL link_datatypes(xmlDocPtr schema)
{
    xmlNodePtr root, next, child;
    xmlNsPtr ns;

847
    assert(xmlGetExternalEntityLoader() == external_entity_loader);
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
    root = xmlDocGetRootElement(schema);
    if (!root)
        return FALSE;

    for (ns = root->nsDef; ns != NULL; ns = ns->next)
    {
        if (xmlStrEqual(ns->href, DT_nsURI))
            break;
    }

    if (!ns)
        return FALSE;

    next = xmlFirstElementChild(root);
    child = xmlNewChild(root, NULL, BAD_CAST "import", NULL);
    if (next) child = xmlAddPrevSibling(next, child);
    xmlSetProp(child, BAD_CAST "namespace", DT_nsURI);
    xmlSetProp(child, BAD_CAST "schemaLocation", DT_nsURI);

    return TRUE;
}

870
static cache_entry* cache_entry_from_xsd_doc(xmlDocPtr doc, xmlChar const* nsURI, MSXML_VERSION v)
871 872 873 874 875
{
    cache_entry* entry = heap_alloc(sizeof(cache_entry));
    xmlSchemaParserCtxtPtr spctx;
    xmlDocPtr new_doc = xmlCopyDoc(doc, 1);

876 877
    link_datatypes(new_doc);

878 879
    /* TODO: if the nsURI is different from the default xmlns or targetNamespace,
     *       do we need to do something special here? */
880
    entry->type = CacheEntryType_XSD;
881 882 883
    entry->ref = 0;
    spctx = xmlSchemaNewDocParserCtxt(new_doc);

884
    if ((entry->schema = Schema_parse(spctx)))
885
    {
886
        xmldoc_init(entry->schema->doc, v);
887 888 889 890 891 892 893 894 895 896 897 898 899 900
        entry->doc = entry->schema->doc;
        xmldoc_add_ref(entry->doc);
    }
    else
    {
        FIXME("failed to parse doc\n");
        xmlFreeDoc(new_doc);
        heap_free(entry);
        entry = NULL;
    }
    xmlSchemaFreeParserCtxt(spctx);
    return entry;
}

901
static cache_entry* cache_entry_from_xdr_doc(xmlDocPtr doc, xmlChar const* nsURI, MSXML_VERSION version)
902 903
{
    cache_entry* entry = heap_alloc(sizeof(cache_entry));
904 905
    xmlSchemaParserCtxtPtr spctx;
    xmlDocPtr new_doc = xmlCopyDoc(doc, 1), xsd_doc = XDR_to_XSD_doc(doc, nsURI);
906

907 908
    link_datatypes(xsd_doc);

909
    entry->type = CacheEntryType_XDR;
910
    entry->ref = 0;
911 912
    spctx = xmlSchemaNewDocParserCtxt(xsd_doc);

913
    if ((entry->schema = Schema_parse(spctx)))
914 915
    {
        entry->doc = new_doc;
916 917
        xmldoc_init(entry->schema->doc, version);
        xmldoc_init(entry->doc, version);
918 919 920 921 922 923 924 925 926 927 928 929
        xmldoc_add_ref(entry->doc);
        xmldoc_add_ref(entry->schema->doc);
    }
    else
    {
        FIXME("failed to parse doc\n");
        xmlFreeDoc(new_doc);
        xmlFreeDoc(xsd_doc);
        heap_free(entry);
        entry = NULL;
    }
    xmlSchemaFreeParserCtxt(spctx);
930 931 932 933

    return entry;
}

934
static cache_entry* cache_entry_from_url(VARIANT url, xmlChar const* nsURI, MSXML_VERSION version)
935 936 937 938
{
    cache_entry* entry;
    IXMLDOMDocument3* domdoc = NULL;
    xmlDocPtr doc = NULL;
939
    HRESULT hr = DOMDocument_create(version, (void**)&domdoc);
940
    VARIANT_BOOL b = VARIANT_FALSE;
941
    CacheEntryType type = CacheEntryType_Invalid;
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956

    if (hr != S_OK)
    {
        FIXME("failed to create domdoc\n");
        return NULL;
    }
    assert(domdoc != NULL);
    assert(V_VT(&url) == VT_BSTR);

    hr = IXMLDOMDocument3_load(domdoc, url, &b);
    if (hr != S_OK)
    {
        ERR("IXMLDOMDocument3_load() returned 0x%08x\n", hr);
        if (b != VARIANT_TRUE)
        {
957
            FIXME("Failed to load doc at %s\n", debugstr_w(V_BSTR(&url)));
958 959 960 961 962
            IXMLDOMDocument3_Release(domdoc);
            return NULL;
        }
    }
    doc = xmlNodePtr_from_domnode((IXMLDOMNode*)domdoc, XML_DOCUMENT_NODE)->doc;
963
    type = cache_type_from_xmlDocPtr(doc);
964 965 966

    switch (type)
    {
967
        case CacheEntryType_XSD:
968
            entry = cache_entry_from_xsd_doc(doc, nsURI, version);
969
            break;
970
        case CacheEntryType_XDR:
971
            entry = cache_entry_from_xdr_doc(doc, nsURI, version);
972
            break;
973
        default:
974 975 976 977 978 979 980 981 982
            entry = NULL;
            FIXME("invalid schema\n");
            break;
    }
    IXMLDOMDocument3_Release(domdoc);

    return entry;
}

983 984 985 986 987
static void cache_free(void* data, xmlChar* name /* ignored */)
{
    cache_entry_release((cache_entry*)data);
}

988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
/* returns index or -1 if not found */
static int cache_free_uri(schema_cache *cache, const xmlChar *uri)
{
    int i;

    for (i = 0; i < cache->count; i++)
        if (xmlStrEqual(cache->uris[i], uri))
        {
            heap_free(cache->uris[i]);
            return i;
        }

    return -1;
}

static void cache_add_entry(schema_cache *cache, const xmlChar *uri, cache_entry *entry)
{
    int i;

    /* meaning no entry found with this name */
    if (xmlHashRemoveEntry(cache->cache, uri, cache_free))
    {
        if (cache->count == cache->allocated)
        {
            cache->allocated *= 2;
            cache->uris = heap_realloc(cache->uris, cache->allocated*sizeof(xmlChar*));
        }
        i = cache->count++;
    }
    else
        i = cache_free_uri(cache, uri);

    cache->uris[i] = heap_strdupxmlChar(uri);
    xmlHashAddEntry(cache->cache, uri, entry);
}

static void cache_remove_entry(schema_cache *cache, const xmlChar *uri)
{
    /* adjust index if entry was really removed */
    if (xmlHashRemoveEntry(cache->cache, uri, cache_free) == 0)
    {
        int i = cache_free_uri(cache, uri);
        if (i == -1) return;
        /* shift array */
        if (i != --cache->count)
            memmove(&cache->uris[i], &cache->uris[i+1], (cache->count-i)*sizeof(xmlChar*));
    }
}

1037 1038 1039 1040 1041 1042 1043 1044 1045
/* This one adds all namespaces defined in document to a cache, without anything
   associated with uri obviously.
   Unfortunately namespace:: axis implementation in libxml2 differs from what we need,
   it uses additional node type to describe namespace definition attribute while
   in msxml it's expected to be a normal attribute - as a workaround document is
   queried at libxml2 level here. */
HRESULT cache_from_doc_ns(IXMLDOMSchemaCollection2 *iface, xmlnode *node)
{
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1046
    static const xmlChar query[] = "//*/namespace::*";
1047 1048 1049
    xmlXPathObjectPtr nodeset;
    xmlXPathContextPtr ctxt;

1050 1051
    This->read_only = 1;

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
    ctxt = xmlXPathNewContext(node->node->doc);

    nodeset = xmlXPathEvalExpression(query, ctxt);
    xmlXPathFreeContext(ctxt);

    if (nodeset)
    {
        int pos = 0, len = xmlXPathNodeSetGetLength(nodeset->nodesetval);

        while (pos < len)
        {
            xmlNodePtr node = xmlXPathNodeSetItem(nodeset->nodesetval, pos);
            if (node->type == XML_NAMESPACE_DECL)
            {
                static const xmlChar defns[] = "http://www.w3.org/XML/1998/namespace";
                xmlNsPtr ns = (xmlNsPtr)node;
                cache_entry *entry;

                /* filter out default uri */
                if (xmlStrEqual(ns->href, defns))
                {
                    pos++;
                    continue;
                }

                entry = heap_alloc(sizeof(cache_entry));
                entry->type = CacheEntryType_NS;
                entry->ref = 1;
                entry->schema = NULL;
                entry->doc = NULL;

1083
                cache_add_entry(This, ns->href, entry);
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
            }
            pos++;
        }

        xmlXPathFreeObject(nodeset);
    }

    return S_OK;
}

1094 1095
static HRESULT WINAPI schema_cache_QueryInterface(IXMLDOMSchemaCollection2* iface,
                                                  REFIID riid, void** ppvObject)
1096
{
1097
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1098 1099 1100 1101 1102

    TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppvObject);

    if ( IsEqualIID(riid, &IID_IUnknown) ||
         IsEqualIID(riid, &IID_IDispatch) ||
1103 1104
         IsEqualIID(riid, &IID_IXMLDOMSchemaCollection) ||
         IsEqualIID(riid, &IID_IXMLDOMSchemaCollection2) )
1105 1106 1107
    {
        *ppvObject = iface;
    }
1108 1109 1110 1111
    else if (dispex_query_interface(&This->dispex, riid, ppvObject))
    {
        return *ppvObject ? S_OK : E_NOINTERFACE;
    }
1112 1113 1114 1115
    else if(IsEqualGUID( riid, &IID_ISupportErrorInfo ))
    {
        return node_create_supporterrorinfo(schema_cache_se_tids, ppvObject);
    }
1116 1117 1118
    else
    {
        FIXME("interface %s not implemented\n", debugstr_guid(riid));
1119
        *ppvObject = NULL;
1120 1121 1122
        return E_NOINTERFACE;
    }

1123
    IXMLDOMSchemaCollection2_AddRef(iface);
1124 1125 1126 1127

    return S_OK;
}

1128
static ULONG WINAPI schema_cache_AddRef(IXMLDOMSchemaCollection2* iface)
1129
{
1130
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1131
    LONG ref = InterlockedIncrement(&This->ref);
1132
    TRACE("(%p)->(%d)\n", This, ref);
1133 1134 1135
    return ref;
}

1136
static ULONG WINAPI schema_cache_Release(IXMLDOMSchemaCollection2* iface)
1137
{
1138
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1139
    LONG ref = InterlockedDecrement(&This->ref);
1140
    TRACE("(%p)->(%d)\n", This, ref);
1141

1142
    if (ref == 0)
1143
    {
1144 1145 1146 1147 1148
        int i;

        for (i = 0; i < This->count; i++)
            heap_free(This->uris[i]);
        heap_free(This->uris);
1149 1150
        xmlHashFree(This->cache, cache_free);
        heap_free(This);
1151 1152 1153 1154 1155
    }

    return ref;
}

1156 1157
static HRESULT WINAPI schema_cache_GetTypeInfoCount(IXMLDOMSchemaCollection2* iface,
                                                    UINT* pctinfo)
1158
{
1159
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1160
    return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
1161 1162
}

1163
static HRESULT WINAPI schema_cache_GetTypeInfo(IXMLDOMSchemaCollection2* iface,
1164
                                               UINT iTInfo, LCID lcid, ITypeInfo** ppTInfo)
1165
{
1166
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1167 1168
    return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface,
        iTInfo, lcid, ppTInfo);
1169 1170
}

1171 1172 1173
static HRESULT WINAPI schema_cache_GetIDsOfNames(IXMLDOMSchemaCollection2* iface,
                                                 REFIID riid, LPOLESTR* rgszNames,
                                                 UINT cNames, LCID lcid, DISPID* rgDispId)
1174
{
1175
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1176 1177
    return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface,
        riid, rgszNames, cNames, lcid, rgDispId);
1178 1179
}

1180 1181 1182 1183
static HRESULT WINAPI schema_cache_Invoke(IXMLDOMSchemaCollection2* iface,
                                          DISPID dispIdMember, REFIID riid, LCID lcid,
                                          WORD wFlags, DISPPARAMS* pDispParams,
                                          VARIANT* pVarResult, EXCEPINFO* pExcepInfo,
1184
                                          UINT* puArgErr)
1185
{
1186
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1187 1188
    return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface,
        dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
1189 1190
}

1191
static HRESULT WINAPI schema_cache_add(IXMLDOMSchemaCollection2* iface, BSTR uri, VARIANT var)
1192
{
1193
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1194 1195
    xmlChar* name;

1196
    TRACE("(%p)->(%s %s)\n", This, debugstr_w(uri), debugstr_variant(&var));
1197

1198 1199
    if (This->read_only) return E_FAIL;

1200 1201
    name = uri ? xmlchar_from_wchar(uri) : xmlchar_from_wchar(emptyW);

1202 1203 1204 1205
    switch (V_VT(&var))
    {
        case VT_NULL:
            {
1206
                cache_remove_entry(This, name);
1207 1208 1209 1210 1211
            }
            break;

        case VT_BSTR:
            {
1212
                cache_entry* entry = cache_entry_from_url(var, name, This->version);
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223

                if (entry)
                {
                    cache_entry_add_ref(entry);
                }
                else
                {
                    heap_free(name);
                    return E_FAIL;
                }

1224
                cache_add_entry(This, name, entry);
1225 1226 1227 1228 1229 1230 1231
            }
            break;

        case VT_DISPATCH:
            {
                xmlDocPtr doc = NULL;
                cache_entry* entry;
1232
                CacheEntryType type;
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
                IXMLDOMNode* domnode = NULL;
                IDispatch_QueryInterface(V_DISPATCH(&var), &IID_IXMLDOMNode, (void**)&domnode);

                if (domnode)
                    doc = xmlNodePtr_from_domnode(domnode, XML_DOCUMENT_NODE)->doc;

                if (!doc)
                {
                    IXMLDOMNode_Release(domnode);
                    heap_free(name);
                    return E_INVALIDARG;
                }
1245
                type = cache_type_from_xmlDocPtr(doc);
1246

1247
                if (type == CacheEntryType_XSD)
1248
                {
1249
                    entry = cache_entry_from_xsd_doc(doc, name, This->version);
1250
                }
1251
                else if (type == CacheEntryType_XDR)
1252
                {
1253
                    entry = cache_entry_from_xdr_doc(doc, name, This->version);
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
                }
                else
                {
                    WARN("invalid schema!\n");
                    entry = NULL;
                }

                IXMLDOMNode_Release(domnode);

                if (entry)
                {
                    cache_entry_add_ref(entry);
                }
                else
                {
                    heap_free(name);
                    return E_FAIL;
                }

1273
                cache_add_entry(This, name, entry);
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
            }
            break;

        default:
            {
                heap_free(name);
                return E_INVALIDARG;
            }
    }
    heap_free(name);
1284 1285 1286
    return S_OK;
}

1287 1288
static HRESULT WINAPI schema_cache_get(IXMLDOMSchemaCollection2* iface, BSTR uri,
                                       IXMLDOMNode** node)
1289
{
1290
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1291
    cache_entry* entry;
1292 1293
    xmlChar* name;

1294
    TRACE("(%p)->(%s %p)\n", This, debugstr_w(uri), node);
1295

1296 1297 1298 1299 1300
    if (This->version == MSXML6)
    {
        if (node) *node = NULL;
        return E_NOTIMPL;
    }
1301

1302 1303 1304
    if (!node)
        return E_POINTER;

1305 1306
    *node = NULL;

1307
    name = uri ? xmlchar_from_wchar(uri) : xmlchar_from_wchar(emptyW);
1308 1309 1310 1311
    entry = (cache_entry*) xmlHashLookup(This->cache, name);
    heap_free(name);

    /* TODO: this should be read-only */
1312
    if (entry && entry->doc)
1313
        return get_domdoc_from_xmldoc(entry->doc, (IXMLDOMDocument3**)node);
1314 1315

    return S_OK;
1316 1317
}

1318
static HRESULT WINAPI schema_cache_remove(IXMLDOMSchemaCollection2* iface, BSTR uri)
1319
{
1320
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1321 1322
    xmlChar* name;

1323
    TRACE("(%p)->(%s)\n", This, debugstr_w(uri));
1324

1325 1326
    if (This->version == MSXML6) return E_NOTIMPL;

1327
    name = uri ? xmlchar_from_wchar(uri) : xmlchar_from_wchar(emptyW);
1328
    cache_remove_entry(This, name);
1329 1330
    heap_free(name);
    return S_OK;
1331 1332
}

1333
static HRESULT WINAPI schema_cache_get_length(IXMLDOMSchemaCollection2* iface, LONG* length)
1334
{
1335
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1336 1337 1338 1339
    TRACE("(%p)->(%p)\n", This, length);

    if (!length)
        return E_POINTER;
1340

1341 1342
    *length = This->count;
    return S_OK;
1343 1344
}

1345
static HRESULT WINAPI schema_cache_get_namespaceURI(IXMLDOMSchemaCollection2* iface,
1346
                                                    LONG index, BSTR* uri)
1347
{
1348
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1349

1350 1351 1352
    TRACE("(%p)->(%i %p)\n", This, index, uri);

    if (!uri)
1353 1354
        return E_POINTER;

1355 1356 1357
    if (This->version == MSXML6)
        *uri = NULL;

1358
    if (index >= This->count)
1359 1360
        return E_FAIL;

1361
    *uri = bstr_from_xmlChar(This->uris[index]);
1362
    return S_OK;
1363 1364
}

1365 1366 1367 1368 1369 1370 1371 1372
static void cache_copy(void* data, void* dest, xmlChar* name)
{
    schema_cache* This = (schema_cache*) dest;
    cache_entry* entry = (cache_entry*) data;

    if (xmlHashLookup(This->cache, name) == NULL)
    {
        cache_entry_add_ref(entry);
1373
        cache_add_entry(This, name, entry);
1374 1375 1376
    }
}

1377
static HRESULT WINAPI schema_cache_addCollection(IXMLDOMSchemaCollection2* iface,
1378
                                                 IXMLDOMSchemaCollection* collection)
1379
{
1380
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1381 1382 1383
    schema_cache* That;

    TRACE("(%p)->(%p)\n", This, collection);
1384

1385
    if (!collection)
1386 1387
        return E_POINTER;

1388 1389 1390 1391 1392 1393 1394
    That = unsafe_impl_from_IXMLDOMSchemaCollection(collection);
    if (!That)
    {
        ERR("external collection implementation\n");
        return E_FAIL;
    }

1395 1396 1397 1398
    /* TODO: detect errors while copying & return E_FAIL */
    xmlHashScan(That->cache, cache_copy, This);

    return S_OK;
1399 1400
}

1401
static HRESULT WINAPI schema_cache_get__newEnum(IXMLDOMSchemaCollection2* iface, IUnknown** enumv)
1402
{
1403
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1404 1405
    TRACE("(%p)->(%p)\n", This, enumv);
    return create_enumvariant((IUnknown*)iface, TRUE, &schemacache_enumvariant, (IEnumVARIANT**)enumv);
1406 1407
}

1408 1409
static HRESULT WINAPI schema_cache_validate(IXMLDOMSchemaCollection2* iface)
{
1410 1411
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
    FIXME("(%p): stub\n", This);
1412 1413 1414 1415
    return E_NOTIMPL;
}

static HRESULT WINAPI schema_cache_put_validateOnLoad(IXMLDOMSchemaCollection2* iface,
1416
                                                      VARIANT_BOOL value)
1417
{
1418 1419
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
    FIXME("(%p)->(%d): stub\n", This, value);
1420 1421 1422 1423 1424

    This->validateOnLoad = value;
    /* it's ok to disable it, cause we don't validate on load anyway */
    if (value == VARIANT_FALSE) return S_OK;

1425 1426 1427 1428
    return E_NOTIMPL;
}

static HRESULT WINAPI schema_cache_get_validateOnLoad(IXMLDOMSchemaCollection2* iface,
1429
                                                      VARIANT_BOOL* value)
1430
{
1431
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1432 1433 1434 1435 1436 1437
    TRACE("(%p)->(%p)\n", This, value);

    if (!value) return E_POINTER;
    *value = This->validateOnLoad;

    return S_OK;
1438 1439 1440 1441 1442
}

static HRESULT WINAPI schema_cache_getSchema(IXMLDOMSchemaCollection2* iface,
                                             BSTR namespaceURI, ISchema** schema)
{
1443 1444
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
    FIXME("(%p)->(%s %p): stub\n", This, debugstr_w(namespaceURI), schema);
1445 1446 1447 1448 1449 1450 1451 1452
    if (schema)
        *schema = NULL;
    return E_NOTIMPL;
}

static HRESULT WINAPI schema_cache_getDeclaration(IXMLDOMSchemaCollection2* iface,
                                                  IXMLDOMNode* node, ISchemaItem** item)
{
1453 1454
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
    FIXME("(%p)->(%p %p): stub\n", This, node, item);
1455 1456 1457 1458 1459
    if (item)
        *item = NULL;
    return E_NOTIMPL;
}

1460
static const struct IXMLDOMSchemaCollection2Vtbl XMLDOMSchemaCollection2Vtbl =
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
{
    schema_cache_QueryInterface,
    schema_cache_AddRef,
    schema_cache_Release,
    schema_cache_GetTypeInfoCount,
    schema_cache_GetTypeInfo,
    schema_cache_GetIDsOfNames,
    schema_cache_Invoke,
    schema_cache_add,
    schema_cache_get,
    schema_cache_remove,
    schema_cache_get_length,
    schema_cache_get_namespaceURI,
    schema_cache_addCollection,
1475 1476 1477 1478 1479 1480
    schema_cache_get__newEnum,
    schema_cache_validate,
    schema_cache_put_validateOnLoad,
    schema_cache_get_validateOnLoad,
    schema_cache_getSchema,
    schema_cache_getDeclaration
1481 1482
};

1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
static xmlSchemaElementPtr lookup_schema_elemDecl(xmlSchemaPtr schema, xmlNodePtr node)
{
    xmlSchemaElementPtr decl = NULL;
    xmlChar const* nsURI = get_node_nsURI(node);

    TRACE("(%p, %p)\n", schema, node);

    if (xmlStrEqual(nsURI, schema->targetNamespace))
        decl = xmlHashLookup(schema->elemDecl, node->name);

    if (!decl && xmlHashSize(schema->schemasImports) > 1)
    {
        FIXME("declaration not found in main schema - need to check schema imports!\n");
        /*xmlSchemaImportPtr import;
        if (nsURI == NULL)
            import = xmlHashLookup(schema->schemasImports, XML_SCHEMAS_NO_NAMESPACE);
        else
            import = xmlHashLookup(schema->schemasImports, node->ns->href);

        if (import != NULL)
            decl = xmlHashLookup(import->schema->elemDecl, node->name);*/
    }

    return decl;
}

static inline xmlNodePtr lookup_schema_element(xmlSchemaPtr schema, xmlNodePtr node)
{
    xmlSchemaElementPtr decl = lookup_schema_elemDecl(schema, node);
    while (decl != NULL && decl->refDecl != NULL)
        decl = decl->refDecl;
    return (decl != NULL)? decl->node : NULL;
}

1517 1518 1519
HRESULT SchemaCache_validate_tree(IXMLDOMSchemaCollection2* iface, xmlNodePtr tree)
{
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
1520 1521
    xmlSchemaPtr schema;

1522 1523 1524 1525 1526
    TRACE("(%p, %p)\n", This, tree);

    if (!tree)
        return E_POINTER;

1527 1528
    if (tree->type == XML_DOCUMENT_NODE)
        tree = xmlDocGetRootElement(tree->doc);
1529

1530
    schema = get_node_schema(This, tree);
1531 1532
    /* TODO: if the ns is not in the cache, and it's a URL,
     *       do we try to load from that? */
1533
    if (schema)
1534
        return Schema_validate_tree(schema, tree);
1535 1536
    else
        WARN("no schema found for xmlns=%s\n", get_node_nsURI(tree));
1537 1538 1539 1540

    return E_FAIL;
}

1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
XDR_DT SchemaCache_get_node_dt(IXMLDOMSchemaCollection2* iface, xmlNodePtr node)
{
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
    xmlSchemaPtr schema = get_node_schema(This, node);
    XDR_DT dt = DT_INVALID;

    TRACE("(%p, %p)\n", This, node);

    if (node->ns && xmlStrEqual(node->ns->href, DT_nsURI))
    {
1551
        dt = str_to_dt(node->name, -1);
1552 1553 1554 1555 1556 1557 1558 1559 1560
    }
    else if (schema)
    {
        xmlChar* str;
        xmlNodePtr schema_node = lookup_schema_element(schema, node);

        str = xmlGetNsProp(schema_node, BAD_CAST "dt", DT_nsURI);
        if (str)
        {
1561
            dt = str_to_dt(str, -1);
1562 1563 1564 1565 1566 1567 1568
            xmlFree(str);
        }
    }

    return dt;
}

1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
static const tid_t schemacache_iface_tids[] = {
    IXMLDOMSchemaCollection2_tid,
    0
};

static dispex_static_data_t schemacache_dispex = {
    NULL,
    IXMLDOMSchemaCollection2_tid,
    NULL,
    schemacache_iface_tids
};

1581
HRESULT SchemaCache_create(MSXML_VERSION version, void** obj)
1582
{
1583 1584
    schema_cache* This = heap_alloc(sizeof(schema_cache));
    if (!This)
1585 1586
        return E_OUTOFMEMORY;

1587
    TRACE("(%d %p)\n", version, obj);
1588

1589
    This->IXMLDOMSchemaCollection2_iface.lpVtbl = &XMLDOMSchemaCollection2Vtbl;
1590
    This->cache = xmlHashCreate(DEFAULT_HASHTABLE_SIZE);
1591 1592 1593
    This->allocated = 10;
    This->count = 0;
    This->uris = heap_alloc(This->allocated*sizeof(xmlChar*));
1594
    This->ref = 1;
1595
    This->version = version;
1596
    This->validateOnLoad = VARIANT_TRUE;
1597
    This->read_only = 0;
1598
    init_dispex(&This->dispex, (IUnknown*)&This->IXMLDOMSchemaCollection2_iface, &schemacache_dispex);
1599

1600
    *obj = &This->IXMLDOMSchemaCollection2_iface;
1601 1602
    return S_OK;
}
1603 1604 1605

#else

1606
HRESULT SchemaCache_create(MSXML_VERSION version, void** obj)
1607 1608 1609 1610 1611 1612 1613
{
    MESSAGE("This program tried to use a SchemaCache object, but\n"
            "libxml2 support was not present at compile time.\n");
    return E_NOTIMPL;
}

#endif